1 // Copyright 2013 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "src/hydrogen.h"
10 #include "src/allocation-site-scopes.h"
11 #include "src/codegen.h"
12 #include "src/full-codegen.h"
13 #include "src/hashmap.h"
14 #include "src/hydrogen-bce.h"
15 #include "src/hydrogen-bch.h"
16 #include "src/hydrogen-canonicalize.h"
17 #include "src/hydrogen-check-elimination.h"
18 #include "src/hydrogen-dce.h"
19 #include "src/hydrogen-dehoist.h"
20 #include "src/hydrogen-environment-liveness.h"
21 #include "src/hydrogen-escape-analysis.h"
22 #include "src/hydrogen-infer-representation.h"
23 #include "src/hydrogen-infer-types.h"
24 #include "src/hydrogen-load-elimination.h"
25 #include "src/hydrogen-gvn.h"
26 #include "src/hydrogen-mark-deoptimize.h"
27 #include "src/hydrogen-mark-unreachable.h"
28 #include "src/hydrogen-osr.h"
29 #include "src/hydrogen-range-analysis.h"
30 #include "src/hydrogen-redundant-phi.h"
31 #include "src/hydrogen-removable-simulates.h"
32 #include "src/hydrogen-representation-changes.h"
33 #include "src/hydrogen-sce.h"
34 #include "src/hydrogen-store-elimination.h"
35 #include "src/hydrogen-uint32-analysis.h"
36 #include "src/lithium-allocator.h"
37 #include "src/parser.h"
38 #include "src/runtime.h"
39 #include "src/scopeinfo.h"
40 #include "src/scopes.h"
41 #include "src/stub-cache.h"
42 #include "src/typing.h"
44 #if V8_TARGET_ARCH_IA32
45 #include "src/ia32/lithium-codegen-ia32.h"
46 #elif V8_TARGET_ARCH_X64
47 #include "src/x64/lithium-codegen-x64.h"
48 #elif V8_TARGET_ARCH_ARM64
49 #include "src/arm64/lithium-codegen-arm64.h"
50 #elif V8_TARGET_ARCH_ARM
51 #include "src/arm/lithium-codegen-arm.h"
52 #elif V8_TARGET_ARCH_MIPS
53 #include "src/mips/lithium-codegen-mips.h"
54 #elif V8_TARGET_ARCH_X87
55 #include "src/x87/lithium-codegen-x87.h"
57 #error Unsupported target architecture.
63 HBasicBlock::HBasicBlock(HGraph* graph)
64 : block_id_(graph->GetNextBlockID()),
66 phis_(4, graph->zone()),
70 loop_information_(NULL),
71 predecessors_(2, graph->zone()),
73 dominated_blocks_(4, graph->zone()),
74 last_environment_(NULL),
76 first_instruction_index_(-1),
77 last_instruction_index_(-1),
78 deleted_phis_(4, graph->zone()),
79 parent_loop_header_(NULL),
80 inlined_entry_block_(NULL),
81 is_inline_return_target_(false),
83 dominates_loop_successors_(false),
85 is_ordered_(false) { }
88 Isolate* HBasicBlock::isolate() const {
89 return graph_->isolate();
93 void HBasicBlock::MarkUnreachable() {
94 is_reachable_ = false;
98 void HBasicBlock::AttachLoopInformation() {
99 ASSERT(!IsLoopHeader());
100 loop_information_ = new(zone()) HLoopInformation(this, zone());
104 void HBasicBlock::DetachLoopInformation() {
105 ASSERT(IsLoopHeader());
106 loop_information_ = NULL;
110 void HBasicBlock::AddPhi(HPhi* phi) {
111 ASSERT(!IsStartBlock());
112 phis_.Add(phi, zone());
117 void HBasicBlock::RemovePhi(HPhi* phi) {
118 ASSERT(phi->block() == this);
119 ASSERT(phis_.Contains(phi));
121 phis_.RemoveElement(phi);
126 void HBasicBlock::AddInstruction(HInstruction* instr,
127 HSourcePosition position) {
128 ASSERT(!IsStartBlock() || !IsFinished());
129 ASSERT(!instr->IsLinked());
130 ASSERT(!IsFinished());
132 if (!position.IsUnknown()) {
133 instr->set_position(position);
135 if (first_ == NULL) {
136 ASSERT(last_environment() != NULL);
137 ASSERT(!last_environment()->ast_id().IsNone());
138 HBlockEntry* entry = new(zone()) HBlockEntry();
139 entry->InitializeAsFirst(this);
140 if (!position.IsUnknown()) {
141 entry->set_position(position);
143 ASSERT(!FLAG_hydrogen_track_positions ||
144 !graph()->info()->IsOptimizing());
146 first_ = last_ = entry;
148 instr->InsertAfter(last_);
152 HPhi* HBasicBlock::AddNewPhi(int merged_index) {
153 if (graph()->IsInsideNoSideEffectsScope()) {
154 merged_index = HPhi::kInvalidMergedIndex;
156 HPhi* phi = new(zone()) HPhi(merged_index, zone());
162 HSimulate* HBasicBlock::CreateSimulate(BailoutId ast_id,
163 RemovableSimulate removable) {
164 ASSERT(HasEnvironment());
165 HEnvironment* environment = last_environment();
166 ASSERT(ast_id.IsNone() ||
167 ast_id == BailoutId::StubEntry() ||
168 environment->closure()->shared()->VerifyBailoutId(ast_id));
170 int push_count = environment->push_count();
171 int pop_count = environment->pop_count();
174 new(zone()) HSimulate(ast_id, pop_count, zone(), removable);
176 instr->set_closure(environment->closure());
178 // Order of pushed values: newest (top of stack) first. This allows
179 // HSimulate::MergeWith() to easily append additional pushed values
180 // that are older (from further down the stack).
181 for (int i = 0; i < push_count; ++i) {
182 instr->AddPushedValue(environment->ExpressionStackAt(i));
184 for (GrowableBitVector::Iterator it(environment->assigned_variables(),
188 int index = it.Current();
189 instr->AddAssignedValue(index, environment->Lookup(index));
191 environment->ClearHistory();
196 void HBasicBlock::Finish(HControlInstruction* end, HSourcePosition position) {
197 ASSERT(!IsFinished());
198 AddInstruction(end, position);
200 for (HSuccessorIterator it(end); !it.Done(); it.Advance()) {
201 it.Current()->RegisterPredecessor(this);
206 void HBasicBlock::Goto(HBasicBlock* block,
207 HSourcePosition position,
208 FunctionState* state,
210 bool drop_extra = state != NULL &&
211 state->inlining_kind() == NORMAL_RETURN;
213 if (block->IsInlineReturnTarget()) {
214 HEnvironment* env = last_environment();
215 int argument_count = env->arguments_environment()->parameter_count();
216 AddInstruction(new(zone())
217 HLeaveInlined(state->entry(), argument_count),
219 UpdateEnvironment(last_environment()->DiscardInlined(drop_extra));
222 if (add_simulate) AddNewSimulate(BailoutId::None(), position);
223 HGoto* instr = new(zone()) HGoto(block);
224 Finish(instr, position);
228 void HBasicBlock::AddLeaveInlined(HValue* return_value,
229 FunctionState* state,
230 HSourcePosition position) {
231 HBasicBlock* target = state->function_return();
232 bool drop_extra = state->inlining_kind() == NORMAL_RETURN;
234 ASSERT(target->IsInlineReturnTarget());
235 ASSERT(return_value != NULL);
236 HEnvironment* env = last_environment();
237 int argument_count = env->arguments_environment()->parameter_count();
238 AddInstruction(new(zone()) HLeaveInlined(state->entry(), argument_count),
240 UpdateEnvironment(last_environment()->DiscardInlined(drop_extra));
241 last_environment()->Push(return_value);
242 AddNewSimulate(BailoutId::None(), position);
243 HGoto* instr = new(zone()) HGoto(target);
244 Finish(instr, position);
248 void HBasicBlock::SetInitialEnvironment(HEnvironment* env) {
249 ASSERT(!HasEnvironment());
250 ASSERT(first() == NULL);
251 UpdateEnvironment(env);
255 void HBasicBlock::UpdateEnvironment(HEnvironment* env) {
256 last_environment_ = env;
257 graph()->update_maximum_environment_size(env->first_expression_index());
261 void HBasicBlock::SetJoinId(BailoutId ast_id) {
262 int length = predecessors_.length();
264 for (int i = 0; i < length; i++) {
265 HBasicBlock* predecessor = predecessors_[i];
266 ASSERT(predecessor->end()->IsGoto());
267 HSimulate* simulate = HSimulate::cast(predecessor->end()->previous());
269 (predecessor->last_environment()->closure().is_null() ||
270 predecessor->last_environment()->closure()->shared()
271 ->VerifyBailoutId(ast_id)));
272 simulate->set_ast_id(ast_id);
273 predecessor->last_environment()->set_ast_id(ast_id);
278 bool HBasicBlock::Dominates(HBasicBlock* other) const {
279 HBasicBlock* current = other->dominator();
280 while (current != NULL) {
281 if (current == this) return true;
282 current = current->dominator();
288 bool HBasicBlock::EqualToOrDominates(HBasicBlock* other) const {
289 if (this == other) return true;
290 return Dominates(other);
294 int HBasicBlock::LoopNestingDepth() const {
295 const HBasicBlock* current = this;
296 int result = (current->IsLoopHeader()) ? 1 : 0;
297 while (current->parent_loop_header() != NULL) {
298 current = current->parent_loop_header();
305 void HBasicBlock::PostProcessLoopHeader(IterationStatement* stmt) {
306 ASSERT(IsLoopHeader());
308 SetJoinId(stmt->EntryId());
309 if (predecessors()->length() == 1) {
310 // This is a degenerated loop.
311 DetachLoopInformation();
315 // Only the first entry into the loop is from outside the loop. All other
316 // entries must be back edges.
317 for (int i = 1; i < predecessors()->length(); ++i) {
318 loop_information()->RegisterBackEdge(predecessors()->at(i));
323 void HBasicBlock::MarkSuccEdgeUnreachable(int succ) {
324 ASSERT(IsFinished());
325 HBasicBlock* succ_block = end()->SuccessorAt(succ);
327 ASSERT(succ_block->predecessors()->length() == 1);
328 succ_block->MarkUnreachable();
332 void HBasicBlock::RegisterPredecessor(HBasicBlock* pred) {
333 if (HasPredecessor()) {
334 // Only loop header blocks can have a predecessor added after
335 // instructions have been added to the block (they have phis for all
336 // values in the environment, these phis may be eliminated later).
337 ASSERT(IsLoopHeader() || first_ == NULL);
338 HEnvironment* incoming_env = pred->last_environment();
339 if (IsLoopHeader()) {
340 ASSERT(phis()->length() == incoming_env->length());
341 for (int i = 0; i < phis_.length(); ++i) {
342 phis_[i]->AddInput(incoming_env->values()->at(i));
345 last_environment()->AddIncomingEdge(this, pred->last_environment());
347 } else if (!HasEnvironment() && !IsFinished()) {
348 ASSERT(!IsLoopHeader());
349 SetInitialEnvironment(pred->last_environment()->Copy());
352 predecessors_.Add(pred, zone());
356 void HBasicBlock::AddDominatedBlock(HBasicBlock* block) {
357 ASSERT(!dominated_blocks_.Contains(block));
358 // Keep the list of dominated blocks sorted such that if there is two
359 // succeeding block in this list, the predecessor is before the successor.
361 while (index < dominated_blocks_.length() &&
362 dominated_blocks_[index]->block_id() < block->block_id()) {
365 dominated_blocks_.InsertAt(index, block, zone());
369 void HBasicBlock::AssignCommonDominator(HBasicBlock* other) {
370 if (dominator_ == NULL) {
372 other->AddDominatedBlock(this);
373 } else if (other->dominator() != NULL) {
374 HBasicBlock* first = dominator_;
375 HBasicBlock* second = other;
377 while (first != second) {
378 if (first->block_id() > second->block_id()) {
379 first = first->dominator();
381 second = second->dominator();
383 ASSERT(first != NULL && second != NULL);
386 if (dominator_ != first) {
387 ASSERT(dominator_->dominated_blocks_.Contains(this));
388 dominator_->dominated_blocks_.RemoveElement(this);
390 first->AddDominatedBlock(this);
396 void HBasicBlock::AssignLoopSuccessorDominators() {
397 // Mark blocks that dominate all subsequent reachable blocks inside their
398 // loop. Exploit the fact that blocks are sorted in reverse post order. When
399 // the loop is visited in increasing block id order, if the number of
400 // non-loop-exiting successor edges at the dominator_candidate block doesn't
401 // exceed the number of previously encountered predecessor edges, there is no
402 // path from the loop header to any block with higher id that doesn't go
403 // through the dominator_candidate block. In this case, the
404 // dominator_candidate block is guaranteed to dominate all blocks reachable
405 // from it with higher ids.
406 HBasicBlock* last = loop_information()->GetLastBackEdge();
407 int outstanding_successors = 1; // one edge from the pre-header
408 // Header always dominates everything.
409 MarkAsLoopSuccessorDominator();
410 for (int j = block_id(); j <= last->block_id(); ++j) {
411 HBasicBlock* dominator_candidate = graph_->blocks()->at(j);
412 for (HPredecessorIterator it(dominator_candidate); !it.Done();
414 HBasicBlock* predecessor = it.Current();
415 // Don't count back edges.
416 if (predecessor->block_id() < dominator_candidate->block_id()) {
417 outstanding_successors--;
421 // If more successors than predecessors have been seen in the loop up to
422 // now, it's not possible to guarantee that the current block dominates
423 // all of the blocks with higher IDs. In this case, assume conservatively
424 // that those paths through loop that don't go through the current block
425 // contain all of the loop's dependencies. Also be careful to record
426 // dominator information about the current loop that's being processed,
427 // and not nested loops, which will be processed when
428 // AssignLoopSuccessorDominators gets called on their header.
429 ASSERT(outstanding_successors >= 0);
430 HBasicBlock* parent_loop_header = dominator_candidate->parent_loop_header();
431 if (outstanding_successors == 0 &&
432 (parent_loop_header == this && !dominator_candidate->IsLoopHeader())) {
433 dominator_candidate->MarkAsLoopSuccessorDominator();
435 HControlInstruction* end = dominator_candidate->end();
436 for (HSuccessorIterator it(end); !it.Done(); it.Advance()) {
437 HBasicBlock* successor = it.Current();
438 // Only count successors that remain inside the loop and don't loop back
440 if (successor->block_id() > dominator_candidate->block_id() &&
441 successor->block_id() <= last->block_id()) {
442 // Backwards edges must land on loop headers.
443 ASSERT(successor->block_id() > dominator_candidate->block_id() ||
444 successor->IsLoopHeader());
445 outstanding_successors++;
452 int HBasicBlock::PredecessorIndexOf(HBasicBlock* predecessor) const {
453 for (int i = 0; i < predecessors_.length(); ++i) {
454 if (predecessors_[i] == predecessor) return i;
462 void HBasicBlock::Verify() {
463 // Check that every block is finished.
464 ASSERT(IsFinished());
465 ASSERT(block_id() >= 0);
467 // Check that the incoming edges are in edge split form.
468 if (predecessors_.length() > 1) {
469 for (int i = 0; i < predecessors_.length(); ++i) {
470 ASSERT(predecessors_[i]->end()->SecondSuccessor() == NULL);
477 void HLoopInformation::RegisterBackEdge(HBasicBlock* block) {
478 this->back_edges_.Add(block, block->zone());
483 HBasicBlock* HLoopInformation::GetLastBackEdge() const {
485 HBasicBlock* result = NULL;
486 for (int i = 0; i < back_edges_.length(); ++i) {
487 HBasicBlock* cur = back_edges_[i];
488 if (cur->block_id() > max_id) {
489 max_id = cur->block_id();
497 void HLoopInformation::AddBlock(HBasicBlock* block) {
498 if (block == loop_header()) return;
499 if (block->parent_loop_header() == loop_header()) return;
500 if (block->parent_loop_header() != NULL) {
501 AddBlock(block->parent_loop_header());
503 block->set_parent_loop_header(loop_header());
504 blocks_.Add(block, block->zone());
505 for (int i = 0; i < block->predecessors()->length(); ++i) {
506 AddBlock(block->predecessors()->at(i));
514 // Checks reachability of the blocks in this graph and stores a bit in
515 // the BitVector "reachable()" for every block that can be reached
516 // from the start block of the graph. If "dont_visit" is non-null, the given
517 // block is treated as if it would not be part of the graph. "visited_count()"
518 // returns the number of reachable blocks.
519 class ReachabilityAnalyzer BASE_EMBEDDED {
521 ReachabilityAnalyzer(HBasicBlock* entry_block,
523 HBasicBlock* dont_visit)
525 stack_(16, entry_block->zone()),
526 reachable_(block_count, entry_block->zone()),
527 dont_visit_(dont_visit) {
528 PushBlock(entry_block);
532 int visited_count() const { return visited_count_; }
533 const BitVector* reachable() const { return &reachable_; }
536 void PushBlock(HBasicBlock* block) {
537 if (block != NULL && block != dont_visit_ &&
538 !reachable_.Contains(block->block_id())) {
539 reachable_.Add(block->block_id());
540 stack_.Add(block, block->zone());
546 while (!stack_.is_empty()) {
547 HControlInstruction* end = stack_.RemoveLast()->end();
548 for (HSuccessorIterator it(end); !it.Done(); it.Advance()) {
549 PushBlock(it.Current());
555 ZoneList<HBasicBlock*> stack_;
556 BitVector reachable_;
557 HBasicBlock* dont_visit_;
561 void HGraph::Verify(bool do_full_verify) const {
562 Heap::RelocationLock relocation_lock(isolate()->heap());
563 AllowHandleDereference allow_deref;
564 AllowDeferredHandleDereference allow_deferred_deref;
565 for (int i = 0; i < blocks_.length(); i++) {
566 HBasicBlock* block = blocks_.at(i);
570 // Check that every block contains at least one node and that only the last
571 // node is a control instruction.
572 HInstruction* current = block->first();
573 ASSERT(current != NULL && current->IsBlockEntry());
574 while (current != NULL) {
575 ASSERT((current->next() == NULL) == current->IsControlInstruction());
576 ASSERT(current->block() == block);
578 current = current->next();
581 // Check that successors are correctly set.
582 HBasicBlock* first = block->end()->FirstSuccessor();
583 HBasicBlock* second = block->end()->SecondSuccessor();
584 ASSERT(second == NULL || first != NULL);
586 // Check that the predecessor array is correct.
588 ASSERT(first->predecessors()->Contains(block));
589 if (second != NULL) {
590 ASSERT(second->predecessors()->Contains(block));
594 // Check that phis have correct arguments.
595 for (int j = 0; j < block->phis()->length(); j++) {
596 HPhi* phi = block->phis()->at(j);
600 // Check that all join blocks have predecessors that end with an
601 // unconditional goto and agree on their environment node id.
602 if (block->predecessors()->length() >= 2) {
604 block->predecessors()->first()->last_environment()->ast_id();
605 for (int k = 0; k < block->predecessors()->length(); k++) {
606 HBasicBlock* predecessor = block->predecessors()->at(k);
607 ASSERT(predecessor->end()->IsGoto() ||
608 predecessor->end()->IsDeoptimize());
609 ASSERT(predecessor->last_environment()->ast_id() == id);
614 // Check special property of first block to have no predecessors.
615 ASSERT(blocks_.at(0)->predecessors()->is_empty());
617 if (do_full_verify) {
618 // Check that the graph is fully connected.
619 ReachabilityAnalyzer analyzer(entry_block_, blocks_.length(), NULL);
620 ASSERT(analyzer.visited_count() == blocks_.length());
622 // Check that entry block dominator is NULL.
623 ASSERT(entry_block_->dominator() == NULL);
626 for (int i = 0; i < blocks_.length(); ++i) {
627 HBasicBlock* block = blocks_.at(i);
628 if (block->dominator() == NULL) {
629 // Only start block may have no dominator assigned to.
632 // Assert that block is unreachable if dominator must not be visited.
633 ReachabilityAnalyzer dominator_analyzer(entry_block_,
636 ASSERT(!dominator_analyzer.reachable()->Contains(block->block_id()));
645 HConstant* HGraph::GetConstant(SetOncePointer<HConstant>* pointer,
647 if (!pointer->is_set()) {
648 // Can't pass GetInvalidContext() to HConstant::New, because that will
649 // recursively call GetConstant
650 HConstant* constant = HConstant::New(zone(), NULL, value);
651 constant->InsertAfter(entry_block()->first());
652 pointer->set(constant);
655 return ReinsertConstantIfNecessary(pointer->get());
659 HConstant* HGraph::ReinsertConstantIfNecessary(HConstant* constant) {
660 if (!constant->IsLinked()) {
661 // The constant was removed from the graph. Reinsert.
662 constant->ClearFlag(HValue::kIsDead);
663 constant->InsertAfter(entry_block()->first());
669 HConstant* HGraph::GetConstant0() {
670 return GetConstant(&constant_0_, 0);
674 HConstant* HGraph::GetConstant1() {
675 return GetConstant(&constant_1_, 1);
679 HConstant* HGraph::GetConstantMinus1() {
680 return GetConstant(&constant_minus1_, -1);
684 #define DEFINE_GET_CONSTANT(Name, name, type, htype, boolean_value) \
685 HConstant* HGraph::GetConstant##Name() { \
686 if (!constant_##name##_.is_set()) { \
687 HConstant* constant = new(zone()) HConstant( \
688 Unique<Object>::CreateImmovable(isolate()->factory()->name##_value()), \
689 Unique<Map>::CreateImmovable(isolate()->factory()->type##_map()), \
691 Representation::Tagged(), \
697 constant->InsertAfter(entry_block()->first()); \
698 constant_##name##_.set(constant); \
700 return ReinsertConstantIfNecessary(constant_##name##_.get()); \
704 DEFINE_GET_CONSTANT(Undefined, undefined, undefined, HType::Undefined(), false)
705 DEFINE_GET_CONSTANT(True, true, boolean, HType::Boolean(), true)
706 DEFINE_GET_CONSTANT(False, false, boolean, HType::Boolean(), false)
707 DEFINE_GET_CONSTANT(Hole, the_hole, the_hole, HType::None(), false)
708 DEFINE_GET_CONSTANT(Null, null, null, HType::Null(), false)
711 #undef DEFINE_GET_CONSTANT
713 #define DEFINE_IS_CONSTANT(Name, name) \
714 bool HGraph::IsConstant##Name(HConstant* constant) { \
715 return constant_##name##_.is_set() && constant == constant_##name##_.get(); \
717 DEFINE_IS_CONSTANT(Undefined, undefined)
718 DEFINE_IS_CONSTANT(0, 0)
719 DEFINE_IS_CONSTANT(1, 1)
720 DEFINE_IS_CONSTANT(Minus1, minus1)
721 DEFINE_IS_CONSTANT(True, true)
722 DEFINE_IS_CONSTANT(False, false)
723 DEFINE_IS_CONSTANT(Hole, the_hole)
724 DEFINE_IS_CONSTANT(Null, null)
726 #undef DEFINE_IS_CONSTANT
729 HConstant* HGraph::GetInvalidContext() {
730 return GetConstant(&constant_invalid_context_, 0xFFFFC0C7);
734 bool HGraph::IsStandardConstant(HConstant* constant) {
735 if (IsConstantUndefined(constant)) return true;
736 if (IsConstant0(constant)) return true;
737 if (IsConstant1(constant)) return true;
738 if (IsConstantMinus1(constant)) return true;
739 if (IsConstantTrue(constant)) return true;
740 if (IsConstantFalse(constant)) return true;
741 if (IsConstantHole(constant)) return true;
742 if (IsConstantNull(constant)) return true;
747 HGraphBuilder::IfBuilder::IfBuilder(HGraphBuilder* builder)
756 needs_compare_(true),
757 pending_merge_block_(false),
758 split_edge_merge_block_(NULL),
759 merge_at_join_blocks_(NULL),
760 normal_merge_at_join_block_count_(0),
761 deopt_merge_at_join_block_count_(0) {
762 HEnvironment* env = builder->environment();
763 first_true_block_ = builder->CreateBasicBlock(env->Copy());
764 first_false_block_ = builder->CreateBasicBlock(env->Copy());
768 HGraphBuilder::IfBuilder::IfBuilder(
769 HGraphBuilder* builder,
770 HIfContinuation* continuation)
779 needs_compare_(false),
780 pending_merge_block_(false),
781 first_true_block_(NULL),
782 first_false_block_(NULL),
783 split_edge_merge_block_(NULL),
784 merge_at_join_blocks_(NULL),
785 normal_merge_at_join_block_count_(0),
786 deopt_merge_at_join_block_count_(0) {
787 continuation->Continue(&first_true_block_,
788 &first_false_block_);
792 HControlInstruction* HGraphBuilder::IfBuilder::AddCompare(
793 HControlInstruction* compare) {
794 ASSERT(did_then_ == did_else_);
796 // Handle if-then-elseif
802 pending_merge_block_ = false;
803 split_edge_merge_block_ = NULL;
804 HEnvironment* env = builder_->environment();
805 first_true_block_ = builder_->CreateBasicBlock(env->Copy());
806 first_false_block_ = builder_->CreateBasicBlock(env->Copy());
808 if (split_edge_merge_block_ != NULL) {
809 HEnvironment* env = first_false_block_->last_environment();
810 HBasicBlock* split_edge =
811 builder_->CreateBasicBlock(env->Copy());
813 compare->SetSuccessorAt(0, split_edge);
814 compare->SetSuccessorAt(1, first_false_block_);
816 compare->SetSuccessorAt(0, first_true_block_);
817 compare->SetSuccessorAt(1, split_edge);
819 builder_->GotoNoSimulate(split_edge, split_edge_merge_block_);
821 compare->SetSuccessorAt(0, first_true_block_);
822 compare->SetSuccessorAt(1, first_false_block_);
824 builder_->FinishCurrentBlock(compare);
825 needs_compare_ = false;
830 void HGraphBuilder::IfBuilder::Or() {
831 ASSERT(!needs_compare_);
834 HEnvironment* env = first_false_block_->last_environment();
835 if (split_edge_merge_block_ == NULL) {
836 split_edge_merge_block_ =
837 builder_->CreateBasicBlock(env->Copy());
838 builder_->GotoNoSimulate(first_true_block_, split_edge_merge_block_);
839 first_true_block_ = split_edge_merge_block_;
841 builder_->set_current_block(first_false_block_);
842 first_false_block_ = builder_->CreateBasicBlock(env->Copy());
846 void HGraphBuilder::IfBuilder::And() {
847 ASSERT(!needs_compare_);
850 HEnvironment* env = first_false_block_->last_environment();
851 if (split_edge_merge_block_ == NULL) {
852 split_edge_merge_block_ = builder_->CreateBasicBlock(env->Copy());
853 builder_->GotoNoSimulate(first_false_block_, split_edge_merge_block_);
854 first_false_block_ = split_edge_merge_block_;
856 builder_->set_current_block(first_true_block_);
857 first_true_block_ = builder_->CreateBasicBlock(env->Copy());
861 void HGraphBuilder::IfBuilder::CaptureContinuation(
862 HIfContinuation* continuation) {
863 ASSERT(!did_else_if_);
867 HBasicBlock* true_block = NULL;
868 HBasicBlock* false_block = NULL;
869 Finish(&true_block, &false_block);
870 ASSERT(true_block != NULL);
871 ASSERT(false_block != NULL);
872 continuation->Capture(true_block, false_block);
874 builder_->set_current_block(NULL);
879 void HGraphBuilder::IfBuilder::JoinContinuation(HIfContinuation* continuation) {
880 ASSERT(!did_else_if_);
883 HBasicBlock* true_block = NULL;
884 HBasicBlock* false_block = NULL;
885 Finish(&true_block, &false_block);
886 merge_at_join_blocks_ = NULL;
887 if (true_block != NULL && !true_block->IsFinished()) {
888 ASSERT(continuation->IsTrueReachable());
889 builder_->GotoNoSimulate(true_block, continuation->true_branch());
891 if (false_block != NULL && !false_block->IsFinished()) {
892 ASSERT(continuation->IsFalseReachable());
893 builder_->GotoNoSimulate(false_block, continuation->false_branch());
900 void HGraphBuilder::IfBuilder::Then() {
904 if (needs_compare_) {
905 // Handle if's without any expressions, they jump directly to the "else"
906 // branch. However, we must pretend that the "then" branch is reachable,
907 // so that the graph builder visits it and sees any live range extending
908 // constructs within it.
909 HConstant* constant_false = builder_->graph()->GetConstantFalse();
910 ToBooleanStub::Types boolean_type = ToBooleanStub::Types();
911 boolean_type.Add(ToBooleanStub::BOOLEAN);
912 HBranch* branch = builder()->New<HBranch>(
913 constant_false, boolean_type, first_true_block_, first_false_block_);
914 builder_->FinishCurrentBlock(branch);
916 builder_->set_current_block(first_true_block_);
917 pending_merge_block_ = true;
921 void HGraphBuilder::IfBuilder::Else() {
925 AddMergeAtJoinBlock(false);
926 builder_->set_current_block(first_false_block_);
927 pending_merge_block_ = true;
932 void HGraphBuilder::IfBuilder::Deopt(const char* reason) {
934 builder_->Add<HDeoptimize>(reason, Deoptimizer::EAGER);
935 AddMergeAtJoinBlock(true);
939 void HGraphBuilder::IfBuilder::Return(HValue* value) {
940 HValue* parameter_count = builder_->graph()->GetConstantMinus1();
941 builder_->FinishExitCurrentBlock(
942 builder_->New<HReturn>(value, parameter_count));
943 AddMergeAtJoinBlock(false);
947 void HGraphBuilder::IfBuilder::AddMergeAtJoinBlock(bool deopt) {
948 if (!pending_merge_block_) return;
949 HBasicBlock* block = builder_->current_block();
950 ASSERT(block == NULL || !block->IsFinished());
951 MergeAtJoinBlock* record =
952 new(builder_->zone()) MergeAtJoinBlock(block, deopt,
953 merge_at_join_blocks_);
954 merge_at_join_blocks_ = record;
956 ASSERT(block->end() == NULL);
958 normal_merge_at_join_block_count_++;
960 deopt_merge_at_join_block_count_++;
963 builder_->set_current_block(NULL);
964 pending_merge_block_ = false;
968 void HGraphBuilder::IfBuilder::Finish() {
973 AddMergeAtJoinBlock(false);
976 AddMergeAtJoinBlock(false);
982 void HGraphBuilder::IfBuilder::Finish(HBasicBlock** then_continuation,
983 HBasicBlock** else_continuation) {
986 MergeAtJoinBlock* else_record = merge_at_join_blocks_;
987 if (else_continuation != NULL) {
988 *else_continuation = else_record->block_;
990 MergeAtJoinBlock* then_record = else_record->next_;
991 if (then_continuation != NULL) {
992 *then_continuation = then_record->block_;
994 ASSERT(then_record->next_ == NULL);
998 void HGraphBuilder::IfBuilder::End() {
999 if (captured_) return;
1002 int total_merged_blocks = normal_merge_at_join_block_count_ +
1003 deopt_merge_at_join_block_count_;
1004 ASSERT(total_merged_blocks >= 1);
1005 HBasicBlock* merge_block = total_merged_blocks == 1
1006 ? NULL : builder_->graph()->CreateBasicBlock();
1008 // Merge non-deopt blocks first to ensure environment has right size for
1010 MergeAtJoinBlock* current = merge_at_join_blocks_;
1011 while (current != NULL) {
1012 if (!current->deopt_ && current->block_ != NULL) {
1013 // If there is only one block that makes it through to the end of the
1014 // if, then just set it as the current block and continue rather then
1015 // creating an unnecessary merge block.
1016 if (total_merged_blocks == 1) {
1017 builder_->set_current_block(current->block_);
1020 builder_->GotoNoSimulate(current->block_, merge_block);
1022 current = current->next_;
1025 // Merge deopt blocks, padding when necessary.
1026 current = merge_at_join_blocks_;
1027 while (current != NULL) {
1028 if (current->deopt_ && current->block_ != NULL) {
1029 current->block_->FinishExit(
1030 HAbnormalExit::New(builder_->zone(), NULL),
1031 HSourcePosition::Unknown());
1033 current = current->next_;
1035 builder_->set_current_block(merge_block);
1039 HGraphBuilder::LoopBuilder::LoopBuilder(HGraphBuilder* builder,
1041 LoopBuilder::Direction direction)
1042 : builder_(builder),
1044 direction_(direction),
1046 header_block_ = builder->CreateLoopHeaderBlock();
1049 exit_trampoline_block_ = NULL;
1050 increment_amount_ = builder_->graph()->GetConstant1();
1054 HGraphBuilder::LoopBuilder::LoopBuilder(HGraphBuilder* builder,
1056 LoopBuilder::Direction direction,
1057 HValue* increment_amount)
1058 : builder_(builder),
1060 direction_(direction),
1062 header_block_ = builder->CreateLoopHeaderBlock();
1065 exit_trampoline_block_ = NULL;
1066 increment_amount_ = increment_amount;
1070 HValue* HGraphBuilder::LoopBuilder::BeginBody(
1072 HValue* terminating,
1073 Token::Value token) {
1074 HEnvironment* env = builder_->environment();
1075 phi_ = header_block_->AddNewPhi(env->values()->length());
1076 phi_->AddInput(initial);
1078 builder_->GotoNoSimulate(header_block_);
1080 HEnvironment* body_env = env->Copy();
1081 HEnvironment* exit_env = env->Copy();
1082 // Remove the phi from the expression stack
1085 body_block_ = builder_->CreateBasicBlock(body_env);
1086 exit_block_ = builder_->CreateBasicBlock(exit_env);
1088 builder_->set_current_block(header_block_);
1090 builder_->FinishCurrentBlock(builder_->New<HCompareNumericAndBranch>(
1091 phi_, terminating, token, body_block_, exit_block_));
1093 builder_->set_current_block(body_block_);
1094 if (direction_ == kPreIncrement || direction_ == kPreDecrement) {
1095 HValue* one = builder_->graph()->GetConstant1();
1096 if (direction_ == kPreIncrement) {
1097 increment_ = HAdd::New(zone(), context_, phi_, one);
1099 increment_ = HSub::New(zone(), context_, phi_, one);
1101 increment_->ClearFlag(HValue::kCanOverflow);
1102 builder_->AddInstruction(increment_);
1110 void HGraphBuilder::LoopBuilder::Break() {
1111 if (exit_trampoline_block_ == NULL) {
1112 // Its the first time we saw a break.
1113 HEnvironment* env = exit_block_->last_environment()->Copy();
1114 exit_trampoline_block_ = builder_->CreateBasicBlock(env);
1115 builder_->GotoNoSimulate(exit_block_, exit_trampoline_block_);
1118 builder_->GotoNoSimulate(exit_trampoline_block_);
1119 builder_->set_current_block(NULL);
1123 void HGraphBuilder::LoopBuilder::EndBody() {
1126 if (direction_ == kPostIncrement || direction_ == kPostDecrement) {
1127 if (direction_ == kPostIncrement) {
1128 increment_ = HAdd::New(zone(), context_, phi_, increment_amount_);
1130 increment_ = HSub::New(zone(), context_, phi_, increment_amount_);
1132 increment_->ClearFlag(HValue::kCanOverflow);
1133 builder_->AddInstruction(increment_);
1136 // Push the new increment value on the expression stack to merge into the phi.
1137 builder_->environment()->Push(increment_);
1138 HBasicBlock* last_block = builder_->current_block();
1139 builder_->GotoNoSimulate(last_block, header_block_);
1140 header_block_->loop_information()->RegisterBackEdge(last_block);
1142 if (exit_trampoline_block_ != NULL) {
1143 builder_->set_current_block(exit_trampoline_block_);
1145 builder_->set_current_block(exit_block_);
1151 HGraph* HGraphBuilder::CreateGraph() {
1152 graph_ = new(zone()) HGraph(info_);
1153 if (FLAG_hydrogen_stats) isolate()->GetHStatistics()->Initialize(info_);
1154 CompilationPhase phase("H_Block building", info_);
1155 set_current_block(graph()->entry_block());
1156 if (!BuildGraph()) return NULL;
1157 graph()->FinalizeUniqueness();
1162 HInstruction* HGraphBuilder::AddInstruction(HInstruction* instr) {
1163 ASSERT(current_block() != NULL);
1164 ASSERT(!FLAG_hydrogen_track_positions ||
1165 !position_.IsUnknown() ||
1166 !info_->IsOptimizing());
1167 current_block()->AddInstruction(instr, source_position());
1168 if (graph()->IsInsideNoSideEffectsScope()) {
1169 instr->SetFlag(HValue::kHasNoObservableSideEffects);
1175 void HGraphBuilder::FinishCurrentBlock(HControlInstruction* last) {
1176 ASSERT(!FLAG_hydrogen_track_positions ||
1177 !info_->IsOptimizing() ||
1178 !position_.IsUnknown());
1179 current_block()->Finish(last, source_position());
1180 if (last->IsReturn() || last->IsAbnormalExit()) {
1181 set_current_block(NULL);
1186 void HGraphBuilder::FinishExitCurrentBlock(HControlInstruction* instruction) {
1187 ASSERT(!FLAG_hydrogen_track_positions || !info_->IsOptimizing() ||
1188 !position_.IsUnknown());
1189 current_block()->FinishExit(instruction, source_position());
1190 if (instruction->IsReturn() || instruction->IsAbnormalExit()) {
1191 set_current_block(NULL);
1196 void HGraphBuilder::AddIncrementCounter(StatsCounter* counter) {
1197 if (FLAG_native_code_counters && counter->Enabled()) {
1198 HValue* reference = Add<HConstant>(ExternalReference(counter));
1199 HValue* old_value = Add<HLoadNamedField>(
1200 reference, static_cast<HValue*>(NULL), HObjectAccess::ForCounter());
1201 HValue* new_value = AddUncasted<HAdd>(old_value, graph()->GetConstant1());
1202 new_value->ClearFlag(HValue::kCanOverflow); // Ignore counter overflow
1203 Add<HStoreNamedField>(reference, HObjectAccess::ForCounter(),
1204 new_value, STORE_TO_INITIALIZED_ENTRY);
1209 void HGraphBuilder::AddSimulate(BailoutId id,
1210 RemovableSimulate removable) {
1211 ASSERT(current_block() != NULL);
1212 ASSERT(!graph()->IsInsideNoSideEffectsScope());
1213 current_block()->AddNewSimulate(id, source_position(), removable);
1217 HBasicBlock* HGraphBuilder::CreateBasicBlock(HEnvironment* env) {
1218 HBasicBlock* b = graph()->CreateBasicBlock();
1219 b->SetInitialEnvironment(env);
1224 HBasicBlock* HGraphBuilder::CreateLoopHeaderBlock() {
1225 HBasicBlock* header = graph()->CreateBasicBlock();
1226 HEnvironment* entry_env = environment()->CopyAsLoopHeader(header);
1227 header->SetInitialEnvironment(entry_env);
1228 header->AttachLoopInformation();
1233 HValue* HGraphBuilder::BuildGetElementsKind(HValue* object) {
1234 HValue* map = Add<HLoadNamedField>(object, static_cast<HValue*>(NULL),
1235 HObjectAccess::ForMap());
1237 HValue* bit_field2 = Add<HLoadNamedField>(map, static_cast<HValue*>(NULL),
1238 HObjectAccess::ForMapBitField2());
1239 return BuildDecodeField<Map::ElementsKindBits>(bit_field2);
1243 HValue* HGraphBuilder::BuildCheckHeapObject(HValue* obj) {
1244 if (obj->type().IsHeapObject()) return obj;
1245 return Add<HCheckHeapObject>(obj);
1249 void HGraphBuilder::FinishExitWithHardDeoptimization(const char* reason) {
1250 Add<HDeoptimize>(reason, Deoptimizer::EAGER);
1251 FinishExitCurrentBlock(New<HAbnormalExit>());
1255 HValue* HGraphBuilder::BuildCheckString(HValue* string) {
1256 if (!string->type().IsString()) {
1257 ASSERT(!string->IsConstant() ||
1258 !HConstant::cast(string)->HasStringValue());
1259 BuildCheckHeapObject(string);
1260 return Add<HCheckInstanceType>(string, HCheckInstanceType::IS_STRING);
1266 HValue* HGraphBuilder::BuildWrapReceiver(HValue* object, HValue* function) {
1267 if (object->type().IsJSObject()) return object;
1268 if (function->IsConstant() &&
1269 HConstant::cast(function)->handle(isolate())->IsJSFunction()) {
1270 Handle<JSFunction> f = Handle<JSFunction>::cast(
1271 HConstant::cast(function)->handle(isolate()));
1272 SharedFunctionInfo* shared = f->shared();
1273 if (shared->strict_mode() == STRICT || shared->native()) return object;
1275 return Add<HWrapReceiver>(object, function);
1279 HValue* HGraphBuilder::BuildCheckForCapacityGrow(
1286 PropertyAccessType access_type) {
1287 IfBuilder length_checker(this);
1289 Token::Value token = IsHoleyElementsKind(kind) ? Token::GTE : Token::EQ;
1290 length_checker.If<HCompareNumericAndBranch>(key, length, token);
1292 length_checker.Then();
1294 HValue* current_capacity = AddLoadFixedArrayLength(elements);
1296 IfBuilder capacity_checker(this);
1298 capacity_checker.If<HCompareNumericAndBranch>(key, current_capacity,
1300 capacity_checker.Then();
1302 HValue* max_gap = Add<HConstant>(static_cast<int32_t>(JSObject::kMaxGap));
1303 HValue* max_capacity = AddUncasted<HAdd>(current_capacity, max_gap);
1305 Add<HBoundsCheck>(key, max_capacity);
1307 HValue* new_capacity = BuildNewElementsCapacity(key);
1308 HValue* new_elements = BuildGrowElementsCapacity(object, elements,
1312 environment()->Push(new_elements);
1313 capacity_checker.Else();
1315 environment()->Push(elements);
1316 capacity_checker.End();
1319 HValue* new_length = AddUncasted<HAdd>(key, graph_->GetConstant1());
1320 new_length->ClearFlag(HValue::kCanOverflow);
1322 Add<HStoreNamedField>(object, HObjectAccess::ForArrayLength(kind),
1326 if (access_type == STORE && kind == FAST_SMI_ELEMENTS) {
1327 HValue* checked_elements = environment()->Top();
1329 // Write zero to ensure that the new element is initialized with some smi.
1330 Add<HStoreKeyed>(checked_elements, key, graph()->GetConstant0(), kind);
1333 length_checker.Else();
1334 Add<HBoundsCheck>(key, length);
1336 environment()->Push(elements);
1337 length_checker.End();
1339 return environment()->Pop();
1343 HValue* HGraphBuilder::BuildCopyElementsOnWrite(HValue* object,
1347 Factory* factory = isolate()->factory();
1349 IfBuilder cow_checker(this);
1351 cow_checker.If<HCompareMap>(elements, factory->fixed_cow_array_map());
1354 HValue* capacity = AddLoadFixedArrayLength(elements);
1356 HValue* new_elements = BuildGrowElementsCapacity(object, elements, kind,
1357 kind, length, capacity);
1359 environment()->Push(new_elements);
1363 environment()->Push(elements);
1367 return environment()->Pop();
1371 void HGraphBuilder::BuildTransitionElementsKind(HValue* object,
1373 ElementsKind from_kind,
1374 ElementsKind to_kind,
1376 ASSERT(!IsFastHoleyElementsKind(from_kind) ||
1377 IsFastHoleyElementsKind(to_kind));
1379 if (AllocationSite::GetMode(from_kind, to_kind) == TRACK_ALLOCATION_SITE) {
1380 Add<HTrapAllocationMemento>(object);
1383 if (!IsSimpleMapChangeTransition(from_kind, to_kind)) {
1384 HInstruction* elements = AddLoadElements(object);
1386 HInstruction* empty_fixed_array = Add<HConstant>(
1387 isolate()->factory()->empty_fixed_array());
1389 IfBuilder if_builder(this);
1391 if_builder.IfNot<HCompareObjectEqAndBranch>(elements, empty_fixed_array);
1395 HInstruction* elements_length = AddLoadFixedArrayLength(elements);
1397 HInstruction* array_length = is_jsarray
1398 ? Add<HLoadNamedField>(object, static_cast<HValue*>(NULL),
1399 HObjectAccess::ForArrayLength(from_kind))
1402 BuildGrowElementsCapacity(object, elements, from_kind, to_kind,
1403 array_length, elements_length);
1408 Add<HStoreNamedField>(object, HObjectAccess::ForMap(), map);
1412 void HGraphBuilder::BuildJSObjectCheck(HValue* receiver,
1413 int bit_field_mask) {
1414 // Check that the object isn't a smi.
1415 Add<HCheckHeapObject>(receiver);
1417 // Get the map of the receiver.
1418 HValue* map = Add<HLoadNamedField>(receiver, static_cast<HValue*>(NULL),
1419 HObjectAccess::ForMap());
1421 // Check the instance type and if an access check is needed, this can be
1422 // done with a single load, since both bytes are adjacent in the map.
1423 HObjectAccess access(HObjectAccess::ForMapInstanceTypeAndBitField());
1424 HValue* instance_type_and_bit_field =
1425 Add<HLoadNamedField>(map, static_cast<HValue*>(NULL), access);
1427 HValue* mask = Add<HConstant>(0x00FF | (bit_field_mask << 8));
1428 HValue* and_result = AddUncasted<HBitwise>(Token::BIT_AND,
1429 instance_type_and_bit_field,
1431 HValue* sub_result = AddUncasted<HSub>(and_result,
1432 Add<HConstant>(JS_OBJECT_TYPE));
1433 Add<HBoundsCheck>(sub_result, Add<HConstant>(0x100 - JS_OBJECT_TYPE));
1437 void HGraphBuilder::BuildKeyedIndexCheck(HValue* key,
1438 HIfContinuation* join_continuation) {
1439 // The sometimes unintuitively backward ordering of the ifs below is
1440 // convoluted, but necessary. All of the paths must guarantee that the
1441 // if-true of the continuation returns a smi element index and the if-false of
1442 // the continuation returns either a symbol or a unique string key. All other
1443 // object types cause a deopt to fall back to the runtime.
1445 IfBuilder key_smi_if(this);
1446 key_smi_if.If<HIsSmiAndBranch>(key);
1449 Push(key); // Nothing to do, just continue to true of continuation.
1453 HValue* map = Add<HLoadNamedField>(key, static_cast<HValue*>(NULL),
1454 HObjectAccess::ForMap());
1455 HValue* instance_type =
1456 Add<HLoadNamedField>(map, static_cast<HValue*>(NULL),
1457 HObjectAccess::ForMapInstanceType());
1459 // Non-unique string, check for a string with a hash code that is actually
1461 STATIC_ASSERT(LAST_UNIQUE_NAME_TYPE == FIRST_NONSTRING_TYPE);
1462 IfBuilder not_string_or_name_if(this);
1463 not_string_or_name_if.If<HCompareNumericAndBranch>(
1465 Add<HConstant>(LAST_UNIQUE_NAME_TYPE),
1468 not_string_or_name_if.Then();
1470 // Non-smi, non-Name, non-String: Try to convert to smi in case of
1472 // TODO(danno): This could call some variant of ToString
1473 Push(AddUncasted<HForceRepresentation>(key, Representation::Smi()));
1475 not_string_or_name_if.Else();
1477 // String or Name: check explicitly for Name, they can short-circuit
1478 // directly to unique non-index key path.
1479 IfBuilder not_symbol_if(this);
1480 not_symbol_if.If<HCompareNumericAndBranch>(
1482 Add<HConstant>(SYMBOL_TYPE),
1485 not_symbol_if.Then();
1487 // String: check whether the String is a String of an index. If it is,
1488 // extract the index value from the hash.
1490 Add<HLoadNamedField>(key, static_cast<HValue*>(NULL),
1491 HObjectAccess::ForNameHashField());
1492 HValue* not_index_mask = Add<HConstant>(static_cast<int>(
1493 String::kContainsCachedArrayIndexMask));
1495 HValue* not_index_test = AddUncasted<HBitwise>(
1496 Token::BIT_AND, hash, not_index_mask);
1498 IfBuilder string_index_if(this);
1499 string_index_if.If<HCompareNumericAndBranch>(not_index_test,
1500 graph()->GetConstant0(),
1502 string_index_if.Then();
1504 // String with index in hash: extract string and merge to index path.
1505 Push(BuildDecodeField<String::ArrayIndexValueBits>(hash));
1507 string_index_if.Else();
1509 // Key is a non-index String, check for uniqueness/internalization. If
1511 HValue* not_internalized_bit = AddUncasted<HBitwise>(
1514 Add<HConstant>(static_cast<int>(kIsNotInternalizedMask)));
1515 DeoptimizeIf<HCompareNumericAndBranch>(
1516 not_internalized_bit,
1517 graph()->GetConstant0(),
1519 "BuildKeyedIndexCheck: string isn't internalized");
1520 // Key guaranteed to be a unqiue string
1523 string_index_if.JoinContinuation(join_continuation);
1525 not_symbol_if.Else();
1527 Push(key); // Key is symbol
1529 not_symbol_if.JoinContinuation(join_continuation);
1531 not_string_or_name_if.JoinContinuation(join_continuation);
1533 key_smi_if.JoinContinuation(join_continuation);
1537 void HGraphBuilder::BuildNonGlobalObjectCheck(HValue* receiver) {
1538 // Get the the instance type of the receiver, and make sure that it is
1539 // not one of the global object types.
1540 HValue* map = Add<HLoadNamedField>(receiver, static_cast<HValue*>(NULL),
1541 HObjectAccess::ForMap());
1542 HValue* instance_type =
1543 Add<HLoadNamedField>(map, static_cast<HValue*>(NULL),
1544 HObjectAccess::ForMapInstanceType());
1545 STATIC_ASSERT(JS_BUILTINS_OBJECT_TYPE == JS_GLOBAL_OBJECT_TYPE + 1);
1546 HValue* min_global_type = Add<HConstant>(JS_GLOBAL_OBJECT_TYPE);
1547 HValue* max_global_type = Add<HConstant>(JS_BUILTINS_OBJECT_TYPE);
1549 IfBuilder if_global_object(this);
1550 if_global_object.If<HCompareNumericAndBranch>(instance_type,
1553 if_global_object.And();
1554 if_global_object.If<HCompareNumericAndBranch>(instance_type,
1557 if_global_object.ThenDeopt("receiver was a global object");
1558 if_global_object.End();
1562 void HGraphBuilder::BuildTestForDictionaryProperties(
1564 HIfContinuation* continuation) {
1565 HValue* properties = Add<HLoadNamedField>(
1566 object, static_cast<HValue*>(NULL),
1567 HObjectAccess::ForPropertiesPointer());
1568 HValue* properties_map =
1569 Add<HLoadNamedField>(properties, static_cast<HValue*>(NULL),
1570 HObjectAccess::ForMap());
1571 HValue* hash_map = Add<HLoadRoot>(Heap::kHashTableMapRootIndex);
1572 IfBuilder builder(this);
1573 builder.If<HCompareObjectEqAndBranch>(properties_map, hash_map);
1574 builder.CaptureContinuation(continuation);
1578 HValue* HGraphBuilder::BuildKeyedLookupCacheHash(HValue* object,
1580 // Load the map of the receiver, compute the keyed lookup cache hash
1581 // based on 32 bits of the map pointer and the string hash.
1582 HValue* object_map =
1583 Add<HLoadNamedField>(object, static_cast<HValue*>(NULL),
1584 HObjectAccess::ForMapAsInteger32());
1585 HValue* shifted_map = AddUncasted<HShr>(
1586 object_map, Add<HConstant>(KeyedLookupCache::kMapHashShift));
1587 HValue* string_hash =
1588 Add<HLoadNamedField>(key, static_cast<HValue*>(NULL),
1589 HObjectAccess::ForStringHashField());
1590 HValue* shifted_hash = AddUncasted<HShr>(
1591 string_hash, Add<HConstant>(String::kHashShift));
1592 HValue* xor_result = AddUncasted<HBitwise>(Token::BIT_XOR, shifted_map,
1594 int mask = (KeyedLookupCache::kCapacityMask & KeyedLookupCache::kHashMask);
1595 return AddUncasted<HBitwise>(Token::BIT_AND, xor_result,
1596 Add<HConstant>(mask));
1600 HValue* HGraphBuilder::BuildUncheckedDictionaryElementLoadHelper(
1605 int current_probe) {
1606 if (current_probe == kNumberDictionaryProbes) {
1610 int32_t offset = SeededNumberDictionary::GetProbeOffset(current_probe);
1611 HValue* raw_index = (current_probe == 0)
1613 : AddUncasted<HAdd>(hash, Add<HConstant>(offset));
1614 raw_index = AddUncasted<HBitwise>(Token::BIT_AND, raw_index, mask);
1615 int32_t entry_size = SeededNumberDictionary::kEntrySize;
1616 raw_index = AddUncasted<HMul>(raw_index, Add<HConstant>(entry_size));
1617 raw_index->ClearFlag(HValue::kCanOverflow);
1619 int32_t base_offset = SeededNumberDictionary::kElementsStartIndex;
1620 HValue* key_index = AddUncasted<HAdd>(raw_index, Add<HConstant>(base_offset));
1621 key_index->ClearFlag(HValue::kCanOverflow);
1623 HValue* candidate_key = Add<HLoadKeyed>(elements, key_index,
1624 static_cast<HValue*>(NULL),
1627 IfBuilder key_compare(this);
1628 key_compare.IfNot<HCompareObjectEqAndBranch>(key, candidate_key);
1631 // Key at the current probe doesn't match, try at the next probe.
1632 HValue* result = BuildUncheckedDictionaryElementLoadHelper(
1633 elements, key, hash, mask, current_probe + 1);
1634 if (result == NULL) {
1635 key_compare.Deopt("probes exhausted in keyed load dictionary lookup");
1636 result = graph()->GetConstantUndefined();
1643 // Key at current probe matches. Details must be zero, otherwise the
1644 // dictionary element requires special handling.
1645 HValue* details_index = AddUncasted<HAdd>(
1646 raw_index, Add<HConstant>(base_offset + 2));
1647 details_index->ClearFlag(HValue::kCanOverflow);
1649 HValue* details = Add<HLoadKeyed>(elements, details_index,
1650 static_cast<HValue*>(NULL),
1652 IfBuilder details_compare(this);
1653 details_compare.If<HCompareNumericAndBranch>(details,
1654 graph()->GetConstant0(),
1656 details_compare.ThenDeopt("keyed load dictionary element not fast case");
1658 details_compare.Else();
1660 // Key matches and details are zero --> fast case. Load and return the
1662 HValue* result_index = AddUncasted<HAdd>(
1663 raw_index, Add<HConstant>(base_offset + 1));
1664 result_index->ClearFlag(HValue::kCanOverflow);
1666 Push(Add<HLoadKeyed>(elements, result_index,
1667 static_cast<HValue*>(NULL),
1670 details_compare.End();
1678 HValue* HGraphBuilder::BuildElementIndexHash(HValue* index) {
1679 int32_t seed_value = static_cast<uint32_t>(isolate()->heap()->HashSeed());
1680 HValue* seed = Add<HConstant>(seed_value);
1681 HValue* hash = AddUncasted<HBitwise>(Token::BIT_XOR, index, seed);
1683 // hash = ~hash + (hash << 15);
1684 HValue* shifted_hash = AddUncasted<HShl>(hash, Add<HConstant>(15));
1685 HValue* not_hash = AddUncasted<HBitwise>(Token::BIT_XOR, hash,
1686 graph()->GetConstantMinus1());
1687 hash = AddUncasted<HAdd>(shifted_hash, not_hash);
1689 // hash = hash ^ (hash >> 12);
1690 shifted_hash = AddUncasted<HShr>(hash, Add<HConstant>(12));
1691 hash = AddUncasted<HBitwise>(Token::BIT_XOR, hash, shifted_hash);
1693 // hash = hash + (hash << 2);
1694 shifted_hash = AddUncasted<HShl>(hash, Add<HConstant>(2));
1695 hash = AddUncasted<HAdd>(hash, shifted_hash);
1697 // hash = hash ^ (hash >> 4);
1698 shifted_hash = AddUncasted<HShr>(hash, Add<HConstant>(4));
1699 hash = AddUncasted<HBitwise>(Token::BIT_XOR, hash, shifted_hash);
1701 // hash = hash * 2057;
1702 hash = AddUncasted<HMul>(hash, Add<HConstant>(2057));
1703 hash->ClearFlag(HValue::kCanOverflow);
1705 // hash = hash ^ (hash >> 16);
1706 shifted_hash = AddUncasted<HShr>(hash, Add<HConstant>(16));
1707 return AddUncasted<HBitwise>(Token::BIT_XOR, hash, shifted_hash);
1711 HValue* HGraphBuilder::BuildUncheckedDictionaryElementLoad(HValue* receiver,
1715 HValue* capacity = Add<HLoadKeyed>(
1717 Add<HConstant>(NameDictionary::kCapacityIndex),
1718 static_cast<HValue*>(NULL),
1721 HValue* mask = AddUncasted<HSub>(capacity, graph()->GetConstant1());
1722 mask->ChangeRepresentation(Representation::Integer32());
1723 mask->ClearFlag(HValue::kCanOverflow);
1725 return BuildUncheckedDictionaryElementLoadHelper(elements, key,
1730 HValue* HGraphBuilder::BuildRegExpConstructResult(HValue* length,
1733 NoObservableSideEffectsScope scope(this);
1734 HConstant* max_length = Add<HConstant>(JSObject::kInitialMaxFastElementArray);
1735 Add<HBoundsCheck>(length, max_length);
1737 // Generate size calculation code here in order to make it dominate
1738 // the JSRegExpResult allocation.
1739 ElementsKind elements_kind = FAST_ELEMENTS;
1740 HValue* size = BuildCalculateElementsSize(elements_kind, length);
1742 // Allocate the JSRegExpResult and the FixedArray in one step.
1743 HValue* result = Add<HAllocate>(
1744 Add<HConstant>(JSRegExpResult::kSize), HType::JSArray(),
1745 NOT_TENURED, JS_ARRAY_TYPE);
1747 // Initialize the JSRegExpResult header.
1748 HValue* global_object = Add<HLoadNamedField>(
1749 context(), static_cast<HValue*>(NULL),
1750 HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
1751 HValue* native_context = Add<HLoadNamedField>(
1752 global_object, static_cast<HValue*>(NULL),
1753 HObjectAccess::ForGlobalObjectNativeContext());
1754 Add<HStoreNamedField>(
1755 result, HObjectAccess::ForMap(),
1756 Add<HLoadNamedField>(
1757 native_context, static_cast<HValue*>(NULL),
1758 HObjectAccess::ForContextSlot(Context::REGEXP_RESULT_MAP_INDEX)));
1759 HConstant* empty_fixed_array =
1760 Add<HConstant>(isolate()->factory()->empty_fixed_array());
1761 Add<HStoreNamedField>(
1762 result, HObjectAccess::ForJSArrayOffset(JSArray::kPropertiesOffset),
1764 Add<HStoreNamedField>(
1765 result, HObjectAccess::ForJSArrayOffset(JSArray::kElementsOffset),
1767 Add<HStoreNamedField>(
1768 result, HObjectAccess::ForJSArrayOffset(JSArray::kLengthOffset), length);
1770 // Initialize the additional fields.
1771 Add<HStoreNamedField>(
1772 result, HObjectAccess::ForJSArrayOffset(JSRegExpResult::kIndexOffset),
1774 Add<HStoreNamedField>(
1775 result, HObjectAccess::ForJSArrayOffset(JSRegExpResult::kInputOffset),
1778 // Allocate and initialize the elements header.
1779 HAllocate* elements = BuildAllocateElements(elements_kind, size);
1780 BuildInitializeElementsHeader(elements, elements_kind, length);
1782 HConstant* size_in_bytes_upper_bound = EstablishElementsAllocationSize(
1783 elements_kind, max_length->Integer32Value());
1784 elements->set_size_upper_bound(size_in_bytes_upper_bound);
1786 Add<HStoreNamedField>(
1787 result, HObjectAccess::ForJSArrayOffset(JSArray::kElementsOffset),
1790 // Initialize the elements contents with undefined.
1791 BuildFillElementsWithValue(
1792 elements, elements_kind, graph()->GetConstant0(), length,
1793 graph()->GetConstantUndefined());
1799 HValue* HGraphBuilder::BuildNumberToString(HValue* object, Type* type) {
1800 NoObservableSideEffectsScope scope(this);
1802 // Convert constant numbers at compile time.
1803 if (object->IsConstant() && HConstant::cast(object)->HasNumberValue()) {
1804 Handle<Object> number = HConstant::cast(object)->handle(isolate());
1805 Handle<String> result = isolate()->factory()->NumberToString(number);
1806 return Add<HConstant>(result);
1809 // Create a joinable continuation.
1810 HIfContinuation found(graph()->CreateBasicBlock(),
1811 graph()->CreateBasicBlock());
1813 // Load the number string cache.
1814 HValue* number_string_cache =
1815 Add<HLoadRoot>(Heap::kNumberStringCacheRootIndex);
1817 // Make the hash mask from the length of the number string cache. It
1818 // contains two elements (number and string) for each cache entry.
1819 HValue* mask = AddLoadFixedArrayLength(number_string_cache);
1820 mask->set_type(HType::Smi());
1821 mask = AddUncasted<HSar>(mask, graph()->GetConstant1());
1822 mask = AddUncasted<HSub>(mask, graph()->GetConstant1());
1824 // Check whether object is a smi.
1825 IfBuilder if_objectissmi(this);
1826 if_objectissmi.If<HIsSmiAndBranch>(object);
1827 if_objectissmi.Then();
1829 // Compute hash for smi similar to smi_get_hash().
1830 HValue* hash = AddUncasted<HBitwise>(Token::BIT_AND, object, mask);
1833 HValue* key_index = AddUncasted<HShl>(hash, graph()->GetConstant1());
1834 HValue* key = Add<HLoadKeyed>(number_string_cache, key_index,
1835 static_cast<HValue*>(NULL),
1836 FAST_ELEMENTS, ALLOW_RETURN_HOLE);
1838 // Check if object == key.
1839 IfBuilder if_objectiskey(this);
1840 if_objectiskey.If<HCompareObjectEqAndBranch>(object, key);
1841 if_objectiskey.Then();
1843 // Make the key_index available.
1846 if_objectiskey.JoinContinuation(&found);
1848 if_objectissmi.Else();
1850 if (type->Is(Type::SignedSmall())) {
1851 if_objectissmi.Deopt("Expected smi");
1853 // Check if the object is a heap number.
1854 IfBuilder if_objectisnumber(this);
1855 HValue* objectisnumber = if_objectisnumber.If<HCompareMap>(
1856 object, isolate()->factory()->heap_number_map());
1857 if_objectisnumber.Then();
1859 // Compute hash for heap number similar to double_get_hash().
1860 HValue* low = Add<HLoadNamedField>(
1861 object, objectisnumber,
1862 HObjectAccess::ForHeapNumberValueLowestBits());
1863 HValue* high = Add<HLoadNamedField>(
1864 object, objectisnumber,
1865 HObjectAccess::ForHeapNumberValueHighestBits());
1866 HValue* hash = AddUncasted<HBitwise>(Token::BIT_XOR, low, high);
1867 hash = AddUncasted<HBitwise>(Token::BIT_AND, hash, mask);
1870 HValue* key_index = AddUncasted<HShl>(hash, graph()->GetConstant1());
1871 HValue* key = Add<HLoadKeyed>(number_string_cache, key_index,
1872 static_cast<HValue*>(NULL),
1873 FAST_ELEMENTS, ALLOW_RETURN_HOLE);
1875 // Check if the key is a heap number and compare it with the object.
1876 IfBuilder if_keyisnotsmi(this);
1877 HValue* keyisnotsmi = if_keyisnotsmi.IfNot<HIsSmiAndBranch>(key);
1878 if_keyisnotsmi.Then();
1880 IfBuilder if_keyisheapnumber(this);
1881 if_keyisheapnumber.If<HCompareMap>(
1882 key, isolate()->factory()->heap_number_map());
1883 if_keyisheapnumber.Then();
1885 // Check if values of key and object match.
1886 IfBuilder if_keyeqobject(this);
1887 if_keyeqobject.If<HCompareNumericAndBranch>(
1888 Add<HLoadNamedField>(key, keyisnotsmi,
1889 HObjectAccess::ForHeapNumberValue()),
1890 Add<HLoadNamedField>(object, objectisnumber,
1891 HObjectAccess::ForHeapNumberValue()),
1893 if_keyeqobject.Then();
1895 // Make the key_index available.
1898 if_keyeqobject.JoinContinuation(&found);
1900 if_keyisheapnumber.JoinContinuation(&found);
1902 if_keyisnotsmi.JoinContinuation(&found);
1904 if_objectisnumber.Else();
1906 if (type->Is(Type::Number())) {
1907 if_objectisnumber.Deopt("Expected heap number");
1910 if_objectisnumber.JoinContinuation(&found);
1913 if_objectissmi.JoinContinuation(&found);
1915 // Check for cache hit.
1916 IfBuilder if_found(this, &found);
1919 // Count number to string operation in native code.
1920 AddIncrementCounter(isolate()->counters()->number_to_string_native());
1922 // Load the value in case of cache hit.
1923 HValue* key_index = Pop();
1924 HValue* value_index = AddUncasted<HAdd>(key_index, graph()->GetConstant1());
1925 Push(Add<HLoadKeyed>(number_string_cache, value_index,
1926 static_cast<HValue*>(NULL),
1927 FAST_ELEMENTS, ALLOW_RETURN_HOLE));
1931 // Cache miss, fallback to runtime.
1932 Add<HPushArguments>(object);
1933 Push(Add<HCallRuntime>(
1934 isolate()->factory()->empty_string(),
1935 Runtime::FunctionForId(Runtime::kHiddenNumberToStringSkipCache),
1944 HAllocate* HGraphBuilder::BuildAllocate(
1945 HValue* object_size,
1947 InstanceType instance_type,
1948 HAllocationMode allocation_mode) {
1949 // Compute the effective allocation size.
1950 HValue* size = object_size;
1951 if (allocation_mode.CreateAllocationMementos()) {
1952 size = AddUncasted<HAdd>(size, Add<HConstant>(AllocationMemento::kSize));
1953 size->ClearFlag(HValue::kCanOverflow);
1956 // Perform the actual allocation.
1957 HAllocate* object = Add<HAllocate>(
1958 size, type, allocation_mode.GetPretenureMode(),
1959 instance_type, allocation_mode.feedback_site());
1961 // Setup the allocation memento.
1962 if (allocation_mode.CreateAllocationMementos()) {
1963 BuildCreateAllocationMemento(
1964 object, object_size, allocation_mode.current_site());
1971 HValue* HGraphBuilder::BuildAddStringLengths(HValue* left_length,
1972 HValue* right_length) {
1973 // Compute the combined string length and check against max string length.
1974 HValue* length = AddUncasted<HAdd>(left_length, right_length);
1975 // Check that length <= kMaxLength <=> length < MaxLength + 1.
1976 HValue* max_length = Add<HConstant>(String::kMaxLength + 1);
1977 Add<HBoundsCheck>(length, max_length);
1982 HValue* HGraphBuilder::BuildCreateConsString(
1986 HAllocationMode allocation_mode) {
1987 // Determine the string instance types.
1988 HInstruction* left_instance_type = AddLoadStringInstanceType(left);
1989 HInstruction* right_instance_type = AddLoadStringInstanceType(right);
1991 // Allocate the cons string object. HAllocate does not care whether we
1992 // pass CONS_STRING_TYPE or CONS_ASCII_STRING_TYPE here, so we just use
1993 // CONS_STRING_TYPE here. Below we decide whether the cons string is
1994 // one-byte or two-byte and set the appropriate map.
1995 ASSERT(HAllocate::CompatibleInstanceTypes(CONS_STRING_TYPE,
1996 CONS_ASCII_STRING_TYPE));
1997 HAllocate* result = BuildAllocate(Add<HConstant>(ConsString::kSize),
1998 HType::String(), CONS_STRING_TYPE,
2001 // Compute intersection and difference of instance types.
2002 HValue* anded_instance_types = AddUncasted<HBitwise>(
2003 Token::BIT_AND, left_instance_type, right_instance_type);
2004 HValue* xored_instance_types = AddUncasted<HBitwise>(
2005 Token::BIT_XOR, left_instance_type, right_instance_type);
2007 // We create a one-byte cons string if
2008 // 1. both strings are one-byte, or
2009 // 2. at least one of the strings is two-byte, but happens to contain only
2010 // one-byte characters.
2011 // To do this, we check
2012 // 1. if both strings are one-byte, or if the one-byte data hint is set in
2014 // 2. if one of the strings has the one-byte data hint set and the other
2015 // string is one-byte.
2016 IfBuilder if_onebyte(this);
2017 STATIC_ASSERT(kOneByteStringTag != 0);
2018 STATIC_ASSERT(kOneByteDataHintMask != 0);
2019 if_onebyte.If<HCompareNumericAndBranch>(
2020 AddUncasted<HBitwise>(
2021 Token::BIT_AND, anded_instance_types,
2022 Add<HConstant>(static_cast<int32_t>(
2023 kStringEncodingMask | kOneByteDataHintMask))),
2024 graph()->GetConstant0(), Token::NE);
2026 STATIC_ASSERT(kOneByteStringTag != 0 &&
2027 kOneByteDataHintTag != 0 &&
2028 kOneByteDataHintTag != kOneByteStringTag);
2029 if_onebyte.If<HCompareNumericAndBranch>(
2030 AddUncasted<HBitwise>(
2031 Token::BIT_AND, xored_instance_types,
2032 Add<HConstant>(static_cast<int32_t>(
2033 kOneByteStringTag | kOneByteDataHintTag))),
2034 Add<HConstant>(static_cast<int32_t>(
2035 kOneByteStringTag | kOneByteDataHintTag)), Token::EQ);
2038 // We can safely skip the write barrier for storing the map here.
2039 Add<HStoreNamedField>(
2040 result, HObjectAccess::ForMap(),
2041 Add<HConstant>(isolate()->factory()->cons_ascii_string_map()));
2045 // We can safely skip the write barrier for storing the map here.
2046 Add<HStoreNamedField>(
2047 result, HObjectAccess::ForMap(),
2048 Add<HConstant>(isolate()->factory()->cons_string_map()));
2052 // Initialize the cons string fields.
2053 Add<HStoreNamedField>(result, HObjectAccess::ForStringHashField(),
2054 Add<HConstant>(String::kEmptyHashField));
2055 Add<HStoreNamedField>(result, HObjectAccess::ForStringLength(), length);
2056 Add<HStoreNamedField>(result, HObjectAccess::ForConsStringFirst(), left);
2057 Add<HStoreNamedField>(result, HObjectAccess::ForConsStringSecond(), right);
2059 // Count the native string addition.
2060 AddIncrementCounter(isolate()->counters()->string_add_native());
2066 void HGraphBuilder::BuildCopySeqStringChars(HValue* src,
2068 String::Encoding src_encoding,
2071 String::Encoding dst_encoding,
2073 ASSERT(dst_encoding != String::ONE_BYTE_ENCODING ||
2074 src_encoding == String::ONE_BYTE_ENCODING);
2075 LoopBuilder loop(this, context(), LoopBuilder::kPostIncrement);
2076 HValue* index = loop.BeginBody(graph()->GetConstant0(), length, Token::LT);
2078 HValue* src_index = AddUncasted<HAdd>(src_offset, index);
2080 AddUncasted<HSeqStringGetChar>(src_encoding, src, src_index);
2081 HValue* dst_index = AddUncasted<HAdd>(dst_offset, index);
2082 Add<HSeqStringSetChar>(dst_encoding, dst, dst_index, value);
2088 HValue* HGraphBuilder::BuildObjectSizeAlignment(
2089 HValue* unaligned_size, int header_size) {
2090 ASSERT((header_size & kObjectAlignmentMask) == 0);
2091 HValue* size = AddUncasted<HAdd>(
2092 unaligned_size, Add<HConstant>(static_cast<int32_t>(
2093 header_size + kObjectAlignmentMask)));
2094 size->ClearFlag(HValue::kCanOverflow);
2095 return AddUncasted<HBitwise>(
2096 Token::BIT_AND, size, Add<HConstant>(static_cast<int32_t>(
2097 ~kObjectAlignmentMask)));
2101 HValue* HGraphBuilder::BuildUncheckedStringAdd(
2104 HAllocationMode allocation_mode) {
2105 // Determine the string lengths.
2106 HValue* left_length = AddLoadStringLength(left);
2107 HValue* right_length = AddLoadStringLength(right);
2109 // Compute the combined string length.
2110 HValue* length = BuildAddStringLengths(left_length, right_length);
2112 // Do some manual constant folding here.
2113 if (left_length->IsConstant()) {
2114 HConstant* c_left_length = HConstant::cast(left_length);
2115 ASSERT_NE(0, c_left_length->Integer32Value());
2116 if (c_left_length->Integer32Value() + 1 >= ConsString::kMinLength) {
2117 // The right string contains at least one character.
2118 return BuildCreateConsString(length, left, right, allocation_mode);
2120 } else if (right_length->IsConstant()) {
2121 HConstant* c_right_length = HConstant::cast(right_length);
2122 ASSERT_NE(0, c_right_length->Integer32Value());
2123 if (c_right_length->Integer32Value() + 1 >= ConsString::kMinLength) {
2124 // The left string contains at least one character.
2125 return BuildCreateConsString(length, left, right, allocation_mode);
2129 // Check if we should create a cons string.
2130 IfBuilder if_createcons(this);
2131 if_createcons.If<HCompareNumericAndBranch>(
2132 length, Add<HConstant>(ConsString::kMinLength), Token::GTE);
2133 if_createcons.Then();
2135 // Create a cons string.
2136 Push(BuildCreateConsString(length, left, right, allocation_mode));
2138 if_createcons.Else();
2140 // Determine the string instance types.
2141 HValue* left_instance_type = AddLoadStringInstanceType(left);
2142 HValue* right_instance_type = AddLoadStringInstanceType(right);
2144 // Compute union and difference of instance types.
2145 HValue* ored_instance_types = AddUncasted<HBitwise>(
2146 Token::BIT_OR, left_instance_type, right_instance_type);
2147 HValue* xored_instance_types = AddUncasted<HBitwise>(
2148 Token::BIT_XOR, left_instance_type, right_instance_type);
2150 // Check if both strings have the same encoding and both are
2152 IfBuilder if_sameencodingandsequential(this);
2153 if_sameencodingandsequential.If<HCompareNumericAndBranch>(
2154 AddUncasted<HBitwise>(
2155 Token::BIT_AND, xored_instance_types,
2156 Add<HConstant>(static_cast<int32_t>(kStringEncodingMask))),
2157 graph()->GetConstant0(), Token::EQ);
2158 if_sameencodingandsequential.And();
2159 STATIC_ASSERT(kSeqStringTag == 0);
2160 if_sameencodingandsequential.If<HCompareNumericAndBranch>(
2161 AddUncasted<HBitwise>(
2162 Token::BIT_AND, ored_instance_types,
2163 Add<HConstant>(static_cast<int32_t>(kStringRepresentationMask))),
2164 graph()->GetConstant0(), Token::EQ);
2165 if_sameencodingandsequential.Then();
2167 HConstant* string_map =
2168 Add<HConstant>(isolate()->factory()->string_map());
2169 HConstant* ascii_string_map =
2170 Add<HConstant>(isolate()->factory()->ascii_string_map());
2172 // Determine map and size depending on whether result is one-byte string.
2173 IfBuilder if_onebyte(this);
2174 STATIC_ASSERT(kOneByteStringTag != 0);
2175 if_onebyte.If<HCompareNumericAndBranch>(
2176 AddUncasted<HBitwise>(
2177 Token::BIT_AND, ored_instance_types,
2178 Add<HConstant>(static_cast<int32_t>(kStringEncodingMask))),
2179 graph()->GetConstant0(), Token::NE);
2182 // Allocate sequential one-byte string object.
2184 Push(ascii_string_map);
2188 // Allocate sequential two-byte string object.
2189 HValue* size = AddUncasted<HShl>(length, graph()->GetConstant1());
2190 size->ClearFlag(HValue::kCanOverflow);
2191 size->SetFlag(HValue::kUint32);
2196 HValue* map = Pop();
2198 // Calculate the number of bytes needed for the characters in the
2199 // string while observing object alignment.
2200 STATIC_ASSERT((SeqString::kHeaderSize & kObjectAlignmentMask) == 0);
2201 HValue* size = BuildObjectSizeAlignment(Pop(), SeqString::kHeaderSize);
2203 // Allocate the string object. HAllocate does not care whether we pass
2204 // STRING_TYPE or ASCII_STRING_TYPE here, so we just use STRING_TYPE here.
2205 HAllocate* result = BuildAllocate(
2206 size, HType::String(), STRING_TYPE, allocation_mode);
2207 Add<HStoreNamedField>(result, HObjectAccess::ForMap(), map);
2209 // Initialize the string fields.
2210 Add<HStoreNamedField>(result, HObjectAccess::ForStringHashField(),
2211 Add<HConstant>(String::kEmptyHashField));
2212 Add<HStoreNamedField>(result, HObjectAccess::ForStringLength(), length);
2214 // Copy characters to the result string.
2215 IfBuilder if_twobyte(this);
2216 if_twobyte.If<HCompareObjectEqAndBranch>(map, string_map);
2219 // Copy characters from the left string.
2220 BuildCopySeqStringChars(
2221 left, graph()->GetConstant0(), String::TWO_BYTE_ENCODING,
2222 result, graph()->GetConstant0(), String::TWO_BYTE_ENCODING,
2225 // Copy characters from the right string.
2226 BuildCopySeqStringChars(
2227 right, graph()->GetConstant0(), String::TWO_BYTE_ENCODING,
2228 result, left_length, String::TWO_BYTE_ENCODING,
2233 // Copy characters from the left string.
2234 BuildCopySeqStringChars(
2235 left, graph()->GetConstant0(), String::ONE_BYTE_ENCODING,
2236 result, graph()->GetConstant0(), String::ONE_BYTE_ENCODING,
2239 // Copy characters from the right string.
2240 BuildCopySeqStringChars(
2241 right, graph()->GetConstant0(), String::ONE_BYTE_ENCODING,
2242 result, left_length, String::ONE_BYTE_ENCODING,
2247 // Count the native string addition.
2248 AddIncrementCounter(isolate()->counters()->string_add_native());
2250 // Return the sequential string.
2253 if_sameencodingandsequential.Else();
2255 // Fallback to the runtime to add the two strings.
2256 Add<HPushArguments>(left, right);
2257 Push(Add<HCallRuntime>(
2258 isolate()->factory()->empty_string(),
2259 Runtime::FunctionForId(Runtime::kHiddenStringAdd),
2262 if_sameencodingandsequential.End();
2264 if_createcons.End();
2270 HValue* HGraphBuilder::BuildStringAdd(
2273 HAllocationMode allocation_mode) {
2274 NoObservableSideEffectsScope no_effects(this);
2276 // Determine string lengths.
2277 HValue* left_length = AddLoadStringLength(left);
2278 HValue* right_length = AddLoadStringLength(right);
2280 // Check if left string is empty.
2281 IfBuilder if_leftempty(this);
2282 if_leftempty.If<HCompareNumericAndBranch>(
2283 left_length, graph()->GetConstant0(), Token::EQ);
2284 if_leftempty.Then();
2286 // Count the native string addition.
2287 AddIncrementCounter(isolate()->counters()->string_add_native());
2289 // Just return the right string.
2292 if_leftempty.Else();
2294 // Check if right string is empty.
2295 IfBuilder if_rightempty(this);
2296 if_rightempty.If<HCompareNumericAndBranch>(
2297 right_length, graph()->GetConstant0(), Token::EQ);
2298 if_rightempty.Then();
2300 // Count the native string addition.
2301 AddIncrementCounter(isolate()->counters()->string_add_native());
2303 // Just return the left string.
2306 if_rightempty.Else();
2308 // Add the two non-empty strings.
2309 Push(BuildUncheckedStringAdd(left, right, allocation_mode));
2311 if_rightempty.End();
2319 HInstruction* HGraphBuilder::BuildUncheckedMonomorphicElementAccess(
2320 HValue* checked_object,
2324 ElementsKind elements_kind,
2325 PropertyAccessType access_type,
2326 LoadKeyedHoleMode load_mode,
2327 KeyedAccessStoreMode store_mode) {
2328 ASSERT((!IsExternalArrayElementsKind(elements_kind) &&
2329 !IsFixedTypedArrayElementsKind(elements_kind)) ||
2331 // No GVNFlag is necessary for ElementsKind if there is an explicit dependency
2332 // on a HElementsTransition instruction. The flag can also be removed if the
2333 // map to check has FAST_HOLEY_ELEMENTS, since there can be no further
2334 // ElementsKind transitions. Finally, the dependency can be removed for stores
2335 // for FAST_ELEMENTS, since a transition to HOLEY elements won't change the
2336 // generated store code.
2337 if ((elements_kind == FAST_HOLEY_ELEMENTS) ||
2338 (elements_kind == FAST_ELEMENTS && access_type == STORE)) {
2339 checked_object->ClearDependsOnFlag(kElementsKind);
2342 bool fast_smi_only_elements = IsFastSmiElementsKind(elements_kind);
2343 bool fast_elements = IsFastObjectElementsKind(elements_kind);
2344 HValue* elements = AddLoadElements(checked_object);
2345 if (access_type == STORE && (fast_elements || fast_smi_only_elements) &&
2346 store_mode != STORE_NO_TRANSITION_HANDLE_COW) {
2347 HCheckMaps* check_cow_map = Add<HCheckMaps>(
2348 elements, isolate()->factory()->fixed_array_map());
2349 check_cow_map->ClearDependsOnFlag(kElementsKind);
2351 HInstruction* length = NULL;
2353 length = Add<HLoadNamedField>(
2354 checked_object->ActualValue(), checked_object,
2355 HObjectAccess::ForArrayLength(elements_kind));
2357 length = AddLoadFixedArrayLength(elements);
2359 length->set_type(HType::Smi());
2360 HValue* checked_key = NULL;
2361 if (IsExternalArrayElementsKind(elements_kind) ||
2362 IsFixedTypedArrayElementsKind(elements_kind)) {
2363 HValue* backing_store;
2364 if (IsExternalArrayElementsKind(elements_kind)) {
2365 backing_store = Add<HLoadNamedField>(
2366 elements, static_cast<HValue*>(NULL),
2367 HObjectAccess::ForExternalArrayExternalPointer());
2369 backing_store = elements;
2371 if (store_mode == STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
2372 NoObservableSideEffectsScope no_effects(this);
2373 IfBuilder length_checker(this);
2374 length_checker.If<HCompareNumericAndBranch>(key, length, Token::LT);
2375 length_checker.Then();
2376 IfBuilder negative_checker(this);
2377 HValue* bounds_check = negative_checker.If<HCompareNumericAndBranch>(
2378 key, graph()->GetConstant0(), Token::GTE);
2379 negative_checker.Then();
2380 HInstruction* result = AddElementAccess(
2381 backing_store, key, val, bounds_check, elements_kind, access_type);
2382 negative_checker.ElseDeopt("Negative key encountered");
2383 negative_checker.End();
2384 length_checker.End();
2387 ASSERT(store_mode == STANDARD_STORE);
2388 checked_key = Add<HBoundsCheck>(key, length);
2389 return AddElementAccess(
2390 backing_store, checked_key, val,
2391 checked_object, elements_kind, access_type);
2394 ASSERT(fast_smi_only_elements ||
2396 IsFastDoubleElementsKind(elements_kind));
2398 // In case val is stored into a fast smi array, assure that the value is a smi
2399 // before manipulating the backing store. Otherwise the actual store may
2400 // deopt, leaving the backing store in an invalid state.
2401 if (access_type == STORE && IsFastSmiElementsKind(elements_kind) &&
2402 !val->type().IsSmi()) {
2403 val = AddUncasted<HForceRepresentation>(val, Representation::Smi());
2406 if (IsGrowStoreMode(store_mode)) {
2407 NoObservableSideEffectsScope no_effects(this);
2408 elements = BuildCheckForCapacityGrow(checked_object, elements,
2409 elements_kind, length, key,
2410 is_js_array, access_type);
2413 checked_key = Add<HBoundsCheck>(key, length);
2415 if (access_type == STORE && (fast_elements || fast_smi_only_elements)) {
2416 if (store_mode == STORE_NO_TRANSITION_HANDLE_COW) {
2417 NoObservableSideEffectsScope no_effects(this);
2418 elements = BuildCopyElementsOnWrite(checked_object, elements,
2419 elements_kind, length);
2421 HCheckMaps* check_cow_map = Add<HCheckMaps>(
2422 elements, isolate()->factory()->fixed_array_map());
2423 check_cow_map->ClearDependsOnFlag(kElementsKind);
2427 return AddElementAccess(elements, checked_key, val, checked_object,
2428 elements_kind, access_type, load_mode);
2432 HValue* HGraphBuilder::BuildAllocateArrayFromLength(
2433 JSArrayBuilder* array_builder,
2434 HValue* length_argument) {
2435 if (length_argument->IsConstant() &&
2436 HConstant::cast(length_argument)->HasSmiValue()) {
2437 int array_length = HConstant::cast(length_argument)->Integer32Value();
2438 if (array_length == 0) {
2439 return array_builder->AllocateEmptyArray();
2441 return array_builder->AllocateArray(length_argument,
2447 HValue* constant_zero = graph()->GetConstant0();
2448 HConstant* max_alloc_length =
2449 Add<HConstant>(JSObject::kInitialMaxFastElementArray);
2450 HInstruction* checked_length = Add<HBoundsCheck>(length_argument,
2452 IfBuilder if_builder(this);
2453 if_builder.If<HCompareNumericAndBranch>(checked_length, constant_zero,
2456 const int initial_capacity = JSArray::kPreallocatedArrayElements;
2457 HConstant* initial_capacity_node = Add<HConstant>(initial_capacity);
2458 Push(initial_capacity_node); // capacity
2459 Push(constant_zero); // length
2461 if (!(top_info()->IsStub()) &&
2462 IsFastPackedElementsKind(array_builder->kind())) {
2463 // We'll come back later with better (holey) feedback.
2464 if_builder.Deopt("Holey array despite packed elements_kind feedback");
2466 Push(checked_length); // capacity
2467 Push(checked_length); // length
2471 // Figure out total size
2472 HValue* length = Pop();
2473 HValue* capacity = Pop();
2474 return array_builder->AllocateArray(capacity, max_alloc_length, length);
2478 HValue* HGraphBuilder::BuildCalculateElementsSize(ElementsKind kind,
2480 int elements_size = IsFastDoubleElementsKind(kind)
2484 HConstant* elements_size_value = Add<HConstant>(elements_size);
2485 HInstruction* mul = HMul::NewImul(zone(), context(),
2486 capacity->ActualValue(),
2487 elements_size_value);
2488 AddInstruction(mul);
2489 mul->ClearFlag(HValue::kCanOverflow);
2491 STATIC_ASSERT(FixedDoubleArray::kHeaderSize == FixedArray::kHeaderSize);
2493 HConstant* header_size = Add<HConstant>(FixedArray::kHeaderSize);
2494 HValue* total_size = AddUncasted<HAdd>(mul, header_size);
2495 total_size->ClearFlag(HValue::kCanOverflow);
2500 HAllocate* HGraphBuilder::AllocateJSArrayObject(AllocationSiteMode mode) {
2501 int base_size = JSArray::kSize;
2502 if (mode == TRACK_ALLOCATION_SITE) {
2503 base_size += AllocationMemento::kSize;
2505 HConstant* size_in_bytes = Add<HConstant>(base_size);
2506 return Add<HAllocate>(
2507 size_in_bytes, HType::JSArray(), NOT_TENURED, JS_OBJECT_TYPE);
2511 HConstant* HGraphBuilder::EstablishElementsAllocationSize(
2514 int base_size = IsFastDoubleElementsKind(kind)
2515 ? FixedDoubleArray::SizeFor(capacity)
2516 : FixedArray::SizeFor(capacity);
2518 return Add<HConstant>(base_size);
2522 HAllocate* HGraphBuilder::BuildAllocateElements(ElementsKind kind,
2523 HValue* size_in_bytes) {
2524 InstanceType instance_type = IsFastDoubleElementsKind(kind)
2525 ? FIXED_DOUBLE_ARRAY_TYPE
2528 return Add<HAllocate>(size_in_bytes, HType::HeapObject(), NOT_TENURED,
2533 void HGraphBuilder::BuildInitializeElementsHeader(HValue* elements,
2536 Factory* factory = isolate()->factory();
2537 Handle<Map> map = IsFastDoubleElementsKind(kind)
2538 ? factory->fixed_double_array_map()
2539 : factory->fixed_array_map();
2541 Add<HStoreNamedField>(elements, HObjectAccess::ForMap(), Add<HConstant>(map));
2542 Add<HStoreNamedField>(elements, HObjectAccess::ForFixedArrayLength(),
2547 HValue* HGraphBuilder::BuildAllocateElementsAndInitializeElementsHeader(
2550 // The HForceRepresentation is to prevent possible deopt on int-smi
2551 // conversion after allocation but before the new object fields are set.
2552 capacity = AddUncasted<HForceRepresentation>(capacity, Representation::Smi());
2553 HValue* size_in_bytes = BuildCalculateElementsSize(kind, capacity);
2554 HValue* new_elements = BuildAllocateElements(kind, size_in_bytes);
2555 BuildInitializeElementsHeader(new_elements, kind, capacity);
2556 return new_elements;
2560 void HGraphBuilder::BuildJSArrayHeader(HValue* array,
2563 AllocationSiteMode mode,
2564 ElementsKind elements_kind,
2565 HValue* allocation_site_payload,
2566 HValue* length_field) {
2567 Add<HStoreNamedField>(array, HObjectAccess::ForMap(), array_map);
2569 HConstant* empty_fixed_array =
2570 Add<HConstant>(isolate()->factory()->empty_fixed_array());
2572 Add<HStoreNamedField>(
2573 array, HObjectAccess::ForPropertiesPointer(), empty_fixed_array);
2575 Add<HStoreNamedField>(
2576 array, HObjectAccess::ForElementsPointer(),
2577 elements != NULL ? elements : empty_fixed_array);
2579 Add<HStoreNamedField>(
2580 array, HObjectAccess::ForArrayLength(elements_kind), length_field);
2582 if (mode == TRACK_ALLOCATION_SITE) {
2583 BuildCreateAllocationMemento(
2584 array, Add<HConstant>(JSArray::kSize), allocation_site_payload);
2589 HInstruction* HGraphBuilder::AddElementAccess(
2591 HValue* checked_key,
2594 ElementsKind elements_kind,
2595 PropertyAccessType access_type,
2596 LoadKeyedHoleMode load_mode) {
2597 if (access_type == STORE) {
2598 ASSERT(val != NULL);
2599 if (elements_kind == EXTERNAL_UINT8_CLAMPED_ELEMENTS ||
2600 elements_kind == UINT8_CLAMPED_ELEMENTS) {
2601 val = Add<HClampToUint8>(val);
2603 return Add<HStoreKeyed>(elements, checked_key, val, elements_kind,
2604 elements_kind == FAST_SMI_ELEMENTS
2605 ? STORE_TO_INITIALIZED_ENTRY
2606 : INITIALIZING_STORE);
2609 ASSERT(access_type == LOAD);
2610 ASSERT(val == NULL);
2611 HLoadKeyed* load = Add<HLoadKeyed>(
2612 elements, checked_key, dependency, elements_kind, load_mode);
2613 if (FLAG_opt_safe_uint32_operations &&
2614 (elements_kind == EXTERNAL_UINT32_ELEMENTS ||
2615 elements_kind == UINT32_ELEMENTS)) {
2616 graph()->RecordUint32Instruction(load);
2622 HLoadNamedField* HGraphBuilder::AddLoadMap(HValue* object,
2623 HValue* dependency) {
2624 return Add<HLoadNamedField>(object, dependency, HObjectAccess::ForMap());
2628 HLoadNamedField* HGraphBuilder::AddLoadElements(HValue* object,
2629 HValue* dependency) {
2630 return Add<HLoadNamedField>(
2631 object, dependency, HObjectAccess::ForElementsPointer());
2635 HLoadNamedField* HGraphBuilder::AddLoadFixedArrayLength(
2637 HValue* dependency) {
2638 return Add<HLoadNamedField>(
2639 array, dependency, HObjectAccess::ForFixedArrayLength());
2643 HLoadNamedField* HGraphBuilder::AddLoadArrayLength(HValue* array,
2645 HValue* dependency) {
2646 return Add<HLoadNamedField>(
2647 array, dependency, HObjectAccess::ForArrayLength(kind));
2651 HValue* HGraphBuilder::BuildNewElementsCapacity(HValue* old_capacity) {
2652 HValue* half_old_capacity = AddUncasted<HShr>(old_capacity,
2653 graph_->GetConstant1());
2655 HValue* new_capacity = AddUncasted<HAdd>(half_old_capacity, old_capacity);
2656 new_capacity->ClearFlag(HValue::kCanOverflow);
2658 HValue* min_growth = Add<HConstant>(16);
2660 new_capacity = AddUncasted<HAdd>(new_capacity, min_growth);
2661 new_capacity->ClearFlag(HValue::kCanOverflow);
2663 return new_capacity;
2667 HValue* HGraphBuilder::BuildGrowElementsCapacity(HValue* object,
2670 ElementsKind new_kind,
2672 HValue* new_capacity) {
2673 Add<HBoundsCheck>(new_capacity, Add<HConstant>(
2674 (Page::kMaxRegularHeapObjectSize - FixedArray::kHeaderSize) >>
2675 ElementsKindToShiftSize(kind)));
2677 HValue* new_elements = BuildAllocateElementsAndInitializeElementsHeader(
2678 new_kind, new_capacity);
2680 BuildCopyElements(elements, kind, new_elements,
2681 new_kind, length, new_capacity);
2683 Add<HStoreNamedField>(object, HObjectAccess::ForElementsPointer(),
2686 return new_elements;
2690 void HGraphBuilder::BuildFillElementsWithValue(HValue* elements,
2691 ElementsKind elements_kind,
2696 to = AddLoadFixedArrayLength(elements);
2699 // Special loop unfolding case
2700 STATIC_ASSERT(JSArray::kPreallocatedArrayElements <=
2701 kElementLoopUnrollThreshold);
2702 int initial_capacity = -1;
2703 if (from->IsInteger32Constant() && to->IsInteger32Constant()) {
2704 int constant_from = from->GetInteger32Constant();
2705 int constant_to = to->GetInteger32Constant();
2707 if (constant_from == 0 && constant_to <= kElementLoopUnrollThreshold) {
2708 initial_capacity = constant_to;
2712 // Since we're about to store a hole value, the store instruction below must
2713 // assume an elements kind that supports heap object values.
2714 if (IsFastSmiOrObjectElementsKind(elements_kind)) {
2715 elements_kind = FAST_HOLEY_ELEMENTS;
2718 if (initial_capacity >= 0) {
2719 for (int i = 0; i < initial_capacity; i++) {
2720 HInstruction* key = Add<HConstant>(i);
2721 Add<HStoreKeyed>(elements, key, value, elements_kind);
2724 // Carefully loop backwards so that the "from" remains live through the loop
2725 // rather than the to. This often corresponds to keeping length live rather
2726 // then capacity, which helps register allocation, since length is used more
2727 // other than capacity after filling with holes.
2728 LoopBuilder builder(this, context(), LoopBuilder::kPostDecrement);
2730 HValue* key = builder.BeginBody(to, from, Token::GT);
2732 HValue* adjusted_key = AddUncasted<HSub>(key, graph()->GetConstant1());
2733 adjusted_key->ClearFlag(HValue::kCanOverflow);
2735 Add<HStoreKeyed>(elements, adjusted_key, value, elements_kind);
2742 void HGraphBuilder::BuildFillElementsWithHole(HValue* elements,
2743 ElementsKind elements_kind,
2746 // Fast elements kinds need to be initialized in case statements below cause a
2747 // garbage collection.
2748 Factory* factory = isolate()->factory();
2750 double nan_double = FixedDoubleArray::hole_nan_as_double();
2751 HValue* hole = IsFastSmiOrObjectElementsKind(elements_kind)
2752 ? Add<HConstant>(factory->the_hole_value())
2753 : Add<HConstant>(nan_double);
2755 BuildFillElementsWithValue(elements, elements_kind, from, to, hole);
2759 void HGraphBuilder::BuildCopyElements(HValue* from_elements,
2760 ElementsKind from_elements_kind,
2761 HValue* to_elements,
2762 ElementsKind to_elements_kind,
2765 int constant_capacity = -1;
2766 if (capacity != NULL &&
2767 capacity->IsConstant() &&
2768 HConstant::cast(capacity)->HasInteger32Value()) {
2769 int constant_candidate = HConstant::cast(capacity)->Integer32Value();
2770 if (constant_candidate <= kElementLoopUnrollThreshold) {
2771 constant_capacity = constant_candidate;
2775 bool pre_fill_with_holes =
2776 IsFastDoubleElementsKind(from_elements_kind) &&
2777 IsFastObjectElementsKind(to_elements_kind);
2778 if (pre_fill_with_holes) {
2779 // If the copy might trigger a GC, make sure that the FixedArray is
2780 // pre-initialized with holes to make sure that it's always in a
2781 // consistent state.
2782 BuildFillElementsWithHole(to_elements, to_elements_kind,
2783 graph()->GetConstant0(), NULL);
2786 if (constant_capacity != -1) {
2787 // Unroll the loop for small elements kinds.
2788 for (int i = 0; i < constant_capacity; i++) {
2789 HValue* key_constant = Add<HConstant>(i);
2790 HInstruction* value = Add<HLoadKeyed>(from_elements, key_constant,
2791 static_cast<HValue*>(NULL),
2792 from_elements_kind);
2793 Add<HStoreKeyed>(to_elements, key_constant, value, to_elements_kind);
2796 if (!pre_fill_with_holes &&
2797 (capacity == NULL || !length->Equals(capacity))) {
2798 BuildFillElementsWithHole(to_elements, to_elements_kind,
2802 if (capacity == NULL) {
2803 capacity = AddLoadFixedArrayLength(to_elements);
2806 LoopBuilder builder(this, context(), LoopBuilder::kPostDecrement);
2808 HValue* key = builder.BeginBody(length, graph()->GetConstant0(),
2811 key = AddUncasted<HSub>(key, graph()->GetConstant1());
2812 key->ClearFlag(HValue::kCanOverflow);
2814 HValue* element = Add<HLoadKeyed>(from_elements, key,
2815 static_cast<HValue*>(NULL),
2819 ElementsKind kind = (IsHoleyElementsKind(from_elements_kind) &&
2820 IsFastSmiElementsKind(to_elements_kind))
2821 ? FAST_HOLEY_ELEMENTS : to_elements_kind;
2823 if (IsHoleyElementsKind(from_elements_kind) &&
2824 from_elements_kind != to_elements_kind) {
2825 IfBuilder if_hole(this);
2826 if_hole.If<HCompareHoleAndBranch>(element);
2828 HConstant* hole_constant = IsFastDoubleElementsKind(to_elements_kind)
2829 ? Add<HConstant>(FixedDoubleArray::hole_nan_as_double())
2830 : graph()->GetConstantHole();
2831 Add<HStoreKeyed>(to_elements, key, hole_constant, kind);
2833 HStoreKeyed* store = Add<HStoreKeyed>(to_elements, key, element, kind);
2834 store->SetFlag(HValue::kAllowUndefinedAsNaN);
2837 HStoreKeyed* store = Add<HStoreKeyed>(to_elements, key, element, kind);
2838 store->SetFlag(HValue::kAllowUndefinedAsNaN);
2844 Counters* counters = isolate()->counters();
2845 AddIncrementCounter(counters->inlined_copied_elements());
2849 HValue* HGraphBuilder::BuildCloneShallowArrayCow(HValue* boilerplate,
2850 HValue* allocation_site,
2851 AllocationSiteMode mode,
2852 ElementsKind kind) {
2853 HAllocate* array = AllocateJSArrayObject(mode);
2855 HValue* map = AddLoadMap(boilerplate);
2856 HValue* elements = AddLoadElements(boilerplate);
2857 HValue* length = AddLoadArrayLength(boilerplate, kind);
2859 BuildJSArrayHeader(array,
2870 HValue* HGraphBuilder::BuildCloneShallowArrayEmpty(HValue* boilerplate,
2871 HValue* allocation_site,
2872 AllocationSiteMode mode) {
2873 HAllocate* array = AllocateJSArrayObject(mode);
2875 HValue* map = AddLoadMap(boilerplate);
2877 BuildJSArrayHeader(array,
2879 NULL, // set elements to empty fixed array
2883 graph()->GetConstant0());
2888 HValue* HGraphBuilder::BuildCloneShallowArrayNonEmpty(HValue* boilerplate,
2889 HValue* allocation_site,
2890 AllocationSiteMode mode,
2891 ElementsKind kind) {
2892 HValue* boilerplate_elements = AddLoadElements(boilerplate);
2893 HValue* capacity = AddLoadFixedArrayLength(boilerplate_elements);
2895 // Generate size calculation code here in order to make it dominate
2896 // the JSArray allocation.
2897 HValue* elements_size = BuildCalculateElementsSize(kind, capacity);
2899 // Create empty JSArray object for now, store elimination should remove
2900 // redundant initialization of elements and length fields and at the same
2901 // time the object will be fully prepared for GC if it happens during
2902 // elements allocation.
2903 HValue* result = BuildCloneShallowArrayEmpty(
2904 boilerplate, allocation_site, mode);
2906 HAllocate* elements = BuildAllocateElements(kind, elements_size);
2908 // This function implicitly relies on the fact that the
2909 // FastCloneShallowArrayStub is called only for literals shorter than
2910 // JSObject::kInitialMaxFastElementArray.
2911 // Can't add HBoundsCheck here because otherwise the stub will eager a frame.
2912 HConstant* size_upper_bound = EstablishElementsAllocationSize(
2913 kind, JSObject::kInitialMaxFastElementArray);
2914 elements->set_size_upper_bound(size_upper_bound);
2916 Add<HStoreNamedField>(result, HObjectAccess::ForElementsPointer(), elements);
2918 // The allocation for the cloned array above causes register pressure on
2919 // machines with low register counts. Force a reload of the boilerplate
2920 // elements here to free up a register for the allocation to avoid unnecessary
2922 boilerplate_elements = AddLoadElements(boilerplate);
2923 boilerplate_elements->SetFlag(HValue::kCantBeReplaced);
2925 // Copy the elements array header.
2926 for (int i = 0; i < FixedArrayBase::kHeaderSize; i += kPointerSize) {
2927 HObjectAccess access = HObjectAccess::ForFixedArrayHeader(i);
2928 Add<HStoreNamedField>(elements, access,
2929 Add<HLoadNamedField>(boilerplate_elements,
2930 static_cast<HValue*>(NULL), access));
2933 // And the result of the length
2934 HValue* length = AddLoadArrayLength(boilerplate, kind);
2935 Add<HStoreNamedField>(result, HObjectAccess::ForArrayLength(kind), length);
2937 BuildCopyElements(boilerplate_elements, kind, elements,
2938 kind, length, NULL);
2943 void HGraphBuilder::BuildCompareNil(
2946 HIfContinuation* continuation) {
2947 IfBuilder if_nil(this);
2948 bool some_case_handled = false;
2949 bool some_case_missing = false;
2951 if (type->Maybe(Type::Null())) {
2952 if (some_case_handled) if_nil.Or();
2953 if_nil.If<HCompareObjectEqAndBranch>(value, graph()->GetConstantNull());
2954 some_case_handled = true;
2956 some_case_missing = true;
2959 if (type->Maybe(Type::Undefined())) {
2960 if (some_case_handled) if_nil.Or();
2961 if_nil.If<HCompareObjectEqAndBranch>(value,
2962 graph()->GetConstantUndefined());
2963 some_case_handled = true;
2965 some_case_missing = true;
2968 if (type->Maybe(Type::Undetectable())) {
2969 if (some_case_handled) if_nil.Or();
2970 if_nil.If<HIsUndetectableAndBranch>(value);
2971 some_case_handled = true;
2973 some_case_missing = true;
2976 if (some_case_missing) {
2979 if (type->NumClasses() == 1) {
2980 BuildCheckHeapObject(value);
2981 // For ICs, the map checked below is a sentinel map that gets replaced by
2982 // the monomorphic map when the code is used as a template to generate a
2983 // new IC. For optimized functions, there is no sentinel map, the map
2984 // emitted below is the actual monomorphic map.
2985 Add<HCheckMaps>(value, type->Classes().Current());
2987 if_nil.Deopt("Too many undetectable types");
2991 if_nil.CaptureContinuation(continuation);
2995 void HGraphBuilder::BuildCreateAllocationMemento(
2996 HValue* previous_object,
2997 HValue* previous_object_size,
2998 HValue* allocation_site) {
2999 ASSERT(allocation_site != NULL);
3000 HInnerAllocatedObject* allocation_memento = Add<HInnerAllocatedObject>(
3001 previous_object, previous_object_size, HType::HeapObject());
3002 AddStoreMapConstant(
3003 allocation_memento, isolate()->factory()->allocation_memento_map());
3004 Add<HStoreNamedField>(
3006 HObjectAccess::ForAllocationMementoSite(),
3008 if (FLAG_allocation_site_pretenuring) {
3009 HValue* memento_create_count = Add<HLoadNamedField>(
3010 allocation_site, static_cast<HValue*>(NULL),
3011 HObjectAccess::ForAllocationSiteOffset(
3012 AllocationSite::kPretenureCreateCountOffset));
3013 memento_create_count = AddUncasted<HAdd>(
3014 memento_create_count, graph()->GetConstant1());
3015 // This smi value is reset to zero after every gc, overflow isn't a problem
3016 // since the counter is bounded by the new space size.
3017 memento_create_count->ClearFlag(HValue::kCanOverflow);
3018 Add<HStoreNamedField>(
3019 allocation_site, HObjectAccess::ForAllocationSiteOffset(
3020 AllocationSite::kPretenureCreateCountOffset), memento_create_count);
3025 HInstruction* HGraphBuilder::BuildGetNativeContext(HValue* closure) {
3026 // Get the global context, then the native context
3027 HInstruction* context =
3028 Add<HLoadNamedField>(closure, static_cast<HValue*>(NULL),
3029 HObjectAccess::ForFunctionContextPointer());
3030 HInstruction* global_object = Add<HLoadNamedField>(
3031 context, static_cast<HValue*>(NULL),
3032 HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
3033 HObjectAccess access = HObjectAccess::ForObservableJSObjectOffset(
3034 GlobalObject::kNativeContextOffset);
3035 return Add<HLoadNamedField>(
3036 global_object, static_cast<HValue*>(NULL), access);
3040 HInstruction* HGraphBuilder::BuildGetNativeContext() {
3041 // Get the global context, then the native context
3042 HValue* global_object = Add<HLoadNamedField>(
3043 context(), static_cast<HValue*>(NULL),
3044 HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
3045 return Add<HLoadNamedField>(
3046 global_object, static_cast<HValue*>(NULL),
3047 HObjectAccess::ForObservableJSObjectOffset(
3048 GlobalObject::kNativeContextOffset));
3052 HInstruction* HGraphBuilder::BuildGetArrayFunction() {
3053 HInstruction* native_context = BuildGetNativeContext();
3054 HInstruction* index =
3055 Add<HConstant>(static_cast<int32_t>(Context::ARRAY_FUNCTION_INDEX));
3056 return Add<HLoadKeyed>(
3057 native_context, index, static_cast<HValue*>(NULL), FAST_ELEMENTS);
3061 HGraphBuilder::JSArrayBuilder::JSArrayBuilder(HGraphBuilder* builder,
3063 HValue* allocation_site_payload,
3064 HValue* constructor_function,
3065 AllocationSiteOverrideMode override_mode) :
3068 allocation_site_payload_(allocation_site_payload),
3069 constructor_function_(constructor_function) {
3070 ASSERT(!allocation_site_payload->IsConstant() ||
3071 HConstant::cast(allocation_site_payload)->handle(
3072 builder_->isolate())->IsAllocationSite());
3073 mode_ = override_mode == DISABLE_ALLOCATION_SITES
3074 ? DONT_TRACK_ALLOCATION_SITE
3075 : AllocationSite::GetMode(kind);
3079 HGraphBuilder::JSArrayBuilder::JSArrayBuilder(HGraphBuilder* builder,
3081 HValue* constructor_function) :
3084 mode_(DONT_TRACK_ALLOCATION_SITE),
3085 allocation_site_payload_(NULL),
3086 constructor_function_(constructor_function) {
3090 HValue* HGraphBuilder::JSArrayBuilder::EmitMapCode() {
3091 if (!builder()->top_info()->IsStub()) {
3092 // A constant map is fine.
3093 Handle<Map> map(builder()->isolate()->get_initial_js_array_map(kind_),
3094 builder()->isolate());
3095 return builder()->Add<HConstant>(map);
3098 if (constructor_function_ != NULL && kind_ == GetInitialFastElementsKind()) {
3099 // No need for a context lookup if the kind_ matches the initial
3100 // map, because we can just load the map in that case.
3101 HObjectAccess access = HObjectAccess::ForPrototypeOrInitialMap();
3102 return builder()->Add<HLoadNamedField>(
3103 constructor_function_, static_cast<HValue*>(NULL), access);
3106 // TODO(mvstanton): we should always have a constructor function if we
3107 // are creating a stub.
3108 HInstruction* native_context = constructor_function_ != NULL
3109 ? builder()->BuildGetNativeContext(constructor_function_)
3110 : builder()->BuildGetNativeContext();
3112 HInstruction* index = builder()->Add<HConstant>(
3113 static_cast<int32_t>(Context::JS_ARRAY_MAPS_INDEX));
3115 HInstruction* map_array = builder()->Add<HLoadKeyed>(
3116 native_context, index, static_cast<HValue*>(NULL), FAST_ELEMENTS);
3118 HInstruction* kind_index = builder()->Add<HConstant>(kind_);
3120 return builder()->Add<HLoadKeyed>(
3121 map_array, kind_index, static_cast<HValue*>(NULL), FAST_ELEMENTS);
3125 HValue* HGraphBuilder::JSArrayBuilder::EmitInternalMapCode() {
3126 // Find the map near the constructor function
3127 HObjectAccess access = HObjectAccess::ForPrototypeOrInitialMap();
3128 return builder()->Add<HLoadNamedField>(
3129 constructor_function_, static_cast<HValue*>(NULL), access);
3133 HAllocate* HGraphBuilder::JSArrayBuilder::AllocateEmptyArray() {
3134 HConstant* capacity = builder()->Add<HConstant>(initial_capacity());
3135 return AllocateArray(capacity,
3137 builder()->graph()->GetConstant0());
3141 HAllocate* HGraphBuilder::JSArrayBuilder::AllocateArray(
3143 HConstant* capacity_upper_bound,
3144 HValue* length_field,
3145 FillMode fill_mode) {
3146 return AllocateArray(capacity,
3147 capacity_upper_bound->GetInteger32Constant(),
3153 HAllocate* HGraphBuilder::JSArrayBuilder::AllocateArray(
3155 int capacity_upper_bound,
3156 HValue* length_field,
3157 FillMode fill_mode) {
3158 HConstant* elememts_size_upper_bound = capacity->IsInteger32Constant()
3159 ? HConstant::cast(capacity)
3160 : builder()->EstablishElementsAllocationSize(kind_, capacity_upper_bound);
3162 HAllocate* array = AllocateArray(capacity, length_field, fill_mode);
3163 if (!elements_location_->has_size_upper_bound()) {
3164 elements_location_->set_size_upper_bound(elememts_size_upper_bound);
3170 HAllocate* HGraphBuilder::JSArrayBuilder::AllocateArray(
3172 HValue* length_field,
3173 FillMode fill_mode) {
3174 // These HForceRepresentations are because we store these as fields in the
3175 // objects we construct, and an int32-to-smi HChange could deopt. Accept
3176 // the deopt possibility now, before allocation occurs.
3178 builder()->AddUncasted<HForceRepresentation>(capacity,
3179 Representation::Smi());
3181 builder()->AddUncasted<HForceRepresentation>(length_field,
3182 Representation::Smi());
3184 // Generate size calculation code here in order to make it dominate
3185 // the JSArray allocation.
3186 HValue* elements_size =
3187 builder()->BuildCalculateElementsSize(kind_, capacity);
3189 // Allocate (dealing with failure appropriately)
3190 HAllocate* array_object = builder()->AllocateJSArrayObject(mode_);
3192 // Fill in the fields: map, properties, length
3194 if (allocation_site_payload_ == NULL) {
3195 map = EmitInternalMapCode();
3197 map = EmitMapCode();
3200 builder()->BuildJSArrayHeader(array_object,
3202 NULL, // set elements to empty fixed array
3205 allocation_site_payload_,
3208 // Allocate and initialize the elements
3209 elements_location_ = builder()->BuildAllocateElements(kind_, elements_size);
3211 builder()->BuildInitializeElementsHeader(elements_location_, kind_, capacity);
3214 builder()->Add<HStoreNamedField>(
3215 array_object, HObjectAccess::ForElementsPointer(), elements_location_);
3217 if (fill_mode == FILL_WITH_HOLE) {
3218 builder()->BuildFillElementsWithHole(elements_location_, kind_,
3219 graph()->GetConstant0(), capacity);
3222 return array_object;
3226 HValue* HGraphBuilder::AddLoadJSBuiltin(Builtins::JavaScript builtin) {
3227 HValue* global_object = Add<HLoadNamedField>(
3228 context(), static_cast<HValue*>(NULL),
3229 HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
3230 HObjectAccess access = HObjectAccess::ForObservableJSObjectOffset(
3231 GlobalObject::kBuiltinsOffset);
3232 HValue* builtins = Add<HLoadNamedField>(
3233 global_object, static_cast<HValue*>(NULL), access);
3234 HObjectAccess function_access = HObjectAccess::ForObservableJSObjectOffset(
3235 JSBuiltinsObject::OffsetOfFunctionWithId(builtin));
3236 return Add<HLoadNamedField>(
3237 builtins, static_cast<HValue*>(NULL), function_access);
3241 HOptimizedGraphBuilder::HOptimizedGraphBuilder(CompilationInfo* info)
3242 : HGraphBuilder(info),
3243 function_state_(NULL),
3244 initial_function_state_(this, info, NORMAL_RETURN, 0),
3248 globals_(10, info->zone()),
3249 inline_bailout_(false),
3250 osr_(new(info->zone()) HOsrBuilder(this)) {
3251 // This is not initialized in the initializer list because the
3252 // constructor for the initial state relies on function_state_ == NULL
3253 // to know it's the initial state.
3254 function_state_= &initial_function_state_;
3255 InitializeAstVisitor(info->zone());
3256 if (FLAG_hydrogen_track_positions) {
3257 SetSourcePosition(info->shared_info()->start_position());
3262 HBasicBlock* HOptimizedGraphBuilder::CreateJoin(HBasicBlock* first,
3263 HBasicBlock* second,
3264 BailoutId join_id) {
3265 if (first == NULL) {
3267 } else if (second == NULL) {
3270 HBasicBlock* join_block = graph()->CreateBasicBlock();
3271 Goto(first, join_block);
3272 Goto(second, join_block);
3273 join_block->SetJoinId(join_id);
3279 HBasicBlock* HOptimizedGraphBuilder::JoinContinue(IterationStatement* statement,
3280 HBasicBlock* exit_block,
3281 HBasicBlock* continue_block) {
3282 if (continue_block != NULL) {
3283 if (exit_block != NULL) Goto(exit_block, continue_block);
3284 continue_block->SetJoinId(statement->ContinueId());
3285 return continue_block;
3291 HBasicBlock* HOptimizedGraphBuilder::CreateLoop(IterationStatement* statement,
3292 HBasicBlock* loop_entry,
3293 HBasicBlock* body_exit,
3294 HBasicBlock* loop_successor,
3295 HBasicBlock* break_block) {
3296 if (body_exit != NULL) Goto(body_exit, loop_entry);
3297 loop_entry->PostProcessLoopHeader(statement);
3298 if (break_block != NULL) {
3299 if (loop_successor != NULL) Goto(loop_successor, break_block);
3300 break_block->SetJoinId(statement->ExitId());
3303 return loop_successor;
3307 // Build a new loop header block and set it as the current block.
3308 HBasicBlock* HOptimizedGraphBuilder::BuildLoopEntry() {
3309 HBasicBlock* loop_entry = CreateLoopHeaderBlock();
3311 set_current_block(loop_entry);
3316 HBasicBlock* HOptimizedGraphBuilder::BuildLoopEntry(
3317 IterationStatement* statement) {
3318 HBasicBlock* loop_entry = osr()->HasOsrEntryAt(statement)
3319 ? osr()->BuildOsrLoopEntry(statement)
3325 void HBasicBlock::FinishExit(HControlInstruction* instruction,
3326 HSourcePosition position) {
3327 Finish(instruction, position);
3332 HGraph::HGraph(CompilationInfo* info)
3333 : isolate_(info->isolate()),
3336 blocks_(8, info->zone()),
3337 values_(16, info->zone()),
3339 uint32_instructions_(NULL),
3342 zone_(info->zone()),
3343 is_recursive_(false),
3344 use_optimistic_licm_(false),
3345 depends_on_empty_array_proto_elements_(false),
3346 type_change_checksum_(0),
3347 maximum_environment_size_(0),
3348 no_side_effects_scope_count_(0),
3349 disallow_adding_new_values_(false),
3351 inlined_functions_(5, info->zone()) {
3352 if (info->IsStub()) {
3353 HydrogenCodeStub* stub = info->code_stub();
3354 CodeStubInterfaceDescriptor* descriptor = stub->GetInterfaceDescriptor();
3355 start_environment_ =
3356 new(zone_) HEnvironment(zone_, descriptor->environment_length());
3358 TraceInlinedFunction(info->shared_info(), HSourcePosition::Unknown());
3359 start_environment_ =
3360 new(zone_) HEnvironment(NULL, info->scope(), info->closure(), zone_);
3362 start_environment_->set_ast_id(BailoutId::FunctionEntry());
3363 entry_block_ = CreateBasicBlock();
3364 entry_block_->SetInitialEnvironment(start_environment_);
3368 HBasicBlock* HGraph::CreateBasicBlock() {
3369 HBasicBlock* result = new(zone()) HBasicBlock(this);
3370 blocks_.Add(result, zone());
3375 void HGraph::FinalizeUniqueness() {
3376 DisallowHeapAllocation no_gc;
3377 ASSERT(!OptimizingCompilerThread::IsOptimizerThread(isolate()));
3378 for (int i = 0; i < blocks()->length(); ++i) {
3379 for (HInstructionIterator it(blocks()->at(i)); !it.Done(); it.Advance()) {
3380 it.Current()->FinalizeUniqueness();
3386 int HGraph::TraceInlinedFunction(
3387 Handle<SharedFunctionInfo> shared,
3388 HSourcePosition position) {
3389 if (!FLAG_hydrogen_track_positions) {
3394 for (; id < inlined_functions_.length(); id++) {
3395 if (inlined_functions_[id].shared().is_identical_to(shared)) {
3400 if (id == inlined_functions_.length()) {
3401 inlined_functions_.Add(InlinedFunctionInfo(shared), zone());
3403 if (!shared->script()->IsUndefined()) {
3404 Handle<Script> script(Script::cast(shared->script()));
3405 if (!script->source()->IsUndefined()) {
3406 CodeTracer::Scope tracing_scope(isolate()->GetCodeTracer());
3407 PrintF(tracing_scope.file(),
3408 "--- FUNCTION SOURCE (%s) id{%d,%d} ---\n",
3409 shared->DebugName()->ToCString().get(),
3410 info()->optimization_id(),
3414 ConsStringIteratorOp op;
3415 StringCharacterStream stream(String::cast(script->source()),
3417 shared->start_position());
3418 // fun->end_position() points to the last character in the stream. We
3419 // need to compensate by adding one to calculate the length.
3421 shared->end_position() - shared->start_position() + 1;
3422 for (int i = 0; i < source_len; i++) {
3423 if (stream.HasMore()) {
3424 PrintF(tracing_scope.file(), "%c", stream.GetNext());
3429 PrintF(tracing_scope.file(), "\n--- END ---\n");
3434 int inline_id = next_inline_id_++;
3436 if (inline_id != 0) {
3437 CodeTracer::Scope tracing_scope(isolate()->GetCodeTracer());
3438 PrintF(tracing_scope.file(), "INLINE (%s) id{%d,%d} AS %d AT ",
3439 shared->DebugName()->ToCString().get(),
3440 info()->optimization_id(),
3443 position.PrintTo(tracing_scope.file());
3444 PrintF(tracing_scope.file(), "\n");
3451 int HGraph::SourcePositionToScriptPosition(HSourcePosition pos) {
3452 if (!FLAG_hydrogen_track_positions || pos.IsUnknown()) {
3456 return inlined_functions_[pos.inlining_id()].start_position() +
3461 // Block ordering was implemented with two mutually recursive methods,
3462 // HGraph::Postorder and HGraph::PostorderLoopBlocks.
3463 // The recursion could lead to stack overflow so the algorithm has been
3464 // implemented iteratively.
3465 // At a high level the algorithm looks like this:
3467 // Postorder(block, loop_header) : {
3468 // if (block has already been visited or is of another loop) return;
3469 // mark block as visited;
3470 // if (block is a loop header) {
3471 // VisitLoopMembers(block, loop_header);
3472 // VisitSuccessorsOfLoopHeader(block);
3474 // VisitSuccessors(block)
3476 // put block in result list;
3479 // VisitLoopMembers(block, outer_loop_header) {
3480 // foreach (block b in block loop members) {
3481 // VisitSuccessorsOfLoopMember(b, outer_loop_header);
3482 // if (b is loop header) VisitLoopMembers(b);
3486 // VisitSuccessorsOfLoopMember(block, outer_loop_header) {
3487 // foreach (block b in block successors) Postorder(b, outer_loop_header)
3490 // VisitSuccessorsOfLoopHeader(block) {
3491 // foreach (block b in block successors) Postorder(b, block)
3494 // VisitSuccessors(block, loop_header) {
3495 // foreach (block b in block successors) Postorder(b, loop_header)
3498 // The ordering is started calling Postorder(entry, NULL).
3500 // Each instance of PostorderProcessor represents the "stack frame" of the
3501 // recursion, and particularly keeps the state of the loop (iteration) of the
3502 // "Visit..." function it represents.
3503 // To recycle memory we keep all the frames in a double linked list but
3504 // this means that we cannot use constructors to initialize the frames.
3506 class PostorderProcessor : public ZoneObject {
3508 // Back link (towards the stack bottom).
3509 PostorderProcessor* parent() {return father_; }
3510 // Forward link (towards the stack top).
3511 PostorderProcessor* child() {return child_; }
3512 HBasicBlock* block() { return block_; }
3513 HLoopInformation* loop() { return loop_; }
3514 HBasicBlock* loop_header() { return loop_header_; }
3516 static PostorderProcessor* CreateEntryProcessor(Zone* zone,
3517 HBasicBlock* block) {
3518 PostorderProcessor* result = new(zone) PostorderProcessor(NULL);
3519 return result->SetupSuccessors(zone, block, NULL);
3522 PostorderProcessor* PerformStep(Zone* zone,
3523 ZoneList<HBasicBlock*>* order) {
3524 PostorderProcessor* next =
3525 PerformNonBacktrackingStep(zone, order);
3529 return Backtrack(zone, order);
3534 explicit PostorderProcessor(PostorderProcessor* father)
3535 : father_(father), child_(NULL), successor_iterator(NULL) { }
3537 // Each enum value states the cycle whose state is kept by this instance.
3541 SUCCESSORS_OF_LOOP_HEADER,
3543 SUCCESSORS_OF_LOOP_MEMBER
3546 // Each "Setup..." method is like a constructor for a cycle state.
3547 PostorderProcessor* SetupSuccessors(Zone* zone,
3549 HBasicBlock* loop_header) {
3550 if (block == NULL || block->IsOrdered() ||
3551 block->parent_loop_header() != loop_header) {
3555 loop_header_ = NULL;
3560 block->MarkAsOrdered();
3562 if (block->IsLoopHeader()) {
3563 kind_ = SUCCESSORS_OF_LOOP_HEADER;
3564 loop_header_ = block;
3565 InitializeSuccessors();
3566 PostorderProcessor* result = Push(zone);
3567 return result->SetupLoopMembers(zone, block, block->loop_information(),
3570 ASSERT(block->IsFinished());
3572 loop_header_ = loop_header;
3573 InitializeSuccessors();
3579 PostorderProcessor* SetupLoopMembers(Zone* zone,
3581 HLoopInformation* loop,
3582 HBasicBlock* loop_header) {
3583 kind_ = LOOP_MEMBERS;
3586 loop_header_ = loop_header;
3587 InitializeLoopMembers();
3591 PostorderProcessor* SetupSuccessorsOfLoopMember(
3593 HLoopInformation* loop,
3594 HBasicBlock* loop_header) {
3595 kind_ = SUCCESSORS_OF_LOOP_MEMBER;
3598 loop_header_ = loop_header;
3599 InitializeSuccessors();
3603 // This method "allocates" a new stack frame.
3604 PostorderProcessor* Push(Zone* zone) {
3605 if (child_ == NULL) {
3606 child_ = new(zone) PostorderProcessor(this);
3611 void ClosePostorder(ZoneList<HBasicBlock*>* order, Zone* zone) {
3612 ASSERT(block_->end()->FirstSuccessor() == NULL ||
3613 order->Contains(block_->end()->FirstSuccessor()) ||
3614 block_->end()->FirstSuccessor()->IsLoopHeader());
3615 ASSERT(block_->end()->SecondSuccessor() == NULL ||
3616 order->Contains(block_->end()->SecondSuccessor()) ||
3617 block_->end()->SecondSuccessor()->IsLoopHeader());
3618 order->Add(block_, zone);
3621 // This method is the basic block to walk up the stack.
3622 PostorderProcessor* Pop(Zone* zone,
3623 ZoneList<HBasicBlock*>* order) {
3626 case SUCCESSORS_OF_LOOP_HEADER:
3627 ClosePostorder(order, zone);
3631 case SUCCESSORS_OF_LOOP_MEMBER:
3632 if (block()->IsLoopHeader() && block() != loop_->loop_header()) {
3633 // In this case we need to perform a LOOP_MEMBERS cycle so we
3634 // initialize it and return this instead of father.
3635 return SetupLoopMembers(zone, block(),
3636 block()->loop_information(), loop_header_);
3647 // Walks up the stack.
3648 PostorderProcessor* Backtrack(Zone* zone,
3649 ZoneList<HBasicBlock*>* order) {
3650 PostorderProcessor* parent = Pop(zone, order);
3651 while (parent != NULL) {
3652 PostorderProcessor* next =
3653 parent->PerformNonBacktrackingStep(zone, order);
3657 parent = parent->Pop(zone, order);
3663 PostorderProcessor* PerformNonBacktrackingStep(
3665 ZoneList<HBasicBlock*>* order) {
3666 HBasicBlock* next_block;
3669 next_block = AdvanceSuccessors();
3670 if (next_block != NULL) {
3671 PostorderProcessor* result = Push(zone);
3672 return result->SetupSuccessors(zone, next_block, loop_header_);
3675 case SUCCESSORS_OF_LOOP_HEADER:
3676 next_block = AdvanceSuccessors();
3677 if (next_block != NULL) {
3678 PostorderProcessor* result = Push(zone);
3679 return result->SetupSuccessors(zone, next_block, block());
3683 next_block = AdvanceLoopMembers();
3684 if (next_block != NULL) {
3685 PostorderProcessor* result = Push(zone);
3686 return result->SetupSuccessorsOfLoopMember(next_block,
3687 loop_, loop_header_);
3690 case SUCCESSORS_OF_LOOP_MEMBER:
3691 next_block = AdvanceSuccessors();
3692 if (next_block != NULL) {
3693 PostorderProcessor* result = Push(zone);
3694 return result->SetupSuccessors(zone, next_block, loop_header_);
3703 // The following two methods implement a "foreach b in successors" cycle.
3704 void InitializeSuccessors() {
3707 successor_iterator = HSuccessorIterator(block_->end());
3710 HBasicBlock* AdvanceSuccessors() {
3711 if (!successor_iterator.Done()) {
3712 HBasicBlock* result = successor_iterator.Current();
3713 successor_iterator.Advance();
3719 // The following two methods implement a "foreach b in loop members" cycle.
3720 void InitializeLoopMembers() {
3722 loop_length = loop_->blocks()->length();
3725 HBasicBlock* AdvanceLoopMembers() {
3726 if (loop_index < loop_length) {
3727 HBasicBlock* result = loop_->blocks()->at(loop_index);
3736 PostorderProcessor* father_;
3737 PostorderProcessor* child_;
3738 HLoopInformation* loop_;
3739 HBasicBlock* block_;
3740 HBasicBlock* loop_header_;
3743 HSuccessorIterator successor_iterator;
3747 void HGraph::OrderBlocks() {
3748 CompilationPhase phase("H_Block ordering", info());
3751 // Initially the blocks must not be ordered.
3752 for (int i = 0; i < blocks_.length(); ++i) {
3753 ASSERT(!blocks_[i]->IsOrdered());
3757 PostorderProcessor* postorder =
3758 PostorderProcessor::CreateEntryProcessor(zone(), blocks_[0]);
3761 postorder = postorder->PerformStep(zone(), &blocks_);
3765 // Now all blocks must be marked as ordered.
3766 for (int i = 0; i < blocks_.length(); ++i) {
3767 ASSERT(blocks_[i]->IsOrdered());
3771 // Reverse block list and assign block IDs.
3772 for (int i = 0, j = blocks_.length(); --j >= i; ++i) {
3773 HBasicBlock* bi = blocks_[i];
3774 HBasicBlock* bj = blocks_[j];
3775 bi->set_block_id(j);
3776 bj->set_block_id(i);
3783 void HGraph::AssignDominators() {
3784 HPhase phase("H_Assign dominators", this);
3785 for (int i = 0; i < blocks_.length(); ++i) {
3786 HBasicBlock* block = blocks_[i];
3787 if (block->IsLoopHeader()) {
3788 // Only the first predecessor of a loop header is from outside the loop.
3789 // All others are back edges, and thus cannot dominate the loop header.
3790 block->AssignCommonDominator(block->predecessors()->first());
3791 block->AssignLoopSuccessorDominators();
3793 for (int j = blocks_[i]->predecessors()->length() - 1; j >= 0; --j) {
3794 blocks_[i]->AssignCommonDominator(blocks_[i]->predecessors()->at(j));
3801 bool HGraph::CheckArgumentsPhiUses() {
3802 int block_count = blocks_.length();
3803 for (int i = 0; i < block_count; ++i) {
3804 for (int j = 0; j < blocks_[i]->phis()->length(); ++j) {
3805 HPhi* phi = blocks_[i]->phis()->at(j);
3806 // We don't support phi uses of arguments for now.
3807 if (phi->CheckFlag(HValue::kIsArguments)) return false;
3814 bool HGraph::CheckConstPhiUses() {
3815 int block_count = blocks_.length();
3816 for (int i = 0; i < block_count; ++i) {
3817 for (int j = 0; j < blocks_[i]->phis()->length(); ++j) {
3818 HPhi* phi = blocks_[i]->phis()->at(j);
3819 // Check for the hole value (from an uninitialized const).
3820 for (int k = 0; k < phi->OperandCount(); k++) {
3821 if (phi->OperandAt(k) == GetConstantHole()) return false;
3829 void HGraph::CollectPhis() {
3830 int block_count = blocks_.length();
3831 phi_list_ = new(zone()) ZoneList<HPhi*>(block_count, zone());
3832 for (int i = 0; i < block_count; ++i) {
3833 for (int j = 0; j < blocks_[i]->phis()->length(); ++j) {
3834 HPhi* phi = blocks_[i]->phis()->at(j);
3835 phi_list_->Add(phi, zone());
3841 // Implementation of utility class to encapsulate the translation state for
3842 // a (possibly inlined) function.
3843 FunctionState::FunctionState(HOptimizedGraphBuilder* owner,
3844 CompilationInfo* info,
3845 InliningKind inlining_kind,
3848 compilation_info_(info),
3849 call_context_(NULL),
3850 inlining_kind_(inlining_kind),
3851 function_return_(NULL),
3852 test_context_(NULL),
3854 arguments_object_(NULL),
3855 arguments_elements_(NULL),
3856 inlining_id_(inlining_id),
3857 outer_source_position_(HSourcePosition::Unknown()),
3858 outer_(owner->function_state()) {
3859 if (outer_ != NULL) {
3860 // State for an inline function.
3861 if (owner->ast_context()->IsTest()) {
3862 HBasicBlock* if_true = owner->graph()->CreateBasicBlock();
3863 HBasicBlock* if_false = owner->graph()->CreateBasicBlock();
3864 if_true->MarkAsInlineReturnTarget(owner->current_block());
3865 if_false->MarkAsInlineReturnTarget(owner->current_block());
3866 TestContext* outer_test_context = TestContext::cast(owner->ast_context());
3867 Expression* cond = outer_test_context->condition();
3868 // The AstContext constructor pushed on the context stack. This newed
3869 // instance is the reason that AstContext can't be BASE_EMBEDDED.
3870 test_context_ = new TestContext(owner, cond, if_true, if_false);
3872 function_return_ = owner->graph()->CreateBasicBlock();
3873 function_return()->MarkAsInlineReturnTarget(owner->current_block());
3875 // Set this after possibly allocating a new TestContext above.
3876 call_context_ = owner->ast_context();
3879 // Push on the state stack.
3880 owner->set_function_state(this);
3882 if (FLAG_hydrogen_track_positions) {
3883 outer_source_position_ = owner->source_position();
3884 owner->EnterInlinedSource(
3885 info->shared_info()->start_position(),
3887 owner->SetSourcePosition(info->shared_info()->start_position());
3892 FunctionState::~FunctionState() {
3893 delete test_context_;
3894 owner_->set_function_state(outer_);
3896 if (FLAG_hydrogen_track_positions) {
3897 owner_->set_source_position(outer_source_position_);
3898 owner_->EnterInlinedSource(
3899 outer_->compilation_info()->shared_info()->start_position(),
3900 outer_->inlining_id());
3905 // Implementation of utility classes to represent an expression's context in
3907 AstContext::AstContext(HOptimizedGraphBuilder* owner, Expression::Context kind)
3910 outer_(owner->ast_context()),
3911 for_typeof_(false) {
3912 owner->set_ast_context(this); // Push.
3914 ASSERT(owner->environment()->frame_type() == JS_FUNCTION);
3915 original_length_ = owner->environment()->length();
3920 AstContext::~AstContext() {
3921 owner_->set_ast_context(outer_); // Pop.
3925 EffectContext::~EffectContext() {
3926 ASSERT(owner()->HasStackOverflow() ||
3927 owner()->current_block() == NULL ||
3928 (owner()->environment()->length() == original_length_ &&
3929 owner()->environment()->frame_type() == JS_FUNCTION));
3933 ValueContext::~ValueContext() {
3934 ASSERT(owner()->HasStackOverflow() ||
3935 owner()->current_block() == NULL ||
3936 (owner()->environment()->length() == original_length_ + 1 &&
3937 owner()->environment()->frame_type() == JS_FUNCTION));
3941 void EffectContext::ReturnValue(HValue* value) {
3942 // The value is simply ignored.
3946 void ValueContext::ReturnValue(HValue* value) {
3947 // The value is tracked in the bailout environment, and communicated
3948 // through the environment as the result of the expression.
3949 if (!arguments_allowed() && value->CheckFlag(HValue::kIsArguments)) {
3950 owner()->Bailout(kBadValueContextForArgumentsValue);
3952 owner()->Push(value);
3956 void TestContext::ReturnValue(HValue* value) {
3961 void EffectContext::ReturnInstruction(HInstruction* instr, BailoutId ast_id) {
3962 ASSERT(!instr->IsControlInstruction());
3963 owner()->AddInstruction(instr);
3964 if (instr->HasObservableSideEffects()) {
3965 owner()->Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
3970 void EffectContext::ReturnControl(HControlInstruction* instr,
3972 ASSERT(!instr->HasObservableSideEffects());
3973 HBasicBlock* empty_true = owner()->graph()->CreateBasicBlock();
3974 HBasicBlock* empty_false = owner()->graph()->CreateBasicBlock();
3975 instr->SetSuccessorAt(0, empty_true);
3976 instr->SetSuccessorAt(1, empty_false);
3977 owner()->FinishCurrentBlock(instr);
3978 HBasicBlock* join = owner()->CreateJoin(empty_true, empty_false, ast_id);
3979 owner()->set_current_block(join);
3983 void EffectContext::ReturnContinuation(HIfContinuation* continuation,
3985 HBasicBlock* true_branch = NULL;
3986 HBasicBlock* false_branch = NULL;
3987 continuation->Continue(&true_branch, &false_branch);
3988 if (!continuation->IsTrueReachable()) {
3989 owner()->set_current_block(false_branch);
3990 } else if (!continuation->IsFalseReachable()) {
3991 owner()->set_current_block(true_branch);
3993 HBasicBlock* join = owner()->CreateJoin(true_branch, false_branch, ast_id);
3994 owner()->set_current_block(join);
3999 void ValueContext::ReturnInstruction(HInstruction* instr, BailoutId ast_id) {
4000 ASSERT(!instr->IsControlInstruction());
4001 if (!arguments_allowed() && instr->CheckFlag(HValue::kIsArguments)) {
4002 return owner()->Bailout(kBadValueContextForArgumentsObjectValue);
4004 owner()->AddInstruction(instr);
4005 owner()->Push(instr);
4006 if (instr->HasObservableSideEffects()) {
4007 owner()->Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
4012 void ValueContext::ReturnControl(HControlInstruction* instr, BailoutId ast_id) {
4013 ASSERT(!instr->HasObservableSideEffects());
4014 if (!arguments_allowed() && instr->CheckFlag(HValue::kIsArguments)) {
4015 return owner()->Bailout(kBadValueContextForArgumentsObjectValue);
4017 HBasicBlock* materialize_false = owner()->graph()->CreateBasicBlock();
4018 HBasicBlock* materialize_true = owner()->graph()->CreateBasicBlock();
4019 instr->SetSuccessorAt(0, materialize_true);
4020 instr->SetSuccessorAt(1, materialize_false);
4021 owner()->FinishCurrentBlock(instr);
4022 owner()->set_current_block(materialize_true);
4023 owner()->Push(owner()->graph()->GetConstantTrue());
4024 owner()->set_current_block(materialize_false);
4025 owner()->Push(owner()->graph()->GetConstantFalse());
4027 owner()->CreateJoin(materialize_true, materialize_false, ast_id);
4028 owner()->set_current_block(join);
4032 void ValueContext::ReturnContinuation(HIfContinuation* continuation,
4034 HBasicBlock* materialize_true = NULL;
4035 HBasicBlock* materialize_false = NULL;
4036 continuation->Continue(&materialize_true, &materialize_false);
4037 if (continuation->IsTrueReachable()) {
4038 owner()->set_current_block(materialize_true);
4039 owner()->Push(owner()->graph()->GetConstantTrue());
4040 owner()->set_current_block(materialize_true);
4042 if (continuation->IsFalseReachable()) {
4043 owner()->set_current_block(materialize_false);
4044 owner()->Push(owner()->graph()->GetConstantFalse());
4045 owner()->set_current_block(materialize_false);
4047 if (continuation->TrueAndFalseReachable()) {
4049 owner()->CreateJoin(materialize_true, materialize_false, ast_id);
4050 owner()->set_current_block(join);
4055 void TestContext::ReturnInstruction(HInstruction* instr, BailoutId ast_id) {
4056 ASSERT(!instr->IsControlInstruction());
4057 HOptimizedGraphBuilder* builder = owner();
4058 builder->AddInstruction(instr);
4059 // We expect a simulate after every expression with side effects, though
4060 // this one isn't actually needed (and wouldn't work if it were targeted).
4061 if (instr->HasObservableSideEffects()) {
4062 builder->Push(instr);
4063 builder->Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
4070 void TestContext::ReturnControl(HControlInstruction* instr, BailoutId ast_id) {
4071 ASSERT(!instr->HasObservableSideEffects());
4072 HBasicBlock* empty_true = owner()->graph()->CreateBasicBlock();
4073 HBasicBlock* empty_false = owner()->graph()->CreateBasicBlock();
4074 instr->SetSuccessorAt(0, empty_true);
4075 instr->SetSuccessorAt(1, empty_false);
4076 owner()->FinishCurrentBlock(instr);
4077 owner()->Goto(empty_true, if_true(), owner()->function_state());
4078 owner()->Goto(empty_false, if_false(), owner()->function_state());
4079 owner()->set_current_block(NULL);
4083 void TestContext::ReturnContinuation(HIfContinuation* continuation,
4085 HBasicBlock* true_branch = NULL;
4086 HBasicBlock* false_branch = NULL;
4087 continuation->Continue(&true_branch, &false_branch);
4088 if (continuation->IsTrueReachable()) {
4089 owner()->Goto(true_branch, if_true(), owner()->function_state());
4091 if (continuation->IsFalseReachable()) {
4092 owner()->Goto(false_branch, if_false(), owner()->function_state());
4094 owner()->set_current_block(NULL);
4098 void TestContext::BuildBranch(HValue* value) {
4099 // We expect the graph to be in edge-split form: there is no edge that
4100 // connects a branch node to a join node. We conservatively ensure that
4101 // property by always adding an empty block on the outgoing edges of this
4103 HOptimizedGraphBuilder* builder = owner();
4104 if (value != NULL && value->CheckFlag(HValue::kIsArguments)) {
4105 builder->Bailout(kArgumentsObjectValueInATestContext);
4107 ToBooleanStub::Types expected(condition()->to_boolean_types());
4108 ReturnControl(owner()->New<HBranch>(value, expected), BailoutId::None());
4112 // HOptimizedGraphBuilder infrastructure for bailing out and checking bailouts.
4113 #define CHECK_BAILOUT(call) \
4116 if (HasStackOverflow()) return; \
4120 #define CHECK_ALIVE(call) \
4123 if (HasStackOverflow() || current_block() == NULL) return; \
4127 #define CHECK_ALIVE_OR_RETURN(call, value) \
4130 if (HasStackOverflow() || current_block() == NULL) return value; \
4134 void HOptimizedGraphBuilder::Bailout(BailoutReason reason) {
4135 current_info()->set_bailout_reason(reason);
4140 void HOptimizedGraphBuilder::VisitForEffect(Expression* expr) {
4141 EffectContext for_effect(this);
4146 void HOptimizedGraphBuilder::VisitForValue(Expression* expr,
4147 ArgumentsAllowedFlag flag) {
4148 ValueContext for_value(this, flag);
4153 void HOptimizedGraphBuilder::VisitForTypeOf(Expression* expr) {
4154 ValueContext for_value(this, ARGUMENTS_NOT_ALLOWED);
4155 for_value.set_for_typeof(true);
4160 void HOptimizedGraphBuilder::VisitForControl(Expression* expr,
4161 HBasicBlock* true_block,
4162 HBasicBlock* false_block) {
4163 TestContext for_test(this, expr, true_block, false_block);
4168 void HOptimizedGraphBuilder::VisitExpressions(
4169 ZoneList<Expression*>* exprs) {
4170 for (int i = 0; i < exprs->length(); ++i) {
4171 CHECK_ALIVE(VisitForValue(exprs->at(i)));
4176 bool HOptimizedGraphBuilder::BuildGraph() {
4177 if (current_info()->function()->is_generator()) {
4178 Bailout(kFunctionIsAGenerator);
4181 Scope* scope = current_info()->scope();
4182 if (scope->HasIllegalRedeclaration()) {
4183 Bailout(kFunctionWithIllegalRedeclaration);
4186 if (scope->calls_eval()) {
4187 Bailout(kFunctionCallsEval);
4192 // Add an edge to the body entry. This is warty: the graph's start
4193 // environment will be used by the Lithium translation as the initial
4194 // environment on graph entry, but it has now been mutated by the
4195 // Hydrogen translation of the instructions in the start block. This
4196 // environment uses values which have not been defined yet. These
4197 // Hydrogen instructions will then be replayed by the Lithium
4198 // translation, so they cannot have an environment effect. The edge to
4199 // the body's entry block (along with some special logic for the start
4200 // block in HInstruction::InsertAfter) seals the start block from
4201 // getting unwanted instructions inserted.
4203 // TODO(kmillikin): Fix this. Stop mutating the initial environment.
4204 // Make the Hydrogen instructions in the initial block into Hydrogen
4205 // values (but not instructions), present in the initial environment and
4206 // not replayed by the Lithium translation.
4207 HEnvironment* initial_env = environment()->CopyWithoutHistory();
4208 HBasicBlock* body_entry = CreateBasicBlock(initial_env);
4210 body_entry->SetJoinId(BailoutId::FunctionEntry());
4211 set_current_block(body_entry);
4213 // Handle implicit declaration of the function name in named function
4214 // expressions before other declarations.
4215 if (scope->is_function_scope() && scope->function() != NULL) {
4216 VisitVariableDeclaration(scope->function());
4218 VisitDeclarations(scope->declarations());
4219 Add<HSimulate>(BailoutId::Declarations());
4221 Add<HStackCheck>(HStackCheck::kFunctionEntry);
4223 VisitStatements(current_info()->function()->body());
4224 if (HasStackOverflow()) return false;
4226 if (current_block() != NULL) {
4227 Add<HReturn>(graph()->GetConstantUndefined());
4228 set_current_block(NULL);
4231 // If the checksum of the number of type info changes is the same as the
4232 // last time this function was compiled, then this recompile is likely not
4233 // due to missing/inadequate type feedback, but rather too aggressive
4234 // optimization. Disable optimistic LICM in that case.
4235 Handle<Code> unoptimized_code(current_info()->shared_info()->code());
4236 ASSERT(unoptimized_code->kind() == Code::FUNCTION);
4237 Handle<TypeFeedbackInfo> type_info(
4238 TypeFeedbackInfo::cast(unoptimized_code->type_feedback_info()));
4239 int checksum = type_info->own_type_change_checksum();
4240 int composite_checksum = graph()->update_type_change_checksum(checksum);
4241 graph()->set_use_optimistic_licm(
4242 !type_info->matches_inlined_type_change_checksum(composite_checksum));
4243 type_info->set_inlined_type_change_checksum(composite_checksum);
4245 // Perform any necessary OSR-specific cleanups or changes to the graph.
4246 osr()->FinishGraph();
4252 bool HGraph::Optimize(BailoutReason* bailout_reason) {
4256 // We need to create a HConstant "zero" now so that GVN will fold every
4257 // zero-valued constant in the graph together.
4258 // The constant is needed to make idef-based bounds check work: the pass
4259 // evaluates relations with "zero" and that zero cannot be created after GVN.
4263 // Do a full verify after building the graph and computing dominators.
4267 if (FLAG_analyze_environment_liveness && maximum_environment_size() != 0) {
4268 Run<HEnvironmentLivenessAnalysisPhase>();
4271 if (!CheckConstPhiUses()) {
4272 *bailout_reason = kUnsupportedPhiUseOfConstVariable;
4275 Run<HRedundantPhiEliminationPhase>();
4276 if (!CheckArgumentsPhiUses()) {
4277 *bailout_reason = kUnsupportedPhiUseOfArguments;
4281 // Find and mark unreachable code to simplify optimizations, especially gvn,
4282 // where unreachable code could unnecessarily defeat LICM.
4283 Run<HMarkUnreachableBlocksPhase>();
4285 if (FLAG_dead_code_elimination) Run<HDeadCodeEliminationPhase>();
4286 if (FLAG_use_escape_analysis) Run<HEscapeAnalysisPhase>();
4288 if (FLAG_load_elimination) Run<HLoadEliminationPhase>();
4292 if (has_osr()) osr()->FinishOsrValues();
4294 Run<HInferRepresentationPhase>();
4296 // Remove HSimulate instructions that have turned out not to be needed
4297 // after all by folding them into the following HSimulate.
4298 // This must happen after inferring representations.
4299 Run<HMergeRemovableSimulatesPhase>();
4301 Run<HMarkDeoptimizeOnUndefinedPhase>();
4302 Run<HRepresentationChangesPhase>();
4304 Run<HInferTypesPhase>();
4306 // Must be performed before canonicalization to ensure that Canonicalize
4307 // will not remove semantically meaningful ToInt32 operations e.g. BIT_OR with
4309 if (FLAG_opt_safe_uint32_operations) Run<HUint32AnalysisPhase>();
4311 if (FLAG_use_canonicalizing) Run<HCanonicalizePhase>();
4313 if (FLAG_use_gvn) Run<HGlobalValueNumberingPhase>();
4315 if (FLAG_check_elimination) Run<HCheckEliminationPhase>();
4317 if (FLAG_store_elimination) Run<HStoreEliminationPhase>();
4319 Run<HRangeAnalysisPhase>();
4321 Run<HComputeChangeUndefinedToNaN>();
4323 // Eliminate redundant stack checks on backwards branches.
4324 Run<HStackCheckEliminationPhase>();
4326 if (FLAG_array_bounds_checks_elimination) Run<HBoundsCheckEliminationPhase>();
4327 if (FLAG_array_bounds_checks_hoisting) Run<HBoundsCheckHoistingPhase>();
4328 if (FLAG_array_index_dehoisting) Run<HDehoistIndexComputationsPhase>();
4329 if (FLAG_dead_code_elimination) Run<HDeadCodeEliminationPhase>();
4331 RestoreActualValues();
4333 // Find unreachable code a second time, GVN and other optimizations may have
4334 // made blocks unreachable that were previously reachable.
4335 Run<HMarkUnreachableBlocksPhase>();
4341 void HGraph::RestoreActualValues() {
4342 HPhase phase("H_Restore actual values", this);
4344 for (int block_index = 0; block_index < blocks()->length(); block_index++) {
4345 HBasicBlock* block = blocks()->at(block_index);
4348 for (int i = 0; i < block->phis()->length(); i++) {
4349 HPhi* phi = block->phis()->at(i);
4350 ASSERT(phi->ActualValue() == phi);
4354 for (HInstructionIterator it(block); !it.Done(); it.Advance()) {
4355 HInstruction* instruction = it.Current();
4356 if (instruction->ActualValue() == instruction) continue;
4357 if (instruction->CheckFlag(HValue::kIsDead)) {
4358 // The instruction was marked as deleted but left in the graph
4359 // as a control flow dependency point for subsequent
4361 instruction->DeleteAndReplaceWith(instruction->ActualValue());
4363 ASSERT(instruction->IsInformativeDefinition());
4364 if (instruction->IsPurelyInformativeDefinition()) {
4365 instruction->DeleteAndReplaceWith(instruction->RedefinedOperand());
4367 instruction->ReplaceAllUsesWith(instruction->ActualValue());
4375 void HOptimizedGraphBuilder::PushArgumentsFromEnvironment(int count) {
4376 ZoneList<HValue*> arguments(count, zone());
4377 for (int i = 0; i < count; ++i) {
4378 arguments.Add(Pop(), zone());
4381 HPushArguments* push_args = New<HPushArguments>();
4382 while (!arguments.is_empty()) {
4383 push_args->AddInput(arguments.RemoveLast());
4385 AddInstruction(push_args);
4389 template <class Instruction>
4390 HInstruction* HOptimizedGraphBuilder::PreProcessCall(Instruction* call) {
4391 PushArgumentsFromEnvironment(call->argument_count());
4396 void HOptimizedGraphBuilder::SetUpScope(Scope* scope) {
4397 // First special is HContext.
4398 HInstruction* context = Add<HContext>();
4399 environment()->BindContext(context);
4401 // Create an arguments object containing the initial parameters. Set the
4402 // initial values of parameters including "this" having parameter index 0.
4403 ASSERT_EQ(scope->num_parameters() + 1, environment()->parameter_count());
4404 HArgumentsObject* arguments_object =
4405 New<HArgumentsObject>(environment()->parameter_count());
4406 for (int i = 0; i < environment()->parameter_count(); ++i) {
4407 HInstruction* parameter = Add<HParameter>(i);
4408 arguments_object->AddArgument(parameter, zone());
4409 environment()->Bind(i, parameter);
4411 AddInstruction(arguments_object);
4412 graph()->SetArgumentsObject(arguments_object);
4414 HConstant* undefined_constant = graph()->GetConstantUndefined();
4415 // Initialize specials and locals to undefined.
4416 for (int i = environment()->parameter_count() + 1;
4417 i < environment()->length();
4419 environment()->Bind(i, undefined_constant);
4422 // Handle the arguments and arguments shadow variables specially (they do
4423 // not have declarations).
4424 if (scope->arguments() != NULL) {
4425 if (!scope->arguments()->IsStackAllocated()) {
4426 return Bailout(kContextAllocatedArguments);
4429 environment()->Bind(scope->arguments(),
4430 graph()->GetArgumentsObject());
4435 void HOptimizedGraphBuilder::VisitStatements(ZoneList<Statement*>* statements) {
4436 for (int i = 0; i < statements->length(); i++) {
4437 Statement* stmt = statements->at(i);
4438 CHECK_ALIVE(Visit(stmt));
4439 if (stmt->IsJump()) break;
4444 void HOptimizedGraphBuilder::VisitBlock(Block* stmt) {
4445 ASSERT(!HasStackOverflow());
4446 ASSERT(current_block() != NULL);
4447 ASSERT(current_block()->HasPredecessor());
4449 Scope* outer_scope = scope();
4450 Scope* scope = stmt->scope();
4451 BreakAndContinueInfo break_info(stmt, outer_scope);
4453 { BreakAndContinueScope push(&break_info, this);
4454 if (scope != NULL) {
4455 // Load the function object.
4456 Scope* declaration_scope = scope->DeclarationScope();
4457 HInstruction* function;
4458 HValue* outer_context = environment()->context();
4459 if (declaration_scope->is_global_scope() ||
4460 declaration_scope->is_eval_scope()) {
4461 function = new(zone()) HLoadContextSlot(
4462 outer_context, Context::CLOSURE_INDEX, HLoadContextSlot::kNoCheck);
4464 function = New<HThisFunction>();
4466 AddInstruction(function);
4467 // Allocate a block context and store it to the stack frame.
4468 HInstruction* inner_context = Add<HAllocateBlockContext>(
4469 outer_context, function, scope->GetScopeInfo());
4470 HInstruction* instr = Add<HStoreFrameContext>(inner_context);
4471 if (instr->HasObservableSideEffects()) {
4472 AddSimulate(stmt->EntryId(), REMOVABLE_SIMULATE);
4475 environment()->BindContext(inner_context);
4476 VisitDeclarations(scope->declarations());
4477 AddSimulate(stmt->DeclsId(), REMOVABLE_SIMULATE);
4479 CHECK_BAILOUT(VisitStatements(stmt->statements()));
4481 set_scope(outer_scope);
4482 if (scope != NULL && current_block() != NULL) {
4483 HValue* inner_context = environment()->context();
4484 HValue* outer_context = Add<HLoadNamedField>(
4485 inner_context, static_cast<HValue*>(NULL),
4486 HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX));
4488 HInstruction* instr = Add<HStoreFrameContext>(outer_context);
4489 if (instr->HasObservableSideEffects()) {
4490 AddSimulate(stmt->ExitId(), REMOVABLE_SIMULATE);
4492 environment()->BindContext(outer_context);
4494 HBasicBlock* break_block = break_info.break_block();
4495 if (break_block != NULL) {
4496 if (current_block() != NULL) Goto(break_block);
4497 break_block->SetJoinId(stmt->ExitId());
4498 set_current_block(break_block);
4503 void HOptimizedGraphBuilder::VisitExpressionStatement(
4504 ExpressionStatement* stmt) {
4505 ASSERT(!HasStackOverflow());
4506 ASSERT(current_block() != NULL);
4507 ASSERT(current_block()->HasPredecessor());
4508 VisitForEffect(stmt->expression());
4512 void HOptimizedGraphBuilder::VisitEmptyStatement(EmptyStatement* stmt) {
4513 ASSERT(!HasStackOverflow());
4514 ASSERT(current_block() != NULL);
4515 ASSERT(current_block()->HasPredecessor());
4519 void HOptimizedGraphBuilder::VisitIfStatement(IfStatement* stmt) {
4520 ASSERT(!HasStackOverflow());
4521 ASSERT(current_block() != NULL);
4522 ASSERT(current_block()->HasPredecessor());
4523 if (stmt->condition()->ToBooleanIsTrue()) {
4524 Add<HSimulate>(stmt->ThenId());
4525 Visit(stmt->then_statement());
4526 } else if (stmt->condition()->ToBooleanIsFalse()) {
4527 Add<HSimulate>(stmt->ElseId());
4528 Visit(stmt->else_statement());
4530 HBasicBlock* cond_true = graph()->CreateBasicBlock();
4531 HBasicBlock* cond_false = graph()->CreateBasicBlock();
4532 CHECK_BAILOUT(VisitForControl(stmt->condition(), cond_true, cond_false));
4534 if (cond_true->HasPredecessor()) {
4535 cond_true->SetJoinId(stmt->ThenId());
4536 set_current_block(cond_true);
4537 CHECK_BAILOUT(Visit(stmt->then_statement()));
4538 cond_true = current_block();
4543 if (cond_false->HasPredecessor()) {
4544 cond_false->SetJoinId(stmt->ElseId());
4545 set_current_block(cond_false);
4546 CHECK_BAILOUT(Visit(stmt->else_statement()));
4547 cond_false = current_block();
4552 HBasicBlock* join = CreateJoin(cond_true, cond_false, stmt->IfId());
4553 set_current_block(join);
4558 HBasicBlock* HOptimizedGraphBuilder::BreakAndContinueScope::Get(
4559 BreakableStatement* stmt,
4564 BreakAndContinueScope* current = this;
4565 while (current != NULL && current->info()->target() != stmt) {
4566 *drop_extra += current->info()->drop_extra();
4567 current = current->next();
4569 ASSERT(current != NULL); // Always found (unless stack is malformed).
4570 *scope = current->info()->scope();
4572 if (type == BREAK) {
4573 *drop_extra += current->info()->drop_extra();
4576 HBasicBlock* block = NULL;
4579 block = current->info()->break_block();
4580 if (block == NULL) {
4581 block = current->owner()->graph()->CreateBasicBlock();
4582 current->info()->set_break_block(block);
4587 block = current->info()->continue_block();
4588 if (block == NULL) {
4589 block = current->owner()->graph()->CreateBasicBlock();
4590 current->info()->set_continue_block(block);
4599 void HOptimizedGraphBuilder::VisitContinueStatement(
4600 ContinueStatement* stmt) {
4601 ASSERT(!HasStackOverflow());
4602 ASSERT(current_block() != NULL);
4603 ASSERT(current_block()->HasPredecessor());
4604 Scope* outer_scope = NULL;
4605 Scope* inner_scope = scope();
4607 HBasicBlock* continue_block = break_scope()->Get(
4608 stmt->target(), BreakAndContinueScope::CONTINUE,
4609 &outer_scope, &drop_extra);
4610 HValue* context = environment()->context();
4612 int context_pop_count = inner_scope->ContextChainLength(outer_scope);
4613 if (context_pop_count > 0) {
4614 while (context_pop_count-- > 0) {
4615 HInstruction* context_instruction = Add<HLoadNamedField>(
4616 context, static_cast<HValue*>(NULL),
4617 HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX));
4618 context = context_instruction;
4620 HInstruction* instr = Add<HStoreFrameContext>(context);
4621 if (instr->HasObservableSideEffects()) {
4622 AddSimulate(stmt->target()->EntryId(), REMOVABLE_SIMULATE);
4624 environment()->BindContext(context);
4627 Goto(continue_block);
4628 set_current_block(NULL);
4632 void HOptimizedGraphBuilder::VisitBreakStatement(BreakStatement* stmt) {
4633 ASSERT(!HasStackOverflow());
4634 ASSERT(current_block() != NULL);
4635 ASSERT(current_block()->HasPredecessor());
4636 Scope* outer_scope = NULL;
4637 Scope* inner_scope = scope();
4639 HBasicBlock* break_block = break_scope()->Get(
4640 stmt->target(), BreakAndContinueScope::BREAK,
4641 &outer_scope, &drop_extra);
4642 HValue* context = environment()->context();
4644 int context_pop_count = inner_scope->ContextChainLength(outer_scope);
4645 if (context_pop_count > 0) {
4646 while (context_pop_count-- > 0) {
4647 HInstruction* context_instruction = Add<HLoadNamedField>(
4648 context, static_cast<HValue*>(NULL),
4649 HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX));
4650 context = context_instruction;
4652 HInstruction* instr = Add<HStoreFrameContext>(context);
4653 if (instr->HasObservableSideEffects()) {
4654 AddSimulate(stmt->target()->ExitId(), REMOVABLE_SIMULATE);
4656 environment()->BindContext(context);
4659 set_current_block(NULL);
4663 void HOptimizedGraphBuilder::VisitReturnStatement(ReturnStatement* stmt) {
4664 ASSERT(!HasStackOverflow());
4665 ASSERT(current_block() != NULL);
4666 ASSERT(current_block()->HasPredecessor());
4667 FunctionState* state = function_state();
4668 AstContext* context = call_context();
4669 if (context == NULL) {
4670 // Not an inlined return, so an actual one.
4671 CHECK_ALIVE(VisitForValue(stmt->expression()));
4672 HValue* result = environment()->Pop();
4673 Add<HReturn>(result);
4674 } else if (state->inlining_kind() == CONSTRUCT_CALL_RETURN) {
4675 // Return from an inlined construct call. In a test context the return value
4676 // will always evaluate to true, in a value context the return value needs
4677 // to be a JSObject.
4678 if (context->IsTest()) {
4679 TestContext* test = TestContext::cast(context);
4680 CHECK_ALIVE(VisitForEffect(stmt->expression()));
4681 Goto(test->if_true(), state);
4682 } else if (context->IsEffect()) {
4683 CHECK_ALIVE(VisitForEffect(stmt->expression()));
4684 Goto(function_return(), state);
4686 ASSERT(context->IsValue());
4687 CHECK_ALIVE(VisitForValue(stmt->expression()));
4688 HValue* return_value = Pop();
4689 HValue* receiver = environment()->arguments_environment()->Lookup(0);
4690 HHasInstanceTypeAndBranch* typecheck =
4691 New<HHasInstanceTypeAndBranch>(return_value,
4692 FIRST_SPEC_OBJECT_TYPE,
4693 LAST_SPEC_OBJECT_TYPE);
4694 HBasicBlock* if_spec_object = graph()->CreateBasicBlock();
4695 HBasicBlock* not_spec_object = graph()->CreateBasicBlock();
4696 typecheck->SetSuccessorAt(0, if_spec_object);
4697 typecheck->SetSuccessorAt(1, not_spec_object);
4698 FinishCurrentBlock(typecheck);
4699 AddLeaveInlined(if_spec_object, return_value, state);
4700 AddLeaveInlined(not_spec_object, receiver, state);
4702 } else if (state->inlining_kind() == SETTER_CALL_RETURN) {
4703 // Return from an inlined setter call. The returned value is never used, the
4704 // value of an assignment is always the value of the RHS of the assignment.
4705 CHECK_ALIVE(VisitForEffect(stmt->expression()));
4706 if (context->IsTest()) {
4707 HValue* rhs = environment()->arguments_environment()->Lookup(1);
4708 context->ReturnValue(rhs);
4709 } else if (context->IsEffect()) {
4710 Goto(function_return(), state);
4712 ASSERT(context->IsValue());
4713 HValue* rhs = environment()->arguments_environment()->Lookup(1);
4714 AddLeaveInlined(rhs, state);
4717 // Return from a normal inlined function. Visit the subexpression in the
4718 // expression context of the call.
4719 if (context->IsTest()) {
4720 TestContext* test = TestContext::cast(context);
4721 VisitForControl(stmt->expression(), test->if_true(), test->if_false());
4722 } else if (context->IsEffect()) {
4723 // Visit in value context and ignore the result. This is needed to keep
4724 // environment in sync with full-codegen since some visitors (e.g.
4725 // VisitCountOperation) use the operand stack differently depending on
4727 CHECK_ALIVE(VisitForValue(stmt->expression()));
4729 Goto(function_return(), state);
4731 ASSERT(context->IsValue());
4732 CHECK_ALIVE(VisitForValue(stmt->expression()));
4733 AddLeaveInlined(Pop(), state);
4736 set_current_block(NULL);
4740 void HOptimizedGraphBuilder::VisitWithStatement(WithStatement* stmt) {
4741 ASSERT(!HasStackOverflow());
4742 ASSERT(current_block() != NULL);
4743 ASSERT(current_block()->HasPredecessor());
4744 return Bailout(kWithStatement);
4748 void HOptimizedGraphBuilder::VisitSwitchStatement(SwitchStatement* stmt) {
4749 ASSERT(!HasStackOverflow());
4750 ASSERT(current_block() != NULL);
4751 ASSERT(current_block()->HasPredecessor());
4753 // We only optimize switch statements with a bounded number of clauses.
4754 const int kCaseClauseLimit = 128;
4755 ZoneList<CaseClause*>* clauses = stmt->cases();
4756 int clause_count = clauses->length();
4757 ZoneList<HBasicBlock*> body_blocks(clause_count, zone());
4758 if (clause_count > kCaseClauseLimit) {
4759 return Bailout(kSwitchStatementTooManyClauses);
4762 CHECK_ALIVE(VisitForValue(stmt->tag()));
4763 Add<HSimulate>(stmt->EntryId());
4764 HValue* tag_value = Top();
4765 Type* tag_type = stmt->tag()->bounds().lower;
4767 // 1. Build all the tests, with dangling true branches
4768 BailoutId default_id = BailoutId::None();
4769 for (int i = 0; i < clause_count; ++i) {
4770 CaseClause* clause = clauses->at(i);
4771 if (clause->is_default()) {
4772 body_blocks.Add(NULL, zone());
4773 if (default_id.IsNone()) default_id = clause->EntryId();
4777 // Generate a compare and branch.
4778 CHECK_ALIVE(VisitForValue(clause->label()));
4779 HValue* label_value = Pop();
4781 Type* label_type = clause->label()->bounds().lower;
4782 Type* combined_type = clause->compare_type();
4783 HControlInstruction* compare = BuildCompareInstruction(
4784 Token::EQ_STRICT, tag_value, label_value, tag_type, label_type,
4786 ScriptPositionToSourcePosition(stmt->tag()->position()),
4787 ScriptPositionToSourcePosition(clause->label()->position()),
4788 PUSH_BEFORE_SIMULATE, clause->id());
4790 HBasicBlock* next_test_block = graph()->CreateBasicBlock();
4791 HBasicBlock* body_block = graph()->CreateBasicBlock();
4792 body_blocks.Add(body_block, zone());
4793 compare->SetSuccessorAt(0, body_block);
4794 compare->SetSuccessorAt(1, next_test_block);
4795 FinishCurrentBlock(compare);
4797 set_current_block(body_block);
4798 Drop(1); // tag_value
4800 set_current_block(next_test_block);
4803 // Save the current block to use for the default or to join with the
4805 HBasicBlock* last_block = current_block();
4806 Drop(1); // tag_value
4808 // 2. Loop over the clauses and the linked list of tests in lockstep,
4809 // translating the clause bodies.
4810 HBasicBlock* fall_through_block = NULL;
4812 BreakAndContinueInfo break_info(stmt, scope());
4813 { BreakAndContinueScope push(&break_info, this);
4814 for (int i = 0; i < clause_count; ++i) {
4815 CaseClause* clause = clauses->at(i);
4817 // Identify the block where normal (non-fall-through) control flow
4819 HBasicBlock* normal_block = NULL;
4820 if (clause->is_default()) {
4821 if (last_block == NULL) continue;
4822 normal_block = last_block;
4823 last_block = NULL; // Cleared to indicate we've handled it.
4825 normal_block = body_blocks[i];
4828 if (fall_through_block == NULL) {
4829 set_current_block(normal_block);
4831 HBasicBlock* join = CreateJoin(fall_through_block,
4834 set_current_block(join);
4837 CHECK_BAILOUT(VisitStatements(clause->statements()));
4838 fall_through_block = current_block();
4842 // Create an up-to-3-way join. Use the break block if it exists since
4843 // it's already a join block.
4844 HBasicBlock* break_block = break_info.break_block();
4845 if (break_block == NULL) {
4846 set_current_block(CreateJoin(fall_through_block,
4850 if (fall_through_block != NULL) Goto(fall_through_block, break_block);
4851 if (last_block != NULL) Goto(last_block, break_block);
4852 break_block->SetJoinId(stmt->ExitId());
4853 set_current_block(break_block);
4858 void HOptimizedGraphBuilder::VisitLoopBody(IterationStatement* stmt,
4859 HBasicBlock* loop_entry) {
4860 Add<HSimulate>(stmt->StackCheckId());
4861 HStackCheck* stack_check =
4862 HStackCheck::cast(Add<HStackCheck>(HStackCheck::kBackwardsBranch));
4863 ASSERT(loop_entry->IsLoopHeader());
4864 loop_entry->loop_information()->set_stack_check(stack_check);
4865 CHECK_BAILOUT(Visit(stmt->body()));
4869 void HOptimizedGraphBuilder::VisitDoWhileStatement(DoWhileStatement* stmt) {
4870 ASSERT(!HasStackOverflow());
4871 ASSERT(current_block() != NULL);
4872 ASSERT(current_block()->HasPredecessor());
4873 ASSERT(current_block() != NULL);
4874 HBasicBlock* loop_entry = BuildLoopEntry(stmt);
4876 BreakAndContinueInfo break_info(stmt, scope());
4878 BreakAndContinueScope push(&break_info, this);
4879 CHECK_BAILOUT(VisitLoopBody(stmt, loop_entry));
4881 HBasicBlock* body_exit =
4882 JoinContinue(stmt, current_block(), break_info.continue_block());
4883 HBasicBlock* loop_successor = NULL;
4884 if (body_exit != NULL && !stmt->cond()->ToBooleanIsTrue()) {
4885 set_current_block(body_exit);
4886 loop_successor = graph()->CreateBasicBlock();
4887 if (stmt->cond()->ToBooleanIsFalse()) {
4888 loop_entry->loop_information()->stack_check()->Eliminate();
4889 Goto(loop_successor);
4892 // The block for a true condition, the actual predecessor block of the
4894 body_exit = graph()->CreateBasicBlock();
4895 CHECK_BAILOUT(VisitForControl(stmt->cond(), body_exit, loop_successor));
4897 if (body_exit != NULL && body_exit->HasPredecessor()) {
4898 body_exit->SetJoinId(stmt->BackEdgeId());
4902 if (loop_successor->HasPredecessor()) {
4903 loop_successor->SetJoinId(stmt->ExitId());
4905 loop_successor = NULL;
4908 HBasicBlock* loop_exit = CreateLoop(stmt,
4912 break_info.break_block());
4913 set_current_block(loop_exit);
4917 void HOptimizedGraphBuilder::VisitWhileStatement(WhileStatement* stmt) {
4918 ASSERT(!HasStackOverflow());
4919 ASSERT(current_block() != NULL);
4920 ASSERT(current_block()->HasPredecessor());
4921 ASSERT(current_block() != NULL);
4922 HBasicBlock* loop_entry = BuildLoopEntry(stmt);
4924 // If the condition is constant true, do not generate a branch.
4925 HBasicBlock* loop_successor = NULL;
4926 if (!stmt->cond()->ToBooleanIsTrue()) {
4927 HBasicBlock* body_entry = graph()->CreateBasicBlock();
4928 loop_successor = graph()->CreateBasicBlock();
4929 CHECK_BAILOUT(VisitForControl(stmt->cond(), body_entry, loop_successor));
4930 if (body_entry->HasPredecessor()) {
4931 body_entry->SetJoinId(stmt->BodyId());
4932 set_current_block(body_entry);
4934 if (loop_successor->HasPredecessor()) {
4935 loop_successor->SetJoinId(stmt->ExitId());
4937 loop_successor = NULL;
4941 BreakAndContinueInfo break_info(stmt, scope());
4942 if (current_block() != NULL) {
4943 BreakAndContinueScope push(&break_info, this);
4944 CHECK_BAILOUT(VisitLoopBody(stmt, loop_entry));
4946 HBasicBlock* body_exit =
4947 JoinContinue(stmt, current_block(), break_info.continue_block());
4948 HBasicBlock* loop_exit = CreateLoop(stmt,
4952 break_info.break_block());
4953 set_current_block(loop_exit);
4957 void HOptimizedGraphBuilder::VisitForStatement(ForStatement* stmt) {
4958 ASSERT(!HasStackOverflow());
4959 ASSERT(current_block() != NULL);
4960 ASSERT(current_block()->HasPredecessor());
4961 if (stmt->init() != NULL) {
4962 CHECK_ALIVE(Visit(stmt->init()));
4964 ASSERT(current_block() != NULL);
4965 HBasicBlock* loop_entry = BuildLoopEntry(stmt);
4967 HBasicBlock* loop_successor = NULL;
4968 if (stmt->cond() != NULL) {
4969 HBasicBlock* body_entry = graph()->CreateBasicBlock();
4970 loop_successor = graph()->CreateBasicBlock();
4971 CHECK_BAILOUT(VisitForControl(stmt->cond(), body_entry, loop_successor));
4972 if (body_entry->HasPredecessor()) {
4973 body_entry->SetJoinId(stmt->BodyId());
4974 set_current_block(body_entry);
4976 if (loop_successor->HasPredecessor()) {
4977 loop_successor->SetJoinId(stmt->ExitId());
4979 loop_successor = NULL;
4983 BreakAndContinueInfo break_info(stmt, scope());
4984 if (current_block() != NULL) {
4985 BreakAndContinueScope push(&break_info, this);
4986 CHECK_BAILOUT(VisitLoopBody(stmt, loop_entry));
4988 HBasicBlock* body_exit =
4989 JoinContinue(stmt, current_block(), break_info.continue_block());
4991 if (stmt->next() != NULL && body_exit != NULL) {
4992 set_current_block(body_exit);
4993 CHECK_BAILOUT(Visit(stmt->next()));
4994 body_exit = current_block();
4997 HBasicBlock* loop_exit = CreateLoop(stmt,
5001 break_info.break_block());
5002 set_current_block(loop_exit);
5006 void HOptimizedGraphBuilder::VisitForInStatement(ForInStatement* stmt) {
5007 ASSERT(!HasStackOverflow());
5008 ASSERT(current_block() != NULL);
5009 ASSERT(current_block()->HasPredecessor());
5011 if (!FLAG_optimize_for_in) {
5012 return Bailout(kForInStatementOptimizationIsDisabled);
5015 if (stmt->for_in_type() != ForInStatement::FAST_FOR_IN) {
5016 return Bailout(kForInStatementIsNotFastCase);
5019 if (!stmt->each()->IsVariableProxy() ||
5020 !stmt->each()->AsVariableProxy()->var()->IsStackLocal()) {
5021 return Bailout(kForInStatementWithNonLocalEachVariable);
5024 Variable* each_var = stmt->each()->AsVariableProxy()->var();
5026 CHECK_ALIVE(VisitForValue(stmt->enumerable()));
5027 HValue* enumerable = Top(); // Leave enumerable at the top.
5029 HInstruction* map = Add<HForInPrepareMap>(enumerable);
5030 Add<HSimulate>(stmt->PrepareId());
5032 HInstruction* array = Add<HForInCacheArray>(
5033 enumerable, map, DescriptorArray::kEnumCacheBridgeCacheIndex);
5035 HInstruction* enum_length = Add<HMapEnumLength>(map);
5037 HInstruction* start_index = Add<HConstant>(0);
5044 HInstruction* index_cache = Add<HForInCacheArray>(
5045 enumerable, map, DescriptorArray::kEnumCacheBridgeIndicesCacheIndex);
5046 HForInCacheArray::cast(array)->set_index_cache(
5047 HForInCacheArray::cast(index_cache));
5049 HBasicBlock* loop_entry = BuildLoopEntry(stmt);
5051 HValue* index = environment()->ExpressionStackAt(0);
5052 HValue* limit = environment()->ExpressionStackAt(1);
5054 // Check that we still have more keys.
5055 HCompareNumericAndBranch* compare_index =
5056 New<HCompareNumericAndBranch>(index, limit, Token::LT);
5057 compare_index->set_observed_input_representation(
5058 Representation::Smi(), Representation::Smi());
5060 HBasicBlock* loop_body = graph()->CreateBasicBlock();
5061 HBasicBlock* loop_successor = graph()->CreateBasicBlock();
5063 compare_index->SetSuccessorAt(0, loop_body);
5064 compare_index->SetSuccessorAt(1, loop_successor);
5065 FinishCurrentBlock(compare_index);
5067 set_current_block(loop_successor);
5070 set_current_block(loop_body);
5072 HValue* key = Add<HLoadKeyed>(
5073 environment()->ExpressionStackAt(2), // Enum cache.
5074 environment()->ExpressionStackAt(0), // Iteration index.
5075 environment()->ExpressionStackAt(0),
5078 // Check if the expected map still matches that of the enumerable.
5079 // If not just deoptimize.
5080 Add<HCheckMapValue>(environment()->ExpressionStackAt(4),
5081 environment()->ExpressionStackAt(3));
5083 Bind(each_var, key);
5085 BreakAndContinueInfo break_info(stmt, scope(), 5);
5087 BreakAndContinueScope push(&break_info, this);
5088 CHECK_BAILOUT(VisitLoopBody(stmt, loop_entry));
5091 HBasicBlock* body_exit =
5092 JoinContinue(stmt, current_block(), break_info.continue_block());
5094 if (body_exit != NULL) {
5095 set_current_block(body_exit);
5097 HValue* current_index = Pop();
5098 Push(AddUncasted<HAdd>(current_index, graph()->GetConstant1()));
5099 body_exit = current_block();
5102 HBasicBlock* loop_exit = CreateLoop(stmt,
5106 break_info.break_block());
5108 set_current_block(loop_exit);
5112 void HOptimizedGraphBuilder::VisitForOfStatement(ForOfStatement* stmt) {
5113 ASSERT(!HasStackOverflow());
5114 ASSERT(current_block() != NULL);
5115 ASSERT(current_block()->HasPredecessor());
5116 return Bailout(kForOfStatement);
5120 void HOptimizedGraphBuilder::VisitTryCatchStatement(TryCatchStatement* stmt) {
5121 ASSERT(!HasStackOverflow());
5122 ASSERT(current_block() != NULL);
5123 ASSERT(current_block()->HasPredecessor());
5124 return Bailout(kTryCatchStatement);
5128 void HOptimizedGraphBuilder::VisitTryFinallyStatement(
5129 TryFinallyStatement* stmt) {
5130 ASSERT(!HasStackOverflow());
5131 ASSERT(current_block() != NULL);
5132 ASSERT(current_block()->HasPredecessor());
5133 return Bailout(kTryFinallyStatement);
5137 void HOptimizedGraphBuilder::VisitDebuggerStatement(DebuggerStatement* stmt) {
5138 ASSERT(!HasStackOverflow());
5139 ASSERT(current_block() != NULL);
5140 ASSERT(current_block()->HasPredecessor());
5141 return Bailout(kDebuggerStatement);
5145 void HOptimizedGraphBuilder::VisitCaseClause(CaseClause* clause) {
5150 void HOptimizedGraphBuilder::VisitFunctionLiteral(FunctionLiteral* expr) {
5151 ASSERT(!HasStackOverflow());
5152 ASSERT(current_block() != NULL);
5153 ASSERT(current_block()->HasPredecessor());
5154 Handle<SharedFunctionInfo> shared_info = expr->shared_info();
5155 if (shared_info.is_null()) {
5156 shared_info = Compiler::BuildFunctionInfo(expr, current_info()->script());
5158 // We also have a stack overflow if the recursive compilation did.
5159 if (HasStackOverflow()) return;
5160 HFunctionLiteral* instr =
5161 New<HFunctionLiteral>(shared_info, expr->pretenure());
5162 return ast_context()->ReturnInstruction(instr, expr->id());
5166 void HOptimizedGraphBuilder::VisitNativeFunctionLiteral(
5167 NativeFunctionLiteral* expr) {
5168 ASSERT(!HasStackOverflow());
5169 ASSERT(current_block() != NULL);
5170 ASSERT(current_block()->HasPredecessor());
5171 return Bailout(kNativeFunctionLiteral);
5175 void HOptimizedGraphBuilder::VisitConditional(Conditional* expr) {
5176 ASSERT(!HasStackOverflow());
5177 ASSERT(current_block() != NULL);
5178 ASSERT(current_block()->HasPredecessor());
5179 HBasicBlock* cond_true = graph()->CreateBasicBlock();
5180 HBasicBlock* cond_false = graph()->CreateBasicBlock();
5181 CHECK_BAILOUT(VisitForControl(expr->condition(), cond_true, cond_false));
5183 // Visit the true and false subexpressions in the same AST context as the
5184 // whole expression.
5185 if (cond_true->HasPredecessor()) {
5186 cond_true->SetJoinId(expr->ThenId());
5187 set_current_block(cond_true);
5188 CHECK_BAILOUT(Visit(expr->then_expression()));
5189 cond_true = current_block();
5194 if (cond_false->HasPredecessor()) {
5195 cond_false->SetJoinId(expr->ElseId());
5196 set_current_block(cond_false);
5197 CHECK_BAILOUT(Visit(expr->else_expression()));
5198 cond_false = current_block();
5203 if (!ast_context()->IsTest()) {
5204 HBasicBlock* join = CreateJoin(cond_true, cond_false, expr->id());
5205 set_current_block(join);
5206 if (join != NULL && !ast_context()->IsEffect()) {
5207 return ast_context()->ReturnValue(Pop());
5213 HOptimizedGraphBuilder::GlobalPropertyAccess
5214 HOptimizedGraphBuilder::LookupGlobalProperty(
5215 Variable* var, LookupResult* lookup, PropertyAccessType access_type) {
5216 if (var->is_this() || !current_info()->has_global_object()) {
5219 Handle<GlobalObject> global(current_info()->global_object());
5220 global->Lookup(var->name(), lookup);
5221 if (!lookup->IsNormal() ||
5222 (access_type == STORE && lookup->IsReadOnly()) ||
5223 lookup->holder() != *global) {
5231 HValue* HOptimizedGraphBuilder::BuildContextChainWalk(Variable* var) {
5232 ASSERT(var->IsContextSlot());
5233 HValue* context = environment()->context();
5234 int length = scope()->ContextChainLength(var->scope());
5235 while (length-- > 0) {
5236 context = Add<HLoadNamedField>(
5237 context, static_cast<HValue*>(NULL),
5238 HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX));
5244 void HOptimizedGraphBuilder::VisitVariableProxy(VariableProxy* expr) {
5245 if (expr->is_this()) {
5246 current_info()->set_this_has_uses(true);
5249 ASSERT(!HasStackOverflow());
5250 ASSERT(current_block() != NULL);
5251 ASSERT(current_block()->HasPredecessor());
5252 Variable* variable = expr->var();
5253 switch (variable->location()) {
5254 case Variable::UNALLOCATED: {
5255 if (IsLexicalVariableMode(variable->mode())) {
5256 // TODO(rossberg): should this be an ASSERT?
5257 return Bailout(kReferenceToGlobalLexicalVariable);
5259 // Handle known global constants like 'undefined' specially to avoid a
5260 // load from a global cell for them.
5261 Handle<Object> constant_value =
5262 isolate()->factory()->GlobalConstantFor(variable->name());
5263 if (!constant_value.is_null()) {
5264 HConstant* instr = New<HConstant>(constant_value);
5265 return ast_context()->ReturnInstruction(instr, expr->id());
5268 LookupResult lookup(isolate());
5269 GlobalPropertyAccess type = LookupGlobalProperty(variable, &lookup, LOAD);
5271 if (type == kUseCell &&
5272 current_info()->global_object()->IsAccessCheckNeeded()) {
5276 if (type == kUseCell) {
5277 Handle<GlobalObject> global(current_info()->global_object());
5278 Handle<PropertyCell> cell(global->GetPropertyCell(&lookup));
5279 if (cell->type()->IsConstant()) {
5280 PropertyCell::AddDependentCompilationInfo(cell, top_info());
5281 Handle<Object> constant_object = cell->type()->AsConstant()->Value();
5282 if (constant_object->IsConsString()) {
5284 String::Flatten(Handle<String>::cast(constant_object));
5286 HConstant* constant = New<HConstant>(constant_object);
5287 return ast_context()->ReturnInstruction(constant, expr->id());
5289 HLoadGlobalCell* instr =
5290 New<HLoadGlobalCell>(cell, lookup.GetPropertyDetails());
5291 return ast_context()->ReturnInstruction(instr, expr->id());
5294 HValue* global_object = Add<HLoadNamedField>(
5295 context(), static_cast<HValue*>(NULL),
5296 HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
5297 HLoadGlobalGeneric* instr =
5298 New<HLoadGlobalGeneric>(global_object,
5300 ast_context()->is_for_typeof());
5301 return ast_context()->ReturnInstruction(instr, expr->id());
5305 case Variable::PARAMETER:
5306 case Variable::LOCAL: {
5307 HValue* value = LookupAndMakeLive(variable);
5308 if (value == graph()->GetConstantHole()) {
5309 ASSERT(IsDeclaredVariableMode(variable->mode()) &&
5310 variable->mode() != VAR);
5311 return Bailout(kReferenceToUninitializedVariable);
5313 return ast_context()->ReturnValue(value);
5316 case Variable::CONTEXT: {
5317 HValue* context = BuildContextChainWalk(variable);
5318 HLoadContextSlot::Mode mode;
5319 switch (variable->mode()) {
5322 mode = HLoadContextSlot::kCheckDeoptimize;
5325 mode = HLoadContextSlot::kCheckReturnUndefined;
5328 mode = HLoadContextSlot::kNoCheck;
5331 HLoadContextSlot* instr =
5332 new(zone()) HLoadContextSlot(context, variable->index(), mode);
5333 return ast_context()->ReturnInstruction(instr, expr->id());
5336 case Variable::LOOKUP:
5337 return Bailout(kReferenceToAVariableWhichRequiresDynamicLookup);
5342 void HOptimizedGraphBuilder::VisitLiteral(Literal* expr) {
5343 ASSERT(!HasStackOverflow());
5344 ASSERT(current_block() != NULL);
5345 ASSERT(current_block()->HasPredecessor());
5346 HConstant* instr = New<HConstant>(expr->value());
5347 return ast_context()->ReturnInstruction(instr, expr->id());
5351 void HOptimizedGraphBuilder::VisitRegExpLiteral(RegExpLiteral* expr) {
5352 ASSERT(!HasStackOverflow());
5353 ASSERT(current_block() != NULL);
5354 ASSERT(current_block()->HasPredecessor());
5355 Handle<JSFunction> closure = function_state()->compilation_info()->closure();
5356 Handle<FixedArray> literals(closure->literals());
5357 HRegExpLiteral* instr = New<HRegExpLiteral>(literals,
5360 expr->literal_index());
5361 return ast_context()->ReturnInstruction(instr, expr->id());
5365 static bool CanInlinePropertyAccess(Type* type) {
5366 if (type->Is(Type::NumberOrString())) return true;
5367 if (!type->IsClass()) return false;
5368 Handle<Map> map = type->AsClass()->Map();
5369 return map->IsJSObjectMap() &&
5370 !map->is_dictionary_map() &&
5371 !map->has_named_interceptor();
5375 // Determines whether the given array or object literal boilerplate satisfies
5376 // all limits to be considered for fast deep-copying and computes the total
5377 // size of all objects that are part of the graph.
5378 static bool IsFastLiteral(Handle<JSObject> boilerplate,
5380 int* max_properties) {
5381 if (boilerplate->map()->is_deprecated() &&
5382 !JSObject::TryMigrateInstance(boilerplate)) {
5386 ASSERT(max_depth >= 0 && *max_properties >= 0);
5387 if (max_depth == 0) return false;
5389 Isolate* isolate = boilerplate->GetIsolate();
5390 Handle<FixedArrayBase> elements(boilerplate->elements());
5391 if (elements->length() > 0 &&
5392 elements->map() != isolate->heap()->fixed_cow_array_map()) {
5393 if (boilerplate->HasFastObjectElements()) {
5394 Handle<FixedArray> fast_elements = Handle<FixedArray>::cast(elements);
5395 int length = elements->length();
5396 for (int i = 0; i < length; i++) {
5397 if ((*max_properties)-- == 0) return false;
5398 Handle<Object> value(fast_elements->get(i), isolate);
5399 if (value->IsJSObject()) {
5400 Handle<JSObject> value_object = Handle<JSObject>::cast(value);
5401 if (!IsFastLiteral(value_object,
5408 } else if (!boilerplate->HasFastDoubleElements()) {
5413 Handle<FixedArray> properties(boilerplate->properties());
5414 if (properties->length() > 0) {
5417 Handle<DescriptorArray> descriptors(
5418 boilerplate->map()->instance_descriptors());
5419 int limit = boilerplate->map()->NumberOfOwnDescriptors();
5420 for (int i = 0; i < limit; i++) {
5421 PropertyDetails details = descriptors->GetDetails(i);
5422 if (details.type() != FIELD) continue;
5423 int index = descriptors->GetFieldIndex(i);
5424 if ((*max_properties)-- == 0) return false;
5425 Handle<Object> value(boilerplate->InObjectPropertyAt(index), isolate);
5426 if (value->IsJSObject()) {
5427 Handle<JSObject> value_object = Handle<JSObject>::cast(value);
5428 if (!IsFastLiteral(value_object,
5440 void HOptimizedGraphBuilder::VisitObjectLiteral(ObjectLiteral* expr) {
5441 ASSERT(!HasStackOverflow());
5442 ASSERT(current_block() != NULL);
5443 ASSERT(current_block()->HasPredecessor());
5444 expr->BuildConstantProperties(isolate());
5445 Handle<JSFunction> closure = function_state()->compilation_info()->closure();
5446 HInstruction* literal;
5448 // Check whether to use fast or slow deep-copying for boilerplate.
5449 int max_properties = kMaxFastLiteralProperties;
5450 Handle<Object> literals_cell(closure->literals()->get(expr->literal_index()),
5452 Handle<AllocationSite> site;
5453 Handle<JSObject> boilerplate;
5454 if (!literals_cell->IsUndefined()) {
5455 // Retrieve the boilerplate
5456 site = Handle<AllocationSite>::cast(literals_cell);
5457 boilerplate = Handle<JSObject>(JSObject::cast(site->transition_info()),
5461 if (!boilerplate.is_null() &&
5462 IsFastLiteral(boilerplate, kMaxFastLiteralDepth, &max_properties)) {
5463 AllocationSiteUsageContext usage_context(isolate(), site, false);
5464 usage_context.EnterNewScope();
5465 literal = BuildFastLiteral(boilerplate, &usage_context);
5466 usage_context.ExitScope(site, boilerplate);
5468 NoObservableSideEffectsScope no_effects(this);
5469 Handle<FixedArray> closure_literals(closure->literals(), isolate());
5470 Handle<FixedArray> constant_properties = expr->constant_properties();
5471 int literal_index = expr->literal_index();
5472 int flags = expr->fast_elements()
5473 ? ObjectLiteral::kFastElements : ObjectLiteral::kNoFlags;
5474 flags |= expr->has_function()
5475 ? ObjectLiteral::kHasFunction : ObjectLiteral::kNoFlags;
5477 Add<HPushArguments>(Add<HConstant>(closure_literals),
5478 Add<HConstant>(literal_index),
5479 Add<HConstant>(constant_properties),
5480 Add<HConstant>(flags));
5482 // TODO(mvstanton): Add a flag to turn off creation of any
5483 // AllocationMementos for this call: we are in crankshaft and should have
5484 // learned enough about transition behavior to stop emitting mementos.
5485 Runtime::FunctionId function_id = Runtime::kHiddenCreateObjectLiteral;
5486 literal = Add<HCallRuntime>(isolate()->factory()->empty_string(),
5487 Runtime::FunctionForId(function_id),
5491 // The object is expected in the bailout environment during computation
5492 // of the property values and is the value of the entire expression.
5495 expr->CalculateEmitStore(zone());
5497 for (int i = 0; i < expr->properties()->length(); i++) {
5498 ObjectLiteral::Property* property = expr->properties()->at(i);
5499 if (property->IsCompileTimeValue()) continue;
5501 Literal* key = property->key();
5502 Expression* value = property->value();
5504 switch (property->kind()) {
5505 case ObjectLiteral::Property::MATERIALIZED_LITERAL:
5506 ASSERT(!CompileTimeValue::IsCompileTimeValue(value));
5508 case ObjectLiteral::Property::COMPUTED:
5509 if (key->value()->IsInternalizedString()) {
5510 if (property->emit_store()) {
5511 CHECK_ALIVE(VisitForValue(value));
5512 HValue* value = Pop();
5513 Handle<Map> map = property->GetReceiverType();
5514 Handle<String> name = property->key()->AsPropertyName();
5515 HInstruction* store;
5516 if (map.is_null()) {
5517 // If we don't know the monomorphic type, do a generic store.
5518 CHECK_ALIVE(store = BuildNamedGeneric(
5519 STORE, literal, name, value));
5521 PropertyAccessInfo info(this, STORE, ToType(map), name);
5522 if (info.CanAccessMonomorphic()) {
5523 HValue* checked_literal = Add<HCheckMaps>(literal, map);
5524 ASSERT(!info.lookup()->IsPropertyCallbacks());
5525 store = BuildMonomorphicAccess(
5526 &info, literal, checked_literal, value,
5527 BailoutId::None(), BailoutId::None());
5529 CHECK_ALIVE(store = BuildNamedGeneric(
5530 STORE, literal, name, value));
5533 AddInstruction(store);
5534 if (store->HasObservableSideEffects()) {
5535 Add<HSimulate>(key->id(), REMOVABLE_SIMULATE);
5538 CHECK_ALIVE(VisitForEffect(value));
5543 case ObjectLiteral::Property::PROTOTYPE:
5544 case ObjectLiteral::Property::SETTER:
5545 case ObjectLiteral::Property::GETTER:
5546 return Bailout(kObjectLiteralWithComplexProperty);
5547 default: UNREACHABLE();
5551 if (expr->has_function()) {
5552 // Return the result of the transformation to fast properties
5553 // instead of the original since this operation changes the map
5554 // of the object. This makes sure that the original object won't
5555 // be used by other optimized code before it is transformed
5556 // (e.g. because of code motion).
5557 HToFastProperties* result = Add<HToFastProperties>(Pop());
5558 return ast_context()->ReturnValue(result);
5560 return ast_context()->ReturnValue(Pop());
5565 void HOptimizedGraphBuilder::VisitArrayLiteral(ArrayLiteral* expr) {
5566 ASSERT(!HasStackOverflow());
5567 ASSERT(current_block() != NULL);
5568 ASSERT(current_block()->HasPredecessor());
5569 expr->BuildConstantElements(isolate());
5570 ZoneList<Expression*>* subexprs = expr->values();
5571 int length = subexprs->length();
5572 HInstruction* literal;
5574 Handle<AllocationSite> site;
5575 Handle<FixedArray> literals(environment()->closure()->literals(), isolate());
5576 bool uninitialized = false;
5577 Handle<Object> literals_cell(literals->get(expr->literal_index()),
5579 Handle<JSObject> boilerplate_object;
5580 if (literals_cell->IsUndefined()) {
5581 uninitialized = true;
5582 Handle<Object> raw_boilerplate;
5583 ASSIGN_RETURN_ON_EXCEPTION_VALUE(
5584 isolate(), raw_boilerplate,
5585 Runtime::CreateArrayLiteralBoilerplate(
5586 isolate(), literals, expr->constant_elements()),
5587 Bailout(kArrayBoilerplateCreationFailed));
5589 boilerplate_object = Handle<JSObject>::cast(raw_boilerplate);
5590 AllocationSiteCreationContext creation_context(isolate());
5591 site = creation_context.EnterNewScope();
5592 if (JSObject::DeepWalk(boilerplate_object, &creation_context).is_null()) {
5593 return Bailout(kArrayBoilerplateCreationFailed);
5595 creation_context.ExitScope(site, boilerplate_object);
5596 literals->set(expr->literal_index(), *site);
5598 if (boilerplate_object->elements()->map() ==
5599 isolate()->heap()->fixed_cow_array_map()) {
5600 isolate()->counters()->cow_arrays_created_runtime()->Increment();
5603 ASSERT(literals_cell->IsAllocationSite());
5604 site = Handle<AllocationSite>::cast(literals_cell);
5605 boilerplate_object = Handle<JSObject>(
5606 JSObject::cast(site->transition_info()), isolate());
5609 ASSERT(!boilerplate_object.is_null());
5610 ASSERT(site->SitePointsToLiteral());
5612 ElementsKind boilerplate_elements_kind =
5613 boilerplate_object->GetElementsKind();
5615 // Check whether to use fast or slow deep-copying for boilerplate.
5616 int max_properties = kMaxFastLiteralProperties;
5617 if (IsFastLiteral(boilerplate_object,
5618 kMaxFastLiteralDepth,
5620 AllocationSiteUsageContext usage_context(isolate(), site, false);
5621 usage_context.EnterNewScope();
5622 literal = BuildFastLiteral(boilerplate_object, &usage_context);
5623 usage_context.ExitScope(site, boilerplate_object);
5625 NoObservableSideEffectsScope no_effects(this);
5626 // Boilerplate already exists and constant elements are never accessed,
5627 // pass an empty fixed array to the runtime function instead.
5628 Handle<FixedArray> constants = isolate()->factory()->empty_fixed_array();
5629 int literal_index = expr->literal_index();
5630 int flags = expr->depth() == 1
5631 ? ArrayLiteral::kShallowElements
5632 : ArrayLiteral::kNoFlags;
5633 flags |= ArrayLiteral::kDisableMementos;
5635 Add<HPushArguments>(Add<HConstant>(literals),
5636 Add<HConstant>(literal_index),
5637 Add<HConstant>(constants),
5638 Add<HConstant>(flags));
5640 // TODO(mvstanton): Consider a flag to turn off creation of any
5641 // AllocationMementos for this call: we are in crankshaft and should have
5642 // learned enough about transition behavior to stop emitting mementos.
5643 Runtime::FunctionId function_id = Runtime::kHiddenCreateArrayLiteral;
5644 literal = Add<HCallRuntime>(isolate()->factory()->empty_string(),
5645 Runtime::FunctionForId(function_id),
5648 // De-opt if elements kind changed from boilerplate_elements_kind.
5649 Handle<Map> map = Handle<Map>(boilerplate_object->map(), isolate());
5650 literal = Add<HCheckMaps>(literal, map);
5653 // The array is expected in the bailout environment during computation
5654 // of the property values and is the value of the entire expression.
5656 // The literal index is on the stack, too.
5657 Push(Add<HConstant>(expr->literal_index()));
5659 HInstruction* elements = NULL;
5661 for (int i = 0; i < length; i++) {
5662 Expression* subexpr = subexprs->at(i);
5663 // If the subexpression is a literal or a simple materialized literal it
5664 // is already set in the cloned array.
5665 if (CompileTimeValue::IsCompileTimeValue(subexpr)) continue;
5667 CHECK_ALIVE(VisitForValue(subexpr));
5668 HValue* value = Pop();
5669 if (!Smi::IsValid(i)) return Bailout(kNonSmiKeyInArrayLiteral);
5671 elements = AddLoadElements(literal);
5673 HValue* key = Add<HConstant>(i);
5675 switch (boilerplate_elements_kind) {
5676 case FAST_SMI_ELEMENTS:
5677 case FAST_HOLEY_SMI_ELEMENTS:
5679 case FAST_HOLEY_ELEMENTS:
5680 case FAST_DOUBLE_ELEMENTS:
5681 case FAST_HOLEY_DOUBLE_ELEMENTS: {
5682 HStoreKeyed* instr = Add<HStoreKeyed>(elements, key, value,
5683 boilerplate_elements_kind);
5684 instr->SetUninitialized(uninitialized);
5692 Add<HSimulate>(expr->GetIdForElement(i));
5695 Drop(1); // array literal index
5696 return ast_context()->ReturnValue(Pop());
5700 HCheckMaps* HOptimizedGraphBuilder::AddCheckMap(HValue* object,
5702 BuildCheckHeapObject(object);
5703 return Add<HCheckMaps>(object, map);
5707 HInstruction* HOptimizedGraphBuilder::BuildLoadNamedField(
5708 PropertyAccessInfo* info,
5709 HValue* checked_object) {
5710 // See if this is a load for an immutable property
5711 if (checked_object->ActualValue()->IsConstant() &&
5712 info->lookup()->IsCacheable() &&
5713 info->lookup()->IsReadOnly() && info->lookup()->IsDontDelete()) {
5714 Handle<Object> object(
5715 HConstant::cast(checked_object->ActualValue())->handle(isolate()));
5717 if (object->IsJSObject()) {
5718 LookupResult lookup(isolate());
5719 Handle<JSObject>::cast(object)->Lookup(info->name(), &lookup);
5720 Handle<Object> value(lookup.GetLazyValue(), isolate());
5722 if (!value->IsTheHole()) {
5723 return New<HConstant>(value);
5728 HObjectAccess access = info->access();
5729 if (access.representation().IsDouble()) {
5730 // Load the heap number.
5731 checked_object = Add<HLoadNamedField>(
5732 checked_object, static_cast<HValue*>(NULL),
5733 access.WithRepresentation(Representation::Tagged()));
5734 // Load the double value from it.
5735 access = HObjectAccess::ForHeapNumberValue();
5738 SmallMapList* map_list = info->field_maps();
5739 if (map_list->length() == 0) {
5740 return New<HLoadNamedField>(checked_object, checked_object, access);
5743 UniqueSet<Map>* maps = new(zone()) UniqueSet<Map>(map_list->length(), zone());
5744 for (int i = 0; i < map_list->length(); ++i) {
5745 maps->Add(Unique<Map>::CreateImmovable(map_list->at(i)), zone());
5747 return New<HLoadNamedField>(
5748 checked_object, checked_object, access, maps, info->field_type());
5752 HInstruction* HOptimizedGraphBuilder::BuildStoreNamedField(
5753 PropertyAccessInfo* info,
5754 HValue* checked_object,
5756 bool transition_to_field = info->lookup()->IsTransition();
5757 // TODO(verwaest): Move this logic into PropertyAccessInfo.
5758 HObjectAccess field_access = info->access();
5760 HStoreNamedField *instr;
5761 if (field_access.representation().IsDouble()) {
5762 HObjectAccess heap_number_access =
5763 field_access.WithRepresentation(Representation::Tagged());
5764 if (transition_to_field) {
5765 // The store requires a mutable HeapNumber to be allocated.
5766 NoObservableSideEffectsScope no_side_effects(this);
5767 HInstruction* heap_number_size = Add<HConstant>(HeapNumber::kSize);
5769 // TODO(hpayer): Allocation site pretenuring support.
5770 HInstruction* heap_number = Add<HAllocate>(heap_number_size,
5771 HType::HeapObject(),
5774 AddStoreMapConstant(heap_number, isolate()->factory()->heap_number_map());
5775 Add<HStoreNamedField>(heap_number, HObjectAccess::ForHeapNumberValue(),
5777 instr = New<HStoreNamedField>(checked_object->ActualValue(),
5781 // Already holds a HeapNumber; load the box and write its value field.
5782 HInstruction* heap_number = Add<HLoadNamedField>(
5783 checked_object, static_cast<HValue*>(NULL), heap_number_access);
5784 instr = New<HStoreNamedField>(heap_number,
5785 HObjectAccess::ForHeapNumberValue(),
5786 value, STORE_TO_INITIALIZED_ENTRY);
5789 if (field_access.representation().IsHeapObject()) {
5790 BuildCheckHeapObject(value);
5793 if (!info->field_maps()->is_empty()) {
5794 ASSERT(field_access.representation().IsHeapObject());
5795 value = Add<HCheckMaps>(value, info->field_maps());
5798 // This is a normal store.
5799 instr = New<HStoreNamedField>(
5800 checked_object->ActualValue(), field_access, value,
5801 transition_to_field ? INITIALIZING_STORE : STORE_TO_INITIALIZED_ENTRY);
5804 if (transition_to_field) {
5805 Handle<Map> transition(info->transition());
5806 ASSERT(!transition->is_deprecated());
5807 instr->SetTransition(Add<HConstant>(transition));
5813 bool HOptimizedGraphBuilder::PropertyAccessInfo::IsCompatible(
5814 PropertyAccessInfo* info) {
5815 if (!CanInlinePropertyAccess(type_)) return false;
5817 // Currently only handle Type::Number as a polymorphic case.
5818 // TODO(verwaest): Support monomorphic handling of numbers with a HCheckNumber
5820 if (type_->Is(Type::Number())) return false;
5822 // Values are only compatible for monomorphic load if they all behave the same
5823 // regarding value wrappers.
5824 if (type_->Is(Type::NumberOrString())) {
5825 if (!info->type_->Is(Type::NumberOrString())) return false;
5827 if (info->type_->Is(Type::NumberOrString())) return false;
5830 if (!LookupDescriptor()) return false;
5832 if (!lookup_.IsFound()) {
5833 return (!info->lookup_.IsFound() || info->has_holder()) &&
5834 map()->prototype() == info->map()->prototype();
5837 // Mismatch if the other access info found the property in the prototype
5839 if (info->has_holder()) return false;
5841 if (lookup_.IsPropertyCallbacks()) {
5842 return accessor_.is_identical_to(info->accessor_) &&
5843 api_holder_.is_identical_to(info->api_holder_);
5846 if (lookup_.IsConstant()) {
5847 return constant_.is_identical_to(info->constant_);
5850 ASSERT(lookup_.IsField());
5851 if (!info->lookup_.IsField()) return false;
5853 Representation r = access_.representation();
5855 if (!info->access_.representation().IsCompatibleForLoad(r)) return false;
5857 if (!info->access_.representation().IsCompatibleForStore(r)) return false;
5859 if (info->access_.offset() != access_.offset()) return false;
5860 if (info->access_.IsInobject() != access_.IsInobject()) return false;
5862 if (field_maps_.is_empty()) {
5863 info->field_maps_.Clear();
5864 } else if (!info->field_maps_.is_empty()) {
5865 for (int i = 0; i < field_maps_.length(); ++i) {
5866 info->field_maps_.AddMapIfMissing(field_maps_.at(i), info->zone());
5868 info->field_maps_.Sort();
5871 // We can only merge stores that agree on their field maps. The comparison
5872 // below is safe, since we keep the field maps sorted.
5873 if (field_maps_.length() != info->field_maps_.length()) return false;
5874 for (int i = 0; i < field_maps_.length(); ++i) {
5875 if (!field_maps_.at(i).is_identical_to(info->field_maps_.at(i))) {
5880 info->GeneralizeRepresentation(r);
5881 info->field_type_ = info->field_type_.Combine(field_type_);
5886 bool HOptimizedGraphBuilder::PropertyAccessInfo::LookupDescriptor() {
5887 if (!type_->IsClass()) return true;
5888 map()->LookupDescriptor(NULL, *name_, &lookup_);
5889 return LoadResult(map());
5893 bool HOptimizedGraphBuilder::PropertyAccessInfo::LoadResult(Handle<Map> map) {
5894 if (!IsLoad() && lookup_.IsProperty() &&
5895 (lookup_.IsReadOnly() || !lookup_.IsCacheable())) {
5899 if (lookup_.IsField()) {
5900 // Construct the object field access.
5901 access_ = HObjectAccess::ForField(map, &lookup_, name_);
5903 // Load field map for heap objects.
5905 } else if (lookup_.IsPropertyCallbacks()) {
5906 Handle<Object> callback(lookup_.GetValueFromMap(*map), isolate());
5907 if (!callback->IsAccessorPair()) return false;
5908 Object* raw_accessor = IsLoad()
5909 ? Handle<AccessorPair>::cast(callback)->getter()
5910 : Handle<AccessorPair>::cast(callback)->setter();
5911 if (!raw_accessor->IsJSFunction()) return false;
5912 Handle<JSFunction> accessor = handle(JSFunction::cast(raw_accessor));
5913 if (accessor->shared()->IsApiFunction()) {
5914 CallOptimization call_optimization(accessor);
5915 if (call_optimization.is_simple_api_call()) {
5916 CallOptimization::HolderLookup holder_lookup;
5917 Handle<Map> receiver_map = this->map();
5918 api_holder_ = call_optimization.LookupHolderOfExpectedType(
5919 receiver_map, &holder_lookup);
5922 accessor_ = accessor;
5923 } else if (lookup_.IsConstant()) {
5924 constant_ = handle(lookup_.GetConstantFromMap(*map), isolate());
5931 void HOptimizedGraphBuilder::PropertyAccessInfo::LoadFieldMaps(
5933 // Clear any previously collected field maps/type.
5934 field_maps_.Clear();
5935 field_type_ = HType::Tagged();
5937 // Figure out the field type from the accessor map.
5938 Handle<HeapType> field_type(lookup_.GetFieldTypeFromMap(*map), isolate());
5940 // Collect the (stable) maps from the field type.
5941 int num_field_maps = field_type->NumClasses();
5942 if (num_field_maps == 0) return;
5943 ASSERT(access_.representation().IsHeapObject());
5944 field_maps_.Reserve(num_field_maps, zone());
5945 HeapType::Iterator<Map> it = field_type->Classes();
5946 while (!it.Done()) {
5947 Handle<Map> field_map = it.Current();
5948 if (!field_map->is_stable()) {
5949 field_maps_.Clear();
5952 field_maps_.Add(field_map, zone());
5956 ASSERT_EQ(num_field_maps, field_maps_.length());
5958 // Determine field HType from field HeapType.
5959 field_type_ = HType::FromType<HeapType>(field_type);
5960 ASSERT(field_type_.IsHeapObject());
5962 // Add dependency on the map that introduced the field.
5963 Map::AddDependentCompilationInfo(
5964 handle(lookup_.GetFieldOwnerFromMap(*map), isolate()),
5965 DependentCode::kFieldTypeGroup, top_info());
5969 bool HOptimizedGraphBuilder::PropertyAccessInfo::LookupInPrototypes() {
5970 Handle<Map> map = this->map();
5972 while (map->prototype()->IsJSObject()) {
5973 holder_ = handle(JSObject::cast(map->prototype()));
5974 if (holder_->map()->is_deprecated()) {
5975 JSObject::TryMigrateInstance(holder_);
5977 map = Handle<Map>(holder_->map());
5978 if (!CanInlinePropertyAccess(ToType(map))) {
5982 map->LookupDescriptor(*holder_, *name_, &lookup_);
5983 if (lookup_.IsFound()) return LoadResult(map);
5990 bool HOptimizedGraphBuilder::PropertyAccessInfo::CanAccessMonomorphic() {
5991 if (!CanInlinePropertyAccess(type_)) return false;
5992 if (IsJSObjectFieldAccessor()) return IsLoad();
5993 if (!LookupDescriptor()) return false;
5994 if (lookup_.IsFound()) {
5995 if (IsLoad()) return true;
5996 return !lookup_.IsReadOnly() && lookup_.IsCacheable();
5998 if (!LookupInPrototypes()) return false;
5999 if (IsLoad()) return true;
6001 if (lookup_.IsPropertyCallbacks()) return true;
6002 Handle<Map> map = this->map();
6003 map->LookupTransition(NULL, *name_, &lookup_);
6004 if (lookup_.IsTransitionToField() && map->unused_property_fields() > 0) {
6005 // Construct the object field access.
6006 access_ = HObjectAccess::ForField(map, &lookup_, name_);
6008 // Load field map for heap objects.
6009 LoadFieldMaps(transition());
6016 bool HOptimizedGraphBuilder::PropertyAccessInfo::CanAccessAsMonomorphic(
6017 SmallMapList* types) {
6018 ASSERT(type_->Is(ToType(types->first())));
6019 if (!CanAccessMonomorphic()) return false;
6020 STATIC_ASSERT(kMaxLoadPolymorphism == kMaxStorePolymorphism);
6021 if (types->length() > kMaxLoadPolymorphism) return false;
6023 HObjectAccess access = HObjectAccess::ForMap(); // bogus default
6024 if (GetJSObjectFieldAccess(&access)) {
6025 for (int i = 1; i < types->length(); ++i) {
6026 PropertyAccessInfo test_info(
6027 builder_, access_type_, ToType(types->at(i)), name_);
6028 HObjectAccess test_access = HObjectAccess::ForMap(); // bogus default
6029 if (!test_info.GetJSObjectFieldAccess(&test_access)) return false;
6030 if (!access.Equals(test_access)) return false;
6035 // Currently only handle Type::Number as a polymorphic case.
6036 // TODO(verwaest): Support monomorphic handling of numbers with a HCheckNumber
6038 if (type_->Is(Type::Number())) return false;
6040 // Multiple maps cannot transition to the same target map.
6041 ASSERT(!IsLoad() || !lookup_.IsTransition());
6042 if (lookup_.IsTransition() && types->length() > 1) return false;
6044 for (int i = 1; i < types->length(); ++i) {
6045 PropertyAccessInfo test_info(
6046 builder_, access_type_, ToType(types->at(i)), name_);
6047 if (!test_info.IsCompatible(this)) return false;
6054 static bool NeedsWrappingFor(Type* type, Handle<JSFunction> target) {
6055 return type->Is(Type::NumberOrString()) &&
6056 target->shared()->strict_mode() == SLOPPY &&
6057 !target->shared()->native();
6061 HInstruction* HOptimizedGraphBuilder::BuildMonomorphicAccess(
6062 PropertyAccessInfo* info,
6064 HValue* checked_object,
6067 BailoutId return_id,
6068 bool can_inline_accessor) {
6070 HObjectAccess access = HObjectAccess::ForMap(); // bogus default
6071 if (info->GetJSObjectFieldAccess(&access)) {
6072 ASSERT(info->IsLoad());
6073 return New<HLoadNamedField>(object, checked_object, access);
6076 HValue* checked_holder = checked_object;
6077 if (info->has_holder()) {
6078 Handle<JSObject> prototype(JSObject::cast(info->map()->prototype()));
6079 checked_holder = BuildCheckPrototypeMaps(prototype, info->holder());
6082 if (!info->lookup()->IsFound()) {
6083 ASSERT(info->IsLoad());
6084 return graph()->GetConstantUndefined();
6087 if (info->lookup()->IsField()) {
6088 if (info->IsLoad()) {
6089 return BuildLoadNamedField(info, checked_holder);
6091 return BuildStoreNamedField(info, checked_object, value);
6095 if (info->lookup()->IsTransition()) {
6096 ASSERT(!info->IsLoad());
6097 return BuildStoreNamedField(info, checked_object, value);
6100 if (info->lookup()->IsPropertyCallbacks()) {
6101 Push(checked_object);
6102 int argument_count = 1;
6103 if (!info->IsLoad()) {
6108 if (NeedsWrappingFor(info->type(), info->accessor())) {
6109 HValue* function = Add<HConstant>(info->accessor());
6110 PushArgumentsFromEnvironment(argument_count);
6111 return New<HCallFunction>(function, argument_count, WRAP_AND_CALL);
6112 } else if (FLAG_inline_accessors && can_inline_accessor) {
6113 bool success = info->IsLoad()
6114 ? TryInlineGetter(info->accessor(), info->map(), ast_id, return_id)
6116 info->accessor(), info->map(), ast_id, return_id, value);
6117 if (success || HasStackOverflow()) return NULL;
6120 PushArgumentsFromEnvironment(argument_count);
6121 return BuildCallConstantFunction(info->accessor(), argument_count);
6124 ASSERT(info->lookup()->IsConstant());
6125 if (info->IsLoad()) {
6126 return New<HConstant>(info->constant());
6128 return New<HCheckValue>(value, Handle<JSFunction>::cast(info->constant()));
6133 void HOptimizedGraphBuilder::HandlePolymorphicNamedFieldAccess(
6134 PropertyAccessType access_type,
6136 BailoutId return_id,
6139 SmallMapList* types,
6140 Handle<String> name) {
6141 // Something did not match; must use a polymorphic load.
6143 HBasicBlock* join = NULL;
6144 HBasicBlock* number_block = NULL;
6145 bool handled_string = false;
6147 bool handle_smi = false;
6148 STATIC_ASSERT(kMaxLoadPolymorphism == kMaxStorePolymorphism);
6149 for (int i = 0; i < types->length() && count < kMaxLoadPolymorphism; ++i) {
6150 PropertyAccessInfo info(this, access_type, ToType(types->at(i)), name);
6151 if (info.type()->Is(Type::String())) {
6152 if (handled_string) continue;
6153 handled_string = true;
6155 if (info.CanAccessMonomorphic()) {
6157 if (info.type()->Is(Type::Number())) {
6165 HControlInstruction* smi_check = NULL;
6166 handled_string = false;
6168 for (int i = 0; i < types->length() && count < kMaxLoadPolymorphism; ++i) {
6169 PropertyAccessInfo info(this, access_type, ToType(types->at(i)), name);
6170 if (info.type()->Is(Type::String())) {
6171 if (handled_string) continue;
6172 handled_string = true;
6174 if (!info.CanAccessMonomorphic()) continue;
6177 join = graph()->CreateBasicBlock();
6179 HBasicBlock* empty_smi_block = graph()->CreateBasicBlock();
6180 HBasicBlock* not_smi_block = graph()->CreateBasicBlock();
6181 number_block = graph()->CreateBasicBlock();
6182 smi_check = New<HIsSmiAndBranch>(
6183 object, empty_smi_block, not_smi_block);
6184 FinishCurrentBlock(smi_check);
6185 GotoNoSimulate(empty_smi_block, number_block);
6186 set_current_block(not_smi_block);
6188 BuildCheckHeapObject(object);
6192 HBasicBlock* if_true = graph()->CreateBasicBlock();
6193 HBasicBlock* if_false = graph()->CreateBasicBlock();
6194 HUnaryControlInstruction* compare;
6197 if (info.type()->Is(Type::Number())) {
6198 Handle<Map> heap_number_map = isolate()->factory()->heap_number_map();
6199 compare = New<HCompareMap>(object, heap_number_map, if_true, if_false);
6200 dependency = smi_check;
6201 } else if (info.type()->Is(Type::String())) {
6202 compare = New<HIsStringAndBranch>(object, if_true, if_false);
6203 dependency = compare;
6205 compare = New<HCompareMap>(object, info.map(), if_true, if_false);
6206 dependency = compare;
6208 FinishCurrentBlock(compare);
6210 if (info.type()->Is(Type::Number())) {
6211 GotoNoSimulate(if_true, number_block);
6212 if_true = number_block;
6215 set_current_block(if_true);
6217 HInstruction* access = BuildMonomorphicAccess(
6218 &info, object, dependency, value, ast_id,
6219 return_id, FLAG_polymorphic_inlining);
6221 HValue* result = NULL;
6222 switch (access_type) {
6231 if (access == NULL) {
6232 if (HasStackOverflow()) return;
6234 if (!access->IsLinked()) AddInstruction(access);
6235 if (!ast_context()->IsEffect()) Push(result);
6238 if (current_block() != NULL) Goto(join);
6239 set_current_block(if_false);
6242 // Finish up. Unconditionally deoptimize if we've handled all the maps we
6243 // know about and do not want to handle ones we've never seen. Otherwise
6244 // use a generic IC.
6245 if (count == types->length() && FLAG_deoptimize_uncommon_cases) {
6246 FinishExitWithHardDeoptimization("Uknown map in polymorphic access");
6248 HInstruction* instr = BuildNamedGeneric(access_type, object, name, value);
6249 AddInstruction(instr);
6250 if (!ast_context()->IsEffect()) Push(access_type == LOAD ? instr : value);
6255 Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6256 if (!ast_context()->IsEffect()) ast_context()->ReturnValue(Pop());
6261 ASSERT(join != NULL);
6262 if (join->HasPredecessor()) {
6263 join->SetJoinId(ast_id);
6264 set_current_block(join);
6265 if (!ast_context()->IsEffect()) ast_context()->ReturnValue(Pop());
6267 set_current_block(NULL);
6272 static bool ComputeReceiverTypes(Expression* expr,
6276 SmallMapList* types = expr->GetReceiverTypes();
6278 bool monomorphic = expr->IsMonomorphic();
6279 if (types != NULL && receiver->HasMonomorphicJSObjectType()) {
6280 Map* root_map = receiver->GetMonomorphicJSObjectMap()->FindRootMap();
6281 types->FilterForPossibleTransitions(root_map);
6282 monomorphic = types->length() == 1;
6284 return monomorphic && CanInlinePropertyAccess(
6285 IC::MapToType<Type>(types->first(), zone));
6289 static bool AreStringTypes(SmallMapList* types) {
6290 for (int i = 0; i < types->length(); i++) {
6291 if (types->at(i)->instance_type() >= FIRST_NONSTRING_TYPE) return false;
6297 void HOptimizedGraphBuilder::BuildStore(Expression* expr,
6300 BailoutId return_id,
6301 bool is_uninitialized) {
6302 if (!prop->key()->IsPropertyName()) {
6304 HValue* value = environment()->ExpressionStackAt(0);
6305 HValue* key = environment()->ExpressionStackAt(1);
6306 HValue* object = environment()->ExpressionStackAt(2);
6307 bool has_side_effects = false;
6308 HandleKeyedElementAccess(object, key, value, expr,
6309 STORE, &has_side_effects);
6312 Add<HSimulate>(return_id, REMOVABLE_SIMULATE);
6313 return ast_context()->ReturnValue(Pop());
6317 HValue* value = Pop();
6318 HValue* object = Pop();
6320 Literal* key = prop->key()->AsLiteral();
6321 Handle<String> name = Handle<String>::cast(key->value());
6322 ASSERT(!name.is_null());
6324 HInstruction* instr = BuildNamedAccess(STORE, ast_id, return_id, expr,
6325 object, name, value, is_uninitialized);
6326 if (instr == NULL) return;
6328 if (!ast_context()->IsEffect()) Push(value);
6329 AddInstruction(instr);
6330 if (instr->HasObservableSideEffects()) {
6331 Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6333 if (!ast_context()->IsEffect()) Drop(1);
6334 return ast_context()->ReturnValue(value);
6338 void HOptimizedGraphBuilder::HandlePropertyAssignment(Assignment* expr) {
6339 Property* prop = expr->target()->AsProperty();
6340 ASSERT(prop != NULL);
6341 CHECK_ALIVE(VisitForValue(prop->obj()));
6342 if (!prop->key()->IsPropertyName()) {
6343 CHECK_ALIVE(VisitForValue(prop->key()));
6345 CHECK_ALIVE(VisitForValue(expr->value()));
6346 BuildStore(expr, prop, expr->id(),
6347 expr->AssignmentId(), expr->IsUninitialized());
6351 // Because not every expression has a position and there is not common
6352 // superclass of Assignment and CountOperation, we cannot just pass the
6353 // owning expression instead of position and ast_id separately.
6354 void HOptimizedGraphBuilder::HandleGlobalVariableAssignment(
6358 LookupResult lookup(isolate());
6359 GlobalPropertyAccess type = LookupGlobalProperty(var, &lookup, STORE);
6360 if (type == kUseCell) {
6361 Handle<GlobalObject> global(current_info()->global_object());
6362 Handle<PropertyCell> cell(global->GetPropertyCell(&lookup));
6363 if (cell->type()->IsConstant()) {
6364 Handle<Object> constant = cell->type()->AsConstant()->Value();
6365 if (value->IsConstant()) {
6366 HConstant* c_value = HConstant::cast(value);
6367 if (!constant.is_identical_to(c_value->handle(isolate()))) {
6368 Add<HDeoptimize>("Constant global variable assignment",
6369 Deoptimizer::EAGER);
6372 HValue* c_constant = Add<HConstant>(constant);
6373 IfBuilder builder(this);
6374 if (constant->IsNumber()) {
6375 builder.If<HCompareNumericAndBranch>(value, c_constant, Token::EQ);
6377 builder.If<HCompareObjectEqAndBranch>(value, c_constant);
6381 Add<HDeoptimize>("Constant global variable assignment",
6382 Deoptimizer::EAGER);
6386 HInstruction* instr =
6387 Add<HStoreGlobalCell>(value, cell, lookup.GetPropertyDetails());
6388 if (instr->HasObservableSideEffects()) {
6389 Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6392 HValue* global_object = Add<HLoadNamedField>(
6393 context(), static_cast<HValue*>(NULL),
6394 HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
6395 HStoreNamedGeneric* instr =
6396 Add<HStoreNamedGeneric>(global_object, var->name(),
6397 value, function_strict_mode());
6399 ASSERT(instr->HasObservableSideEffects());
6400 Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6405 void HOptimizedGraphBuilder::HandleCompoundAssignment(Assignment* expr) {
6406 Expression* target = expr->target();
6407 VariableProxy* proxy = target->AsVariableProxy();
6408 Property* prop = target->AsProperty();
6409 ASSERT(proxy == NULL || prop == NULL);
6411 // We have a second position recorded in the FullCodeGenerator to have
6412 // type feedback for the binary operation.
6413 BinaryOperation* operation = expr->binary_operation();
6415 if (proxy != NULL) {
6416 Variable* var = proxy->var();
6417 if (var->mode() == LET) {
6418 return Bailout(kUnsupportedLetCompoundAssignment);
6421 CHECK_ALIVE(VisitForValue(operation));
6423 switch (var->location()) {
6424 case Variable::UNALLOCATED:
6425 HandleGlobalVariableAssignment(var,
6427 expr->AssignmentId());
6430 case Variable::PARAMETER:
6431 case Variable::LOCAL:
6432 if (var->mode() == CONST_LEGACY) {
6433 return Bailout(kUnsupportedConstCompoundAssignment);
6435 BindIfLive(var, Top());
6438 case Variable::CONTEXT: {
6439 // Bail out if we try to mutate a parameter value in a function
6440 // using the arguments object. We do not (yet) correctly handle the
6441 // arguments property of the function.
6442 if (current_info()->scope()->arguments() != NULL) {
6443 // Parameters will be allocated to context slots. We have no
6444 // direct way to detect that the variable is a parameter so we do
6445 // a linear search of the parameter variables.
6446 int count = current_info()->scope()->num_parameters();
6447 for (int i = 0; i < count; ++i) {
6448 if (var == current_info()->scope()->parameter(i)) {
6449 Bailout(kAssignmentToParameterFunctionUsesArgumentsObject);
6454 HStoreContextSlot::Mode mode;
6456 switch (var->mode()) {
6458 mode = HStoreContextSlot::kCheckDeoptimize;
6461 // This case is checked statically so no need to
6462 // perform checks here
6465 return ast_context()->ReturnValue(Pop());
6467 mode = HStoreContextSlot::kNoCheck;
6470 HValue* context = BuildContextChainWalk(var);
6471 HStoreContextSlot* instr = Add<HStoreContextSlot>(
6472 context, var->index(), mode, Top());
6473 if (instr->HasObservableSideEffects()) {
6474 Add<HSimulate>(expr->AssignmentId(), REMOVABLE_SIMULATE);
6479 case Variable::LOOKUP:
6480 return Bailout(kCompoundAssignmentToLookupSlot);
6482 return ast_context()->ReturnValue(Pop());
6484 } else if (prop != NULL) {
6485 CHECK_ALIVE(VisitForValue(prop->obj()));
6486 HValue* object = Top();
6488 if ((!prop->IsFunctionPrototype() && !prop->key()->IsPropertyName()) ||
6489 prop->IsStringAccess()) {
6490 CHECK_ALIVE(VisitForValue(prop->key()));
6494 CHECK_ALIVE(PushLoad(prop, object, key));
6496 CHECK_ALIVE(VisitForValue(expr->value()));
6497 HValue* right = Pop();
6498 HValue* left = Pop();
6500 Push(BuildBinaryOperation(operation, left, right, PUSH_BEFORE_SIMULATE));
6502 BuildStore(expr, prop, expr->id(),
6503 expr->AssignmentId(), expr->IsUninitialized());
6505 return Bailout(kInvalidLhsInCompoundAssignment);
6510 void HOptimizedGraphBuilder::VisitAssignment(Assignment* expr) {
6511 ASSERT(!HasStackOverflow());
6512 ASSERT(current_block() != NULL);
6513 ASSERT(current_block()->HasPredecessor());
6514 VariableProxy* proxy = expr->target()->AsVariableProxy();
6515 Property* prop = expr->target()->AsProperty();
6516 ASSERT(proxy == NULL || prop == NULL);
6518 if (expr->is_compound()) {
6519 HandleCompoundAssignment(expr);
6524 HandlePropertyAssignment(expr);
6525 } else if (proxy != NULL) {
6526 Variable* var = proxy->var();
6528 if (var->mode() == CONST) {
6529 if (expr->op() != Token::INIT_CONST) {
6530 return Bailout(kNonInitializerAssignmentToConst);
6532 } else if (var->mode() == CONST_LEGACY) {
6533 if (expr->op() != Token::INIT_CONST_LEGACY) {
6534 CHECK_ALIVE(VisitForValue(expr->value()));
6535 return ast_context()->ReturnValue(Pop());
6538 if (var->IsStackAllocated()) {
6539 // We insert a use of the old value to detect unsupported uses of const
6540 // variables (e.g. initialization inside a loop).
6541 HValue* old_value = environment()->Lookup(var);
6542 Add<HUseConst>(old_value);
6546 if (proxy->IsArguments()) return Bailout(kAssignmentToArguments);
6548 // Handle the assignment.
6549 switch (var->location()) {
6550 case Variable::UNALLOCATED:
6551 CHECK_ALIVE(VisitForValue(expr->value()));
6552 HandleGlobalVariableAssignment(var,
6554 expr->AssignmentId());
6555 return ast_context()->ReturnValue(Pop());
6557 case Variable::PARAMETER:
6558 case Variable::LOCAL: {
6559 // Perform an initialization check for let declared variables
6561 if (var->mode() == LET && expr->op() == Token::ASSIGN) {
6562 HValue* env_value = environment()->Lookup(var);
6563 if (env_value == graph()->GetConstantHole()) {
6564 return Bailout(kAssignmentToLetVariableBeforeInitialization);
6567 // We do not allow the arguments object to occur in a context where it
6568 // may escape, but assignments to stack-allocated locals are
6570 CHECK_ALIVE(VisitForValue(expr->value(), ARGUMENTS_ALLOWED));
6571 HValue* value = Pop();
6572 BindIfLive(var, value);
6573 return ast_context()->ReturnValue(value);
6576 case Variable::CONTEXT: {
6577 // Bail out if we try to mutate a parameter value in a function using
6578 // the arguments object. We do not (yet) correctly handle the
6579 // arguments property of the function.
6580 if (current_info()->scope()->arguments() != NULL) {
6581 // Parameters will rewrite to context slots. We have no direct way
6582 // to detect that the variable is a parameter.
6583 int count = current_info()->scope()->num_parameters();
6584 for (int i = 0; i < count; ++i) {
6585 if (var == current_info()->scope()->parameter(i)) {
6586 return Bailout(kAssignmentToParameterInArgumentsObject);
6591 CHECK_ALIVE(VisitForValue(expr->value()));
6592 HStoreContextSlot::Mode mode;
6593 if (expr->op() == Token::ASSIGN) {
6594 switch (var->mode()) {
6596 mode = HStoreContextSlot::kCheckDeoptimize;
6599 // This case is checked statically so no need to
6600 // perform checks here
6603 return ast_context()->ReturnValue(Pop());
6605 mode = HStoreContextSlot::kNoCheck;
6607 } else if (expr->op() == Token::INIT_VAR ||
6608 expr->op() == Token::INIT_LET ||
6609 expr->op() == Token::INIT_CONST) {
6610 mode = HStoreContextSlot::kNoCheck;
6612 ASSERT(expr->op() == Token::INIT_CONST_LEGACY);
6614 mode = HStoreContextSlot::kCheckIgnoreAssignment;
6617 HValue* context = BuildContextChainWalk(var);
6618 HStoreContextSlot* instr = Add<HStoreContextSlot>(
6619 context, var->index(), mode, Top());
6620 if (instr->HasObservableSideEffects()) {
6621 Add<HSimulate>(expr->AssignmentId(), REMOVABLE_SIMULATE);
6623 return ast_context()->ReturnValue(Pop());
6626 case Variable::LOOKUP:
6627 return Bailout(kAssignmentToLOOKUPVariable);
6630 return Bailout(kInvalidLeftHandSideInAssignment);
6635 void HOptimizedGraphBuilder::VisitYield(Yield* expr) {
6636 // Generators are not optimized, so we should never get here.
6641 void HOptimizedGraphBuilder::VisitThrow(Throw* expr) {
6642 ASSERT(!HasStackOverflow());
6643 ASSERT(current_block() != NULL);
6644 ASSERT(current_block()->HasPredecessor());
6645 // We don't optimize functions with invalid left-hand sides in
6646 // assignments, count operations, or for-in. Consequently throw can
6647 // currently only occur in an effect context.
6648 ASSERT(ast_context()->IsEffect());
6649 CHECK_ALIVE(VisitForValue(expr->exception()));
6651 HValue* value = environment()->Pop();
6652 if (!FLAG_hydrogen_track_positions) SetSourcePosition(expr->position());
6653 Add<HPushArguments>(value);
6654 Add<HCallRuntime>(isolate()->factory()->empty_string(),
6655 Runtime::FunctionForId(Runtime::kHiddenThrow), 1);
6656 Add<HSimulate>(expr->id());
6658 // If the throw definitely exits the function, we can finish with a dummy
6659 // control flow at this point. This is not the case if the throw is inside
6660 // an inlined function which may be replaced.
6661 if (call_context() == NULL) {
6662 FinishExitCurrentBlock(New<HAbnormalExit>());
6667 HInstruction* HGraphBuilder::AddLoadStringInstanceType(HValue* string) {
6668 if (string->IsConstant()) {
6669 HConstant* c_string = HConstant::cast(string);
6670 if (c_string->HasStringValue()) {
6671 return Add<HConstant>(c_string->StringValue()->map()->instance_type());
6674 return Add<HLoadNamedField>(
6675 Add<HLoadNamedField>(string, static_cast<HValue*>(NULL),
6676 HObjectAccess::ForMap()),
6677 static_cast<HValue*>(NULL), HObjectAccess::ForMapInstanceType());
6681 HInstruction* HGraphBuilder::AddLoadStringLength(HValue* string) {
6682 if (string->IsConstant()) {
6683 HConstant* c_string = HConstant::cast(string);
6684 if (c_string->HasStringValue()) {
6685 return Add<HConstant>(c_string->StringValue()->length());
6688 return Add<HLoadNamedField>(string, static_cast<HValue*>(NULL),
6689 HObjectAccess::ForStringLength());
6693 HInstruction* HOptimizedGraphBuilder::BuildNamedGeneric(
6694 PropertyAccessType access_type,
6696 Handle<String> name,
6698 bool is_uninitialized) {
6699 if (is_uninitialized) {
6700 Add<HDeoptimize>("Insufficient type feedback for generic named access",
6703 if (access_type == LOAD) {
6704 return New<HLoadNamedGeneric>(object, name);
6706 return New<HStoreNamedGeneric>(object, name, value, function_strict_mode());
6712 HInstruction* HOptimizedGraphBuilder::BuildKeyedGeneric(
6713 PropertyAccessType access_type,
6717 if (access_type == LOAD) {
6718 return New<HLoadKeyedGeneric>(object, key);
6720 return New<HStoreKeyedGeneric>(object, key, value, function_strict_mode());
6725 LoadKeyedHoleMode HOptimizedGraphBuilder::BuildKeyedHoleMode(Handle<Map> map) {
6726 // Loads from a "stock" fast holey double arrays can elide the hole check.
6727 LoadKeyedHoleMode load_mode = NEVER_RETURN_HOLE;
6728 if (*map == isolate()->get_initial_js_array_map(FAST_HOLEY_DOUBLE_ELEMENTS) &&
6729 isolate()->IsFastArrayConstructorPrototypeChainIntact()) {
6730 Handle<JSObject> prototype(JSObject::cast(map->prototype()), isolate());
6731 Handle<JSObject> object_prototype = isolate()->initial_object_prototype();
6732 BuildCheckPrototypeMaps(prototype, object_prototype);
6733 load_mode = ALLOW_RETURN_HOLE;
6734 graph()->MarkDependsOnEmptyArrayProtoElements();
6741 HInstruction* HOptimizedGraphBuilder::BuildMonomorphicElementAccess(
6747 PropertyAccessType access_type,
6748 KeyedAccessStoreMode store_mode) {
6749 HCheckMaps* checked_object = Add<HCheckMaps>(object, map, dependency);
6751 checked_object->ClearDependsOnFlag(kElementsKind);
6754 if (access_type == STORE && map->prototype()->IsJSObject()) {
6755 // monomorphic stores need a prototype chain check because shape
6756 // changes could allow callbacks on elements in the chain that
6757 // aren't compatible with monomorphic keyed stores.
6758 Handle<JSObject> prototype(JSObject::cast(map->prototype()));
6759 JSObject* holder = JSObject::cast(map->prototype());
6760 while (!holder->GetPrototype()->IsNull()) {
6761 holder = JSObject::cast(holder->GetPrototype());
6764 BuildCheckPrototypeMaps(prototype,
6765 Handle<JSObject>(JSObject::cast(holder)));
6768 LoadKeyedHoleMode load_mode = BuildKeyedHoleMode(map);
6769 return BuildUncheckedMonomorphicElementAccess(
6770 checked_object, key, val,
6771 map->instance_type() == JS_ARRAY_TYPE,
6772 map->elements_kind(), access_type,
6773 load_mode, store_mode);
6777 HInstruction* HOptimizedGraphBuilder::TryBuildConsolidatedElementLoad(
6781 SmallMapList* maps) {
6782 // For polymorphic loads of similar elements kinds (i.e. all tagged or all
6783 // double), always use the "worst case" code without a transition. This is
6784 // much faster than transitioning the elements to the worst case, trading a
6785 // HTransitionElements for a HCheckMaps, and avoiding mutation of the array.
6786 bool has_double_maps = false;
6787 bool has_smi_or_object_maps = false;
6788 bool has_js_array_access = false;
6789 bool has_non_js_array_access = false;
6790 bool has_seen_holey_elements = false;
6791 Handle<Map> most_general_consolidated_map;
6792 for (int i = 0; i < maps->length(); ++i) {
6793 Handle<Map> map = maps->at(i);
6794 if (!map->IsJSObjectMap()) return NULL;
6795 // Don't allow mixing of JSArrays with JSObjects.
6796 if (map->instance_type() == JS_ARRAY_TYPE) {
6797 if (has_non_js_array_access) return NULL;
6798 has_js_array_access = true;
6799 } else if (has_js_array_access) {
6802 has_non_js_array_access = true;
6804 // Don't allow mixed, incompatible elements kinds.
6805 if (map->has_fast_double_elements()) {
6806 if (has_smi_or_object_maps) return NULL;
6807 has_double_maps = true;
6808 } else if (map->has_fast_smi_or_object_elements()) {
6809 if (has_double_maps) return NULL;
6810 has_smi_or_object_maps = true;
6814 // Remember if we've ever seen holey elements.
6815 if (IsHoleyElementsKind(map->elements_kind())) {
6816 has_seen_holey_elements = true;
6818 // Remember the most general elements kind, the code for its load will
6819 // properly handle all of the more specific cases.
6820 if ((i == 0) || IsMoreGeneralElementsKindTransition(
6821 most_general_consolidated_map->elements_kind(),
6822 map->elements_kind())) {
6823 most_general_consolidated_map = map;
6826 if (!has_double_maps && !has_smi_or_object_maps) return NULL;
6828 HCheckMaps* checked_object = Add<HCheckMaps>(object, maps);
6829 // FAST_ELEMENTS is considered more general than FAST_HOLEY_SMI_ELEMENTS.
6830 // If we've seen both, the consolidated load must use FAST_HOLEY_ELEMENTS.
6831 ElementsKind consolidated_elements_kind = has_seen_holey_elements
6832 ? GetHoleyElementsKind(most_general_consolidated_map->elements_kind())
6833 : most_general_consolidated_map->elements_kind();
6834 HInstruction* instr = BuildUncheckedMonomorphicElementAccess(
6835 checked_object, key, val,
6836 most_general_consolidated_map->instance_type() == JS_ARRAY_TYPE,
6837 consolidated_elements_kind,
6838 LOAD, NEVER_RETURN_HOLE, STANDARD_STORE);
6843 HValue* HOptimizedGraphBuilder::HandlePolymorphicElementAccess(
6848 PropertyAccessType access_type,
6849 KeyedAccessStoreMode store_mode,
6850 bool* has_side_effects) {
6851 *has_side_effects = false;
6852 BuildCheckHeapObject(object);
6854 if (access_type == LOAD) {
6855 HInstruction* consolidated_load =
6856 TryBuildConsolidatedElementLoad(object, key, val, maps);
6857 if (consolidated_load != NULL) {
6858 *has_side_effects |= consolidated_load->HasObservableSideEffects();
6859 return consolidated_load;
6863 // Elements_kind transition support.
6864 MapHandleList transition_target(maps->length());
6865 // Collect possible transition targets.
6866 MapHandleList possible_transitioned_maps(maps->length());
6867 for (int i = 0; i < maps->length(); ++i) {
6868 Handle<Map> map = maps->at(i);
6869 ElementsKind elements_kind = map->elements_kind();
6870 if (IsFastElementsKind(elements_kind) &&
6871 elements_kind != GetInitialFastElementsKind()) {
6872 possible_transitioned_maps.Add(map);
6874 if (elements_kind == SLOPPY_ARGUMENTS_ELEMENTS) {
6875 HInstruction* result = BuildKeyedGeneric(access_type, object, key, val);
6876 *has_side_effects = result->HasObservableSideEffects();
6877 return AddInstruction(result);
6880 // Get transition target for each map (NULL == no transition).
6881 for (int i = 0; i < maps->length(); ++i) {
6882 Handle<Map> map = maps->at(i);
6883 Handle<Map> transitioned_map =
6884 map->FindTransitionedMap(&possible_transitioned_maps);
6885 transition_target.Add(transitioned_map);
6888 MapHandleList untransitionable_maps(maps->length());
6889 HTransitionElementsKind* transition = NULL;
6890 for (int i = 0; i < maps->length(); ++i) {
6891 Handle<Map> map = maps->at(i);
6892 ASSERT(map->IsMap());
6893 if (!transition_target.at(i).is_null()) {
6894 ASSERT(Map::IsValidElementsTransition(
6895 map->elements_kind(),
6896 transition_target.at(i)->elements_kind()));
6897 transition = Add<HTransitionElementsKind>(object, map,
6898 transition_target.at(i));
6900 untransitionable_maps.Add(map);
6904 // If only one map is left after transitioning, handle this case
6906 ASSERT(untransitionable_maps.length() >= 1);
6907 if (untransitionable_maps.length() == 1) {
6908 Handle<Map> untransitionable_map = untransitionable_maps[0];
6909 HInstruction* instr = NULL;
6910 if (untransitionable_map->has_slow_elements_kind() ||
6911 !untransitionable_map->IsJSObjectMap()) {
6912 instr = AddInstruction(BuildKeyedGeneric(access_type, object, key, val));
6914 instr = BuildMonomorphicElementAccess(
6915 object, key, val, transition, untransitionable_map, access_type,
6918 *has_side_effects |= instr->HasObservableSideEffects();
6919 return access_type == STORE ? NULL : instr;
6922 HBasicBlock* join = graph()->CreateBasicBlock();
6924 for (int i = 0; i < untransitionable_maps.length(); ++i) {
6925 Handle<Map> map = untransitionable_maps[i];
6926 if (!map->IsJSObjectMap()) continue;
6927 ElementsKind elements_kind = map->elements_kind();
6928 HBasicBlock* this_map = graph()->CreateBasicBlock();
6929 HBasicBlock* other_map = graph()->CreateBasicBlock();
6930 HCompareMap* mapcompare =
6931 New<HCompareMap>(object, map, this_map, other_map);
6932 FinishCurrentBlock(mapcompare);
6934 set_current_block(this_map);
6935 HInstruction* access = NULL;
6936 if (IsDictionaryElementsKind(elements_kind)) {
6937 access = AddInstruction(BuildKeyedGeneric(access_type, object, key, val));
6939 ASSERT(IsFastElementsKind(elements_kind) ||
6940 IsExternalArrayElementsKind(elements_kind) ||
6941 IsFixedTypedArrayElementsKind(elements_kind));
6942 LoadKeyedHoleMode load_mode = BuildKeyedHoleMode(map);
6943 // Happily, mapcompare is a checked object.
6944 access = BuildUncheckedMonomorphicElementAccess(
6945 mapcompare, key, val,
6946 map->instance_type() == JS_ARRAY_TYPE,
6947 elements_kind, access_type,
6951 *has_side_effects |= access->HasObservableSideEffects();
6952 // The caller will use has_side_effects and add a correct Simulate.
6953 access->SetFlag(HValue::kHasNoObservableSideEffects);
6954 if (access_type == LOAD) {
6957 NoObservableSideEffectsScope scope(this);
6958 GotoNoSimulate(join);
6959 set_current_block(other_map);
6962 // Ensure that we visited at least one map above that goes to join. This is
6963 // necessary because FinishExitWithHardDeoptimization does an AbnormalExit
6964 // rather than joining the join block. If this becomes an issue, insert a
6965 // generic access in the case length() == 0.
6966 ASSERT(join->predecessors()->length() > 0);
6967 // Deopt if none of the cases matched.
6968 NoObservableSideEffectsScope scope(this);
6969 FinishExitWithHardDeoptimization("Unknown map in polymorphic element access");
6970 set_current_block(join);
6971 return access_type == STORE ? NULL : Pop();
6975 HValue* HOptimizedGraphBuilder::HandleKeyedElementAccess(
6980 PropertyAccessType access_type,
6981 bool* has_side_effects) {
6982 ASSERT(!expr->IsPropertyName());
6983 HInstruction* instr = NULL;
6985 SmallMapList* types;
6986 bool monomorphic = ComputeReceiverTypes(expr, obj, &types, zone());
6988 bool force_generic = false;
6989 if (access_type == STORE &&
6990 (monomorphic || (types != NULL && !types->is_empty()))) {
6991 // Stores can't be mono/polymorphic if their prototype chain has dictionary
6992 // elements. However a receiver map that has dictionary elements itself
6993 // should be left to normal mono/poly behavior (the other maps may benefit
6994 // from highly optimized stores).
6995 for (int i = 0; i < types->length(); i++) {
6996 Handle<Map> current_map = types->at(i);
6997 if (current_map->DictionaryElementsInPrototypeChainOnly()) {
6998 force_generic = true;
6999 monomorphic = false;
7006 Handle<Map> map = types->first();
7007 if (map->has_slow_elements_kind() || !map->IsJSObjectMap()) {
7008 instr = AddInstruction(BuildKeyedGeneric(access_type, obj, key, val));
7010 BuildCheckHeapObject(obj);
7011 instr = BuildMonomorphicElementAccess(
7012 obj, key, val, NULL, map, access_type, expr->GetStoreMode());
7014 } else if (!force_generic && (types != NULL && !types->is_empty())) {
7015 return HandlePolymorphicElementAccess(
7016 obj, key, val, types, access_type,
7017 expr->GetStoreMode(), has_side_effects);
7019 if (access_type == STORE) {
7020 if (expr->IsAssignment() &&
7021 expr->AsAssignment()->HasNoTypeInformation()) {
7022 Add<HDeoptimize>("Insufficient type feedback for keyed store",
7026 if (expr->AsProperty()->HasNoTypeInformation()) {
7027 Add<HDeoptimize>("Insufficient type feedback for keyed load",
7031 instr = AddInstruction(BuildKeyedGeneric(access_type, obj, key, val));
7033 *has_side_effects = instr->HasObservableSideEffects();
7038 void HOptimizedGraphBuilder::EnsureArgumentsArePushedForAccess() {
7039 // Outermost function already has arguments on the stack.
7040 if (function_state()->outer() == NULL) return;
7042 if (function_state()->arguments_pushed()) return;
7044 // Push arguments when entering inlined function.
7045 HEnterInlined* entry = function_state()->entry();
7046 entry->set_arguments_pushed();
7048 HArgumentsObject* arguments = entry->arguments_object();
7049 const ZoneList<HValue*>* arguments_values = arguments->arguments_values();
7051 HInstruction* insert_after = entry;
7052 for (int i = 0; i < arguments_values->length(); i++) {
7053 HValue* argument = arguments_values->at(i);
7054 HInstruction* push_argument = New<HPushArguments>(argument);
7055 push_argument->InsertAfter(insert_after);
7056 insert_after = push_argument;
7059 HArgumentsElements* arguments_elements = New<HArgumentsElements>(true);
7060 arguments_elements->ClearFlag(HValue::kUseGVN);
7061 arguments_elements->InsertAfter(insert_after);
7062 function_state()->set_arguments_elements(arguments_elements);
7066 bool HOptimizedGraphBuilder::TryArgumentsAccess(Property* expr) {
7067 VariableProxy* proxy = expr->obj()->AsVariableProxy();
7068 if (proxy == NULL) return false;
7069 if (!proxy->var()->IsStackAllocated()) return false;
7070 if (!environment()->Lookup(proxy->var())->CheckFlag(HValue::kIsArguments)) {
7074 HInstruction* result = NULL;
7075 if (expr->key()->IsPropertyName()) {
7076 Handle<String> name = expr->key()->AsLiteral()->AsPropertyName();
7077 if (!name->IsOneByteEqualTo(STATIC_ASCII_VECTOR("length"))) return false;
7079 if (function_state()->outer() == NULL) {
7080 HInstruction* elements = Add<HArgumentsElements>(false);
7081 result = New<HArgumentsLength>(elements);
7083 // Number of arguments without receiver.
7084 int argument_count = environment()->
7085 arguments_environment()->parameter_count() - 1;
7086 result = New<HConstant>(argument_count);
7089 Push(graph()->GetArgumentsObject());
7090 CHECK_ALIVE_OR_RETURN(VisitForValue(expr->key()), true);
7091 HValue* key = Pop();
7092 Drop(1); // Arguments object.
7093 if (function_state()->outer() == NULL) {
7094 HInstruction* elements = Add<HArgumentsElements>(false);
7095 HInstruction* length = Add<HArgumentsLength>(elements);
7096 HInstruction* checked_key = Add<HBoundsCheck>(key, length);
7097 result = New<HAccessArgumentsAt>(elements, length, checked_key);
7099 EnsureArgumentsArePushedForAccess();
7101 // Number of arguments without receiver.
7102 HInstruction* elements = function_state()->arguments_elements();
7103 int argument_count = environment()->
7104 arguments_environment()->parameter_count() - 1;
7105 HInstruction* length = Add<HConstant>(argument_count);
7106 HInstruction* checked_key = Add<HBoundsCheck>(key, length);
7107 result = New<HAccessArgumentsAt>(elements, length, checked_key);
7110 ast_context()->ReturnInstruction(result, expr->id());
7115 HInstruction* HOptimizedGraphBuilder::BuildNamedAccess(
7116 PropertyAccessType access,
7118 BailoutId return_id,
7121 Handle<String> name,
7123 bool is_uninitialized) {
7124 SmallMapList* types;
7125 ComputeReceiverTypes(expr, object, &types, zone());
7126 ASSERT(types != NULL);
7128 if (types->length() > 0) {
7129 PropertyAccessInfo info(this, access, ToType(types->first()), name);
7130 if (!info.CanAccessAsMonomorphic(types)) {
7131 HandlePolymorphicNamedFieldAccess(
7132 access, ast_id, return_id, object, value, types, name);
7136 HValue* checked_object;
7137 // Type::Number() is only supported by polymorphic load/call handling.
7138 ASSERT(!info.type()->Is(Type::Number()));
7139 BuildCheckHeapObject(object);
7140 if (AreStringTypes(types)) {
7142 Add<HCheckInstanceType>(object, HCheckInstanceType::IS_STRING);
7144 checked_object = Add<HCheckMaps>(object, types);
7146 return BuildMonomorphicAccess(
7147 &info, object, checked_object, value, ast_id, return_id);
7150 return BuildNamedGeneric(access, object, name, value, is_uninitialized);
7154 void HOptimizedGraphBuilder::PushLoad(Property* expr,
7157 ValueContext for_value(this, ARGUMENTS_NOT_ALLOWED);
7159 if (key != NULL) Push(key);
7160 BuildLoad(expr, expr->LoadId());
7164 void HOptimizedGraphBuilder::BuildLoad(Property* expr,
7166 HInstruction* instr = NULL;
7167 if (expr->IsStringAccess()) {
7168 HValue* index = Pop();
7169 HValue* string = Pop();
7170 HInstruction* char_code = BuildStringCharCodeAt(string, index);
7171 AddInstruction(char_code);
7172 instr = NewUncasted<HStringCharFromCode>(char_code);
7174 } else if (expr->IsFunctionPrototype()) {
7175 HValue* function = Pop();
7176 BuildCheckHeapObject(function);
7177 instr = New<HLoadFunctionPrototype>(function);
7179 } else if (expr->key()->IsPropertyName()) {
7180 Handle<String> name = expr->key()->AsLiteral()->AsPropertyName();
7181 HValue* object = Pop();
7183 instr = BuildNamedAccess(LOAD, ast_id, expr->LoadId(), expr,
7184 object, name, NULL, expr->IsUninitialized());
7185 if (instr == NULL) return;
7186 if (instr->IsLinked()) return ast_context()->ReturnValue(instr);
7189 HValue* key = Pop();
7190 HValue* obj = Pop();
7192 bool has_side_effects = false;
7193 HValue* load = HandleKeyedElementAccess(
7194 obj, key, NULL, expr, LOAD, &has_side_effects);
7195 if (has_side_effects) {
7196 if (ast_context()->IsEffect()) {
7197 Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
7200 Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
7204 return ast_context()->ReturnValue(load);
7206 return ast_context()->ReturnInstruction(instr, ast_id);
7210 void HOptimizedGraphBuilder::VisitProperty(Property* expr) {
7211 ASSERT(!HasStackOverflow());
7212 ASSERT(current_block() != NULL);
7213 ASSERT(current_block()->HasPredecessor());
7215 if (TryArgumentsAccess(expr)) return;
7217 CHECK_ALIVE(VisitForValue(expr->obj()));
7218 if ((!expr->IsFunctionPrototype() && !expr->key()->IsPropertyName()) ||
7219 expr->IsStringAccess()) {
7220 CHECK_ALIVE(VisitForValue(expr->key()));
7223 BuildLoad(expr, expr->id());
7227 HInstruction* HGraphBuilder::BuildConstantMapCheck(Handle<JSObject> constant) {
7228 HCheckMaps* check = Add<HCheckMaps>(
7229 Add<HConstant>(constant), handle(constant->map()));
7230 check->ClearDependsOnFlag(kElementsKind);
7235 HInstruction* HGraphBuilder::BuildCheckPrototypeMaps(Handle<JSObject> prototype,
7236 Handle<JSObject> holder) {
7237 while (holder.is_null() || !prototype.is_identical_to(holder)) {
7238 BuildConstantMapCheck(prototype);
7239 Object* next_prototype = prototype->GetPrototype();
7240 if (next_prototype->IsNull()) return NULL;
7241 CHECK(next_prototype->IsJSObject());
7242 prototype = handle(JSObject::cast(next_prototype));
7244 return BuildConstantMapCheck(prototype);
7248 void HOptimizedGraphBuilder::AddCheckPrototypeMaps(Handle<JSObject> holder,
7249 Handle<Map> receiver_map) {
7250 if (!holder.is_null()) {
7251 Handle<JSObject> prototype(JSObject::cast(receiver_map->prototype()));
7252 BuildCheckPrototypeMaps(prototype, holder);
7257 HInstruction* HOptimizedGraphBuilder::NewPlainFunctionCall(
7258 HValue* fun, int argument_count, bool pass_argument_count) {
7259 return New<HCallJSFunction>(
7260 fun, argument_count, pass_argument_count);
7264 HInstruction* HOptimizedGraphBuilder::NewArgumentAdaptorCall(
7265 HValue* fun, HValue* context,
7266 int argument_count, HValue* expected_param_count) {
7267 CallInterfaceDescriptor* descriptor =
7268 isolate()->call_descriptor(Isolate::ArgumentAdaptorCall);
7270 HValue* arity = Add<HConstant>(argument_count - 1);
7272 HValue* op_vals[] = { fun, context, arity, expected_param_count };
7274 Handle<Code> adaptor =
7275 isolate()->builtins()->ArgumentsAdaptorTrampoline();
7276 HConstant* adaptor_value = Add<HConstant>(adaptor);
7278 return New<HCallWithDescriptor>(
7279 adaptor_value, argument_count, descriptor,
7280 Vector<HValue*>(op_vals, descriptor->environment_length()));
7284 HInstruction* HOptimizedGraphBuilder::BuildCallConstantFunction(
7285 Handle<JSFunction> jsfun, int argument_count) {
7286 HValue* target = Add<HConstant>(jsfun);
7287 // For constant functions, we try to avoid calling the
7288 // argument adaptor and instead call the function directly
7289 int formal_parameter_count = jsfun->shared()->formal_parameter_count();
7290 bool dont_adapt_arguments =
7291 (formal_parameter_count ==
7292 SharedFunctionInfo::kDontAdaptArgumentsSentinel);
7293 int arity = argument_count - 1;
7294 bool can_invoke_directly =
7295 dont_adapt_arguments || formal_parameter_count == arity;
7296 if (can_invoke_directly) {
7297 if (jsfun.is_identical_to(current_info()->closure())) {
7298 graph()->MarkRecursive();
7300 return NewPlainFunctionCall(target, argument_count, dont_adapt_arguments);
7302 HValue* param_count_value = Add<HConstant>(formal_parameter_count);
7303 HValue* context = Add<HLoadNamedField>(
7304 target, static_cast<HValue*>(NULL),
7305 HObjectAccess::ForFunctionContextPointer());
7306 return NewArgumentAdaptorCall(target, context,
7307 argument_count, param_count_value);
7314 class FunctionSorter {
7316 FunctionSorter(int index = 0, int ticks = 0, int size = 0)
7317 : index_(index), ticks_(ticks), size_(size) { }
7319 int index() const { return index_; }
7320 int ticks() const { return ticks_; }
7321 int size() const { return size_; }
7330 inline bool operator<(const FunctionSorter& lhs, const FunctionSorter& rhs) {
7331 int diff = lhs.ticks() - rhs.ticks();
7332 if (diff != 0) return diff > 0;
7333 return lhs.size() < rhs.size();
7337 void HOptimizedGraphBuilder::HandlePolymorphicCallNamed(
7340 SmallMapList* types,
7341 Handle<String> name) {
7342 int argument_count = expr->arguments()->length() + 1; // Includes receiver.
7343 FunctionSorter order[kMaxCallPolymorphism];
7345 bool handle_smi = false;
7346 bool handled_string = false;
7347 int ordered_functions = 0;
7350 i < types->length() && ordered_functions < kMaxCallPolymorphism;
7352 PropertyAccessInfo info(this, LOAD, ToType(types->at(i)), name);
7353 if (info.CanAccessMonomorphic() &&
7354 info.lookup()->IsConstant() &&
7355 info.constant()->IsJSFunction()) {
7356 if (info.type()->Is(Type::String())) {
7357 if (handled_string) continue;
7358 handled_string = true;
7360 Handle<JSFunction> target = Handle<JSFunction>::cast(info.constant());
7361 if (info.type()->Is(Type::Number())) {
7364 expr->set_target(target);
7365 order[ordered_functions++] = FunctionSorter(
7366 i, target->shared()->profiler_ticks(), InliningAstSize(target));
7370 std::sort(order, order + ordered_functions);
7372 HBasicBlock* number_block = NULL;
7373 HBasicBlock* join = NULL;
7374 handled_string = false;
7377 for (int fn = 0; fn < ordered_functions; ++fn) {
7378 int i = order[fn].index();
7379 PropertyAccessInfo info(this, LOAD, ToType(types->at(i)), name);
7380 if (info.type()->Is(Type::String())) {
7381 if (handled_string) continue;
7382 handled_string = true;
7384 // Reloads the target.
7385 info.CanAccessMonomorphic();
7386 Handle<JSFunction> target = Handle<JSFunction>::cast(info.constant());
7388 expr->set_target(target);
7390 // Only needed once.
7391 join = graph()->CreateBasicBlock();
7393 HBasicBlock* empty_smi_block = graph()->CreateBasicBlock();
7394 HBasicBlock* not_smi_block = graph()->CreateBasicBlock();
7395 number_block = graph()->CreateBasicBlock();
7396 FinishCurrentBlock(New<HIsSmiAndBranch>(
7397 receiver, empty_smi_block, not_smi_block));
7398 GotoNoSimulate(empty_smi_block, number_block);
7399 set_current_block(not_smi_block);
7401 BuildCheckHeapObject(receiver);
7405 HBasicBlock* if_true = graph()->CreateBasicBlock();
7406 HBasicBlock* if_false = graph()->CreateBasicBlock();
7407 HUnaryControlInstruction* compare;
7409 Handle<Map> map = info.map();
7410 if (info.type()->Is(Type::Number())) {
7411 Handle<Map> heap_number_map = isolate()->factory()->heap_number_map();
7412 compare = New<HCompareMap>(receiver, heap_number_map, if_true, if_false);
7413 } else if (info.type()->Is(Type::String())) {
7414 compare = New<HIsStringAndBranch>(receiver, if_true, if_false);
7416 compare = New<HCompareMap>(receiver, map, if_true, if_false);
7418 FinishCurrentBlock(compare);
7420 if (info.type()->Is(Type::Number())) {
7421 GotoNoSimulate(if_true, number_block);
7422 if_true = number_block;
7425 set_current_block(if_true);
7427 AddCheckPrototypeMaps(info.holder(), map);
7429 HValue* function = Add<HConstant>(expr->target());
7430 environment()->SetExpressionStackAt(0, function);
7432 CHECK_ALIVE(VisitExpressions(expr->arguments()));
7433 bool needs_wrapping = NeedsWrappingFor(info.type(), target);
7434 bool try_inline = FLAG_polymorphic_inlining && !needs_wrapping;
7435 if (FLAG_trace_inlining && try_inline) {
7436 Handle<JSFunction> caller = current_info()->closure();
7437 SmartArrayPointer<char> caller_name =
7438 caller->shared()->DebugName()->ToCString();
7439 PrintF("Trying to inline the polymorphic call to %s from %s\n",
7440 name->ToCString().get(),
7443 if (try_inline && TryInlineCall(expr)) {
7444 // Trying to inline will signal that we should bailout from the
7445 // entire compilation by setting stack overflow on the visitor.
7446 if (HasStackOverflow()) return;
7448 // Since HWrapReceiver currently cannot actually wrap numbers and strings,
7449 // use the regular CallFunctionStub for method calls to wrap the receiver.
7450 // TODO(verwaest): Support creation of value wrappers directly in
7452 HInstruction* call = needs_wrapping
7453 ? NewUncasted<HCallFunction>(
7454 function, argument_count, WRAP_AND_CALL)
7455 : BuildCallConstantFunction(target, argument_count);
7456 PushArgumentsFromEnvironment(argument_count);
7457 AddInstruction(call);
7458 Drop(1); // Drop the function.
7459 if (!ast_context()->IsEffect()) Push(call);
7462 if (current_block() != NULL) Goto(join);
7463 set_current_block(if_false);
7466 // Finish up. Unconditionally deoptimize if we've handled all the maps we
7467 // know about and do not want to handle ones we've never seen. Otherwise
7468 // use a generic IC.
7469 if (ordered_functions == types->length() && FLAG_deoptimize_uncommon_cases) {
7470 FinishExitWithHardDeoptimization("Unknown map in polymorphic call");
7472 Property* prop = expr->expression()->AsProperty();
7473 HInstruction* function = BuildNamedGeneric(
7474 LOAD, receiver, name, NULL, prop->IsUninitialized());
7475 AddInstruction(function);
7477 AddSimulate(prop->LoadId(), REMOVABLE_SIMULATE);
7479 environment()->SetExpressionStackAt(1, function);
7480 environment()->SetExpressionStackAt(0, receiver);
7481 CHECK_ALIVE(VisitExpressions(expr->arguments()));
7483 CallFunctionFlags flags = receiver->type().IsJSObject()
7484 ? NO_CALL_FUNCTION_FLAGS : CALL_AS_METHOD;
7485 HInstruction* call = New<HCallFunction>(
7486 function, argument_count, flags);
7488 PushArgumentsFromEnvironment(argument_count);
7490 Drop(1); // Function.
7493 AddInstruction(call);
7494 if (!ast_context()->IsEffect()) Push(call);
7497 return ast_context()->ReturnInstruction(call, expr->id());
7501 // We assume that control flow is always live after an expression. So
7502 // even without predecessors to the join block, we set it as the exit
7503 // block and continue by adding instructions there.
7504 ASSERT(join != NULL);
7505 if (join->HasPredecessor()) {
7506 set_current_block(join);
7507 join->SetJoinId(expr->id());
7508 if (!ast_context()->IsEffect()) return ast_context()->ReturnValue(Pop());
7510 set_current_block(NULL);
7515 void HOptimizedGraphBuilder::TraceInline(Handle<JSFunction> target,
7516 Handle<JSFunction> caller,
7517 const char* reason) {
7518 if (FLAG_trace_inlining) {
7519 SmartArrayPointer<char> target_name =
7520 target->shared()->DebugName()->ToCString();
7521 SmartArrayPointer<char> caller_name =
7522 caller->shared()->DebugName()->ToCString();
7523 if (reason == NULL) {
7524 PrintF("Inlined %s called from %s.\n", target_name.get(),
7527 PrintF("Did not inline %s called from %s (%s).\n",
7528 target_name.get(), caller_name.get(), reason);
7534 static const int kNotInlinable = 1000000000;
7537 int HOptimizedGraphBuilder::InliningAstSize(Handle<JSFunction> target) {
7538 if (!FLAG_use_inlining) return kNotInlinable;
7540 // Precondition: call is monomorphic and we have found a target with the
7541 // appropriate arity.
7542 Handle<JSFunction> caller = current_info()->closure();
7543 Handle<SharedFunctionInfo> target_shared(target->shared());
7545 // Always inline builtins marked for inlining.
7546 if (target->IsBuiltin()) {
7547 return target_shared->inline_builtin() ? 0 : kNotInlinable;
7550 if (target_shared->IsApiFunction()) {
7551 TraceInline(target, caller, "target is api function");
7552 return kNotInlinable;
7555 // Do a quick check on source code length to avoid parsing large
7556 // inlining candidates.
7557 if (target_shared->SourceSize() >
7558 Min(FLAG_max_inlined_source_size, kUnlimitedMaxInlinedSourceSize)) {
7559 TraceInline(target, caller, "target text too big");
7560 return kNotInlinable;
7563 // Target must be inlineable.
7564 if (!target_shared->IsInlineable()) {
7565 TraceInline(target, caller, "target not inlineable");
7566 return kNotInlinable;
7568 if (target_shared->dont_inline() || target_shared->dont_optimize()) {
7569 TraceInline(target, caller, "target contains unsupported syntax [early]");
7570 return kNotInlinable;
7573 int nodes_added = target_shared->ast_node_count();
7578 bool HOptimizedGraphBuilder::TryInline(Handle<JSFunction> target,
7579 int arguments_count,
7580 HValue* implicit_return_value,
7582 BailoutId return_id,
7583 InliningKind inlining_kind,
7584 HSourcePosition position) {
7585 int nodes_added = InliningAstSize(target);
7586 if (nodes_added == kNotInlinable) return false;
7588 Handle<JSFunction> caller = current_info()->closure();
7590 if (nodes_added > Min(FLAG_max_inlined_nodes, kUnlimitedMaxInlinedNodes)) {
7591 TraceInline(target, caller, "target AST is too large [early]");
7595 // Don't inline deeper than the maximum number of inlining levels.
7596 HEnvironment* env = environment();
7597 int current_level = 1;
7598 while (env->outer() != NULL) {
7599 if (current_level == FLAG_max_inlining_levels) {
7600 TraceInline(target, caller, "inline depth limit reached");
7603 if (env->outer()->frame_type() == JS_FUNCTION) {
7609 // Don't inline recursive functions.
7610 for (FunctionState* state = function_state();
7612 state = state->outer()) {
7613 if (*state->compilation_info()->closure() == *target) {
7614 TraceInline(target, caller, "target is recursive");
7619 // We don't want to add more than a certain number of nodes from inlining.
7620 if (inlined_count_ > Min(FLAG_max_inlined_nodes_cumulative,
7621 kUnlimitedMaxInlinedNodesCumulative)) {
7622 TraceInline(target, caller, "cumulative AST node limit reached");
7626 // Parse and allocate variables.
7627 CompilationInfo target_info(target, zone());
7628 Handle<SharedFunctionInfo> target_shared(target->shared());
7629 if (!Parser::Parse(&target_info) || !Scope::Analyze(&target_info)) {
7630 if (target_info.isolate()->has_pending_exception()) {
7631 // Parse or scope error, never optimize this function.
7633 target_shared->DisableOptimization(kParseScopeError);
7635 TraceInline(target, caller, "parse failure");
7639 if (target_info.scope()->num_heap_slots() > 0) {
7640 TraceInline(target, caller, "target has context-allocated variables");
7643 FunctionLiteral* function = target_info.function();
7645 // The following conditions must be checked again after re-parsing, because
7646 // earlier the information might not have been complete due to lazy parsing.
7647 nodes_added = function->ast_node_count();
7648 if (nodes_added > Min(FLAG_max_inlined_nodes, kUnlimitedMaxInlinedNodes)) {
7649 TraceInline(target, caller, "target AST is too large [late]");
7652 AstProperties::Flags* flags(function->flags());
7653 if (flags->Contains(kDontInline) || function->dont_optimize()) {
7654 TraceInline(target, caller, "target contains unsupported syntax [late]");
7658 // If the function uses the arguments object check that inlining of functions
7659 // with arguments object is enabled and the arguments-variable is
7661 if (function->scope()->arguments() != NULL) {
7662 if (!FLAG_inline_arguments) {
7663 TraceInline(target, caller, "target uses arguments object");
7667 if (!function->scope()->arguments()->IsStackAllocated()) {
7670 "target uses non-stackallocated arguments object");
7675 // All declarations must be inlineable.
7676 ZoneList<Declaration*>* decls = target_info.scope()->declarations();
7677 int decl_count = decls->length();
7678 for (int i = 0; i < decl_count; ++i) {
7679 if (!decls->at(i)->IsInlineable()) {
7680 TraceInline(target, caller, "target has non-trivial declaration");
7685 // Generate the deoptimization data for the unoptimized version of
7686 // the target function if we don't already have it.
7687 if (!target_shared->has_deoptimization_support()) {
7688 // Note that we compile here using the same AST that we will use for
7689 // generating the optimized inline code.
7690 target_info.EnableDeoptimizationSupport();
7691 if (!FullCodeGenerator::MakeCode(&target_info)) {
7692 TraceInline(target, caller, "could not generate deoptimization info");
7695 if (target_shared->scope_info() == ScopeInfo::Empty(isolate())) {
7696 // The scope info might not have been set if a lazily compiled
7697 // function is inlined before being called for the first time.
7698 Handle<ScopeInfo> target_scope_info =
7699 ScopeInfo::Create(target_info.scope(), zone());
7700 target_shared->set_scope_info(*target_scope_info);
7702 target_shared->EnableDeoptimizationSupport(*target_info.code());
7703 target_shared->set_feedback_vector(*target_info.feedback_vector());
7704 Compiler::RecordFunctionCompilation(Logger::FUNCTION_TAG,
7709 // ----------------------------------------------------------------
7710 // After this point, we've made a decision to inline this function (so
7711 // TryInline should always return true).
7713 // Type-check the inlined function.
7714 ASSERT(target_shared->has_deoptimization_support());
7715 AstTyper::Run(&target_info);
7717 int function_id = graph()->TraceInlinedFunction(target_shared, position);
7719 // Save the pending call context. Set up new one for the inlined function.
7720 // The function state is new-allocated because we need to delete it
7721 // in two different places.
7722 FunctionState* target_state = new FunctionState(
7723 this, &target_info, inlining_kind, function_id);
7725 HConstant* undefined = graph()->GetConstantUndefined();
7727 HEnvironment* inner_env =
7728 environment()->CopyForInlining(target,
7732 function_state()->inlining_kind());
7734 HConstant* context = Add<HConstant>(Handle<Context>(target->context()));
7735 inner_env->BindContext(context);
7737 HArgumentsObject* arguments_object = NULL;
7739 // If the function uses arguments object create and bind one, also copy
7740 // current arguments values to use them for materialization.
7741 if (function->scope()->arguments() != NULL) {
7742 ASSERT(function->scope()->arguments()->IsStackAllocated());
7743 HEnvironment* arguments_env = inner_env->arguments_environment();
7744 int arguments_count = arguments_env->parameter_count();
7745 arguments_object = Add<HArgumentsObject>(arguments_count);
7746 inner_env->Bind(function->scope()->arguments(), arguments_object);
7747 for (int i = 0; i < arguments_count; i++) {
7748 arguments_object->AddArgument(arguments_env->Lookup(i), zone());
7752 // Capture the state before invoking the inlined function for deopt in the
7753 // inlined function. This simulate has no bailout-id since it's not directly
7754 // reachable for deopt, and is only used to capture the state. If the simulate
7755 // becomes reachable by merging, the ast id of the simulate merged into it is
7757 Add<HSimulate>(BailoutId::None());
7759 current_block()->UpdateEnvironment(inner_env);
7760 Scope* saved_scope = scope();
7761 set_scope(target_info.scope());
7762 HEnterInlined* enter_inlined =
7763 Add<HEnterInlined>(return_id, target, arguments_count, function,
7764 function_state()->inlining_kind(),
7765 function->scope()->arguments(),
7767 function_state()->set_entry(enter_inlined);
7769 VisitDeclarations(target_info.scope()->declarations());
7770 VisitStatements(function->body());
7771 set_scope(saved_scope);
7772 if (HasStackOverflow()) {
7773 // Bail out if the inline function did, as we cannot residualize a call
7775 TraceInline(target, caller, "inline graph construction failed");
7776 target_shared->DisableOptimization(kInliningBailedOut);
7777 inline_bailout_ = true;
7778 delete target_state;
7782 // Update inlined nodes count.
7783 inlined_count_ += nodes_added;
7785 Handle<Code> unoptimized_code(target_shared->code());
7786 ASSERT(unoptimized_code->kind() == Code::FUNCTION);
7787 Handle<TypeFeedbackInfo> type_info(
7788 TypeFeedbackInfo::cast(unoptimized_code->type_feedback_info()));
7789 graph()->update_type_change_checksum(type_info->own_type_change_checksum());
7791 TraceInline(target, caller, NULL);
7793 if (current_block() != NULL) {
7794 FunctionState* state = function_state();
7795 if (state->inlining_kind() == CONSTRUCT_CALL_RETURN) {
7796 // Falling off the end of an inlined construct call. In a test context the
7797 // return value will always evaluate to true, in a value context the
7798 // return value is the newly allocated receiver.
7799 if (call_context()->IsTest()) {
7800 Goto(inlined_test_context()->if_true(), state);
7801 } else if (call_context()->IsEffect()) {
7802 Goto(function_return(), state);
7804 ASSERT(call_context()->IsValue());
7805 AddLeaveInlined(implicit_return_value, state);
7807 } else if (state->inlining_kind() == SETTER_CALL_RETURN) {
7808 // Falling off the end of an inlined setter call. The returned value is
7809 // never used, the value of an assignment is always the value of the RHS
7810 // of the assignment.
7811 if (call_context()->IsTest()) {
7812 inlined_test_context()->ReturnValue(implicit_return_value);
7813 } else if (call_context()->IsEffect()) {
7814 Goto(function_return(), state);
7816 ASSERT(call_context()->IsValue());
7817 AddLeaveInlined(implicit_return_value, state);
7820 // Falling off the end of a normal inlined function. This basically means
7821 // returning undefined.
7822 if (call_context()->IsTest()) {
7823 Goto(inlined_test_context()->if_false(), state);
7824 } else if (call_context()->IsEffect()) {
7825 Goto(function_return(), state);
7827 ASSERT(call_context()->IsValue());
7828 AddLeaveInlined(undefined, state);
7833 // Fix up the function exits.
7834 if (inlined_test_context() != NULL) {
7835 HBasicBlock* if_true = inlined_test_context()->if_true();
7836 HBasicBlock* if_false = inlined_test_context()->if_false();
7838 HEnterInlined* entry = function_state()->entry();
7840 // Pop the return test context from the expression context stack.
7841 ASSERT(ast_context() == inlined_test_context());
7842 ClearInlinedTestContext();
7843 delete target_state;
7845 // Forward to the real test context.
7846 if (if_true->HasPredecessor()) {
7847 entry->RegisterReturnTarget(if_true, zone());
7848 if_true->SetJoinId(ast_id);
7849 HBasicBlock* true_target = TestContext::cast(ast_context())->if_true();
7850 Goto(if_true, true_target, function_state());
7852 if (if_false->HasPredecessor()) {
7853 entry->RegisterReturnTarget(if_false, zone());
7854 if_false->SetJoinId(ast_id);
7855 HBasicBlock* false_target = TestContext::cast(ast_context())->if_false();
7856 Goto(if_false, false_target, function_state());
7858 set_current_block(NULL);
7861 } else if (function_return()->HasPredecessor()) {
7862 function_state()->entry()->RegisterReturnTarget(function_return(), zone());
7863 function_return()->SetJoinId(ast_id);
7864 set_current_block(function_return());
7866 set_current_block(NULL);
7868 delete target_state;
7873 bool HOptimizedGraphBuilder::TryInlineCall(Call* expr) {
7874 return TryInline(expr->target(),
7875 expr->arguments()->length(),
7880 ScriptPositionToSourcePosition(expr->position()));
7884 bool HOptimizedGraphBuilder::TryInlineConstruct(CallNew* expr,
7885 HValue* implicit_return_value) {
7886 return TryInline(expr->target(),
7887 expr->arguments()->length(),
7888 implicit_return_value,
7891 CONSTRUCT_CALL_RETURN,
7892 ScriptPositionToSourcePosition(expr->position()));
7896 bool HOptimizedGraphBuilder::TryInlineGetter(Handle<JSFunction> getter,
7897 Handle<Map> receiver_map,
7899 BailoutId return_id) {
7900 if (TryInlineApiGetter(getter, receiver_map, ast_id)) return true;
7901 return TryInline(getter,
7911 bool HOptimizedGraphBuilder::TryInlineSetter(Handle<JSFunction> setter,
7912 Handle<Map> receiver_map,
7914 BailoutId assignment_id,
7915 HValue* implicit_return_value) {
7916 if (TryInlineApiSetter(setter, receiver_map, id)) return true;
7917 return TryInline(setter,
7919 implicit_return_value,
7926 bool HOptimizedGraphBuilder::TryInlineApply(Handle<JSFunction> function,
7928 int arguments_count) {
7929 return TryInline(function,
7935 ScriptPositionToSourcePosition(expr->position()));
7939 bool HOptimizedGraphBuilder::TryInlineBuiltinFunctionCall(Call* expr) {
7940 if (!expr->target()->shared()->HasBuiltinFunctionId()) return false;
7941 BuiltinFunctionId id = expr->target()->shared()->builtin_function_id();
7944 if (!FLAG_fast_math) break;
7945 // Fall through if FLAG_fast_math.
7952 if (expr->arguments()->length() == 1) {
7953 HValue* argument = Pop();
7954 Drop(2); // Receiver and function.
7955 HInstruction* op = NewUncasted<HUnaryMathOperation>(argument, id);
7956 ast_context()->ReturnInstruction(op, expr->id());
7961 if (expr->arguments()->length() == 2) {
7962 HValue* right = Pop();
7963 HValue* left = Pop();
7964 Drop(2); // Receiver and function.
7965 HInstruction* op = HMul::NewImul(zone(), context(), left, right);
7966 ast_context()->ReturnInstruction(op, expr->id());
7971 // Not supported for inlining yet.
7978 bool HOptimizedGraphBuilder::TryInlineBuiltinMethodCall(
7981 Handle<Map> receiver_map) {
7982 // Try to inline calls like Math.* as operations in the calling function.
7983 if (!expr->target()->shared()->HasBuiltinFunctionId()) return false;
7984 BuiltinFunctionId id = expr->target()->shared()->builtin_function_id();
7985 int argument_count = expr->arguments()->length() + 1; // Plus receiver.
7987 case kStringCharCodeAt:
7989 if (argument_count == 2) {
7990 HValue* index = Pop();
7991 HValue* string = Pop();
7992 Drop(1); // Function.
7993 HInstruction* char_code =
7994 BuildStringCharCodeAt(string, index);
7995 if (id == kStringCharCodeAt) {
7996 ast_context()->ReturnInstruction(char_code, expr->id());
7999 AddInstruction(char_code);
8000 HInstruction* result = NewUncasted<HStringCharFromCode>(char_code);
8001 ast_context()->ReturnInstruction(result, expr->id());
8005 case kStringFromCharCode:
8006 if (argument_count == 2) {
8007 HValue* argument = Pop();
8008 Drop(2); // Receiver and function.
8009 HInstruction* result = NewUncasted<HStringCharFromCode>(argument);
8010 ast_context()->ReturnInstruction(result, expr->id());
8015 if (!FLAG_fast_math) break;
8016 // Fall through if FLAG_fast_math.
8023 if (argument_count == 2) {
8024 HValue* argument = Pop();
8025 Drop(2); // Receiver and function.
8026 HInstruction* op = NewUncasted<HUnaryMathOperation>(argument, id);
8027 ast_context()->ReturnInstruction(op, expr->id());
8032 if (argument_count == 3) {
8033 HValue* right = Pop();
8034 HValue* left = Pop();
8035 Drop(2); // Receiver and function.
8036 HInstruction* result = NULL;
8037 // Use sqrt() if exponent is 0.5 or -0.5.
8038 if (right->IsConstant() && HConstant::cast(right)->HasDoubleValue()) {
8039 double exponent = HConstant::cast(right)->DoubleValue();
8040 if (exponent == 0.5) {
8041 result = NewUncasted<HUnaryMathOperation>(left, kMathPowHalf);
8042 } else if (exponent == -0.5) {
8043 HValue* one = graph()->GetConstant1();
8044 HInstruction* sqrt = AddUncasted<HUnaryMathOperation>(
8045 left, kMathPowHalf);
8046 // MathPowHalf doesn't have side effects so there's no need for
8047 // an environment simulation here.
8048 ASSERT(!sqrt->HasObservableSideEffects());
8049 result = NewUncasted<HDiv>(one, sqrt);
8050 } else if (exponent == 2.0) {
8051 result = NewUncasted<HMul>(left, left);
8055 if (result == NULL) {
8056 result = NewUncasted<HPower>(left, right);
8058 ast_context()->ReturnInstruction(result, expr->id());
8064 if (argument_count == 3) {
8065 HValue* right = Pop();
8066 HValue* left = Pop();
8067 Drop(2); // Receiver and function.
8068 HMathMinMax::Operation op = (id == kMathMin) ? HMathMinMax::kMathMin
8069 : HMathMinMax::kMathMax;
8070 HInstruction* result = NewUncasted<HMathMinMax>(left, right, op);
8071 ast_context()->ReturnInstruction(result, expr->id());
8076 if (argument_count == 3) {
8077 HValue* right = Pop();
8078 HValue* left = Pop();
8079 Drop(2); // Receiver and function.
8080 HInstruction* result = HMul::NewImul(zone(), context(), left, right);
8081 ast_context()->ReturnInstruction(result, expr->id());
8086 if (receiver_map.is_null()) return false;
8087 if (receiver_map->instance_type() != JS_ARRAY_TYPE) return false;
8088 ElementsKind elements_kind = receiver_map->elements_kind();
8089 if (!IsFastElementsKind(elements_kind)) return false;
8090 if (receiver_map->is_observed()) return false;
8091 ASSERT(receiver_map->is_extensible());
8093 Drop(expr->arguments()->length());
8095 HValue* reduced_length;
8096 HValue* receiver = Pop();
8098 HValue* checked_object = AddCheckMap(receiver, receiver_map);
8099 HValue* length = Add<HLoadNamedField>(
8100 checked_object, static_cast<HValue*>(NULL),
8101 HObjectAccess::ForArrayLength(elements_kind));
8103 Drop(1); // Function.
8105 { NoObservableSideEffectsScope scope(this);
8106 IfBuilder length_checker(this);
8108 HValue* bounds_check = length_checker.If<HCompareNumericAndBranch>(
8109 length, graph()->GetConstant0(), Token::EQ);
8110 length_checker.Then();
8112 if (!ast_context()->IsEffect()) Push(graph()->GetConstantUndefined());
8114 length_checker.Else();
8115 HValue* elements = AddLoadElements(checked_object);
8116 // Ensure that we aren't popping from a copy-on-write array.
8117 if (IsFastSmiOrObjectElementsKind(elements_kind)) {
8118 elements = BuildCopyElementsOnWrite(checked_object, elements,
8119 elements_kind, length);
8121 reduced_length = AddUncasted<HSub>(length, graph()->GetConstant1());
8122 result = AddElementAccess(elements, reduced_length, NULL,
8123 bounds_check, elements_kind, LOAD);
8124 Factory* factory = isolate()->factory();
8125 double nan_double = FixedDoubleArray::hole_nan_as_double();
8126 HValue* hole = IsFastSmiOrObjectElementsKind(elements_kind)
8127 ? Add<HConstant>(factory->the_hole_value())
8128 : Add<HConstant>(nan_double);
8129 if (IsFastSmiOrObjectElementsKind(elements_kind)) {
8130 elements_kind = FAST_HOLEY_ELEMENTS;
8133 elements, reduced_length, hole, bounds_check, elements_kind, STORE);
8134 Add<HStoreNamedField>(
8135 checked_object, HObjectAccess::ForArrayLength(elements_kind),
8136 reduced_length, STORE_TO_INITIALIZED_ENTRY);
8138 if (!ast_context()->IsEffect()) Push(result);
8140 length_checker.End();
8142 result = ast_context()->IsEffect() ? graph()->GetConstant0() : Top();
8143 Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
8144 if (!ast_context()->IsEffect()) Drop(1);
8146 ast_context()->ReturnValue(result);
8150 if (receiver_map.is_null()) return false;
8151 if (receiver_map->instance_type() != JS_ARRAY_TYPE) return false;
8152 ElementsKind elements_kind = receiver_map->elements_kind();
8153 if (!IsFastElementsKind(elements_kind)) return false;
8154 if (receiver_map->is_observed()) return false;
8155 if (JSArray::IsReadOnlyLengthDescriptor(receiver_map)) return false;
8156 ASSERT(receiver_map->is_extensible());
8158 // If there may be elements accessors in the prototype chain, the fast
8159 // inlined version can't be used.
8160 if (receiver_map->DictionaryElementsInPrototypeChainOnly()) return false;
8161 // If there currently can be no elements accessors on the prototype chain,
8162 // it doesn't mean that there won't be any later. Install a full prototype
8163 // chain check to trap element accessors being installed on the prototype
8164 // chain, which would cause elements to go to dictionary mode and result
8166 Handle<JSObject> prototype(JSObject::cast(receiver_map->prototype()));
8167 BuildCheckPrototypeMaps(prototype, Handle<JSObject>());
8169 const int argc = expr->arguments()->length();
8170 if (argc != 1) return false;
8172 HValue* value_to_push = Pop();
8173 HValue* array = Pop();
8174 Drop(1); // Drop function.
8176 HInstruction* new_size = NULL;
8177 HValue* length = NULL;
8180 NoObservableSideEffectsScope scope(this);
8182 length = Add<HLoadNamedField>(array, static_cast<HValue*>(NULL),
8183 HObjectAccess::ForArrayLength(elements_kind));
8185 new_size = AddUncasted<HAdd>(length, graph()->GetConstant1());
8187 bool is_array = receiver_map->instance_type() == JS_ARRAY_TYPE;
8188 BuildUncheckedMonomorphicElementAccess(array, length,
8189 value_to_push, is_array,
8190 elements_kind, STORE,
8192 STORE_AND_GROW_NO_TRANSITION);
8194 if (!ast_context()->IsEffect()) Push(new_size);
8195 Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
8196 if (!ast_context()->IsEffect()) Drop(1);
8199 ast_context()->ReturnValue(new_size);
8203 if (receiver_map.is_null()) return false;
8204 if (receiver_map->instance_type() != JS_ARRAY_TYPE) return false;
8205 ElementsKind kind = receiver_map->elements_kind();
8206 if (!IsFastElementsKind(kind)) return false;
8207 if (receiver_map->is_observed()) return false;
8208 ASSERT(receiver_map->is_extensible());
8210 // If there may be elements accessors in the prototype chain, the fast
8211 // inlined version can't be used.
8212 if (receiver_map->DictionaryElementsInPrototypeChainOnly()) return false;
8214 // If there currently can be no elements accessors on the prototype chain,
8215 // it doesn't mean that there won't be any later. Install a full prototype
8216 // chain check to trap element accessors being installed on the prototype
8217 // chain, which would cause elements to go to dictionary mode and result
8219 BuildCheckPrototypeMaps(
8220 handle(JSObject::cast(receiver_map->prototype()), isolate()),
8221 Handle<JSObject>::null());
8223 // Threshold for fast inlined Array.shift().
8224 HConstant* inline_threshold = Add<HConstant>(static_cast<int32_t>(16));
8226 Drop(expr->arguments()->length());
8227 HValue* receiver = Pop();
8228 HValue* function = Pop();
8232 NoObservableSideEffectsScope scope(this);
8234 HValue* length = Add<HLoadNamedField>(
8235 receiver, static_cast<HValue*>(NULL),
8236 HObjectAccess::ForArrayLength(kind));
8238 IfBuilder if_lengthiszero(this);
8239 HValue* lengthiszero = if_lengthiszero.If<HCompareNumericAndBranch>(
8240 length, graph()->GetConstant0(), Token::EQ);
8241 if_lengthiszero.Then();
8243 if (!ast_context()->IsEffect()) Push(graph()->GetConstantUndefined());
8245 if_lengthiszero.Else();
8247 HValue* elements = AddLoadElements(receiver);
8249 // Check if we can use the fast inlined Array.shift().
8250 IfBuilder if_inline(this);
8251 if_inline.If<HCompareNumericAndBranch>(
8252 length, inline_threshold, Token::LTE);
8253 if (IsFastSmiOrObjectElementsKind(kind)) {
8254 // We cannot handle copy-on-write backing stores here.
8255 if_inline.AndIf<HCompareMap>(
8256 elements, isolate()->factory()->fixed_array_map());
8260 // Remember the result.
8261 if (!ast_context()->IsEffect()) {
8262 Push(AddElementAccess(elements, graph()->GetConstant0(), NULL,
8263 lengthiszero, kind, LOAD));
8266 // Compute the new length.
8267 HValue* new_length = AddUncasted<HSub>(
8268 length, graph()->GetConstant1());
8269 new_length->ClearFlag(HValue::kCanOverflow);
8271 // Copy the remaining elements.
8272 LoopBuilder loop(this, context(), LoopBuilder::kPostIncrement);
8274 HValue* new_key = loop.BeginBody(
8275 graph()->GetConstant0(), new_length, Token::LT);
8276 HValue* key = AddUncasted<HAdd>(new_key, graph()->GetConstant1());
8277 key->ClearFlag(HValue::kCanOverflow);
8278 HValue* element = AddUncasted<HLoadKeyed>(
8279 elements, key, lengthiszero, kind, ALLOW_RETURN_HOLE);
8280 HStoreKeyed* store = Add<HStoreKeyed>(
8281 elements, new_key, element, kind);
8282 store->SetFlag(HValue::kAllowUndefinedAsNaN);
8286 // Put a hole at the end.
8287 HValue* hole = IsFastSmiOrObjectElementsKind(kind)
8288 ? Add<HConstant>(isolate()->factory()->the_hole_value())
8289 : Add<HConstant>(FixedDoubleArray::hole_nan_as_double());
8290 if (IsFastSmiOrObjectElementsKind(kind)) kind = FAST_HOLEY_ELEMENTS;
8292 elements, new_length, hole, kind, INITIALIZING_STORE);
8294 // Remember new length.
8295 Add<HStoreNamedField>(
8296 receiver, HObjectAccess::ForArrayLength(kind),
8297 new_length, STORE_TO_INITIALIZED_ENTRY);
8301 Add<HPushArguments>(receiver);
8302 result = Add<HCallJSFunction>(function, 1, true);
8303 if (!ast_context()->IsEffect()) Push(result);
8307 if_lengthiszero.End();
8309 result = ast_context()->IsEffect() ? graph()->GetConstant0() : Top();
8310 Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
8311 if (!ast_context()->IsEffect()) Drop(1);
8312 ast_context()->ReturnValue(result);
8316 case kArrayLastIndexOf: {
8317 if (receiver_map.is_null()) return false;
8318 if (receiver_map->instance_type() != JS_ARRAY_TYPE) return false;
8319 ElementsKind kind = receiver_map->elements_kind();
8320 if (!IsFastElementsKind(kind)) return false;
8321 if (receiver_map->is_observed()) return false;
8322 if (argument_count != 2) return false;
8323 ASSERT(receiver_map->is_extensible());
8325 // If there may be elements accessors in the prototype chain, the fast
8326 // inlined version can't be used.
8327 if (receiver_map->DictionaryElementsInPrototypeChainOnly()) return false;
8329 // If there currently can be no elements accessors on the prototype chain,
8330 // it doesn't mean that there won't be any later. Install a full prototype
8331 // chain check to trap element accessors being installed on the prototype
8332 // chain, which would cause elements to go to dictionary mode and result
8334 BuildCheckPrototypeMaps(
8335 handle(JSObject::cast(receiver_map->prototype()), isolate()),
8336 Handle<JSObject>::null());
8338 HValue* search_element = Pop();
8339 HValue* receiver = Pop();
8340 Drop(1); // Drop function.
8342 ArrayIndexOfMode mode = (id == kArrayIndexOf)
8343 ? kFirstIndexOf : kLastIndexOf;
8344 HValue* index = BuildArrayIndexOf(receiver, search_element, kind, mode);
8346 if (!ast_context()->IsEffect()) Push(index);
8347 Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
8348 if (!ast_context()->IsEffect()) Drop(1);
8349 ast_context()->ReturnValue(index);
8353 // Not yet supported for inlining.
8360 bool HOptimizedGraphBuilder::TryInlineApiFunctionCall(Call* expr,
8362 Handle<JSFunction> function = expr->target();
8363 int argc = expr->arguments()->length();
8364 SmallMapList receiver_maps;
8365 return TryInlineApiCall(function,
8374 bool HOptimizedGraphBuilder::TryInlineApiMethodCall(
8377 SmallMapList* receiver_maps) {
8378 Handle<JSFunction> function = expr->target();
8379 int argc = expr->arguments()->length();
8380 return TryInlineApiCall(function,
8389 bool HOptimizedGraphBuilder::TryInlineApiGetter(Handle<JSFunction> function,
8390 Handle<Map> receiver_map,
8392 SmallMapList receiver_maps(1, zone());
8393 receiver_maps.Add(receiver_map, zone());
8394 return TryInlineApiCall(function,
8395 NULL, // Receiver is on expression stack.
8403 bool HOptimizedGraphBuilder::TryInlineApiSetter(Handle<JSFunction> function,
8404 Handle<Map> receiver_map,
8406 SmallMapList receiver_maps(1, zone());
8407 receiver_maps.Add(receiver_map, zone());
8408 return TryInlineApiCall(function,
8409 NULL, // Receiver is on expression stack.
8417 bool HOptimizedGraphBuilder::TryInlineApiCall(Handle<JSFunction> function,
8419 SmallMapList* receiver_maps,
8422 ApiCallType call_type) {
8423 CallOptimization optimization(function);
8424 if (!optimization.is_simple_api_call()) return false;
8425 Handle<Map> holder_map;
8426 if (call_type == kCallApiFunction) {
8427 // Cannot embed a direct reference to the global proxy map
8428 // as it maybe dropped on deserialization.
8429 CHECK(!isolate()->serializer_enabled());
8430 ASSERT_EQ(0, receiver_maps->length());
8431 receiver_maps->Add(handle(
8432 function->context()->global_object()->global_receiver()->map()),
8435 CallOptimization::HolderLookup holder_lookup =
8436 CallOptimization::kHolderNotFound;
8437 Handle<JSObject> api_holder = optimization.LookupHolderOfExpectedType(
8438 receiver_maps->first(), &holder_lookup);
8439 if (holder_lookup == CallOptimization::kHolderNotFound) return false;
8441 if (FLAG_trace_inlining) {
8442 PrintF("Inlining api function ");
8443 function->ShortPrint();
8447 bool drop_extra = false;
8448 bool is_store = false;
8449 switch (call_type) {
8450 case kCallApiFunction:
8451 case kCallApiMethod:
8452 // Need to check that none of the receiver maps could have changed.
8453 Add<HCheckMaps>(receiver, receiver_maps);
8454 // Need to ensure the chain between receiver and api_holder is intact.
8455 if (holder_lookup == CallOptimization::kHolderFound) {
8456 AddCheckPrototypeMaps(api_holder, receiver_maps->first());
8458 ASSERT_EQ(holder_lookup, CallOptimization::kHolderIsReceiver);
8460 // Includes receiver.
8461 PushArgumentsFromEnvironment(argc + 1);
8462 // Drop function after call.
8465 case kCallApiGetter:
8466 // Receiver and prototype chain cannot have changed.
8468 ASSERT_EQ(NULL, receiver);
8469 // Receiver is on expression stack.
8471 Add<HPushArguments>(receiver);
8473 case kCallApiSetter:
8476 // Receiver and prototype chain cannot have changed.
8478 ASSERT_EQ(NULL, receiver);
8479 // Receiver and value are on expression stack.
8480 HValue* value = Pop();
8482 Add<HPushArguments>(receiver, value);
8487 HValue* holder = NULL;
8488 switch (holder_lookup) {
8489 case CallOptimization::kHolderFound:
8490 holder = Add<HConstant>(api_holder);
8492 case CallOptimization::kHolderIsReceiver:
8495 case CallOptimization::kHolderNotFound:
8499 Handle<CallHandlerInfo> api_call_info = optimization.api_call_info();
8500 Handle<Object> call_data_obj(api_call_info->data(), isolate());
8501 bool call_data_is_undefined = call_data_obj->IsUndefined();
8502 HValue* call_data = Add<HConstant>(call_data_obj);
8503 ApiFunction fun(v8::ToCData<Address>(api_call_info->callback()));
8504 ExternalReference ref = ExternalReference(&fun,
8505 ExternalReference::DIRECT_API_CALL,
8507 HValue* api_function_address = Add<HConstant>(ExternalReference(ref));
8509 HValue* op_vals[] = {
8510 Add<HConstant>(function),
8513 api_function_address,
8517 CallInterfaceDescriptor* descriptor =
8518 isolate()->call_descriptor(Isolate::ApiFunctionCall);
8520 CallApiFunctionStub stub(isolate(), is_store, call_data_is_undefined, argc);
8521 Handle<Code> code = stub.GetCode();
8522 HConstant* code_value = Add<HConstant>(code);
8524 ASSERT((sizeof(op_vals) / kPointerSize) ==
8525 descriptor->environment_length());
8527 HInstruction* call = New<HCallWithDescriptor>(
8528 code_value, argc + 1, descriptor,
8529 Vector<HValue*>(op_vals, descriptor->environment_length()));
8531 if (drop_extra) Drop(1); // Drop function.
8532 ast_context()->ReturnInstruction(call, ast_id);
8537 bool HOptimizedGraphBuilder::TryCallApply(Call* expr) {
8538 ASSERT(expr->expression()->IsProperty());
8540 if (!expr->IsMonomorphic()) {
8543 Handle<Map> function_map = expr->GetReceiverTypes()->first();
8544 if (function_map->instance_type() != JS_FUNCTION_TYPE ||
8545 !expr->target()->shared()->HasBuiltinFunctionId() ||
8546 expr->target()->shared()->builtin_function_id() != kFunctionApply) {
8550 if (current_info()->scope()->arguments() == NULL) return false;
8552 ZoneList<Expression*>* args = expr->arguments();
8553 if (args->length() != 2) return false;
8555 VariableProxy* arg_two = args->at(1)->AsVariableProxy();
8556 if (arg_two == NULL || !arg_two->var()->IsStackAllocated()) return false;
8557 HValue* arg_two_value = LookupAndMakeLive(arg_two->var());
8558 if (!arg_two_value->CheckFlag(HValue::kIsArguments)) return false;
8560 // Found pattern f.apply(receiver, arguments).
8561 CHECK_ALIVE_OR_RETURN(VisitForValue(args->at(0)), true);
8562 HValue* receiver = Pop(); // receiver
8563 HValue* function = Pop(); // f
8566 HValue* checked_function = AddCheckMap(function, function_map);
8568 if (function_state()->outer() == NULL) {
8569 HInstruction* elements = Add<HArgumentsElements>(false);
8570 HInstruction* length = Add<HArgumentsLength>(elements);
8571 HValue* wrapped_receiver = BuildWrapReceiver(receiver, checked_function);
8572 HInstruction* result = New<HApplyArguments>(function,
8576 ast_context()->ReturnInstruction(result, expr->id());
8579 // We are inside inlined function and we know exactly what is inside
8580 // arguments object. But we need to be able to materialize at deopt.
8581 ASSERT_EQ(environment()->arguments_environment()->parameter_count(),
8582 function_state()->entry()->arguments_object()->arguments_count());
8583 HArgumentsObject* args = function_state()->entry()->arguments_object();
8584 const ZoneList<HValue*>* arguments_values = args->arguments_values();
8585 int arguments_count = arguments_values->length();
8587 Push(BuildWrapReceiver(receiver, checked_function));
8588 for (int i = 1; i < arguments_count; i++) {
8589 Push(arguments_values->at(i));
8592 Handle<JSFunction> known_function;
8593 if (function->IsConstant() &&
8594 HConstant::cast(function)->handle(isolate())->IsJSFunction()) {
8595 known_function = Handle<JSFunction>::cast(
8596 HConstant::cast(function)->handle(isolate()));
8597 int args_count = arguments_count - 1; // Excluding receiver.
8598 if (TryInlineApply(known_function, expr, args_count)) return true;
8601 PushArgumentsFromEnvironment(arguments_count);
8602 HInvokeFunction* call = New<HInvokeFunction>(
8603 function, known_function, arguments_count);
8604 Drop(1); // Function.
8605 ast_context()->ReturnInstruction(call, expr->id());
8611 HValue* HOptimizedGraphBuilder::ImplicitReceiverFor(HValue* function,
8612 Handle<JSFunction> target) {
8613 SharedFunctionInfo* shared = target->shared();
8614 if (shared->strict_mode() == SLOPPY && !shared->native()) {
8615 // Cannot embed a direct reference to the global proxy
8616 // as is it dropped on deserialization.
8617 CHECK(!isolate()->serializer_enabled());
8618 Handle<JSObject> global_receiver(
8619 target->context()->global_object()->global_receiver());
8620 return Add<HConstant>(global_receiver);
8622 return graph()->GetConstantUndefined();
8626 void HOptimizedGraphBuilder::BuildArrayCall(Expression* expression,
8627 int arguments_count,
8629 Handle<AllocationSite> site) {
8630 Add<HCheckValue>(function, array_function());
8632 if (IsCallArrayInlineable(arguments_count, site)) {
8633 BuildInlinedCallArray(expression, arguments_count, site);
8637 HInstruction* call = PreProcessCall(New<HCallNewArray>(
8638 function, arguments_count + 1, site->GetElementsKind()));
8639 if (expression->IsCall()) {
8642 ast_context()->ReturnInstruction(call, expression->id());
8646 HValue* HOptimizedGraphBuilder::BuildArrayIndexOf(HValue* receiver,
8647 HValue* search_element,
8649 ArrayIndexOfMode mode) {
8650 ASSERT(IsFastElementsKind(kind));
8652 NoObservableSideEffectsScope no_effects(this);
8654 HValue* elements = AddLoadElements(receiver);
8655 HValue* length = AddLoadArrayLength(receiver, kind);
8658 HValue* terminating;
8660 LoopBuilder::Direction direction;
8661 if (mode == kFirstIndexOf) {
8662 initial = graph()->GetConstant0();
8663 terminating = length;
8665 direction = LoopBuilder::kPostIncrement;
8667 ASSERT_EQ(kLastIndexOf, mode);
8669 terminating = graph()->GetConstant0();
8671 direction = LoopBuilder::kPreDecrement;
8674 Push(graph()->GetConstantMinus1());
8675 if (IsFastDoubleElementsKind(kind) || IsFastSmiElementsKind(kind)) {
8676 LoopBuilder loop(this, context(), direction);
8678 HValue* index = loop.BeginBody(initial, terminating, token);
8679 HValue* element = AddUncasted<HLoadKeyed>(
8680 elements, index, static_cast<HValue*>(NULL),
8681 kind, ALLOW_RETURN_HOLE);
8682 IfBuilder if_issame(this);
8683 if (IsFastDoubleElementsKind(kind)) {
8684 if_issame.If<HCompareNumericAndBranch>(
8685 element, search_element, Token::EQ_STRICT);
8687 if_issame.If<HCompareObjectEqAndBranch>(element, search_element);
8699 IfBuilder if_isstring(this);
8700 if_isstring.If<HIsStringAndBranch>(search_element);
8703 LoopBuilder loop(this, context(), direction);
8705 HValue* index = loop.BeginBody(initial, terminating, token);
8706 HValue* element = AddUncasted<HLoadKeyed>(
8707 elements, index, static_cast<HValue*>(NULL),
8708 kind, ALLOW_RETURN_HOLE);
8709 IfBuilder if_issame(this);
8710 if_issame.If<HIsStringAndBranch>(element);
8711 if_issame.AndIf<HStringCompareAndBranch>(
8712 element, search_element, Token::EQ_STRICT);
8725 IfBuilder if_isnumber(this);
8726 if_isnumber.If<HIsSmiAndBranch>(search_element);
8727 if_isnumber.OrIf<HCompareMap>(
8728 search_element, isolate()->factory()->heap_number_map());
8731 HValue* search_number =
8732 AddUncasted<HForceRepresentation>(search_element,
8733 Representation::Double());
8734 LoopBuilder loop(this, context(), direction);
8736 HValue* index = loop.BeginBody(initial, terminating, token);
8737 HValue* element = AddUncasted<HLoadKeyed>(
8738 elements, index, static_cast<HValue*>(NULL),
8739 kind, ALLOW_RETURN_HOLE);
8741 IfBuilder if_element_isnumber(this);
8742 if_element_isnumber.If<HIsSmiAndBranch>(element);
8743 if_element_isnumber.OrIf<HCompareMap>(
8744 element, isolate()->factory()->heap_number_map());
8745 if_element_isnumber.Then();
8748 AddUncasted<HForceRepresentation>(element,
8749 Representation::Double());
8750 IfBuilder if_issame(this);
8751 if_issame.If<HCompareNumericAndBranch>(
8752 number, search_number, Token::EQ_STRICT);
8761 if_element_isnumber.End();
8767 LoopBuilder loop(this, context(), direction);
8769 HValue* index = loop.BeginBody(initial, terminating, token);
8770 HValue* element = AddUncasted<HLoadKeyed>(
8771 elements, index, static_cast<HValue*>(NULL),
8772 kind, ALLOW_RETURN_HOLE);
8773 IfBuilder if_issame(this);
8774 if_issame.If<HCompareObjectEqAndBranch>(
8775 element, search_element);
8795 bool HOptimizedGraphBuilder::TryHandleArrayCall(Call* expr, HValue* function) {
8796 if (!array_function().is_identical_to(expr->target())) {
8800 Handle<AllocationSite> site = expr->allocation_site();
8801 if (site.is_null()) return false;
8803 BuildArrayCall(expr,
8804 expr->arguments()->length(),
8811 bool HOptimizedGraphBuilder::TryHandleArrayCallNew(CallNew* expr,
8813 if (!array_function().is_identical_to(expr->target())) {
8817 BuildArrayCall(expr,
8818 expr->arguments()->length(),
8820 expr->allocation_site());
8825 void HOptimizedGraphBuilder::VisitCall(Call* expr) {
8826 ASSERT(!HasStackOverflow());
8827 ASSERT(current_block() != NULL);
8828 ASSERT(current_block()->HasPredecessor());
8829 Expression* callee = expr->expression();
8830 int argument_count = expr->arguments()->length() + 1; // Plus receiver.
8831 HInstruction* call = NULL;
8833 Property* prop = callee->AsProperty();
8835 CHECK_ALIVE(VisitForValue(prop->obj()));
8836 HValue* receiver = Top();
8838 SmallMapList* types;
8839 ComputeReceiverTypes(expr, receiver, &types, zone());
8841 if (prop->key()->IsPropertyName() && types->length() > 0) {
8842 Handle<String> name = prop->key()->AsLiteral()->AsPropertyName();
8843 PropertyAccessInfo info(this, LOAD, ToType(types->first()), name);
8844 if (!info.CanAccessAsMonomorphic(types)) {
8845 HandlePolymorphicCallNamed(expr, receiver, types, name);
8851 if (!prop->key()->IsPropertyName()) {
8852 CHECK_ALIVE(VisitForValue(prop->key()));
8856 CHECK_ALIVE(PushLoad(prop, receiver, key));
8857 HValue* function = Pop();
8859 if (FLAG_hydrogen_track_positions) SetSourcePosition(expr->position());
8861 // Push the function under the receiver.
8862 environment()->SetExpressionStackAt(0, function);
8866 if (function->IsConstant() &&
8867 HConstant::cast(function)->handle(isolate())->IsJSFunction()) {
8868 Handle<JSFunction> known_function = Handle<JSFunction>::cast(
8869 HConstant::cast(function)->handle(isolate()));
8870 expr->set_target(known_function);
8872 if (TryCallApply(expr)) return;
8873 CHECK_ALIVE(VisitExpressions(expr->arguments()));
8875 Handle<Map> map = types->length() == 1 ? types->first() : Handle<Map>();
8876 if (TryInlineBuiltinMethodCall(expr, receiver, map)) {
8877 if (FLAG_trace_inlining) {
8878 PrintF("Inlining builtin ");
8879 known_function->ShortPrint();
8884 if (TryInlineApiMethodCall(expr, receiver, types)) return;
8886 // Wrap the receiver if necessary.
8887 if (NeedsWrappingFor(ToType(types->first()), known_function)) {
8888 // Since HWrapReceiver currently cannot actually wrap numbers and
8889 // strings, use the regular CallFunctionStub for method calls to wrap
8891 // TODO(verwaest): Support creation of value wrappers directly in
8893 call = New<HCallFunction>(
8894 function, argument_count, WRAP_AND_CALL);
8895 } else if (TryInlineCall(expr)) {
8898 call = BuildCallConstantFunction(known_function, argument_count);
8902 CHECK_ALIVE(VisitExpressions(expr->arguments()));
8903 CallFunctionFlags flags = receiver->type().IsJSObject()
8904 ? NO_CALL_FUNCTION_FLAGS : CALL_AS_METHOD;
8905 call = New<HCallFunction>(function, argument_count, flags);
8907 PushArgumentsFromEnvironment(argument_count);
8910 VariableProxy* proxy = expr->expression()->AsVariableProxy();
8911 if (proxy != NULL && proxy->var()->is_possibly_eval(isolate())) {
8912 return Bailout(kPossibleDirectCallToEval);
8915 // The function is on the stack in the unoptimized code during
8916 // evaluation of the arguments.
8917 CHECK_ALIVE(VisitForValue(expr->expression()));
8918 HValue* function = Top();
8919 if (expr->global_call()) {
8920 Variable* var = proxy->var();
8921 bool known_global_function = false;
8922 // If there is a global property cell for the name at compile time and
8923 // access check is not enabled we assume that the function will not change
8924 // and generate optimized code for calling the function.
8925 LookupResult lookup(isolate());
8926 GlobalPropertyAccess type = LookupGlobalProperty(var, &lookup, LOAD);
8927 if (type == kUseCell &&
8928 !current_info()->global_object()->IsAccessCheckNeeded()) {
8929 Handle<GlobalObject> global(current_info()->global_object());
8930 known_global_function = expr->ComputeGlobalTarget(global, &lookup);
8932 if (known_global_function) {
8933 Add<HCheckValue>(function, expr->target());
8935 // Placeholder for the receiver.
8936 Push(graph()->GetConstantUndefined());
8937 CHECK_ALIVE(VisitExpressions(expr->arguments()));
8939 // Patch the global object on the stack by the expected receiver.
8940 HValue* receiver = ImplicitReceiverFor(function, expr->target());
8941 const int receiver_index = argument_count - 1;
8942 environment()->SetExpressionStackAt(receiver_index, receiver);
8944 if (TryInlineBuiltinFunctionCall(expr)) {
8945 if (FLAG_trace_inlining) {
8946 PrintF("Inlining builtin ");
8947 expr->target()->ShortPrint();
8952 if (TryInlineApiFunctionCall(expr, receiver)) return;
8953 if (TryHandleArrayCall(expr, function)) return;
8954 if (TryInlineCall(expr)) return;
8956 PushArgumentsFromEnvironment(argument_count);
8957 call = BuildCallConstantFunction(expr->target(), argument_count);
8959 Push(graph()->GetConstantUndefined());
8960 CHECK_ALIVE(VisitExpressions(expr->arguments()));
8961 PushArgumentsFromEnvironment(argument_count);
8962 call = New<HCallFunction>(function, argument_count);
8965 } else if (expr->IsMonomorphic()) {
8966 Add<HCheckValue>(function, expr->target());
8968 Push(graph()->GetConstantUndefined());
8969 CHECK_ALIVE(VisitExpressions(expr->arguments()));
8971 HValue* receiver = ImplicitReceiverFor(function, expr->target());
8972 const int receiver_index = argument_count - 1;
8973 environment()->SetExpressionStackAt(receiver_index, receiver);
8975 if (TryInlineBuiltinFunctionCall(expr)) {
8976 if (FLAG_trace_inlining) {
8977 PrintF("Inlining builtin ");
8978 expr->target()->ShortPrint();
8983 if (TryInlineApiFunctionCall(expr, receiver)) return;
8985 if (TryInlineCall(expr)) return;
8987 call = PreProcessCall(New<HInvokeFunction>(
8988 function, expr->target(), argument_count));
8991 Push(graph()->GetConstantUndefined());
8992 CHECK_ALIVE(VisitExpressions(expr->arguments()));
8993 PushArgumentsFromEnvironment(argument_count);
8994 call = New<HCallFunction>(function, argument_count);
8998 Drop(1); // Drop the function.
8999 return ast_context()->ReturnInstruction(call, expr->id());
9003 void HOptimizedGraphBuilder::BuildInlinedCallArray(
9004 Expression* expression,
9006 Handle<AllocationSite> site) {
9007 ASSERT(!site.is_null());
9008 ASSERT(argument_count >= 0 && argument_count <= 1);
9009 NoObservableSideEffectsScope no_effects(this);
9011 // We should at least have the constructor on the expression stack.
9012 HValue* constructor = environment()->ExpressionStackAt(argument_count);
9014 // Register on the site for deoptimization if the transition feedback changes.
9015 AllocationSite::AddDependentCompilationInfo(
9016 site, AllocationSite::TRANSITIONS, top_info());
9017 ElementsKind kind = site->GetElementsKind();
9018 HInstruction* site_instruction = Add<HConstant>(site);
9020 // In the single constant argument case, we may have to adjust elements kind
9021 // to avoid creating a packed non-empty array.
9022 if (argument_count == 1 && !IsHoleyElementsKind(kind)) {
9023 HValue* argument = environment()->Top();
9024 if (argument->IsConstant()) {
9025 HConstant* constant_argument = HConstant::cast(argument);
9026 ASSERT(constant_argument->HasSmiValue());
9027 int constant_array_size = constant_argument->Integer32Value();
9028 if (constant_array_size != 0) {
9029 kind = GetHoleyElementsKind(kind);
9035 JSArrayBuilder array_builder(this,
9039 DISABLE_ALLOCATION_SITES);
9040 HValue* new_object = argument_count == 0
9041 ? array_builder.AllocateEmptyArray()
9042 : BuildAllocateArrayFromLength(&array_builder, Top());
9044 int args_to_drop = argument_count + (expression->IsCall() ? 2 : 1);
9046 ast_context()->ReturnValue(new_object);
9050 // Checks whether allocation using the given constructor can be inlined.
9051 static bool IsAllocationInlineable(Handle<JSFunction> constructor) {
9052 return constructor->has_initial_map() &&
9053 constructor->initial_map()->instance_type() == JS_OBJECT_TYPE &&
9054 constructor->initial_map()->instance_size() < HAllocate::kMaxInlineSize &&
9055 constructor->initial_map()->InitialPropertiesLength() == 0;
9059 bool HOptimizedGraphBuilder::IsCallArrayInlineable(
9061 Handle<AllocationSite> site) {
9062 Handle<JSFunction> caller = current_info()->closure();
9063 Handle<JSFunction> target = array_function();
9064 // We should have the function plus array arguments on the environment stack.
9065 ASSERT(environment()->length() >= (argument_count + 1));
9066 ASSERT(!site.is_null());
9068 bool inline_ok = false;
9069 if (site->CanInlineCall()) {
9070 // We also want to avoid inlining in certain 1 argument scenarios.
9071 if (argument_count == 1) {
9072 HValue* argument = Top();
9073 if (argument->IsConstant()) {
9074 // Do not inline if the constant length argument is not a smi or
9075 // outside the valid range for unrolled loop initialization.
9076 HConstant* constant_argument = HConstant::cast(argument);
9077 if (constant_argument->HasSmiValue()) {
9078 int value = constant_argument->Integer32Value();
9079 inline_ok = value >= 0 && value <= kElementLoopUnrollThreshold;
9081 TraceInline(target, caller,
9082 "Constant length outside of valid inlining range.");
9086 TraceInline(target, caller,
9087 "Dont inline [new] Array(n) where n isn't constant.");
9089 } else if (argument_count == 0) {
9092 TraceInline(target, caller, "Too many arguments to inline.");
9095 TraceInline(target, caller, "AllocationSite requested no inlining.");
9099 TraceInline(target, caller, NULL);
9105 void HOptimizedGraphBuilder::VisitCallNew(CallNew* expr) {
9106 ASSERT(!HasStackOverflow());
9107 ASSERT(current_block() != NULL);
9108 ASSERT(current_block()->HasPredecessor());
9109 if (!FLAG_hydrogen_track_positions) SetSourcePosition(expr->position());
9110 int argument_count = expr->arguments()->length() + 1; // Plus constructor.
9111 Factory* factory = isolate()->factory();
9113 // The constructor function is on the stack in the unoptimized code
9114 // during evaluation of the arguments.
9115 CHECK_ALIVE(VisitForValue(expr->expression()));
9116 HValue* function = Top();
9117 CHECK_ALIVE(VisitExpressions(expr->arguments()));
9119 if (FLAG_inline_construct &&
9120 expr->IsMonomorphic() &&
9121 IsAllocationInlineable(expr->target())) {
9122 Handle<JSFunction> constructor = expr->target();
9123 HValue* check = Add<HCheckValue>(function, constructor);
9125 // Force completion of inobject slack tracking before generating
9126 // allocation code to finalize instance size.
9127 if (constructor->IsInobjectSlackTrackingInProgress()) {
9128 constructor->CompleteInobjectSlackTracking();
9131 // Calculate instance size from initial map of constructor.
9132 ASSERT(constructor->has_initial_map());
9133 Handle<Map> initial_map(constructor->initial_map());
9134 int instance_size = initial_map->instance_size();
9135 ASSERT(initial_map->InitialPropertiesLength() == 0);
9137 // Allocate an instance of the implicit receiver object.
9138 HValue* size_in_bytes = Add<HConstant>(instance_size);
9139 HAllocationMode allocation_mode;
9140 if (FLAG_pretenuring_call_new) {
9141 if (FLAG_allocation_site_pretenuring) {
9142 // Try to use pretenuring feedback.
9143 Handle<AllocationSite> allocation_site = expr->allocation_site();
9144 allocation_mode = HAllocationMode(allocation_site);
9145 // Take a dependency on allocation site.
9146 AllocationSite::AddDependentCompilationInfo(allocation_site,
9147 AllocationSite::TENURING,
9152 HAllocate* receiver = BuildAllocate(
9153 size_in_bytes, HType::JSObject(), JS_OBJECT_TYPE, allocation_mode);
9154 receiver->set_known_initial_map(initial_map);
9156 // Initialize map and fields of the newly allocated object.
9157 { NoObservableSideEffectsScope no_effects(this);
9158 ASSERT(initial_map->instance_type() == JS_OBJECT_TYPE);
9159 Add<HStoreNamedField>(receiver,
9160 HObjectAccess::ForMapAndOffset(initial_map, JSObject::kMapOffset),
9161 Add<HConstant>(initial_map));
9162 HValue* empty_fixed_array = Add<HConstant>(factory->empty_fixed_array());
9163 Add<HStoreNamedField>(receiver,
9164 HObjectAccess::ForMapAndOffset(initial_map,
9165 JSObject::kPropertiesOffset),
9167 Add<HStoreNamedField>(receiver,
9168 HObjectAccess::ForMapAndOffset(initial_map,
9169 JSObject::kElementsOffset),
9171 if (initial_map->inobject_properties() != 0) {
9172 HConstant* undefined = graph()->GetConstantUndefined();
9173 for (int i = 0; i < initial_map->inobject_properties(); i++) {
9174 int property_offset = initial_map->GetInObjectPropertyOffset(i);
9175 Add<HStoreNamedField>(receiver,
9176 HObjectAccess::ForMapAndOffset(initial_map, property_offset),
9182 // Replace the constructor function with a newly allocated receiver using
9183 // the index of the receiver from the top of the expression stack.
9184 const int receiver_index = argument_count - 1;
9185 ASSERT(environment()->ExpressionStackAt(receiver_index) == function);
9186 environment()->SetExpressionStackAt(receiver_index, receiver);
9188 if (TryInlineConstruct(expr, receiver)) {
9189 // Inlining worked, add a dependency on the initial map to make sure that
9190 // this code is deoptimized whenever the initial map of the constructor
9192 Map::AddDependentCompilationInfo(
9193 initial_map, DependentCode::kInitialMapChangedGroup, top_info());
9197 // TODO(mstarzinger): For now we remove the previous HAllocate and all
9198 // corresponding instructions and instead add HPushArguments for the
9199 // arguments in case inlining failed. What we actually should do is for
9200 // inlining to try to build a subgraph without mutating the parent graph.
9201 HInstruction* instr = current_block()->last();
9203 HInstruction* prev_instr = instr->previous();
9204 instr->DeleteAndReplaceWith(NULL);
9206 } while (instr != check);
9207 environment()->SetExpressionStackAt(receiver_index, function);
9208 HInstruction* call =
9209 PreProcessCall(New<HCallNew>(function, argument_count));
9210 return ast_context()->ReturnInstruction(call, expr->id());
9212 // The constructor function is both an operand to the instruction and an
9213 // argument to the construct call.
9214 if (TryHandleArrayCallNew(expr, function)) return;
9216 HInstruction* call =
9217 PreProcessCall(New<HCallNew>(function, argument_count));
9218 return ast_context()->ReturnInstruction(call, expr->id());
9223 // Support for generating inlined runtime functions.
9225 // Lookup table for generators for runtime calls that are generated inline.
9226 // Elements of the table are member pointers to functions of
9227 // HOptimizedGraphBuilder.
9228 #define INLINE_FUNCTION_GENERATOR_ADDRESS(Name, argc, ressize) \
9229 &HOptimizedGraphBuilder::Generate##Name,
9231 const HOptimizedGraphBuilder::InlineFunctionGenerator
9232 HOptimizedGraphBuilder::kInlineFunctionGenerators[] = {
9233 INLINE_FUNCTION_LIST(INLINE_FUNCTION_GENERATOR_ADDRESS)
9234 INLINE_OPTIMIZED_FUNCTION_LIST(INLINE_FUNCTION_GENERATOR_ADDRESS)
9236 #undef INLINE_FUNCTION_GENERATOR_ADDRESS
9239 template <class ViewClass>
9240 void HGraphBuilder::BuildArrayBufferViewInitialization(
9243 HValue* byte_offset,
9244 HValue* byte_length) {
9246 for (int offset = ViewClass::kSize;
9247 offset < ViewClass::kSizeWithInternalFields;
9248 offset += kPointerSize) {
9249 Add<HStoreNamedField>(obj,
9250 HObjectAccess::ForObservableJSObjectOffset(offset),
9251 graph()->GetConstant0());
9254 Add<HStoreNamedField>(
9256 HObjectAccess::ForJSArrayBufferViewByteOffset(),
9258 Add<HStoreNamedField>(
9260 HObjectAccess::ForJSArrayBufferViewByteLength(),
9263 if (buffer != NULL) {
9264 Add<HStoreNamedField>(
9266 HObjectAccess::ForJSArrayBufferViewBuffer(), buffer);
9267 HObjectAccess weak_first_view_access =
9268 HObjectAccess::ForJSArrayBufferWeakFirstView();
9269 Add<HStoreNamedField>(obj,
9270 HObjectAccess::ForJSArrayBufferViewWeakNext(),
9271 Add<HLoadNamedField>(buffer,
9272 static_cast<HValue*>(NULL),
9273 weak_first_view_access));
9274 Add<HStoreNamedField>(buffer, weak_first_view_access, obj);
9276 Add<HStoreNamedField>(
9278 HObjectAccess::ForJSArrayBufferViewBuffer(),
9279 Add<HConstant>(static_cast<int32_t>(0)));
9280 Add<HStoreNamedField>(obj,
9281 HObjectAccess::ForJSArrayBufferViewWeakNext(),
9282 graph()->GetConstantUndefined());
9287 void HOptimizedGraphBuilder::GenerateDataViewInitialize(
9288 CallRuntime* expr) {
9289 ZoneList<Expression*>* arguments = expr->arguments();
9291 ASSERT(arguments->length()== 4);
9292 CHECK_ALIVE(VisitForValue(arguments->at(0)));
9293 HValue* obj = Pop();
9295 CHECK_ALIVE(VisitForValue(arguments->at(1)));
9296 HValue* buffer = Pop();
9298 CHECK_ALIVE(VisitForValue(arguments->at(2)));
9299 HValue* byte_offset = Pop();
9301 CHECK_ALIVE(VisitForValue(arguments->at(3)));
9302 HValue* byte_length = Pop();
9305 NoObservableSideEffectsScope scope(this);
9306 BuildArrayBufferViewInitialization<JSDataView>(
9307 obj, buffer, byte_offset, byte_length);
9312 static Handle<Map> TypedArrayMap(Isolate* isolate,
9313 ExternalArrayType array_type,
9314 ElementsKind target_kind) {
9315 Handle<Context> native_context = isolate->native_context();
9316 Handle<JSFunction> fun;
9317 switch (array_type) {
9318 #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
9319 case kExternal##Type##Array: \
9320 fun = Handle<JSFunction>(native_context->type##_array_fun()); \
9323 TYPED_ARRAYS(TYPED_ARRAY_CASE)
9324 #undef TYPED_ARRAY_CASE
9326 Handle<Map> map(fun->initial_map());
9327 return Map::AsElementsKind(map, target_kind);
9331 HValue* HOptimizedGraphBuilder::BuildAllocateExternalElements(
9332 ExternalArrayType array_type,
9333 bool is_zero_byte_offset,
9334 HValue* buffer, HValue* byte_offset, HValue* length) {
9335 Handle<Map> external_array_map(
9336 isolate()->heap()->MapForExternalArrayType(array_type));
9338 // The HForceRepresentation is to prevent possible deopt on int-smi
9339 // conversion after allocation but before the new object fields are set.
9340 length = AddUncasted<HForceRepresentation>(length, Representation::Smi());
9343 Add<HConstant>(ExternalArray::kAlignedSize),
9344 HType::HeapObject(),
9346 external_array_map->instance_type());
9348 AddStoreMapConstant(elements, external_array_map);
9349 Add<HStoreNamedField>(elements,
9350 HObjectAccess::ForFixedArrayLength(), length);
9352 HValue* backing_store = Add<HLoadNamedField>(
9353 buffer, static_cast<HValue*>(NULL),
9354 HObjectAccess::ForJSArrayBufferBackingStore());
9356 HValue* typed_array_start;
9357 if (is_zero_byte_offset) {
9358 typed_array_start = backing_store;
9360 HInstruction* external_pointer =
9361 AddUncasted<HAdd>(backing_store, byte_offset);
9362 // Arguments are checked prior to call to TypedArrayInitialize,
9363 // including byte_offset.
9364 external_pointer->ClearFlag(HValue::kCanOverflow);
9365 typed_array_start = external_pointer;
9368 Add<HStoreNamedField>(elements,
9369 HObjectAccess::ForExternalArrayExternalPointer(),
9376 HValue* HOptimizedGraphBuilder::BuildAllocateFixedTypedArray(
9377 ExternalArrayType array_type, size_t element_size,
9378 ElementsKind fixed_elements_kind,
9379 HValue* byte_length, HValue* length) {
9381 (FixedTypedArrayBase::kHeaderSize & kObjectAlignmentMask) == 0);
9384 // if fixed array's elements are not aligned to object's alignment,
9385 // we need to align the whole array to object alignment.
9386 if (element_size % kObjectAlignment != 0) {
9387 total_size = BuildObjectSizeAlignment(
9388 byte_length, FixedTypedArrayBase::kHeaderSize);
9390 total_size = AddUncasted<HAdd>(byte_length,
9391 Add<HConstant>(FixedTypedArrayBase::kHeaderSize));
9392 total_size->ClearFlag(HValue::kCanOverflow);
9395 // The HForceRepresentation is to prevent possible deopt on int-smi
9396 // conversion after allocation but before the new object fields are set.
9397 length = AddUncasted<HForceRepresentation>(length, Representation::Smi());
9398 Handle<Map> fixed_typed_array_map(
9399 isolate()->heap()->MapForFixedTypedArray(array_type));
9401 Add<HAllocate>(total_size, HType::HeapObject(),
9402 NOT_TENURED, fixed_typed_array_map->instance_type());
9403 AddStoreMapConstant(elements, fixed_typed_array_map);
9405 Add<HStoreNamedField>(elements,
9406 HObjectAccess::ForFixedArrayLength(),
9409 HValue* filler = Add<HConstant>(static_cast<int32_t>(0));
9412 LoopBuilder builder(this, context(), LoopBuilder::kPostIncrement);
9414 HValue* key = builder.BeginBody(
9415 Add<HConstant>(static_cast<int32_t>(0)),
9417 Add<HStoreKeyed>(elements, key, filler, fixed_elements_kind);
9425 void HOptimizedGraphBuilder::GenerateTypedArrayInitialize(
9426 CallRuntime* expr) {
9427 ZoneList<Expression*>* arguments = expr->arguments();
9429 static const int kObjectArg = 0;
9430 static const int kArrayIdArg = 1;
9431 static const int kBufferArg = 2;
9432 static const int kByteOffsetArg = 3;
9433 static const int kByteLengthArg = 4;
9434 static const int kArgsLength = 5;
9435 ASSERT(arguments->length() == kArgsLength);
9438 CHECK_ALIVE(VisitForValue(arguments->at(kObjectArg)));
9439 HValue* obj = Pop();
9441 if (arguments->at(kArrayIdArg)->IsLiteral()) {
9442 // This should never happen in real use, but can happen when fuzzing.
9444 Bailout(kNeedSmiLiteral);
9447 Handle<Object> value =
9448 static_cast<Literal*>(arguments->at(kArrayIdArg))->value();
9449 if (!value->IsSmi()) {
9450 // This should never happen in real use, but can happen when fuzzing.
9452 Bailout(kNeedSmiLiteral);
9455 int array_id = Smi::cast(*value)->value();
9458 if (!arguments->at(kBufferArg)->IsNullLiteral()) {
9459 CHECK_ALIVE(VisitForValue(arguments->at(kBufferArg)));
9465 HValue* byte_offset;
9466 bool is_zero_byte_offset;
9468 if (arguments->at(kByteOffsetArg)->IsLiteral()
9469 && Smi::FromInt(0) ==
9470 *static_cast<Literal*>(arguments->at(kByteOffsetArg))->value()) {
9471 byte_offset = Add<HConstant>(static_cast<int32_t>(0));
9472 is_zero_byte_offset = true;
9474 CHECK_ALIVE(VisitForValue(arguments->at(kByteOffsetArg)));
9475 byte_offset = Pop();
9476 is_zero_byte_offset = false;
9477 ASSERT(buffer != NULL);
9480 CHECK_ALIVE(VisitForValue(arguments->at(kByteLengthArg)));
9481 HValue* byte_length = Pop();
9483 NoObservableSideEffectsScope scope(this);
9484 IfBuilder byte_offset_smi(this);
9486 if (!is_zero_byte_offset) {
9487 byte_offset_smi.If<HIsSmiAndBranch>(byte_offset);
9488 byte_offset_smi.Then();
9491 ExternalArrayType array_type =
9492 kExternalInt8Array; // Bogus initialization.
9493 size_t element_size = 1; // Bogus initialization.
9494 ElementsKind external_elements_kind = // Bogus initialization.
9495 EXTERNAL_INT8_ELEMENTS;
9496 ElementsKind fixed_elements_kind = // Bogus initialization.
9498 Runtime::ArrayIdToTypeAndSize(array_id,
9500 &external_elements_kind,
9501 &fixed_elements_kind,
9505 { // byte_offset is Smi.
9506 BuildArrayBufferViewInitialization<JSTypedArray>(
9507 obj, buffer, byte_offset, byte_length);
9510 HInstruction* length = AddUncasted<HDiv>(byte_length,
9511 Add<HConstant>(static_cast<int32_t>(element_size)));
9513 Add<HStoreNamedField>(obj,
9514 HObjectAccess::ForJSTypedArrayLength(),
9518 if (buffer != NULL) {
9519 elements = BuildAllocateExternalElements(
9520 array_type, is_zero_byte_offset, buffer, byte_offset, length);
9521 Handle<Map> obj_map = TypedArrayMap(
9522 isolate(), array_type, external_elements_kind);
9523 AddStoreMapConstant(obj, obj_map);
9525 ASSERT(is_zero_byte_offset);
9526 elements = BuildAllocateFixedTypedArray(
9527 array_type, element_size, fixed_elements_kind,
9528 byte_length, length);
9530 Add<HStoreNamedField>(
9531 obj, HObjectAccess::ForElementsPointer(), elements);
9534 if (!is_zero_byte_offset) {
9535 byte_offset_smi.Else();
9536 { // byte_offset is not Smi.
9538 CHECK_ALIVE(VisitForValue(arguments->at(kArrayIdArg)));
9542 PushArgumentsFromEnvironment(kArgsLength);
9543 Add<HCallRuntime>(expr->name(), expr->function(), kArgsLength);
9546 byte_offset_smi.End();
9550 void HOptimizedGraphBuilder::GenerateMaxSmi(CallRuntime* expr) {
9551 ASSERT(expr->arguments()->length() == 0);
9552 HConstant* max_smi = New<HConstant>(static_cast<int32_t>(Smi::kMaxValue));
9553 return ast_context()->ReturnInstruction(max_smi, expr->id());
9557 void HOptimizedGraphBuilder::GenerateTypedArrayMaxSizeInHeap(
9558 CallRuntime* expr) {
9559 ASSERT(expr->arguments()->length() == 0);
9560 HConstant* result = New<HConstant>(static_cast<int32_t>(
9561 FLAG_typed_array_max_size_in_heap));
9562 return ast_context()->ReturnInstruction(result, expr->id());
9566 void HOptimizedGraphBuilder::GenerateArrayBufferGetByteLength(
9567 CallRuntime* expr) {
9568 ASSERT(expr->arguments()->length() == 1);
9569 CHECK_ALIVE(VisitForValue(expr->arguments()->at(0)));
9570 HValue* buffer = Pop();
9571 HInstruction* result = New<HLoadNamedField>(
9573 static_cast<HValue*>(NULL),
9574 HObjectAccess::ForJSArrayBufferByteLength());
9575 return ast_context()->ReturnInstruction(result, expr->id());
9579 void HOptimizedGraphBuilder::GenerateArrayBufferViewGetByteLength(
9580 CallRuntime* expr) {
9581 ASSERT(expr->arguments()->length() == 1);
9582 CHECK_ALIVE(VisitForValue(expr->arguments()->at(0)));
9583 HValue* buffer = Pop();
9584 HInstruction* result = New<HLoadNamedField>(
9586 static_cast<HValue*>(NULL),
9587 HObjectAccess::ForJSArrayBufferViewByteLength());
9588 return ast_context()->ReturnInstruction(result, expr->id());
9592 void HOptimizedGraphBuilder::GenerateArrayBufferViewGetByteOffset(
9593 CallRuntime* expr) {
9594 ASSERT(expr->arguments()->length() == 1);
9595 CHECK_ALIVE(VisitForValue(expr->arguments()->at(0)));
9596 HValue* buffer = Pop();
9597 HInstruction* result = New<HLoadNamedField>(
9599 static_cast<HValue*>(NULL),
9600 HObjectAccess::ForJSArrayBufferViewByteOffset());
9601 return ast_context()->ReturnInstruction(result, expr->id());
9605 void HOptimizedGraphBuilder::GenerateTypedArrayGetLength(
9606 CallRuntime* expr) {
9607 ASSERT(expr->arguments()->length() == 1);
9608 CHECK_ALIVE(VisitForValue(expr->arguments()->at(0)));
9609 HValue* buffer = Pop();
9610 HInstruction* result = New<HLoadNamedField>(
9612 static_cast<HValue*>(NULL),
9613 HObjectAccess::ForJSTypedArrayLength());
9614 return ast_context()->ReturnInstruction(result, expr->id());
9618 void HOptimizedGraphBuilder::VisitCallRuntime(CallRuntime* expr) {
9619 ASSERT(!HasStackOverflow());
9620 ASSERT(current_block() != NULL);
9621 ASSERT(current_block()->HasPredecessor());
9622 if (expr->is_jsruntime()) {
9623 return Bailout(kCallToAJavaScriptRuntimeFunction);
9626 const Runtime::Function* function = expr->function();
9627 ASSERT(function != NULL);
9629 if (function->intrinsic_type == Runtime::INLINE ||
9630 function->intrinsic_type == Runtime::INLINE_OPTIMIZED) {
9631 ASSERT(expr->name()->length() > 0);
9632 ASSERT(expr->name()->Get(0) == '_');
9633 // Call to an inline function.
9634 int lookup_index = static_cast<int>(function->function_id) -
9635 static_cast<int>(Runtime::kFirstInlineFunction);
9636 ASSERT(lookup_index >= 0);
9637 ASSERT(static_cast<size_t>(lookup_index) <
9638 ARRAY_SIZE(kInlineFunctionGenerators));
9639 InlineFunctionGenerator generator = kInlineFunctionGenerators[lookup_index];
9641 // Call the inline code generator using the pointer-to-member.
9642 (this->*generator)(expr);
9644 ASSERT(function->intrinsic_type == Runtime::RUNTIME);
9645 Handle<String> name = expr->name();
9646 int argument_count = expr->arguments()->length();
9647 CHECK_ALIVE(VisitExpressions(expr->arguments()));
9648 PushArgumentsFromEnvironment(argument_count);
9649 HCallRuntime* call = New<HCallRuntime>(name, function,
9651 return ast_context()->ReturnInstruction(call, expr->id());
9656 void HOptimizedGraphBuilder::VisitUnaryOperation(UnaryOperation* expr) {
9657 ASSERT(!HasStackOverflow());
9658 ASSERT(current_block() != NULL);
9659 ASSERT(current_block()->HasPredecessor());
9660 switch (expr->op()) {
9661 case Token::DELETE: return VisitDelete(expr);
9662 case Token::VOID: return VisitVoid(expr);
9663 case Token::TYPEOF: return VisitTypeof(expr);
9664 case Token::NOT: return VisitNot(expr);
9665 default: UNREACHABLE();
9670 void HOptimizedGraphBuilder::VisitDelete(UnaryOperation* expr) {
9671 Property* prop = expr->expression()->AsProperty();
9672 VariableProxy* proxy = expr->expression()->AsVariableProxy();
9674 CHECK_ALIVE(VisitForValue(prop->obj()));
9675 CHECK_ALIVE(VisitForValue(prop->key()));
9676 HValue* key = Pop();
9677 HValue* obj = Pop();
9678 HValue* function = AddLoadJSBuiltin(Builtins::DELETE);
9679 Add<HPushArguments>(obj, key, Add<HConstant>(function_strict_mode()));
9680 // TODO(olivf) InvokeFunction produces a check for the parameter count,
9681 // even though we are certain to pass the correct number of arguments here.
9682 HInstruction* instr = New<HInvokeFunction>(function, 3);
9683 return ast_context()->ReturnInstruction(instr, expr->id());
9684 } else if (proxy != NULL) {
9685 Variable* var = proxy->var();
9686 if (var->IsUnallocated()) {
9687 Bailout(kDeleteWithGlobalVariable);
9688 } else if (var->IsStackAllocated() || var->IsContextSlot()) {
9689 // Result of deleting non-global variables is false. 'this' is not
9690 // really a variable, though we implement it as one. The
9691 // subexpression does not have side effects.
9692 HValue* value = var->is_this()
9693 ? graph()->GetConstantTrue()
9694 : graph()->GetConstantFalse();
9695 return ast_context()->ReturnValue(value);
9697 Bailout(kDeleteWithNonGlobalVariable);
9700 // Result of deleting non-property, non-variable reference is true.
9701 // Evaluate the subexpression for side effects.
9702 CHECK_ALIVE(VisitForEffect(expr->expression()));
9703 return ast_context()->ReturnValue(graph()->GetConstantTrue());
9708 void HOptimizedGraphBuilder::VisitVoid(UnaryOperation* expr) {
9709 CHECK_ALIVE(VisitForEffect(expr->expression()));
9710 return ast_context()->ReturnValue(graph()->GetConstantUndefined());
9714 void HOptimizedGraphBuilder::VisitTypeof(UnaryOperation* expr) {
9715 CHECK_ALIVE(VisitForTypeOf(expr->expression()));
9716 HValue* value = Pop();
9717 HInstruction* instr = New<HTypeof>(value);
9718 return ast_context()->ReturnInstruction(instr, expr->id());
9722 void HOptimizedGraphBuilder::VisitNot(UnaryOperation* expr) {
9723 if (ast_context()->IsTest()) {
9724 TestContext* context = TestContext::cast(ast_context());
9725 VisitForControl(expr->expression(),
9726 context->if_false(),
9727 context->if_true());
9731 if (ast_context()->IsEffect()) {
9732 VisitForEffect(expr->expression());
9736 ASSERT(ast_context()->IsValue());
9737 HBasicBlock* materialize_false = graph()->CreateBasicBlock();
9738 HBasicBlock* materialize_true = graph()->CreateBasicBlock();
9739 CHECK_BAILOUT(VisitForControl(expr->expression(),
9743 if (materialize_false->HasPredecessor()) {
9744 materialize_false->SetJoinId(expr->MaterializeFalseId());
9745 set_current_block(materialize_false);
9746 Push(graph()->GetConstantFalse());
9748 materialize_false = NULL;
9751 if (materialize_true->HasPredecessor()) {
9752 materialize_true->SetJoinId(expr->MaterializeTrueId());
9753 set_current_block(materialize_true);
9754 Push(graph()->GetConstantTrue());
9756 materialize_true = NULL;
9760 CreateJoin(materialize_false, materialize_true, expr->id());
9761 set_current_block(join);
9762 if (join != NULL) return ast_context()->ReturnValue(Pop());
9766 HInstruction* HOptimizedGraphBuilder::BuildIncrement(
9767 bool returns_original_input,
9768 CountOperation* expr) {
9769 // The input to the count operation is on top of the expression stack.
9770 Representation rep = Representation::FromType(expr->type());
9771 if (rep.IsNone() || rep.IsTagged()) {
9772 rep = Representation::Smi();
9775 if (returns_original_input) {
9776 // We need an explicit HValue representing ToNumber(input). The
9777 // actual HChange instruction we need is (sometimes) added in a later
9778 // phase, so it is not available now to be used as an input to HAdd and
9779 // as the return value.
9780 HInstruction* number_input = AddUncasted<HForceRepresentation>(Pop(), rep);
9781 if (!rep.IsDouble()) {
9782 number_input->SetFlag(HInstruction::kFlexibleRepresentation);
9783 number_input->SetFlag(HInstruction::kCannotBeTagged);
9788 // The addition has no side effects, so we do not need
9789 // to simulate the expression stack after this instruction.
9790 // Any later failures deopt to the load of the input or earlier.
9791 HConstant* delta = (expr->op() == Token::INC)
9792 ? graph()->GetConstant1()
9793 : graph()->GetConstantMinus1();
9794 HInstruction* instr = AddUncasted<HAdd>(Top(), delta);
9795 if (instr->IsAdd()) {
9796 HAdd* add = HAdd::cast(instr);
9797 add->set_observed_input_representation(1, rep);
9798 add->set_observed_input_representation(2, Representation::Smi());
9800 instr->SetFlag(HInstruction::kCannotBeTagged);
9801 instr->ClearAllSideEffects();
9806 void HOptimizedGraphBuilder::BuildStoreForEffect(Expression* expr,
9809 BailoutId return_id,
9813 EffectContext for_effect(this);
9815 if (key != NULL) Push(key);
9817 BuildStore(expr, prop, ast_id, return_id);
9821 void HOptimizedGraphBuilder::VisitCountOperation(CountOperation* expr) {
9822 ASSERT(!HasStackOverflow());
9823 ASSERT(current_block() != NULL);
9824 ASSERT(current_block()->HasPredecessor());
9825 if (!FLAG_hydrogen_track_positions) SetSourcePosition(expr->position());
9826 Expression* target = expr->expression();
9827 VariableProxy* proxy = target->AsVariableProxy();
9828 Property* prop = target->AsProperty();
9829 if (proxy == NULL && prop == NULL) {
9830 return Bailout(kInvalidLhsInCountOperation);
9833 // Match the full code generator stack by simulating an extra stack
9834 // element for postfix operations in a non-effect context. The return
9835 // value is ToNumber(input).
9836 bool returns_original_input =
9837 expr->is_postfix() && !ast_context()->IsEffect();
9838 HValue* input = NULL; // ToNumber(original_input).
9839 HValue* after = NULL; // The result after incrementing or decrementing.
9841 if (proxy != NULL) {
9842 Variable* var = proxy->var();
9843 if (var->mode() == CONST_LEGACY) {
9844 return Bailout(kUnsupportedCountOperationWithConst);
9846 // Argument of the count operation is a variable, not a property.
9847 ASSERT(prop == NULL);
9848 CHECK_ALIVE(VisitForValue(target));
9850 after = BuildIncrement(returns_original_input, expr);
9851 input = returns_original_input ? Top() : Pop();
9854 switch (var->location()) {
9855 case Variable::UNALLOCATED:
9856 HandleGlobalVariableAssignment(var,
9858 expr->AssignmentId());
9861 case Variable::PARAMETER:
9862 case Variable::LOCAL:
9863 BindIfLive(var, after);
9866 case Variable::CONTEXT: {
9867 // Bail out if we try to mutate a parameter value in a function
9868 // using the arguments object. We do not (yet) correctly handle the
9869 // arguments property of the function.
9870 if (current_info()->scope()->arguments() != NULL) {
9871 // Parameters will rewrite to context slots. We have no direct
9872 // way to detect that the variable is a parameter so we use a
9873 // linear search of the parameter list.
9874 int count = current_info()->scope()->num_parameters();
9875 for (int i = 0; i < count; ++i) {
9876 if (var == current_info()->scope()->parameter(i)) {
9877 return Bailout(kAssignmentToParameterInArgumentsObject);
9882 HValue* context = BuildContextChainWalk(var);
9883 HStoreContextSlot::Mode mode = IsLexicalVariableMode(var->mode())
9884 ? HStoreContextSlot::kCheckDeoptimize : HStoreContextSlot::kNoCheck;
9885 HStoreContextSlot* instr = Add<HStoreContextSlot>(context, var->index(),
9887 if (instr->HasObservableSideEffects()) {
9888 Add<HSimulate>(expr->AssignmentId(), REMOVABLE_SIMULATE);
9893 case Variable::LOOKUP:
9894 return Bailout(kLookupVariableInCountOperation);
9897 Drop(returns_original_input ? 2 : 1);
9898 return ast_context()->ReturnValue(expr->is_postfix() ? input : after);
9901 // Argument of the count operation is a property.
9902 ASSERT(prop != NULL);
9903 if (returns_original_input) Push(graph()->GetConstantUndefined());
9905 CHECK_ALIVE(VisitForValue(prop->obj()));
9906 HValue* object = Top();
9909 if ((!prop->IsFunctionPrototype() && !prop->key()->IsPropertyName()) ||
9910 prop->IsStringAccess()) {
9911 CHECK_ALIVE(VisitForValue(prop->key()));
9915 CHECK_ALIVE(PushLoad(prop, object, key));
9917 after = BuildIncrement(returns_original_input, expr);
9919 if (returns_original_input) {
9921 // Drop object and key to push it again in the effect context below.
9922 Drop(key == NULL ? 1 : 2);
9923 environment()->SetExpressionStackAt(0, input);
9924 CHECK_ALIVE(BuildStoreForEffect(
9925 expr, prop, expr->id(), expr->AssignmentId(), object, key, after));
9926 return ast_context()->ReturnValue(Pop());
9929 environment()->SetExpressionStackAt(0, after);
9930 return BuildStore(expr, prop, expr->id(), expr->AssignmentId());
9934 HInstruction* HOptimizedGraphBuilder::BuildStringCharCodeAt(
9937 if (string->IsConstant() && index->IsConstant()) {
9938 HConstant* c_string = HConstant::cast(string);
9939 HConstant* c_index = HConstant::cast(index);
9940 if (c_string->HasStringValue() && c_index->HasNumberValue()) {
9941 int32_t i = c_index->NumberValueAsInteger32();
9942 Handle<String> s = c_string->StringValue();
9943 if (i < 0 || i >= s->length()) {
9944 return New<HConstant>(OS::nan_value());
9946 return New<HConstant>(s->Get(i));
9949 string = BuildCheckString(string);
9950 index = Add<HBoundsCheck>(index, AddLoadStringLength(string));
9951 return New<HStringCharCodeAt>(string, index);
9955 // Checks if the given shift amounts have following forms:
9956 // (N1) and (N2) with N1 + N2 = 32; (sa) and (32 - sa).
9957 static bool ShiftAmountsAllowReplaceByRotate(HValue* sa,
9958 HValue* const32_minus_sa) {
9959 if (sa->IsConstant() && const32_minus_sa->IsConstant()) {
9960 const HConstant* c1 = HConstant::cast(sa);
9961 const HConstant* c2 = HConstant::cast(const32_minus_sa);
9962 return c1->HasInteger32Value() && c2->HasInteger32Value() &&
9963 (c1->Integer32Value() + c2->Integer32Value() == 32);
9965 if (!const32_minus_sa->IsSub()) return false;
9966 HSub* sub = HSub::cast(const32_minus_sa);
9967 return sub->left()->EqualsInteger32Constant(32) && sub->right() == sa;
9971 // Checks if the left and the right are shift instructions with the oposite
9972 // directions that can be replaced by one rotate right instruction or not.
9973 // Returns the operand and the shift amount for the rotate instruction in the
9975 bool HGraphBuilder::MatchRotateRight(HValue* left,
9978 HValue** shift_amount) {
9981 if (left->IsShl() && right->IsShr()) {
9982 shl = HShl::cast(left);
9983 shr = HShr::cast(right);
9984 } else if (left->IsShr() && right->IsShl()) {
9985 shl = HShl::cast(right);
9986 shr = HShr::cast(left);
9990 if (shl->left() != shr->left()) return false;
9992 if (!ShiftAmountsAllowReplaceByRotate(shl->right(), shr->right()) &&
9993 !ShiftAmountsAllowReplaceByRotate(shr->right(), shl->right())) {
9996 *operand= shr->left();
9997 *shift_amount = shr->right();
10002 bool CanBeZero(HValue* right) {
10003 if (right->IsConstant()) {
10004 HConstant* right_const = HConstant::cast(right);
10005 if (right_const->HasInteger32Value() &&
10006 (right_const->Integer32Value() & 0x1f) != 0) {
10014 HValue* HGraphBuilder::EnforceNumberType(HValue* number,
10016 if (expected->Is(Type::SignedSmall())) {
10017 return AddUncasted<HForceRepresentation>(number, Representation::Smi());
10019 if (expected->Is(Type::Signed32())) {
10020 return AddUncasted<HForceRepresentation>(number,
10021 Representation::Integer32());
10027 HValue* HGraphBuilder::TruncateToNumber(HValue* value, Type** expected) {
10028 if (value->IsConstant()) {
10029 HConstant* constant = HConstant::cast(value);
10030 Maybe<HConstant*> number = constant->CopyToTruncatedNumber(zone());
10031 if (number.has_value) {
10032 *expected = Type::Number(zone());
10033 return AddInstruction(number.value);
10037 // We put temporary values on the stack, which don't correspond to anything
10038 // in baseline code. Since nothing is observable we avoid recording those
10039 // pushes with a NoObservableSideEffectsScope.
10040 NoObservableSideEffectsScope no_effects(this);
10042 Type* expected_type = *expected;
10044 // Separate the number type from the rest.
10045 Type* expected_obj =
10046 Type::Intersect(expected_type, Type::NonNumber(zone()), zone());
10047 Type* expected_number =
10048 Type::Intersect(expected_type, Type::Number(zone()), zone());
10050 // We expect to get a number.
10051 // (We need to check first, since Type::None->Is(Type::Any()) == true.
10052 if (expected_obj->Is(Type::None())) {
10053 ASSERT(!expected_number->Is(Type::None(zone())));
10057 if (expected_obj->Is(Type::Undefined(zone()))) {
10058 // This is already done by HChange.
10059 *expected = Type::Union(expected_number, Type::Number(zone()), zone());
10067 HValue* HOptimizedGraphBuilder::BuildBinaryOperation(
10068 BinaryOperation* expr,
10071 PushBeforeSimulateBehavior push_sim_result) {
10072 Type* left_type = expr->left()->bounds().lower;
10073 Type* right_type = expr->right()->bounds().lower;
10074 Type* result_type = expr->bounds().lower;
10075 Maybe<int> fixed_right_arg = expr->fixed_right_arg();
10076 Handle<AllocationSite> allocation_site = expr->allocation_site();
10078 HAllocationMode allocation_mode;
10079 if (FLAG_allocation_site_pretenuring && !allocation_site.is_null()) {
10080 allocation_mode = HAllocationMode(allocation_site);
10083 HValue* result = HGraphBuilder::BuildBinaryOperation(
10084 expr->op(), left, right, left_type, right_type, result_type,
10085 fixed_right_arg, allocation_mode);
10086 // Add a simulate after instructions with observable side effects, and
10087 // after phis, which are the result of BuildBinaryOperation when we
10088 // inlined some complex subgraph.
10089 if (result->HasObservableSideEffects() || result->IsPhi()) {
10090 if (push_sim_result == PUSH_BEFORE_SIMULATE) {
10092 Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
10095 Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
10102 HValue* HGraphBuilder::BuildBinaryOperation(
10109 Maybe<int> fixed_right_arg,
10110 HAllocationMode allocation_mode) {
10112 Representation left_rep = Representation::FromType(left_type);
10113 Representation right_rep = Representation::FromType(right_type);
10115 bool maybe_string_add = op == Token::ADD &&
10116 (left_type->Maybe(Type::String()) ||
10117 right_type->Maybe(Type::String()));
10119 if (left_type->Is(Type::None())) {
10120 Add<HDeoptimize>("Insufficient type feedback for LHS of binary operation",
10121 Deoptimizer::SOFT);
10122 // TODO(rossberg): we should be able to get rid of non-continuous
10124 left_type = Type::Any(zone());
10126 if (!maybe_string_add) left = TruncateToNumber(left, &left_type);
10127 left_rep = Representation::FromType(left_type);
10130 if (right_type->Is(Type::None())) {
10131 Add<HDeoptimize>("Insufficient type feedback for RHS of binary operation",
10132 Deoptimizer::SOFT);
10133 right_type = Type::Any(zone());
10135 if (!maybe_string_add) right = TruncateToNumber(right, &right_type);
10136 right_rep = Representation::FromType(right_type);
10139 // Special case for string addition here.
10140 if (op == Token::ADD &&
10141 (left_type->Is(Type::String()) || right_type->Is(Type::String()))) {
10142 // Validate type feedback for left argument.
10143 if (left_type->Is(Type::String())) {
10144 left = BuildCheckString(left);
10147 // Validate type feedback for right argument.
10148 if (right_type->Is(Type::String())) {
10149 right = BuildCheckString(right);
10152 // Convert left argument as necessary.
10153 if (left_type->Is(Type::Number())) {
10154 ASSERT(right_type->Is(Type::String()));
10155 left = BuildNumberToString(left, left_type);
10156 } else if (!left_type->Is(Type::String())) {
10157 ASSERT(right_type->Is(Type::String()));
10158 HValue* function = AddLoadJSBuiltin(Builtins::STRING_ADD_RIGHT);
10159 Add<HPushArguments>(left, right);
10160 return AddUncasted<HInvokeFunction>(function, 2);
10163 // Convert right argument as necessary.
10164 if (right_type->Is(Type::Number())) {
10165 ASSERT(left_type->Is(Type::String()));
10166 right = BuildNumberToString(right, right_type);
10167 } else if (!right_type->Is(Type::String())) {
10168 ASSERT(left_type->Is(Type::String()));
10169 HValue* function = AddLoadJSBuiltin(Builtins::STRING_ADD_LEFT);
10170 Add<HPushArguments>(left, right);
10171 return AddUncasted<HInvokeFunction>(function, 2);
10174 // Fast path for empty constant strings.
10175 if (left->IsConstant() &&
10176 HConstant::cast(left)->HasStringValue() &&
10177 HConstant::cast(left)->StringValue()->length() == 0) {
10180 if (right->IsConstant() &&
10181 HConstant::cast(right)->HasStringValue() &&
10182 HConstant::cast(right)->StringValue()->length() == 0) {
10186 // Register the dependent code with the allocation site.
10187 if (!allocation_mode.feedback_site().is_null()) {
10188 ASSERT(!graph()->info()->IsStub());
10189 Handle<AllocationSite> site(allocation_mode.feedback_site());
10190 AllocationSite::AddDependentCompilationInfo(
10191 site, AllocationSite::TENURING, top_info());
10194 // Inline the string addition into the stub when creating allocation
10195 // mementos to gather allocation site feedback, or if we can statically
10196 // infer that we're going to create a cons string.
10197 if ((graph()->info()->IsStub() &&
10198 allocation_mode.CreateAllocationMementos()) ||
10199 (left->IsConstant() &&
10200 HConstant::cast(left)->HasStringValue() &&
10201 HConstant::cast(left)->StringValue()->length() + 1 >=
10202 ConsString::kMinLength) ||
10203 (right->IsConstant() &&
10204 HConstant::cast(right)->HasStringValue() &&
10205 HConstant::cast(right)->StringValue()->length() + 1 >=
10206 ConsString::kMinLength)) {
10207 return BuildStringAdd(left, right, allocation_mode);
10210 // Fallback to using the string add stub.
10211 return AddUncasted<HStringAdd>(
10212 left, right, allocation_mode.GetPretenureMode(),
10213 STRING_ADD_CHECK_NONE, allocation_mode.feedback_site());
10216 if (graph()->info()->IsStub()) {
10217 left = EnforceNumberType(left, left_type);
10218 right = EnforceNumberType(right, right_type);
10221 Representation result_rep = Representation::FromType(result_type);
10223 bool is_non_primitive = (left_rep.IsTagged() && !left_rep.IsSmi()) ||
10224 (right_rep.IsTagged() && !right_rep.IsSmi());
10226 HInstruction* instr = NULL;
10227 // Only the stub is allowed to call into the runtime, since otherwise we would
10228 // inline several instructions (including the two pushes) for every tagged
10229 // operation in optimized code, which is more expensive, than a stub call.
10230 if (graph()->info()->IsStub() && is_non_primitive) {
10231 HValue* function = AddLoadJSBuiltin(BinaryOpIC::TokenToJSBuiltin(op));
10232 Add<HPushArguments>(left, right);
10233 instr = AddUncasted<HInvokeFunction>(function, 2);
10237 instr = AddUncasted<HAdd>(left, right);
10240 instr = AddUncasted<HSub>(left, right);
10243 instr = AddUncasted<HMul>(left, right);
10246 if (fixed_right_arg.has_value &&
10247 !right->EqualsInteger32Constant(fixed_right_arg.value)) {
10248 HConstant* fixed_right = Add<HConstant>(
10249 static_cast<int>(fixed_right_arg.value));
10250 IfBuilder if_same(this);
10251 if_same.If<HCompareNumericAndBranch>(right, fixed_right, Token::EQ);
10253 if_same.ElseDeopt("Unexpected RHS of binary operation");
10254 right = fixed_right;
10256 instr = AddUncasted<HMod>(left, right);
10260 instr = AddUncasted<HDiv>(left, right);
10262 case Token::BIT_XOR:
10263 case Token::BIT_AND:
10264 instr = AddUncasted<HBitwise>(op, left, right);
10266 case Token::BIT_OR: {
10267 HValue* operand, *shift_amount;
10268 if (left_type->Is(Type::Signed32()) &&
10269 right_type->Is(Type::Signed32()) &&
10270 MatchRotateRight(left, right, &operand, &shift_amount)) {
10271 instr = AddUncasted<HRor>(operand, shift_amount);
10273 instr = AddUncasted<HBitwise>(op, left, right);
10278 instr = AddUncasted<HSar>(left, right);
10281 instr = AddUncasted<HShr>(left, right);
10282 if (FLAG_opt_safe_uint32_operations && instr->IsShr() &&
10283 CanBeZero(right)) {
10284 graph()->RecordUint32Instruction(instr);
10288 instr = AddUncasted<HShl>(left, right);
10295 if (instr->IsBinaryOperation()) {
10296 HBinaryOperation* binop = HBinaryOperation::cast(instr);
10297 binop->set_observed_input_representation(1, left_rep);
10298 binop->set_observed_input_representation(2, right_rep);
10299 binop->initialize_output_representation(result_rep);
10300 if (graph()->info()->IsStub()) {
10301 // Stub should not call into stub.
10302 instr->SetFlag(HValue::kCannotBeTagged);
10303 // And should truncate on HForceRepresentation already.
10304 if (left->IsForceRepresentation()) {
10305 left->CopyFlag(HValue::kTruncatingToSmi, instr);
10306 left->CopyFlag(HValue::kTruncatingToInt32, instr);
10308 if (right->IsForceRepresentation()) {
10309 right->CopyFlag(HValue::kTruncatingToSmi, instr);
10310 right->CopyFlag(HValue::kTruncatingToInt32, instr);
10318 // Check for the form (%_ClassOf(foo) === 'BarClass').
10319 static bool IsClassOfTest(CompareOperation* expr) {
10320 if (expr->op() != Token::EQ_STRICT) return false;
10321 CallRuntime* call = expr->left()->AsCallRuntime();
10322 if (call == NULL) return false;
10323 Literal* literal = expr->right()->AsLiteral();
10324 if (literal == NULL) return false;
10325 if (!literal->value()->IsString()) return false;
10326 if (!call->name()->IsOneByteEqualTo(STATIC_ASCII_VECTOR("_ClassOf"))) {
10329 ASSERT(call->arguments()->length() == 1);
10334 void HOptimizedGraphBuilder::VisitBinaryOperation(BinaryOperation* expr) {
10335 ASSERT(!HasStackOverflow());
10336 ASSERT(current_block() != NULL);
10337 ASSERT(current_block()->HasPredecessor());
10338 switch (expr->op()) {
10340 return VisitComma(expr);
10343 return VisitLogicalExpression(expr);
10345 return VisitArithmeticExpression(expr);
10350 void HOptimizedGraphBuilder::VisitComma(BinaryOperation* expr) {
10351 CHECK_ALIVE(VisitForEffect(expr->left()));
10352 // Visit the right subexpression in the same AST context as the entire
10354 Visit(expr->right());
10358 void HOptimizedGraphBuilder::VisitLogicalExpression(BinaryOperation* expr) {
10359 bool is_logical_and = expr->op() == Token::AND;
10360 if (ast_context()->IsTest()) {
10361 TestContext* context = TestContext::cast(ast_context());
10362 // Translate left subexpression.
10363 HBasicBlock* eval_right = graph()->CreateBasicBlock();
10364 if (is_logical_and) {
10365 CHECK_BAILOUT(VisitForControl(expr->left(),
10367 context->if_false()));
10369 CHECK_BAILOUT(VisitForControl(expr->left(),
10370 context->if_true(),
10374 // Translate right subexpression by visiting it in the same AST
10375 // context as the entire expression.
10376 if (eval_right->HasPredecessor()) {
10377 eval_right->SetJoinId(expr->RightId());
10378 set_current_block(eval_right);
10379 Visit(expr->right());
10382 } else if (ast_context()->IsValue()) {
10383 CHECK_ALIVE(VisitForValue(expr->left()));
10384 ASSERT(current_block() != NULL);
10385 HValue* left_value = Top();
10387 // Short-circuit left values that always evaluate to the same boolean value.
10388 if (expr->left()->ToBooleanIsTrue() || expr->left()->ToBooleanIsFalse()) {
10389 // l (evals true) && r -> r
10390 // l (evals true) || r -> l
10391 // l (evals false) && r -> l
10392 // l (evals false) || r -> r
10393 if (is_logical_and == expr->left()->ToBooleanIsTrue()) {
10395 CHECK_ALIVE(VisitForValue(expr->right()));
10397 return ast_context()->ReturnValue(Pop());
10400 // We need an extra block to maintain edge-split form.
10401 HBasicBlock* empty_block = graph()->CreateBasicBlock();
10402 HBasicBlock* eval_right = graph()->CreateBasicBlock();
10403 ToBooleanStub::Types expected(expr->left()->to_boolean_types());
10404 HBranch* test = is_logical_and
10405 ? New<HBranch>(left_value, expected, eval_right, empty_block)
10406 : New<HBranch>(left_value, expected, empty_block, eval_right);
10407 FinishCurrentBlock(test);
10409 set_current_block(eval_right);
10410 Drop(1); // Value of the left subexpression.
10411 CHECK_BAILOUT(VisitForValue(expr->right()));
10413 HBasicBlock* join_block =
10414 CreateJoin(empty_block, current_block(), expr->id());
10415 set_current_block(join_block);
10416 return ast_context()->ReturnValue(Pop());
10419 ASSERT(ast_context()->IsEffect());
10420 // In an effect context, we don't need the value of the left subexpression,
10421 // only its control flow and side effects. We need an extra block to
10422 // maintain edge-split form.
10423 HBasicBlock* empty_block = graph()->CreateBasicBlock();
10424 HBasicBlock* right_block = graph()->CreateBasicBlock();
10425 if (is_logical_and) {
10426 CHECK_BAILOUT(VisitForControl(expr->left(), right_block, empty_block));
10428 CHECK_BAILOUT(VisitForControl(expr->left(), empty_block, right_block));
10431 // TODO(kmillikin): Find a way to fix this. It's ugly that there are
10432 // actually two empty blocks (one here and one inserted by
10433 // TestContext::BuildBranch, and that they both have an HSimulate though the
10434 // second one is not a merge node, and that we really have no good AST ID to
10435 // put on that first HSimulate.
10437 if (empty_block->HasPredecessor()) {
10438 empty_block->SetJoinId(expr->id());
10440 empty_block = NULL;
10443 if (right_block->HasPredecessor()) {
10444 right_block->SetJoinId(expr->RightId());
10445 set_current_block(right_block);
10446 CHECK_BAILOUT(VisitForEffect(expr->right()));
10447 right_block = current_block();
10449 right_block = NULL;
10452 HBasicBlock* join_block =
10453 CreateJoin(empty_block, right_block, expr->id());
10454 set_current_block(join_block);
10455 // We did not materialize any value in the predecessor environments,
10456 // so there is no need to handle it here.
10461 void HOptimizedGraphBuilder::VisitArithmeticExpression(BinaryOperation* expr) {
10462 CHECK_ALIVE(VisitForValue(expr->left()));
10463 CHECK_ALIVE(VisitForValue(expr->right()));
10464 SetSourcePosition(expr->position());
10465 HValue* right = Pop();
10466 HValue* left = Pop();
10468 BuildBinaryOperation(expr, left, right,
10469 ast_context()->IsEffect() ? NO_PUSH_BEFORE_SIMULATE
10470 : PUSH_BEFORE_SIMULATE);
10471 if (FLAG_hydrogen_track_positions && result->IsBinaryOperation()) {
10472 HBinaryOperation::cast(result)->SetOperandPositions(
10474 ScriptPositionToSourcePosition(expr->left()->position()),
10475 ScriptPositionToSourcePosition(expr->right()->position()));
10477 return ast_context()->ReturnValue(result);
10481 void HOptimizedGraphBuilder::HandleLiteralCompareTypeof(CompareOperation* expr,
10482 Expression* sub_expr,
10483 Handle<String> check) {
10484 CHECK_ALIVE(VisitForTypeOf(sub_expr));
10485 SetSourcePosition(expr->position());
10486 HValue* value = Pop();
10487 HTypeofIsAndBranch* instr = New<HTypeofIsAndBranch>(value, check);
10488 return ast_context()->ReturnControl(instr, expr->id());
10492 static bool IsLiteralCompareBool(Isolate* isolate,
10496 return op == Token::EQ_STRICT &&
10497 ((left->IsConstant() &&
10498 HConstant::cast(left)->handle(isolate)->IsBoolean()) ||
10499 (right->IsConstant() &&
10500 HConstant::cast(right)->handle(isolate)->IsBoolean()));
10504 void HOptimizedGraphBuilder::VisitCompareOperation(CompareOperation* expr) {
10505 ASSERT(!HasStackOverflow());
10506 ASSERT(current_block() != NULL);
10507 ASSERT(current_block()->HasPredecessor());
10509 if (!FLAG_hydrogen_track_positions) SetSourcePosition(expr->position());
10511 // Check for a few fast cases. The AST visiting behavior must be in sync
10512 // with the full codegen: We don't push both left and right values onto
10513 // the expression stack when one side is a special-case literal.
10514 Expression* sub_expr = NULL;
10515 Handle<String> check;
10516 if (expr->IsLiteralCompareTypeof(&sub_expr, &check)) {
10517 return HandleLiteralCompareTypeof(expr, sub_expr, check);
10519 if (expr->IsLiteralCompareUndefined(&sub_expr, isolate())) {
10520 return HandleLiteralCompareNil(expr, sub_expr, kUndefinedValue);
10522 if (expr->IsLiteralCompareNull(&sub_expr)) {
10523 return HandleLiteralCompareNil(expr, sub_expr, kNullValue);
10526 if (IsClassOfTest(expr)) {
10527 CallRuntime* call = expr->left()->AsCallRuntime();
10528 ASSERT(call->arguments()->length() == 1);
10529 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
10530 HValue* value = Pop();
10531 Literal* literal = expr->right()->AsLiteral();
10532 Handle<String> rhs = Handle<String>::cast(literal->value());
10533 HClassOfTestAndBranch* instr = New<HClassOfTestAndBranch>(value, rhs);
10534 return ast_context()->ReturnControl(instr, expr->id());
10537 Type* left_type = expr->left()->bounds().lower;
10538 Type* right_type = expr->right()->bounds().lower;
10539 Type* combined_type = expr->combined_type();
10541 CHECK_ALIVE(VisitForValue(expr->left()));
10542 CHECK_ALIVE(VisitForValue(expr->right()));
10544 if (FLAG_hydrogen_track_positions) SetSourcePosition(expr->position());
10546 HValue* right = Pop();
10547 HValue* left = Pop();
10548 Token::Value op = expr->op();
10550 if (IsLiteralCompareBool(isolate(), left, op, right)) {
10551 HCompareObjectEqAndBranch* result =
10552 New<HCompareObjectEqAndBranch>(left, right);
10553 return ast_context()->ReturnControl(result, expr->id());
10556 if (op == Token::INSTANCEOF) {
10557 // Check to see if the rhs of the instanceof is a global function not
10558 // residing in new space. If it is we assume that the function will stay the
10560 Handle<JSFunction> target = Handle<JSFunction>::null();
10561 VariableProxy* proxy = expr->right()->AsVariableProxy();
10562 bool global_function = (proxy != NULL) && proxy->var()->IsUnallocated();
10563 if (global_function &&
10564 current_info()->has_global_object() &&
10565 !current_info()->global_object()->IsAccessCheckNeeded()) {
10566 Handle<String> name = proxy->name();
10567 Handle<GlobalObject> global(current_info()->global_object());
10568 LookupResult lookup(isolate());
10569 global->Lookup(name, &lookup);
10570 if (lookup.IsNormal() && lookup.GetValue()->IsJSFunction()) {
10571 Handle<JSFunction> candidate(JSFunction::cast(lookup.GetValue()));
10572 // If the function is in new space we assume it's more likely to
10573 // change and thus prefer the general IC code.
10574 if (!isolate()->heap()->InNewSpace(*candidate)) {
10575 target = candidate;
10580 // If the target is not null we have found a known global function that is
10581 // assumed to stay the same for this instanceof.
10582 if (target.is_null()) {
10583 HInstanceOf* result = New<HInstanceOf>(left, right);
10584 return ast_context()->ReturnInstruction(result, expr->id());
10586 Add<HCheckValue>(right, target);
10587 HInstanceOfKnownGlobal* result =
10588 New<HInstanceOfKnownGlobal>(left, target);
10589 return ast_context()->ReturnInstruction(result, expr->id());
10592 // Code below assumes that we don't fall through.
10594 } else if (op == Token::IN) {
10595 HValue* function = AddLoadJSBuiltin(Builtins::IN);
10596 Add<HPushArguments>(left, right);
10597 // TODO(olivf) InvokeFunction produces a check for the parameter count,
10598 // even though we are certain to pass the correct number of arguments here.
10599 HInstruction* result = New<HInvokeFunction>(function, 2);
10600 return ast_context()->ReturnInstruction(result, expr->id());
10603 PushBeforeSimulateBehavior push_behavior =
10604 ast_context()->IsEffect() ? NO_PUSH_BEFORE_SIMULATE
10605 : PUSH_BEFORE_SIMULATE;
10606 HControlInstruction* compare = BuildCompareInstruction(
10607 op, left, right, left_type, right_type, combined_type,
10608 ScriptPositionToSourcePosition(expr->left()->position()),
10609 ScriptPositionToSourcePosition(expr->right()->position()),
10610 push_behavior, expr->id());
10611 if (compare == NULL) return; // Bailed out.
10612 return ast_context()->ReturnControl(compare, expr->id());
10616 HControlInstruction* HOptimizedGraphBuilder::BuildCompareInstruction(
10622 Type* combined_type,
10623 HSourcePosition left_position,
10624 HSourcePosition right_position,
10625 PushBeforeSimulateBehavior push_sim_result,
10626 BailoutId bailout_id) {
10627 // Cases handled below depend on collected type feedback. They should
10628 // soft deoptimize when there is no type feedback.
10629 if (combined_type->Is(Type::None())) {
10630 Add<HDeoptimize>("Insufficient type feedback for combined type "
10631 "of binary operation",
10632 Deoptimizer::SOFT);
10633 combined_type = left_type = right_type = Type::Any(zone());
10636 Representation left_rep = Representation::FromType(left_type);
10637 Representation right_rep = Representation::FromType(right_type);
10638 Representation combined_rep = Representation::FromType(combined_type);
10640 if (combined_type->Is(Type::Receiver())) {
10641 if (Token::IsEqualityOp(op)) {
10642 // HCompareObjectEqAndBranch can only deal with object, so
10643 // exclude numbers.
10644 if ((left->IsConstant() &&
10645 HConstant::cast(left)->HasNumberValue()) ||
10646 (right->IsConstant() &&
10647 HConstant::cast(right)->HasNumberValue())) {
10648 Add<HDeoptimize>("Type mismatch between feedback and constant",
10649 Deoptimizer::SOFT);
10650 // The caller expects a branch instruction, so make it happy.
10651 return New<HBranch>(graph()->GetConstantTrue());
10653 // Can we get away with map check and not instance type check?
10654 HValue* operand_to_check =
10655 left->block()->block_id() < right->block()->block_id() ? left : right;
10656 if (combined_type->IsClass()) {
10657 Handle<Map> map = combined_type->AsClass()->Map();
10658 AddCheckMap(operand_to_check, map);
10659 HCompareObjectEqAndBranch* result =
10660 New<HCompareObjectEqAndBranch>(left, right);
10661 if (FLAG_hydrogen_track_positions) {
10662 result->set_operand_position(zone(), 0, left_position);
10663 result->set_operand_position(zone(), 1, right_position);
10667 BuildCheckHeapObject(operand_to_check);
10668 Add<HCheckInstanceType>(operand_to_check,
10669 HCheckInstanceType::IS_SPEC_OBJECT);
10670 HCompareObjectEqAndBranch* result =
10671 New<HCompareObjectEqAndBranch>(left, right);
10675 Bailout(kUnsupportedNonPrimitiveCompare);
10678 } else if (combined_type->Is(Type::InternalizedString()) &&
10679 Token::IsEqualityOp(op)) {
10680 // If we have a constant argument, it should be consistent with the type
10681 // feedback (otherwise we fail assertions in HCompareObjectEqAndBranch).
10682 if ((left->IsConstant() &&
10683 !HConstant::cast(left)->HasInternalizedStringValue()) ||
10684 (right->IsConstant() &&
10685 !HConstant::cast(right)->HasInternalizedStringValue())) {
10686 Add<HDeoptimize>("Type mismatch between feedback and constant",
10687 Deoptimizer::SOFT);
10688 // The caller expects a branch instruction, so make it happy.
10689 return New<HBranch>(graph()->GetConstantTrue());
10691 BuildCheckHeapObject(left);
10692 Add<HCheckInstanceType>(left, HCheckInstanceType::IS_INTERNALIZED_STRING);
10693 BuildCheckHeapObject(right);
10694 Add<HCheckInstanceType>(right, HCheckInstanceType::IS_INTERNALIZED_STRING);
10695 HCompareObjectEqAndBranch* result =
10696 New<HCompareObjectEqAndBranch>(left, right);
10698 } else if (combined_type->Is(Type::String())) {
10699 BuildCheckHeapObject(left);
10700 Add<HCheckInstanceType>(left, HCheckInstanceType::IS_STRING);
10701 BuildCheckHeapObject(right);
10702 Add<HCheckInstanceType>(right, HCheckInstanceType::IS_STRING);
10703 HStringCompareAndBranch* result =
10704 New<HStringCompareAndBranch>(left, right, op);
10707 if (combined_rep.IsTagged() || combined_rep.IsNone()) {
10708 HCompareGeneric* result = Add<HCompareGeneric>(left, right, op);
10709 result->set_observed_input_representation(1, left_rep);
10710 result->set_observed_input_representation(2, right_rep);
10711 if (result->HasObservableSideEffects()) {
10712 if (push_sim_result == PUSH_BEFORE_SIMULATE) {
10714 AddSimulate(bailout_id, REMOVABLE_SIMULATE);
10717 AddSimulate(bailout_id, REMOVABLE_SIMULATE);
10720 // TODO(jkummerow): Can we make this more efficient?
10721 HBranch* branch = New<HBranch>(result);
10724 HCompareNumericAndBranch* result =
10725 New<HCompareNumericAndBranch>(left, right, op);
10726 result->set_observed_input_representation(left_rep, right_rep);
10727 if (FLAG_hydrogen_track_positions) {
10728 result->SetOperandPositions(zone(), left_position, right_position);
10736 void HOptimizedGraphBuilder::HandleLiteralCompareNil(CompareOperation* expr,
10737 Expression* sub_expr,
10739 ASSERT(!HasStackOverflow());
10740 ASSERT(current_block() != NULL);
10741 ASSERT(current_block()->HasPredecessor());
10742 ASSERT(expr->op() == Token::EQ || expr->op() == Token::EQ_STRICT);
10743 if (!FLAG_hydrogen_track_positions) SetSourcePosition(expr->position());
10744 CHECK_ALIVE(VisitForValue(sub_expr));
10745 HValue* value = Pop();
10746 if (expr->op() == Token::EQ_STRICT) {
10747 HConstant* nil_constant = nil == kNullValue
10748 ? graph()->GetConstantNull()
10749 : graph()->GetConstantUndefined();
10750 HCompareObjectEqAndBranch* instr =
10751 New<HCompareObjectEqAndBranch>(value, nil_constant);
10752 return ast_context()->ReturnControl(instr, expr->id());
10754 ASSERT_EQ(Token::EQ, expr->op());
10755 Type* type = expr->combined_type()->Is(Type::None())
10756 ? Type::Any(zone()) : expr->combined_type();
10757 HIfContinuation continuation;
10758 BuildCompareNil(value, type, &continuation);
10759 return ast_context()->ReturnContinuation(&continuation, expr->id());
10764 HInstruction* HOptimizedGraphBuilder::BuildThisFunction() {
10765 // If we share optimized code between different closures, the
10766 // this-function is not a constant, except inside an inlined body.
10767 if (function_state()->outer() != NULL) {
10768 return New<HConstant>(
10769 function_state()->compilation_info()->closure());
10771 return New<HThisFunction>();
10776 HInstruction* HOptimizedGraphBuilder::BuildFastLiteral(
10777 Handle<JSObject> boilerplate_object,
10778 AllocationSiteUsageContext* site_context) {
10779 NoObservableSideEffectsScope no_effects(this);
10780 InstanceType instance_type = boilerplate_object->map()->instance_type();
10781 ASSERT(instance_type == JS_ARRAY_TYPE || instance_type == JS_OBJECT_TYPE);
10783 HType type = instance_type == JS_ARRAY_TYPE
10784 ? HType::JSArray() : HType::JSObject();
10785 HValue* object_size_constant = Add<HConstant>(
10786 boilerplate_object->map()->instance_size());
10788 PretenureFlag pretenure_flag = NOT_TENURED;
10789 if (FLAG_allocation_site_pretenuring) {
10790 pretenure_flag = site_context->current()->GetPretenureMode();
10791 Handle<AllocationSite> site(site_context->current());
10792 AllocationSite::AddDependentCompilationInfo(
10793 site, AllocationSite::TENURING, top_info());
10796 HInstruction* object = Add<HAllocate>(object_size_constant, type,
10797 pretenure_flag, instance_type, site_context->current());
10799 // If allocation folding reaches Page::kMaxRegularHeapObjectSize the
10800 // elements array may not get folded into the object. Hence, we set the
10801 // elements pointer to empty fixed array and let store elimination remove
10802 // this store in the folding case.
10803 HConstant* empty_fixed_array = Add<HConstant>(
10804 isolate()->factory()->empty_fixed_array());
10805 Add<HStoreNamedField>(object, HObjectAccess::ForElementsPointer(),
10806 empty_fixed_array);
10808 BuildEmitObjectHeader(boilerplate_object, object);
10810 Handle<FixedArrayBase> elements(boilerplate_object->elements());
10811 int elements_size = (elements->length() > 0 &&
10812 elements->map() != isolate()->heap()->fixed_cow_array_map()) ?
10813 elements->Size() : 0;
10815 if (pretenure_flag == TENURED &&
10816 elements->map() == isolate()->heap()->fixed_cow_array_map() &&
10817 isolate()->heap()->InNewSpace(*elements)) {
10818 // If we would like to pretenure a fixed cow array, we must ensure that the
10819 // array is already in old space, otherwise we'll create too many old-to-
10820 // new-space pointers (overflowing the store buffer).
10821 elements = Handle<FixedArrayBase>(
10822 isolate()->factory()->CopyAndTenureFixedCOWArray(
10823 Handle<FixedArray>::cast(elements)));
10824 boilerplate_object->set_elements(*elements);
10827 HInstruction* object_elements = NULL;
10828 if (elements_size > 0) {
10829 HValue* object_elements_size = Add<HConstant>(elements_size);
10830 InstanceType instance_type = boilerplate_object->HasFastDoubleElements()
10831 ? FIXED_DOUBLE_ARRAY_TYPE : FIXED_ARRAY_TYPE;
10832 object_elements = Add<HAllocate>(
10833 object_elements_size, HType::HeapObject(),
10834 pretenure_flag, instance_type, site_context->current());
10836 BuildInitElementsInObjectHeader(boilerplate_object, object, object_elements);
10838 // Copy object elements if non-COW.
10839 if (object_elements != NULL) {
10840 BuildEmitElements(boilerplate_object, elements, object_elements,
10844 // Copy in-object properties.
10845 if (boilerplate_object->map()->NumberOfFields() != 0) {
10846 BuildEmitInObjectProperties(boilerplate_object, object, site_context,
10853 void HOptimizedGraphBuilder::BuildEmitObjectHeader(
10854 Handle<JSObject> boilerplate_object,
10855 HInstruction* object) {
10856 ASSERT(boilerplate_object->properties()->length() == 0);
10858 Handle<Map> boilerplate_object_map(boilerplate_object->map());
10859 AddStoreMapConstant(object, boilerplate_object_map);
10861 Handle<Object> properties_field =
10862 Handle<Object>(boilerplate_object->properties(), isolate());
10863 ASSERT(*properties_field == isolate()->heap()->empty_fixed_array());
10864 HInstruction* properties = Add<HConstant>(properties_field);
10865 HObjectAccess access = HObjectAccess::ForPropertiesPointer();
10866 Add<HStoreNamedField>(object, access, properties);
10868 if (boilerplate_object->IsJSArray()) {
10869 Handle<JSArray> boilerplate_array =
10870 Handle<JSArray>::cast(boilerplate_object);
10871 Handle<Object> length_field =
10872 Handle<Object>(boilerplate_array->length(), isolate());
10873 HInstruction* length = Add<HConstant>(length_field);
10875 ASSERT(boilerplate_array->length()->IsSmi());
10876 Add<HStoreNamedField>(object, HObjectAccess::ForArrayLength(
10877 boilerplate_array->GetElementsKind()), length);
10882 void HOptimizedGraphBuilder::BuildInitElementsInObjectHeader(
10883 Handle<JSObject> boilerplate_object,
10884 HInstruction* object,
10885 HInstruction* object_elements) {
10886 ASSERT(boilerplate_object->properties()->length() == 0);
10887 if (object_elements == NULL) {
10888 Handle<Object> elements_field =
10889 Handle<Object>(boilerplate_object->elements(), isolate());
10890 object_elements = Add<HConstant>(elements_field);
10892 Add<HStoreNamedField>(object, HObjectAccess::ForElementsPointer(),
10897 void HOptimizedGraphBuilder::BuildEmitInObjectProperties(
10898 Handle<JSObject> boilerplate_object,
10899 HInstruction* object,
10900 AllocationSiteUsageContext* site_context,
10901 PretenureFlag pretenure_flag) {
10902 Handle<Map> boilerplate_map(boilerplate_object->map());
10903 Handle<DescriptorArray> descriptors(boilerplate_map->instance_descriptors());
10904 int limit = boilerplate_map->NumberOfOwnDescriptors();
10906 int copied_fields = 0;
10907 for (int i = 0; i < limit; i++) {
10908 PropertyDetails details = descriptors->GetDetails(i);
10909 if (details.type() != FIELD) continue;
10911 int index = descriptors->GetFieldIndex(i);
10912 int property_offset = boilerplate_object->GetInObjectPropertyOffset(index);
10913 Handle<Name> name(descriptors->GetKey(i));
10914 Handle<Object> value =
10915 Handle<Object>(boilerplate_object->InObjectPropertyAt(index),
10918 // The access for the store depends on the type of the boilerplate.
10919 HObjectAccess access = boilerplate_object->IsJSArray() ?
10920 HObjectAccess::ForJSArrayOffset(property_offset) :
10921 HObjectAccess::ForMapAndOffset(boilerplate_map, property_offset);
10923 if (value->IsJSObject()) {
10924 Handle<JSObject> value_object = Handle<JSObject>::cast(value);
10925 Handle<AllocationSite> current_site = site_context->EnterNewScope();
10926 HInstruction* result =
10927 BuildFastLiteral(value_object, site_context);
10928 site_context->ExitScope(current_site, value_object);
10929 Add<HStoreNamedField>(object, access, result);
10931 Representation representation = details.representation();
10932 HInstruction* value_instruction;
10934 if (representation.IsDouble()) {
10935 // Allocate a HeapNumber box and store the value into it.
10936 HValue* heap_number_constant = Add<HConstant>(HeapNumber::kSize);
10937 // This heap number alloc does not have a corresponding
10938 // AllocationSite. That is okay because
10939 // 1) it's a child object of another object with a valid allocation site
10940 // 2) we can just use the mode of the parent object for pretenuring
10941 HInstruction* double_box =
10942 Add<HAllocate>(heap_number_constant, HType::HeapObject(),
10943 pretenure_flag, HEAP_NUMBER_TYPE);
10944 AddStoreMapConstant(double_box,
10945 isolate()->factory()->heap_number_map());
10946 Add<HStoreNamedField>(double_box, HObjectAccess::ForHeapNumberValue(),
10947 Add<HConstant>(value));
10948 value_instruction = double_box;
10949 } else if (representation.IsSmi()) {
10950 value_instruction = value->IsUninitialized()
10951 ? graph()->GetConstant0()
10952 : Add<HConstant>(value);
10953 // Ensure that value is stored as smi.
10954 access = access.WithRepresentation(representation);
10956 value_instruction = Add<HConstant>(value);
10959 Add<HStoreNamedField>(object, access, value_instruction);
10963 int inobject_properties = boilerplate_object->map()->inobject_properties();
10964 HInstruction* value_instruction =
10965 Add<HConstant>(isolate()->factory()->one_pointer_filler_map());
10966 for (int i = copied_fields; i < inobject_properties; i++) {
10967 ASSERT(boilerplate_object->IsJSObject());
10968 int property_offset = boilerplate_object->GetInObjectPropertyOffset(i);
10969 HObjectAccess access =
10970 HObjectAccess::ForMapAndOffset(boilerplate_map, property_offset);
10971 Add<HStoreNamedField>(object, access, value_instruction);
10976 void HOptimizedGraphBuilder::BuildEmitElements(
10977 Handle<JSObject> boilerplate_object,
10978 Handle<FixedArrayBase> elements,
10979 HValue* object_elements,
10980 AllocationSiteUsageContext* site_context) {
10981 ElementsKind kind = boilerplate_object->map()->elements_kind();
10982 int elements_length = elements->length();
10983 HValue* object_elements_length = Add<HConstant>(elements_length);
10984 BuildInitializeElementsHeader(object_elements, kind, object_elements_length);
10986 // Copy elements backing store content.
10987 if (elements->IsFixedDoubleArray()) {
10988 BuildEmitFixedDoubleArray(elements, kind, object_elements);
10989 } else if (elements->IsFixedArray()) {
10990 BuildEmitFixedArray(elements, kind, object_elements,
10998 void HOptimizedGraphBuilder::BuildEmitFixedDoubleArray(
10999 Handle<FixedArrayBase> elements,
11001 HValue* object_elements) {
11002 HInstruction* boilerplate_elements = Add<HConstant>(elements);
11003 int elements_length = elements->length();
11004 for (int i = 0; i < elements_length; i++) {
11005 HValue* key_constant = Add<HConstant>(i);
11006 HInstruction* value_instruction =
11007 Add<HLoadKeyed>(boilerplate_elements, key_constant,
11008 static_cast<HValue*>(NULL), kind,
11009 ALLOW_RETURN_HOLE);
11010 HInstruction* store = Add<HStoreKeyed>(object_elements, key_constant,
11011 value_instruction, kind);
11012 store->SetFlag(HValue::kAllowUndefinedAsNaN);
11017 void HOptimizedGraphBuilder::BuildEmitFixedArray(
11018 Handle<FixedArrayBase> elements,
11020 HValue* object_elements,
11021 AllocationSiteUsageContext* site_context) {
11022 HInstruction* boilerplate_elements = Add<HConstant>(elements);
11023 int elements_length = elements->length();
11024 Handle<FixedArray> fast_elements = Handle<FixedArray>::cast(elements);
11025 for (int i = 0; i < elements_length; i++) {
11026 Handle<Object> value(fast_elements->get(i), isolate());
11027 HValue* key_constant = Add<HConstant>(i);
11028 if (value->IsJSObject()) {
11029 Handle<JSObject> value_object = Handle<JSObject>::cast(value);
11030 Handle<AllocationSite> current_site = site_context->EnterNewScope();
11031 HInstruction* result =
11032 BuildFastLiteral(value_object, site_context);
11033 site_context->ExitScope(current_site, value_object);
11034 Add<HStoreKeyed>(object_elements, key_constant, result, kind);
11036 HInstruction* value_instruction =
11037 Add<HLoadKeyed>(boilerplate_elements, key_constant,
11038 static_cast<HValue*>(NULL), kind,
11039 ALLOW_RETURN_HOLE);
11040 Add<HStoreKeyed>(object_elements, key_constant, value_instruction, kind);
11046 void HOptimizedGraphBuilder::VisitThisFunction(ThisFunction* expr) {
11047 ASSERT(!HasStackOverflow());
11048 ASSERT(current_block() != NULL);
11049 ASSERT(current_block()->HasPredecessor());
11050 HInstruction* instr = BuildThisFunction();
11051 return ast_context()->ReturnInstruction(instr, expr->id());
11055 void HOptimizedGraphBuilder::VisitDeclarations(
11056 ZoneList<Declaration*>* declarations) {
11057 ASSERT(globals_.is_empty());
11058 AstVisitor::VisitDeclarations(declarations);
11059 if (!globals_.is_empty()) {
11060 Handle<FixedArray> array =
11061 isolate()->factory()->NewFixedArray(globals_.length(), TENURED);
11062 for (int i = 0; i < globals_.length(); ++i) array->set(i, *globals_.at(i));
11063 int flags = DeclareGlobalsEvalFlag::encode(current_info()->is_eval()) |
11064 DeclareGlobalsNativeFlag::encode(current_info()->is_native()) |
11065 DeclareGlobalsStrictMode::encode(current_info()->strict_mode());
11066 Add<HDeclareGlobals>(array, flags);
11067 globals_.Rewind(0);
11072 void HOptimizedGraphBuilder::VisitVariableDeclaration(
11073 VariableDeclaration* declaration) {
11074 VariableProxy* proxy = declaration->proxy();
11075 VariableMode mode = declaration->mode();
11076 Variable* variable = proxy->var();
11077 bool hole_init = mode == LET || mode == CONST || mode == CONST_LEGACY;
11078 switch (variable->location()) {
11079 case Variable::UNALLOCATED:
11080 globals_.Add(variable->name(), zone());
11081 globals_.Add(variable->binding_needs_init()
11082 ? isolate()->factory()->the_hole_value()
11083 : isolate()->factory()->undefined_value(), zone());
11085 case Variable::PARAMETER:
11086 case Variable::LOCAL:
11088 HValue* value = graph()->GetConstantHole();
11089 environment()->Bind(variable, value);
11092 case Variable::CONTEXT:
11094 HValue* value = graph()->GetConstantHole();
11095 HValue* context = environment()->context();
11096 HStoreContextSlot* store = Add<HStoreContextSlot>(
11097 context, variable->index(), HStoreContextSlot::kNoCheck, value);
11098 if (store->HasObservableSideEffects()) {
11099 Add<HSimulate>(proxy->id(), REMOVABLE_SIMULATE);
11103 case Variable::LOOKUP:
11104 return Bailout(kUnsupportedLookupSlotInDeclaration);
11109 void HOptimizedGraphBuilder::VisitFunctionDeclaration(
11110 FunctionDeclaration* declaration) {
11111 VariableProxy* proxy = declaration->proxy();
11112 Variable* variable = proxy->var();
11113 switch (variable->location()) {
11114 case Variable::UNALLOCATED: {
11115 globals_.Add(variable->name(), zone());
11116 Handle<SharedFunctionInfo> function = Compiler::BuildFunctionInfo(
11117 declaration->fun(), current_info()->script());
11118 // Check for stack-overflow exception.
11119 if (function.is_null()) return SetStackOverflow();
11120 globals_.Add(function, zone());
11123 case Variable::PARAMETER:
11124 case Variable::LOCAL: {
11125 CHECK_ALIVE(VisitForValue(declaration->fun()));
11126 HValue* value = Pop();
11127 BindIfLive(variable, value);
11130 case Variable::CONTEXT: {
11131 CHECK_ALIVE(VisitForValue(declaration->fun()));
11132 HValue* value = Pop();
11133 HValue* context = environment()->context();
11134 HStoreContextSlot* store = Add<HStoreContextSlot>(
11135 context, variable->index(), HStoreContextSlot::kNoCheck, value);
11136 if (store->HasObservableSideEffects()) {
11137 Add<HSimulate>(proxy->id(), REMOVABLE_SIMULATE);
11141 case Variable::LOOKUP:
11142 return Bailout(kUnsupportedLookupSlotInDeclaration);
11147 void HOptimizedGraphBuilder::VisitModuleDeclaration(
11148 ModuleDeclaration* declaration) {
11153 void HOptimizedGraphBuilder::VisitImportDeclaration(
11154 ImportDeclaration* declaration) {
11159 void HOptimizedGraphBuilder::VisitExportDeclaration(
11160 ExportDeclaration* declaration) {
11165 void HOptimizedGraphBuilder::VisitModuleLiteral(ModuleLiteral* module) {
11170 void HOptimizedGraphBuilder::VisitModuleVariable(ModuleVariable* module) {
11175 void HOptimizedGraphBuilder::VisitModulePath(ModulePath* module) {
11180 void HOptimizedGraphBuilder::VisitModuleUrl(ModuleUrl* module) {
11185 void HOptimizedGraphBuilder::VisitModuleStatement(ModuleStatement* stmt) {
11190 // Generators for inline runtime functions.
11191 // Support for types.
11192 void HOptimizedGraphBuilder::GenerateIsSmi(CallRuntime* call) {
11193 ASSERT(call->arguments()->length() == 1);
11194 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11195 HValue* value = Pop();
11196 HIsSmiAndBranch* result = New<HIsSmiAndBranch>(value);
11197 return ast_context()->ReturnControl(result, call->id());
11201 void HOptimizedGraphBuilder::GenerateIsSpecObject(CallRuntime* call) {
11202 ASSERT(call->arguments()->length() == 1);
11203 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11204 HValue* value = Pop();
11205 HHasInstanceTypeAndBranch* result =
11206 New<HHasInstanceTypeAndBranch>(value,
11207 FIRST_SPEC_OBJECT_TYPE,
11208 LAST_SPEC_OBJECT_TYPE);
11209 return ast_context()->ReturnControl(result, call->id());
11213 void HOptimizedGraphBuilder::GenerateIsFunction(CallRuntime* call) {
11214 ASSERT(call->arguments()->length() == 1);
11215 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11216 HValue* value = Pop();
11217 HHasInstanceTypeAndBranch* result =
11218 New<HHasInstanceTypeAndBranch>(value, JS_FUNCTION_TYPE);
11219 return ast_context()->ReturnControl(result, call->id());
11223 void HOptimizedGraphBuilder::GenerateIsMinusZero(CallRuntime* call) {
11224 ASSERT(call->arguments()->length() == 1);
11225 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11226 HValue* value = Pop();
11227 HCompareMinusZeroAndBranch* result = New<HCompareMinusZeroAndBranch>(value);
11228 return ast_context()->ReturnControl(result, call->id());
11232 void HOptimizedGraphBuilder::GenerateHasCachedArrayIndex(CallRuntime* call) {
11233 ASSERT(call->arguments()->length() == 1);
11234 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11235 HValue* value = Pop();
11236 HHasCachedArrayIndexAndBranch* result =
11237 New<HHasCachedArrayIndexAndBranch>(value);
11238 return ast_context()->ReturnControl(result, call->id());
11242 void HOptimizedGraphBuilder::GenerateIsArray(CallRuntime* call) {
11243 ASSERT(call->arguments()->length() == 1);
11244 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11245 HValue* value = Pop();
11246 HHasInstanceTypeAndBranch* result =
11247 New<HHasInstanceTypeAndBranch>(value, JS_ARRAY_TYPE);
11248 return ast_context()->ReturnControl(result, call->id());
11252 void HOptimizedGraphBuilder::GenerateIsRegExp(CallRuntime* call) {
11253 ASSERT(call->arguments()->length() == 1);
11254 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11255 HValue* value = Pop();
11256 HHasInstanceTypeAndBranch* result =
11257 New<HHasInstanceTypeAndBranch>(value, JS_REGEXP_TYPE);
11258 return ast_context()->ReturnControl(result, call->id());
11262 void HOptimizedGraphBuilder::GenerateIsObject(CallRuntime* call) {
11263 ASSERT(call->arguments()->length() == 1);
11264 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11265 HValue* value = Pop();
11266 HIsObjectAndBranch* result = New<HIsObjectAndBranch>(value);
11267 return ast_context()->ReturnControl(result, call->id());
11271 void HOptimizedGraphBuilder::GenerateIsNonNegativeSmi(CallRuntime* call) {
11272 return Bailout(kInlinedRuntimeFunctionIsNonNegativeSmi);
11276 void HOptimizedGraphBuilder::GenerateIsUndetectableObject(CallRuntime* call) {
11277 ASSERT(call->arguments()->length() == 1);
11278 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11279 HValue* value = Pop();
11280 HIsUndetectableAndBranch* result = New<HIsUndetectableAndBranch>(value);
11281 return ast_context()->ReturnControl(result, call->id());
11285 void HOptimizedGraphBuilder::GenerateIsStringWrapperSafeForDefaultValueOf(
11286 CallRuntime* call) {
11287 return Bailout(kInlinedRuntimeFunctionIsStringWrapperSafeForDefaultValueOf);
11291 // Support for construct call checks.
11292 void HOptimizedGraphBuilder::GenerateIsConstructCall(CallRuntime* call) {
11293 ASSERT(call->arguments()->length() == 0);
11294 if (function_state()->outer() != NULL) {
11295 // We are generating graph for inlined function.
11296 HValue* value = function_state()->inlining_kind() == CONSTRUCT_CALL_RETURN
11297 ? graph()->GetConstantTrue()
11298 : graph()->GetConstantFalse();
11299 return ast_context()->ReturnValue(value);
11301 return ast_context()->ReturnControl(New<HIsConstructCallAndBranch>(),
11307 // Support for arguments.length and arguments[?].
11308 void HOptimizedGraphBuilder::GenerateArgumentsLength(CallRuntime* call) {
11309 // Our implementation of arguments (based on this stack frame or an
11310 // adapter below it) does not work for inlined functions. This runtime
11311 // function is blacklisted by AstNode::IsInlineable.
11312 ASSERT(function_state()->outer() == NULL);
11313 ASSERT(call->arguments()->length() == 0);
11314 HInstruction* elements = Add<HArgumentsElements>(false);
11315 HArgumentsLength* result = New<HArgumentsLength>(elements);
11316 return ast_context()->ReturnInstruction(result, call->id());
11320 void HOptimizedGraphBuilder::GenerateArguments(CallRuntime* call) {
11321 // Our implementation of arguments (based on this stack frame or an
11322 // adapter below it) does not work for inlined functions. This runtime
11323 // function is blacklisted by AstNode::IsInlineable.
11324 ASSERT(function_state()->outer() == NULL);
11325 ASSERT(call->arguments()->length() == 1);
11326 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11327 HValue* index = Pop();
11328 HInstruction* elements = Add<HArgumentsElements>(false);
11329 HInstruction* length = Add<HArgumentsLength>(elements);
11330 HInstruction* checked_index = Add<HBoundsCheck>(index, length);
11331 HAccessArgumentsAt* result = New<HAccessArgumentsAt>(
11332 elements, length, checked_index);
11333 return ast_context()->ReturnInstruction(result, call->id());
11337 // Support for accessing the class and value fields of an object.
11338 void HOptimizedGraphBuilder::GenerateClassOf(CallRuntime* call) {
11339 // The special form detected by IsClassOfTest is detected before we get here
11340 // and does not cause a bailout.
11341 return Bailout(kInlinedRuntimeFunctionClassOf);
11345 void HOptimizedGraphBuilder::GenerateValueOf(CallRuntime* call) {
11346 ASSERT(call->arguments()->length() == 1);
11347 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11348 HValue* object = Pop();
11350 IfBuilder if_objectisvalue(this);
11351 HValue* objectisvalue = if_objectisvalue.If<HHasInstanceTypeAndBranch>(
11352 object, JS_VALUE_TYPE);
11353 if_objectisvalue.Then();
11355 // Return the actual value.
11356 Push(Add<HLoadNamedField>(
11357 object, objectisvalue,
11358 HObjectAccess::ForObservableJSObjectOffset(
11359 JSValue::kValueOffset)));
11360 Add<HSimulate>(call->id(), FIXED_SIMULATE);
11362 if_objectisvalue.Else();
11364 // If the object is not a value return the object.
11366 Add<HSimulate>(call->id(), FIXED_SIMULATE);
11368 if_objectisvalue.End();
11369 return ast_context()->ReturnValue(Pop());
11373 void HOptimizedGraphBuilder::GenerateDateField(CallRuntime* call) {
11374 ASSERT(call->arguments()->length() == 2);
11375 ASSERT_NE(NULL, call->arguments()->at(1)->AsLiteral());
11376 Smi* index = Smi::cast(*(call->arguments()->at(1)->AsLiteral()->value()));
11377 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11378 HValue* date = Pop();
11379 HDateField* result = New<HDateField>(date, index);
11380 return ast_context()->ReturnInstruction(result, call->id());
11384 void HOptimizedGraphBuilder::GenerateOneByteSeqStringSetChar(
11385 CallRuntime* call) {
11386 ASSERT(call->arguments()->length() == 3);
11387 // We need to follow the evaluation order of full codegen.
11388 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
11389 CHECK_ALIVE(VisitForValue(call->arguments()->at(2)));
11390 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11391 HValue* string = Pop();
11392 HValue* value = Pop();
11393 HValue* index = Pop();
11394 Add<HSeqStringSetChar>(String::ONE_BYTE_ENCODING, string,
11396 Add<HSimulate>(call->id(), FIXED_SIMULATE);
11397 return ast_context()->ReturnValue(graph()->GetConstantUndefined());
11401 void HOptimizedGraphBuilder::GenerateTwoByteSeqStringSetChar(
11402 CallRuntime* call) {
11403 ASSERT(call->arguments()->length() == 3);
11404 // We need to follow the evaluation order of full codegen.
11405 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
11406 CHECK_ALIVE(VisitForValue(call->arguments()->at(2)));
11407 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11408 HValue* string = Pop();
11409 HValue* value = Pop();
11410 HValue* index = Pop();
11411 Add<HSeqStringSetChar>(String::TWO_BYTE_ENCODING, string,
11413 Add<HSimulate>(call->id(), FIXED_SIMULATE);
11414 return ast_context()->ReturnValue(graph()->GetConstantUndefined());
11418 void HOptimizedGraphBuilder::GenerateSetValueOf(CallRuntime* call) {
11419 ASSERT(call->arguments()->length() == 2);
11420 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11421 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
11422 HValue* value = Pop();
11423 HValue* object = Pop();
11425 // Check if object is a JSValue.
11426 IfBuilder if_objectisvalue(this);
11427 if_objectisvalue.If<HHasInstanceTypeAndBranch>(object, JS_VALUE_TYPE);
11428 if_objectisvalue.Then();
11430 // Create in-object property store to kValueOffset.
11431 Add<HStoreNamedField>(object,
11432 HObjectAccess::ForObservableJSObjectOffset(JSValue::kValueOffset),
11434 if (!ast_context()->IsEffect()) {
11437 Add<HSimulate>(call->id(), FIXED_SIMULATE);
11439 if_objectisvalue.Else();
11441 // Nothing to do in this case.
11442 if (!ast_context()->IsEffect()) {
11445 Add<HSimulate>(call->id(), FIXED_SIMULATE);
11447 if_objectisvalue.End();
11448 if (!ast_context()->IsEffect()) {
11451 return ast_context()->ReturnValue(value);
11455 // Fast support for charCodeAt(n).
11456 void HOptimizedGraphBuilder::GenerateStringCharCodeAt(CallRuntime* call) {
11457 ASSERT(call->arguments()->length() == 2);
11458 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11459 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
11460 HValue* index = Pop();
11461 HValue* string = Pop();
11462 HInstruction* result = BuildStringCharCodeAt(string, index);
11463 return ast_context()->ReturnInstruction(result, call->id());
11467 // Fast support for string.charAt(n) and string[n].
11468 void HOptimizedGraphBuilder::GenerateStringCharFromCode(CallRuntime* call) {
11469 ASSERT(call->arguments()->length() == 1);
11470 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11471 HValue* char_code = Pop();
11472 HInstruction* result = NewUncasted<HStringCharFromCode>(char_code);
11473 return ast_context()->ReturnInstruction(result, call->id());
11477 // Fast support for string.charAt(n) and string[n].
11478 void HOptimizedGraphBuilder::GenerateStringCharAt(CallRuntime* call) {
11479 ASSERT(call->arguments()->length() == 2);
11480 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11481 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
11482 HValue* index = Pop();
11483 HValue* string = Pop();
11484 HInstruction* char_code = BuildStringCharCodeAt(string, index);
11485 AddInstruction(char_code);
11486 HInstruction* result = NewUncasted<HStringCharFromCode>(char_code);
11487 return ast_context()->ReturnInstruction(result, call->id());
11491 // Fast support for object equality testing.
11492 void HOptimizedGraphBuilder::GenerateObjectEquals(CallRuntime* call) {
11493 ASSERT(call->arguments()->length() == 2);
11494 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11495 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
11496 HValue* right = Pop();
11497 HValue* left = Pop();
11498 HCompareObjectEqAndBranch* result =
11499 New<HCompareObjectEqAndBranch>(left, right);
11500 return ast_context()->ReturnControl(result, call->id());
11504 // Fast support for StringAdd.
11505 void HOptimizedGraphBuilder::GenerateStringAdd(CallRuntime* call) {
11506 ASSERT_EQ(2, call->arguments()->length());
11507 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11508 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
11509 HValue* right = Pop();
11510 HValue* left = Pop();
11511 HInstruction* result = NewUncasted<HStringAdd>(left, right);
11512 return ast_context()->ReturnInstruction(result, call->id());
11516 // Fast support for SubString.
11517 void HOptimizedGraphBuilder::GenerateSubString(CallRuntime* call) {
11518 ASSERT_EQ(3, call->arguments()->length());
11519 CHECK_ALIVE(VisitExpressions(call->arguments()));
11520 PushArgumentsFromEnvironment(call->arguments()->length());
11521 HCallStub* result = New<HCallStub>(CodeStub::SubString, 3);
11522 return ast_context()->ReturnInstruction(result, call->id());
11526 // Fast support for StringCompare.
11527 void HOptimizedGraphBuilder::GenerateStringCompare(CallRuntime* call) {
11528 ASSERT_EQ(2, call->arguments()->length());
11529 CHECK_ALIVE(VisitExpressions(call->arguments()));
11530 PushArgumentsFromEnvironment(call->arguments()->length());
11531 HCallStub* result = New<HCallStub>(CodeStub::StringCompare, 2);
11532 return ast_context()->ReturnInstruction(result, call->id());
11536 // Support for direct calls from JavaScript to native RegExp code.
11537 void HOptimizedGraphBuilder::GenerateRegExpExec(CallRuntime* call) {
11538 ASSERT_EQ(4, call->arguments()->length());
11539 CHECK_ALIVE(VisitExpressions(call->arguments()));
11540 PushArgumentsFromEnvironment(call->arguments()->length());
11541 HCallStub* result = New<HCallStub>(CodeStub::RegExpExec, 4);
11542 return ast_context()->ReturnInstruction(result, call->id());
11546 void HOptimizedGraphBuilder::GenerateDoubleLo(CallRuntime* call) {
11547 ASSERT_EQ(1, call->arguments()->length());
11548 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11549 HValue* value = Pop();
11550 HInstruction* result = NewUncasted<HDoubleBits>(value, HDoubleBits::LOW);
11551 return ast_context()->ReturnInstruction(result, call->id());
11555 void HOptimizedGraphBuilder::GenerateDoubleHi(CallRuntime* call) {
11556 ASSERT_EQ(1, call->arguments()->length());
11557 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11558 HValue* value = Pop();
11559 HInstruction* result = NewUncasted<HDoubleBits>(value, HDoubleBits::HIGH);
11560 return ast_context()->ReturnInstruction(result, call->id());
11564 void HOptimizedGraphBuilder::GenerateConstructDouble(CallRuntime* call) {
11565 ASSERT_EQ(2, call->arguments()->length());
11566 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11567 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
11568 HValue* lo = Pop();
11569 HValue* hi = Pop();
11570 HInstruction* result = NewUncasted<HConstructDouble>(hi, lo);
11571 return ast_context()->ReturnInstruction(result, call->id());
11575 // Construct a RegExp exec result with two in-object properties.
11576 void HOptimizedGraphBuilder::GenerateRegExpConstructResult(CallRuntime* call) {
11577 ASSERT_EQ(3, call->arguments()->length());
11578 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11579 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
11580 CHECK_ALIVE(VisitForValue(call->arguments()->at(2)));
11581 HValue* input = Pop();
11582 HValue* index = Pop();
11583 HValue* length = Pop();
11584 HValue* result = BuildRegExpConstructResult(length, index, input);
11585 return ast_context()->ReturnValue(result);
11589 // Support for fast native caches.
11590 void HOptimizedGraphBuilder::GenerateGetFromCache(CallRuntime* call) {
11591 return Bailout(kInlinedRuntimeFunctionGetFromCache);
11595 // Fast support for number to string.
11596 void HOptimizedGraphBuilder::GenerateNumberToString(CallRuntime* call) {
11597 ASSERT_EQ(1, call->arguments()->length());
11598 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11599 HValue* number = Pop();
11600 HValue* result = BuildNumberToString(number, Type::Any(zone()));
11601 return ast_context()->ReturnValue(result);
11605 // Fast call for custom callbacks.
11606 void HOptimizedGraphBuilder::GenerateCallFunction(CallRuntime* call) {
11607 // 1 ~ The function to call is not itself an argument to the call.
11608 int arg_count = call->arguments()->length() - 1;
11609 ASSERT(arg_count >= 1); // There's always at least a receiver.
11611 CHECK_ALIVE(VisitExpressions(call->arguments()));
11612 // The function is the last argument
11613 HValue* function = Pop();
11614 // Push the arguments to the stack
11615 PushArgumentsFromEnvironment(arg_count);
11617 IfBuilder if_is_jsfunction(this);
11618 if_is_jsfunction.If<HHasInstanceTypeAndBranch>(function, JS_FUNCTION_TYPE);
11620 if_is_jsfunction.Then();
11622 HInstruction* invoke_result =
11623 Add<HInvokeFunction>(function, arg_count);
11624 if (!ast_context()->IsEffect()) {
11625 Push(invoke_result);
11627 Add<HSimulate>(call->id(), FIXED_SIMULATE);
11630 if_is_jsfunction.Else();
11632 HInstruction* call_result =
11633 Add<HCallFunction>(function, arg_count);
11634 if (!ast_context()->IsEffect()) {
11637 Add<HSimulate>(call->id(), FIXED_SIMULATE);
11639 if_is_jsfunction.End();
11641 if (ast_context()->IsEffect()) {
11642 // EffectContext::ReturnValue ignores the value, so we can just pass
11643 // 'undefined' (as we do not have the call result anymore).
11644 return ast_context()->ReturnValue(graph()->GetConstantUndefined());
11646 return ast_context()->ReturnValue(Pop());
11651 // Fast call to math functions.
11652 void HOptimizedGraphBuilder::GenerateMathPow(CallRuntime* call) {
11653 ASSERT_EQ(2, call->arguments()->length());
11654 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11655 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
11656 HValue* right = Pop();
11657 HValue* left = Pop();
11658 HInstruction* result = NewUncasted<HPower>(left, right);
11659 return ast_context()->ReturnInstruction(result, call->id());
11663 void HOptimizedGraphBuilder::GenerateMathLogRT(CallRuntime* call) {
11664 ASSERT(call->arguments()->length() == 1);
11665 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11666 HValue* value = Pop();
11667 HInstruction* result = NewUncasted<HUnaryMathOperation>(value, kMathLog);
11668 return ast_context()->ReturnInstruction(result, call->id());
11672 void HOptimizedGraphBuilder::GenerateMathSqrtRT(CallRuntime* call) {
11673 ASSERT(call->arguments()->length() == 1);
11674 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11675 HValue* value = Pop();
11676 HInstruction* result = NewUncasted<HUnaryMathOperation>(value, kMathSqrt);
11677 return ast_context()->ReturnInstruction(result, call->id());
11681 void HOptimizedGraphBuilder::GenerateGetCachedArrayIndex(CallRuntime* call) {
11682 ASSERT(call->arguments()->length() == 1);
11683 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11684 HValue* value = Pop();
11685 HGetCachedArrayIndex* result = New<HGetCachedArrayIndex>(value);
11686 return ast_context()->ReturnInstruction(result, call->id());
11690 void HOptimizedGraphBuilder::GenerateFastAsciiArrayJoin(CallRuntime* call) {
11691 return Bailout(kInlinedRuntimeFunctionFastAsciiArrayJoin);
11695 // Support for generators.
11696 void HOptimizedGraphBuilder::GenerateGeneratorNext(CallRuntime* call) {
11697 return Bailout(kInlinedRuntimeFunctionGeneratorNext);
11701 void HOptimizedGraphBuilder::GenerateGeneratorThrow(CallRuntime* call) {
11702 return Bailout(kInlinedRuntimeFunctionGeneratorThrow);
11706 void HOptimizedGraphBuilder::GenerateDebugBreakInOptimizedCode(
11707 CallRuntime* call) {
11708 Add<HDebugBreak>();
11709 return ast_context()->ReturnValue(graph()->GetConstant0());
11713 void HOptimizedGraphBuilder::GenerateDebugCallbackSupportsStepping(
11714 CallRuntime* call) {
11715 ASSERT(call->arguments()->length() == 1);
11716 // Debugging is not supported in optimized code.
11717 return ast_context()->ReturnValue(graph()->GetConstantFalse());
11721 #undef CHECK_BAILOUT
11725 HEnvironment::HEnvironment(HEnvironment* outer,
11727 Handle<JSFunction> closure,
11729 : closure_(closure),
11731 frame_type_(JS_FUNCTION),
11732 parameter_count_(0),
11733 specials_count_(1),
11739 ast_id_(BailoutId::None()),
11741 Scope* declaration_scope = scope->DeclarationScope();
11742 Initialize(declaration_scope->num_parameters() + 1,
11743 declaration_scope->num_stack_slots(), 0);
11747 HEnvironment::HEnvironment(Zone* zone, int parameter_count)
11748 : values_(0, zone),
11750 parameter_count_(parameter_count),
11751 specials_count_(1),
11757 ast_id_(BailoutId::None()),
11759 Initialize(parameter_count, 0, 0);
11763 HEnvironment::HEnvironment(const HEnvironment* other, Zone* zone)
11764 : values_(0, zone),
11765 frame_type_(JS_FUNCTION),
11766 parameter_count_(0),
11767 specials_count_(0),
11773 ast_id_(other->ast_id()),
11779 HEnvironment::HEnvironment(HEnvironment* outer,
11780 Handle<JSFunction> closure,
11781 FrameType frame_type,
11784 : closure_(closure),
11785 values_(arguments, zone),
11786 frame_type_(frame_type),
11787 parameter_count_(arguments),
11788 specials_count_(0),
11794 ast_id_(BailoutId::None()),
11799 void HEnvironment::Initialize(int parameter_count,
11801 int stack_height) {
11802 parameter_count_ = parameter_count;
11803 local_count_ = local_count;
11805 // Avoid reallocating the temporaries' backing store on the first Push.
11806 int total = parameter_count + specials_count_ + local_count + stack_height;
11807 values_.Initialize(total + 4, zone());
11808 for (int i = 0; i < total; ++i) values_.Add(NULL, zone());
11812 void HEnvironment::Initialize(const HEnvironment* other) {
11813 closure_ = other->closure();
11814 values_.AddAll(other->values_, zone());
11815 assigned_variables_.Union(other->assigned_variables_, zone());
11816 frame_type_ = other->frame_type_;
11817 parameter_count_ = other->parameter_count_;
11818 local_count_ = other->local_count_;
11819 if (other->outer_ != NULL) outer_ = other->outer_->Copy(); // Deep copy.
11820 entry_ = other->entry_;
11821 pop_count_ = other->pop_count_;
11822 push_count_ = other->push_count_;
11823 specials_count_ = other->specials_count_;
11824 ast_id_ = other->ast_id_;
11828 void HEnvironment::AddIncomingEdge(HBasicBlock* block, HEnvironment* other) {
11829 ASSERT(!block->IsLoopHeader());
11830 ASSERT(values_.length() == other->values_.length());
11832 int length = values_.length();
11833 for (int i = 0; i < length; ++i) {
11834 HValue* value = values_[i];
11835 if (value != NULL && value->IsPhi() && value->block() == block) {
11836 // There is already a phi for the i'th value.
11837 HPhi* phi = HPhi::cast(value);
11838 // Assert index is correct and that we haven't missed an incoming edge.
11839 ASSERT(phi->merged_index() == i || !phi->HasMergedIndex());
11840 ASSERT(phi->OperandCount() == block->predecessors()->length());
11841 phi->AddInput(other->values_[i]);
11842 } else if (values_[i] != other->values_[i]) {
11843 // There is a fresh value on the incoming edge, a phi is needed.
11844 ASSERT(values_[i] != NULL && other->values_[i] != NULL);
11845 HPhi* phi = block->AddNewPhi(i);
11846 HValue* old_value = values_[i];
11847 for (int j = 0; j < block->predecessors()->length(); j++) {
11848 phi->AddInput(old_value);
11850 phi->AddInput(other->values_[i]);
11851 this->values_[i] = phi;
11857 void HEnvironment::Bind(int index, HValue* value) {
11858 ASSERT(value != NULL);
11859 assigned_variables_.Add(index, zone());
11860 values_[index] = value;
11864 bool HEnvironment::HasExpressionAt(int index) const {
11865 return index >= parameter_count_ + specials_count_ + local_count_;
11869 bool HEnvironment::ExpressionStackIsEmpty() const {
11870 ASSERT(length() >= first_expression_index());
11871 return length() == first_expression_index();
11875 void HEnvironment::SetExpressionStackAt(int index_from_top, HValue* value) {
11876 int count = index_from_top + 1;
11877 int index = values_.length() - count;
11878 ASSERT(HasExpressionAt(index));
11879 // The push count must include at least the element in question or else
11880 // the new value will not be included in this environment's history.
11881 if (push_count_ < count) {
11882 // This is the same effect as popping then re-pushing 'count' elements.
11883 pop_count_ += (count - push_count_);
11884 push_count_ = count;
11886 values_[index] = value;
11890 void HEnvironment::Drop(int count) {
11891 for (int i = 0; i < count; ++i) {
11897 HEnvironment* HEnvironment::Copy() const {
11898 return new(zone()) HEnvironment(this, zone());
11902 HEnvironment* HEnvironment::CopyWithoutHistory() const {
11903 HEnvironment* result = Copy();
11904 result->ClearHistory();
11909 HEnvironment* HEnvironment::CopyAsLoopHeader(HBasicBlock* loop_header) const {
11910 HEnvironment* new_env = Copy();
11911 for (int i = 0; i < values_.length(); ++i) {
11912 HPhi* phi = loop_header->AddNewPhi(i);
11913 phi->AddInput(values_[i]);
11914 new_env->values_[i] = phi;
11916 new_env->ClearHistory();
11921 HEnvironment* HEnvironment::CreateStubEnvironment(HEnvironment* outer,
11922 Handle<JSFunction> target,
11923 FrameType frame_type,
11924 int arguments) const {
11925 HEnvironment* new_env =
11926 new(zone()) HEnvironment(outer, target, frame_type,
11927 arguments + 1, zone());
11928 for (int i = 0; i <= arguments; ++i) { // Include receiver.
11929 new_env->Push(ExpressionStackAt(arguments - i));
11931 new_env->ClearHistory();
11936 HEnvironment* HEnvironment::CopyForInlining(
11937 Handle<JSFunction> target,
11939 FunctionLiteral* function,
11940 HConstant* undefined,
11941 InliningKind inlining_kind) const {
11942 ASSERT(frame_type() == JS_FUNCTION);
11944 // Outer environment is a copy of this one without the arguments.
11945 int arity = function->scope()->num_parameters();
11947 HEnvironment* outer = Copy();
11948 outer->Drop(arguments + 1); // Including receiver.
11949 outer->ClearHistory();
11951 if (inlining_kind == CONSTRUCT_CALL_RETURN) {
11952 // Create artificial constructor stub environment. The receiver should
11953 // actually be the constructor function, but we pass the newly allocated
11954 // object instead, DoComputeConstructStubFrame() relies on that.
11955 outer = CreateStubEnvironment(outer, target, JS_CONSTRUCT, arguments);
11956 } else if (inlining_kind == GETTER_CALL_RETURN) {
11957 // We need an additional StackFrame::INTERNAL frame for restoring the
11958 // correct context.
11959 outer = CreateStubEnvironment(outer, target, JS_GETTER, arguments);
11960 } else if (inlining_kind == SETTER_CALL_RETURN) {
11961 // We need an additional StackFrame::INTERNAL frame for temporarily saving
11962 // the argument of the setter, see StoreStubCompiler::CompileStoreViaSetter.
11963 outer = CreateStubEnvironment(outer, target, JS_SETTER, arguments);
11966 if (arity != arguments) {
11967 // Create artificial arguments adaptation environment.
11968 outer = CreateStubEnvironment(outer, target, ARGUMENTS_ADAPTOR, arguments);
11971 HEnvironment* inner =
11972 new(zone()) HEnvironment(outer, function->scope(), target, zone());
11973 // Get the argument values from the original environment.
11974 for (int i = 0; i <= arity; ++i) { // Include receiver.
11975 HValue* push = (i <= arguments) ?
11976 ExpressionStackAt(arguments - i) : undefined;
11977 inner->SetValueAt(i, push);
11979 inner->SetValueAt(arity + 1, context());
11980 for (int i = arity + 2; i < inner->length(); ++i) {
11981 inner->SetValueAt(i, undefined);
11984 inner->set_ast_id(BailoutId::FunctionEntry());
11989 void HEnvironment::PrintTo(StringStream* stream) {
11990 for (int i = 0; i < length(); i++) {
11991 if (i == 0) stream->Add("parameters\n");
11992 if (i == parameter_count()) stream->Add("specials\n");
11993 if (i == parameter_count() + specials_count()) stream->Add("locals\n");
11994 if (i == parameter_count() + specials_count() + local_count()) {
11995 stream->Add("expressions\n");
11997 HValue* val = values_.at(i);
11998 stream->Add("%d: ", i);
12000 val->PrintNameTo(stream);
12002 stream->Add("NULL");
12010 void HEnvironment::PrintToStd() {
12011 HeapStringAllocator string_allocator;
12012 StringStream trace(&string_allocator);
12014 PrintF("%s", trace.ToCString().get());
12018 void HTracer::TraceCompilation(CompilationInfo* info) {
12019 Tag tag(this, "compilation");
12020 if (info->IsOptimizing()) {
12021 Handle<String> name = info->function()->debug_name();
12022 PrintStringProperty("name", name->ToCString().get());
12024 trace_.Add("method \"%s:%d\"\n",
12025 name->ToCString().get(),
12026 info->optimization_id());
12028 CodeStub::Major major_key = info->code_stub()->MajorKey();
12029 PrintStringProperty("name", CodeStub::MajorName(major_key, false));
12030 PrintStringProperty("method", "stub");
12032 PrintLongProperty("date", static_cast<int64_t>(OS::TimeCurrentMillis()));
12036 void HTracer::TraceLithium(const char* name, LChunk* chunk) {
12037 ASSERT(!chunk->isolate()->concurrent_recompilation_enabled());
12038 AllowHandleDereference allow_deref;
12039 AllowDeferredHandleDereference allow_deferred_deref;
12040 Trace(name, chunk->graph(), chunk);
12044 void HTracer::TraceHydrogen(const char* name, HGraph* graph) {
12045 ASSERT(!graph->isolate()->concurrent_recompilation_enabled());
12046 AllowHandleDereference allow_deref;
12047 AllowDeferredHandleDereference allow_deferred_deref;
12048 Trace(name, graph, NULL);
12052 void HTracer::Trace(const char* name, HGraph* graph, LChunk* chunk) {
12053 Tag tag(this, "cfg");
12054 PrintStringProperty("name", name);
12055 const ZoneList<HBasicBlock*>* blocks = graph->blocks();
12056 for (int i = 0; i < blocks->length(); i++) {
12057 HBasicBlock* current = blocks->at(i);
12058 Tag block_tag(this, "block");
12059 PrintBlockProperty("name", current->block_id());
12060 PrintIntProperty("from_bci", -1);
12061 PrintIntProperty("to_bci", -1);
12063 if (!current->predecessors()->is_empty()) {
12065 trace_.Add("predecessors");
12066 for (int j = 0; j < current->predecessors()->length(); ++j) {
12067 trace_.Add(" \"B%d\"", current->predecessors()->at(j)->block_id());
12071 PrintEmptyProperty("predecessors");
12074 if (current->end()->SuccessorCount() == 0) {
12075 PrintEmptyProperty("successors");
12078 trace_.Add("successors");
12079 for (HSuccessorIterator it(current->end()); !it.Done(); it.Advance()) {
12080 trace_.Add(" \"B%d\"", it.Current()->block_id());
12085 PrintEmptyProperty("xhandlers");
12089 trace_.Add("flags");
12090 if (current->IsLoopSuccessorDominator()) {
12091 trace_.Add(" \"dom-loop-succ\"");
12093 if (current->IsUnreachable()) {
12094 trace_.Add(" \"dead\"");
12096 if (current->is_osr_entry()) {
12097 trace_.Add(" \"osr\"");
12102 if (current->dominator() != NULL) {
12103 PrintBlockProperty("dominator", current->dominator()->block_id());
12106 PrintIntProperty("loop_depth", current->LoopNestingDepth());
12108 if (chunk != NULL) {
12109 int first_index = current->first_instruction_index();
12110 int last_index = current->last_instruction_index();
12113 LifetimePosition::FromInstructionIndex(first_index).Value());
12116 LifetimePosition::FromInstructionIndex(last_index).Value());
12120 Tag states_tag(this, "states");
12121 Tag locals_tag(this, "locals");
12122 int total = current->phis()->length();
12123 PrintIntProperty("size", current->phis()->length());
12124 PrintStringProperty("method", "None");
12125 for (int j = 0; j < total; ++j) {
12126 HPhi* phi = current->phis()->at(j);
12128 trace_.Add("%d ", phi->merged_index());
12129 phi->PrintNameTo(&trace_);
12131 phi->PrintTo(&trace_);
12137 Tag HIR_tag(this, "HIR");
12138 for (HInstructionIterator it(current); !it.Done(); it.Advance()) {
12139 HInstruction* instruction = it.Current();
12140 int uses = instruction->UseCount();
12142 trace_.Add("0 %d ", uses);
12143 instruction->PrintNameTo(&trace_);
12145 instruction->PrintTo(&trace_);
12146 if (FLAG_hydrogen_track_positions &&
12147 instruction->has_position() &&
12148 instruction->position().raw() != 0) {
12149 const HSourcePosition pos = instruction->position();
12150 trace_.Add(" pos:");
12151 if (pos.inlining_id() != 0) {
12152 trace_.Add("%d_", pos.inlining_id());
12154 trace_.Add("%d", pos.position());
12156 trace_.Add(" <|@\n");
12161 if (chunk != NULL) {
12162 Tag LIR_tag(this, "LIR");
12163 int first_index = current->first_instruction_index();
12164 int last_index = current->last_instruction_index();
12165 if (first_index != -1 && last_index != -1) {
12166 const ZoneList<LInstruction*>* instructions = chunk->instructions();
12167 for (int i = first_index; i <= last_index; ++i) {
12168 LInstruction* linstr = instructions->at(i);
12169 if (linstr != NULL) {
12172 LifetimePosition::FromInstructionIndex(i).Value());
12173 linstr->PrintTo(&trace_);
12174 trace_.Add(" [hir:");
12175 linstr->hydrogen_value()->PrintNameTo(&trace_);
12177 trace_.Add(" <|@\n");
12186 void HTracer::TraceLiveRanges(const char* name, LAllocator* allocator) {
12187 Tag tag(this, "intervals");
12188 PrintStringProperty("name", name);
12190 const Vector<LiveRange*>* fixed_d = allocator->fixed_double_live_ranges();
12191 for (int i = 0; i < fixed_d->length(); ++i) {
12192 TraceLiveRange(fixed_d->at(i), "fixed", allocator->zone());
12195 const Vector<LiveRange*>* fixed = allocator->fixed_live_ranges();
12196 for (int i = 0; i < fixed->length(); ++i) {
12197 TraceLiveRange(fixed->at(i), "fixed", allocator->zone());
12200 const ZoneList<LiveRange*>* live_ranges = allocator->live_ranges();
12201 for (int i = 0; i < live_ranges->length(); ++i) {
12202 TraceLiveRange(live_ranges->at(i), "object", allocator->zone());
12207 void HTracer::TraceLiveRange(LiveRange* range, const char* type,
12209 if (range != NULL && !range->IsEmpty()) {
12211 trace_.Add("%d %s", range->id(), type);
12212 if (range->HasRegisterAssigned()) {
12213 LOperand* op = range->CreateAssignedOperand(zone);
12214 int assigned_reg = op->index();
12215 if (op->IsDoubleRegister()) {
12216 trace_.Add(" \"%s\"",
12217 DoubleRegister::AllocationIndexToString(assigned_reg));
12219 ASSERT(op->IsRegister());
12220 trace_.Add(" \"%s\"", Register::AllocationIndexToString(assigned_reg));
12222 } else if (range->IsSpilled()) {
12223 LOperand* op = range->TopLevel()->GetSpillOperand();
12224 if (op->IsDoubleStackSlot()) {
12225 trace_.Add(" \"double_stack:%d\"", op->index());
12227 ASSERT(op->IsStackSlot());
12228 trace_.Add(" \"stack:%d\"", op->index());
12231 int parent_index = -1;
12232 if (range->IsChild()) {
12233 parent_index = range->parent()->id();
12235 parent_index = range->id();
12237 LOperand* op = range->FirstHint();
12238 int hint_index = -1;
12239 if (op != NULL && op->IsUnallocated()) {
12240 hint_index = LUnallocated::cast(op)->virtual_register();
12242 trace_.Add(" %d %d", parent_index, hint_index);
12243 UseInterval* cur_interval = range->first_interval();
12244 while (cur_interval != NULL && range->Covers(cur_interval->start())) {
12245 trace_.Add(" [%d, %d[",
12246 cur_interval->start().Value(),
12247 cur_interval->end().Value());
12248 cur_interval = cur_interval->next();
12251 UsePosition* current_pos = range->first_pos();
12252 while (current_pos != NULL) {
12253 if (current_pos->RegisterIsBeneficial() || FLAG_trace_all_uses) {
12254 trace_.Add(" %d M", current_pos->pos().Value());
12256 current_pos = current_pos->next();
12259 trace_.Add(" \"\"\n");
12264 void HTracer::FlushToFile() {
12265 AppendChars(filename_.start(), trace_.ToCString().get(), trace_.length(),
12271 void HStatistics::Initialize(CompilationInfo* info) {
12272 if (info->shared_info().is_null()) return;
12273 source_size_ += info->shared_info()->SourceSize();
12277 void HStatistics::Print() {
12278 PrintF("Timing results:\n");
12280 for (int i = 0; i < times_.length(); ++i) {
12284 for (int i = 0; i < names_.length(); ++i) {
12285 PrintF("%32s", names_[i]);
12286 double ms = times_[i].InMillisecondsF();
12287 double percent = times_[i].PercentOf(sum);
12288 PrintF(" %8.3f ms / %4.1f %% ", ms, percent);
12290 unsigned size = sizes_[i];
12291 double size_percent = static_cast<double>(size) * 100 / total_size_;
12292 PrintF(" %9u bytes / %4.1f %%\n", size, size_percent);
12295 PrintF("----------------------------------------"
12296 "---------------------------------------\n");
12297 TimeDelta total = create_graph_ + optimize_graph_ + generate_code_;
12298 PrintF("%32s %8.3f ms / %4.1f %% \n",
12300 create_graph_.InMillisecondsF(),
12301 create_graph_.PercentOf(total));
12302 PrintF("%32s %8.3f ms / %4.1f %% \n",
12304 optimize_graph_.InMillisecondsF(),
12305 optimize_graph_.PercentOf(total));
12306 PrintF("%32s %8.3f ms / %4.1f %% \n",
12307 "Generate and install code",
12308 generate_code_.InMillisecondsF(),
12309 generate_code_.PercentOf(total));
12310 PrintF("----------------------------------------"
12311 "---------------------------------------\n");
12312 PrintF("%32s %8.3f ms (%.1f times slower than full code gen)\n",
12314 total.InMillisecondsF(),
12315 total.TimesOf(full_code_gen_));
12317 double source_size_in_kb = static_cast<double>(source_size_) / 1024;
12318 double normalized_time = source_size_in_kb > 0
12319 ? total.InMillisecondsF() / source_size_in_kb
12321 double normalized_size_in_kb = source_size_in_kb > 0
12322 ? total_size_ / 1024 / source_size_in_kb
12324 PrintF("%32s %8.3f ms %7.3f kB allocated\n",
12325 "Average per kB source",
12326 normalized_time, normalized_size_in_kb);
12330 void HStatistics::SaveTiming(const char* name, TimeDelta time, unsigned size) {
12331 total_size_ += size;
12332 for (int i = 0; i < names_.length(); ++i) {
12333 if (strcmp(names_[i], name) == 0) {
12345 HPhase::~HPhase() {
12346 if (ShouldProduceTraceOutput()) {
12347 isolate()->GetHTracer()->TraceHydrogen(name(), graph_);
12351 graph_->Verify(false); // No full verify.
12355 } } // namespace v8::internal