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"
11 #include "src/allocation-site-scopes.h"
12 #include "src/codegen.h"
13 #include "src/full-codegen.h"
14 #include "src/hashmap.h"
15 #include "src/hydrogen-bce.h"
16 #include "src/hydrogen-bch.h"
17 #include "src/hydrogen-canonicalize.h"
18 #include "src/hydrogen-check-elimination.h"
19 #include "src/hydrogen-dce.h"
20 #include "src/hydrogen-dehoist.h"
21 #include "src/hydrogen-environment-liveness.h"
22 #include "src/hydrogen-escape-analysis.h"
23 #include "src/hydrogen-gvn.h"
24 #include "src/hydrogen-infer-representation.h"
25 #include "src/hydrogen-infer-types.h"
26 #include "src/hydrogen-load-elimination.h"
27 #include "src/hydrogen-mark-deoptimize.h"
28 #include "src/hydrogen-mark-unreachable.h"
29 #include "src/hydrogen-osr.h"
30 #include "src/hydrogen-range-analysis.h"
31 #include "src/hydrogen-redundant-phi.h"
32 #include "src/hydrogen-removable-simulates.h"
33 #include "src/hydrogen-representation-changes.h"
34 #include "src/hydrogen-sce.h"
35 #include "src/hydrogen-store-elimination.h"
36 #include "src/hydrogen-uint32-analysis.h"
37 #include "src/lithium-allocator.h"
38 #include "src/parser.h"
39 #include "src/runtime.h"
40 #include "src/scopeinfo.h"
41 #include "src/scopes.h"
42 #include "src/stub-cache.h"
43 #include "src/typing.h"
45 #if V8_TARGET_ARCH_IA32
46 #include "src/ia32/lithium-codegen-ia32.h" // NOLINT
47 #elif V8_TARGET_ARCH_X64
48 #include "src/x64/lithium-codegen-x64.h" // NOLINT
49 #elif V8_TARGET_ARCH_ARM64
50 #include "src/arm64/lithium-codegen-arm64.h" // NOLINT
51 #elif V8_TARGET_ARCH_ARM
52 #include "src/arm/lithium-codegen-arm.h" // NOLINT
53 #elif V8_TARGET_ARCH_MIPS
54 #include "src/mips/lithium-codegen-mips.h" // NOLINT
55 #elif V8_TARGET_ARCH_MIPS64
56 #include "src/mips64/lithium-codegen-mips64.h" // NOLINT
57 #elif V8_TARGET_ARCH_X87
58 #include "src/x87/lithium-codegen-x87.h" // NOLINT
60 #error Unsupported target architecture.
66 HBasicBlock::HBasicBlock(HGraph* graph)
67 : block_id_(graph->GetNextBlockID()),
69 phis_(4, graph->zone()),
73 loop_information_(NULL),
74 predecessors_(2, graph->zone()),
76 dominated_blocks_(4, graph->zone()),
77 last_environment_(NULL),
79 first_instruction_index_(-1),
80 last_instruction_index_(-1),
81 deleted_phis_(4, graph->zone()),
82 parent_loop_header_(NULL),
83 inlined_entry_block_(NULL),
84 is_inline_return_target_(false),
86 dominates_loop_successors_(false),
88 is_ordered_(false) { }
91 Isolate* HBasicBlock::isolate() const {
92 return graph_->isolate();
96 void HBasicBlock::MarkUnreachable() {
97 is_reachable_ = false;
101 void HBasicBlock::AttachLoopInformation() {
102 DCHECK(!IsLoopHeader());
103 loop_information_ = new(zone()) HLoopInformation(this, zone());
107 void HBasicBlock::DetachLoopInformation() {
108 DCHECK(IsLoopHeader());
109 loop_information_ = NULL;
113 void HBasicBlock::AddPhi(HPhi* phi) {
114 DCHECK(!IsStartBlock());
115 phis_.Add(phi, zone());
120 void HBasicBlock::RemovePhi(HPhi* phi) {
121 DCHECK(phi->block() == this);
122 DCHECK(phis_.Contains(phi));
124 phis_.RemoveElement(phi);
129 void HBasicBlock::AddInstruction(HInstruction* instr,
130 HSourcePosition position) {
131 DCHECK(!IsStartBlock() || !IsFinished());
132 DCHECK(!instr->IsLinked());
133 DCHECK(!IsFinished());
135 if (!position.IsUnknown()) {
136 instr->set_position(position);
138 if (first_ == NULL) {
139 DCHECK(last_environment() != NULL);
140 DCHECK(!last_environment()->ast_id().IsNone());
141 HBlockEntry* entry = new(zone()) HBlockEntry();
142 entry->InitializeAsFirst(this);
143 if (!position.IsUnknown()) {
144 entry->set_position(position);
146 DCHECK(!FLAG_hydrogen_track_positions ||
147 !graph()->info()->IsOptimizing());
149 first_ = last_ = entry;
151 instr->InsertAfter(last_);
155 HPhi* HBasicBlock::AddNewPhi(int merged_index) {
156 if (graph()->IsInsideNoSideEffectsScope()) {
157 merged_index = HPhi::kInvalidMergedIndex;
159 HPhi* phi = new(zone()) HPhi(merged_index, zone());
165 HSimulate* HBasicBlock::CreateSimulate(BailoutId ast_id,
166 RemovableSimulate removable) {
167 DCHECK(HasEnvironment());
168 HEnvironment* environment = last_environment();
169 DCHECK(ast_id.IsNone() ||
170 ast_id == BailoutId::StubEntry() ||
171 environment->closure()->shared()->VerifyBailoutId(ast_id));
173 int push_count = environment->push_count();
174 int pop_count = environment->pop_count();
177 new(zone()) HSimulate(ast_id, pop_count, zone(), removable);
179 instr->set_closure(environment->closure());
181 // Order of pushed values: newest (top of stack) first. This allows
182 // HSimulate::MergeWith() to easily append additional pushed values
183 // that are older (from further down the stack).
184 for (int i = 0; i < push_count; ++i) {
185 instr->AddPushedValue(environment->ExpressionStackAt(i));
187 for (GrowableBitVector::Iterator it(environment->assigned_variables(),
191 int index = it.Current();
192 instr->AddAssignedValue(index, environment->Lookup(index));
194 environment->ClearHistory();
199 void HBasicBlock::Finish(HControlInstruction* end, HSourcePosition position) {
200 DCHECK(!IsFinished());
201 AddInstruction(end, position);
203 for (HSuccessorIterator it(end); !it.Done(); it.Advance()) {
204 it.Current()->RegisterPredecessor(this);
209 void HBasicBlock::Goto(HBasicBlock* block,
210 HSourcePosition position,
211 FunctionState* state,
213 bool drop_extra = state != NULL &&
214 state->inlining_kind() == NORMAL_RETURN;
216 if (block->IsInlineReturnTarget()) {
217 HEnvironment* env = last_environment();
218 int argument_count = env->arguments_environment()->parameter_count();
219 AddInstruction(new(zone())
220 HLeaveInlined(state->entry(), argument_count),
222 UpdateEnvironment(last_environment()->DiscardInlined(drop_extra));
225 if (add_simulate) AddNewSimulate(BailoutId::None(), position);
226 HGoto* instr = new(zone()) HGoto(block);
227 Finish(instr, position);
231 void HBasicBlock::AddLeaveInlined(HValue* return_value,
232 FunctionState* state,
233 HSourcePosition position) {
234 HBasicBlock* target = state->function_return();
235 bool drop_extra = state->inlining_kind() == NORMAL_RETURN;
237 DCHECK(target->IsInlineReturnTarget());
238 DCHECK(return_value != NULL);
239 HEnvironment* env = last_environment();
240 int argument_count = env->arguments_environment()->parameter_count();
241 AddInstruction(new(zone()) HLeaveInlined(state->entry(), argument_count),
243 UpdateEnvironment(last_environment()->DiscardInlined(drop_extra));
244 last_environment()->Push(return_value);
245 AddNewSimulate(BailoutId::None(), position);
246 HGoto* instr = new(zone()) HGoto(target);
247 Finish(instr, position);
251 void HBasicBlock::SetInitialEnvironment(HEnvironment* env) {
252 DCHECK(!HasEnvironment());
253 DCHECK(first() == NULL);
254 UpdateEnvironment(env);
258 void HBasicBlock::UpdateEnvironment(HEnvironment* env) {
259 last_environment_ = env;
260 graph()->update_maximum_environment_size(env->first_expression_index());
264 void HBasicBlock::SetJoinId(BailoutId ast_id) {
265 int length = predecessors_.length();
267 for (int i = 0; i < length; i++) {
268 HBasicBlock* predecessor = predecessors_[i];
269 DCHECK(predecessor->end()->IsGoto());
270 HSimulate* simulate = HSimulate::cast(predecessor->end()->previous());
272 (predecessor->last_environment()->closure().is_null() ||
273 predecessor->last_environment()->closure()->shared()
274 ->VerifyBailoutId(ast_id)));
275 simulate->set_ast_id(ast_id);
276 predecessor->last_environment()->set_ast_id(ast_id);
281 bool HBasicBlock::Dominates(HBasicBlock* other) const {
282 HBasicBlock* current = other->dominator();
283 while (current != NULL) {
284 if (current == this) return true;
285 current = current->dominator();
291 bool HBasicBlock::EqualToOrDominates(HBasicBlock* other) const {
292 if (this == other) return true;
293 return Dominates(other);
297 int HBasicBlock::LoopNestingDepth() const {
298 const HBasicBlock* current = this;
299 int result = (current->IsLoopHeader()) ? 1 : 0;
300 while (current->parent_loop_header() != NULL) {
301 current = current->parent_loop_header();
308 void HBasicBlock::PostProcessLoopHeader(IterationStatement* stmt) {
309 DCHECK(IsLoopHeader());
311 SetJoinId(stmt->EntryId());
312 if (predecessors()->length() == 1) {
313 // This is a degenerated loop.
314 DetachLoopInformation();
318 // Only the first entry into the loop is from outside the loop. All other
319 // entries must be back edges.
320 for (int i = 1; i < predecessors()->length(); ++i) {
321 loop_information()->RegisterBackEdge(predecessors()->at(i));
326 void HBasicBlock::MarkSuccEdgeUnreachable(int succ) {
327 DCHECK(IsFinished());
328 HBasicBlock* succ_block = end()->SuccessorAt(succ);
330 DCHECK(succ_block->predecessors()->length() == 1);
331 succ_block->MarkUnreachable();
335 void HBasicBlock::RegisterPredecessor(HBasicBlock* pred) {
336 if (HasPredecessor()) {
337 // Only loop header blocks can have a predecessor added after
338 // instructions have been added to the block (they have phis for all
339 // values in the environment, these phis may be eliminated later).
340 DCHECK(IsLoopHeader() || first_ == NULL);
341 HEnvironment* incoming_env = pred->last_environment();
342 if (IsLoopHeader()) {
343 DCHECK(phis()->length() == incoming_env->length());
344 for (int i = 0; i < phis_.length(); ++i) {
345 phis_[i]->AddInput(incoming_env->values()->at(i));
348 last_environment()->AddIncomingEdge(this, pred->last_environment());
350 } else if (!HasEnvironment() && !IsFinished()) {
351 DCHECK(!IsLoopHeader());
352 SetInitialEnvironment(pred->last_environment()->Copy());
355 predecessors_.Add(pred, zone());
359 void HBasicBlock::AddDominatedBlock(HBasicBlock* block) {
360 DCHECK(!dominated_blocks_.Contains(block));
361 // Keep the list of dominated blocks sorted such that if there is two
362 // succeeding block in this list, the predecessor is before the successor.
364 while (index < dominated_blocks_.length() &&
365 dominated_blocks_[index]->block_id() < block->block_id()) {
368 dominated_blocks_.InsertAt(index, block, zone());
372 void HBasicBlock::AssignCommonDominator(HBasicBlock* other) {
373 if (dominator_ == NULL) {
375 other->AddDominatedBlock(this);
376 } else if (other->dominator() != NULL) {
377 HBasicBlock* first = dominator_;
378 HBasicBlock* second = other;
380 while (first != second) {
381 if (first->block_id() > second->block_id()) {
382 first = first->dominator();
384 second = second->dominator();
386 DCHECK(first != NULL && second != NULL);
389 if (dominator_ != first) {
390 DCHECK(dominator_->dominated_blocks_.Contains(this));
391 dominator_->dominated_blocks_.RemoveElement(this);
393 first->AddDominatedBlock(this);
399 void HBasicBlock::AssignLoopSuccessorDominators() {
400 // Mark blocks that dominate all subsequent reachable blocks inside their
401 // loop. Exploit the fact that blocks are sorted in reverse post order. When
402 // the loop is visited in increasing block id order, if the number of
403 // non-loop-exiting successor edges at the dominator_candidate block doesn't
404 // exceed the number of previously encountered predecessor edges, there is no
405 // path from the loop header to any block with higher id that doesn't go
406 // through the dominator_candidate block. In this case, the
407 // dominator_candidate block is guaranteed to dominate all blocks reachable
408 // from it with higher ids.
409 HBasicBlock* last = loop_information()->GetLastBackEdge();
410 int outstanding_successors = 1; // one edge from the pre-header
411 // Header always dominates everything.
412 MarkAsLoopSuccessorDominator();
413 for (int j = block_id(); j <= last->block_id(); ++j) {
414 HBasicBlock* dominator_candidate = graph_->blocks()->at(j);
415 for (HPredecessorIterator it(dominator_candidate); !it.Done();
417 HBasicBlock* predecessor = it.Current();
418 // Don't count back edges.
419 if (predecessor->block_id() < dominator_candidate->block_id()) {
420 outstanding_successors--;
424 // If more successors than predecessors have been seen in the loop up to
425 // now, it's not possible to guarantee that the current block dominates
426 // all of the blocks with higher IDs. In this case, assume conservatively
427 // that those paths through loop that don't go through the current block
428 // contain all of the loop's dependencies. Also be careful to record
429 // dominator information about the current loop that's being processed,
430 // and not nested loops, which will be processed when
431 // AssignLoopSuccessorDominators gets called on their header.
432 DCHECK(outstanding_successors >= 0);
433 HBasicBlock* parent_loop_header = dominator_candidate->parent_loop_header();
434 if (outstanding_successors == 0 &&
435 (parent_loop_header == this && !dominator_candidate->IsLoopHeader())) {
436 dominator_candidate->MarkAsLoopSuccessorDominator();
438 HControlInstruction* end = dominator_candidate->end();
439 for (HSuccessorIterator it(end); !it.Done(); it.Advance()) {
440 HBasicBlock* successor = it.Current();
441 // Only count successors that remain inside the loop and don't loop back
443 if (successor->block_id() > dominator_candidate->block_id() &&
444 successor->block_id() <= last->block_id()) {
445 // Backwards edges must land on loop headers.
446 DCHECK(successor->block_id() > dominator_candidate->block_id() ||
447 successor->IsLoopHeader());
448 outstanding_successors++;
455 int HBasicBlock::PredecessorIndexOf(HBasicBlock* predecessor) const {
456 for (int i = 0; i < predecessors_.length(); ++i) {
457 if (predecessors_[i] == predecessor) return i;
465 void HBasicBlock::Verify() {
466 // Check that every block is finished.
467 DCHECK(IsFinished());
468 DCHECK(block_id() >= 0);
470 // Check that the incoming edges are in edge split form.
471 if (predecessors_.length() > 1) {
472 for (int i = 0; i < predecessors_.length(); ++i) {
473 DCHECK(predecessors_[i]->end()->SecondSuccessor() == NULL);
480 void HLoopInformation::RegisterBackEdge(HBasicBlock* block) {
481 this->back_edges_.Add(block, block->zone());
486 HBasicBlock* HLoopInformation::GetLastBackEdge() const {
488 HBasicBlock* result = NULL;
489 for (int i = 0; i < back_edges_.length(); ++i) {
490 HBasicBlock* cur = back_edges_[i];
491 if (cur->block_id() > max_id) {
492 max_id = cur->block_id();
500 void HLoopInformation::AddBlock(HBasicBlock* block) {
501 if (block == loop_header()) return;
502 if (block->parent_loop_header() == loop_header()) return;
503 if (block->parent_loop_header() != NULL) {
504 AddBlock(block->parent_loop_header());
506 block->set_parent_loop_header(loop_header());
507 blocks_.Add(block, block->zone());
508 for (int i = 0; i < block->predecessors()->length(); ++i) {
509 AddBlock(block->predecessors()->at(i));
517 // Checks reachability of the blocks in this graph and stores a bit in
518 // the BitVector "reachable()" for every block that can be reached
519 // from the start block of the graph. If "dont_visit" is non-null, the given
520 // block is treated as if it would not be part of the graph. "visited_count()"
521 // returns the number of reachable blocks.
522 class ReachabilityAnalyzer BASE_EMBEDDED {
524 ReachabilityAnalyzer(HBasicBlock* entry_block,
526 HBasicBlock* dont_visit)
528 stack_(16, entry_block->zone()),
529 reachable_(block_count, entry_block->zone()),
530 dont_visit_(dont_visit) {
531 PushBlock(entry_block);
535 int visited_count() const { return visited_count_; }
536 const BitVector* reachable() const { return &reachable_; }
539 void PushBlock(HBasicBlock* block) {
540 if (block != NULL && block != dont_visit_ &&
541 !reachable_.Contains(block->block_id())) {
542 reachable_.Add(block->block_id());
543 stack_.Add(block, block->zone());
549 while (!stack_.is_empty()) {
550 HControlInstruction* end = stack_.RemoveLast()->end();
551 for (HSuccessorIterator it(end); !it.Done(); it.Advance()) {
552 PushBlock(it.Current());
558 ZoneList<HBasicBlock*> stack_;
559 BitVector reachable_;
560 HBasicBlock* dont_visit_;
564 void HGraph::Verify(bool do_full_verify) const {
565 Heap::RelocationLock relocation_lock(isolate()->heap());
566 AllowHandleDereference allow_deref;
567 AllowDeferredHandleDereference allow_deferred_deref;
568 for (int i = 0; i < blocks_.length(); i++) {
569 HBasicBlock* block = blocks_.at(i);
573 // Check that every block contains at least one node and that only the last
574 // node is a control instruction.
575 HInstruction* current = block->first();
576 DCHECK(current != NULL && current->IsBlockEntry());
577 while (current != NULL) {
578 DCHECK((current->next() == NULL) == current->IsControlInstruction());
579 DCHECK(current->block() == block);
581 current = current->next();
584 // Check that successors are correctly set.
585 HBasicBlock* first = block->end()->FirstSuccessor();
586 HBasicBlock* second = block->end()->SecondSuccessor();
587 DCHECK(second == NULL || first != NULL);
589 // Check that the predecessor array is correct.
591 DCHECK(first->predecessors()->Contains(block));
592 if (second != NULL) {
593 DCHECK(second->predecessors()->Contains(block));
597 // Check that phis have correct arguments.
598 for (int j = 0; j < block->phis()->length(); j++) {
599 HPhi* phi = block->phis()->at(j);
603 // Check that all join blocks have predecessors that end with an
604 // unconditional goto and agree on their environment node id.
605 if (block->predecessors()->length() >= 2) {
607 block->predecessors()->first()->last_environment()->ast_id();
608 for (int k = 0; k < block->predecessors()->length(); k++) {
609 HBasicBlock* predecessor = block->predecessors()->at(k);
610 DCHECK(predecessor->end()->IsGoto() ||
611 predecessor->end()->IsDeoptimize());
612 DCHECK(predecessor->last_environment()->ast_id() == id);
617 // Check special property of first block to have no predecessors.
618 DCHECK(blocks_.at(0)->predecessors()->is_empty());
620 if (do_full_verify) {
621 // Check that the graph is fully connected.
622 ReachabilityAnalyzer analyzer(entry_block_, blocks_.length(), NULL);
623 DCHECK(analyzer.visited_count() == blocks_.length());
625 // Check that entry block dominator is NULL.
626 DCHECK(entry_block_->dominator() == NULL);
629 for (int i = 0; i < blocks_.length(); ++i) {
630 HBasicBlock* block = blocks_.at(i);
631 if (block->dominator() == NULL) {
632 // Only start block may have no dominator assigned to.
635 // Assert that block is unreachable if dominator must not be visited.
636 ReachabilityAnalyzer dominator_analyzer(entry_block_,
639 DCHECK(!dominator_analyzer.reachable()->Contains(block->block_id()));
648 HConstant* HGraph::GetConstant(SetOncePointer<HConstant>* pointer,
650 if (!pointer->is_set()) {
651 // Can't pass GetInvalidContext() to HConstant::New, because that will
652 // recursively call GetConstant
653 HConstant* constant = HConstant::New(zone(), NULL, value);
654 constant->InsertAfter(entry_block()->first());
655 pointer->set(constant);
658 return ReinsertConstantIfNecessary(pointer->get());
662 HConstant* HGraph::ReinsertConstantIfNecessary(HConstant* constant) {
663 if (!constant->IsLinked()) {
664 // The constant was removed from the graph. Reinsert.
665 constant->ClearFlag(HValue::kIsDead);
666 constant->InsertAfter(entry_block()->first());
672 HConstant* HGraph::GetConstant0() {
673 return GetConstant(&constant_0_, 0);
677 HConstant* HGraph::GetConstant1() {
678 return GetConstant(&constant_1_, 1);
682 HConstant* HGraph::GetConstantMinus1() {
683 return GetConstant(&constant_minus1_, -1);
687 #define DEFINE_GET_CONSTANT(Name, name, type, htype, boolean_value) \
688 HConstant* HGraph::GetConstant##Name() { \
689 if (!constant_##name##_.is_set()) { \
690 HConstant* constant = new(zone()) HConstant( \
691 Unique<Object>::CreateImmovable(isolate()->factory()->name##_value()), \
692 Unique<Map>::CreateImmovable(isolate()->factory()->type##_map()), \
694 Representation::Tagged(), \
700 constant->InsertAfter(entry_block()->first()); \
701 constant_##name##_.set(constant); \
703 return ReinsertConstantIfNecessary(constant_##name##_.get()); \
707 DEFINE_GET_CONSTANT(Undefined, undefined, undefined, HType::Undefined(), false)
708 DEFINE_GET_CONSTANT(True, true, boolean, HType::Boolean(), true)
709 DEFINE_GET_CONSTANT(False, false, boolean, HType::Boolean(), false)
710 DEFINE_GET_CONSTANT(Hole, the_hole, the_hole, HType::None(), false)
711 DEFINE_GET_CONSTANT(Null, null, null, HType::Null(), false)
714 #undef DEFINE_GET_CONSTANT
716 #define DEFINE_IS_CONSTANT(Name, name) \
717 bool HGraph::IsConstant##Name(HConstant* constant) { \
718 return constant_##name##_.is_set() && constant == constant_##name##_.get(); \
720 DEFINE_IS_CONSTANT(Undefined, undefined)
721 DEFINE_IS_CONSTANT(0, 0)
722 DEFINE_IS_CONSTANT(1, 1)
723 DEFINE_IS_CONSTANT(Minus1, minus1)
724 DEFINE_IS_CONSTANT(True, true)
725 DEFINE_IS_CONSTANT(False, false)
726 DEFINE_IS_CONSTANT(Hole, the_hole)
727 DEFINE_IS_CONSTANT(Null, null)
729 #undef DEFINE_IS_CONSTANT
732 HConstant* HGraph::GetInvalidContext() {
733 return GetConstant(&constant_invalid_context_, 0xFFFFC0C7);
737 bool HGraph::IsStandardConstant(HConstant* constant) {
738 if (IsConstantUndefined(constant)) return true;
739 if (IsConstant0(constant)) return true;
740 if (IsConstant1(constant)) return true;
741 if (IsConstantMinus1(constant)) return true;
742 if (IsConstantTrue(constant)) return true;
743 if (IsConstantFalse(constant)) return true;
744 if (IsConstantHole(constant)) return true;
745 if (IsConstantNull(constant)) return true;
750 HGraphBuilder::IfBuilder::IfBuilder() : builder_(NULL), needs_compare_(true) {}
753 HGraphBuilder::IfBuilder::IfBuilder(HGraphBuilder* builder)
754 : needs_compare_(true) {
759 HGraphBuilder::IfBuilder::IfBuilder(HGraphBuilder* builder,
760 HIfContinuation* continuation)
761 : needs_compare_(false), first_true_block_(NULL), first_false_block_(NULL) {
762 InitializeDontCreateBlocks(builder);
763 continuation->Continue(&first_true_block_, &first_false_block_);
767 void HGraphBuilder::IfBuilder::InitializeDontCreateBlocks(
768 HGraphBuilder* builder) {
773 did_else_if_ = false;
777 pending_merge_block_ = false;
778 split_edge_merge_block_ = NULL;
779 merge_at_join_blocks_ = NULL;
780 normal_merge_at_join_block_count_ = 0;
781 deopt_merge_at_join_block_count_ = 0;
785 void HGraphBuilder::IfBuilder::Initialize(HGraphBuilder* builder) {
786 InitializeDontCreateBlocks(builder);
787 HEnvironment* env = builder->environment();
788 first_true_block_ = builder->CreateBasicBlock(env->Copy());
789 first_false_block_ = builder->CreateBasicBlock(env->Copy());
793 HControlInstruction* HGraphBuilder::IfBuilder::AddCompare(
794 HControlInstruction* compare) {
795 DCHECK(did_then_ == did_else_);
797 // Handle if-then-elseif
803 pending_merge_block_ = false;
804 split_edge_merge_block_ = NULL;
805 HEnvironment* env = builder()->environment();
806 first_true_block_ = builder()->CreateBasicBlock(env->Copy());
807 first_false_block_ = builder()->CreateBasicBlock(env->Copy());
809 if (split_edge_merge_block_ != NULL) {
810 HEnvironment* env = first_false_block_->last_environment();
811 HBasicBlock* split_edge = 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 DCHECK(!needs_compare_);
834 HEnvironment* env = first_false_block_->last_environment();
835 if (split_edge_merge_block_ == NULL) {
836 split_edge_merge_block_ = builder()->CreateBasicBlock(env->Copy());
837 builder()->GotoNoSimulate(first_true_block_, split_edge_merge_block_);
838 first_true_block_ = split_edge_merge_block_;
840 builder()->set_current_block(first_false_block_);
841 first_false_block_ = builder()->CreateBasicBlock(env->Copy());
845 void HGraphBuilder::IfBuilder::And() {
846 DCHECK(!needs_compare_);
849 HEnvironment* env = first_false_block_->last_environment();
850 if (split_edge_merge_block_ == NULL) {
851 split_edge_merge_block_ = builder()->CreateBasicBlock(env->Copy());
852 builder()->GotoNoSimulate(first_false_block_, split_edge_merge_block_);
853 first_false_block_ = split_edge_merge_block_;
855 builder()->set_current_block(first_true_block_);
856 first_true_block_ = builder()->CreateBasicBlock(env->Copy());
860 void HGraphBuilder::IfBuilder::CaptureContinuation(
861 HIfContinuation* continuation) {
862 DCHECK(!did_else_if_);
866 HBasicBlock* true_block = NULL;
867 HBasicBlock* false_block = NULL;
868 Finish(&true_block, &false_block);
869 DCHECK(true_block != NULL);
870 DCHECK(false_block != NULL);
871 continuation->Capture(true_block, false_block);
873 builder()->set_current_block(NULL);
878 void HGraphBuilder::IfBuilder::JoinContinuation(HIfContinuation* continuation) {
879 DCHECK(!did_else_if_);
882 HBasicBlock* true_block = NULL;
883 HBasicBlock* false_block = NULL;
884 Finish(&true_block, &false_block);
885 merge_at_join_blocks_ = NULL;
886 if (true_block != NULL && !true_block->IsFinished()) {
887 DCHECK(continuation->IsTrueReachable());
888 builder()->GotoNoSimulate(true_block, continuation->true_branch());
890 if (false_block != NULL && !false_block->IsFinished()) {
891 DCHECK(continuation->IsFalseReachable());
892 builder()->GotoNoSimulate(false_block, continuation->false_branch());
899 void HGraphBuilder::IfBuilder::Then() {
903 if (needs_compare_) {
904 // Handle if's without any expressions, they jump directly to the "else"
905 // branch. However, we must pretend that the "then" branch is reachable,
906 // so that the graph builder visits it and sees any live range extending
907 // constructs within it.
908 HConstant* constant_false = builder()->graph()->GetConstantFalse();
909 ToBooleanStub::Types boolean_type = ToBooleanStub::Types();
910 boolean_type.Add(ToBooleanStub::BOOLEAN);
911 HBranch* branch = builder()->New<HBranch>(
912 constant_false, boolean_type, first_true_block_, first_false_block_);
913 builder()->FinishCurrentBlock(branch);
915 builder()->set_current_block(first_true_block_);
916 pending_merge_block_ = true;
920 void HGraphBuilder::IfBuilder::Else() {
924 AddMergeAtJoinBlock(false);
925 builder()->set_current_block(first_false_block_);
926 pending_merge_block_ = true;
931 void HGraphBuilder::IfBuilder::Deopt(const char* reason) {
933 builder()->Add<HDeoptimize>(reason, Deoptimizer::EAGER);
934 AddMergeAtJoinBlock(true);
938 void HGraphBuilder::IfBuilder::Return(HValue* value) {
939 HValue* parameter_count = builder()->graph()->GetConstantMinus1();
940 builder()->FinishExitCurrentBlock(
941 builder()->New<HReturn>(value, parameter_count));
942 AddMergeAtJoinBlock(false);
946 void HGraphBuilder::IfBuilder::AddMergeAtJoinBlock(bool deopt) {
947 if (!pending_merge_block_) return;
948 HBasicBlock* block = builder()->current_block();
949 DCHECK(block == NULL || !block->IsFinished());
950 MergeAtJoinBlock* record = new (builder()->zone())
951 MergeAtJoinBlock(block, deopt, merge_at_join_blocks_);
952 merge_at_join_blocks_ = record;
954 DCHECK(block->end() == NULL);
956 normal_merge_at_join_block_count_++;
958 deopt_merge_at_join_block_count_++;
961 builder()->set_current_block(NULL);
962 pending_merge_block_ = false;
966 void HGraphBuilder::IfBuilder::Finish() {
971 AddMergeAtJoinBlock(false);
974 AddMergeAtJoinBlock(false);
980 void HGraphBuilder::IfBuilder::Finish(HBasicBlock** then_continuation,
981 HBasicBlock** else_continuation) {
984 MergeAtJoinBlock* else_record = merge_at_join_blocks_;
985 if (else_continuation != NULL) {
986 *else_continuation = else_record->block_;
988 MergeAtJoinBlock* then_record = else_record->next_;
989 if (then_continuation != NULL) {
990 *then_continuation = then_record->block_;
992 DCHECK(then_record->next_ == NULL);
996 void HGraphBuilder::IfBuilder::End() {
997 if (captured_) return;
1000 int total_merged_blocks = normal_merge_at_join_block_count_ +
1001 deopt_merge_at_join_block_count_;
1002 DCHECK(total_merged_blocks >= 1);
1003 HBasicBlock* merge_block =
1004 total_merged_blocks == 1 ? NULL : builder()->graph()->CreateBasicBlock();
1006 // Merge non-deopt blocks first to ensure environment has right size for
1008 MergeAtJoinBlock* current = merge_at_join_blocks_;
1009 while (current != NULL) {
1010 if (!current->deopt_ && current->block_ != NULL) {
1011 // If there is only one block that makes it through to the end of the
1012 // if, then just set it as the current block and continue rather then
1013 // creating an unnecessary merge block.
1014 if (total_merged_blocks == 1) {
1015 builder()->set_current_block(current->block_);
1018 builder()->GotoNoSimulate(current->block_, merge_block);
1020 current = current->next_;
1023 // Merge deopt blocks, padding when necessary.
1024 current = merge_at_join_blocks_;
1025 while (current != NULL) {
1026 if (current->deopt_ && current->block_ != NULL) {
1027 current->block_->FinishExit(HAbnormalExit::New(builder()->zone(), NULL),
1028 HSourcePosition::Unknown());
1030 current = current->next_;
1032 builder()->set_current_block(merge_block);
1036 HGraphBuilder::LoopBuilder::LoopBuilder(HGraphBuilder* builder) {
1037 Initialize(builder, NULL, kWhileTrue, NULL);
1041 HGraphBuilder::LoopBuilder::LoopBuilder(HGraphBuilder* builder, HValue* context,
1042 LoopBuilder::Direction direction) {
1043 Initialize(builder, context, direction, builder->graph()->GetConstant1());
1047 HGraphBuilder::LoopBuilder::LoopBuilder(HGraphBuilder* builder, HValue* context,
1048 LoopBuilder::Direction direction,
1049 HValue* increment_amount) {
1050 Initialize(builder, context, direction, increment_amount);
1051 increment_amount_ = increment_amount;
1055 void HGraphBuilder::LoopBuilder::Initialize(HGraphBuilder* builder,
1057 Direction direction,
1058 HValue* increment_amount) {
1061 direction_ = direction;
1062 increment_amount_ = increment_amount;
1065 header_block_ = builder->CreateLoopHeaderBlock();
1068 exit_trampoline_block_ = NULL;
1072 HValue* HGraphBuilder::LoopBuilder::BeginBody(
1074 HValue* terminating,
1075 Token::Value token) {
1076 DCHECK(direction_ != kWhileTrue);
1077 HEnvironment* env = builder_->environment();
1078 phi_ = header_block_->AddNewPhi(env->values()->length());
1079 phi_->AddInput(initial);
1081 builder_->GotoNoSimulate(header_block_);
1083 HEnvironment* body_env = env->Copy();
1084 HEnvironment* exit_env = env->Copy();
1085 // Remove the phi from the expression stack
1088 body_block_ = builder_->CreateBasicBlock(body_env);
1089 exit_block_ = builder_->CreateBasicBlock(exit_env);
1091 builder_->set_current_block(header_block_);
1093 builder_->FinishCurrentBlock(builder_->New<HCompareNumericAndBranch>(
1094 phi_, terminating, token, body_block_, exit_block_));
1096 builder_->set_current_block(body_block_);
1097 if (direction_ == kPreIncrement || direction_ == kPreDecrement) {
1098 HValue* one = builder_->graph()->GetConstant1();
1099 if (direction_ == kPreIncrement) {
1100 increment_ = HAdd::New(zone(), context_, phi_, one);
1102 increment_ = HSub::New(zone(), context_, phi_, one);
1104 increment_->ClearFlag(HValue::kCanOverflow);
1105 builder_->AddInstruction(increment_);
1113 void HGraphBuilder::LoopBuilder::BeginBody(int drop_count) {
1114 DCHECK(direction_ == kWhileTrue);
1115 HEnvironment* env = builder_->environment();
1116 builder_->GotoNoSimulate(header_block_);
1117 builder_->set_current_block(header_block_);
1118 env->Drop(drop_count);
1122 void HGraphBuilder::LoopBuilder::Break() {
1123 if (exit_trampoline_block_ == NULL) {
1124 // Its the first time we saw a break.
1125 if (direction_ == kWhileTrue) {
1126 HEnvironment* env = builder_->environment()->Copy();
1127 exit_trampoline_block_ = builder_->CreateBasicBlock(env);
1129 HEnvironment* env = exit_block_->last_environment()->Copy();
1130 exit_trampoline_block_ = builder_->CreateBasicBlock(env);
1131 builder_->GotoNoSimulate(exit_block_, exit_trampoline_block_);
1135 builder_->GotoNoSimulate(exit_trampoline_block_);
1136 builder_->set_current_block(NULL);
1140 void HGraphBuilder::LoopBuilder::EndBody() {
1143 if (direction_ == kPostIncrement || direction_ == kPostDecrement) {
1144 if (direction_ == kPostIncrement) {
1145 increment_ = HAdd::New(zone(), context_, phi_, increment_amount_);
1147 increment_ = HSub::New(zone(), context_, phi_, increment_amount_);
1149 increment_->ClearFlag(HValue::kCanOverflow);
1150 builder_->AddInstruction(increment_);
1153 if (direction_ != kWhileTrue) {
1154 // Push the new increment value on the expression stack to merge into
1156 builder_->environment()->Push(increment_);
1158 HBasicBlock* last_block = builder_->current_block();
1159 builder_->GotoNoSimulate(last_block, header_block_);
1160 header_block_->loop_information()->RegisterBackEdge(last_block);
1162 if (exit_trampoline_block_ != NULL) {
1163 builder_->set_current_block(exit_trampoline_block_);
1165 builder_->set_current_block(exit_block_);
1171 HGraph* HGraphBuilder::CreateGraph() {
1172 graph_ = new(zone()) HGraph(info_);
1173 if (FLAG_hydrogen_stats) isolate()->GetHStatistics()->Initialize(info_);
1174 CompilationPhase phase("H_Block building", info_);
1175 set_current_block(graph()->entry_block());
1176 if (!BuildGraph()) return NULL;
1177 graph()->FinalizeUniqueness();
1182 HInstruction* HGraphBuilder::AddInstruction(HInstruction* instr) {
1183 DCHECK(current_block() != NULL);
1184 DCHECK(!FLAG_hydrogen_track_positions ||
1185 !position_.IsUnknown() ||
1186 !info_->IsOptimizing());
1187 current_block()->AddInstruction(instr, source_position());
1188 if (graph()->IsInsideNoSideEffectsScope()) {
1189 instr->SetFlag(HValue::kHasNoObservableSideEffects);
1195 void HGraphBuilder::FinishCurrentBlock(HControlInstruction* last) {
1196 DCHECK(!FLAG_hydrogen_track_positions ||
1197 !info_->IsOptimizing() ||
1198 !position_.IsUnknown());
1199 current_block()->Finish(last, source_position());
1200 if (last->IsReturn() || last->IsAbnormalExit()) {
1201 set_current_block(NULL);
1206 void HGraphBuilder::FinishExitCurrentBlock(HControlInstruction* instruction) {
1207 DCHECK(!FLAG_hydrogen_track_positions || !info_->IsOptimizing() ||
1208 !position_.IsUnknown());
1209 current_block()->FinishExit(instruction, source_position());
1210 if (instruction->IsReturn() || instruction->IsAbnormalExit()) {
1211 set_current_block(NULL);
1216 void HGraphBuilder::AddIncrementCounter(StatsCounter* counter) {
1217 if (FLAG_native_code_counters && counter->Enabled()) {
1218 HValue* reference = Add<HConstant>(ExternalReference(counter));
1219 HValue* old_value = Add<HLoadNamedField>(
1220 reference, static_cast<HValue*>(NULL), HObjectAccess::ForCounter());
1221 HValue* new_value = AddUncasted<HAdd>(old_value, graph()->GetConstant1());
1222 new_value->ClearFlag(HValue::kCanOverflow); // Ignore counter overflow
1223 Add<HStoreNamedField>(reference, HObjectAccess::ForCounter(),
1224 new_value, STORE_TO_INITIALIZED_ENTRY);
1229 void HGraphBuilder::AddSimulate(BailoutId id,
1230 RemovableSimulate removable) {
1231 DCHECK(current_block() != NULL);
1232 DCHECK(!graph()->IsInsideNoSideEffectsScope());
1233 current_block()->AddNewSimulate(id, source_position(), removable);
1237 HBasicBlock* HGraphBuilder::CreateBasicBlock(HEnvironment* env) {
1238 HBasicBlock* b = graph()->CreateBasicBlock();
1239 b->SetInitialEnvironment(env);
1244 HBasicBlock* HGraphBuilder::CreateLoopHeaderBlock() {
1245 HBasicBlock* header = graph()->CreateBasicBlock();
1246 HEnvironment* entry_env = environment()->CopyAsLoopHeader(header);
1247 header->SetInitialEnvironment(entry_env);
1248 header->AttachLoopInformation();
1253 HValue* HGraphBuilder::BuildGetElementsKind(HValue* object) {
1254 HValue* map = Add<HLoadNamedField>(object, static_cast<HValue*>(NULL),
1255 HObjectAccess::ForMap());
1257 HValue* bit_field2 = Add<HLoadNamedField>(map, static_cast<HValue*>(NULL),
1258 HObjectAccess::ForMapBitField2());
1259 return BuildDecodeField<Map::ElementsKindBits>(bit_field2);
1263 HValue* HGraphBuilder::BuildCheckHeapObject(HValue* obj) {
1264 if (obj->type().IsHeapObject()) return obj;
1265 return Add<HCheckHeapObject>(obj);
1269 void HGraphBuilder::FinishExitWithHardDeoptimization(const char* reason) {
1270 Add<HDeoptimize>(reason, Deoptimizer::EAGER);
1271 FinishExitCurrentBlock(New<HAbnormalExit>());
1275 HValue* HGraphBuilder::BuildCheckString(HValue* string) {
1276 if (!string->type().IsString()) {
1277 DCHECK(!string->IsConstant() ||
1278 !HConstant::cast(string)->HasStringValue());
1279 BuildCheckHeapObject(string);
1280 return Add<HCheckInstanceType>(string, HCheckInstanceType::IS_STRING);
1286 HValue* HGraphBuilder::BuildWrapReceiver(HValue* object, HValue* function) {
1287 if (object->type().IsJSObject()) return object;
1288 if (function->IsConstant() &&
1289 HConstant::cast(function)->handle(isolate())->IsJSFunction()) {
1290 Handle<JSFunction> f = Handle<JSFunction>::cast(
1291 HConstant::cast(function)->handle(isolate()));
1292 SharedFunctionInfo* shared = f->shared();
1293 if (shared->strict_mode() == STRICT || shared->native()) return object;
1295 return Add<HWrapReceiver>(object, function);
1299 HValue* HGraphBuilder::BuildCheckForCapacityGrow(
1306 PropertyAccessType access_type) {
1307 IfBuilder length_checker(this);
1309 Token::Value token = IsHoleyElementsKind(kind) ? Token::GTE : Token::EQ;
1310 length_checker.If<HCompareNumericAndBranch>(key, length, token);
1312 length_checker.Then();
1314 HValue* current_capacity = AddLoadFixedArrayLength(elements);
1316 IfBuilder capacity_checker(this);
1318 capacity_checker.If<HCompareNumericAndBranch>(key, current_capacity,
1320 capacity_checker.Then();
1322 HValue* max_gap = Add<HConstant>(static_cast<int32_t>(JSObject::kMaxGap));
1323 HValue* max_capacity = AddUncasted<HAdd>(current_capacity, max_gap);
1325 Add<HBoundsCheck>(key, max_capacity);
1327 HValue* new_capacity = BuildNewElementsCapacity(key);
1328 HValue* new_elements = BuildGrowElementsCapacity(object, elements,
1332 environment()->Push(new_elements);
1333 capacity_checker.Else();
1335 environment()->Push(elements);
1336 capacity_checker.End();
1339 HValue* new_length = AddUncasted<HAdd>(key, graph_->GetConstant1());
1340 new_length->ClearFlag(HValue::kCanOverflow);
1342 Add<HStoreNamedField>(object, HObjectAccess::ForArrayLength(kind),
1346 if (access_type == STORE && kind == FAST_SMI_ELEMENTS) {
1347 HValue* checked_elements = environment()->Top();
1349 // Write zero to ensure that the new element is initialized with some smi.
1350 Add<HStoreKeyed>(checked_elements, key, graph()->GetConstant0(), kind);
1353 length_checker.Else();
1354 Add<HBoundsCheck>(key, length);
1356 environment()->Push(elements);
1357 length_checker.End();
1359 return environment()->Pop();
1363 HValue* HGraphBuilder::BuildCopyElementsOnWrite(HValue* object,
1367 Factory* factory = isolate()->factory();
1369 IfBuilder cow_checker(this);
1371 cow_checker.If<HCompareMap>(elements, factory->fixed_cow_array_map());
1374 HValue* capacity = AddLoadFixedArrayLength(elements);
1376 HValue* new_elements = BuildGrowElementsCapacity(object, elements, kind,
1377 kind, length, capacity);
1379 environment()->Push(new_elements);
1383 environment()->Push(elements);
1387 return environment()->Pop();
1391 void HGraphBuilder::BuildTransitionElementsKind(HValue* object,
1393 ElementsKind from_kind,
1394 ElementsKind to_kind,
1396 DCHECK(!IsFastHoleyElementsKind(from_kind) ||
1397 IsFastHoleyElementsKind(to_kind));
1399 if (AllocationSite::GetMode(from_kind, to_kind) == TRACK_ALLOCATION_SITE) {
1400 Add<HTrapAllocationMemento>(object);
1403 if (!IsSimpleMapChangeTransition(from_kind, to_kind)) {
1404 HInstruction* elements = AddLoadElements(object);
1406 HInstruction* empty_fixed_array = Add<HConstant>(
1407 isolate()->factory()->empty_fixed_array());
1409 IfBuilder if_builder(this);
1411 if_builder.IfNot<HCompareObjectEqAndBranch>(elements, empty_fixed_array);
1415 HInstruction* elements_length = AddLoadFixedArrayLength(elements);
1417 HInstruction* array_length = is_jsarray
1418 ? Add<HLoadNamedField>(object, static_cast<HValue*>(NULL),
1419 HObjectAccess::ForArrayLength(from_kind))
1422 BuildGrowElementsCapacity(object, elements, from_kind, to_kind,
1423 array_length, elements_length);
1428 Add<HStoreNamedField>(object, HObjectAccess::ForMap(), map);
1432 void HGraphBuilder::BuildJSObjectCheck(HValue* receiver,
1433 int bit_field_mask) {
1434 // Check that the object isn't a smi.
1435 Add<HCheckHeapObject>(receiver);
1437 // Get the map of the receiver.
1438 HValue* map = Add<HLoadNamedField>(receiver, static_cast<HValue*>(NULL),
1439 HObjectAccess::ForMap());
1441 // Check the instance type and if an access check is needed, this can be
1442 // done with a single load, since both bytes are adjacent in the map.
1443 HObjectAccess access(HObjectAccess::ForMapInstanceTypeAndBitField());
1444 HValue* instance_type_and_bit_field =
1445 Add<HLoadNamedField>(map, static_cast<HValue*>(NULL), access);
1447 HValue* mask = Add<HConstant>(0x00FF | (bit_field_mask << 8));
1448 HValue* and_result = AddUncasted<HBitwise>(Token::BIT_AND,
1449 instance_type_and_bit_field,
1451 HValue* sub_result = AddUncasted<HSub>(and_result,
1452 Add<HConstant>(JS_OBJECT_TYPE));
1453 Add<HBoundsCheck>(sub_result,
1454 Add<HConstant>(LAST_JS_OBJECT_TYPE + 1 - JS_OBJECT_TYPE));
1458 void HGraphBuilder::BuildKeyedIndexCheck(HValue* key,
1459 HIfContinuation* join_continuation) {
1460 // The sometimes unintuitively backward ordering of the ifs below is
1461 // convoluted, but necessary. All of the paths must guarantee that the
1462 // if-true of the continuation returns a smi element index and the if-false of
1463 // the continuation returns either a symbol or a unique string key. All other
1464 // object types cause a deopt to fall back to the runtime.
1466 IfBuilder key_smi_if(this);
1467 key_smi_if.If<HIsSmiAndBranch>(key);
1470 Push(key); // Nothing to do, just continue to true of continuation.
1474 HValue* map = Add<HLoadNamedField>(key, static_cast<HValue*>(NULL),
1475 HObjectAccess::ForMap());
1476 HValue* instance_type =
1477 Add<HLoadNamedField>(map, static_cast<HValue*>(NULL),
1478 HObjectAccess::ForMapInstanceType());
1480 // Non-unique string, check for a string with a hash code that is actually
1482 STATIC_ASSERT(LAST_UNIQUE_NAME_TYPE == FIRST_NONSTRING_TYPE);
1483 IfBuilder not_string_or_name_if(this);
1484 not_string_or_name_if.If<HCompareNumericAndBranch>(
1486 Add<HConstant>(LAST_UNIQUE_NAME_TYPE),
1489 not_string_or_name_if.Then();
1491 // Non-smi, non-Name, non-String: Try to convert to smi in case of
1493 // TODO(danno): This could call some variant of ToString
1494 Push(AddUncasted<HForceRepresentation>(key, Representation::Smi()));
1496 not_string_or_name_if.Else();
1498 // String or Name: check explicitly for Name, they can short-circuit
1499 // directly to unique non-index key path.
1500 IfBuilder not_symbol_if(this);
1501 not_symbol_if.If<HCompareNumericAndBranch>(
1503 Add<HConstant>(SYMBOL_TYPE),
1506 not_symbol_if.Then();
1508 // String: check whether the String is a String of an index. If it is,
1509 // extract the index value from the hash.
1511 Add<HLoadNamedField>(key, static_cast<HValue*>(NULL),
1512 HObjectAccess::ForNameHashField());
1513 HValue* not_index_mask = Add<HConstant>(static_cast<int>(
1514 String::kContainsCachedArrayIndexMask));
1516 HValue* not_index_test = AddUncasted<HBitwise>(
1517 Token::BIT_AND, hash, not_index_mask);
1519 IfBuilder string_index_if(this);
1520 string_index_if.If<HCompareNumericAndBranch>(not_index_test,
1521 graph()->GetConstant0(),
1523 string_index_if.Then();
1525 // String with index in hash: extract string and merge to index path.
1526 Push(BuildDecodeField<String::ArrayIndexValueBits>(hash));
1528 string_index_if.Else();
1530 // Key is a non-index String, check for uniqueness/internalization.
1531 // If it's not internalized yet, internalize it now.
1532 HValue* not_internalized_bit = AddUncasted<HBitwise>(
1535 Add<HConstant>(static_cast<int>(kIsNotInternalizedMask)));
1537 IfBuilder internalized(this);
1538 internalized.If<HCompareNumericAndBranch>(not_internalized_bit,
1539 graph()->GetConstant0(),
1541 internalized.Then();
1544 internalized.Else();
1545 Add<HPushArguments>(key);
1546 HValue* intern_key = Add<HCallRuntime>(
1547 isolate()->factory()->empty_string(),
1548 Runtime::FunctionForId(Runtime::kInternalizeString), 1);
1552 // Key guaranteed to be a unique string
1554 string_index_if.JoinContinuation(join_continuation);
1556 not_symbol_if.Else();
1558 Push(key); // Key is symbol
1560 not_symbol_if.JoinContinuation(join_continuation);
1562 not_string_or_name_if.JoinContinuation(join_continuation);
1564 key_smi_if.JoinContinuation(join_continuation);
1568 void HGraphBuilder::BuildNonGlobalObjectCheck(HValue* receiver) {
1569 // Get the the instance type of the receiver, and make sure that it is
1570 // not one of the global object types.
1571 HValue* map = Add<HLoadNamedField>(receiver, static_cast<HValue*>(NULL),
1572 HObjectAccess::ForMap());
1573 HValue* instance_type =
1574 Add<HLoadNamedField>(map, static_cast<HValue*>(NULL),
1575 HObjectAccess::ForMapInstanceType());
1576 STATIC_ASSERT(JS_BUILTINS_OBJECT_TYPE == JS_GLOBAL_OBJECT_TYPE + 1);
1577 HValue* min_global_type = Add<HConstant>(JS_GLOBAL_OBJECT_TYPE);
1578 HValue* max_global_type = Add<HConstant>(JS_BUILTINS_OBJECT_TYPE);
1580 IfBuilder if_global_object(this);
1581 if_global_object.If<HCompareNumericAndBranch>(instance_type,
1584 if_global_object.And();
1585 if_global_object.If<HCompareNumericAndBranch>(instance_type,
1588 if_global_object.ThenDeopt("receiver was a global object");
1589 if_global_object.End();
1593 void HGraphBuilder::BuildTestForDictionaryProperties(
1595 HIfContinuation* continuation) {
1596 HValue* properties = Add<HLoadNamedField>(
1597 object, static_cast<HValue*>(NULL),
1598 HObjectAccess::ForPropertiesPointer());
1599 HValue* properties_map =
1600 Add<HLoadNamedField>(properties, static_cast<HValue*>(NULL),
1601 HObjectAccess::ForMap());
1602 HValue* hash_map = Add<HLoadRoot>(Heap::kHashTableMapRootIndex);
1603 IfBuilder builder(this);
1604 builder.If<HCompareObjectEqAndBranch>(properties_map, hash_map);
1605 builder.CaptureContinuation(continuation);
1609 HValue* HGraphBuilder::BuildKeyedLookupCacheHash(HValue* object,
1611 // Load the map of the receiver, compute the keyed lookup cache hash
1612 // based on 32 bits of the map pointer and the string hash.
1613 HValue* object_map =
1614 Add<HLoadNamedField>(object, static_cast<HValue*>(NULL),
1615 HObjectAccess::ForMapAsInteger32());
1616 HValue* shifted_map = AddUncasted<HShr>(
1617 object_map, Add<HConstant>(KeyedLookupCache::kMapHashShift));
1618 HValue* string_hash =
1619 Add<HLoadNamedField>(key, static_cast<HValue*>(NULL),
1620 HObjectAccess::ForStringHashField());
1621 HValue* shifted_hash = AddUncasted<HShr>(
1622 string_hash, Add<HConstant>(String::kHashShift));
1623 HValue* xor_result = AddUncasted<HBitwise>(Token::BIT_XOR, shifted_map,
1625 int mask = (KeyedLookupCache::kCapacityMask & KeyedLookupCache::kHashMask);
1626 return AddUncasted<HBitwise>(Token::BIT_AND, xor_result,
1627 Add<HConstant>(mask));
1631 HValue* HGraphBuilder::BuildElementIndexHash(HValue* index) {
1632 int32_t seed_value = static_cast<uint32_t>(isolate()->heap()->HashSeed());
1633 HValue* seed = Add<HConstant>(seed_value);
1634 HValue* hash = AddUncasted<HBitwise>(Token::BIT_XOR, index, seed);
1636 // hash = ~hash + (hash << 15);
1637 HValue* shifted_hash = AddUncasted<HShl>(hash, Add<HConstant>(15));
1638 HValue* not_hash = AddUncasted<HBitwise>(Token::BIT_XOR, hash,
1639 graph()->GetConstantMinus1());
1640 hash = AddUncasted<HAdd>(shifted_hash, not_hash);
1642 // hash = hash ^ (hash >> 12);
1643 shifted_hash = AddUncasted<HShr>(hash, Add<HConstant>(12));
1644 hash = AddUncasted<HBitwise>(Token::BIT_XOR, hash, shifted_hash);
1646 // hash = hash + (hash << 2);
1647 shifted_hash = AddUncasted<HShl>(hash, Add<HConstant>(2));
1648 hash = AddUncasted<HAdd>(hash, shifted_hash);
1650 // hash = hash ^ (hash >> 4);
1651 shifted_hash = AddUncasted<HShr>(hash, Add<HConstant>(4));
1652 hash = AddUncasted<HBitwise>(Token::BIT_XOR, hash, shifted_hash);
1654 // hash = hash * 2057;
1655 hash = AddUncasted<HMul>(hash, Add<HConstant>(2057));
1656 hash->ClearFlag(HValue::kCanOverflow);
1658 // hash = hash ^ (hash >> 16);
1659 shifted_hash = AddUncasted<HShr>(hash, Add<HConstant>(16));
1660 return AddUncasted<HBitwise>(Token::BIT_XOR, hash, shifted_hash);
1664 HValue* HGraphBuilder::BuildUncheckedDictionaryElementLoad(HValue* receiver,
1668 HValue* capacity = Add<HLoadKeyed>(
1670 Add<HConstant>(NameDictionary::kCapacityIndex),
1671 static_cast<HValue*>(NULL),
1674 HValue* mask = AddUncasted<HSub>(capacity, graph()->GetConstant1());
1675 mask->ChangeRepresentation(Representation::Integer32());
1676 mask->ClearFlag(HValue::kCanOverflow);
1678 HValue* entry = hash;
1679 HValue* count = graph()->GetConstant1();
1683 HIfContinuation return_or_loop_continuation(graph()->CreateBasicBlock(),
1684 graph()->CreateBasicBlock());
1685 HIfContinuation found_key_match_continuation(graph()->CreateBasicBlock(),
1686 graph()->CreateBasicBlock());
1687 LoopBuilder probe_loop(this);
1688 probe_loop.BeginBody(2); // Drop entry, count from last environment to
1689 // appease live range building without simulates.
1693 entry = AddUncasted<HBitwise>(Token::BIT_AND, entry, mask);
1694 int entry_size = SeededNumberDictionary::kEntrySize;
1695 HValue* base_index = AddUncasted<HMul>(entry, Add<HConstant>(entry_size));
1696 base_index->ClearFlag(HValue::kCanOverflow);
1697 int start_offset = SeededNumberDictionary::kElementsStartIndex;
1699 AddUncasted<HAdd>(base_index, Add<HConstant>(start_offset));
1700 key_index->ClearFlag(HValue::kCanOverflow);
1702 HValue* candidate_key = Add<HLoadKeyed>(
1703 elements, key_index, static_cast<HValue*>(NULL), FAST_ELEMENTS);
1704 IfBuilder if_undefined(this);
1705 if_undefined.If<HCompareObjectEqAndBranch>(candidate_key,
1706 graph()->GetConstantUndefined());
1707 if_undefined.Then();
1709 // element == undefined means "not found". Call the runtime.
1710 // TODO(jkummerow): walk the prototype chain instead.
1711 Add<HPushArguments>(receiver, key);
1712 Push(Add<HCallRuntime>(isolate()->factory()->empty_string(),
1713 Runtime::FunctionForId(Runtime::kKeyedGetProperty),
1716 if_undefined.Else();
1718 IfBuilder if_match(this);
1719 if_match.If<HCompareObjectEqAndBranch>(candidate_key, key);
1723 // Update non-internalized string in the dictionary with internalized key?
1724 IfBuilder if_update_with_internalized(this);
1726 if_update_with_internalized.IfNot<HIsSmiAndBranch>(candidate_key);
1727 if_update_with_internalized.And();
1728 HValue* map = AddLoadMap(candidate_key, smi_check);
1729 HValue* instance_type = Add<HLoadNamedField>(
1730 map, static_cast<HValue*>(NULL), HObjectAccess::ForMapInstanceType());
1731 HValue* not_internalized_bit = AddUncasted<HBitwise>(
1732 Token::BIT_AND, instance_type,
1733 Add<HConstant>(static_cast<int>(kIsNotInternalizedMask)));
1734 if_update_with_internalized.If<HCompareNumericAndBranch>(
1735 not_internalized_bit, graph()->GetConstant0(), Token::NE);
1736 if_update_with_internalized.And();
1737 if_update_with_internalized.IfNot<HCompareObjectEqAndBranch>(
1738 candidate_key, graph()->GetConstantHole());
1739 if_update_with_internalized.AndIf<HStringCompareAndBranch>(candidate_key,
1741 if_update_with_internalized.Then();
1742 // Replace a key that is a non-internalized string by the equivalent
1743 // internalized string for faster further lookups.
1744 Add<HStoreKeyed>(elements, key_index, key, FAST_ELEMENTS);
1745 if_update_with_internalized.Else();
1747 if_update_with_internalized.JoinContinuation(&found_key_match_continuation);
1748 if_match.JoinContinuation(&found_key_match_continuation);
1750 IfBuilder found_key_match(this, &found_key_match_continuation);
1751 found_key_match.Then();
1752 // Key at current probe matches. Relevant bits in the |details| field must
1753 // be zero, otherwise the dictionary element requires special handling.
1754 HValue* details_index =
1755 AddUncasted<HAdd>(base_index, Add<HConstant>(start_offset + 2));
1756 details_index->ClearFlag(HValue::kCanOverflow);
1757 HValue* details = Add<HLoadKeyed>(
1758 elements, details_index, static_cast<HValue*>(NULL), FAST_ELEMENTS);
1759 int details_mask = PropertyDetails::TypeField::kMask |
1760 PropertyDetails::DeletedField::kMask;
1761 details = AddUncasted<HBitwise>(Token::BIT_AND, details,
1762 Add<HConstant>(details_mask));
1763 IfBuilder details_compare(this);
1764 details_compare.If<HCompareNumericAndBranch>(
1765 details, graph()->GetConstant0(), Token::EQ);
1766 details_compare.Then();
1767 HValue* result_index =
1768 AddUncasted<HAdd>(base_index, Add<HConstant>(start_offset + 1));
1769 result_index->ClearFlag(HValue::kCanOverflow);
1770 Push(Add<HLoadKeyed>(elements, result_index, static_cast<HValue*>(NULL),
1772 details_compare.Else();
1773 Add<HPushArguments>(receiver, key);
1774 Push(Add<HCallRuntime>(isolate()->factory()->empty_string(),
1775 Runtime::FunctionForId(Runtime::kKeyedGetProperty),
1777 details_compare.End();
1779 found_key_match.Else();
1780 found_key_match.JoinContinuation(&return_or_loop_continuation);
1782 if_undefined.JoinContinuation(&return_or_loop_continuation);
1784 IfBuilder return_or_loop(this, &return_or_loop_continuation);
1785 return_or_loop.Then();
1788 return_or_loop.Else();
1789 entry = AddUncasted<HAdd>(entry, count);
1790 entry->ClearFlag(HValue::kCanOverflow);
1791 count = AddUncasted<HAdd>(count, graph()->GetConstant1());
1792 count->ClearFlag(HValue::kCanOverflow);
1796 probe_loop.EndBody();
1798 return_or_loop.End();
1804 HValue* HGraphBuilder::BuildRegExpConstructResult(HValue* length,
1807 NoObservableSideEffectsScope scope(this);
1808 HConstant* max_length = Add<HConstant>(JSObject::kInitialMaxFastElementArray);
1809 Add<HBoundsCheck>(length, max_length);
1811 // Generate size calculation code here in order to make it dominate
1812 // the JSRegExpResult allocation.
1813 ElementsKind elements_kind = FAST_ELEMENTS;
1814 HValue* size = BuildCalculateElementsSize(elements_kind, length);
1816 // Allocate the JSRegExpResult and the FixedArray in one step.
1817 HValue* result = Add<HAllocate>(
1818 Add<HConstant>(JSRegExpResult::kSize), HType::JSArray(),
1819 NOT_TENURED, JS_ARRAY_TYPE);
1821 // Initialize the JSRegExpResult header.
1822 HValue* global_object = Add<HLoadNamedField>(
1823 context(), static_cast<HValue*>(NULL),
1824 HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
1825 HValue* native_context = Add<HLoadNamedField>(
1826 global_object, static_cast<HValue*>(NULL),
1827 HObjectAccess::ForGlobalObjectNativeContext());
1828 Add<HStoreNamedField>(
1829 result, HObjectAccess::ForMap(),
1830 Add<HLoadNamedField>(
1831 native_context, static_cast<HValue*>(NULL),
1832 HObjectAccess::ForContextSlot(Context::REGEXP_RESULT_MAP_INDEX)));
1833 HConstant* empty_fixed_array =
1834 Add<HConstant>(isolate()->factory()->empty_fixed_array());
1835 Add<HStoreNamedField>(
1836 result, HObjectAccess::ForJSArrayOffset(JSArray::kPropertiesOffset),
1838 Add<HStoreNamedField>(
1839 result, HObjectAccess::ForJSArrayOffset(JSArray::kElementsOffset),
1841 Add<HStoreNamedField>(
1842 result, HObjectAccess::ForJSArrayOffset(JSArray::kLengthOffset), length);
1844 // Initialize the additional fields.
1845 Add<HStoreNamedField>(
1846 result, HObjectAccess::ForJSArrayOffset(JSRegExpResult::kIndexOffset),
1848 Add<HStoreNamedField>(
1849 result, HObjectAccess::ForJSArrayOffset(JSRegExpResult::kInputOffset),
1852 // Allocate and initialize the elements header.
1853 HAllocate* elements = BuildAllocateElements(elements_kind, size);
1854 BuildInitializeElementsHeader(elements, elements_kind, length);
1856 HConstant* size_in_bytes_upper_bound = EstablishElementsAllocationSize(
1857 elements_kind, max_length->Integer32Value());
1858 elements->set_size_upper_bound(size_in_bytes_upper_bound);
1860 Add<HStoreNamedField>(
1861 result, HObjectAccess::ForJSArrayOffset(JSArray::kElementsOffset),
1864 // Initialize the elements contents with undefined.
1865 BuildFillElementsWithValue(
1866 elements, elements_kind, graph()->GetConstant0(), length,
1867 graph()->GetConstantUndefined());
1873 HValue* HGraphBuilder::BuildNumberToString(HValue* object, Type* type) {
1874 NoObservableSideEffectsScope scope(this);
1876 // Convert constant numbers at compile time.
1877 if (object->IsConstant() && HConstant::cast(object)->HasNumberValue()) {
1878 Handle<Object> number = HConstant::cast(object)->handle(isolate());
1879 Handle<String> result = isolate()->factory()->NumberToString(number);
1880 return Add<HConstant>(result);
1883 // Create a joinable continuation.
1884 HIfContinuation found(graph()->CreateBasicBlock(),
1885 graph()->CreateBasicBlock());
1887 // Load the number string cache.
1888 HValue* number_string_cache =
1889 Add<HLoadRoot>(Heap::kNumberStringCacheRootIndex);
1891 // Make the hash mask from the length of the number string cache. It
1892 // contains two elements (number and string) for each cache entry.
1893 HValue* mask = AddLoadFixedArrayLength(number_string_cache);
1894 mask->set_type(HType::Smi());
1895 mask = AddUncasted<HSar>(mask, graph()->GetConstant1());
1896 mask = AddUncasted<HSub>(mask, graph()->GetConstant1());
1898 // Check whether object is a smi.
1899 IfBuilder if_objectissmi(this);
1900 if_objectissmi.If<HIsSmiAndBranch>(object);
1901 if_objectissmi.Then();
1903 // Compute hash for smi similar to smi_get_hash().
1904 HValue* hash = AddUncasted<HBitwise>(Token::BIT_AND, object, mask);
1907 HValue* key_index = AddUncasted<HShl>(hash, graph()->GetConstant1());
1908 HValue* key = Add<HLoadKeyed>(number_string_cache, key_index,
1909 static_cast<HValue*>(NULL),
1910 FAST_ELEMENTS, ALLOW_RETURN_HOLE);
1912 // Check if object == key.
1913 IfBuilder if_objectiskey(this);
1914 if_objectiskey.If<HCompareObjectEqAndBranch>(object, key);
1915 if_objectiskey.Then();
1917 // Make the key_index available.
1920 if_objectiskey.JoinContinuation(&found);
1922 if_objectissmi.Else();
1924 if (type->Is(Type::SignedSmall())) {
1925 if_objectissmi.Deopt("Expected smi");
1927 // Check if the object is a heap number.
1928 IfBuilder if_objectisnumber(this);
1929 HValue* objectisnumber = if_objectisnumber.If<HCompareMap>(
1930 object, isolate()->factory()->heap_number_map());
1931 if_objectisnumber.Then();
1933 // Compute hash for heap number similar to double_get_hash().
1934 HValue* low = Add<HLoadNamedField>(
1935 object, objectisnumber,
1936 HObjectAccess::ForHeapNumberValueLowestBits());
1937 HValue* high = Add<HLoadNamedField>(
1938 object, objectisnumber,
1939 HObjectAccess::ForHeapNumberValueHighestBits());
1940 HValue* hash = AddUncasted<HBitwise>(Token::BIT_XOR, low, high);
1941 hash = AddUncasted<HBitwise>(Token::BIT_AND, hash, mask);
1944 HValue* key_index = AddUncasted<HShl>(hash, graph()->GetConstant1());
1945 HValue* key = Add<HLoadKeyed>(number_string_cache, key_index,
1946 static_cast<HValue*>(NULL),
1947 FAST_ELEMENTS, ALLOW_RETURN_HOLE);
1949 // Check if the key is a heap number and compare it with the object.
1950 IfBuilder if_keyisnotsmi(this);
1951 HValue* keyisnotsmi = if_keyisnotsmi.IfNot<HIsSmiAndBranch>(key);
1952 if_keyisnotsmi.Then();
1954 IfBuilder if_keyisheapnumber(this);
1955 if_keyisheapnumber.If<HCompareMap>(
1956 key, isolate()->factory()->heap_number_map());
1957 if_keyisheapnumber.Then();
1959 // Check if values of key and object match.
1960 IfBuilder if_keyeqobject(this);
1961 if_keyeqobject.If<HCompareNumericAndBranch>(
1962 Add<HLoadNamedField>(key, keyisnotsmi,
1963 HObjectAccess::ForHeapNumberValue()),
1964 Add<HLoadNamedField>(object, objectisnumber,
1965 HObjectAccess::ForHeapNumberValue()),
1967 if_keyeqobject.Then();
1969 // Make the key_index available.
1972 if_keyeqobject.JoinContinuation(&found);
1974 if_keyisheapnumber.JoinContinuation(&found);
1976 if_keyisnotsmi.JoinContinuation(&found);
1978 if_objectisnumber.Else();
1980 if (type->Is(Type::Number())) {
1981 if_objectisnumber.Deopt("Expected heap number");
1984 if_objectisnumber.JoinContinuation(&found);
1987 if_objectissmi.JoinContinuation(&found);
1989 // Check for cache hit.
1990 IfBuilder if_found(this, &found);
1993 // Count number to string operation in native code.
1994 AddIncrementCounter(isolate()->counters()->number_to_string_native());
1996 // Load the value in case of cache hit.
1997 HValue* key_index = Pop();
1998 HValue* value_index = AddUncasted<HAdd>(key_index, graph()->GetConstant1());
1999 Push(Add<HLoadKeyed>(number_string_cache, value_index,
2000 static_cast<HValue*>(NULL),
2001 FAST_ELEMENTS, ALLOW_RETURN_HOLE));
2005 // Cache miss, fallback to runtime.
2006 Add<HPushArguments>(object);
2007 Push(Add<HCallRuntime>(
2008 isolate()->factory()->empty_string(),
2009 Runtime::FunctionForId(Runtime::kNumberToStringSkipCache),
2018 HAllocate* HGraphBuilder::BuildAllocate(
2019 HValue* object_size,
2021 InstanceType instance_type,
2022 HAllocationMode allocation_mode) {
2023 // Compute the effective allocation size.
2024 HValue* size = object_size;
2025 if (allocation_mode.CreateAllocationMementos()) {
2026 size = AddUncasted<HAdd>(size, Add<HConstant>(AllocationMemento::kSize));
2027 size->ClearFlag(HValue::kCanOverflow);
2030 // Perform the actual allocation.
2031 HAllocate* object = Add<HAllocate>(
2032 size, type, allocation_mode.GetPretenureMode(),
2033 instance_type, allocation_mode.feedback_site());
2035 // Setup the allocation memento.
2036 if (allocation_mode.CreateAllocationMementos()) {
2037 BuildCreateAllocationMemento(
2038 object, object_size, allocation_mode.current_site());
2045 HValue* HGraphBuilder::BuildAddStringLengths(HValue* left_length,
2046 HValue* right_length) {
2047 // Compute the combined string length and check against max string length.
2048 HValue* length = AddUncasted<HAdd>(left_length, right_length);
2049 // Check that length <= kMaxLength <=> length < MaxLength + 1.
2050 HValue* max_length = Add<HConstant>(String::kMaxLength + 1);
2051 Add<HBoundsCheck>(length, max_length);
2056 HValue* HGraphBuilder::BuildCreateConsString(
2060 HAllocationMode allocation_mode) {
2061 // Determine the string instance types.
2062 HInstruction* left_instance_type = AddLoadStringInstanceType(left);
2063 HInstruction* right_instance_type = AddLoadStringInstanceType(right);
2065 // Allocate the cons string object. HAllocate does not care whether we
2066 // pass CONS_STRING_TYPE or CONS_ASCII_STRING_TYPE here, so we just use
2067 // CONS_STRING_TYPE here. Below we decide whether the cons string is
2068 // one-byte or two-byte and set the appropriate map.
2069 DCHECK(HAllocate::CompatibleInstanceTypes(CONS_STRING_TYPE,
2070 CONS_ASCII_STRING_TYPE));
2071 HAllocate* result = BuildAllocate(Add<HConstant>(ConsString::kSize),
2072 HType::String(), CONS_STRING_TYPE,
2075 // Compute intersection and difference of instance types.
2076 HValue* anded_instance_types = AddUncasted<HBitwise>(
2077 Token::BIT_AND, left_instance_type, right_instance_type);
2078 HValue* xored_instance_types = AddUncasted<HBitwise>(
2079 Token::BIT_XOR, left_instance_type, right_instance_type);
2081 // We create a one-byte cons string if
2082 // 1. both strings are one-byte, or
2083 // 2. at least one of the strings is two-byte, but happens to contain only
2084 // one-byte characters.
2085 // To do this, we check
2086 // 1. if both strings are one-byte, or if the one-byte data hint is set in
2088 // 2. if one of the strings has the one-byte data hint set and the other
2089 // string is one-byte.
2090 IfBuilder if_onebyte(this);
2091 STATIC_ASSERT(kOneByteStringTag != 0);
2092 STATIC_ASSERT(kOneByteDataHintMask != 0);
2093 if_onebyte.If<HCompareNumericAndBranch>(
2094 AddUncasted<HBitwise>(
2095 Token::BIT_AND, anded_instance_types,
2096 Add<HConstant>(static_cast<int32_t>(
2097 kStringEncodingMask | kOneByteDataHintMask))),
2098 graph()->GetConstant0(), Token::NE);
2100 STATIC_ASSERT(kOneByteStringTag != 0 &&
2101 kOneByteDataHintTag != 0 &&
2102 kOneByteDataHintTag != kOneByteStringTag);
2103 if_onebyte.If<HCompareNumericAndBranch>(
2104 AddUncasted<HBitwise>(
2105 Token::BIT_AND, xored_instance_types,
2106 Add<HConstant>(static_cast<int32_t>(
2107 kOneByteStringTag | kOneByteDataHintTag))),
2108 Add<HConstant>(static_cast<int32_t>(
2109 kOneByteStringTag | kOneByteDataHintTag)), Token::EQ);
2112 // We can safely skip the write barrier for storing the map here.
2113 Add<HStoreNamedField>(
2114 result, HObjectAccess::ForMap(),
2115 Add<HConstant>(isolate()->factory()->cons_ascii_string_map()));
2119 // We can safely skip the write barrier for storing the map here.
2120 Add<HStoreNamedField>(
2121 result, HObjectAccess::ForMap(),
2122 Add<HConstant>(isolate()->factory()->cons_string_map()));
2126 // Initialize the cons string fields.
2127 Add<HStoreNamedField>(result, HObjectAccess::ForStringHashField(),
2128 Add<HConstant>(String::kEmptyHashField));
2129 Add<HStoreNamedField>(result, HObjectAccess::ForStringLength(), length);
2130 Add<HStoreNamedField>(result, HObjectAccess::ForConsStringFirst(), left);
2131 Add<HStoreNamedField>(result, HObjectAccess::ForConsStringSecond(), right);
2133 // Count the native string addition.
2134 AddIncrementCounter(isolate()->counters()->string_add_native());
2140 void HGraphBuilder::BuildCopySeqStringChars(HValue* src,
2142 String::Encoding src_encoding,
2145 String::Encoding dst_encoding,
2147 DCHECK(dst_encoding != String::ONE_BYTE_ENCODING ||
2148 src_encoding == String::ONE_BYTE_ENCODING);
2149 LoopBuilder loop(this, context(), LoopBuilder::kPostIncrement);
2150 HValue* index = loop.BeginBody(graph()->GetConstant0(), length, Token::LT);
2152 HValue* src_index = AddUncasted<HAdd>(src_offset, index);
2154 AddUncasted<HSeqStringGetChar>(src_encoding, src, src_index);
2155 HValue* dst_index = AddUncasted<HAdd>(dst_offset, index);
2156 Add<HSeqStringSetChar>(dst_encoding, dst, dst_index, value);
2162 HValue* HGraphBuilder::BuildObjectSizeAlignment(
2163 HValue* unaligned_size, int header_size) {
2164 DCHECK((header_size & kObjectAlignmentMask) == 0);
2165 HValue* size = AddUncasted<HAdd>(
2166 unaligned_size, Add<HConstant>(static_cast<int32_t>(
2167 header_size + kObjectAlignmentMask)));
2168 size->ClearFlag(HValue::kCanOverflow);
2169 return AddUncasted<HBitwise>(
2170 Token::BIT_AND, size, Add<HConstant>(static_cast<int32_t>(
2171 ~kObjectAlignmentMask)));
2175 HValue* HGraphBuilder::BuildUncheckedStringAdd(
2178 HAllocationMode allocation_mode) {
2179 // Determine the string lengths.
2180 HValue* left_length = AddLoadStringLength(left);
2181 HValue* right_length = AddLoadStringLength(right);
2183 // Compute the combined string length.
2184 HValue* length = BuildAddStringLengths(left_length, right_length);
2186 // Do some manual constant folding here.
2187 if (left_length->IsConstant()) {
2188 HConstant* c_left_length = HConstant::cast(left_length);
2189 DCHECK_NE(0, c_left_length->Integer32Value());
2190 if (c_left_length->Integer32Value() + 1 >= ConsString::kMinLength) {
2191 // The right string contains at least one character.
2192 return BuildCreateConsString(length, left, right, allocation_mode);
2194 } else if (right_length->IsConstant()) {
2195 HConstant* c_right_length = HConstant::cast(right_length);
2196 DCHECK_NE(0, c_right_length->Integer32Value());
2197 if (c_right_length->Integer32Value() + 1 >= ConsString::kMinLength) {
2198 // The left string contains at least one character.
2199 return BuildCreateConsString(length, left, right, allocation_mode);
2203 // Check if we should create a cons string.
2204 IfBuilder if_createcons(this);
2205 if_createcons.If<HCompareNumericAndBranch>(
2206 length, Add<HConstant>(ConsString::kMinLength), Token::GTE);
2207 if_createcons.Then();
2209 // Create a cons string.
2210 Push(BuildCreateConsString(length, left, right, allocation_mode));
2212 if_createcons.Else();
2214 // Determine the string instance types.
2215 HValue* left_instance_type = AddLoadStringInstanceType(left);
2216 HValue* right_instance_type = AddLoadStringInstanceType(right);
2218 // Compute union and difference of instance types.
2219 HValue* ored_instance_types = AddUncasted<HBitwise>(
2220 Token::BIT_OR, left_instance_type, right_instance_type);
2221 HValue* xored_instance_types = AddUncasted<HBitwise>(
2222 Token::BIT_XOR, left_instance_type, right_instance_type);
2224 // Check if both strings have the same encoding and both are
2226 IfBuilder if_sameencodingandsequential(this);
2227 if_sameencodingandsequential.If<HCompareNumericAndBranch>(
2228 AddUncasted<HBitwise>(
2229 Token::BIT_AND, xored_instance_types,
2230 Add<HConstant>(static_cast<int32_t>(kStringEncodingMask))),
2231 graph()->GetConstant0(), Token::EQ);
2232 if_sameencodingandsequential.And();
2233 STATIC_ASSERT(kSeqStringTag == 0);
2234 if_sameencodingandsequential.If<HCompareNumericAndBranch>(
2235 AddUncasted<HBitwise>(
2236 Token::BIT_AND, ored_instance_types,
2237 Add<HConstant>(static_cast<int32_t>(kStringRepresentationMask))),
2238 graph()->GetConstant0(), Token::EQ);
2239 if_sameencodingandsequential.Then();
2241 HConstant* string_map =
2242 Add<HConstant>(isolate()->factory()->string_map());
2243 HConstant* ascii_string_map =
2244 Add<HConstant>(isolate()->factory()->ascii_string_map());
2246 // Determine map and size depending on whether result is one-byte string.
2247 IfBuilder if_onebyte(this);
2248 STATIC_ASSERT(kOneByteStringTag != 0);
2249 if_onebyte.If<HCompareNumericAndBranch>(
2250 AddUncasted<HBitwise>(
2251 Token::BIT_AND, ored_instance_types,
2252 Add<HConstant>(static_cast<int32_t>(kStringEncodingMask))),
2253 graph()->GetConstant0(), Token::NE);
2256 // Allocate sequential one-byte string object.
2258 Push(ascii_string_map);
2262 // Allocate sequential two-byte string object.
2263 HValue* size = AddUncasted<HShl>(length, graph()->GetConstant1());
2264 size->ClearFlag(HValue::kCanOverflow);
2265 size->SetFlag(HValue::kUint32);
2270 HValue* map = Pop();
2272 // Calculate the number of bytes needed for the characters in the
2273 // string while observing object alignment.
2274 STATIC_ASSERT((SeqString::kHeaderSize & kObjectAlignmentMask) == 0);
2275 HValue* size = BuildObjectSizeAlignment(Pop(), SeqString::kHeaderSize);
2277 // Allocate the string object. HAllocate does not care whether we pass
2278 // STRING_TYPE or ASCII_STRING_TYPE here, so we just use STRING_TYPE here.
2279 HAllocate* result = BuildAllocate(
2280 size, HType::String(), STRING_TYPE, allocation_mode);
2281 Add<HStoreNamedField>(result, HObjectAccess::ForMap(), map);
2283 // Initialize the string fields.
2284 Add<HStoreNamedField>(result, HObjectAccess::ForStringHashField(),
2285 Add<HConstant>(String::kEmptyHashField));
2286 Add<HStoreNamedField>(result, HObjectAccess::ForStringLength(), length);
2288 // Copy characters to the result string.
2289 IfBuilder if_twobyte(this);
2290 if_twobyte.If<HCompareObjectEqAndBranch>(map, string_map);
2293 // Copy characters from the left string.
2294 BuildCopySeqStringChars(
2295 left, graph()->GetConstant0(), String::TWO_BYTE_ENCODING,
2296 result, graph()->GetConstant0(), String::TWO_BYTE_ENCODING,
2299 // Copy characters from the right string.
2300 BuildCopySeqStringChars(
2301 right, graph()->GetConstant0(), String::TWO_BYTE_ENCODING,
2302 result, left_length, String::TWO_BYTE_ENCODING,
2307 // Copy characters from the left string.
2308 BuildCopySeqStringChars(
2309 left, graph()->GetConstant0(), String::ONE_BYTE_ENCODING,
2310 result, graph()->GetConstant0(), String::ONE_BYTE_ENCODING,
2313 // Copy characters from the right string.
2314 BuildCopySeqStringChars(
2315 right, graph()->GetConstant0(), String::ONE_BYTE_ENCODING,
2316 result, left_length, String::ONE_BYTE_ENCODING,
2321 // Count the native string addition.
2322 AddIncrementCounter(isolate()->counters()->string_add_native());
2324 // Return the sequential string.
2327 if_sameencodingandsequential.Else();
2329 // Fallback to the runtime to add the two strings.
2330 Add<HPushArguments>(left, right);
2331 Push(Add<HCallRuntime>(
2332 isolate()->factory()->empty_string(),
2333 Runtime::FunctionForId(Runtime::kStringAdd),
2336 if_sameencodingandsequential.End();
2338 if_createcons.End();
2344 HValue* HGraphBuilder::BuildStringAdd(
2347 HAllocationMode allocation_mode) {
2348 NoObservableSideEffectsScope no_effects(this);
2350 // Determine string lengths.
2351 HValue* left_length = AddLoadStringLength(left);
2352 HValue* right_length = AddLoadStringLength(right);
2354 // Check if left string is empty.
2355 IfBuilder if_leftempty(this);
2356 if_leftempty.If<HCompareNumericAndBranch>(
2357 left_length, graph()->GetConstant0(), Token::EQ);
2358 if_leftempty.Then();
2360 // Count the native string addition.
2361 AddIncrementCounter(isolate()->counters()->string_add_native());
2363 // Just return the right string.
2366 if_leftempty.Else();
2368 // Check if right string is empty.
2369 IfBuilder if_rightempty(this);
2370 if_rightempty.If<HCompareNumericAndBranch>(
2371 right_length, graph()->GetConstant0(), Token::EQ);
2372 if_rightempty.Then();
2374 // Count the native string addition.
2375 AddIncrementCounter(isolate()->counters()->string_add_native());
2377 // Just return the left string.
2380 if_rightempty.Else();
2382 // Add the two non-empty strings.
2383 Push(BuildUncheckedStringAdd(left, right, allocation_mode));
2385 if_rightempty.End();
2393 HInstruction* HGraphBuilder::BuildUncheckedMonomorphicElementAccess(
2394 HValue* checked_object,
2398 ElementsKind elements_kind,
2399 PropertyAccessType access_type,
2400 LoadKeyedHoleMode load_mode,
2401 KeyedAccessStoreMode store_mode) {
2402 DCHECK((!IsExternalArrayElementsKind(elements_kind) &&
2403 !IsFixedTypedArrayElementsKind(elements_kind)) ||
2405 // No GVNFlag is necessary for ElementsKind if there is an explicit dependency
2406 // on a HElementsTransition instruction. The flag can also be removed if the
2407 // map to check has FAST_HOLEY_ELEMENTS, since there can be no further
2408 // ElementsKind transitions. Finally, the dependency can be removed for stores
2409 // for FAST_ELEMENTS, since a transition to HOLEY elements won't change the
2410 // generated store code.
2411 if ((elements_kind == FAST_HOLEY_ELEMENTS) ||
2412 (elements_kind == FAST_ELEMENTS && access_type == STORE)) {
2413 checked_object->ClearDependsOnFlag(kElementsKind);
2416 bool fast_smi_only_elements = IsFastSmiElementsKind(elements_kind);
2417 bool fast_elements = IsFastObjectElementsKind(elements_kind);
2418 HValue* elements = AddLoadElements(checked_object);
2419 if (access_type == STORE && (fast_elements || fast_smi_only_elements) &&
2420 store_mode != STORE_NO_TRANSITION_HANDLE_COW) {
2421 HCheckMaps* check_cow_map = Add<HCheckMaps>(
2422 elements, isolate()->factory()->fixed_array_map());
2423 check_cow_map->ClearDependsOnFlag(kElementsKind);
2425 HInstruction* length = NULL;
2427 length = Add<HLoadNamedField>(
2428 checked_object->ActualValue(), checked_object,
2429 HObjectAccess::ForArrayLength(elements_kind));
2431 length = AddLoadFixedArrayLength(elements);
2433 length->set_type(HType::Smi());
2434 HValue* checked_key = NULL;
2435 if (IsExternalArrayElementsKind(elements_kind) ||
2436 IsFixedTypedArrayElementsKind(elements_kind)) {
2437 HValue* backing_store;
2438 if (IsExternalArrayElementsKind(elements_kind)) {
2439 backing_store = Add<HLoadNamedField>(
2440 elements, static_cast<HValue*>(NULL),
2441 HObjectAccess::ForExternalArrayExternalPointer());
2443 backing_store = elements;
2445 if (store_mode == STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
2446 NoObservableSideEffectsScope no_effects(this);
2447 IfBuilder length_checker(this);
2448 length_checker.If<HCompareNumericAndBranch>(key, length, Token::LT);
2449 length_checker.Then();
2450 IfBuilder negative_checker(this);
2451 HValue* bounds_check = negative_checker.If<HCompareNumericAndBranch>(
2452 key, graph()->GetConstant0(), Token::GTE);
2453 negative_checker.Then();
2454 HInstruction* result = AddElementAccess(
2455 backing_store, key, val, bounds_check, elements_kind, access_type);
2456 negative_checker.ElseDeopt("Negative key encountered");
2457 negative_checker.End();
2458 length_checker.End();
2461 DCHECK(store_mode == STANDARD_STORE);
2462 checked_key = Add<HBoundsCheck>(key, length);
2463 return AddElementAccess(
2464 backing_store, checked_key, val,
2465 checked_object, elements_kind, access_type);
2468 DCHECK(fast_smi_only_elements ||
2470 IsFastDoubleElementsKind(elements_kind));
2472 // In case val is stored into a fast smi array, assure that the value is a smi
2473 // before manipulating the backing store. Otherwise the actual store may
2474 // deopt, leaving the backing store in an invalid state.
2475 if (access_type == STORE && IsFastSmiElementsKind(elements_kind) &&
2476 !val->type().IsSmi()) {
2477 val = AddUncasted<HForceRepresentation>(val, Representation::Smi());
2480 if (IsGrowStoreMode(store_mode)) {
2481 NoObservableSideEffectsScope no_effects(this);
2482 Representation representation = HStoreKeyed::RequiredValueRepresentation(
2483 elements_kind, STORE_TO_INITIALIZED_ENTRY);
2484 val = AddUncasted<HForceRepresentation>(val, representation);
2485 elements = BuildCheckForCapacityGrow(checked_object, elements,
2486 elements_kind, length, key,
2487 is_js_array, access_type);
2490 checked_key = Add<HBoundsCheck>(key, length);
2492 if (access_type == STORE && (fast_elements || fast_smi_only_elements)) {
2493 if (store_mode == STORE_NO_TRANSITION_HANDLE_COW) {
2494 NoObservableSideEffectsScope no_effects(this);
2495 elements = BuildCopyElementsOnWrite(checked_object, elements,
2496 elements_kind, length);
2498 HCheckMaps* check_cow_map = Add<HCheckMaps>(
2499 elements, isolate()->factory()->fixed_array_map());
2500 check_cow_map->ClearDependsOnFlag(kElementsKind);
2504 return AddElementAccess(elements, checked_key, val, checked_object,
2505 elements_kind, access_type, load_mode);
2509 HValue* HGraphBuilder::BuildAllocateArrayFromLength(
2510 JSArrayBuilder* array_builder,
2511 HValue* length_argument) {
2512 if (length_argument->IsConstant() &&
2513 HConstant::cast(length_argument)->HasSmiValue()) {
2514 int array_length = HConstant::cast(length_argument)->Integer32Value();
2515 if (array_length == 0) {
2516 return array_builder->AllocateEmptyArray();
2518 return array_builder->AllocateArray(length_argument,
2524 HValue* constant_zero = graph()->GetConstant0();
2525 HConstant* max_alloc_length =
2526 Add<HConstant>(JSObject::kInitialMaxFastElementArray);
2527 HInstruction* checked_length = Add<HBoundsCheck>(length_argument,
2529 IfBuilder if_builder(this);
2530 if_builder.If<HCompareNumericAndBranch>(checked_length, constant_zero,
2533 const int initial_capacity = JSArray::kPreallocatedArrayElements;
2534 HConstant* initial_capacity_node = Add<HConstant>(initial_capacity);
2535 Push(initial_capacity_node); // capacity
2536 Push(constant_zero); // length
2538 if (!(top_info()->IsStub()) &&
2539 IsFastPackedElementsKind(array_builder->kind())) {
2540 // We'll come back later with better (holey) feedback.
2541 if_builder.Deopt("Holey array despite packed elements_kind feedback");
2543 Push(checked_length); // capacity
2544 Push(checked_length); // length
2548 // Figure out total size
2549 HValue* length = Pop();
2550 HValue* capacity = Pop();
2551 return array_builder->AllocateArray(capacity, max_alloc_length, length);
2555 HValue* HGraphBuilder::BuildCalculateElementsSize(ElementsKind kind,
2557 int elements_size = IsFastDoubleElementsKind(kind)
2561 HConstant* elements_size_value = Add<HConstant>(elements_size);
2562 HInstruction* mul = HMul::NewImul(zone(), context(),
2563 capacity->ActualValue(),
2564 elements_size_value);
2565 AddInstruction(mul);
2566 mul->ClearFlag(HValue::kCanOverflow);
2568 STATIC_ASSERT(FixedDoubleArray::kHeaderSize == FixedArray::kHeaderSize);
2570 HConstant* header_size = Add<HConstant>(FixedArray::kHeaderSize);
2571 HValue* total_size = AddUncasted<HAdd>(mul, header_size);
2572 total_size->ClearFlag(HValue::kCanOverflow);
2577 HAllocate* HGraphBuilder::AllocateJSArrayObject(AllocationSiteMode mode) {
2578 int base_size = JSArray::kSize;
2579 if (mode == TRACK_ALLOCATION_SITE) {
2580 base_size += AllocationMemento::kSize;
2582 HConstant* size_in_bytes = Add<HConstant>(base_size);
2583 return Add<HAllocate>(
2584 size_in_bytes, HType::JSArray(), NOT_TENURED, JS_OBJECT_TYPE);
2588 HConstant* HGraphBuilder::EstablishElementsAllocationSize(
2591 int base_size = IsFastDoubleElementsKind(kind)
2592 ? FixedDoubleArray::SizeFor(capacity)
2593 : FixedArray::SizeFor(capacity);
2595 return Add<HConstant>(base_size);
2599 HAllocate* HGraphBuilder::BuildAllocateElements(ElementsKind kind,
2600 HValue* size_in_bytes) {
2601 InstanceType instance_type = IsFastDoubleElementsKind(kind)
2602 ? FIXED_DOUBLE_ARRAY_TYPE
2605 return Add<HAllocate>(size_in_bytes, HType::HeapObject(), NOT_TENURED,
2610 void HGraphBuilder::BuildInitializeElementsHeader(HValue* elements,
2613 Factory* factory = isolate()->factory();
2614 Handle<Map> map = IsFastDoubleElementsKind(kind)
2615 ? factory->fixed_double_array_map()
2616 : factory->fixed_array_map();
2618 Add<HStoreNamedField>(elements, HObjectAccess::ForMap(), Add<HConstant>(map));
2619 Add<HStoreNamedField>(elements, HObjectAccess::ForFixedArrayLength(),
2624 HValue* HGraphBuilder::BuildAllocateElementsAndInitializeElementsHeader(
2627 // The HForceRepresentation is to prevent possible deopt on int-smi
2628 // conversion after allocation but before the new object fields are set.
2629 capacity = AddUncasted<HForceRepresentation>(capacity, Representation::Smi());
2630 HValue* size_in_bytes = BuildCalculateElementsSize(kind, capacity);
2631 HValue* new_elements = BuildAllocateElements(kind, size_in_bytes);
2632 BuildInitializeElementsHeader(new_elements, kind, capacity);
2633 return new_elements;
2637 void HGraphBuilder::BuildJSArrayHeader(HValue* array,
2640 AllocationSiteMode mode,
2641 ElementsKind elements_kind,
2642 HValue* allocation_site_payload,
2643 HValue* length_field) {
2644 Add<HStoreNamedField>(array, HObjectAccess::ForMap(), array_map);
2646 HConstant* empty_fixed_array =
2647 Add<HConstant>(isolate()->factory()->empty_fixed_array());
2649 Add<HStoreNamedField>(
2650 array, HObjectAccess::ForPropertiesPointer(), empty_fixed_array);
2652 Add<HStoreNamedField>(
2653 array, HObjectAccess::ForElementsPointer(),
2654 elements != NULL ? elements : empty_fixed_array);
2656 Add<HStoreNamedField>(
2657 array, HObjectAccess::ForArrayLength(elements_kind), length_field);
2659 if (mode == TRACK_ALLOCATION_SITE) {
2660 BuildCreateAllocationMemento(
2661 array, Add<HConstant>(JSArray::kSize), allocation_site_payload);
2666 HInstruction* HGraphBuilder::AddElementAccess(
2668 HValue* checked_key,
2671 ElementsKind elements_kind,
2672 PropertyAccessType access_type,
2673 LoadKeyedHoleMode load_mode) {
2674 if (access_type == STORE) {
2675 DCHECK(val != NULL);
2676 if (elements_kind == EXTERNAL_UINT8_CLAMPED_ELEMENTS ||
2677 elements_kind == UINT8_CLAMPED_ELEMENTS) {
2678 val = Add<HClampToUint8>(val);
2680 return Add<HStoreKeyed>(elements, checked_key, val, elements_kind,
2681 STORE_TO_INITIALIZED_ENTRY);
2684 DCHECK(access_type == LOAD);
2685 DCHECK(val == NULL);
2686 HLoadKeyed* load = Add<HLoadKeyed>(
2687 elements, checked_key, dependency, elements_kind, load_mode);
2688 if (FLAG_opt_safe_uint32_operations &&
2689 (elements_kind == EXTERNAL_UINT32_ELEMENTS ||
2690 elements_kind == UINT32_ELEMENTS)) {
2691 graph()->RecordUint32Instruction(load);
2697 HLoadNamedField* HGraphBuilder::AddLoadMap(HValue* object,
2698 HValue* dependency) {
2699 return Add<HLoadNamedField>(object, dependency, HObjectAccess::ForMap());
2703 HLoadNamedField* HGraphBuilder::AddLoadElements(HValue* object,
2704 HValue* dependency) {
2705 return Add<HLoadNamedField>(
2706 object, dependency, HObjectAccess::ForElementsPointer());
2710 HLoadNamedField* HGraphBuilder::AddLoadFixedArrayLength(
2712 HValue* dependency) {
2713 return Add<HLoadNamedField>(
2714 array, dependency, HObjectAccess::ForFixedArrayLength());
2718 HLoadNamedField* HGraphBuilder::AddLoadArrayLength(HValue* array,
2720 HValue* dependency) {
2721 return Add<HLoadNamedField>(
2722 array, dependency, HObjectAccess::ForArrayLength(kind));
2726 HValue* HGraphBuilder::BuildNewElementsCapacity(HValue* old_capacity) {
2727 HValue* half_old_capacity = AddUncasted<HShr>(old_capacity,
2728 graph_->GetConstant1());
2730 HValue* new_capacity = AddUncasted<HAdd>(half_old_capacity, old_capacity);
2731 new_capacity->ClearFlag(HValue::kCanOverflow);
2733 HValue* min_growth = Add<HConstant>(16);
2735 new_capacity = AddUncasted<HAdd>(new_capacity, min_growth);
2736 new_capacity->ClearFlag(HValue::kCanOverflow);
2738 return new_capacity;
2742 HValue* HGraphBuilder::BuildGrowElementsCapacity(HValue* object,
2745 ElementsKind new_kind,
2747 HValue* new_capacity) {
2748 Add<HBoundsCheck>(new_capacity, Add<HConstant>(
2749 (Page::kMaxRegularHeapObjectSize - FixedArray::kHeaderSize) >>
2750 ElementsKindToShiftSize(new_kind)));
2752 HValue* new_elements = BuildAllocateElementsAndInitializeElementsHeader(
2753 new_kind, new_capacity);
2755 BuildCopyElements(elements, kind, new_elements,
2756 new_kind, length, new_capacity);
2758 Add<HStoreNamedField>(object, HObjectAccess::ForElementsPointer(),
2761 return new_elements;
2765 void HGraphBuilder::BuildFillElementsWithValue(HValue* elements,
2766 ElementsKind elements_kind,
2771 to = AddLoadFixedArrayLength(elements);
2774 // Special loop unfolding case
2775 STATIC_ASSERT(JSArray::kPreallocatedArrayElements <=
2776 kElementLoopUnrollThreshold);
2777 int initial_capacity = -1;
2778 if (from->IsInteger32Constant() && to->IsInteger32Constant()) {
2779 int constant_from = from->GetInteger32Constant();
2780 int constant_to = to->GetInteger32Constant();
2782 if (constant_from == 0 && constant_to <= kElementLoopUnrollThreshold) {
2783 initial_capacity = constant_to;
2787 // Since we're about to store a hole value, the store instruction below must
2788 // assume an elements kind that supports heap object values.
2789 if (IsFastSmiOrObjectElementsKind(elements_kind)) {
2790 elements_kind = FAST_HOLEY_ELEMENTS;
2793 if (initial_capacity >= 0) {
2794 for (int i = 0; i < initial_capacity; i++) {
2795 HInstruction* key = Add<HConstant>(i);
2796 Add<HStoreKeyed>(elements, key, value, elements_kind);
2799 // Carefully loop backwards so that the "from" remains live through the loop
2800 // rather than the to. This often corresponds to keeping length live rather
2801 // then capacity, which helps register allocation, since length is used more
2802 // other than capacity after filling with holes.
2803 LoopBuilder builder(this, context(), LoopBuilder::kPostDecrement);
2805 HValue* key = builder.BeginBody(to, from, Token::GT);
2807 HValue* adjusted_key = AddUncasted<HSub>(key, graph()->GetConstant1());
2808 adjusted_key->ClearFlag(HValue::kCanOverflow);
2810 Add<HStoreKeyed>(elements, adjusted_key, value, elements_kind);
2817 void HGraphBuilder::BuildFillElementsWithHole(HValue* elements,
2818 ElementsKind elements_kind,
2821 // Fast elements kinds need to be initialized in case statements below cause a
2822 // garbage collection.
2823 Factory* factory = isolate()->factory();
2825 double nan_double = FixedDoubleArray::hole_nan_as_double();
2826 HValue* hole = IsFastSmiOrObjectElementsKind(elements_kind)
2827 ? Add<HConstant>(factory->the_hole_value())
2828 : Add<HConstant>(nan_double);
2830 BuildFillElementsWithValue(elements, elements_kind, from, to, hole);
2834 void HGraphBuilder::BuildCopyElements(HValue* from_elements,
2835 ElementsKind from_elements_kind,
2836 HValue* to_elements,
2837 ElementsKind to_elements_kind,
2840 int constant_capacity = -1;
2841 if (capacity != NULL &&
2842 capacity->IsConstant() &&
2843 HConstant::cast(capacity)->HasInteger32Value()) {
2844 int constant_candidate = HConstant::cast(capacity)->Integer32Value();
2845 if (constant_candidate <= kElementLoopUnrollThreshold) {
2846 constant_capacity = constant_candidate;
2850 bool pre_fill_with_holes =
2851 IsFastDoubleElementsKind(from_elements_kind) &&
2852 IsFastObjectElementsKind(to_elements_kind);
2853 if (pre_fill_with_holes) {
2854 // If the copy might trigger a GC, make sure that the FixedArray is
2855 // pre-initialized with holes to make sure that it's always in a
2856 // consistent state.
2857 BuildFillElementsWithHole(to_elements, to_elements_kind,
2858 graph()->GetConstant0(), NULL);
2861 if (constant_capacity != -1) {
2862 // Unroll the loop for small elements kinds.
2863 for (int i = 0; i < constant_capacity; i++) {
2864 HValue* key_constant = Add<HConstant>(i);
2865 HInstruction* value = Add<HLoadKeyed>(from_elements, key_constant,
2866 static_cast<HValue*>(NULL),
2867 from_elements_kind);
2868 Add<HStoreKeyed>(to_elements, key_constant, value, to_elements_kind);
2871 if (!pre_fill_with_holes &&
2872 (capacity == NULL || !length->Equals(capacity))) {
2873 BuildFillElementsWithHole(to_elements, to_elements_kind,
2877 if (capacity == NULL) {
2878 capacity = AddLoadFixedArrayLength(to_elements);
2881 LoopBuilder builder(this, context(), LoopBuilder::kPostDecrement);
2883 HValue* key = builder.BeginBody(length, graph()->GetConstant0(),
2886 key = AddUncasted<HSub>(key, graph()->GetConstant1());
2887 key->ClearFlag(HValue::kCanOverflow);
2889 HValue* element = Add<HLoadKeyed>(from_elements, key,
2890 static_cast<HValue*>(NULL),
2894 ElementsKind kind = (IsHoleyElementsKind(from_elements_kind) &&
2895 IsFastSmiElementsKind(to_elements_kind))
2896 ? FAST_HOLEY_ELEMENTS : to_elements_kind;
2898 if (IsHoleyElementsKind(from_elements_kind) &&
2899 from_elements_kind != to_elements_kind) {
2900 IfBuilder if_hole(this);
2901 if_hole.If<HCompareHoleAndBranch>(element);
2903 HConstant* hole_constant = IsFastDoubleElementsKind(to_elements_kind)
2904 ? Add<HConstant>(FixedDoubleArray::hole_nan_as_double())
2905 : graph()->GetConstantHole();
2906 Add<HStoreKeyed>(to_elements, key, hole_constant, kind);
2908 HStoreKeyed* store = Add<HStoreKeyed>(to_elements, key, element, kind);
2909 store->SetFlag(HValue::kAllowUndefinedAsNaN);
2912 HStoreKeyed* store = Add<HStoreKeyed>(to_elements, key, element, kind);
2913 store->SetFlag(HValue::kAllowUndefinedAsNaN);
2919 Counters* counters = isolate()->counters();
2920 AddIncrementCounter(counters->inlined_copied_elements());
2924 HValue* HGraphBuilder::BuildCloneShallowArrayCow(HValue* boilerplate,
2925 HValue* allocation_site,
2926 AllocationSiteMode mode,
2927 ElementsKind kind) {
2928 HAllocate* array = AllocateJSArrayObject(mode);
2930 HValue* map = AddLoadMap(boilerplate);
2931 HValue* elements = AddLoadElements(boilerplate);
2932 HValue* length = AddLoadArrayLength(boilerplate, kind);
2934 BuildJSArrayHeader(array,
2945 HValue* HGraphBuilder::BuildCloneShallowArrayEmpty(HValue* boilerplate,
2946 HValue* allocation_site,
2947 AllocationSiteMode mode) {
2948 HAllocate* array = AllocateJSArrayObject(mode);
2950 HValue* map = AddLoadMap(boilerplate);
2952 BuildJSArrayHeader(array,
2954 NULL, // set elements to empty fixed array
2958 graph()->GetConstant0());
2963 HValue* HGraphBuilder::BuildCloneShallowArrayNonEmpty(HValue* boilerplate,
2964 HValue* allocation_site,
2965 AllocationSiteMode mode,
2966 ElementsKind kind) {
2967 HValue* boilerplate_elements = AddLoadElements(boilerplate);
2968 HValue* capacity = AddLoadFixedArrayLength(boilerplate_elements);
2970 // Generate size calculation code here in order to make it dominate
2971 // the JSArray allocation.
2972 HValue* elements_size = BuildCalculateElementsSize(kind, capacity);
2974 // Create empty JSArray object for now, store elimination should remove
2975 // redundant initialization of elements and length fields and at the same
2976 // time the object will be fully prepared for GC if it happens during
2977 // elements allocation.
2978 HValue* result = BuildCloneShallowArrayEmpty(
2979 boilerplate, allocation_site, mode);
2981 HAllocate* elements = BuildAllocateElements(kind, elements_size);
2983 // This function implicitly relies on the fact that the
2984 // FastCloneShallowArrayStub is called only for literals shorter than
2985 // JSObject::kInitialMaxFastElementArray.
2986 // Can't add HBoundsCheck here because otherwise the stub will eager a frame.
2987 HConstant* size_upper_bound = EstablishElementsAllocationSize(
2988 kind, JSObject::kInitialMaxFastElementArray);
2989 elements->set_size_upper_bound(size_upper_bound);
2991 Add<HStoreNamedField>(result, HObjectAccess::ForElementsPointer(), elements);
2993 // The allocation for the cloned array above causes register pressure on
2994 // machines with low register counts. Force a reload of the boilerplate
2995 // elements here to free up a register for the allocation to avoid unnecessary
2997 boilerplate_elements = AddLoadElements(boilerplate);
2998 boilerplate_elements->SetFlag(HValue::kCantBeReplaced);
3000 // Copy the elements array header.
3001 for (int i = 0; i < FixedArrayBase::kHeaderSize; i += kPointerSize) {
3002 HObjectAccess access = HObjectAccess::ForFixedArrayHeader(i);
3003 Add<HStoreNamedField>(elements, access,
3004 Add<HLoadNamedField>(boilerplate_elements,
3005 static_cast<HValue*>(NULL), access));
3008 // And the result of the length
3009 HValue* length = AddLoadArrayLength(boilerplate, kind);
3010 Add<HStoreNamedField>(result, HObjectAccess::ForArrayLength(kind), length);
3012 BuildCopyElements(boilerplate_elements, kind, elements,
3013 kind, length, NULL);
3018 void HGraphBuilder::BuildCompareNil(
3021 HIfContinuation* continuation) {
3022 IfBuilder if_nil(this);
3023 bool some_case_handled = false;
3024 bool some_case_missing = false;
3026 if (type->Maybe(Type::Null())) {
3027 if (some_case_handled) if_nil.Or();
3028 if_nil.If<HCompareObjectEqAndBranch>(value, graph()->GetConstantNull());
3029 some_case_handled = true;
3031 some_case_missing = true;
3034 if (type->Maybe(Type::Undefined())) {
3035 if (some_case_handled) if_nil.Or();
3036 if_nil.If<HCompareObjectEqAndBranch>(value,
3037 graph()->GetConstantUndefined());
3038 some_case_handled = true;
3040 some_case_missing = true;
3043 if (type->Maybe(Type::Undetectable())) {
3044 if (some_case_handled) if_nil.Or();
3045 if_nil.If<HIsUndetectableAndBranch>(value);
3046 some_case_handled = true;
3048 some_case_missing = true;
3051 if (some_case_missing) {
3054 if (type->NumClasses() == 1) {
3055 BuildCheckHeapObject(value);
3056 // For ICs, the map checked below is a sentinel map that gets replaced by
3057 // the monomorphic map when the code is used as a template to generate a
3058 // new IC. For optimized functions, there is no sentinel map, the map
3059 // emitted below is the actual monomorphic map.
3060 Add<HCheckMaps>(value, type->Classes().Current());
3062 if_nil.Deopt("Too many undetectable types");
3066 if_nil.CaptureContinuation(continuation);
3070 void HGraphBuilder::BuildCreateAllocationMemento(
3071 HValue* previous_object,
3072 HValue* previous_object_size,
3073 HValue* allocation_site) {
3074 DCHECK(allocation_site != NULL);
3075 HInnerAllocatedObject* allocation_memento = Add<HInnerAllocatedObject>(
3076 previous_object, previous_object_size, HType::HeapObject());
3077 AddStoreMapConstant(
3078 allocation_memento, isolate()->factory()->allocation_memento_map());
3079 Add<HStoreNamedField>(
3081 HObjectAccess::ForAllocationMementoSite(),
3083 if (FLAG_allocation_site_pretenuring) {
3084 HValue* memento_create_count = Add<HLoadNamedField>(
3085 allocation_site, static_cast<HValue*>(NULL),
3086 HObjectAccess::ForAllocationSiteOffset(
3087 AllocationSite::kPretenureCreateCountOffset));
3088 memento_create_count = AddUncasted<HAdd>(
3089 memento_create_count, graph()->GetConstant1());
3090 // This smi value is reset to zero after every gc, overflow isn't a problem
3091 // since the counter is bounded by the new space size.
3092 memento_create_count->ClearFlag(HValue::kCanOverflow);
3093 Add<HStoreNamedField>(
3094 allocation_site, HObjectAccess::ForAllocationSiteOffset(
3095 AllocationSite::kPretenureCreateCountOffset), memento_create_count);
3100 HInstruction* HGraphBuilder::BuildGetNativeContext(HValue* closure) {
3101 // Get the global context, then the native context
3102 HInstruction* context =
3103 Add<HLoadNamedField>(closure, static_cast<HValue*>(NULL),
3104 HObjectAccess::ForFunctionContextPointer());
3105 HInstruction* global_object = Add<HLoadNamedField>(
3106 context, static_cast<HValue*>(NULL),
3107 HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
3108 HObjectAccess access = HObjectAccess::ForObservableJSObjectOffset(
3109 GlobalObject::kNativeContextOffset);
3110 return Add<HLoadNamedField>(
3111 global_object, static_cast<HValue*>(NULL), access);
3115 HInstruction* HGraphBuilder::BuildGetNativeContext() {
3116 // Get the global context, then the native context
3117 HValue* global_object = Add<HLoadNamedField>(
3118 context(), static_cast<HValue*>(NULL),
3119 HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
3120 return Add<HLoadNamedField>(
3121 global_object, static_cast<HValue*>(NULL),
3122 HObjectAccess::ForObservableJSObjectOffset(
3123 GlobalObject::kNativeContextOffset));
3127 HInstruction* HGraphBuilder::BuildGetArrayFunction() {
3128 HInstruction* native_context = BuildGetNativeContext();
3129 HInstruction* index =
3130 Add<HConstant>(static_cast<int32_t>(Context::ARRAY_FUNCTION_INDEX));
3131 return Add<HLoadKeyed>(
3132 native_context, index, static_cast<HValue*>(NULL), FAST_ELEMENTS);
3136 HGraphBuilder::JSArrayBuilder::JSArrayBuilder(HGraphBuilder* builder,
3138 HValue* allocation_site_payload,
3139 HValue* constructor_function,
3140 AllocationSiteOverrideMode override_mode) :
3143 allocation_site_payload_(allocation_site_payload),
3144 constructor_function_(constructor_function) {
3145 DCHECK(!allocation_site_payload->IsConstant() ||
3146 HConstant::cast(allocation_site_payload)->handle(
3147 builder_->isolate())->IsAllocationSite());
3148 mode_ = override_mode == DISABLE_ALLOCATION_SITES
3149 ? DONT_TRACK_ALLOCATION_SITE
3150 : AllocationSite::GetMode(kind);
3154 HGraphBuilder::JSArrayBuilder::JSArrayBuilder(HGraphBuilder* builder,
3156 HValue* constructor_function) :
3159 mode_(DONT_TRACK_ALLOCATION_SITE),
3160 allocation_site_payload_(NULL),
3161 constructor_function_(constructor_function) {
3165 HValue* HGraphBuilder::JSArrayBuilder::EmitMapCode() {
3166 if (!builder()->top_info()->IsStub()) {
3167 // A constant map is fine.
3168 Handle<Map> map(builder()->isolate()->get_initial_js_array_map(kind_),
3169 builder()->isolate());
3170 return builder()->Add<HConstant>(map);
3173 if (constructor_function_ != NULL && kind_ == GetInitialFastElementsKind()) {
3174 // No need for a context lookup if the kind_ matches the initial
3175 // map, because we can just load the map in that case.
3176 HObjectAccess access = HObjectAccess::ForPrototypeOrInitialMap();
3177 return builder()->Add<HLoadNamedField>(
3178 constructor_function_, static_cast<HValue*>(NULL), access);
3181 // TODO(mvstanton): we should always have a constructor function if we
3182 // are creating a stub.
3183 HInstruction* native_context = constructor_function_ != NULL
3184 ? builder()->BuildGetNativeContext(constructor_function_)
3185 : builder()->BuildGetNativeContext();
3187 HInstruction* index = builder()->Add<HConstant>(
3188 static_cast<int32_t>(Context::JS_ARRAY_MAPS_INDEX));
3190 HInstruction* map_array = builder()->Add<HLoadKeyed>(
3191 native_context, index, static_cast<HValue*>(NULL), FAST_ELEMENTS);
3193 HInstruction* kind_index = builder()->Add<HConstant>(kind_);
3195 return builder()->Add<HLoadKeyed>(
3196 map_array, kind_index, static_cast<HValue*>(NULL), FAST_ELEMENTS);
3200 HValue* HGraphBuilder::JSArrayBuilder::EmitInternalMapCode() {
3201 // Find the map near the constructor function
3202 HObjectAccess access = HObjectAccess::ForPrototypeOrInitialMap();
3203 return builder()->Add<HLoadNamedField>(
3204 constructor_function_, static_cast<HValue*>(NULL), access);
3208 HAllocate* HGraphBuilder::JSArrayBuilder::AllocateEmptyArray() {
3209 HConstant* capacity = builder()->Add<HConstant>(initial_capacity());
3210 return AllocateArray(capacity,
3212 builder()->graph()->GetConstant0());
3216 HAllocate* HGraphBuilder::JSArrayBuilder::AllocateArray(
3218 HConstant* capacity_upper_bound,
3219 HValue* length_field,
3220 FillMode fill_mode) {
3221 return AllocateArray(capacity,
3222 capacity_upper_bound->GetInteger32Constant(),
3228 HAllocate* HGraphBuilder::JSArrayBuilder::AllocateArray(
3230 int capacity_upper_bound,
3231 HValue* length_field,
3232 FillMode fill_mode) {
3233 HConstant* elememts_size_upper_bound = capacity->IsInteger32Constant()
3234 ? HConstant::cast(capacity)
3235 : builder()->EstablishElementsAllocationSize(kind_, capacity_upper_bound);
3237 HAllocate* array = AllocateArray(capacity, length_field, fill_mode);
3238 if (!elements_location_->has_size_upper_bound()) {
3239 elements_location_->set_size_upper_bound(elememts_size_upper_bound);
3245 HAllocate* HGraphBuilder::JSArrayBuilder::AllocateArray(
3247 HValue* length_field,
3248 FillMode fill_mode) {
3249 // These HForceRepresentations are because we store these as fields in the
3250 // objects we construct, and an int32-to-smi HChange could deopt. Accept
3251 // the deopt possibility now, before allocation occurs.
3253 builder()->AddUncasted<HForceRepresentation>(capacity,
3254 Representation::Smi());
3256 builder()->AddUncasted<HForceRepresentation>(length_field,
3257 Representation::Smi());
3259 // Generate size calculation code here in order to make it dominate
3260 // the JSArray allocation.
3261 HValue* elements_size =
3262 builder()->BuildCalculateElementsSize(kind_, capacity);
3264 // Allocate (dealing with failure appropriately)
3265 HAllocate* array_object = builder()->AllocateJSArrayObject(mode_);
3267 // Fill in the fields: map, properties, length
3269 if (allocation_site_payload_ == NULL) {
3270 map = EmitInternalMapCode();
3272 map = EmitMapCode();
3275 builder()->BuildJSArrayHeader(array_object,
3277 NULL, // set elements to empty fixed array
3280 allocation_site_payload_,
3283 // Allocate and initialize the elements
3284 elements_location_ = builder()->BuildAllocateElements(kind_, elements_size);
3286 builder()->BuildInitializeElementsHeader(elements_location_, kind_, capacity);
3289 builder()->Add<HStoreNamedField>(
3290 array_object, HObjectAccess::ForElementsPointer(), elements_location_);
3292 if (fill_mode == FILL_WITH_HOLE) {
3293 builder()->BuildFillElementsWithHole(elements_location_, kind_,
3294 graph()->GetConstant0(), capacity);
3297 return array_object;
3301 HValue* HGraphBuilder::AddLoadJSBuiltin(Builtins::JavaScript builtin) {
3302 HValue* global_object = Add<HLoadNamedField>(
3303 context(), static_cast<HValue*>(NULL),
3304 HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
3305 HObjectAccess access = HObjectAccess::ForObservableJSObjectOffset(
3306 GlobalObject::kBuiltinsOffset);
3307 HValue* builtins = Add<HLoadNamedField>(
3308 global_object, static_cast<HValue*>(NULL), access);
3309 HObjectAccess function_access = HObjectAccess::ForObservableJSObjectOffset(
3310 JSBuiltinsObject::OffsetOfFunctionWithId(builtin));
3311 return Add<HLoadNamedField>(
3312 builtins, static_cast<HValue*>(NULL), function_access);
3316 HOptimizedGraphBuilder::HOptimizedGraphBuilder(CompilationInfo* info)
3317 : HGraphBuilder(info),
3318 function_state_(NULL),
3319 initial_function_state_(this, info, NORMAL_RETURN, 0),
3323 globals_(10, info->zone()),
3324 inline_bailout_(false),
3325 osr_(new(info->zone()) HOsrBuilder(this)) {
3326 // This is not initialized in the initializer list because the
3327 // constructor for the initial state relies on function_state_ == NULL
3328 // to know it's the initial state.
3329 function_state_= &initial_function_state_;
3330 InitializeAstVisitor(info->zone());
3331 if (FLAG_hydrogen_track_positions) {
3332 SetSourcePosition(info->shared_info()->start_position());
3337 HBasicBlock* HOptimizedGraphBuilder::CreateJoin(HBasicBlock* first,
3338 HBasicBlock* second,
3339 BailoutId join_id) {
3340 if (first == NULL) {
3342 } else if (second == NULL) {
3345 HBasicBlock* join_block = graph()->CreateBasicBlock();
3346 Goto(first, join_block);
3347 Goto(second, join_block);
3348 join_block->SetJoinId(join_id);
3354 HBasicBlock* HOptimizedGraphBuilder::JoinContinue(IterationStatement* statement,
3355 HBasicBlock* exit_block,
3356 HBasicBlock* continue_block) {
3357 if (continue_block != NULL) {
3358 if (exit_block != NULL) Goto(exit_block, continue_block);
3359 continue_block->SetJoinId(statement->ContinueId());
3360 return continue_block;
3366 HBasicBlock* HOptimizedGraphBuilder::CreateLoop(IterationStatement* statement,
3367 HBasicBlock* loop_entry,
3368 HBasicBlock* body_exit,
3369 HBasicBlock* loop_successor,
3370 HBasicBlock* break_block) {
3371 if (body_exit != NULL) Goto(body_exit, loop_entry);
3372 loop_entry->PostProcessLoopHeader(statement);
3373 if (break_block != NULL) {
3374 if (loop_successor != NULL) Goto(loop_successor, break_block);
3375 break_block->SetJoinId(statement->ExitId());
3378 return loop_successor;
3382 // Build a new loop header block and set it as the current block.
3383 HBasicBlock* HOptimizedGraphBuilder::BuildLoopEntry() {
3384 HBasicBlock* loop_entry = CreateLoopHeaderBlock();
3386 set_current_block(loop_entry);
3391 HBasicBlock* HOptimizedGraphBuilder::BuildLoopEntry(
3392 IterationStatement* statement) {
3393 HBasicBlock* loop_entry = osr()->HasOsrEntryAt(statement)
3394 ? osr()->BuildOsrLoopEntry(statement)
3400 void HBasicBlock::FinishExit(HControlInstruction* instruction,
3401 HSourcePosition position) {
3402 Finish(instruction, position);
3407 OStream& operator<<(OStream& os, const HBasicBlock& b) {
3408 return os << "B" << b.block_id();
3412 HGraph::HGraph(CompilationInfo* info)
3413 : isolate_(info->isolate()),
3416 blocks_(8, info->zone()),
3417 values_(16, info->zone()),
3419 uint32_instructions_(NULL),
3422 zone_(info->zone()),
3423 is_recursive_(false),
3424 use_optimistic_licm_(false),
3425 depends_on_empty_array_proto_elements_(false),
3426 type_change_checksum_(0),
3427 maximum_environment_size_(0),
3428 no_side_effects_scope_count_(0),
3429 disallow_adding_new_values_(false),
3431 inlined_functions_(5, info->zone()) {
3432 if (info->IsStub()) {
3433 HydrogenCodeStub* stub = info->code_stub();
3434 CodeStubInterfaceDescriptor* descriptor = stub->GetInterfaceDescriptor();
3435 start_environment_ = new(zone_) HEnvironment(
3436 zone_, descriptor->GetEnvironmentParameterCount());
3438 TraceInlinedFunction(info->shared_info(), HSourcePosition::Unknown());
3439 start_environment_ =
3440 new(zone_) HEnvironment(NULL, info->scope(), info->closure(), zone_);
3442 start_environment_->set_ast_id(BailoutId::FunctionEntry());
3443 entry_block_ = CreateBasicBlock();
3444 entry_block_->SetInitialEnvironment(start_environment_);
3448 HBasicBlock* HGraph::CreateBasicBlock() {
3449 HBasicBlock* result = new(zone()) HBasicBlock(this);
3450 blocks_.Add(result, zone());
3455 void HGraph::FinalizeUniqueness() {
3456 DisallowHeapAllocation no_gc;
3457 DCHECK(!OptimizingCompilerThread::IsOptimizerThread(isolate()));
3458 for (int i = 0; i < blocks()->length(); ++i) {
3459 for (HInstructionIterator it(blocks()->at(i)); !it.Done(); it.Advance()) {
3460 it.Current()->FinalizeUniqueness();
3466 int HGraph::TraceInlinedFunction(
3467 Handle<SharedFunctionInfo> shared,
3468 HSourcePosition position) {
3469 if (!FLAG_hydrogen_track_positions) {
3474 for (; id < inlined_functions_.length(); id++) {
3475 if (inlined_functions_[id].shared().is_identical_to(shared)) {
3480 if (id == inlined_functions_.length()) {
3481 inlined_functions_.Add(InlinedFunctionInfo(shared), zone());
3483 if (!shared->script()->IsUndefined()) {
3484 Handle<Script> script(Script::cast(shared->script()));
3485 if (!script->source()->IsUndefined()) {
3486 CodeTracer::Scope tracing_scopex(isolate()->GetCodeTracer());
3487 OFStream os(tracing_scopex.file());
3488 os << "--- FUNCTION SOURCE (" << shared->DebugName()->ToCString().get()
3489 << ") id{" << info()->optimization_id() << "," << id << "} ---\n";
3491 ConsStringIteratorOp op;
3492 StringCharacterStream stream(String::cast(script->source()),
3494 shared->start_position());
3495 // fun->end_position() points to the last character in the stream. We
3496 // need to compensate by adding one to calculate the length.
3498 shared->end_position() - shared->start_position() + 1;
3499 for (int i = 0; i < source_len; i++) {
3500 if (stream.HasMore()) {
3501 os << AsUC16(stream.GetNext());
3506 os << "\n--- END ---\n";
3511 int inline_id = next_inline_id_++;
3513 if (inline_id != 0) {
3514 CodeTracer::Scope tracing_scope(isolate()->GetCodeTracer());
3515 OFStream os(tracing_scope.file());
3516 os << "INLINE (" << shared->DebugName()->ToCString().get() << ") id{"
3517 << info()->optimization_id() << "," << id << "} AS " << inline_id
3518 << " AT " << position << endl;
3525 int HGraph::SourcePositionToScriptPosition(HSourcePosition pos) {
3526 if (!FLAG_hydrogen_track_positions || pos.IsUnknown()) {
3530 return inlined_functions_[pos.inlining_id()].start_position() +
3535 // Block ordering was implemented with two mutually recursive methods,
3536 // HGraph::Postorder and HGraph::PostorderLoopBlocks.
3537 // The recursion could lead to stack overflow so the algorithm has been
3538 // implemented iteratively.
3539 // At a high level the algorithm looks like this:
3541 // Postorder(block, loop_header) : {
3542 // if (block has already been visited or is of another loop) return;
3543 // mark block as visited;
3544 // if (block is a loop header) {
3545 // VisitLoopMembers(block, loop_header);
3546 // VisitSuccessorsOfLoopHeader(block);
3548 // VisitSuccessors(block)
3550 // put block in result list;
3553 // VisitLoopMembers(block, outer_loop_header) {
3554 // foreach (block b in block loop members) {
3555 // VisitSuccessorsOfLoopMember(b, outer_loop_header);
3556 // if (b is loop header) VisitLoopMembers(b);
3560 // VisitSuccessorsOfLoopMember(block, outer_loop_header) {
3561 // foreach (block b in block successors) Postorder(b, outer_loop_header)
3564 // VisitSuccessorsOfLoopHeader(block) {
3565 // foreach (block b in block successors) Postorder(b, block)
3568 // VisitSuccessors(block, loop_header) {
3569 // foreach (block b in block successors) Postorder(b, loop_header)
3572 // The ordering is started calling Postorder(entry, NULL).
3574 // Each instance of PostorderProcessor represents the "stack frame" of the
3575 // recursion, and particularly keeps the state of the loop (iteration) of the
3576 // "Visit..." function it represents.
3577 // To recycle memory we keep all the frames in a double linked list but
3578 // this means that we cannot use constructors to initialize the frames.
3580 class PostorderProcessor : public ZoneObject {
3582 // Back link (towards the stack bottom).
3583 PostorderProcessor* parent() {return father_; }
3584 // Forward link (towards the stack top).
3585 PostorderProcessor* child() {return child_; }
3586 HBasicBlock* block() { return block_; }
3587 HLoopInformation* loop() { return loop_; }
3588 HBasicBlock* loop_header() { return loop_header_; }
3590 static PostorderProcessor* CreateEntryProcessor(Zone* zone,
3591 HBasicBlock* block) {
3592 PostorderProcessor* result = new(zone) PostorderProcessor(NULL);
3593 return result->SetupSuccessors(zone, block, NULL);
3596 PostorderProcessor* PerformStep(Zone* zone,
3597 ZoneList<HBasicBlock*>* order) {
3598 PostorderProcessor* next =
3599 PerformNonBacktrackingStep(zone, order);
3603 return Backtrack(zone, order);
3608 explicit PostorderProcessor(PostorderProcessor* father)
3609 : father_(father), child_(NULL), successor_iterator(NULL) { }
3611 // Each enum value states the cycle whose state is kept by this instance.
3615 SUCCESSORS_OF_LOOP_HEADER,
3617 SUCCESSORS_OF_LOOP_MEMBER
3620 // Each "Setup..." method is like a constructor for a cycle state.
3621 PostorderProcessor* SetupSuccessors(Zone* zone,
3623 HBasicBlock* loop_header) {
3624 if (block == NULL || block->IsOrdered() ||
3625 block->parent_loop_header() != loop_header) {
3629 loop_header_ = NULL;
3634 block->MarkAsOrdered();
3636 if (block->IsLoopHeader()) {
3637 kind_ = SUCCESSORS_OF_LOOP_HEADER;
3638 loop_header_ = block;
3639 InitializeSuccessors();
3640 PostorderProcessor* result = Push(zone);
3641 return result->SetupLoopMembers(zone, block, block->loop_information(),
3644 DCHECK(block->IsFinished());
3646 loop_header_ = loop_header;
3647 InitializeSuccessors();
3653 PostorderProcessor* SetupLoopMembers(Zone* zone,
3655 HLoopInformation* loop,
3656 HBasicBlock* loop_header) {
3657 kind_ = LOOP_MEMBERS;
3660 loop_header_ = loop_header;
3661 InitializeLoopMembers();
3665 PostorderProcessor* SetupSuccessorsOfLoopMember(
3667 HLoopInformation* loop,
3668 HBasicBlock* loop_header) {
3669 kind_ = SUCCESSORS_OF_LOOP_MEMBER;
3672 loop_header_ = loop_header;
3673 InitializeSuccessors();
3677 // This method "allocates" a new stack frame.
3678 PostorderProcessor* Push(Zone* zone) {
3679 if (child_ == NULL) {
3680 child_ = new(zone) PostorderProcessor(this);
3685 void ClosePostorder(ZoneList<HBasicBlock*>* order, Zone* zone) {
3686 DCHECK(block_->end()->FirstSuccessor() == NULL ||
3687 order->Contains(block_->end()->FirstSuccessor()) ||
3688 block_->end()->FirstSuccessor()->IsLoopHeader());
3689 DCHECK(block_->end()->SecondSuccessor() == NULL ||
3690 order->Contains(block_->end()->SecondSuccessor()) ||
3691 block_->end()->SecondSuccessor()->IsLoopHeader());
3692 order->Add(block_, zone);
3695 // This method is the basic block to walk up the stack.
3696 PostorderProcessor* Pop(Zone* zone,
3697 ZoneList<HBasicBlock*>* order) {
3700 case SUCCESSORS_OF_LOOP_HEADER:
3701 ClosePostorder(order, zone);
3705 case SUCCESSORS_OF_LOOP_MEMBER:
3706 if (block()->IsLoopHeader() && block() != loop_->loop_header()) {
3707 // In this case we need to perform a LOOP_MEMBERS cycle so we
3708 // initialize it and return this instead of father.
3709 return SetupLoopMembers(zone, block(),
3710 block()->loop_information(), loop_header_);
3721 // Walks up the stack.
3722 PostorderProcessor* Backtrack(Zone* zone,
3723 ZoneList<HBasicBlock*>* order) {
3724 PostorderProcessor* parent = Pop(zone, order);
3725 while (parent != NULL) {
3726 PostorderProcessor* next =
3727 parent->PerformNonBacktrackingStep(zone, order);
3731 parent = parent->Pop(zone, order);
3737 PostorderProcessor* PerformNonBacktrackingStep(
3739 ZoneList<HBasicBlock*>* order) {
3740 HBasicBlock* next_block;
3743 next_block = AdvanceSuccessors();
3744 if (next_block != NULL) {
3745 PostorderProcessor* result = Push(zone);
3746 return result->SetupSuccessors(zone, next_block, loop_header_);
3749 case SUCCESSORS_OF_LOOP_HEADER:
3750 next_block = AdvanceSuccessors();
3751 if (next_block != NULL) {
3752 PostorderProcessor* result = Push(zone);
3753 return result->SetupSuccessors(zone, next_block, block());
3757 next_block = AdvanceLoopMembers();
3758 if (next_block != NULL) {
3759 PostorderProcessor* result = Push(zone);
3760 return result->SetupSuccessorsOfLoopMember(next_block,
3761 loop_, loop_header_);
3764 case SUCCESSORS_OF_LOOP_MEMBER:
3765 next_block = AdvanceSuccessors();
3766 if (next_block != NULL) {
3767 PostorderProcessor* result = Push(zone);
3768 return result->SetupSuccessors(zone, next_block, loop_header_);
3777 // The following two methods implement a "foreach b in successors" cycle.
3778 void InitializeSuccessors() {
3781 successor_iterator = HSuccessorIterator(block_->end());
3784 HBasicBlock* AdvanceSuccessors() {
3785 if (!successor_iterator.Done()) {
3786 HBasicBlock* result = successor_iterator.Current();
3787 successor_iterator.Advance();
3793 // The following two methods implement a "foreach b in loop members" cycle.
3794 void InitializeLoopMembers() {
3796 loop_length = loop_->blocks()->length();
3799 HBasicBlock* AdvanceLoopMembers() {
3800 if (loop_index < loop_length) {
3801 HBasicBlock* result = loop_->blocks()->at(loop_index);
3810 PostorderProcessor* father_;
3811 PostorderProcessor* child_;
3812 HLoopInformation* loop_;
3813 HBasicBlock* block_;
3814 HBasicBlock* loop_header_;
3817 HSuccessorIterator successor_iterator;
3821 void HGraph::OrderBlocks() {
3822 CompilationPhase phase("H_Block ordering", info());
3825 // Initially the blocks must not be ordered.
3826 for (int i = 0; i < blocks_.length(); ++i) {
3827 DCHECK(!blocks_[i]->IsOrdered());
3831 PostorderProcessor* postorder =
3832 PostorderProcessor::CreateEntryProcessor(zone(), blocks_[0]);
3835 postorder = postorder->PerformStep(zone(), &blocks_);
3839 // Now all blocks must be marked as ordered.
3840 for (int i = 0; i < blocks_.length(); ++i) {
3841 DCHECK(blocks_[i]->IsOrdered());
3845 // Reverse block list and assign block IDs.
3846 for (int i = 0, j = blocks_.length(); --j >= i; ++i) {
3847 HBasicBlock* bi = blocks_[i];
3848 HBasicBlock* bj = blocks_[j];
3849 bi->set_block_id(j);
3850 bj->set_block_id(i);
3857 void HGraph::AssignDominators() {
3858 HPhase phase("H_Assign dominators", this);
3859 for (int i = 0; i < blocks_.length(); ++i) {
3860 HBasicBlock* block = blocks_[i];
3861 if (block->IsLoopHeader()) {
3862 // Only the first predecessor of a loop header is from outside the loop.
3863 // All others are back edges, and thus cannot dominate the loop header.
3864 block->AssignCommonDominator(block->predecessors()->first());
3865 block->AssignLoopSuccessorDominators();
3867 for (int j = blocks_[i]->predecessors()->length() - 1; j >= 0; --j) {
3868 blocks_[i]->AssignCommonDominator(blocks_[i]->predecessors()->at(j));
3875 bool HGraph::CheckArgumentsPhiUses() {
3876 int block_count = blocks_.length();
3877 for (int i = 0; i < block_count; ++i) {
3878 for (int j = 0; j < blocks_[i]->phis()->length(); ++j) {
3879 HPhi* phi = blocks_[i]->phis()->at(j);
3880 // We don't support phi uses of arguments for now.
3881 if (phi->CheckFlag(HValue::kIsArguments)) return false;
3888 bool HGraph::CheckConstPhiUses() {
3889 int block_count = blocks_.length();
3890 for (int i = 0; i < block_count; ++i) {
3891 for (int j = 0; j < blocks_[i]->phis()->length(); ++j) {
3892 HPhi* phi = blocks_[i]->phis()->at(j);
3893 // Check for the hole value (from an uninitialized const).
3894 for (int k = 0; k < phi->OperandCount(); k++) {
3895 if (phi->OperandAt(k) == GetConstantHole()) return false;
3903 void HGraph::CollectPhis() {
3904 int block_count = blocks_.length();
3905 phi_list_ = new(zone()) ZoneList<HPhi*>(block_count, zone());
3906 for (int i = 0; i < block_count; ++i) {
3907 for (int j = 0; j < blocks_[i]->phis()->length(); ++j) {
3908 HPhi* phi = blocks_[i]->phis()->at(j);
3909 phi_list_->Add(phi, zone());
3915 // Implementation of utility class to encapsulate the translation state for
3916 // a (possibly inlined) function.
3917 FunctionState::FunctionState(HOptimizedGraphBuilder* owner,
3918 CompilationInfo* info,
3919 InliningKind inlining_kind,
3922 compilation_info_(info),
3923 call_context_(NULL),
3924 inlining_kind_(inlining_kind),
3925 function_return_(NULL),
3926 test_context_(NULL),
3928 arguments_object_(NULL),
3929 arguments_elements_(NULL),
3930 inlining_id_(inlining_id),
3931 outer_source_position_(HSourcePosition::Unknown()),
3932 outer_(owner->function_state()) {
3933 if (outer_ != NULL) {
3934 // State for an inline function.
3935 if (owner->ast_context()->IsTest()) {
3936 HBasicBlock* if_true = owner->graph()->CreateBasicBlock();
3937 HBasicBlock* if_false = owner->graph()->CreateBasicBlock();
3938 if_true->MarkAsInlineReturnTarget(owner->current_block());
3939 if_false->MarkAsInlineReturnTarget(owner->current_block());
3940 TestContext* outer_test_context = TestContext::cast(owner->ast_context());
3941 Expression* cond = outer_test_context->condition();
3942 // The AstContext constructor pushed on the context stack. This newed
3943 // instance is the reason that AstContext can't be BASE_EMBEDDED.
3944 test_context_ = new TestContext(owner, cond, if_true, if_false);
3946 function_return_ = owner->graph()->CreateBasicBlock();
3947 function_return()->MarkAsInlineReturnTarget(owner->current_block());
3949 // Set this after possibly allocating a new TestContext above.
3950 call_context_ = owner->ast_context();
3953 // Push on the state stack.
3954 owner->set_function_state(this);
3956 if (FLAG_hydrogen_track_positions) {
3957 outer_source_position_ = owner->source_position();
3958 owner->EnterInlinedSource(
3959 info->shared_info()->start_position(),
3961 owner->SetSourcePosition(info->shared_info()->start_position());
3966 FunctionState::~FunctionState() {
3967 delete test_context_;
3968 owner_->set_function_state(outer_);
3970 if (FLAG_hydrogen_track_positions) {
3971 owner_->set_source_position(outer_source_position_);
3972 owner_->EnterInlinedSource(
3973 outer_->compilation_info()->shared_info()->start_position(),
3974 outer_->inlining_id());
3979 // Implementation of utility classes to represent an expression's context in
3981 AstContext::AstContext(HOptimizedGraphBuilder* owner, Expression::Context kind)
3984 outer_(owner->ast_context()),
3985 for_typeof_(false) {
3986 owner->set_ast_context(this); // Push.
3988 DCHECK(owner->environment()->frame_type() == JS_FUNCTION);
3989 original_length_ = owner->environment()->length();
3994 AstContext::~AstContext() {
3995 owner_->set_ast_context(outer_); // Pop.
3999 EffectContext::~EffectContext() {
4000 DCHECK(owner()->HasStackOverflow() ||
4001 owner()->current_block() == NULL ||
4002 (owner()->environment()->length() == original_length_ &&
4003 owner()->environment()->frame_type() == JS_FUNCTION));
4007 ValueContext::~ValueContext() {
4008 DCHECK(owner()->HasStackOverflow() ||
4009 owner()->current_block() == NULL ||
4010 (owner()->environment()->length() == original_length_ + 1 &&
4011 owner()->environment()->frame_type() == JS_FUNCTION));
4015 void EffectContext::ReturnValue(HValue* value) {
4016 // The value is simply ignored.
4020 void ValueContext::ReturnValue(HValue* value) {
4021 // The value is tracked in the bailout environment, and communicated
4022 // through the environment as the result of the expression.
4023 if (!arguments_allowed() && value->CheckFlag(HValue::kIsArguments)) {
4024 owner()->Bailout(kBadValueContextForArgumentsValue);
4026 owner()->Push(value);
4030 void TestContext::ReturnValue(HValue* value) {
4035 void EffectContext::ReturnInstruction(HInstruction* instr, BailoutId ast_id) {
4036 DCHECK(!instr->IsControlInstruction());
4037 owner()->AddInstruction(instr);
4038 if (instr->HasObservableSideEffects()) {
4039 owner()->Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
4044 void EffectContext::ReturnControl(HControlInstruction* instr,
4046 DCHECK(!instr->HasObservableSideEffects());
4047 HBasicBlock* empty_true = owner()->graph()->CreateBasicBlock();
4048 HBasicBlock* empty_false = owner()->graph()->CreateBasicBlock();
4049 instr->SetSuccessorAt(0, empty_true);
4050 instr->SetSuccessorAt(1, empty_false);
4051 owner()->FinishCurrentBlock(instr);
4052 HBasicBlock* join = owner()->CreateJoin(empty_true, empty_false, ast_id);
4053 owner()->set_current_block(join);
4057 void EffectContext::ReturnContinuation(HIfContinuation* continuation,
4059 HBasicBlock* true_branch = NULL;
4060 HBasicBlock* false_branch = NULL;
4061 continuation->Continue(&true_branch, &false_branch);
4062 if (!continuation->IsTrueReachable()) {
4063 owner()->set_current_block(false_branch);
4064 } else if (!continuation->IsFalseReachable()) {
4065 owner()->set_current_block(true_branch);
4067 HBasicBlock* join = owner()->CreateJoin(true_branch, false_branch, ast_id);
4068 owner()->set_current_block(join);
4073 void ValueContext::ReturnInstruction(HInstruction* instr, BailoutId ast_id) {
4074 DCHECK(!instr->IsControlInstruction());
4075 if (!arguments_allowed() && instr->CheckFlag(HValue::kIsArguments)) {
4076 return owner()->Bailout(kBadValueContextForArgumentsObjectValue);
4078 owner()->AddInstruction(instr);
4079 owner()->Push(instr);
4080 if (instr->HasObservableSideEffects()) {
4081 owner()->Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
4086 void ValueContext::ReturnControl(HControlInstruction* instr, BailoutId ast_id) {
4087 DCHECK(!instr->HasObservableSideEffects());
4088 if (!arguments_allowed() && instr->CheckFlag(HValue::kIsArguments)) {
4089 return owner()->Bailout(kBadValueContextForArgumentsObjectValue);
4091 HBasicBlock* materialize_false = owner()->graph()->CreateBasicBlock();
4092 HBasicBlock* materialize_true = owner()->graph()->CreateBasicBlock();
4093 instr->SetSuccessorAt(0, materialize_true);
4094 instr->SetSuccessorAt(1, materialize_false);
4095 owner()->FinishCurrentBlock(instr);
4096 owner()->set_current_block(materialize_true);
4097 owner()->Push(owner()->graph()->GetConstantTrue());
4098 owner()->set_current_block(materialize_false);
4099 owner()->Push(owner()->graph()->GetConstantFalse());
4101 owner()->CreateJoin(materialize_true, materialize_false, ast_id);
4102 owner()->set_current_block(join);
4106 void ValueContext::ReturnContinuation(HIfContinuation* continuation,
4108 HBasicBlock* materialize_true = NULL;
4109 HBasicBlock* materialize_false = NULL;
4110 continuation->Continue(&materialize_true, &materialize_false);
4111 if (continuation->IsTrueReachable()) {
4112 owner()->set_current_block(materialize_true);
4113 owner()->Push(owner()->graph()->GetConstantTrue());
4114 owner()->set_current_block(materialize_true);
4116 if (continuation->IsFalseReachable()) {
4117 owner()->set_current_block(materialize_false);
4118 owner()->Push(owner()->graph()->GetConstantFalse());
4119 owner()->set_current_block(materialize_false);
4121 if (continuation->TrueAndFalseReachable()) {
4123 owner()->CreateJoin(materialize_true, materialize_false, ast_id);
4124 owner()->set_current_block(join);
4129 void TestContext::ReturnInstruction(HInstruction* instr, BailoutId ast_id) {
4130 DCHECK(!instr->IsControlInstruction());
4131 HOptimizedGraphBuilder* builder = owner();
4132 builder->AddInstruction(instr);
4133 // We expect a simulate after every expression with side effects, though
4134 // this one isn't actually needed (and wouldn't work if it were targeted).
4135 if (instr->HasObservableSideEffects()) {
4136 builder->Push(instr);
4137 builder->Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
4144 void TestContext::ReturnControl(HControlInstruction* instr, BailoutId ast_id) {
4145 DCHECK(!instr->HasObservableSideEffects());
4146 HBasicBlock* empty_true = owner()->graph()->CreateBasicBlock();
4147 HBasicBlock* empty_false = owner()->graph()->CreateBasicBlock();
4148 instr->SetSuccessorAt(0, empty_true);
4149 instr->SetSuccessorAt(1, empty_false);
4150 owner()->FinishCurrentBlock(instr);
4151 owner()->Goto(empty_true, if_true(), owner()->function_state());
4152 owner()->Goto(empty_false, if_false(), owner()->function_state());
4153 owner()->set_current_block(NULL);
4157 void TestContext::ReturnContinuation(HIfContinuation* continuation,
4159 HBasicBlock* true_branch = NULL;
4160 HBasicBlock* false_branch = NULL;
4161 continuation->Continue(&true_branch, &false_branch);
4162 if (continuation->IsTrueReachable()) {
4163 owner()->Goto(true_branch, if_true(), owner()->function_state());
4165 if (continuation->IsFalseReachable()) {
4166 owner()->Goto(false_branch, if_false(), owner()->function_state());
4168 owner()->set_current_block(NULL);
4172 void TestContext::BuildBranch(HValue* value) {
4173 // We expect the graph to be in edge-split form: there is no edge that
4174 // connects a branch node to a join node. We conservatively ensure that
4175 // property by always adding an empty block on the outgoing edges of this
4177 HOptimizedGraphBuilder* builder = owner();
4178 if (value != NULL && value->CheckFlag(HValue::kIsArguments)) {
4179 builder->Bailout(kArgumentsObjectValueInATestContext);
4181 ToBooleanStub::Types expected(condition()->to_boolean_types());
4182 ReturnControl(owner()->New<HBranch>(value, expected), BailoutId::None());
4186 // HOptimizedGraphBuilder infrastructure for bailing out and checking bailouts.
4187 #define CHECK_BAILOUT(call) \
4190 if (HasStackOverflow()) return; \
4194 #define CHECK_ALIVE(call) \
4197 if (HasStackOverflow() || current_block() == NULL) return; \
4201 #define CHECK_ALIVE_OR_RETURN(call, value) \
4204 if (HasStackOverflow() || current_block() == NULL) return value; \
4208 void HOptimizedGraphBuilder::Bailout(BailoutReason reason) {
4209 current_info()->set_bailout_reason(reason);
4214 void HOptimizedGraphBuilder::VisitForEffect(Expression* expr) {
4215 EffectContext for_effect(this);
4220 void HOptimizedGraphBuilder::VisitForValue(Expression* expr,
4221 ArgumentsAllowedFlag flag) {
4222 ValueContext for_value(this, flag);
4227 void HOptimizedGraphBuilder::VisitForTypeOf(Expression* expr) {
4228 ValueContext for_value(this, ARGUMENTS_NOT_ALLOWED);
4229 for_value.set_for_typeof(true);
4234 void HOptimizedGraphBuilder::VisitForControl(Expression* expr,
4235 HBasicBlock* true_block,
4236 HBasicBlock* false_block) {
4237 TestContext for_test(this, expr, true_block, false_block);
4242 void HOptimizedGraphBuilder::VisitExpressions(
4243 ZoneList<Expression*>* exprs) {
4244 for (int i = 0; i < exprs->length(); ++i) {
4245 CHECK_ALIVE(VisitForValue(exprs->at(i)));
4250 bool HOptimizedGraphBuilder::BuildGraph() {
4251 if (current_info()->function()->is_generator()) {
4252 Bailout(kFunctionIsAGenerator);
4255 Scope* scope = current_info()->scope();
4256 if (scope->HasIllegalRedeclaration()) {
4257 Bailout(kFunctionWithIllegalRedeclaration);
4260 if (scope->calls_eval()) {
4261 Bailout(kFunctionCallsEval);
4266 // Add an edge to the body entry. This is warty: the graph's start
4267 // environment will be used by the Lithium translation as the initial
4268 // environment on graph entry, but it has now been mutated by the
4269 // Hydrogen translation of the instructions in the start block. This
4270 // environment uses values which have not been defined yet. These
4271 // Hydrogen instructions will then be replayed by the Lithium
4272 // translation, so they cannot have an environment effect. The edge to
4273 // the body's entry block (along with some special logic for the start
4274 // block in HInstruction::InsertAfter) seals the start block from
4275 // getting unwanted instructions inserted.
4277 // TODO(kmillikin): Fix this. Stop mutating the initial environment.
4278 // Make the Hydrogen instructions in the initial block into Hydrogen
4279 // values (but not instructions), present in the initial environment and
4280 // not replayed by the Lithium translation.
4281 HEnvironment* initial_env = environment()->CopyWithoutHistory();
4282 HBasicBlock* body_entry = CreateBasicBlock(initial_env);
4284 body_entry->SetJoinId(BailoutId::FunctionEntry());
4285 set_current_block(body_entry);
4287 // Handle implicit declaration of the function name in named function
4288 // expressions before other declarations.
4289 if (scope->is_function_scope() && scope->function() != NULL) {
4290 VisitVariableDeclaration(scope->function());
4292 VisitDeclarations(scope->declarations());
4293 Add<HSimulate>(BailoutId::Declarations());
4295 Add<HStackCheck>(HStackCheck::kFunctionEntry);
4297 VisitStatements(current_info()->function()->body());
4298 if (HasStackOverflow()) return false;
4300 if (current_block() != NULL) {
4301 Add<HReturn>(graph()->GetConstantUndefined());
4302 set_current_block(NULL);
4305 // If the checksum of the number of type info changes is the same as the
4306 // last time this function was compiled, then this recompile is likely not
4307 // due to missing/inadequate type feedback, but rather too aggressive
4308 // optimization. Disable optimistic LICM in that case.
4309 Handle<Code> unoptimized_code(current_info()->shared_info()->code());
4310 DCHECK(unoptimized_code->kind() == Code::FUNCTION);
4311 Handle<TypeFeedbackInfo> type_info(
4312 TypeFeedbackInfo::cast(unoptimized_code->type_feedback_info()));
4313 int checksum = type_info->own_type_change_checksum();
4314 int composite_checksum = graph()->update_type_change_checksum(checksum);
4315 graph()->set_use_optimistic_licm(
4316 !type_info->matches_inlined_type_change_checksum(composite_checksum));
4317 type_info->set_inlined_type_change_checksum(composite_checksum);
4319 // Perform any necessary OSR-specific cleanups or changes to the graph.
4320 osr()->FinishGraph();
4326 bool HGraph::Optimize(BailoutReason* bailout_reason) {
4330 // We need to create a HConstant "zero" now so that GVN will fold every
4331 // zero-valued constant in the graph together.
4332 // The constant is needed to make idef-based bounds check work: the pass
4333 // evaluates relations with "zero" and that zero cannot be created after GVN.
4337 // Do a full verify after building the graph and computing dominators.
4341 if (FLAG_analyze_environment_liveness && maximum_environment_size() != 0) {
4342 Run<HEnvironmentLivenessAnalysisPhase>();
4345 if (!CheckConstPhiUses()) {
4346 *bailout_reason = kUnsupportedPhiUseOfConstVariable;
4349 Run<HRedundantPhiEliminationPhase>();
4350 if (!CheckArgumentsPhiUses()) {
4351 *bailout_reason = kUnsupportedPhiUseOfArguments;
4355 // Find and mark unreachable code to simplify optimizations, especially gvn,
4356 // where unreachable code could unnecessarily defeat LICM.
4357 Run<HMarkUnreachableBlocksPhase>();
4359 if (FLAG_dead_code_elimination) Run<HDeadCodeEliminationPhase>();
4360 if (FLAG_use_escape_analysis) Run<HEscapeAnalysisPhase>();
4362 if (FLAG_load_elimination) Run<HLoadEliminationPhase>();
4366 if (has_osr()) osr()->FinishOsrValues();
4368 Run<HInferRepresentationPhase>();
4370 // Remove HSimulate instructions that have turned out not to be needed
4371 // after all by folding them into the following HSimulate.
4372 // This must happen after inferring representations.
4373 Run<HMergeRemovableSimulatesPhase>();
4375 Run<HMarkDeoptimizeOnUndefinedPhase>();
4376 Run<HRepresentationChangesPhase>();
4378 Run<HInferTypesPhase>();
4380 // Must be performed before canonicalization to ensure that Canonicalize
4381 // will not remove semantically meaningful ToInt32 operations e.g. BIT_OR with
4383 if (FLAG_opt_safe_uint32_operations) Run<HUint32AnalysisPhase>();
4385 if (FLAG_use_canonicalizing) Run<HCanonicalizePhase>();
4387 if (FLAG_use_gvn) Run<HGlobalValueNumberingPhase>();
4389 if (FLAG_check_elimination) Run<HCheckEliminationPhase>();
4391 if (FLAG_store_elimination) Run<HStoreEliminationPhase>();
4393 Run<HRangeAnalysisPhase>();
4395 Run<HComputeChangeUndefinedToNaN>();
4397 // Eliminate redundant stack checks on backwards branches.
4398 Run<HStackCheckEliminationPhase>();
4400 if (FLAG_array_bounds_checks_elimination) Run<HBoundsCheckEliminationPhase>();
4401 if (FLAG_array_bounds_checks_hoisting) Run<HBoundsCheckHoistingPhase>();
4402 if (FLAG_array_index_dehoisting) Run<HDehoistIndexComputationsPhase>();
4403 if (FLAG_dead_code_elimination) Run<HDeadCodeEliminationPhase>();
4405 RestoreActualValues();
4407 // Find unreachable code a second time, GVN and other optimizations may have
4408 // made blocks unreachable that were previously reachable.
4409 Run<HMarkUnreachableBlocksPhase>();
4415 void HGraph::RestoreActualValues() {
4416 HPhase phase("H_Restore actual values", this);
4418 for (int block_index = 0; block_index < blocks()->length(); block_index++) {
4419 HBasicBlock* block = blocks()->at(block_index);
4422 for (int i = 0; i < block->phis()->length(); i++) {
4423 HPhi* phi = block->phis()->at(i);
4424 DCHECK(phi->ActualValue() == phi);
4428 for (HInstructionIterator it(block); !it.Done(); it.Advance()) {
4429 HInstruction* instruction = it.Current();
4430 if (instruction->ActualValue() == instruction) continue;
4431 if (instruction->CheckFlag(HValue::kIsDead)) {
4432 // The instruction was marked as deleted but left in the graph
4433 // as a control flow dependency point for subsequent
4435 instruction->DeleteAndReplaceWith(instruction->ActualValue());
4437 DCHECK(instruction->IsInformativeDefinition());
4438 if (instruction->IsPurelyInformativeDefinition()) {
4439 instruction->DeleteAndReplaceWith(instruction->RedefinedOperand());
4441 instruction->ReplaceAllUsesWith(instruction->ActualValue());
4449 void HOptimizedGraphBuilder::PushArgumentsFromEnvironment(int count) {
4450 ZoneList<HValue*> arguments(count, zone());
4451 for (int i = 0; i < count; ++i) {
4452 arguments.Add(Pop(), zone());
4455 HPushArguments* push_args = New<HPushArguments>();
4456 while (!arguments.is_empty()) {
4457 push_args->AddInput(arguments.RemoveLast());
4459 AddInstruction(push_args);
4463 template <class Instruction>
4464 HInstruction* HOptimizedGraphBuilder::PreProcessCall(Instruction* call) {
4465 PushArgumentsFromEnvironment(call->argument_count());
4470 void HOptimizedGraphBuilder::SetUpScope(Scope* scope) {
4471 // First special is HContext.
4472 HInstruction* context = Add<HContext>();
4473 environment()->BindContext(context);
4475 // Create an arguments object containing the initial parameters. Set the
4476 // initial values of parameters including "this" having parameter index 0.
4477 DCHECK_EQ(scope->num_parameters() + 1, environment()->parameter_count());
4478 HArgumentsObject* arguments_object =
4479 New<HArgumentsObject>(environment()->parameter_count());
4480 for (int i = 0; i < environment()->parameter_count(); ++i) {
4481 HInstruction* parameter = Add<HParameter>(i);
4482 arguments_object->AddArgument(parameter, zone());
4483 environment()->Bind(i, parameter);
4485 AddInstruction(arguments_object);
4486 graph()->SetArgumentsObject(arguments_object);
4488 HConstant* undefined_constant = graph()->GetConstantUndefined();
4489 // Initialize specials and locals to undefined.
4490 for (int i = environment()->parameter_count() + 1;
4491 i < environment()->length();
4493 environment()->Bind(i, undefined_constant);
4496 // Handle the arguments and arguments shadow variables specially (they do
4497 // not have declarations).
4498 if (scope->arguments() != NULL) {
4499 if (!scope->arguments()->IsStackAllocated()) {
4500 return Bailout(kContextAllocatedArguments);
4503 environment()->Bind(scope->arguments(),
4504 graph()->GetArgumentsObject());
4509 void HOptimizedGraphBuilder::VisitStatements(ZoneList<Statement*>* statements) {
4510 for (int i = 0; i < statements->length(); i++) {
4511 Statement* stmt = statements->at(i);
4512 CHECK_ALIVE(Visit(stmt));
4513 if (stmt->IsJump()) break;
4518 void HOptimizedGraphBuilder::VisitBlock(Block* stmt) {
4519 DCHECK(!HasStackOverflow());
4520 DCHECK(current_block() != NULL);
4521 DCHECK(current_block()->HasPredecessor());
4523 Scope* outer_scope = scope();
4524 Scope* scope = stmt->scope();
4525 BreakAndContinueInfo break_info(stmt, outer_scope);
4527 { BreakAndContinueScope push(&break_info, this);
4528 if (scope != NULL) {
4529 // Load the function object.
4530 Scope* declaration_scope = scope->DeclarationScope();
4531 HInstruction* function;
4532 HValue* outer_context = environment()->context();
4533 if (declaration_scope->is_global_scope() ||
4534 declaration_scope->is_eval_scope()) {
4535 function = new(zone()) HLoadContextSlot(
4536 outer_context, Context::CLOSURE_INDEX, HLoadContextSlot::kNoCheck);
4538 function = New<HThisFunction>();
4540 AddInstruction(function);
4541 // Allocate a block context and store it to the stack frame.
4542 HInstruction* inner_context = Add<HAllocateBlockContext>(
4543 outer_context, function, scope->GetScopeInfo());
4544 HInstruction* instr = Add<HStoreFrameContext>(inner_context);
4545 if (instr->HasObservableSideEffects()) {
4546 AddSimulate(stmt->EntryId(), REMOVABLE_SIMULATE);
4549 environment()->BindContext(inner_context);
4550 VisitDeclarations(scope->declarations());
4551 AddSimulate(stmt->DeclsId(), REMOVABLE_SIMULATE);
4553 CHECK_BAILOUT(VisitStatements(stmt->statements()));
4555 set_scope(outer_scope);
4556 if (scope != NULL && current_block() != NULL) {
4557 HValue* inner_context = environment()->context();
4558 HValue* outer_context = Add<HLoadNamedField>(
4559 inner_context, static_cast<HValue*>(NULL),
4560 HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX));
4562 HInstruction* instr = Add<HStoreFrameContext>(outer_context);
4563 if (instr->HasObservableSideEffects()) {
4564 AddSimulate(stmt->ExitId(), REMOVABLE_SIMULATE);
4566 environment()->BindContext(outer_context);
4568 HBasicBlock* break_block = break_info.break_block();
4569 if (break_block != NULL) {
4570 if (current_block() != NULL) Goto(break_block);
4571 break_block->SetJoinId(stmt->ExitId());
4572 set_current_block(break_block);
4577 void HOptimizedGraphBuilder::VisitExpressionStatement(
4578 ExpressionStatement* stmt) {
4579 DCHECK(!HasStackOverflow());
4580 DCHECK(current_block() != NULL);
4581 DCHECK(current_block()->HasPredecessor());
4582 VisitForEffect(stmt->expression());
4586 void HOptimizedGraphBuilder::VisitEmptyStatement(EmptyStatement* stmt) {
4587 DCHECK(!HasStackOverflow());
4588 DCHECK(current_block() != NULL);
4589 DCHECK(current_block()->HasPredecessor());
4593 void HOptimizedGraphBuilder::VisitIfStatement(IfStatement* stmt) {
4594 DCHECK(!HasStackOverflow());
4595 DCHECK(current_block() != NULL);
4596 DCHECK(current_block()->HasPredecessor());
4597 if (stmt->condition()->ToBooleanIsTrue()) {
4598 Add<HSimulate>(stmt->ThenId());
4599 Visit(stmt->then_statement());
4600 } else if (stmt->condition()->ToBooleanIsFalse()) {
4601 Add<HSimulate>(stmt->ElseId());
4602 Visit(stmt->else_statement());
4604 HBasicBlock* cond_true = graph()->CreateBasicBlock();
4605 HBasicBlock* cond_false = graph()->CreateBasicBlock();
4606 CHECK_BAILOUT(VisitForControl(stmt->condition(), cond_true, cond_false));
4608 if (cond_true->HasPredecessor()) {
4609 cond_true->SetJoinId(stmt->ThenId());
4610 set_current_block(cond_true);
4611 CHECK_BAILOUT(Visit(stmt->then_statement()));
4612 cond_true = current_block();
4617 if (cond_false->HasPredecessor()) {
4618 cond_false->SetJoinId(stmt->ElseId());
4619 set_current_block(cond_false);
4620 CHECK_BAILOUT(Visit(stmt->else_statement()));
4621 cond_false = current_block();
4626 HBasicBlock* join = CreateJoin(cond_true, cond_false, stmt->IfId());
4627 set_current_block(join);
4632 HBasicBlock* HOptimizedGraphBuilder::BreakAndContinueScope::Get(
4633 BreakableStatement* stmt,
4638 BreakAndContinueScope* current = this;
4639 while (current != NULL && current->info()->target() != stmt) {
4640 *drop_extra += current->info()->drop_extra();
4641 current = current->next();
4643 DCHECK(current != NULL); // Always found (unless stack is malformed).
4644 *scope = current->info()->scope();
4646 if (type == BREAK) {
4647 *drop_extra += current->info()->drop_extra();
4650 HBasicBlock* block = NULL;
4653 block = current->info()->break_block();
4654 if (block == NULL) {
4655 block = current->owner()->graph()->CreateBasicBlock();
4656 current->info()->set_break_block(block);
4661 block = current->info()->continue_block();
4662 if (block == NULL) {
4663 block = current->owner()->graph()->CreateBasicBlock();
4664 current->info()->set_continue_block(block);
4673 void HOptimizedGraphBuilder::VisitContinueStatement(
4674 ContinueStatement* stmt) {
4675 DCHECK(!HasStackOverflow());
4676 DCHECK(current_block() != NULL);
4677 DCHECK(current_block()->HasPredecessor());
4678 Scope* outer_scope = NULL;
4679 Scope* inner_scope = scope();
4681 HBasicBlock* continue_block = break_scope()->Get(
4682 stmt->target(), BreakAndContinueScope::CONTINUE,
4683 &outer_scope, &drop_extra);
4684 HValue* context = environment()->context();
4686 int context_pop_count = inner_scope->ContextChainLength(outer_scope);
4687 if (context_pop_count > 0) {
4688 while (context_pop_count-- > 0) {
4689 HInstruction* context_instruction = Add<HLoadNamedField>(
4690 context, static_cast<HValue*>(NULL),
4691 HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX));
4692 context = context_instruction;
4694 HInstruction* instr = Add<HStoreFrameContext>(context);
4695 if (instr->HasObservableSideEffects()) {
4696 AddSimulate(stmt->target()->EntryId(), REMOVABLE_SIMULATE);
4698 environment()->BindContext(context);
4701 Goto(continue_block);
4702 set_current_block(NULL);
4706 void HOptimizedGraphBuilder::VisitBreakStatement(BreakStatement* stmt) {
4707 DCHECK(!HasStackOverflow());
4708 DCHECK(current_block() != NULL);
4709 DCHECK(current_block()->HasPredecessor());
4710 Scope* outer_scope = NULL;
4711 Scope* inner_scope = scope();
4713 HBasicBlock* break_block = break_scope()->Get(
4714 stmt->target(), BreakAndContinueScope::BREAK,
4715 &outer_scope, &drop_extra);
4716 HValue* context = environment()->context();
4718 int context_pop_count = inner_scope->ContextChainLength(outer_scope);
4719 if (context_pop_count > 0) {
4720 while (context_pop_count-- > 0) {
4721 HInstruction* context_instruction = Add<HLoadNamedField>(
4722 context, static_cast<HValue*>(NULL),
4723 HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX));
4724 context = context_instruction;
4726 HInstruction* instr = Add<HStoreFrameContext>(context);
4727 if (instr->HasObservableSideEffects()) {
4728 AddSimulate(stmt->target()->ExitId(), REMOVABLE_SIMULATE);
4730 environment()->BindContext(context);
4733 set_current_block(NULL);
4737 void HOptimizedGraphBuilder::VisitReturnStatement(ReturnStatement* stmt) {
4738 DCHECK(!HasStackOverflow());
4739 DCHECK(current_block() != NULL);
4740 DCHECK(current_block()->HasPredecessor());
4741 FunctionState* state = function_state();
4742 AstContext* context = call_context();
4743 if (context == NULL) {
4744 // Not an inlined return, so an actual one.
4745 CHECK_ALIVE(VisitForValue(stmt->expression()));
4746 HValue* result = environment()->Pop();
4747 Add<HReturn>(result);
4748 } else if (state->inlining_kind() == CONSTRUCT_CALL_RETURN) {
4749 // Return from an inlined construct call. In a test context the return value
4750 // will always evaluate to true, in a value context the return value needs
4751 // to be a JSObject.
4752 if (context->IsTest()) {
4753 TestContext* test = TestContext::cast(context);
4754 CHECK_ALIVE(VisitForEffect(stmt->expression()));
4755 Goto(test->if_true(), state);
4756 } else if (context->IsEffect()) {
4757 CHECK_ALIVE(VisitForEffect(stmt->expression()));
4758 Goto(function_return(), state);
4760 DCHECK(context->IsValue());
4761 CHECK_ALIVE(VisitForValue(stmt->expression()));
4762 HValue* return_value = Pop();
4763 HValue* receiver = environment()->arguments_environment()->Lookup(0);
4764 HHasInstanceTypeAndBranch* typecheck =
4765 New<HHasInstanceTypeAndBranch>(return_value,
4766 FIRST_SPEC_OBJECT_TYPE,
4767 LAST_SPEC_OBJECT_TYPE);
4768 HBasicBlock* if_spec_object = graph()->CreateBasicBlock();
4769 HBasicBlock* not_spec_object = graph()->CreateBasicBlock();
4770 typecheck->SetSuccessorAt(0, if_spec_object);
4771 typecheck->SetSuccessorAt(1, not_spec_object);
4772 FinishCurrentBlock(typecheck);
4773 AddLeaveInlined(if_spec_object, return_value, state);
4774 AddLeaveInlined(not_spec_object, receiver, state);
4776 } else if (state->inlining_kind() == SETTER_CALL_RETURN) {
4777 // Return from an inlined setter call. The returned value is never used, the
4778 // value of an assignment is always the value of the RHS of the assignment.
4779 CHECK_ALIVE(VisitForEffect(stmt->expression()));
4780 if (context->IsTest()) {
4781 HValue* rhs = environment()->arguments_environment()->Lookup(1);
4782 context->ReturnValue(rhs);
4783 } else if (context->IsEffect()) {
4784 Goto(function_return(), state);
4786 DCHECK(context->IsValue());
4787 HValue* rhs = environment()->arguments_environment()->Lookup(1);
4788 AddLeaveInlined(rhs, state);
4791 // Return from a normal inlined function. Visit the subexpression in the
4792 // expression context of the call.
4793 if (context->IsTest()) {
4794 TestContext* test = TestContext::cast(context);
4795 VisitForControl(stmt->expression(), test->if_true(), test->if_false());
4796 } else if (context->IsEffect()) {
4797 // Visit in value context and ignore the result. This is needed to keep
4798 // environment in sync with full-codegen since some visitors (e.g.
4799 // VisitCountOperation) use the operand stack differently depending on
4801 CHECK_ALIVE(VisitForValue(stmt->expression()));
4803 Goto(function_return(), state);
4805 DCHECK(context->IsValue());
4806 CHECK_ALIVE(VisitForValue(stmt->expression()));
4807 AddLeaveInlined(Pop(), state);
4810 set_current_block(NULL);
4814 void HOptimizedGraphBuilder::VisitWithStatement(WithStatement* stmt) {
4815 DCHECK(!HasStackOverflow());
4816 DCHECK(current_block() != NULL);
4817 DCHECK(current_block()->HasPredecessor());
4818 return Bailout(kWithStatement);
4822 void HOptimizedGraphBuilder::VisitSwitchStatement(SwitchStatement* stmt) {
4823 DCHECK(!HasStackOverflow());
4824 DCHECK(current_block() != NULL);
4825 DCHECK(current_block()->HasPredecessor());
4827 // We only optimize switch statements with a bounded number of clauses.
4828 const int kCaseClauseLimit = 128;
4829 ZoneList<CaseClause*>* clauses = stmt->cases();
4830 int clause_count = clauses->length();
4831 ZoneList<HBasicBlock*> body_blocks(clause_count, zone());
4832 if (clause_count > kCaseClauseLimit) {
4833 return Bailout(kSwitchStatementTooManyClauses);
4836 CHECK_ALIVE(VisitForValue(stmt->tag()));
4837 Add<HSimulate>(stmt->EntryId());
4838 HValue* tag_value = Top();
4839 Type* tag_type = stmt->tag()->bounds().lower;
4841 // 1. Build all the tests, with dangling true branches
4842 BailoutId default_id = BailoutId::None();
4843 for (int i = 0; i < clause_count; ++i) {
4844 CaseClause* clause = clauses->at(i);
4845 if (clause->is_default()) {
4846 body_blocks.Add(NULL, zone());
4847 if (default_id.IsNone()) default_id = clause->EntryId();
4851 // Generate a compare and branch.
4852 CHECK_ALIVE(VisitForValue(clause->label()));
4853 HValue* label_value = Pop();
4855 Type* label_type = clause->label()->bounds().lower;
4856 Type* combined_type = clause->compare_type();
4857 HControlInstruction* compare = BuildCompareInstruction(
4858 Token::EQ_STRICT, tag_value, label_value, tag_type, label_type,
4860 ScriptPositionToSourcePosition(stmt->tag()->position()),
4861 ScriptPositionToSourcePosition(clause->label()->position()),
4862 PUSH_BEFORE_SIMULATE, clause->id());
4864 HBasicBlock* next_test_block = graph()->CreateBasicBlock();
4865 HBasicBlock* body_block = graph()->CreateBasicBlock();
4866 body_blocks.Add(body_block, zone());
4867 compare->SetSuccessorAt(0, body_block);
4868 compare->SetSuccessorAt(1, next_test_block);
4869 FinishCurrentBlock(compare);
4871 set_current_block(body_block);
4872 Drop(1); // tag_value
4874 set_current_block(next_test_block);
4877 // Save the current block to use for the default or to join with the
4879 HBasicBlock* last_block = current_block();
4880 Drop(1); // tag_value
4882 // 2. Loop over the clauses and the linked list of tests in lockstep,
4883 // translating the clause bodies.
4884 HBasicBlock* fall_through_block = NULL;
4886 BreakAndContinueInfo break_info(stmt, scope());
4887 { BreakAndContinueScope push(&break_info, this);
4888 for (int i = 0; i < clause_count; ++i) {
4889 CaseClause* clause = clauses->at(i);
4891 // Identify the block where normal (non-fall-through) control flow
4893 HBasicBlock* normal_block = NULL;
4894 if (clause->is_default()) {
4895 if (last_block == NULL) continue;
4896 normal_block = last_block;
4897 last_block = NULL; // Cleared to indicate we've handled it.
4899 normal_block = body_blocks[i];
4902 if (fall_through_block == NULL) {
4903 set_current_block(normal_block);
4905 HBasicBlock* join = CreateJoin(fall_through_block,
4908 set_current_block(join);
4911 CHECK_BAILOUT(VisitStatements(clause->statements()));
4912 fall_through_block = current_block();
4916 // Create an up-to-3-way join. Use the break block if it exists since
4917 // it's already a join block.
4918 HBasicBlock* break_block = break_info.break_block();
4919 if (break_block == NULL) {
4920 set_current_block(CreateJoin(fall_through_block,
4924 if (fall_through_block != NULL) Goto(fall_through_block, break_block);
4925 if (last_block != NULL) Goto(last_block, break_block);
4926 break_block->SetJoinId(stmt->ExitId());
4927 set_current_block(break_block);
4932 void HOptimizedGraphBuilder::VisitLoopBody(IterationStatement* stmt,
4933 HBasicBlock* loop_entry) {
4934 Add<HSimulate>(stmt->StackCheckId());
4935 HStackCheck* stack_check =
4936 HStackCheck::cast(Add<HStackCheck>(HStackCheck::kBackwardsBranch));
4937 DCHECK(loop_entry->IsLoopHeader());
4938 loop_entry->loop_information()->set_stack_check(stack_check);
4939 CHECK_BAILOUT(Visit(stmt->body()));
4943 void HOptimizedGraphBuilder::VisitDoWhileStatement(DoWhileStatement* stmt) {
4944 DCHECK(!HasStackOverflow());
4945 DCHECK(current_block() != NULL);
4946 DCHECK(current_block()->HasPredecessor());
4947 DCHECK(current_block() != NULL);
4948 HBasicBlock* loop_entry = BuildLoopEntry(stmt);
4950 BreakAndContinueInfo break_info(stmt, scope());
4952 BreakAndContinueScope push(&break_info, this);
4953 CHECK_BAILOUT(VisitLoopBody(stmt, loop_entry));
4955 HBasicBlock* body_exit =
4956 JoinContinue(stmt, current_block(), break_info.continue_block());
4957 HBasicBlock* loop_successor = NULL;
4958 if (body_exit != NULL && !stmt->cond()->ToBooleanIsTrue()) {
4959 set_current_block(body_exit);
4960 loop_successor = graph()->CreateBasicBlock();
4961 if (stmt->cond()->ToBooleanIsFalse()) {
4962 loop_entry->loop_information()->stack_check()->Eliminate();
4963 Goto(loop_successor);
4966 // The block for a true condition, the actual predecessor block of the
4968 body_exit = graph()->CreateBasicBlock();
4969 CHECK_BAILOUT(VisitForControl(stmt->cond(), body_exit, loop_successor));
4971 if (body_exit != NULL && body_exit->HasPredecessor()) {
4972 body_exit->SetJoinId(stmt->BackEdgeId());
4976 if (loop_successor->HasPredecessor()) {
4977 loop_successor->SetJoinId(stmt->ExitId());
4979 loop_successor = NULL;
4982 HBasicBlock* loop_exit = CreateLoop(stmt,
4986 break_info.break_block());
4987 set_current_block(loop_exit);
4991 void HOptimizedGraphBuilder::VisitWhileStatement(WhileStatement* stmt) {
4992 DCHECK(!HasStackOverflow());
4993 DCHECK(current_block() != NULL);
4994 DCHECK(current_block()->HasPredecessor());
4995 DCHECK(current_block() != NULL);
4996 HBasicBlock* loop_entry = BuildLoopEntry(stmt);
4998 // If the condition is constant true, do not generate a branch.
4999 HBasicBlock* loop_successor = NULL;
5000 if (!stmt->cond()->ToBooleanIsTrue()) {
5001 HBasicBlock* body_entry = graph()->CreateBasicBlock();
5002 loop_successor = graph()->CreateBasicBlock();
5003 CHECK_BAILOUT(VisitForControl(stmt->cond(), body_entry, loop_successor));
5004 if (body_entry->HasPredecessor()) {
5005 body_entry->SetJoinId(stmt->BodyId());
5006 set_current_block(body_entry);
5008 if (loop_successor->HasPredecessor()) {
5009 loop_successor->SetJoinId(stmt->ExitId());
5011 loop_successor = NULL;
5015 BreakAndContinueInfo break_info(stmt, scope());
5016 if (current_block() != NULL) {
5017 BreakAndContinueScope push(&break_info, this);
5018 CHECK_BAILOUT(VisitLoopBody(stmt, loop_entry));
5020 HBasicBlock* body_exit =
5021 JoinContinue(stmt, current_block(), break_info.continue_block());
5022 HBasicBlock* loop_exit = CreateLoop(stmt,
5026 break_info.break_block());
5027 set_current_block(loop_exit);
5031 void HOptimizedGraphBuilder::VisitForStatement(ForStatement* stmt) {
5032 DCHECK(!HasStackOverflow());
5033 DCHECK(current_block() != NULL);
5034 DCHECK(current_block()->HasPredecessor());
5035 if (stmt->init() != NULL) {
5036 CHECK_ALIVE(Visit(stmt->init()));
5038 DCHECK(current_block() != NULL);
5039 HBasicBlock* loop_entry = BuildLoopEntry(stmt);
5041 HBasicBlock* loop_successor = NULL;
5042 if (stmt->cond() != NULL) {
5043 HBasicBlock* body_entry = graph()->CreateBasicBlock();
5044 loop_successor = graph()->CreateBasicBlock();
5045 CHECK_BAILOUT(VisitForControl(stmt->cond(), body_entry, loop_successor));
5046 if (body_entry->HasPredecessor()) {
5047 body_entry->SetJoinId(stmt->BodyId());
5048 set_current_block(body_entry);
5050 if (loop_successor->HasPredecessor()) {
5051 loop_successor->SetJoinId(stmt->ExitId());
5053 loop_successor = NULL;
5057 BreakAndContinueInfo break_info(stmt, scope());
5058 if (current_block() != NULL) {
5059 BreakAndContinueScope push(&break_info, this);
5060 CHECK_BAILOUT(VisitLoopBody(stmt, loop_entry));
5062 HBasicBlock* body_exit =
5063 JoinContinue(stmt, current_block(), break_info.continue_block());
5065 if (stmt->next() != NULL && body_exit != NULL) {
5066 set_current_block(body_exit);
5067 CHECK_BAILOUT(Visit(stmt->next()));
5068 body_exit = current_block();
5071 HBasicBlock* loop_exit = CreateLoop(stmt,
5075 break_info.break_block());
5076 set_current_block(loop_exit);
5080 void HOptimizedGraphBuilder::VisitForInStatement(ForInStatement* stmt) {
5081 DCHECK(!HasStackOverflow());
5082 DCHECK(current_block() != NULL);
5083 DCHECK(current_block()->HasPredecessor());
5085 if (!FLAG_optimize_for_in) {
5086 return Bailout(kForInStatementOptimizationIsDisabled);
5089 if (stmt->for_in_type() != ForInStatement::FAST_FOR_IN) {
5090 return Bailout(kForInStatementIsNotFastCase);
5093 if (!stmt->each()->IsVariableProxy() ||
5094 !stmt->each()->AsVariableProxy()->var()->IsStackLocal()) {
5095 return Bailout(kForInStatementWithNonLocalEachVariable);
5098 Variable* each_var = stmt->each()->AsVariableProxy()->var();
5100 CHECK_ALIVE(VisitForValue(stmt->enumerable()));
5101 HValue* enumerable = Top(); // Leave enumerable at the top.
5103 HInstruction* map = Add<HForInPrepareMap>(enumerable);
5104 Add<HSimulate>(stmt->PrepareId());
5106 HInstruction* array = Add<HForInCacheArray>(
5107 enumerable, map, DescriptorArray::kEnumCacheBridgeCacheIndex);
5109 HInstruction* enum_length = Add<HMapEnumLength>(map);
5111 HInstruction* start_index = Add<HConstant>(0);
5118 HInstruction* index_cache = Add<HForInCacheArray>(
5119 enumerable, map, DescriptorArray::kEnumCacheBridgeIndicesCacheIndex);
5120 HForInCacheArray::cast(array)->set_index_cache(
5121 HForInCacheArray::cast(index_cache));
5123 HBasicBlock* loop_entry = BuildLoopEntry(stmt);
5125 HValue* index = environment()->ExpressionStackAt(0);
5126 HValue* limit = environment()->ExpressionStackAt(1);
5128 // Check that we still have more keys.
5129 HCompareNumericAndBranch* compare_index =
5130 New<HCompareNumericAndBranch>(index, limit, Token::LT);
5131 compare_index->set_observed_input_representation(
5132 Representation::Smi(), Representation::Smi());
5134 HBasicBlock* loop_body = graph()->CreateBasicBlock();
5135 HBasicBlock* loop_successor = graph()->CreateBasicBlock();
5137 compare_index->SetSuccessorAt(0, loop_body);
5138 compare_index->SetSuccessorAt(1, loop_successor);
5139 FinishCurrentBlock(compare_index);
5141 set_current_block(loop_successor);
5144 set_current_block(loop_body);
5146 HValue* key = Add<HLoadKeyed>(
5147 environment()->ExpressionStackAt(2), // Enum cache.
5148 environment()->ExpressionStackAt(0), // Iteration index.
5149 environment()->ExpressionStackAt(0),
5152 // Check if the expected map still matches that of the enumerable.
5153 // If not just deoptimize.
5154 Add<HCheckMapValue>(environment()->ExpressionStackAt(4),
5155 environment()->ExpressionStackAt(3));
5157 Bind(each_var, key);
5159 BreakAndContinueInfo break_info(stmt, scope(), 5);
5161 BreakAndContinueScope push(&break_info, this);
5162 CHECK_BAILOUT(VisitLoopBody(stmt, loop_entry));
5165 HBasicBlock* body_exit =
5166 JoinContinue(stmt, current_block(), break_info.continue_block());
5168 if (body_exit != NULL) {
5169 set_current_block(body_exit);
5171 HValue* current_index = Pop();
5172 Push(AddUncasted<HAdd>(current_index, graph()->GetConstant1()));
5173 body_exit = current_block();
5176 HBasicBlock* loop_exit = CreateLoop(stmt,
5180 break_info.break_block());
5182 set_current_block(loop_exit);
5186 void HOptimizedGraphBuilder::VisitForOfStatement(ForOfStatement* stmt) {
5187 DCHECK(!HasStackOverflow());
5188 DCHECK(current_block() != NULL);
5189 DCHECK(current_block()->HasPredecessor());
5190 return Bailout(kForOfStatement);
5194 void HOptimizedGraphBuilder::VisitTryCatchStatement(TryCatchStatement* stmt) {
5195 DCHECK(!HasStackOverflow());
5196 DCHECK(current_block() != NULL);
5197 DCHECK(current_block()->HasPredecessor());
5198 return Bailout(kTryCatchStatement);
5202 void HOptimizedGraphBuilder::VisitTryFinallyStatement(
5203 TryFinallyStatement* stmt) {
5204 DCHECK(!HasStackOverflow());
5205 DCHECK(current_block() != NULL);
5206 DCHECK(current_block()->HasPredecessor());
5207 return Bailout(kTryFinallyStatement);
5211 void HOptimizedGraphBuilder::VisitDebuggerStatement(DebuggerStatement* stmt) {
5212 DCHECK(!HasStackOverflow());
5213 DCHECK(current_block() != NULL);
5214 DCHECK(current_block()->HasPredecessor());
5215 return Bailout(kDebuggerStatement);
5219 void HOptimizedGraphBuilder::VisitCaseClause(CaseClause* clause) {
5224 void HOptimizedGraphBuilder::VisitFunctionLiteral(FunctionLiteral* expr) {
5225 DCHECK(!HasStackOverflow());
5226 DCHECK(current_block() != NULL);
5227 DCHECK(current_block()->HasPredecessor());
5228 Handle<SharedFunctionInfo> shared_info = expr->shared_info();
5229 if (shared_info.is_null()) {
5231 Compiler::BuildFunctionInfo(expr, current_info()->script(), top_info());
5233 // We also have a stack overflow if the recursive compilation did.
5234 if (HasStackOverflow()) return;
5235 HFunctionLiteral* instr =
5236 New<HFunctionLiteral>(shared_info, expr->pretenure());
5237 return ast_context()->ReturnInstruction(instr, expr->id());
5241 void HOptimizedGraphBuilder::VisitNativeFunctionLiteral(
5242 NativeFunctionLiteral* expr) {
5243 DCHECK(!HasStackOverflow());
5244 DCHECK(current_block() != NULL);
5245 DCHECK(current_block()->HasPredecessor());
5246 return Bailout(kNativeFunctionLiteral);
5250 void HOptimizedGraphBuilder::VisitConditional(Conditional* expr) {
5251 DCHECK(!HasStackOverflow());
5252 DCHECK(current_block() != NULL);
5253 DCHECK(current_block()->HasPredecessor());
5254 HBasicBlock* cond_true = graph()->CreateBasicBlock();
5255 HBasicBlock* cond_false = graph()->CreateBasicBlock();
5256 CHECK_BAILOUT(VisitForControl(expr->condition(), cond_true, cond_false));
5258 // Visit the true and false subexpressions in the same AST context as the
5259 // whole expression.
5260 if (cond_true->HasPredecessor()) {
5261 cond_true->SetJoinId(expr->ThenId());
5262 set_current_block(cond_true);
5263 CHECK_BAILOUT(Visit(expr->then_expression()));
5264 cond_true = current_block();
5269 if (cond_false->HasPredecessor()) {
5270 cond_false->SetJoinId(expr->ElseId());
5271 set_current_block(cond_false);
5272 CHECK_BAILOUT(Visit(expr->else_expression()));
5273 cond_false = current_block();
5278 if (!ast_context()->IsTest()) {
5279 HBasicBlock* join = CreateJoin(cond_true, cond_false, expr->id());
5280 set_current_block(join);
5281 if (join != NULL && !ast_context()->IsEffect()) {
5282 return ast_context()->ReturnValue(Pop());
5288 HOptimizedGraphBuilder::GlobalPropertyAccess
5289 HOptimizedGraphBuilder::LookupGlobalProperty(
5290 Variable* var, LookupResult* lookup, PropertyAccessType access_type) {
5291 if (var->is_this() || !current_info()->has_global_object()) {
5294 Handle<GlobalObject> global(current_info()->global_object());
5295 global->Lookup(var->name(), lookup);
5296 if (!lookup->IsNormal() ||
5297 (access_type == STORE && lookup->IsReadOnly()) ||
5298 lookup->holder() != *global) {
5306 HValue* HOptimizedGraphBuilder::BuildContextChainWalk(Variable* var) {
5307 DCHECK(var->IsContextSlot());
5308 HValue* context = environment()->context();
5309 int length = scope()->ContextChainLength(var->scope());
5310 while (length-- > 0) {
5311 context = Add<HLoadNamedField>(
5312 context, static_cast<HValue*>(NULL),
5313 HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX));
5319 void HOptimizedGraphBuilder::VisitVariableProxy(VariableProxy* expr) {
5320 if (expr->is_this()) {
5321 current_info()->set_this_has_uses(true);
5324 DCHECK(!HasStackOverflow());
5325 DCHECK(current_block() != NULL);
5326 DCHECK(current_block()->HasPredecessor());
5327 Variable* variable = expr->var();
5328 switch (variable->location()) {
5329 case Variable::UNALLOCATED: {
5330 if (IsLexicalVariableMode(variable->mode())) {
5331 // TODO(rossberg): should this be an DCHECK?
5332 return Bailout(kReferenceToGlobalLexicalVariable);
5334 // Handle known global constants like 'undefined' specially to avoid a
5335 // load from a global cell for them.
5336 Handle<Object> constant_value =
5337 isolate()->factory()->GlobalConstantFor(variable->name());
5338 if (!constant_value.is_null()) {
5339 HConstant* instr = New<HConstant>(constant_value);
5340 return ast_context()->ReturnInstruction(instr, expr->id());
5343 LookupResult lookup(isolate());
5344 GlobalPropertyAccess type = LookupGlobalProperty(variable, &lookup, LOAD);
5346 if (type == kUseCell &&
5347 current_info()->global_object()->IsAccessCheckNeeded()) {
5351 if (type == kUseCell) {
5352 Handle<GlobalObject> global(current_info()->global_object());
5353 Handle<PropertyCell> cell(global->GetPropertyCell(&lookup));
5354 if (cell->type()->IsConstant()) {
5355 PropertyCell::AddDependentCompilationInfo(cell, top_info());
5356 Handle<Object> constant_object = cell->type()->AsConstant()->Value();
5357 if (constant_object->IsConsString()) {
5359 String::Flatten(Handle<String>::cast(constant_object));
5361 HConstant* constant = New<HConstant>(constant_object);
5362 return ast_context()->ReturnInstruction(constant, expr->id());
5364 HLoadGlobalCell* instr =
5365 New<HLoadGlobalCell>(cell, lookup.GetPropertyDetails());
5366 return ast_context()->ReturnInstruction(instr, expr->id());
5369 HValue* global_object = Add<HLoadNamedField>(
5370 context(), static_cast<HValue*>(NULL),
5371 HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
5372 HLoadGlobalGeneric* instr =
5373 New<HLoadGlobalGeneric>(global_object,
5375 ast_context()->is_for_typeof());
5376 if (FLAG_vector_ics) {
5377 Handle<SharedFunctionInfo> current_shared =
5378 function_state()->compilation_info()->shared_info();
5379 instr->SetVectorAndSlot(
5380 handle(current_shared->feedback_vector(), isolate()),
5381 expr->VariableFeedbackSlot());
5383 return ast_context()->ReturnInstruction(instr, expr->id());
5387 case Variable::PARAMETER:
5388 case Variable::LOCAL: {
5389 HValue* value = LookupAndMakeLive(variable);
5390 if (value == graph()->GetConstantHole()) {
5391 DCHECK(IsDeclaredVariableMode(variable->mode()) &&
5392 variable->mode() != VAR);
5393 return Bailout(kReferenceToUninitializedVariable);
5395 return ast_context()->ReturnValue(value);
5398 case Variable::CONTEXT: {
5399 HValue* context = BuildContextChainWalk(variable);
5400 HLoadContextSlot::Mode mode;
5401 switch (variable->mode()) {
5404 mode = HLoadContextSlot::kCheckDeoptimize;
5407 mode = HLoadContextSlot::kCheckReturnUndefined;
5410 mode = HLoadContextSlot::kNoCheck;
5413 HLoadContextSlot* instr =
5414 new(zone()) HLoadContextSlot(context, variable->index(), mode);
5415 return ast_context()->ReturnInstruction(instr, expr->id());
5418 case Variable::LOOKUP:
5419 return Bailout(kReferenceToAVariableWhichRequiresDynamicLookup);
5424 void HOptimizedGraphBuilder::VisitLiteral(Literal* expr) {
5425 DCHECK(!HasStackOverflow());
5426 DCHECK(current_block() != NULL);
5427 DCHECK(current_block()->HasPredecessor());
5428 HConstant* instr = New<HConstant>(expr->value());
5429 return ast_context()->ReturnInstruction(instr, expr->id());
5433 void HOptimizedGraphBuilder::VisitRegExpLiteral(RegExpLiteral* expr) {
5434 DCHECK(!HasStackOverflow());
5435 DCHECK(current_block() != NULL);
5436 DCHECK(current_block()->HasPredecessor());
5437 Handle<JSFunction> closure = function_state()->compilation_info()->closure();
5438 Handle<FixedArray> literals(closure->literals());
5439 HRegExpLiteral* instr = New<HRegExpLiteral>(literals,
5442 expr->literal_index());
5443 return ast_context()->ReturnInstruction(instr, expr->id());
5447 static bool CanInlinePropertyAccess(Type* type) {
5448 if (type->Is(Type::NumberOrString())) return true;
5449 if (!type->IsClass()) return false;
5450 Handle<Map> map = type->AsClass()->Map();
5451 return map->IsJSObjectMap() &&
5452 !map->is_dictionary_map() &&
5453 !map->has_named_interceptor();
5457 // Determines whether the given array or object literal boilerplate satisfies
5458 // all limits to be considered for fast deep-copying and computes the total
5459 // size of all objects that are part of the graph.
5460 static bool IsFastLiteral(Handle<JSObject> boilerplate,
5462 int* max_properties) {
5463 if (boilerplate->map()->is_deprecated() &&
5464 !JSObject::TryMigrateInstance(boilerplate)) {
5468 DCHECK(max_depth >= 0 && *max_properties >= 0);
5469 if (max_depth == 0) return false;
5471 Isolate* isolate = boilerplate->GetIsolate();
5472 Handle<FixedArrayBase> elements(boilerplate->elements());
5473 if (elements->length() > 0 &&
5474 elements->map() != isolate->heap()->fixed_cow_array_map()) {
5475 if (boilerplate->HasFastObjectElements()) {
5476 Handle<FixedArray> fast_elements = Handle<FixedArray>::cast(elements);
5477 int length = elements->length();
5478 for (int i = 0; i < length; i++) {
5479 if ((*max_properties)-- == 0) return false;
5480 Handle<Object> value(fast_elements->get(i), isolate);
5481 if (value->IsJSObject()) {
5482 Handle<JSObject> value_object = Handle<JSObject>::cast(value);
5483 if (!IsFastLiteral(value_object,
5490 } else if (!boilerplate->HasFastDoubleElements()) {
5495 Handle<FixedArray> properties(boilerplate->properties());
5496 if (properties->length() > 0) {
5499 Handle<DescriptorArray> descriptors(
5500 boilerplate->map()->instance_descriptors());
5501 int limit = boilerplate->map()->NumberOfOwnDescriptors();
5502 for (int i = 0; i < limit; i++) {
5503 PropertyDetails details = descriptors->GetDetails(i);
5504 if (details.type() != FIELD) continue;
5505 int index = descriptors->GetFieldIndex(i);
5506 if ((*max_properties)-- == 0) return false;
5507 Handle<Object> value(boilerplate->InObjectPropertyAt(index), isolate);
5508 if (value->IsJSObject()) {
5509 Handle<JSObject> value_object = Handle<JSObject>::cast(value);
5510 if (!IsFastLiteral(value_object,
5522 void HOptimizedGraphBuilder::VisitObjectLiteral(ObjectLiteral* expr) {
5523 DCHECK(!HasStackOverflow());
5524 DCHECK(current_block() != NULL);
5525 DCHECK(current_block()->HasPredecessor());
5526 expr->BuildConstantProperties(isolate());
5527 Handle<JSFunction> closure = function_state()->compilation_info()->closure();
5528 HInstruction* literal;
5530 // Check whether to use fast or slow deep-copying for boilerplate.
5531 int max_properties = kMaxFastLiteralProperties;
5532 Handle<Object> literals_cell(closure->literals()->get(expr->literal_index()),
5534 Handle<AllocationSite> site;
5535 Handle<JSObject> boilerplate;
5536 if (!literals_cell->IsUndefined()) {
5537 // Retrieve the boilerplate
5538 site = Handle<AllocationSite>::cast(literals_cell);
5539 boilerplate = Handle<JSObject>(JSObject::cast(site->transition_info()),
5543 if (!boilerplate.is_null() &&
5544 IsFastLiteral(boilerplate, kMaxFastLiteralDepth, &max_properties)) {
5545 AllocationSiteUsageContext usage_context(isolate(), site, false);
5546 usage_context.EnterNewScope();
5547 literal = BuildFastLiteral(boilerplate, &usage_context);
5548 usage_context.ExitScope(site, boilerplate);
5550 NoObservableSideEffectsScope no_effects(this);
5551 Handle<FixedArray> closure_literals(closure->literals(), isolate());
5552 Handle<FixedArray> constant_properties = expr->constant_properties();
5553 int literal_index = expr->literal_index();
5554 int flags = expr->fast_elements()
5555 ? ObjectLiteral::kFastElements : ObjectLiteral::kNoFlags;
5556 flags |= expr->has_function()
5557 ? ObjectLiteral::kHasFunction : ObjectLiteral::kNoFlags;
5559 Add<HPushArguments>(Add<HConstant>(closure_literals),
5560 Add<HConstant>(literal_index),
5561 Add<HConstant>(constant_properties),
5562 Add<HConstant>(flags));
5564 // TODO(mvstanton): Add a flag to turn off creation of any
5565 // AllocationMementos for this call: we are in crankshaft and should have
5566 // learned enough about transition behavior to stop emitting mementos.
5567 Runtime::FunctionId function_id = Runtime::kCreateObjectLiteral;
5568 literal = Add<HCallRuntime>(isolate()->factory()->empty_string(),
5569 Runtime::FunctionForId(function_id),
5573 // The object is expected in the bailout environment during computation
5574 // of the property values and is the value of the entire expression.
5577 expr->CalculateEmitStore(zone());
5579 for (int i = 0; i < expr->properties()->length(); i++) {
5580 ObjectLiteral::Property* property = expr->properties()->at(i);
5581 if (property->IsCompileTimeValue()) continue;
5583 Literal* key = property->key();
5584 Expression* value = property->value();
5586 switch (property->kind()) {
5587 case ObjectLiteral::Property::MATERIALIZED_LITERAL:
5588 DCHECK(!CompileTimeValue::IsCompileTimeValue(value));
5590 case ObjectLiteral::Property::COMPUTED:
5591 if (key->value()->IsInternalizedString()) {
5592 if (property->emit_store()) {
5593 CHECK_ALIVE(VisitForValue(value));
5594 HValue* value = Pop();
5595 Handle<Map> map = property->GetReceiverType();
5596 Handle<String> name = property->key()->AsPropertyName();
5597 HInstruction* store;
5598 if (map.is_null()) {
5599 // If we don't know the monomorphic type, do a generic store.
5600 CHECK_ALIVE(store = BuildNamedGeneric(
5601 STORE, NULL, literal, name, value));
5603 PropertyAccessInfo info(
5604 this, STORE, ToType(map), name, map->instance_type());
5605 if (info.CanAccessMonomorphic()) {
5606 HValue* checked_literal = Add<HCheckMaps>(literal, map);
5607 DCHECK(!info.lookup()->IsPropertyCallbacks());
5608 store = BuildMonomorphicAccess(
5609 &info, literal, checked_literal, value,
5610 BailoutId::None(), BailoutId::None());
5612 CHECK_ALIVE(store = BuildNamedGeneric(
5613 STORE, NULL, literal, name, value));
5616 AddInstruction(store);
5617 if (store->HasObservableSideEffects()) {
5618 Add<HSimulate>(key->id(), REMOVABLE_SIMULATE);
5621 CHECK_ALIVE(VisitForEffect(value));
5626 case ObjectLiteral::Property::PROTOTYPE:
5627 case ObjectLiteral::Property::SETTER:
5628 case ObjectLiteral::Property::GETTER:
5629 return Bailout(kObjectLiteralWithComplexProperty);
5630 default: UNREACHABLE();
5634 if (expr->has_function()) {
5635 // Return the result of the transformation to fast properties
5636 // instead of the original since this operation changes the map
5637 // of the object. This makes sure that the original object won't
5638 // be used by other optimized code before it is transformed
5639 // (e.g. because of code motion).
5640 HToFastProperties* result = Add<HToFastProperties>(Pop());
5641 return ast_context()->ReturnValue(result);
5643 return ast_context()->ReturnValue(Pop());
5648 void HOptimizedGraphBuilder::VisitArrayLiteral(ArrayLiteral* expr) {
5649 DCHECK(!HasStackOverflow());
5650 DCHECK(current_block() != NULL);
5651 DCHECK(current_block()->HasPredecessor());
5652 expr->BuildConstantElements(isolate());
5653 ZoneList<Expression*>* subexprs = expr->values();
5654 int length = subexprs->length();
5655 HInstruction* literal;
5657 Handle<AllocationSite> site;
5658 Handle<FixedArray> literals(environment()->closure()->literals(), isolate());
5659 bool uninitialized = false;
5660 Handle<Object> literals_cell(literals->get(expr->literal_index()),
5662 Handle<JSObject> boilerplate_object;
5663 if (literals_cell->IsUndefined()) {
5664 uninitialized = true;
5665 Handle<Object> raw_boilerplate;
5666 ASSIGN_RETURN_ON_EXCEPTION_VALUE(
5667 isolate(), raw_boilerplate,
5668 Runtime::CreateArrayLiteralBoilerplate(
5669 isolate(), literals, expr->constant_elements()),
5670 Bailout(kArrayBoilerplateCreationFailed));
5672 boilerplate_object = Handle<JSObject>::cast(raw_boilerplate);
5673 AllocationSiteCreationContext creation_context(isolate());
5674 site = creation_context.EnterNewScope();
5675 if (JSObject::DeepWalk(boilerplate_object, &creation_context).is_null()) {
5676 return Bailout(kArrayBoilerplateCreationFailed);
5678 creation_context.ExitScope(site, boilerplate_object);
5679 literals->set(expr->literal_index(), *site);
5681 if (boilerplate_object->elements()->map() ==
5682 isolate()->heap()->fixed_cow_array_map()) {
5683 isolate()->counters()->cow_arrays_created_runtime()->Increment();
5686 DCHECK(literals_cell->IsAllocationSite());
5687 site = Handle<AllocationSite>::cast(literals_cell);
5688 boilerplate_object = Handle<JSObject>(
5689 JSObject::cast(site->transition_info()), isolate());
5692 DCHECK(!boilerplate_object.is_null());
5693 DCHECK(site->SitePointsToLiteral());
5695 ElementsKind boilerplate_elements_kind =
5696 boilerplate_object->GetElementsKind();
5698 // Check whether to use fast or slow deep-copying for boilerplate.
5699 int max_properties = kMaxFastLiteralProperties;
5700 if (IsFastLiteral(boilerplate_object,
5701 kMaxFastLiteralDepth,
5703 AllocationSiteUsageContext usage_context(isolate(), site, false);
5704 usage_context.EnterNewScope();
5705 literal = BuildFastLiteral(boilerplate_object, &usage_context);
5706 usage_context.ExitScope(site, boilerplate_object);
5708 NoObservableSideEffectsScope no_effects(this);
5709 // Boilerplate already exists and constant elements are never accessed,
5710 // pass an empty fixed array to the runtime function instead.
5711 Handle<FixedArray> constants = isolate()->factory()->empty_fixed_array();
5712 int literal_index = expr->literal_index();
5713 int flags = expr->depth() == 1
5714 ? ArrayLiteral::kShallowElements
5715 : ArrayLiteral::kNoFlags;
5716 flags |= ArrayLiteral::kDisableMementos;
5718 Add<HPushArguments>(Add<HConstant>(literals),
5719 Add<HConstant>(literal_index),
5720 Add<HConstant>(constants),
5721 Add<HConstant>(flags));
5723 // TODO(mvstanton): Consider a flag to turn off creation of any
5724 // AllocationMementos for this call: we are in crankshaft and should have
5725 // learned enough about transition behavior to stop emitting mementos.
5726 Runtime::FunctionId function_id = Runtime::kCreateArrayLiteral;
5727 literal = Add<HCallRuntime>(isolate()->factory()->empty_string(),
5728 Runtime::FunctionForId(function_id),
5731 // De-opt if elements kind changed from boilerplate_elements_kind.
5732 Handle<Map> map = Handle<Map>(boilerplate_object->map(), isolate());
5733 literal = Add<HCheckMaps>(literal, map);
5736 // The array is expected in the bailout environment during computation
5737 // of the property values and is the value of the entire expression.
5739 // The literal index is on the stack, too.
5740 Push(Add<HConstant>(expr->literal_index()));
5742 HInstruction* elements = NULL;
5744 for (int i = 0; i < length; i++) {
5745 Expression* subexpr = subexprs->at(i);
5746 // If the subexpression is a literal or a simple materialized literal it
5747 // is already set in the cloned array.
5748 if (CompileTimeValue::IsCompileTimeValue(subexpr)) continue;
5750 CHECK_ALIVE(VisitForValue(subexpr));
5751 HValue* value = Pop();
5752 if (!Smi::IsValid(i)) return Bailout(kNonSmiKeyInArrayLiteral);
5754 elements = AddLoadElements(literal);
5756 HValue* key = Add<HConstant>(i);
5758 switch (boilerplate_elements_kind) {
5759 case FAST_SMI_ELEMENTS:
5760 case FAST_HOLEY_SMI_ELEMENTS:
5762 case FAST_HOLEY_ELEMENTS:
5763 case FAST_DOUBLE_ELEMENTS:
5764 case FAST_HOLEY_DOUBLE_ELEMENTS: {
5765 HStoreKeyed* instr = Add<HStoreKeyed>(elements, key, value,
5766 boilerplate_elements_kind);
5767 instr->SetUninitialized(uninitialized);
5775 Add<HSimulate>(expr->GetIdForElement(i));
5778 Drop(1); // array literal index
5779 return ast_context()->ReturnValue(Pop());
5783 HCheckMaps* HOptimizedGraphBuilder::AddCheckMap(HValue* object,
5785 BuildCheckHeapObject(object);
5786 return Add<HCheckMaps>(object, map);
5790 HInstruction* HOptimizedGraphBuilder::BuildLoadNamedField(
5791 PropertyAccessInfo* info,
5792 HValue* checked_object) {
5793 // See if this is a load for an immutable property
5794 if (checked_object->ActualValue()->IsConstant() &&
5795 info->lookup()->IsCacheable() &&
5796 info->lookup()->IsReadOnly() && info->lookup()->IsDontDelete()) {
5797 Handle<Object> object(
5798 HConstant::cast(checked_object->ActualValue())->handle(isolate()));
5800 if (object->IsJSObject()) {
5801 LookupResult lookup(isolate());
5802 Handle<JSObject>::cast(object)->Lookup(info->name(), &lookup);
5803 Handle<Object> value(lookup.GetLazyValue(), isolate());
5805 DCHECK(!value->IsTheHole());
5806 return New<HConstant>(value);
5810 HObjectAccess access = info->access();
5811 if (access.representation().IsDouble()) {
5812 // Load the heap number.
5813 checked_object = Add<HLoadNamedField>(
5814 checked_object, static_cast<HValue*>(NULL),
5815 access.WithRepresentation(Representation::Tagged()));
5816 // Load the double value from it.
5817 access = HObjectAccess::ForHeapNumberValue();
5820 SmallMapList* map_list = info->field_maps();
5821 if (map_list->length() == 0) {
5822 return New<HLoadNamedField>(checked_object, checked_object, access);
5825 UniqueSet<Map>* maps = new(zone()) UniqueSet<Map>(map_list->length(), zone());
5826 for (int i = 0; i < map_list->length(); ++i) {
5827 maps->Add(Unique<Map>::CreateImmovable(map_list->at(i)), zone());
5829 return New<HLoadNamedField>(
5830 checked_object, checked_object, access, maps, info->field_type());
5834 HInstruction* HOptimizedGraphBuilder::BuildStoreNamedField(
5835 PropertyAccessInfo* info,
5836 HValue* checked_object,
5838 bool transition_to_field = info->lookup()->IsTransition();
5839 // TODO(verwaest): Move this logic into PropertyAccessInfo.
5840 HObjectAccess field_access = info->access();
5842 HStoreNamedField *instr;
5843 if (field_access.representation().IsDouble()) {
5844 HObjectAccess heap_number_access =
5845 field_access.WithRepresentation(Representation::Tagged());
5846 if (transition_to_field) {
5847 // The store requires a mutable HeapNumber to be allocated.
5848 NoObservableSideEffectsScope no_side_effects(this);
5849 HInstruction* heap_number_size = Add<HConstant>(HeapNumber::kSize);
5851 // TODO(hpayer): Allocation site pretenuring support.
5852 HInstruction* heap_number = Add<HAllocate>(heap_number_size,
5853 HType::HeapObject(),
5855 MUTABLE_HEAP_NUMBER_TYPE);
5856 AddStoreMapConstant(
5857 heap_number, isolate()->factory()->mutable_heap_number_map());
5858 Add<HStoreNamedField>(heap_number, HObjectAccess::ForHeapNumberValue(),
5860 instr = New<HStoreNamedField>(checked_object->ActualValue(),
5864 // Already holds a HeapNumber; load the box and write its value field.
5865 HInstruction* heap_number = Add<HLoadNamedField>(
5866 checked_object, static_cast<HValue*>(NULL), heap_number_access);
5867 instr = New<HStoreNamedField>(heap_number,
5868 HObjectAccess::ForHeapNumberValue(),
5869 value, STORE_TO_INITIALIZED_ENTRY);
5872 if (field_access.representation().IsHeapObject()) {
5873 BuildCheckHeapObject(value);
5876 if (!info->field_maps()->is_empty()) {
5877 DCHECK(field_access.representation().IsHeapObject());
5878 value = Add<HCheckMaps>(value, info->field_maps());
5881 // This is a normal store.
5882 instr = New<HStoreNamedField>(
5883 checked_object->ActualValue(), field_access, value,
5884 transition_to_field ? INITIALIZING_STORE : STORE_TO_INITIALIZED_ENTRY);
5887 if (transition_to_field) {
5888 Handle<Map> transition(info->transition());
5889 DCHECK(!transition->is_deprecated());
5890 instr->SetTransition(Add<HConstant>(transition));
5896 bool HOptimizedGraphBuilder::PropertyAccessInfo::IsCompatible(
5897 PropertyAccessInfo* info) {
5898 if (!CanInlinePropertyAccess(type_)) return false;
5900 // Currently only handle Type::Number as a polymorphic case.
5901 // TODO(verwaest): Support monomorphic handling of numbers with a HCheckNumber
5903 if (type_->Is(Type::Number())) return false;
5905 // Values are only compatible for monomorphic load if they all behave the same
5906 // regarding value wrappers.
5907 if (type_->Is(Type::NumberOrString())) {
5908 if (!info->type_->Is(Type::NumberOrString())) return false;
5910 if (info->type_->Is(Type::NumberOrString())) return false;
5913 if (!LookupDescriptor()) return false;
5915 if (!lookup_.IsFound()) {
5916 return (!info->lookup_.IsFound() || info->has_holder()) &&
5917 map()->prototype() == info->map()->prototype();
5920 // Mismatch if the other access info found the property in the prototype
5922 if (info->has_holder()) return false;
5924 if (lookup_.IsPropertyCallbacks()) {
5925 return accessor_.is_identical_to(info->accessor_) &&
5926 api_holder_.is_identical_to(info->api_holder_);
5929 if (lookup_.IsConstant()) {
5930 return constant_.is_identical_to(info->constant_);
5933 DCHECK(lookup_.IsField());
5934 if (!info->lookup_.IsField()) return false;
5936 Representation r = access_.representation();
5938 if (!info->access_.representation().IsCompatibleForLoad(r)) return false;
5940 if (!info->access_.representation().IsCompatibleForStore(r)) return false;
5942 if (info->access_.offset() != access_.offset()) return false;
5943 if (info->access_.IsInobject() != access_.IsInobject()) return false;
5945 if (field_maps_.is_empty()) {
5946 info->field_maps_.Clear();
5947 } else if (!info->field_maps_.is_empty()) {
5948 for (int i = 0; i < field_maps_.length(); ++i) {
5949 info->field_maps_.AddMapIfMissing(field_maps_.at(i), info->zone());
5951 info->field_maps_.Sort();
5954 // We can only merge stores that agree on their field maps. The comparison
5955 // below is safe, since we keep the field maps sorted.
5956 if (field_maps_.length() != info->field_maps_.length()) return false;
5957 for (int i = 0; i < field_maps_.length(); ++i) {
5958 if (!field_maps_.at(i).is_identical_to(info->field_maps_.at(i))) {
5963 info->GeneralizeRepresentation(r);
5964 info->field_type_ = info->field_type_.Combine(field_type_);
5969 bool HOptimizedGraphBuilder::PropertyAccessInfo::LookupDescriptor() {
5970 if (!type_->IsClass()) return true;
5971 map()->LookupDescriptor(NULL, *name_, &lookup_);
5972 return LoadResult(map());
5976 bool HOptimizedGraphBuilder::PropertyAccessInfo::LoadResult(Handle<Map> map) {
5977 if (!IsLoad() && lookup_.IsProperty() &&
5978 (lookup_.IsReadOnly() || !lookup_.IsCacheable())) {
5982 if (lookup_.IsField()) {
5983 // Construct the object field access.
5984 access_ = HObjectAccess::ForField(map, &lookup_, name_);
5986 // Load field map for heap objects.
5988 } else if (lookup_.IsPropertyCallbacks()) {
5989 Handle<Object> callback(lookup_.GetValueFromMap(*map), isolate());
5990 if (!callback->IsAccessorPair()) return false;
5991 Object* raw_accessor = IsLoad()
5992 ? Handle<AccessorPair>::cast(callback)->getter()
5993 : Handle<AccessorPair>::cast(callback)->setter();
5994 if (!raw_accessor->IsJSFunction()) return false;
5995 Handle<JSFunction> accessor = handle(JSFunction::cast(raw_accessor));
5996 if (accessor->shared()->IsApiFunction()) {
5997 CallOptimization call_optimization(accessor);
5998 if (call_optimization.is_simple_api_call()) {
5999 CallOptimization::HolderLookup holder_lookup;
6000 Handle<Map> receiver_map = this->map();
6001 api_holder_ = call_optimization.LookupHolderOfExpectedType(
6002 receiver_map, &holder_lookup);
6005 accessor_ = accessor;
6006 } else if (lookup_.IsConstant()) {
6007 constant_ = handle(lookup_.GetConstantFromMap(*map), isolate());
6014 void HOptimizedGraphBuilder::PropertyAccessInfo::LoadFieldMaps(
6016 // Clear any previously collected field maps/type.
6017 field_maps_.Clear();
6018 field_type_ = HType::Tagged();
6020 // Figure out the field type from the accessor map.
6021 Handle<HeapType> field_type(lookup_.GetFieldTypeFromMap(*map), isolate());
6023 // Collect the (stable) maps from the field type.
6024 int num_field_maps = field_type->NumClasses();
6025 if (num_field_maps == 0) return;
6026 DCHECK(access_.representation().IsHeapObject());
6027 field_maps_.Reserve(num_field_maps, zone());
6028 HeapType::Iterator<Map> it = field_type->Classes();
6029 while (!it.Done()) {
6030 Handle<Map> field_map = it.Current();
6031 if (!field_map->is_stable()) {
6032 field_maps_.Clear();
6035 field_maps_.Add(field_map, zone());
6039 DCHECK_EQ(num_field_maps, field_maps_.length());
6041 // Determine field HType from field HeapType.
6042 field_type_ = HType::FromType<HeapType>(field_type);
6043 DCHECK(field_type_.IsHeapObject());
6045 // Add dependency on the map that introduced the field.
6046 Map::AddDependentCompilationInfo(
6047 handle(lookup_.GetFieldOwnerFromMap(*map), isolate()),
6048 DependentCode::kFieldTypeGroup, top_info());
6052 bool HOptimizedGraphBuilder::PropertyAccessInfo::LookupInPrototypes() {
6053 Handle<Map> map = this->map();
6055 while (map->prototype()->IsJSObject()) {
6056 holder_ = handle(JSObject::cast(map->prototype()));
6057 if (holder_->map()->is_deprecated()) {
6058 JSObject::TryMigrateInstance(holder_);
6060 map = Handle<Map>(holder_->map());
6061 if (!CanInlinePropertyAccess(ToType(map))) {
6065 map->LookupDescriptor(*holder_, *name_, &lookup_);
6066 if (lookup_.IsFound()) return LoadResult(map);
6073 bool HOptimizedGraphBuilder::PropertyAccessInfo::CanAccessMonomorphic() {
6074 if (IsSIMD128PropertyCallback() &&
6075 CpuFeatures::SupportsSIMD128InCrankshaft()) {
6078 if (!CanInlinePropertyAccess(type_)) return false;
6079 if (IsJSObjectFieldAccessor()) return IsLoad();
6080 if (this->map()->function_with_prototype() &&
6081 !this->map()->has_non_instance_prototype() &&
6082 name_.is_identical_to(isolate()->factory()->prototype_string())) {
6085 if (!LookupDescriptor()) return false;
6086 if (lookup_.IsFound()) {
6087 if (IsLoad()) return true;
6088 return !lookup_.IsReadOnly() && lookup_.IsCacheable();
6090 if (!LookupInPrototypes()) return false;
6091 if (IsLoad()) return true;
6093 if (lookup_.IsPropertyCallbacks()) return true;
6094 Handle<Map> map = this->map();
6095 map->LookupTransition(NULL, *name_, &lookup_);
6096 if (lookup_.IsTransitionToField() && map->unused_property_fields() > 0) {
6097 // Construct the object field access.
6098 access_ = HObjectAccess::ForField(map, &lookup_, name_);
6100 // Load field map for heap objects.
6101 LoadFieldMaps(transition());
6108 bool HOptimizedGraphBuilder::PropertyAccessInfo::CanAccessAsMonomorphic(
6109 SmallMapList* types) {
6110 DCHECK(type_->Is(ToType(types->first())));
6111 if (!CanAccessMonomorphic()) return false;
6112 STATIC_ASSERT(kMaxLoadPolymorphism == kMaxStorePolymorphism);
6113 if (types->length() > kMaxLoadPolymorphism) return false;
6115 if (IsSIMD128PropertyCallback() &&
6116 CpuFeatures::SupportsSIMD128InCrankshaft()) {
6117 for (int i = 1; i < types->length(); ++i) {
6118 if (types->at(i)->instance_type() == types->first()->instance_type()) {
6125 HObjectAccess access = HObjectAccess::ForMap(); // bogus default
6126 if (GetJSObjectFieldAccess(&access)) {
6127 for (int i = 1; i < types->length(); ++i) {
6128 PropertyAccessInfo test_info(
6129 builder_, access_type_, ToType(types->at(i)), name_,
6130 types->at(i)->instance_type());
6131 HObjectAccess test_access = HObjectAccess::ForMap(); // bogus default
6132 if (!test_info.GetJSObjectFieldAccess(&test_access)) return false;
6133 if (!access.Equals(test_access)) return false;
6138 // Currently only handle Type::Number as a polymorphic case.
6139 // TODO(verwaest): Support monomorphic handling of numbers with a HCheckNumber
6141 if (type_->Is(Type::Number())) return false;
6143 // Multiple maps cannot transition to the same target map.
6144 DCHECK(!IsLoad() || !lookup_.IsTransition());
6145 if (lookup_.IsTransition() && types->length() > 1) return false;
6147 for (int i = 1; i < types->length(); ++i) {
6148 PropertyAccessInfo test_info(
6149 builder_, access_type_, ToType(types->at(i)), name_,
6150 types->at(i)->instance_type());
6151 if (!test_info.IsCompatible(this)) return false;
6158 Handle<Map> HOptimizedGraphBuilder::PropertyAccessInfo::map() {
6159 JSFunction* ctor = IC::GetRootConstructor(
6160 type_, current_info()->closure()->context()->native_context());
6161 if (ctor != NULL) return handle(ctor->initial_map());
6162 return type_->AsClass()->Map();
6166 static bool NeedsWrappingFor(Type* type, Handle<JSFunction> target) {
6167 return type->Is(Type::NumberOrString()) &&
6168 target->shared()->strict_mode() == SLOPPY &&
6169 !target->shared()->native();
6173 static bool IsSIMDProperty(Handle<String> name, uint8_t* mask) {
6174 SmartArrayPointer<char> cstring = name->ToCString();
6178 switch (cstring[i]) {
6190 *mask |= (shift << 2*i);
6198 HInstruction* HOptimizedGraphBuilder::BuildMonomorphicAccess(
6199 PropertyAccessInfo* info,
6201 HValue* checked_object,
6204 BailoutId return_id,
6205 bool can_inline_accessor) {
6207 HObjectAccess access = HObjectAccess::ForMap(); // bogus default
6208 if (info->GetJSObjectFieldAccess(&access)) {
6209 DCHECK(info->IsLoad());
6210 return New<HLoadNamedField>(object, checked_object, access);
6213 if (info->name().is_identical_to(isolate()->factory()->prototype_string()) &&
6214 info->map()->function_with_prototype()) {
6215 DCHECK(!info->map()->has_non_instance_prototype());
6216 return New<HLoadFunctionPrototype>(checked_object);
6219 HValue* checked_holder = checked_object;
6220 if (info->has_holder()) {
6221 Handle<JSObject> prototype(JSObject::cast(info->map()->prototype()));
6222 checked_holder = BuildCheckPrototypeMaps(prototype, info->holder());
6225 if (!info->lookup()->IsFound()) {
6226 DCHECK(info->IsLoad());
6227 return graph()->GetConstantUndefined();
6230 if (info->lookup()->IsField()) {
6231 if (info->IsLoad()) {
6232 if (info->map()->constructor()->IsJSFunction()) {
6233 JSFunction* constructor = JSFunction::cast(info->map()->constructor());
6234 String* class_name =
6235 String::cast(constructor->shared()->instance_class_name());
6237 if (class_name->Equals(isolate()->heap()->simd()) &&
6238 IsSIMDProperty(info->name(), &mask) &&
6239 CpuFeatures::SupportsSIMD128InCrankshaft()) {
6240 return New<HConstant>(mask);
6243 return BuildLoadNamedField(info, checked_holder);
6245 return BuildStoreNamedField(info, checked_object, value);
6249 if (info->lookup()->IsTransition()) {
6250 DCHECK(!info->IsLoad());
6251 return BuildStoreNamedField(info, checked_object, value);
6254 if (info->lookup()->IsPropertyCallbacks()) {
6255 Push(checked_object);
6256 int argument_count = 1;
6257 if (!info->IsLoad()) {
6262 if (NeedsWrappingFor(info->type(), info->accessor())) {
6263 HValue* function = Add<HConstant>(info->accessor());
6264 PushArgumentsFromEnvironment(argument_count);
6265 return New<HCallFunction>(function, argument_count, WRAP_AND_CALL);
6266 } else if (FLAG_inline_accessors && can_inline_accessor) {
6267 bool success = info->IsLoad()
6268 ? TryInlineGetter(info->accessor(), info->map(), ast_id, return_id)
6270 info->accessor(), info->map(), ast_id, return_id, value);
6271 if (success || HasStackOverflow()) return NULL;
6274 PushArgumentsFromEnvironment(argument_count);
6275 return BuildCallConstantFunction(info->accessor(), argument_count);
6278 DCHECK(info->lookup()->IsConstant());
6279 if (info->IsLoad()) {
6280 return New<HConstant>(info->constant());
6282 return New<HCheckValue>(value, Handle<JSFunction>::cast(info->constant()));
6287 void HOptimizedGraphBuilder::HandlePolymorphicNamedFieldAccess(
6288 PropertyAccessType access_type,
6291 BailoutId return_id,
6294 SmallMapList* types,
6295 Handle<String> name) {
6296 // Something did not match; must use a polymorphic load.
6298 HBasicBlock* join = NULL;
6299 HBasicBlock* number_block = NULL;
6300 bool handled_string = false;
6302 bool handle_smi = false;
6303 STATIC_ASSERT(kMaxLoadPolymorphism == kMaxStorePolymorphism);
6304 for (int i = 0; i < types->length() && count < kMaxLoadPolymorphism; ++i) {
6305 PropertyAccessInfo info(
6306 this, access_type, ToType(types->at(i)), name,
6307 types->at(i)->instance_type());
6308 if (info.type()->Is(Type::String())) {
6309 if (handled_string) continue;
6310 handled_string = true;
6312 if (info.CanAccessMonomorphic()) {
6314 if (info.type()->Is(Type::Number())) {
6322 HControlInstruction* smi_check = NULL;
6323 handled_string = false;
6325 for (int i = 0; i < types->length() && count < kMaxLoadPolymorphism; ++i) {
6326 PropertyAccessInfo info(
6327 this, access_type, ToType(types->at(i)), name,
6328 types->at(i)->instance_type());
6329 if (info.type()->Is(Type::String())) {
6330 if (handled_string) continue;
6331 handled_string = true;
6333 if (!info.CanAccessMonomorphic()) continue;
6336 join = graph()->CreateBasicBlock();
6338 HBasicBlock* empty_smi_block = graph()->CreateBasicBlock();
6339 HBasicBlock* not_smi_block = graph()->CreateBasicBlock();
6340 number_block = graph()->CreateBasicBlock();
6341 smi_check = New<HIsSmiAndBranch>(
6342 object, empty_smi_block, not_smi_block);
6343 FinishCurrentBlock(smi_check);
6344 GotoNoSimulate(empty_smi_block, number_block);
6345 set_current_block(not_smi_block);
6347 BuildCheckHeapObject(object);
6351 HBasicBlock* if_true = graph()->CreateBasicBlock();
6352 HBasicBlock* if_false = graph()->CreateBasicBlock();
6353 HUnaryControlInstruction* compare;
6356 if (info.type()->Is(Type::Number())) {
6357 Handle<Map> heap_number_map = isolate()->factory()->heap_number_map();
6358 compare = New<HCompareMap>(object, heap_number_map, if_true, if_false);
6359 dependency = smi_check;
6360 } else if (info.type()->Is(Type::String())) {
6361 compare = New<HIsStringAndBranch>(object, if_true, if_false);
6362 dependency = compare;
6364 compare = New<HCompareMap>(object, info.map(), if_true, if_false);
6365 dependency = compare;
6367 FinishCurrentBlock(compare);
6369 if (info.type()->Is(Type::Number())) {
6370 GotoNoSimulate(if_true, number_block);
6371 if_true = number_block;
6374 set_current_block(if_true);
6376 HInstruction* access = BuildMonomorphicAccess(
6377 &info, object, dependency, value, ast_id,
6378 return_id, FLAG_polymorphic_inlining);
6380 HValue* result = NULL;
6381 switch (access_type) {
6390 if (access == NULL) {
6391 if (HasStackOverflow()) return;
6393 if (!access->IsLinked()) AddInstruction(access);
6394 if (!ast_context()->IsEffect()) Push(result);
6397 if (current_block() != NULL) Goto(join);
6398 set_current_block(if_false);
6401 // Finish up. Unconditionally deoptimize if we've handled all the maps we
6402 // know about and do not want to handle ones we've never seen. Otherwise
6403 // use a generic IC.
6404 if (count == types->length() && FLAG_deoptimize_uncommon_cases) {
6405 FinishExitWithHardDeoptimization("Uknown map in polymorphic access");
6407 HInstruction* instr = BuildNamedGeneric(access_type, expr, object, name,
6409 AddInstruction(instr);
6410 if (!ast_context()->IsEffect()) Push(access_type == LOAD ? instr : value);
6415 Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6416 if (!ast_context()->IsEffect()) ast_context()->ReturnValue(Pop());
6421 DCHECK(join != NULL);
6422 if (join->HasPredecessor()) {
6423 join->SetJoinId(ast_id);
6424 set_current_block(join);
6425 if (!ast_context()->IsEffect()) ast_context()->ReturnValue(Pop());
6427 set_current_block(NULL);
6432 static bool ComputeReceiverTypes(Expression* expr,
6436 SmallMapList* types = expr->GetReceiverTypes();
6438 bool monomorphic = expr->IsMonomorphic();
6439 if (types != NULL && receiver->HasMonomorphicJSObjectType()) {
6440 Map* root_map = receiver->GetMonomorphicJSObjectMap()->FindRootMap();
6441 types->FilterForPossibleTransitions(root_map);
6442 monomorphic = types->length() == 1;
6444 return monomorphic && CanInlinePropertyAccess(
6445 IC::MapToType<Type>(types->first(), zone));
6449 static bool AreStringTypes(SmallMapList* types) {
6450 for (int i = 0; i < types->length(); i++) {
6451 if (types->at(i)->instance_type() >= FIRST_NONSTRING_TYPE) return false;
6457 static bool AreInt32x4Types(SmallMapList* types) {
6458 if (types == NULL || types->length() == 0) return false;
6459 for (int i = 0; i < types->length(); i++) {
6460 if (types->at(i)->instance_type() != INT32x4_TYPE) return false;
6466 static bool AreFloat32x4Types(SmallMapList* types) {
6467 if (types == NULL || types->length() == 0) return false;
6468 for (int i = 0; i < types->length(); i++) {
6469 if (types->at(i)->instance_type() != FLOAT32x4_TYPE) return false;
6475 static bool AreFloat64x2Types(SmallMapList* types) {
6476 if (types == NULL || types->length() == 0) return false;
6477 for (int i = 0; i < types->length(); i++) {
6478 if (types->at(i)->instance_type() != FLOAT64x2_TYPE) return false;
6484 static BuiltinFunctionId NameToId(Isolate* isolate, Handle<String> name,
6485 InstanceType type) {
6486 BuiltinFunctionId id;
6487 if (name->Equals(isolate->heap()->signMask())) {
6488 if (type == FLOAT32x4_TYPE) {
6489 id = kFloat32x4GetSignMask;
6490 } else if (type == FLOAT64x2_TYPE) {
6491 id = kFloat64x2GetSignMask;
6493 DCHECK(type == INT32x4_TYPE);
6494 id = kInt32x4GetSignMask;
6496 } else if (name->Equals(isolate->heap()->x())) {
6497 if (type == FLOAT32x4_TYPE) {
6498 id = kFloat32x4GetX;
6499 } else if (type == FLOAT64x2_TYPE) {
6500 id = kFloat64x2GetX;
6502 DCHECK(type == INT32x4_TYPE);
6505 } else if (name->Equals(isolate->heap()->y())) {
6506 if (type == FLOAT32x4_TYPE) {
6507 id = kFloat32x4GetY;
6508 } else if (type == FLOAT64x2_TYPE) {
6509 id = kFloat64x2GetY;
6511 DCHECK(type == INT32x4_TYPE);
6514 } else if (name->Equals(isolate->heap()->z())) {
6515 id = type == FLOAT32x4_TYPE ? kFloat32x4GetZ : kInt32x4GetZ;
6516 } else if (name->Equals(isolate->heap()->w())) {
6517 id = type == FLOAT32x4_TYPE ? kFloat32x4GetW : kInt32x4GetW;
6518 } else if (name->Equals(isolate->heap()->flagX())) {
6519 DCHECK(type == INT32x4_TYPE);
6520 id = kInt32x4GetFlagX;
6521 } else if (name->Equals(isolate->heap()->flagY())) {
6522 DCHECK(type == INT32x4_TYPE);
6523 id = kInt32x4GetFlagY;
6524 } else if (name->Equals(isolate->heap()->flagZ())) {
6525 DCHECK(type == INT32x4_TYPE);
6526 id = kInt32x4GetFlagZ;
6527 } else if (name->Equals(isolate->heap()->flagW())) {
6528 DCHECK(type == INT32x4_TYPE);
6529 id = kInt32x4GetFlagW;
6532 id = kSIMD128Unreachable;
6539 void HOptimizedGraphBuilder::BuildStore(Expression* expr,
6542 BailoutId return_id,
6543 bool is_uninitialized) {
6544 if (!prop->key()->IsPropertyName()) {
6546 HValue* value = environment()->ExpressionStackAt(0);
6547 HValue* key = environment()->ExpressionStackAt(1);
6548 HValue* object = environment()->ExpressionStackAt(2);
6549 bool has_side_effects = false;
6550 HandleKeyedElementAccess(object, key, value, expr,
6551 STORE, &has_side_effects);
6554 Add<HSimulate>(return_id, REMOVABLE_SIMULATE);
6555 return ast_context()->ReturnValue(Pop());
6559 HValue* value = Pop();
6560 HValue* object = Pop();
6562 Literal* key = prop->key()->AsLiteral();
6563 Handle<String> name = Handle<String>::cast(key->value());
6564 DCHECK(!name.is_null());
6566 HInstruction* instr = BuildNamedAccess(STORE, ast_id, return_id, expr,
6567 object, name, value, is_uninitialized);
6568 if (instr == NULL) return;
6570 if (!ast_context()->IsEffect()) Push(value);
6571 AddInstruction(instr);
6572 if (instr->HasObservableSideEffects()) {
6573 Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6575 if (!ast_context()->IsEffect()) Drop(1);
6576 return ast_context()->ReturnValue(value);
6580 void HOptimizedGraphBuilder::HandlePropertyAssignment(Assignment* expr) {
6581 Property* prop = expr->target()->AsProperty();
6582 DCHECK(prop != NULL);
6583 CHECK_ALIVE(VisitForValue(prop->obj()));
6584 if (!prop->key()->IsPropertyName()) {
6585 CHECK_ALIVE(VisitForValue(prop->key()));
6587 CHECK_ALIVE(VisitForValue(expr->value()));
6588 BuildStore(expr, prop, expr->id(),
6589 expr->AssignmentId(), expr->IsUninitialized());
6593 // Because not every expression has a position and there is not common
6594 // superclass of Assignment and CountOperation, we cannot just pass the
6595 // owning expression instead of position and ast_id separately.
6596 void HOptimizedGraphBuilder::HandleGlobalVariableAssignment(
6600 LookupResult lookup(isolate());
6601 GlobalPropertyAccess type = LookupGlobalProperty(var, &lookup, STORE);
6602 if (type == kUseCell) {
6603 Handle<GlobalObject> global(current_info()->global_object());
6604 Handle<PropertyCell> cell(global->GetPropertyCell(&lookup));
6605 if (cell->type()->IsConstant()) {
6606 Handle<Object> constant = cell->type()->AsConstant()->Value();
6607 if (value->IsConstant()) {
6608 HConstant* c_value = HConstant::cast(value);
6609 if (!constant.is_identical_to(c_value->handle(isolate()))) {
6610 Add<HDeoptimize>("Constant global variable assignment",
6611 Deoptimizer::EAGER);
6614 HValue* c_constant = Add<HConstant>(constant);
6615 IfBuilder builder(this);
6616 if (constant->IsNumber()) {
6617 builder.If<HCompareNumericAndBranch>(value, c_constant, Token::EQ);
6619 builder.If<HCompareObjectEqAndBranch>(value, c_constant);
6623 Add<HDeoptimize>("Constant global variable assignment",
6624 Deoptimizer::EAGER);
6628 HInstruction* instr =
6629 Add<HStoreGlobalCell>(value, cell, lookup.GetPropertyDetails());
6630 if (instr->HasObservableSideEffects()) {
6631 Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6634 HValue* global_object = Add<HLoadNamedField>(
6635 context(), static_cast<HValue*>(NULL),
6636 HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
6637 HStoreNamedGeneric* instr =
6638 Add<HStoreNamedGeneric>(global_object, var->name(),
6639 value, function_strict_mode());
6641 DCHECK(instr->HasObservableSideEffects());
6642 Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6647 void HOptimizedGraphBuilder::HandleCompoundAssignment(Assignment* expr) {
6648 Expression* target = expr->target();
6649 VariableProxy* proxy = target->AsVariableProxy();
6650 Property* prop = target->AsProperty();
6651 DCHECK(proxy == NULL || prop == NULL);
6653 // We have a second position recorded in the FullCodeGenerator to have
6654 // type feedback for the binary operation.
6655 BinaryOperation* operation = expr->binary_operation();
6657 if (proxy != NULL) {
6658 Variable* var = proxy->var();
6659 if (var->mode() == LET) {
6660 return Bailout(kUnsupportedLetCompoundAssignment);
6663 CHECK_ALIVE(VisitForValue(operation));
6665 switch (var->location()) {
6666 case Variable::UNALLOCATED:
6667 HandleGlobalVariableAssignment(var,
6669 expr->AssignmentId());
6672 case Variable::PARAMETER:
6673 case Variable::LOCAL:
6674 if (var->mode() == CONST_LEGACY) {
6675 return Bailout(kUnsupportedConstCompoundAssignment);
6677 BindIfLive(var, Top());
6680 case Variable::CONTEXT: {
6681 // Bail out if we try to mutate a parameter value in a function
6682 // using the arguments object. We do not (yet) correctly handle the
6683 // arguments property of the function.
6684 if (current_info()->scope()->arguments() != NULL) {
6685 // Parameters will be allocated to context slots. We have no
6686 // direct way to detect that the variable is a parameter so we do
6687 // a linear search of the parameter variables.
6688 int count = current_info()->scope()->num_parameters();
6689 for (int i = 0; i < count; ++i) {
6690 if (var == current_info()->scope()->parameter(i)) {
6691 Bailout(kAssignmentToParameterFunctionUsesArgumentsObject);
6696 HStoreContextSlot::Mode mode;
6698 switch (var->mode()) {
6700 mode = HStoreContextSlot::kCheckDeoptimize;
6703 // This case is checked statically so no need to
6704 // perform checks here
6707 return ast_context()->ReturnValue(Pop());
6709 mode = HStoreContextSlot::kNoCheck;
6712 HValue* context = BuildContextChainWalk(var);
6713 HStoreContextSlot* instr = Add<HStoreContextSlot>(
6714 context, var->index(), mode, Top());
6715 if (instr->HasObservableSideEffects()) {
6716 Add<HSimulate>(expr->AssignmentId(), REMOVABLE_SIMULATE);
6721 case Variable::LOOKUP:
6722 return Bailout(kCompoundAssignmentToLookupSlot);
6724 return ast_context()->ReturnValue(Pop());
6726 } else if (prop != NULL) {
6727 CHECK_ALIVE(VisitForValue(prop->obj()));
6728 HValue* object = Top();
6730 if (!prop->key()->IsPropertyName() || prop->IsStringAccess()) {
6731 CHECK_ALIVE(VisitForValue(prop->key()));
6735 CHECK_ALIVE(PushLoad(prop, object, key));
6737 CHECK_ALIVE(VisitForValue(expr->value()));
6738 HValue* right = Pop();
6739 HValue* left = Pop();
6741 Push(BuildBinaryOperation(operation, left, right, PUSH_BEFORE_SIMULATE));
6743 BuildStore(expr, prop, expr->id(),
6744 expr->AssignmentId(), expr->IsUninitialized());
6746 return Bailout(kInvalidLhsInCompoundAssignment);
6751 void HOptimizedGraphBuilder::VisitAssignment(Assignment* expr) {
6752 DCHECK(!HasStackOverflow());
6753 DCHECK(current_block() != NULL);
6754 DCHECK(current_block()->HasPredecessor());
6755 VariableProxy* proxy = expr->target()->AsVariableProxy();
6756 Property* prop = expr->target()->AsProperty();
6757 DCHECK(proxy == NULL || prop == NULL);
6759 if (expr->is_compound()) {
6760 HandleCompoundAssignment(expr);
6765 HandlePropertyAssignment(expr);
6766 } else if (proxy != NULL) {
6767 Variable* var = proxy->var();
6769 if (var->mode() == CONST) {
6770 if (expr->op() != Token::INIT_CONST) {
6771 return Bailout(kNonInitializerAssignmentToConst);
6773 } else if (var->mode() == CONST_LEGACY) {
6774 if (expr->op() != Token::INIT_CONST_LEGACY) {
6775 CHECK_ALIVE(VisitForValue(expr->value()));
6776 return ast_context()->ReturnValue(Pop());
6779 if (var->IsStackAllocated()) {
6780 // We insert a use of the old value to detect unsupported uses of const
6781 // variables (e.g. initialization inside a loop).
6782 HValue* old_value = environment()->Lookup(var);
6783 Add<HUseConst>(old_value);
6787 if (proxy->IsArguments()) return Bailout(kAssignmentToArguments);
6789 // Handle the assignment.
6790 switch (var->location()) {
6791 case Variable::UNALLOCATED:
6792 CHECK_ALIVE(VisitForValue(expr->value()));
6793 HandleGlobalVariableAssignment(var,
6795 expr->AssignmentId());
6796 return ast_context()->ReturnValue(Pop());
6798 case Variable::PARAMETER:
6799 case Variable::LOCAL: {
6800 // Perform an initialization check for let declared variables
6802 if (var->mode() == LET && expr->op() == Token::ASSIGN) {
6803 HValue* env_value = environment()->Lookup(var);
6804 if (env_value == graph()->GetConstantHole()) {
6805 return Bailout(kAssignmentToLetVariableBeforeInitialization);
6808 // We do not allow the arguments object to occur in a context where it
6809 // may escape, but assignments to stack-allocated locals are
6811 CHECK_ALIVE(VisitForValue(expr->value(), ARGUMENTS_ALLOWED));
6812 HValue* value = Pop();
6813 BindIfLive(var, value);
6814 return ast_context()->ReturnValue(value);
6817 case Variable::CONTEXT: {
6818 // Bail out if we try to mutate a parameter value in a function using
6819 // the arguments object. We do not (yet) correctly handle the
6820 // arguments property of the function.
6821 if (current_info()->scope()->arguments() != NULL) {
6822 // Parameters will rewrite to context slots. We have no direct way
6823 // to detect that the variable is a parameter.
6824 int count = current_info()->scope()->num_parameters();
6825 for (int i = 0; i < count; ++i) {
6826 if (var == current_info()->scope()->parameter(i)) {
6827 return Bailout(kAssignmentToParameterInArgumentsObject);
6832 CHECK_ALIVE(VisitForValue(expr->value()));
6833 HStoreContextSlot::Mode mode;
6834 if (expr->op() == Token::ASSIGN) {
6835 switch (var->mode()) {
6837 mode = HStoreContextSlot::kCheckDeoptimize;
6840 // This case is checked statically so no need to
6841 // perform checks here
6844 return ast_context()->ReturnValue(Pop());
6846 mode = HStoreContextSlot::kNoCheck;
6848 } else if (expr->op() == Token::INIT_VAR ||
6849 expr->op() == Token::INIT_LET ||
6850 expr->op() == Token::INIT_CONST) {
6851 mode = HStoreContextSlot::kNoCheck;
6853 DCHECK(expr->op() == Token::INIT_CONST_LEGACY);
6855 mode = HStoreContextSlot::kCheckIgnoreAssignment;
6858 HValue* context = BuildContextChainWalk(var);
6859 HStoreContextSlot* instr = Add<HStoreContextSlot>(
6860 context, var->index(), mode, Top());
6861 if (instr->HasObservableSideEffects()) {
6862 Add<HSimulate>(expr->AssignmentId(), REMOVABLE_SIMULATE);
6864 return ast_context()->ReturnValue(Pop());
6867 case Variable::LOOKUP:
6868 return Bailout(kAssignmentToLOOKUPVariable);
6871 return Bailout(kInvalidLeftHandSideInAssignment);
6876 void HOptimizedGraphBuilder::VisitYield(Yield* expr) {
6877 // Generators are not optimized, so we should never get here.
6882 void HOptimizedGraphBuilder::VisitThrow(Throw* expr) {
6883 DCHECK(!HasStackOverflow());
6884 DCHECK(current_block() != NULL);
6885 DCHECK(current_block()->HasPredecessor());
6886 // We don't optimize functions with invalid left-hand sides in
6887 // assignments, count operations, or for-in. Consequently throw can
6888 // currently only occur in an effect context.
6889 DCHECK(ast_context()->IsEffect());
6890 CHECK_ALIVE(VisitForValue(expr->exception()));
6892 HValue* value = environment()->Pop();
6893 if (!FLAG_hydrogen_track_positions) SetSourcePosition(expr->position());
6894 Add<HPushArguments>(value);
6895 Add<HCallRuntime>(isolate()->factory()->empty_string(),
6896 Runtime::FunctionForId(Runtime::kThrow), 1);
6897 Add<HSimulate>(expr->id());
6899 // If the throw definitely exits the function, we can finish with a dummy
6900 // control flow at this point. This is not the case if the throw is inside
6901 // an inlined function which may be replaced.
6902 if (call_context() == NULL) {
6903 FinishExitCurrentBlock(New<HAbnormalExit>());
6908 HInstruction* HGraphBuilder::AddLoadStringInstanceType(HValue* string) {
6909 if (string->IsConstant()) {
6910 HConstant* c_string = HConstant::cast(string);
6911 if (c_string->HasStringValue()) {
6912 return Add<HConstant>(c_string->StringValue()->map()->instance_type());
6915 return Add<HLoadNamedField>(
6916 Add<HLoadNamedField>(string, static_cast<HValue*>(NULL),
6917 HObjectAccess::ForMap()),
6918 static_cast<HValue*>(NULL), HObjectAccess::ForMapInstanceType());
6922 HInstruction* HGraphBuilder::AddLoadStringLength(HValue* string) {
6923 if (string->IsConstant()) {
6924 HConstant* c_string = HConstant::cast(string);
6925 if (c_string->HasStringValue()) {
6926 return Add<HConstant>(c_string->StringValue()->length());
6929 return Add<HLoadNamedField>(string, static_cast<HValue*>(NULL),
6930 HObjectAccess::ForStringLength());
6934 HInstruction* HOptimizedGraphBuilder::BuildNamedGeneric(
6935 PropertyAccessType access_type,
6938 Handle<String> name,
6940 bool is_uninitialized) {
6941 if (is_uninitialized) {
6942 Add<HDeoptimize>("Insufficient type feedback for generic named access",
6945 if (access_type == LOAD) {
6946 HLoadNamedGeneric* result = New<HLoadNamedGeneric>(object, name);
6947 if (FLAG_vector_ics) {
6948 Handle<SharedFunctionInfo> current_shared =
6949 function_state()->compilation_info()->shared_info();
6950 result->SetVectorAndSlot(
6951 handle(current_shared->feedback_vector(), isolate()),
6952 expr->AsProperty()->PropertyFeedbackSlot());
6956 return New<HStoreNamedGeneric>(object, name, value, function_strict_mode());
6962 HInstruction* HOptimizedGraphBuilder::BuildKeyedGeneric(
6963 PropertyAccessType access_type,
6968 if (access_type == LOAD) {
6969 HLoadKeyedGeneric* result = New<HLoadKeyedGeneric>(object, key);
6970 if (FLAG_vector_ics) {
6971 Handle<SharedFunctionInfo> current_shared =
6972 function_state()->compilation_info()->shared_info();
6973 result->SetVectorAndSlot(
6974 handle(current_shared->feedback_vector(), isolate()),
6975 expr->AsProperty()->PropertyFeedbackSlot());
6979 return New<HStoreKeyedGeneric>(object, key, value, function_strict_mode());
6984 LoadKeyedHoleMode HOptimizedGraphBuilder::BuildKeyedHoleMode(Handle<Map> map) {
6985 // Loads from a "stock" fast holey double arrays can elide the hole check.
6986 LoadKeyedHoleMode load_mode = NEVER_RETURN_HOLE;
6987 if (*map == isolate()->get_initial_js_array_map(FAST_HOLEY_DOUBLE_ELEMENTS) &&
6988 isolate()->IsFastArrayConstructorPrototypeChainIntact()) {
6989 Handle<JSObject> prototype(JSObject::cast(map->prototype()), isolate());
6990 Handle<JSObject> object_prototype = isolate()->initial_object_prototype();
6991 BuildCheckPrototypeMaps(prototype, object_prototype);
6992 load_mode = ALLOW_RETURN_HOLE;
6993 graph()->MarkDependsOnEmptyArrayProtoElements();
7000 HInstruction* HOptimizedGraphBuilder::BuildMonomorphicElementAccess(
7006 PropertyAccessType access_type,
7007 KeyedAccessStoreMode store_mode) {
7008 HCheckMaps* checked_object = Add<HCheckMaps>(object, map, dependency);
7010 checked_object->ClearDependsOnFlag(kElementsKind);
7013 if (access_type == STORE && map->prototype()->IsJSObject()) {
7014 // monomorphic stores need a prototype chain check because shape
7015 // changes could allow callbacks on elements in the chain that
7016 // aren't compatible with monomorphic keyed stores.
7017 PrototypeIterator iter(map);
7018 JSObject* holder = NULL;
7019 while (!iter.IsAtEnd()) {
7020 holder = JSObject::cast(*PrototypeIterator::GetCurrent(iter));
7023 DCHECK(holder && holder->IsJSObject());
7025 BuildCheckPrototypeMaps(handle(JSObject::cast(map->prototype())),
7026 Handle<JSObject>(holder));
7029 LoadKeyedHoleMode load_mode = BuildKeyedHoleMode(map);
7030 return BuildUncheckedMonomorphicElementAccess(
7031 checked_object, key, val,
7032 map->instance_type() == JS_ARRAY_TYPE,
7033 map->elements_kind(), access_type,
7034 load_mode, store_mode);
7038 HInstruction* HOptimizedGraphBuilder::TryBuildConsolidatedElementLoad(
7042 SmallMapList* maps) {
7043 // For polymorphic loads of similar elements kinds (i.e. all tagged or all
7044 // double), always use the "worst case" code without a transition. This is
7045 // much faster than transitioning the elements to the worst case, trading a
7046 // HTransitionElements for a HCheckMaps, and avoiding mutation of the array.
7047 bool has_double_maps = false;
7048 bool has_smi_or_object_maps = false;
7049 bool has_js_array_access = false;
7050 bool has_non_js_array_access = false;
7051 bool has_seen_holey_elements = false;
7052 Handle<Map> most_general_consolidated_map;
7053 for (int i = 0; i < maps->length(); ++i) {
7054 Handle<Map> map = maps->at(i);
7055 if (!map->IsJSObjectMap()) return NULL;
7056 // Don't allow mixing of JSArrays with JSObjects.
7057 if (map->instance_type() == JS_ARRAY_TYPE) {
7058 if (has_non_js_array_access) return NULL;
7059 has_js_array_access = true;
7060 } else if (has_js_array_access) {
7063 has_non_js_array_access = true;
7065 // Don't allow mixed, incompatible elements kinds.
7066 if (map->has_fast_double_elements()) {
7067 if (has_smi_or_object_maps) return NULL;
7068 has_double_maps = true;
7069 } else if (map->has_fast_smi_or_object_elements()) {
7070 if (has_double_maps) return NULL;
7071 has_smi_or_object_maps = true;
7075 // Remember if we've ever seen holey elements.
7076 if (IsHoleyElementsKind(map->elements_kind())) {
7077 has_seen_holey_elements = true;
7079 // Remember the most general elements kind, the code for its load will
7080 // properly handle all of the more specific cases.
7081 if ((i == 0) || IsMoreGeneralElementsKindTransition(
7082 most_general_consolidated_map->elements_kind(),
7083 map->elements_kind())) {
7084 most_general_consolidated_map = map;
7087 if (!has_double_maps && !has_smi_or_object_maps) return NULL;
7089 HCheckMaps* checked_object = Add<HCheckMaps>(object, maps);
7090 // FAST_ELEMENTS is considered more general than FAST_HOLEY_SMI_ELEMENTS.
7091 // If we've seen both, the consolidated load must use FAST_HOLEY_ELEMENTS.
7092 ElementsKind consolidated_elements_kind = has_seen_holey_elements
7093 ? GetHoleyElementsKind(most_general_consolidated_map->elements_kind())
7094 : most_general_consolidated_map->elements_kind();
7095 HInstruction* instr = BuildUncheckedMonomorphicElementAccess(
7096 checked_object, key, val,
7097 most_general_consolidated_map->instance_type() == JS_ARRAY_TYPE,
7098 consolidated_elements_kind,
7099 LOAD, NEVER_RETURN_HOLE, STANDARD_STORE);
7104 HValue* HOptimizedGraphBuilder::HandlePolymorphicElementAccess(
7110 PropertyAccessType access_type,
7111 KeyedAccessStoreMode store_mode,
7112 bool* has_side_effects) {
7113 *has_side_effects = false;
7114 BuildCheckHeapObject(object);
7116 if (access_type == LOAD) {
7117 HInstruction* consolidated_load =
7118 TryBuildConsolidatedElementLoad(object, key, val, maps);
7119 if (consolidated_load != NULL) {
7120 *has_side_effects |= consolidated_load->HasObservableSideEffects();
7121 return consolidated_load;
7125 // Elements_kind transition support.
7126 MapHandleList transition_target(maps->length());
7127 // Collect possible transition targets.
7128 MapHandleList possible_transitioned_maps(maps->length());
7129 for (int i = 0; i < maps->length(); ++i) {
7130 Handle<Map> map = maps->at(i);
7131 ElementsKind elements_kind = map->elements_kind();
7132 if (IsFastElementsKind(elements_kind) &&
7133 elements_kind != GetInitialFastElementsKind()) {
7134 possible_transitioned_maps.Add(map);
7136 if (elements_kind == SLOPPY_ARGUMENTS_ELEMENTS) {
7137 HInstruction* result = BuildKeyedGeneric(access_type, expr, object, key,
7139 *has_side_effects = result->HasObservableSideEffects();
7140 return AddInstruction(result);
7143 // Get transition target for each map (NULL == no transition).
7144 for (int i = 0; i < maps->length(); ++i) {
7145 Handle<Map> map = maps->at(i);
7146 Handle<Map> transitioned_map =
7147 map->FindTransitionedMap(&possible_transitioned_maps);
7148 transition_target.Add(transitioned_map);
7151 MapHandleList untransitionable_maps(maps->length());
7152 HTransitionElementsKind* transition = NULL;
7153 for (int i = 0; i < maps->length(); ++i) {
7154 Handle<Map> map = maps->at(i);
7155 DCHECK(map->IsMap());
7156 if (!transition_target.at(i).is_null()) {
7157 DCHECK(Map::IsValidElementsTransition(
7158 map->elements_kind(),
7159 transition_target.at(i)->elements_kind()));
7160 transition = Add<HTransitionElementsKind>(object, map,
7161 transition_target.at(i));
7163 untransitionable_maps.Add(map);
7167 // If only one map is left after transitioning, handle this case
7169 DCHECK(untransitionable_maps.length() >= 1);
7170 if (untransitionable_maps.length() == 1) {
7171 Handle<Map> untransitionable_map = untransitionable_maps[0];
7172 HInstruction* instr = NULL;
7173 if (untransitionable_map->has_slow_elements_kind() ||
7174 !untransitionable_map->IsJSObjectMap()) {
7175 instr = AddInstruction(BuildKeyedGeneric(access_type, expr, object, key,
7178 instr = BuildMonomorphicElementAccess(
7179 object, key, val, transition, untransitionable_map, access_type,
7182 *has_side_effects |= instr->HasObservableSideEffects();
7183 return access_type == STORE ? NULL : instr;
7186 HBasicBlock* join = graph()->CreateBasicBlock();
7188 for (int i = 0; i < untransitionable_maps.length(); ++i) {
7189 Handle<Map> map = untransitionable_maps[i];
7190 if (!map->IsJSObjectMap()) continue;
7191 ElementsKind elements_kind = map->elements_kind();
7192 HBasicBlock* this_map = graph()->CreateBasicBlock();
7193 HBasicBlock* other_map = graph()->CreateBasicBlock();
7194 HCompareMap* mapcompare =
7195 New<HCompareMap>(object, map, this_map, other_map);
7196 FinishCurrentBlock(mapcompare);
7198 set_current_block(this_map);
7199 HInstruction* access = NULL;
7200 if (IsDictionaryElementsKind(elements_kind)) {
7201 access = AddInstruction(BuildKeyedGeneric(access_type, expr, object, key,
7204 DCHECK(IsFastElementsKind(elements_kind) ||
7205 IsExternalArrayElementsKind(elements_kind) ||
7206 IsFixedTypedArrayElementsKind(elements_kind));
7207 LoadKeyedHoleMode load_mode = BuildKeyedHoleMode(map);
7208 // Happily, mapcompare is a checked object.
7209 access = BuildUncheckedMonomorphicElementAccess(
7210 mapcompare, key, val,
7211 map->instance_type() == JS_ARRAY_TYPE,
7212 elements_kind, access_type,
7216 *has_side_effects |= access->HasObservableSideEffects();
7217 // The caller will use has_side_effects and add a correct Simulate.
7218 access->SetFlag(HValue::kHasNoObservableSideEffects);
7219 if (access_type == LOAD) {
7222 NoObservableSideEffectsScope scope(this);
7223 GotoNoSimulate(join);
7224 set_current_block(other_map);
7227 // Ensure that we visited at least one map above that goes to join. This is
7228 // necessary because FinishExitWithHardDeoptimization does an AbnormalExit
7229 // rather than joining the join block. If this becomes an issue, insert a
7230 // generic access in the case length() == 0.
7231 DCHECK(join->predecessors()->length() > 0);
7232 // Deopt if none of the cases matched.
7233 NoObservableSideEffectsScope scope(this);
7234 FinishExitWithHardDeoptimization("Unknown map in polymorphic element access");
7235 set_current_block(join);
7236 return access_type == STORE ? NULL : Pop();
7240 HValue* HOptimizedGraphBuilder::HandleKeyedElementAccess(
7245 PropertyAccessType access_type,
7246 bool* has_side_effects) {
7247 DCHECK(!expr->IsPropertyName());
7248 HInstruction* instr = NULL;
7250 SmallMapList* types;
7251 bool monomorphic = ComputeReceiverTypes(expr, obj, &types, zone());
7253 bool force_generic = false;
7254 if (access_type == STORE &&
7255 (monomorphic || (types != NULL && !types->is_empty()))) {
7256 // Stores can't be mono/polymorphic if their prototype chain has dictionary
7257 // elements. However a receiver map that has dictionary elements itself
7258 // should be left to normal mono/poly behavior (the other maps may benefit
7259 // from highly optimized stores).
7260 for (int i = 0; i < types->length(); i++) {
7261 Handle<Map> current_map = types->at(i);
7262 if (current_map->DictionaryElementsInPrototypeChainOnly()) {
7263 force_generic = true;
7264 monomorphic = false;
7271 Handle<Map> map = types->first();
7272 if (map->has_slow_elements_kind() || !map->IsJSObjectMap()) {
7273 instr = AddInstruction(BuildKeyedGeneric(access_type, expr, obj, key,
7276 BuildCheckHeapObject(obj);
7277 instr = BuildMonomorphicElementAccess(
7278 obj, key, val, NULL, map, access_type, expr->GetStoreMode());
7280 } else if (!force_generic && (types != NULL && !types->is_empty())) {
7281 return HandlePolymorphicElementAccess(
7282 expr, obj, key, val, types, access_type,
7283 expr->GetStoreMode(), has_side_effects);
7285 if (access_type == STORE) {
7286 if (expr->IsAssignment() &&
7287 expr->AsAssignment()->HasNoTypeInformation()) {
7288 Add<HDeoptimize>("Insufficient type feedback for keyed store",
7292 if (expr->AsProperty()->HasNoTypeInformation()) {
7293 Add<HDeoptimize>("Insufficient type feedback for keyed load",
7297 instr = AddInstruction(BuildKeyedGeneric(access_type, expr, obj, key, val));
7299 *has_side_effects = instr->HasObservableSideEffects();
7304 void HOptimizedGraphBuilder::EnsureArgumentsArePushedForAccess() {
7305 // Outermost function already has arguments on the stack.
7306 if (function_state()->outer() == NULL) return;
7308 if (function_state()->arguments_pushed()) return;
7310 // Push arguments when entering inlined function.
7311 HEnterInlined* entry = function_state()->entry();
7312 entry->set_arguments_pushed();
7314 HArgumentsObject* arguments = entry->arguments_object();
7315 const ZoneList<HValue*>* arguments_values = arguments->arguments_values();
7317 HInstruction* insert_after = entry;
7318 for (int i = 0; i < arguments_values->length(); i++) {
7319 HValue* argument = arguments_values->at(i);
7320 HInstruction* push_argument = New<HPushArguments>(argument);
7321 push_argument->InsertAfter(insert_after);
7322 insert_after = push_argument;
7325 HArgumentsElements* arguments_elements = New<HArgumentsElements>(true);
7326 arguments_elements->ClearFlag(HValue::kUseGVN);
7327 arguments_elements->InsertAfter(insert_after);
7328 function_state()->set_arguments_elements(arguments_elements);
7332 bool HOptimizedGraphBuilder::TryArgumentsAccess(Property* expr) {
7333 VariableProxy* proxy = expr->obj()->AsVariableProxy();
7334 if (proxy == NULL) return false;
7335 if (!proxy->var()->IsStackAllocated()) return false;
7336 if (!environment()->Lookup(proxy->var())->CheckFlag(HValue::kIsArguments)) {
7340 HInstruction* result = NULL;
7341 if (expr->key()->IsPropertyName()) {
7342 Handle<String> name = expr->key()->AsLiteral()->AsPropertyName();
7343 if (!name->IsOneByteEqualTo(STATIC_ASCII_VECTOR("length"))) return false;
7345 if (function_state()->outer() == NULL) {
7346 HInstruction* elements = Add<HArgumentsElements>(false);
7347 result = New<HArgumentsLength>(elements);
7349 // Number of arguments without receiver.
7350 int argument_count = environment()->
7351 arguments_environment()->parameter_count() - 1;
7352 result = New<HConstant>(argument_count);
7355 Push(graph()->GetArgumentsObject());
7356 CHECK_ALIVE_OR_RETURN(VisitForValue(expr->key()), true);
7357 HValue* key = Pop();
7358 Drop(1); // Arguments object.
7359 if (function_state()->outer() == NULL) {
7360 HInstruction* elements = Add<HArgumentsElements>(false);
7361 HInstruction* length = Add<HArgumentsLength>(elements);
7362 HInstruction* checked_key = Add<HBoundsCheck>(key, length);
7363 result = New<HAccessArgumentsAt>(elements, length, checked_key);
7365 EnsureArgumentsArePushedForAccess();
7367 // Number of arguments without receiver.
7368 HInstruction* elements = function_state()->arguments_elements();
7369 int argument_count = environment()->
7370 arguments_environment()->parameter_count() - 1;
7371 HInstruction* length = Add<HConstant>(argument_count);
7372 HInstruction* checked_key = Add<HBoundsCheck>(key, length);
7373 result = New<HAccessArgumentsAt>(elements, length, checked_key);
7376 ast_context()->ReturnInstruction(result, expr->id());
7381 HInstruction* HOptimizedGraphBuilder::BuildNamedAccess(
7382 PropertyAccessType access,
7384 BailoutId return_id,
7387 Handle<String> name,
7389 bool is_uninitialized) {
7390 SmallMapList* types;
7391 ComputeReceiverTypes(expr, object, &types, zone());
7392 DCHECK(types != NULL);
7394 if (types->length() > 0) {
7395 PropertyAccessInfo info(
7396 this, access, ToType(types->first()), name,
7397 types->first()->instance_type());
7398 if (!info.CanAccessAsMonomorphic(types)) {
7399 HandlePolymorphicNamedFieldAccess(
7400 access, expr, ast_id, return_id, object, value, types, name);
7404 HValue* checked_object;
7405 // Type::Number() is only supported by polymorphic load/call handling.
7406 DCHECK(!info.type()->Is(Type::Number()));
7407 BuildCheckHeapObject(object);
7409 if (AreStringTypes(types)) {
7411 Add<HCheckInstanceType>(object, HCheckInstanceType::IS_STRING);
7412 } else if (info.IsSIMD128PropertyCallback() &&
7413 AreFloat32x4Types(types) &&
7414 CpuFeatures::SupportsSIMD128InCrankshaft()) {
7415 Handle<JSFunction> function(
7416 isolate()->native_context()->float32x4_function());
7417 HInstruction* constant_function = Add<HConstant>(function);
7418 HObjectAccess map_access = HObjectAccess::ForPrototypeOrInitialMap();
7419 HInstruction* map = Add<HLoadNamedField>(
7420 constant_function, static_cast<HValue*>(NULL), map_access);
7421 HObjectAccess prototype_access = HObjectAccess::ForMapPrototype();
7422 HInstruction* prototype = Add<HLoadNamedField>(
7423 map, static_cast<HValue*>(NULL), prototype_access);
7424 Handle<Map> initial_function_prototype_map(
7425 isolate()->native_context()->float32x4_function_prototype_map());
7426 Add<HCheckMaps>(prototype, initial_function_prototype_map);
7427 BuiltinFunctionId id = NameToId(isolate(), name, FLOAT32x4_TYPE);
7428 return NewUncasted<HUnarySIMDOperation>(object, id);
7429 } else if (info.IsSIMD128PropertyCallback() &&
7430 AreFloat64x2Types(types) &&
7431 CpuFeatures::SupportsSIMD128InCrankshaft()) {
7432 Handle<JSFunction> function(
7433 isolate()->native_context()->float64x2_function());
7434 HInstruction* constant_function = Add<HConstant>(function);
7435 HObjectAccess map_access = HObjectAccess::ForPrototypeOrInitialMap();
7436 HInstruction* map = Add<HLoadNamedField>(
7437 constant_function, static_cast<HValue*>(NULL), map_access);
7438 HObjectAccess prototype_access = HObjectAccess::ForMapPrototype();
7439 HInstruction* prototype = Add<HLoadNamedField>(
7440 map, static_cast<HValue*>(NULL), prototype_access);
7441 Handle<Map> initial_function_prototype_map(
7442 isolate()->native_context()->float64x2_function_prototype_map());
7443 Add<HCheckMaps>(prototype, initial_function_prototype_map);
7444 BuiltinFunctionId id = NameToId(isolate(), name, FLOAT64x2_TYPE);
7445 return NewUncasted<HUnarySIMDOperation>(object, id);
7446 } else if (info.IsSIMD128PropertyCallback() &&
7447 AreInt32x4Types(types) &&
7448 CpuFeatures::SupportsSIMD128InCrankshaft()) {
7449 Handle<JSFunction> function(
7450 isolate()->native_context()->int32x4_function());
7451 HInstruction* constant_function = Add<HConstant>(function);
7452 HObjectAccess map_access = HObjectAccess::ForPrototypeOrInitialMap();
7453 HInstruction* map = Add<HLoadNamedField>(
7454 constant_function, static_cast<HValue*>(NULL), map_access);
7455 HObjectAccess prototype_access = HObjectAccess::ForMapPrototype();
7456 HInstruction* prototype = Add<HLoadNamedField>(
7457 map, static_cast<HValue*>(NULL), prototype_access);
7458 Handle<Map> initial_function_prototype_map(
7459 isolate()->native_context()->int32x4_function_prototype_map());
7460 Add<HCheckMaps>(prototype, initial_function_prototype_map);
7461 BuiltinFunctionId id = NameToId(isolate(), name, INT32x4_TYPE);
7462 return NewUncasted<HUnarySIMDOperation>(object, id);
7464 checked_object = Add<HCheckMaps>(object, types);
7466 return BuildMonomorphicAccess(
7467 &info, object, checked_object, value, ast_id, return_id);
7470 return BuildNamedGeneric(access, expr, object, name, value, is_uninitialized);
7474 void HOptimizedGraphBuilder::PushLoad(Property* expr,
7477 ValueContext for_value(this, ARGUMENTS_NOT_ALLOWED);
7479 if (key != NULL) Push(key);
7480 BuildLoad(expr, expr->LoadId());
7484 void HOptimizedGraphBuilder::BuildLoad(Property* expr,
7486 HInstruction* instr = NULL;
7487 if (expr->IsStringAccess()) {
7488 HValue* index = Pop();
7489 HValue* string = Pop();
7490 HInstruction* char_code = BuildStringCharCodeAt(string, index);
7491 AddInstruction(char_code);
7492 instr = NewUncasted<HStringCharFromCode>(char_code);
7494 } else if (expr->key()->IsPropertyName()) {
7495 Handle<String> name = expr->key()->AsLiteral()->AsPropertyName();
7496 HValue* object = Pop();
7498 instr = BuildNamedAccess(LOAD, ast_id, expr->LoadId(), expr,
7499 object, name, NULL, expr->IsUninitialized());
7500 if (instr == NULL) return;
7501 if (instr->IsLinked()) return ast_context()->ReturnValue(instr);
7504 HValue* key = Pop();
7505 HValue* obj = Pop();
7507 bool has_side_effects = false;
7508 HValue* load = HandleKeyedElementAccess(
7509 obj, key, NULL, expr, LOAD, &has_side_effects);
7510 if (has_side_effects) {
7511 if (ast_context()->IsEffect()) {
7512 Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
7515 Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
7519 return ast_context()->ReturnValue(load);
7521 return ast_context()->ReturnInstruction(instr, ast_id);
7525 void HOptimizedGraphBuilder::VisitProperty(Property* expr) {
7526 DCHECK(!HasStackOverflow());
7527 DCHECK(current_block() != NULL);
7528 DCHECK(current_block()->HasPredecessor());
7530 if (TryArgumentsAccess(expr)) return;
7532 CHECK_ALIVE(VisitForValue(expr->obj()));
7533 if (!expr->key()->IsPropertyName() || expr->IsStringAccess()) {
7534 CHECK_ALIVE(VisitForValue(expr->key()));
7537 BuildLoad(expr, expr->id());
7541 HInstruction* HGraphBuilder::BuildConstantMapCheck(Handle<JSObject> constant) {
7542 HCheckMaps* check = Add<HCheckMaps>(
7543 Add<HConstant>(constant), handle(constant->map()));
7544 check->ClearDependsOnFlag(kElementsKind);
7549 HInstruction* HGraphBuilder::BuildCheckPrototypeMaps(Handle<JSObject> prototype,
7550 Handle<JSObject> holder) {
7551 PrototypeIterator iter(isolate(), prototype,
7552 PrototypeIterator::START_AT_RECEIVER);
7553 while (holder.is_null() ||
7554 !PrototypeIterator::GetCurrent(iter).is_identical_to(holder)) {
7555 BuildConstantMapCheck(
7556 Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter)));
7558 if (iter.IsAtEnd()) {
7562 return BuildConstantMapCheck(
7563 Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter)));
7567 void HOptimizedGraphBuilder::AddCheckPrototypeMaps(Handle<JSObject> holder,
7568 Handle<Map> receiver_map) {
7569 if (!holder.is_null()) {
7570 Handle<JSObject> prototype(JSObject::cast(receiver_map->prototype()));
7571 BuildCheckPrototypeMaps(prototype, holder);
7576 HInstruction* HOptimizedGraphBuilder::NewPlainFunctionCall(
7577 HValue* fun, int argument_count, bool pass_argument_count) {
7578 return New<HCallJSFunction>(
7579 fun, argument_count, pass_argument_count);
7583 HInstruction* HOptimizedGraphBuilder::NewArgumentAdaptorCall(
7584 HValue* fun, HValue* context,
7585 int argument_count, HValue* expected_param_count) {
7586 CallInterfaceDescriptor* descriptor =
7587 isolate()->call_descriptor(Isolate::ArgumentAdaptorCall);
7589 HValue* arity = Add<HConstant>(argument_count - 1);
7591 HValue* op_vals[] = { context, fun, arity, expected_param_count };
7593 Handle<Code> adaptor =
7594 isolate()->builtins()->ArgumentsAdaptorTrampoline();
7595 HConstant* adaptor_value = Add<HConstant>(adaptor);
7597 return New<HCallWithDescriptor>(
7598 adaptor_value, argument_count, descriptor,
7599 Vector<HValue*>(op_vals, descriptor->GetEnvironmentLength()));
7603 HInstruction* HOptimizedGraphBuilder::BuildCallConstantFunction(
7604 Handle<JSFunction> jsfun, int argument_count) {
7605 HValue* target = Add<HConstant>(jsfun);
7606 // For constant functions, we try to avoid calling the
7607 // argument adaptor and instead call the function directly
7608 int formal_parameter_count = jsfun->shared()->formal_parameter_count();
7609 bool dont_adapt_arguments =
7610 (formal_parameter_count ==
7611 SharedFunctionInfo::kDontAdaptArgumentsSentinel);
7612 int arity = argument_count - 1;
7613 bool can_invoke_directly =
7614 dont_adapt_arguments || formal_parameter_count == arity;
7615 if (can_invoke_directly) {
7616 if (jsfun.is_identical_to(current_info()->closure())) {
7617 graph()->MarkRecursive();
7619 return NewPlainFunctionCall(target, argument_count, dont_adapt_arguments);
7621 HValue* param_count_value = Add<HConstant>(formal_parameter_count);
7622 HValue* context = Add<HLoadNamedField>(
7623 target, static_cast<HValue*>(NULL),
7624 HObjectAccess::ForFunctionContextPointer());
7625 return NewArgumentAdaptorCall(target, context,
7626 argument_count, param_count_value);
7633 class FunctionSorter {
7635 explicit FunctionSorter(int index = 0, int ticks = 0, int size = 0)
7636 : index_(index), ticks_(ticks), size_(size) {}
7638 int index() const { return index_; }
7639 int ticks() const { return ticks_; }
7640 int size() const { return size_; }
7649 inline bool operator<(const FunctionSorter& lhs, const FunctionSorter& rhs) {
7650 int diff = lhs.ticks() - rhs.ticks();
7651 if (diff != 0) return diff > 0;
7652 return lhs.size() < rhs.size();
7656 void HOptimizedGraphBuilder::HandlePolymorphicCallNamed(
7659 SmallMapList* types,
7660 Handle<String> name) {
7661 int argument_count = expr->arguments()->length() + 1; // Includes receiver.
7662 FunctionSorter order[kMaxCallPolymorphism];
7664 bool handle_smi = false;
7665 bool handled_string = false;
7666 int ordered_functions = 0;
7669 i < types->length() && ordered_functions < kMaxCallPolymorphism;
7671 PropertyAccessInfo info(
7672 this, LOAD, ToType(types->at(i)), name,
7673 types->at(i)->instance_type());
7674 if (info.CanAccessMonomorphic() &&
7675 info.lookup()->IsConstant() &&
7676 info.constant()->IsJSFunction()) {
7677 if (info.type()->Is(Type::String())) {
7678 if (handled_string) continue;
7679 handled_string = true;
7681 Handle<JSFunction> target = Handle<JSFunction>::cast(info.constant());
7682 if (info.type()->Is(Type::Number())) {
7685 expr->set_target(target);
7686 order[ordered_functions++] = FunctionSorter(
7687 i, target->shared()->profiler_ticks(), InliningAstSize(target));
7691 std::sort(order, order + ordered_functions);
7693 HBasicBlock* number_block = NULL;
7694 HBasicBlock* join = NULL;
7695 handled_string = false;
7698 for (int fn = 0; fn < ordered_functions; ++fn) {
7699 int i = order[fn].index();
7700 PropertyAccessInfo info(this, LOAD, ToType(types->at(i)), name,
7701 types->at(i)->instance_type());
7702 if (info.type()->Is(Type::String())) {
7703 if (handled_string) continue;
7704 handled_string = true;
7706 // Reloads the target.
7707 info.CanAccessMonomorphic();
7708 Handle<JSFunction> target = Handle<JSFunction>::cast(info.constant());
7710 expr->set_target(target);
7712 // Only needed once.
7713 join = graph()->CreateBasicBlock();
7715 HBasicBlock* empty_smi_block = graph()->CreateBasicBlock();
7716 HBasicBlock* not_smi_block = graph()->CreateBasicBlock();
7717 number_block = graph()->CreateBasicBlock();
7718 FinishCurrentBlock(New<HIsSmiAndBranch>(
7719 receiver, empty_smi_block, not_smi_block));
7720 GotoNoSimulate(empty_smi_block, number_block);
7721 set_current_block(not_smi_block);
7723 BuildCheckHeapObject(receiver);
7727 HBasicBlock* if_true = graph()->CreateBasicBlock();
7728 HBasicBlock* if_false = graph()->CreateBasicBlock();
7729 HUnaryControlInstruction* compare;
7731 Handle<Map> map = info.map();
7732 if (info.type()->Is(Type::Number())) {
7733 Handle<Map> heap_number_map = isolate()->factory()->heap_number_map();
7734 compare = New<HCompareMap>(receiver, heap_number_map, if_true, if_false);
7735 } else if (info.type()->Is(Type::String())) {
7736 compare = New<HIsStringAndBranch>(receiver, if_true, if_false);
7738 compare = New<HCompareMap>(receiver, map, if_true, if_false);
7740 FinishCurrentBlock(compare);
7742 if (info.type()->Is(Type::Number())) {
7743 GotoNoSimulate(if_true, number_block);
7744 if_true = number_block;
7747 set_current_block(if_true);
7749 AddCheckPrototypeMaps(info.holder(), map);
7751 HValue* function = Add<HConstant>(expr->target());
7752 environment()->SetExpressionStackAt(0, function);
7754 CHECK_ALIVE(VisitExpressions(expr->arguments()));
7755 bool needs_wrapping = NeedsWrappingFor(info.type(), target);
7756 bool try_inline = FLAG_polymorphic_inlining && !needs_wrapping;
7757 if (FLAG_trace_inlining && try_inline) {
7758 Handle<JSFunction> caller = current_info()->closure();
7759 SmartArrayPointer<char> caller_name =
7760 caller->shared()->DebugName()->ToCString();
7761 PrintF("Trying to inline the polymorphic call to %s from %s\n",
7762 name->ToCString().get(),
7765 if (try_inline && TryInlineCall(expr)) {
7766 // Trying to inline will signal that we should bailout from the
7767 // entire compilation by setting stack overflow on the visitor.
7768 if (HasStackOverflow()) return;
7770 // Since HWrapReceiver currently cannot actually wrap numbers and strings,
7771 // use the regular CallFunctionStub for method calls to wrap the receiver.
7772 // TODO(verwaest): Support creation of value wrappers directly in
7774 HInstruction* call = needs_wrapping
7775 ? NewUncasted<HCallFunction>(
7776 function, argument_count, WRAP_AND_CALL)
7777 : BuildCallConstantFunction(target, argument_count);
7778 PushArgumentsFromEnvironment(argument_count);
7779 AddInstruction(call);
7780 Drop(1); // Drop the function.
7781 if (!ast_context()->IsEffect()) Push(call);
7784 if (current_block() != NULL) Goto(join);
7785 set_current_block(if_false);
7788 // Finish up. Unconditionally deoptimize if we've handled all the maps we
7789 // know about and do not want to handle ones we've never seen. Otherwise
7790 // use a generic IC.
7791 if (ordered_functions == types->length() && FLAG_deoptimize_uncommon_cases) {
7792 FinishExitWithHardDeoptimization("Unknown map in polymorphic call");
7794 Property* prop = expr->expression()->AsProperty();
7795 HInstruction* function = BuildNamedGeneric(
7796 LOAD, prop, receiver, name, NULL, prop->IsUninitialized());
7797 AddInstruction(function);
7799 AddSimulate(prop->LoadId(), REMOVABLE_SIMULATE);
7801 environment()->SetExpressionStackAt(1, function);
7802 environment()->SetExpressionStackAt(0, receiver);
7803 CHECK_ALIVE(VisitExpressions(expr->arguments()));
7805 CallFunctionFlags flags = receiver->type().IsJSObject()
7806 ? NO_CALL_FUNCTION_FLAGS : CALL_AS_METHOD;
7807 HInstruction* call = New<HCallFunction>(
7808 function, argument_count, flags);
7810 PushArgumentsFromEnvironment(argument_count);
7812 Drop(1); // Function.
7815 AddInstruction(call);
7816 if (!ast_context()->IsEffect()) Push(call);
7819 return ast_context()->ReturnInstruction(call, expr->id());
7823 // We assume that control flow is always live after an expression. So
7824 // even without predecessors to the join block, we set it as the exit
7825 // block and continue by adding instructions there.
7826 DCHECK(join != NULL);
7827 if (join->HasPredecessor()) {
7828 set_current_block(join);
7829 join->SetJoinId(expr->id());
7830 if (!ast_context()->IsEffect()) return ast_context()->ReturnValue(Pop());
7832 set_current_block(NULL);
7837 void HOptimizedGraphBuilder::TraceInline(Handle<JSFunction> target,
7838 Handle<JSFunction> caller,
7839 const char* reason) {
7840 if (FLAG_trace_inlining) {
7841 SmartArrayPointer<char> target_name =
7842 target->shared()->DebugName()->ToCString();
7843 SmartArrayPointer<char> caller_name =
7844 caller->shared()->DebugName()->ToCString();
7845 if (reason == NULL) {
7846 PrintF("Inlined %s called from %s.\n", target_name.get(),
7849 PrintF("Did not inline %s called from %s (%s).\n",
7850 target_name.get(), caller_name.get(), reason);
7856 static const int kNotInlinable = 1000000000;
7859 int HOptimizedGraphBuilder::InliningAstSize(Handle<JSFunction> target) {
7860 if (!FLAG_use_inlining) return kNotInlinable;
7862 // Precondition: call is monomorphic and we have found a target with the
7863 // appropriate arity.
7864 Handle<JSFunction> caller = current_info()->closure();
7865 Handle<SharedFunctionInfo> target_shared(target->shared());
7867 // Always inline builtins marked for inlining.
7868 if (target->IsBuiltin()) {
7869 return target_shared->inline_builtin() ? 0 : kNotInlinable;
7872 if (target_shared->IsApiFunction()) {
7873 TraceInline(target, caller, "target is api function");
7874 return kNotInlinable;
7877 // Do a quick check on source code length to avoid parsing large
7878 // inlining candidates.
7879 if (target_shared->SourceSize() >
7880 Min(FLAG_max_inlined_source_size, kUnlimitedMaxInlinedSourceSize)) {
7881 TraceInline(target, caller, "target text too big");
7882 return kNotInlinable;
7885 // Target must be inlineable.
7886 if (!target_shared->IsInlineable()) {
7887 TraceInline(target, caller, "target not inlineable");
7888 return kNotInlinable;
7890 if (target_shared->DisableOptimizationReason() != kNoReason) {
7891 TraceInline(target, caller, "target contains unsupported syntax [early]");
7892 return kNotInlinable;
7895 int nodes_added = target_shared->ast_node_count();
7900 bool HOptimizedGraphBuilder::TryInline(Handle<JSFunction> target,
7901 int arguments_count,
7902 HValue* implicit_return_value,
7904 BailoutId return_id,
7905 InliningKind inlining_kind,
7906 HSourcePosition position) {
7907 int nodes_added = InliningAstSize(target);
7908 if (nodes_added == kNotInlinable) return false;
7910 Handle<JSFunction> caller = current_info()->closure();
7912 if (nodes_added > Min(FLAG_max_inlined_nodes, kUnlimitedMaxInlinedNodes)) {
7913 TraceInline(target, caller, "target AST is too large [early]");
7917 // Don't inline deeper than the maximum number of inlining levels.
7918 HEnvironment* env = environment();
7919 int current_level = 1;
7920 while (env->outer() != NULL) {
7921 if (current_level == FLAG_max_inlining_levels) {
7922 TraceInline(target, caller, "inline depth limit reached");
7925 if (env->outer()->frame_type() == JS_FUNCTION) {
7931 // Don't inline recursive functions.
7932 for (FunctionState* state = function_state();
7934 state = state->outer()) {
7935 if (*state->compilation_info()->closure() == *target) {
7936 TraceInline(target, caller, "target is recursive");
7941 // We don't want to add more than a certain number of nodes from inlining.
7942 if (inlined_count_ > Min(FLAG_max_inlined_nodes_cumulative,
7943 kUnlimitedMaxInlinedNodesCumulative)) {
7944 TraceInline(target, caller, "cumulative AST node limit reached");
7948 // Parse and allocate variables.
7949 CompilationInfo target_info(target, zone());
7950 // Use the same AstValueFactory for creating strings in the sub-compilation
7951 // step, but don't transfer ownership to target_info.
7952 target_info.SetAstValueFactory(top_info()->ast_value_factory(), false);
7953 Handle<SharedFunctionInfo> target_shared(target->shared());
7954 if (!Parser::Parse(&target_info) || !Scope::Analyze(&target_info)) {
7955 if (target_info.isolate()->has_pending_exception()) {
7956 // Parse or scope error, never optimize this function.
7958 target_shared->DisableOptimization(kParseScopeError);
7960 TraceInline(target, caller, "parse failure");
7964 if (target_info.scope()->num_heap_slots() > 0) {
7965 TraceInline(target, caller, "target has context-allocated variables");
7968 FunctionLiteral* function = target_info.function();
7970 // The following conditions must be checked again after re-parsing, because
7971 // earlier the information might not have been complete due to lazy parsing.
7972 nodes_added = function->ast_node_count();
7973 if (nodes_added > Min(FLAG_max_inlined_nodes, kUnlimitedMaxInlinedNodes)) {
7974 TraceInline(target, caller, "target AST is too large [late]");
7977 if (function->dont_optimize()) {
7978 TraceInline(target, caller, "target contains unsupported syntax [late]");
7982 // If the function uses the arguments object check that inlining of functions
7983 // with arguments object is enabled and the arguments-variable is
7985 if (function->scope()->arguments() != NULL) {
7986 if (!FLAG_inline_arguments) {
7987 TraceInline(target, caller, "target uses arguments object");
7991 if (!function->scope()->arguments()->IsStackAllocated()) {
7994 "target uses non-stackallocated arguments object");
7999 // All declarations must be inlineable.
8000 ZoneList<Declaration*>* decls = target_info.scope()->declarations();
8001 int decl_count = decls->length();
8002 for (int i = 0; i < decl_count; ++i) {
8003 if (!decls->at(i)->IsInlineable()) {
8004 TraceInline(target, caller, "target has non-trivial declaration");
8009 // Generate the deoptimization data for the unoptimized version of
8010 // the target function if we don't already have it.
8011 if (!target_shared->has_deoptimization_support()) {
8012 // Note that we compile here using the same AST that we will use for
8013 // generating the optimized inline code.
8014 target_info.EnableDeoptimizationSupport();
8015 if (!FullCodeGenerator::MakeCode(&target_info)) {
8016 TraceInline(target, caller, "could not generate deoptimization info");
8019 if (target_shared->scope_info() == ScopeInfo::Empty(isolate())) {
8020 // The scope info might not have been set if a lazily compiled
8021 // function is inlined before being called for the first time.
8022 Handle<ScopeInfo> target_scope_info =
8023 ScopeInfo::Create(target_info.scope(), zone());
8024 target_shared->set_scope_info(*target_scope_info);
8026 target_shared->EnableDeoptimizationSupport(*target_info.code());
8027 target_shared->set_feedback_vector(*target_info.feedback_vector());
8028 Compiler::RecordFunctionCompilation(Logger::FUNCTION_TAG,
8033 // ----------------------------------------------------------------
8034 // After this point, we've made a decision to inline this function (so
8035 // TryInline should always return true).
8037 // Type-check the inlined function.
8038 DCHECK(target_shared->has_deoptimization_support());
8039 AstTyper::Run(&target_info);
8041 int function_id = graph()->TraceInlinedFunction(target_shared, position);
8043 // Save the pending call context. Set up new one for the inlined function.
8044 // The function state is new-allocated because we need to delete it
8045 // in two different places.
8046 FunctionState* target_state = new FunctionState(
8047 this, &target_info, inlining_kind, function_id);
8049 HConstant* undefined = graph()->GetConstantUndefined();
8051 HEnvironment* inner_env =
8052 environment()->CopyForInlining(target,
8056 function_state()->inlining_kind());
8058 HConstant* context = Add<HConstant>(Handle<Context>(target->context()));
8059 inner_env->BindContext(context);
8061 // Create a dematerialized arguments object for the function, also copy the
8062 // current arguments values to use them for materialization.
8063 HEnvironment* arguments_env = inner_env->arguments_environment();
8064 int parameter_count = arguments_env->parameter_count();
8065 HArgumentsObject* arguments_object = Add<HArgumentsObject>(parameter_count);
8066 for (int i = 0; i < parameter_count; i++) {
8067 arguments_object->AddArgument(arguments_env->Lookup(i), zone());
8070 // If the function uses arguments object then bind bind one.
8071 if (function->scope()->arguments() != NULL) {
8072 DCHECK(function->scope()->arguments()->IsStackAllocated());
8073 inner_env->Bind(function->scope()->arguments(), arguments_object);
8076 // Capture the state before invoking the inlined function for deopt in the
8077 // inlined function. This simulate has no bailout-id since it's not directly
8078 // reachable for deopt, and is only used to capture the state. If the simulate
8079 // becomes reachable by merging, the ast id of the simulate merged into it is
8081 Add<HSimulate>(BailoutId::None());
8083 current_block()->UpdateEnvironment(inner_env);
8084 Scope* saved_scope = scope();
8085 set_scope(target_info.scope());
8086 HEnterInlined* enter_inlined =
8087 Add<HEnterInlined>(return_id, target, arguments_count, function,
8088 function_state()->inlining_kind(),
8089 function->scope()->arguments(),
8091 function_state()->set_entry(enter_inlined);
8093 VisitDeclarations(target_info.scope()->declarations());
8094 VisitStatements(function->body());
8095 set_scope(saved_scope);
8096 if (HasStackOverflow()) {
8097 // Bail out if the inline function did, as we cannot residualize a call
8099 TraceInline(target, caller, "inline graph construction failed");
8100 target_shared->DisableOptimization(kInliningBailedOut);
8101 inline_bailout_ = true;
8102 delete target_state;
8106 // Update inlined nodes count.
8107 inlined_count_ += nodes_added;
8109 Handle<Code> unoptimized_code(target_shared->code());
8110 DCHECK(unoptimized_code->kind() == Code::FUNCTION);
8111 Handle<TypeFeedbackInfo> type_info(
8112 TypeFeedbackInfo::cast(unoptimized_code->type_feedback_info()));
8113 graph()->update_type_change_checksum(type_info->own_type_change_checksum());
8115 TraceInline(target, caller, NULL);
8117 if (current_block() != NULL) {
8118 FunctionState* state = function_state();
8119 if (state->inlining_kind() == CONSTRUCT_CALL_RETURN) {
8120 // Falling off the end of an inlined construct call. In a test context the
8121 // return value will always evaluate to true, in a value context the
8122 // return value is the newly allocated receiver.
8123 if (call_context()->IsTest()) {
8124 Goto(inlined_test_context()->if_true(), state);
8125 } else if (call_context()->IsEffect()) {
8126 Goto(function_return(), state);
8128 DCHECK(call_context()->IsValue());
8129 AddLeaveInlined(implicit_return_value, state);
8131 } else if (state->inlining_kind() == SETTER_CALL_RETURN) {
8132 // Falling off the end of an inlined setter call. The returned value is
8133 // never used, the value of an assignment is always the value of the RHS
8134 // of the assignment.
8135 if (call_context()->IsTest()) {
8136 inlined_test_context()->ReturnValue(implicit_return_value);
8137 } else if (call_context()->IsEffect()) {
8138 Goto(function_return(), state);
8140 DCHECK(call_context()->IsValue());
8141 AddLeaveInlined(implicit_return_value, state);
8144 // Falling off the end of a normal inlined function. This basically means
8145 // returning undefined.
8146 if (call_context()->IsTest()) {
8147 Goto(inlined_test_context()->if_false(), state);
8148 } else if (call_context()->IsEffect()) {
8149 Goto(function_return(), state);
8151 DCHECK(call_context()->IsValue());
8152 AddLeaveInlined(undefined, state);
8157 // Fix up the function exits.
8158 if (inlined_test_context() != NULL) {
8159 HBasicBlock* if_true = inlined_test_context()->if_true();
8160 HBasicBlock* if_false = inlined_test_context()->if_false();
8162 HEnterInlined* entry = function_state()->entry();
8164 // Pop the return test context from the expression context stack.
8165 DCHECK(ast_context() == inlined_test_context());
8166 ClearInlinedTestContext();
8167 delete target_state;
8169 // Forward to the real test context.
8170 if (if_true->HasPredecessor()) {
8171 entry->RegisterReturnTarget(if_true, zone());
8172 if_true->SetJoinId(ast_id);
8173 HBasicBlock* true_target = TestContext::cast(ast_context())->if_true();
8174 Goto(if_true, true_target, function_state());
8176 if (if_false->HasPredecessor()) {
8177 entry->RegisterReturnTarget(if_false, zone());
8178 if_false->SetJoinId(ast_id);
8179 HBasicBlock* false_target = TestContext::cast(ast_context())->if_false();
8180 Goto(if_false, false_target, function_state());
8182 set_current_block(NULL);
8185 } else if (function_return()->HasPredecessor()) {
8186 function_state()->entry()->RegisterReturnTarget(function_return(), zone());
8187 function_return()->SetJoinId(ast_id);
8188 set_current_block(function_return());
8190 set_current_block(NULL);
8192 delete target_state;
8197 bool HOptimizedGraphBuilder::TryInlineCall(Call* expr) {
8198 return TryInline(expr->target(),
8199 expr->arguments()->length(),
8204 ScriptPositionToSourcePosition(expr->position()));
8208 bool HOptimizedGraphBuilder::TryInlineConstruct(CallNew* expr,
8209 HValue* implicit_return_value) {
8210 return TryInline(expr->target(),
8211 expr->arguments()->length(),
8212 implicit_return_value,
8215 CONSTRUCT_CALL_RETURN,
8216 ScriptPositionToSourcePosition(expr->position()));
8220 bool HOptimizedGraphBuilder::TryInlineGetter(Handle<JSFunction> getter,
8221 Handle<Map> receiver_map,
8223 BailoutId return_id) {
8224 if (TryInlineApiGetter(getter, receiver_map, ast_id)) return true;
8225 return TryInline(getter,
8235 bool HOptimizedGraphBuilder::TryInlineSetter(Handle<JSFunction> setter,
8236 Handle<Map> receiver_map,
8238 BailoutId assignment_id,
8239 HValue* implicit_return_value) {
8240 if (TryInlineApiSetter(setter, receiver_map, id)) return true;
8241 return TryInline(setter,
8243 implicit_return_value,
8250 bool HOptimizedGraphBuilder::TryInlineApply(Handle<JSFunction> function,
8252 int arguments_count) {
8253 return TryInline(function,
8259 ScriptPositionToSourcePosition(expr->position()));
8263 bool HOptimizedGraphBuilder::TryInlineBuiltinFunctionCall(Call* expr) {
8264 if (!expr->target()->shared()->HasBuiltinFunctionId()) return false;
8265 BuiltinFunctionId id = expr->target()->shared()->builtin_function_id();
8268 if (!FLAG_fast_math) break;
8269 // Fall through if FLAG_fast_math.
8277 if (expr->arguments()->length() == 1) {
8278 HValue* argument = Pop();
8279 Drop(2); // Receiver and function.
8280 HInstruction* op = NewUncasted<HUnaryMathOperation>(argument, id);
8281 ast_context()->ReturnInstruction(op, expr->id());
8286 if (expr->arguments()->length() == 2) {
8287 HValue* right = Pop();
8288 HValue* left = Pop();
8289 Drop(2); // Receiver and function.
8290 HInstruction* op = HMul::NewImul(zone(), context(), left, right);
8291 ast_context()->ReturnInstruction(op, expr->id());
8295 #define SIMD_NULLARY_OPERATION_CASE_ITEM(p1, p2, name, p4) \
8297 SIMD_NULLARY_OPERATIONS(SIMD_NULLARY_OPERATION_CASE_ITEM)
8298 #undef SIMD_NULLARY_OPERATION_CASE_ITEM
8299 if (CpuFeatures::SupportsSIMD128InCrankshaft() &&
8300 expr->arguments()->length() == 0) {
8301 Drop(2); // Receiver and function.
8302 HInstruction* op = NewUncasted<HNullarySIMDOperation>(id);
8303 ast_context()->ReturnInstruction(op, expr->id());
8307 #define SIMD_UNARY_OPERATION_CASE_ITEM(p1, p2, name, p4, p5) \
8309 SIMD_UNARY_OPERATIONS(SIMD_UNARY_OPERATION_CASE_ITEM)
8310 #undef SIMD_UNARY_OPERATION_CASE_ITEM
8311 if (CpuFeatures::SupportsSIMD128InCrankshaft() &&
8312 expr->arguments()->length() == 1) {
8313 HValue* argument = Pop();
8314 Drop(2); // Receiver and function.
8315 HInstruction* op = NewUncasted<HUnarySIMDOperation>(argument, id);
8316 ast_context()->ReturnInstruction(op, expr->id());
8320 #define SIMD_BINARY_OPERATION_CASE_ITEM(p1, p2, name, p4, p5, p6) \
8322 SIMD_BINARY_OPERATIONS(SIMD_BINARY_OPERATION_CASE_ITEM)
8323 #undef SIMD_BINARY_OPERATION_CASE_ITEM
8324 if (CpuFeatures::SupportsSIMD128InCrankshaft() &&
8325 expr->arguments()->length() == 2) {
8326 HValue* right = Pop();
8327 HValue* left = Pop();
8328 Drop(2); // Receiver and function.
8329 HInstruction* op = NewUncasted<HBinarySIMDOperation>(left, right, id);
8330 ast_context()->ReturnInstruction(op, expr->id());
8334 #define SIMD_TERNARY_OPERATION_CASE_ITEM(p1, p2, name, p4, p5, p6, p7) \
8336 SIMD_TERNARY_OPERATIONS(SIMD_TERNARY_OPERATION_CASE_ITEM)
8337 #undef SIMD_TERNARY_OPERATION_CASE_ITEM
8338 if (CpuFeatures::SupportsSIMD128InCrankshaft() &&
8339 expr->arguments()->length() == 3) {
8340 HValue* right = Pop();
8341 HValue* left = Pop();
8342 HValue* value = Pop();
8343 Drop(2); // Receiver and function.
8345 NewUncasted<HTernarySIMDOperation>(value, left, right, id);
8346 ast_context()->ReturnInstruction(op, expr->id());
8350 #define SIMD_QUARTERNARY_OPERATION_CASE_ITEM(p1, p2, name, p4, p5, p6, p7, p8) \
8352 SIMD_QUARTERNARY_OPERATIONS(SIMD_QUARTERNARY_OPERATION_CASE_ITEM)
8353 #undef SIMD_QUARTERNARY_OPERATION_CASE_ITEM
8354 if (CpuFeatures::SupportsSIMD128InCrankshaft() &&
8355 expr->arguments()->length() == 4) {
8360 Drop(2); // Receiver and function.
8362 NewUncasted<HQuarternarySIMDOperation>(x, y, z, w, id);
8363 ast_context()->ReturnInstruction(op, expr->id());
8368 // Not supported for inlining yet.
8375 bool HOptimizedGraphBuilder::TryInlineBuiltinMethodCall(
8378 Handle<Map> receiver_map) {
8379 // Try to inline calls like Math.* as operations in the calling function.
8380 if (!expr->target()->shared()->HasBuiltinFunctionId()) return false;
8381 BuiltinFunctionId id = expr->target()->shared()->builtin_function_id();
8382 int argument_count = expr->arguments()->length() + 1; // Plus receiver.
8384 case kStringCharCodeAt:
8386 if (argument_count == 2) {
8387 HValue* index = Pop();
8388 HValue* string = Pop();
8389 Drop(1); // Function.
8390 HInstruction* char_code =
8391 BuildStringCharCodeAt(string, index);
8392 if (id == kStringCharCodeAt) {
8393 ast_context()->ReturnInstruction(char_code, expr->id());
8396 AddInstruction(char_code);
8397 HInstruction* result = NewUncasted<HStringCharFromCode>(char_code);
8398 ast_context()->ReturnInstruction(result, expr->id());
8402 case kStringFromCharCode:
8403 if (argument_count == 2) {
8404 HValue* argument = Pop();
8405 Drop(2); // Receiver and function.
8406 HInstruction* result = NewUncasted<HStringCharFromCode>(argument);
8407 ast_context()->ReturnInstruction(result, expr->id());
8412 if (!FLAG_fast_math) break;
8413 // Fall through if FLAG_fast_math.
8421 if (argument_count == 2) {
8422 HValue* argument = Pop();
8423 Drop(2); // Receiver and function.
8424 HInstruction* op = NewUncasted<HUnaryMathOperation>(argument, id);
8425 ast_context()->ReturnInstruction(op, expr->id());
8430 if (argument_count == 3) {
8431 HValue* right = Pop();
8432 HValue* left = Pop();
8433 Drop(2); // Receiver and function.
8434 HInstruction* result = NULL;
8435 // Use sqrt() if exponent is 0.5 or -0.5.
8436 if (right->IsConstant() && HConstant::cast(right)->HasDoubleValue()) {
8437 double exponent = HConstant::cast(right)->DoubleValue();
8438 if (exponent == 0.5) {
8439 result = NewUncasted<HUnaryMathOperation>(left, kMathPowHalf);
8440 } else if (exponent == -0.5) {
8441 HValue* one = graph()->GetConstant1();
8442 HInstruction* sqrt = AddUncasted<HUnaryMathOperation>(
8443 left, kMathPowHalf);
8444 // MathPowHalf doesn't have side effects so there's no need for
8445 // an environment simulation here.
8446 DCHECK(!sqrt->HasObservableSideEffects());
8447 result = NewUncasted<HDiv>(one, sqrt);
8448 } else if (exponent == 2.0) {
8449 result = NewUncasted<HMul>(left, left);
8453 if (result == NULL) {
8454 result = NewUncasted<HPower>(left, right);
8456 ast_context()->ReturnInstruction(result, expr->id());
8462 if (argument_count == 3) {
8463 HValue* right = Pop();
8464 HValue* left = Pop();
8465 Drop(2); // Receiver and function.
8466 HMathMinMax::Operation op = (id == kMathMin) ? HMathMinMax::kMathMin
8467 : HMathMinMax::kMathMax;
8468 HInstruction* result = NewUncasted<HMathMinMax>(left, right, op);
8469 ast_context()->ReturnInstruction(result, expr->id());
8474 if (argument_count == 3) {
8475 HValue* right = Pop();
8476 HValue* left = Pop();
8477 Drop(2); // Receiver and function.
8478 HInstruction* result = HMul::NewImul(zone(), context(), left, right);
8479 ast_context()->ReturnInstruction(result, expr->id());
8484 if (receiver_map.is_null()) return false;
8485 if (receiver_map->instance_type() != JS_ARRAY_TYPE) return false;
8486 ElementsKind elements_kind = receiver_map->elements_kind();
8487 if (!IsFastElementsKind(elements_kind)) return false;
8488 if (receiver_map->is_observed()) return false;
8489 DCHECK(receiver_map->is_extensible());
8491 Drop(expr->arguments()->length());
8493 HValue* reduced_length;
8494 HValue* receiver = Pop();
8496 HValue* checked_object = AddCheckMap(receiver, receiver_map);
8497 HValue* length = Add<HLoadNamedField>(
8498 checked_object, static_cast<HValue*>(NULL),
8499 HObjectAccess::ForArrayLength(elements_kind));
8501 Drop(1); // Function.
8503 { NoObservableSideEffectsScope scope(this);
8504 IfBuilder length_checker(this);
8506 HValue* bounds_check = length_checker.If<HCompareNumericAndBranch>(
8507 length, graph()->GetConstant0(), Token::EQ);
8508 length_checker.Then();
8510 if (!ast_context()->IsEffect()) Push(graph()->GetConstantUndefined());
8512 length_checker.Else();
8513 HValue* elements = AddLoadElements(checked_object);
8514 // Ensure that we aren't popping from a copy-on-write array.
8515 if (IsFastSmiOrObjectElementsKind(elements_kind)) {
8516 elements = BuildCopyElementsOnWrite(checked_object, elements,
8517 elements_kind, length);
8519 reduced_length = AddUncasted<HSub>(length, graph()->GetConstant1());
8520 result = AddElementAccess(elements, reduced_length, NULL,
8521 bounds_check, elements_kind, LOAD);
8522 Factory* factory = isolate()->factory();
8523 double nan_double = FixedDoubleArray::hole_nan_as_double();
8524 HValue* hole = IsFastSmiOrObjectElementsKind(elements_kind)
8525 ? Add<HConstant>(factory->the_hole_value())
8526 : Add<HConstant>(nan_double);
8527 if (IsFastSmiOrObjectElementsKind(elements_kind)) {
8528 elements_kind = FAST_HOLEY_ELEMENTS;
8531 elements, reduced_length, hole, bounds_check, elements_kind, STORE);
8532 Add<HStoreNamedField>(
8533 checked_object, HObjectAccess::ForArrayLength(elements_kind),
8534 reduced_length, STORE_TO_INITIALIZED_ENTRY);
8536 if (!ast_context()->IsEffect()) Push(result);
8538 length_checker.End();
8540 result = ast_context()->IsEffect() ? graph()->GetConstant0() : Top();
8541 Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
8542 if (!ast_context()->IsEffect()) Drop(1);
8544 ast_context()->ReturnValue(result);
8548 if (receiver_map.is_null()) return false;
8549 if (receiver_map->instance_type() != JS_ARRAY_TYPE) return false;
8550 ElementsKind elements_kind = receiver_map->elements_kind();
8551 if (!IsFastElementsKind(elements_kind)) return false;
8552 if (receiver_map->is_observed()) return false;
8553 if (JSArray::IsReadOnlyLengthDescriptor(receiver_map)) return false;
8554 DCHECK(receiver_map->is_extensible());
8556 // If there may be elements accessors in the prototype chain, the fast
8557 // inlined version can't be used.
8558 if (receiver_map->DictionaryElementsInPrototypeChainOnly()) return false;
8559 // If there currently can be no elements accessors on the prototype chain,
8560 // it doesn't mean that there won't be any later. Install a full prototype
8561 // chain check to trap element accessors being installed on the prototype
8562 // chain, which would cause elements to go to dictionary mode and result
8564 Handle<JSObject> prototype(JSObject::cast(receiver_map->prototype()));
8565 BuildCheckPrototypeMaps(prototype, Handle<JSObject>());
8567 const int argc = expr->arguments()->length();
8568 if (argc != 1) return false;
8570 HValue* value_to_push = Pop();
8571 HValue* array = Pop();
8572 Drop(1); // Drop function.
8574 HInstruction* new_size = NULL;
8575 HValue* length = NULL;
8578 NoObservableSideEffectsScope scope(this);
8580 length = Add<HLoadNamedField>(array, static_cast<HValue*>(NULL),
8581 HObjectAccess::ForArrayLength(elements_kind));
8583 new_size = AddUncasted<HAdd>(length, graph()->GetConstant1());
8585 bool is_array = receiver_map->instance_type() == JS_ARRAY_TYPE;
8586 BuildUncheckedMonomorphicElementAccess(array, length,
8587 value_to_push, is_array,
8588 elements_kind, STORE,
8590 STORE_AND_GROW_NO_TRANSITION);
8592 if (!ast_context()->IsEffect()) Push(new_size);
8593 Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
8594 if (!ast_context()->IsEffect()) Drop(1);
8597 ast_context()->ReturnValue(new_size);
8601 if (receiver_map.is_null()) return false;
8602 if (receiver_map->instance_type() != JS_ARRAY_TYPE) return false;
8603 ElementsKind kind = receiver_map->elements_kind();
8604 if (!IsFastElementsKind(kind)) return false;
8605 if (receiver_map->is_observed()) return false;
8606 DCHECK(receiver_map->is_extensible());
8608 // If there may be elements accessors in the prototype chain, the fast
8609 // inlined version can't be used.
8610 if (receiver_map->DictionaryElementsInPrototypeChainOnly()) return false;
8612 // If there currently can be no elements accessors on the prototype chain,
8613 // it doesn't mean that there won't be any later. Install a full prototype
8614 // chain check to trap element accessors being installed on the prototype
8615 // chain, which would cause elements to go to dictionary mode and result
8617 BuildCheckPrototypeMaps(
8618 handle(JSObject::cast(receiver_map->prototype()), isolate()),
8619 Handle<JSObject>::null());
8621 // Threshold for fast inlined Array.shift().
8622 HConstant* inline_threshold = Add<HConstant>(static_cast<int32_t>(16));
8624 Drop(expr->arguments()->length());
8625 HValue* receiver = Pop();
8626 HValue* function = Pop();
8630 NoObservableSideEffectsScope scope(this);
8632 HValue* length = Add<HLoadNamedField>(
8633 receiver, static_cast<HValue*>(NULL),
8634 HObjectAccess::ForArrayLength(kind));
8636 IfBuilder if_lengthiszero(this);
8637 HValue* lengthiszero = if_lengthiszero.If<HCompareNumericAndBranch>(
8638 length, graph()->GetConstant0(), Token::EQ);
8639 if_lengthiszero.Then();
8641 if (!ast_context()->IsEffect()) Push(graph()->GetConstantUndefined());
8643 if_lengthiszero.Else();
8645 HValue* elements = AddLoadElements(receiver);
8647 // Check if we can use the fast inlined Array.shift().
8648 IfBuilder if_inline(this);
8649 if_inline.If<HCompareNumericAndBranch>(
8650 length, inline_threshold, Token::LTE);
8651 if (IsFastSmiOrObjectElementsKind(kind)) {
8652 // We cannot handle copy-on-write backing stores here.
8653 if_inline.AndIf<HCompareMap>(
8654 elements, isolate()->factory()->fixed_array_map());
8658 // Remember the result.
8659 if (!ast_context()->IsEffect()) {
8660 Push(AddElementAccess(elements, graph()->GetConstant0(), NULL,
8661 lengthiszero, kind, LOAD));
8664 // Compute the new length.
8665 HValue* new_length = AddUncasted<HSub>(
8666 length, graph()->GetConstant1());
8667 new_length->ClearFlag(HValue::kCanOverflow);
8669 // Copy the remaining elements.
8670 LoopBuilder loop(this, context(), LoopBuilder::kPostIncrement);
8672 HValue* new_key = loop.BeginBody(
8673 graph()->GetConstant0(), new_length, Token::LT);
8674 HValue* key = AddUncasted<HAdd>(new_key, graph()->GetConstant1());
8675 key->ClearFlag(HValue::kCanOverflow);
8676 HValue* element = AddUncasted<HLoadKeyed>(
8677 elements, key, lengthiszero, kind, ALLOW_RETURN_HOLE);
8678 HStoreKeyed* store = Add<HStoreKeyed>(
8679 elements, new_key, element, kind);
8680 store->SetFlag(HValue::kAllowUndefinedAsNaN);
8684 // Put a hole at the end.
8685 HValue* hole = IsFastSmiOrObjectElementsKind(kind)
8686 ? Add<HConstant>(isolate()->factory()->the_hole_value())
8687 : Add<HConstant>(FixedDoubleArray::hole_nan_as_double());
8688 if (IsFastSmiOrObjectElementsKind(kind)) kind = FAST_HOLEY_ELEMENTS;
8690 elements, new_length, hole, kind, INITIALIZING_STORE);
8692 // Remember new length.
8693 Add<HStoreNamedField>(
8694 receiver, HObjectAccess::ForArrayLength(kind),
8695 new_length, STORE_TO_INITIALIZED_ENTRY);
8699 Add<HPushArguments>(receiver);
8700 result = Add<HCallJSFunction>(function, 1, true);
8701 if (!ast_context()->IsEffect()) Push(result);
8705 if_lengthiszero.End();
8707 result = ast_context()->IsEffect() ? graph()->GetConstant0() : Top();
8708 Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
8709 if (!ast_context()->IsEffect()) Drop(1);
8710 ast_context()->ReturnValue(result);
8714 case kArrayLastIndexOf: {
8715 if (receiver_map.is_null()) return false;
8716 if (receiver_map->instance_type() != JS_ARRAY_TYPE) return false;
8717 ElementsKind kind = receiver_map->elements_kind();
8718 if (!IsFastElementsKind(kind)) return false;
8719 if (receiver_map->is_observed()) return false;
8720 if (argument_count != 2) return false;
8721 DCHECK(receiver_map->is_extensible());
8723 // If there may be elements accessors in the prototype chain, the fast
8724 // inlined version can't be used.
8725 if (receiver_map->DictionaryElementsInPrototypeChainOnly()) return false;
8727 // If there currently can be no elements accessors on the prototype chain,
8728 // it doesn't mean that there won't be any later. Install a full prototype
8729 // chain check to trap element accessors being installed on the prototype
8730 // chain, which would cause elements to go to dictionary mode and result
8732 BuildCheckPrototypeMaps(
8733 handle(JSObject::cast(receiver_map->prototype()), isolate()),
8734 Handle<JSObject>::null());
8736 HValue* search_element = Pop();
8737 HValue* receiver = Pop();
8738 Drop(1); // Drop function.
8740 ArrayIndexOfMode mode = (id == kArrayIndexOf)
8741 ? kFirstIndexOf : kLastIndexOf;
8742 HValue* index = BuildArrayIndexOf(receiver, search_element, kind, mode);
8744 if (!ast_context()->IsEffect()) Push(index);
8745 Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
8746 if (!ast_context()->IsEffect()) Drop(1);
8747 ast_context()->ReturnValue(index);
8750 #define SIMD_NULLARY_OPERATION_CASE_ITEM(p1, p2, name, p4) \
8752 SIMD_NULLARY_OPERATIONS(SIMD_NULLARY_OPERATION_CASE_ITEM)
8753 #undef SIMD_NULLARY_OPERATION_CASE_ITEM
8754 if (CpuFeatures::SupportsSIMD128InCrankshaft() && argument_count == 1) {
8755 Drop(2); // Receiver and function.
8756 HInstruction* op = NewUncasted<HNullarySIMDOperation>(id);
8757 ast_context()->ReturnInstruction(op, expr->id());
8761 #define SIMD_UNARY_OPERATION_CASE_ITEM(p1, p2, name, p4, p5) \
8763 SIMD_UNARY_OPERATIONS(SIMD_UNARY_OPERATION_CASE_ITEM)
8764 #undef SIMD_UNARY_OPERATION_CASE_ITEM
8765 if (CpuFeatures::SupportsSIMD128InCrankshaft() && argument_count == 2) {
8766 HValue* argument = Pop();
8767 Drop(2); // Receiver and function.
8768 HInstruction* op = NewUncasted<HUnarySIMDOperation>(argument, id);
8769 ast_context()->ReturnInstruction(op, expr->id());
8773 #define SIMD_BINARY_OPERATION_CASE_ITEM(p1, p2, name, p4, p5, p6) \
8775 SIMD_BINARY_OPERATIONS(SIMD_BINARY_OPERATION_CASE_ITEM)
8776 #undef SIMD_BINARY_OPERATION_CASE_ITEM
8777 if (CpuFeatures::SupportsSIMD128InCrankshaft() && argument_count == 3) {
8778 HValue* right = Pop();
8779 HValue* left = Pop();
8780 Drop(2); // Receiver and function.
8781 HInstruction* op = NewUncasted<HBinarySIMDOperation>(left, right, id);
8782 ast_context()->ReturnInstruction(op, expr->id());
8786 #define SIMD_TERNARY_OPERATION_CASE_ITEM(p1, p2, name, p4, p5, p6, p7) \
8788 SIMD_TERNARY_OPERATIONS(SIMD_TERNARY_OPERATION_CASE_ITEM)
8789 #undef SIMD_TERNARY_OPERATION_CASE_ITEM
8790 if (CpuFeatures::SupportsSIMD128InCrankshaft() && argument_count == 4) {
8791 HValue* right = Pop();
8792 HValue* left = Pop();
8793 HValue* value = Pop();
8794 Drop(2); // Receiver and function.
8796 NewUncasted<HTernarySIMDOperation>(value, left, right, id);
8797 ast_context()->ReturnInstruction(op, expr->id());
8801 #define SIMD_QUARTERNARY_OPERATION_CASE_ITEM(p1, p2, name, p4, p5, p6, p7, p8) \
8803 SIMD_QUARTERNARY_OPERATIONS(SIMD_QUARTERNARY_OPERATION_CASE_ITEM)
8804 #undef SIMD_QUARTERNARY_OPERATION_CASE_ITEM
8805 if (CpuFeatures::SupportsSIMD128InCrankshaft() && argument_count == 5) {
8810 Drop(2); // Receiver and function.
8811 HValue* context = environment()->context();
8813 HQuarternarySIMDOperation::New(zone(), context, x, y, z, w, id);
8814 ast_context()->ReturnInstruction(op, expr->id());
8816 } else if (CpuFeatures::SupportsSIMD128InCrankshaft() &&
8817 argument_count == 2) {
8818 if (id == kFloat32x4Constructor) {
8819 HValue* argument = Pop();
8820 Drop(2); // Receiver and function.
8822 NewUncasted<HUnarySIMDOperation>(argument, kFloat32x4Coercion);
8823 ast_context()->ReturnInstruction(op, expr->id());
8825 } else if (id == kInt32x4Constructor) {
8826 HValue* argument = Pop();
8827 Drop(2); // Receiver and function.
8829 NewUncasted<HUnarySIMDOperation>(argument, kInt32x4Coercion);
8830 ast_context()->ReturnInstruction(op, expr->id());
8832 } else if (id == kFloat64x2Constructor) {
8833 HValue* argument = Pop();
8834 Drop(2); // Receiver and function.
8836 NewUncasted<HUnarySIMDOperation>(argument, kFloat64x2Coercion);
8837 ast_context()->ReturnInstruction(op, expr->id());
8844 case kFloat32x4ArrayGetAt:
8845 case kFloat64x2ArrayGetAt:
8846 case kInt32x4ArrayGetAt:
8847 if (CpuFeatures::SupportsSIMD128InCrankshaft() && argument_count == 2) {
8848 HValue* key = Pop();
8849 HValue* typed32x4_array = Pop();
8850 DCHECK(typed32x4_array == receiver);
8851 Drop(1); // Drop function.
8852 HInstruction* instr = BuildUncheckedMonomorphicElementAccess(
8853 typed32x4_array, key, NULL,
8854 receiver_map->instance_type() == JS_ARRAY_TYPE,
8855 receiver_map->elements_kind(),
8857 NEVER_RETURN_HOLE, // load_mode.
8859 ast_context()->ReturnValue(instr);
8863 case kFloat32x4ArraySetAt:
8864 case kFloat64x2ArraySetAt:
8865 case kInt32x4ArraySetAt:
8866 if (CpuFeatures::SupportsSIMD128InCrankshaft() && argument_count == 3) {
8867 HValue* value = Pop();
8868 HValue* key = Pop();
8869 HValue* typed32x4_array = Pop();
8870 DCHECK(typed32x4_array == receiver);
8871 Drop(1); // Drop function.
8872 // TODO(haitao): add STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS.
8873 KeyedAccessStoreMode store_mode = STANDARD_STORE;
8874 BuildUncheckedMonomorphicElementAccess(
8875 typed32x4_array, key, value,
8876 receiver_map->instance_type() == JS_ARRAY_TYPE,
8877 receiver_map->elements_kind(),
8879 NEVER_RETURN_HOLE, // load_mode.
8882 Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
8883 ast_context()->ReturnValue(Pop());
8888 // Not yet supported for inlining.
8895 bool HOptimizedGraphBuilder::TryInlineApiFunctionCall(Call* expr,
8897 Handle<JSFunction> function = expr->target();
8898 int argc = expr->arguments()->length();
8899 SmallMapList receiver_maps;
8900 return TryInlineApiCall(function,
8909 bool HOptimizedGraphBuilder::TryInlineApiMethodCall(
8912 SmallMapList* receiver_maps) {
8913 Handle<JSFunction> function = expr->target();
8914 int argc = expr->arguments()->length();
8915 return TryInlineApiCall(function,
8924 bool HOptimizedGraphBuilder::TryInlineApiGetter(Handle<JSFunction> function,
8925 Handle<Map> receiver_map,
8927 SmallMapList receiver_maps(1, zone());
8928 receiver_maps.Add(receiver_map, zone());
8929 return TryInlineApiCall(function,
8930 NULL, // Receiver is on expression stack.
8938 bool HOptimizedGraphBuilder::TryInlineApiSetter(Handle<JSFunction> function,
8939 Handle<Map> receiver_map,
8941 SmallMapList receiver_maps(1, zone());
8942 receiver_maps.Add(receiver_map, zone());
8943 return TryInlineApiCall(function,
8944 NULL, // Receiver is on expression stack.
8952 bool HOptimizedGraphBuilder::TryInlineApiCall(Handle<JSFunction> function,
8954 SmallMapList* receiver_maps,
8957 ApiCallType call_type) {
8958 CallOptimization optimization(function);
8959 if (!optimization.is_simple_api_call()) return false;
8960 Handle<Map> holder_map;
8961 if (call_type == kCallApiFunction) {
8962 // Cannot embed a direct reference to the global proxy map
8963 // as it maybe dropped on deserialization.
8964 CHECK(!isolate()->serializer_enabled());
8965 DCHECK_EQ(0, receiver_maps->length());
8966 receiver_maps->Add(handle(function->global_proxy()->map()), zone());
8968 CallOptimization::HolderLookup holder_lookup =
8969 CallOptimization::kHolderNotFound;
8970 Handle<JSObject> api_holder = optimization.LookupHolderOfExpectedType(
8971 receiver_maps->first(), &holder_lookup);
8972 if (holder_lookup == CallOptimization::kHolderNotFound) return false;
8974 if (FLAG_trace_inlining) {
8975 PrintF("Inlining api function ");
8976 function->ShortPrint();
8980 bool drop_extra = false;
8981 bool is_store = false;
8982 switch (call_type) {
8983 case kCallApiFunction:
8984 case kCallApiMethod:
8985 // Need to check that none of the receiver maps could have changed.
8986 Add<HCheckMaps>(receiver, receiver_maps);
8987 // Need to ensure the chain between receiver and api_holder is intact.
8988 if (holder_lookup == CallOptimization::kHolderFound) {
8989 AddCheckPrototypeMaps(api_holder, receiver_maps->first());
8991 DCHECK_EQ(holder_lookup, CallOptimization::kHolderIsReceiver);
8993 // Includes receiver.
8994 PushArgumentsFromEnvironment(argc + 1);
8995 // Drop function after call.
8998 case kCallApiGetter:
8999 // Receiver and prototype chain cannot have changed.
9001 DCHECK_EQ(NULL, receiver);
9002 // Receiver is on expression stack.
9004 Add<HPushArguments>(receiver);
9006 case kCallApiSetter:
9009 // Receiver and prototype chain cannot have changed.
9011 DCHECK_EQ(NULL, receiver);
9012 // Receiver and value are on expression stack.
9013 HValue* value = Pop();
9015 Add<HPushArguments>(receiver, value);
9020 HValue* holder = NULL;
9021 switch (holder_lookup) {
9022 case CallOptimization::kHolderFound:
9023 holder = Add<HConstant>(api_holder);
9025 case CallOptimization::kHolderIsReceiver:
9028 case CallOptimization::kHolderNotFound:
9032 Handle<CallHandlerInfo> api_call_info = optimization.api_call_info();
9033 Handle<Object> call_data_obj(api_call_info->data(), isolate());
9034 bool call_data_is_undefined = call_data_obj->IsUndefined();
9035 HValue* call_data = Add<HConstant>(call_data_obj);
9036 ApiFunction fun(v8::ToCData<Address>(api_call_info->callback()));
9037 ExternalReference ref = ExternalReference(&fun,
9038 ExternalReference::DIRECT_API_CALL,
9040 HValue* api_function_address = Add<HConstant>(ExternalReference(ref));
9042 HValue* op_vals[] = {
9044 Add<HConstant>(function),
9047 api_function_address
9050 CallInterfaceDescriptor* descriptor =
9051 isolate()->call_descriptor(Isolate::ApiFunctionCall);
9053 CallApiFunctionStub stub(isolate(), is_store, call_data_is_undefined, argc);
9054 Handle<Code> code = stub.GetCode();
9055 HConstant* code_value = Add<HConstant>(code);
9057 DCHECK((sizeof(op_vals) / kPointerSize) ==
9058 descriptor->GetEnvironmentLength());
9060 HInstruction* call = New<HCallWithDescriptor>(
9061 code_value, argc + 1, descriptor,
9062 Vector<HValue*>(op_vals, descriptor->GetEnvironmentLength()));
9064 if (drop_extra) Drop(1); // Drop function.
9065 ast_context()->ReturnInstruction(call, ast_id);
9070 bool HOptimizedGraphBuilder::TryCallApply(Call* expr) {
9071 DCHECK(expr->expression()->IsProperty());
9073 if (!expr->IsMonomorphic()) {
9076 Handle<Map> function_map = expr->GetReceiverTypes()->first();
9077 if (function_map->instance_type() != JS_FUNCTION_TYPE ||
9078 !expr->target()->shared()->HasBuiltinFunctionId() ||
9079 expr->target()->shared()->builtin_function_id() != kFunctionApply) {
9083 if (current_info()->scope()->arguments() == NULL) return false;
9085 ZoneList<Expression*>* args = expr->arguments();
9086 if (args->length() != 2) return false;
9088 VariableProxy* arg_two = args->at(1)->AsVariableProxy();
9089 if (arg_two == NULL || !arg_two->var()->IsStackAllocated()) return false;
9090 HValue* arg_two_value = LookupAndMakeLive(arg_two->var());
9091 if (!arg_two_value->CheckFlag(HValue::kIsArguments)) return false;
9093 // Found pattern f.apply(receiver, arguments).
9094 CHECK_ALIVE_OR_RETURN(VisitForValue(args->at(0)), true);
9095 HValue* receiver = Pop(); // receiver
9096 HValue* function = Pop(); // f
9099 HValue* checked_function = AddCheckMap(function, function_map);
9101 if (function_state()->outer() == NULL) {
9102 HInstruction* elements = Add<HArgumentsElements>(false);
9103 HInstruction* length = Add<HArgumentsLength>(elements);
9104 HValue* wrapped_receiver = BuildWrapReceiver(receiver, checked_function);
9105 HInstruction* result = New<HApplyArguments>(function,
9109 ast_context()->ReturnInstruction(result, expr->id());
9112 // We are inside inlined function and we know exactly what is inside
9113 // arguments object. But we need to be able to materialize at deopt.
9114 DCHECK_EQ(environment()->arguments_environment()->parameter_count(),
9115 function_state()->entry()->arguments_object()->arguments_count());
9116 HArgumentsObject* args = function_state()->entry()->arguments_object();
9117 const ZoneList<HValue*>* arguments_values = args->arguments_values();
9118 int arguments_count = arguments_values->length();
9120 Push(BuildWrapReceiver(receiver, checked_function));
9121 for (int i = 1; i < arguments_count; i++) {
9122 Push(arguments_values->at(i));
9125 Handle<JSFunction> known_function;
9126 if (function->IsConstant() &&
9127 HConstant::cast(function)->handle(isolate())->IsJSFunction()) {
9128 known_function = Handle<JSFunction>::cast(
9129 HConstant::cast(function)->handle(isolate()));
9130 int args_count = arguments_count - 1; // Excluding receiver.
9131 if (TryInlineApply(known_function, expr, args_count)) return true;
9134 PushArgumentsFromEnvironment(arguments_count);
9135 HInvokeFunction* call = New<HInvokeFunction>(
9136 function, known_function, arguments_count);
9137 Drop(1); // Function.
9138 ast_context()->ReturnInstruction(call, expr->id());
9144 HValue* HOptimizedGraphBuilder::ImplicitReceiverFor(HValue* function,
9145 Handle<JSFunction> target) {
9146 SharedFunctionInfo* shared = target->shared();
9147 if (shared->strict_mode() == SLOPPY && !shared->native()) {
9148 // Cannot embed a direct reference to the global proxy
9149 // as is it dropped on deserialization.
9150 CHECK(!isolate()->serializer_enabled());
9151 Handle<JSObject> global_proxy(target->context()->global_proxy());
9152 return Add<HConstant>(global_proxy);
9154 return graph()->GetConstantUndefined();
9158 void HOptimizedGraphBuilder::BuildArrayCall(Expression* expression,
9159 int arguments_count,
9161 Handle<AllocationSite> site) {
9162 Add<HCheckValue>(function, array_function());
9164 if (IsCallArrayInlineable(arguments_count, site)) {
9165 BuildInlinedCallArray(expression, arguments_count, site);
9169 HInstruction* call = PreProcessCall(New<HCallNewArray>(
9170 function, arguments_count + 1, site->GetElementsKind()));
9171 if (expression->IsCall()) {
9174 ast_context()->ReturnInstruction(call, expression->id());
9178 HValue* HOptimizedGraphBuilder::BuildArrayIndexOf(HValue* receiver,
9179 HValue* search_element,
9181 ArrayIndexOfMode mode) {
9182 DCHECK(IsFastElementsKind(kind));
9184 NoObservableSideEffectsScope no_effects(this);
9186 HValue* elements = AddLoadElements(receiver);
9187 HValue* length = AddLoadArrayLength(receiver, kind);
9190 HValue* terminating;
9192 LoopBuilder::Direction direction;
9193 if (mode == kFirstIndexOf) {
9194 initial = graph()->GetConstant0();
9195 terminating = length;
9197 direction = LoopBuilder::kPostIncrement;
9199 DCHECK_EQ(kLastIndexOf, mode);
9201 terminating = graph()->GetConstant0();
9203 direction = LoopBuilder::kPreDecrement;
9206 Push(graph()->GetConstantMinus1());
9207 if (IsFastDoubleElementsKind(kind) || IsFastSmiElementsKind(kind)) {
9208 LoopBuilder loop(this, context(), direction);
9210 HValue* index = loop.BeginBody(initial, terminating, token);
9211 HValue* element = AddUncasted<HLoadKeyed>(
9212 elements, index, static_cast<HValue*>(NULL),
9213 kind, ALLOW_RETURN_HOLE);
9214 IfBuilder if_issame(this);
9215 if (IsFastDoubleElementsKind(kind)) {
9216 if_issame.If<HCompareNumericAndBranch>(
9217 element, search_element, Token::EQ_STRICT);
9219 if_issame.If<HCompareObjectEqAndBranch>(element, search_element);
9231 IfBuilder if_isstring(this);
9232 if_isstring.If<HIsStringAndBranch>(search_element);
9235 LoopBuilder loop(this, context(), direction);
9237 HValue* index = loop.BeginBody(initial, terminating, token);
9238 HValue* element = AddUncasted<HLoadKeyed>(
9239 elements, index, static_cast<HValue*>(NULL),
9240 kind, ALLOW_RETURN_HOLE);
9241 IfBuilder if_issame(this);
9242 if_issame.If<HIsStringAndBranch>(element);
9243 if_issame.AndIf<HStringCompareAndBranch>(
9244 element, search_element, Token::EQ_STRICT);
9257 IfBuilder if_isnumber(this);
9258 if_isnumber.If<HIsSmiAndBranch>(search_element);
9259 if_isnumber.OrIf<HCompareMap>(
9260 search_element, isolate()->factory()->heap_number_map());
9263 HValue* search_number =
9264 AddUncasted<HForceRepresentation>(search_element,
9265 Representation::Double());
9266 LoopBuilder loop(this, context(), direction);
9268 HValue* index = loop.BeginBody(initial, terminating, token);
9269 HValue* element = AddUncasted<HLoadKeyed>(
9270 elements, index, static_cast<HValue*>(NULL),
9271 kind, ALLOW_RETURN_HOLE);
9273 IfBuilder if_element_isnumber(this);
9274 if_element_isnumber.If<HIsSmiAndBranch>(element);
9275 if_element_isnumber.OrIf<HCompareMap>(
9276 element, isolate()->factory()->heap_number_map());
9277 if_element_isnumber.Then();
9280 AddUncasted<HForceRepresentation>(element,
9281 Representation::Double());
9282 IfBuilder if_issame(this);
9283 if_issame.If<HCompareNumericAndBranch>(
9284 number, search_number, Token::EQ_STRICT);
9293 if_element_isnumber.End();
9299 LoopBuilder loop(this, context(), direction);
9301 HValue* index = loop.BeginBody(initial, terminating, token);
9302 HValue* element = AddUncasted<HLoadKeyed>(
9303 elements, index, static_cast<HValue*>(NULL),
9304 kind, ALLOW_RETURN_HOLE);
9305 IfBuilder if_issame(this);
9306 if_issame.If<HCompareObjectEqAndBranch>(
9307 element, search_element);
9327 bool HOptimizedGraphBuilder::TryHandleArrayCall(Call* expr, HValue* function) {
9328 if (!array_function().is_identical_to(expr->target())) {
9332 Handle<AllocationSite> site = expr->allocation_site();
9333 if (site.is_null()) return false;
9335 BuildArrayCall(expr,
9336 expr->arguments()->length(),
9343 bool HOptimizedGraphBuilder::TryHandleArrayCallNew(CallNew* expr,
9345 if (!array_function().is_identical_to(expr->target())) {
9349 BuildArrayCall(expr,
9350 expr->arguments()->length(),
9352 expr->allocation_site());
9357 void HOptimizedGraphBuilder::VisitCall(Call* expr) {
9358 DCHECK(!HasStackOverflow());
9359 DCHECK(current_block() != NULL);
9360 DCHECK(current_block()->HasPredecessor());
9361 Expression* callee = expr->expression();
9362 int argument_count = expr->arguments()->length() + 1; // Plus receiver.
9363 HInstruction* call = NULL;
9365 Property* prop = callee->AsProperty();
9367 CHECK_ALIVE(VisitForValue(prop->obj()));
9368 HValue* receiver = Top();
9370 SmallMapList* types;
9371 ComputeReceiverTypes(expr, receiver, &types, zone());
9373 if (prop->key()->IsPropertyName() && types->length() > 0) {
9374 Handle<String> name = prop->key()->AsLiteral()->AsPropertyName();
9375 PropertyAccessInfo info(this, LOAD, ToType(types->first()), name,
9376 types->first()->instance_type());
9377 if (!info.CanAccessAsMonomorphic(types)) {
9378 HandlePolymorphicCallNamed(expr, receiver, types, name);
9384 if (!prop->key()->IsPropertyName()) {
9385 CHECK_ALIVE(VisitForValue(prop->key()));
9389 CHECK_ALIVE(PushLoad(prop, receiver, key));
9390 HValue* function = Pop();
9392 if (FLAG_hydrogen_track_positions) SetSourcePosition(expr->position());
9394 // Push the function under the receiver.
9395 environment()->SetExpressionStackAt(0, function);
9399 if (function->IsConstant() &&
9400 HConstant::cast(function)->handle(isolate())->IsJSFunction()) {
9401 Handle<JSFunction> known_function = Handle<JSFunction>::cast(
9402 HConstant::cast(function)->handle(isolate()));
9403 expr->set_target(known_function);
9405 if (TryCallApply(expr)) return;
9406 CHECK_ALIVE(VisitExpressions(expr->arguments()));
9408 Handle<Map> map = types->length() == 1 ? types->first() : Handle<Map>();
9409 if (TryInlineBuiltinMethodCall(expr, receiver, map)) {
9410 if (FLAG_trace_inlining) {
9411 PrintF("Inlining builtin ");
9412 known_function->ShortPrint();
9417 if (TryInlineApiMethodCall(expr, receiver, types)) return;
9419 // Wrap the receiver if necessary.
9420 if (NeedsWrappingFor(ToType(types->first()), known_function)) {
9421 // Since HWrapReceiver currently cannot actually wrap numbers and
9422 // strings, use the regular CallFunctionStub for method calls to wrap
9424 // TODO(verwaest): Support creation of value wrappers directly in
9426 call = New<HCallFunction>(
9427 function, argument_count, WRAP_AND_CALL);
9428 } else if (TryInlineCall(expr)) {
9431 call = BuildCallConstantFunction(known_function, argument_count);
9435 CHECK_ALIVE(VisitExpressions(expr->arguments()));
9436 CallFunctionFlags flags = receiver->type().IsJSObject()
9437 ? NO_CALL_FUNCTION_FLAGS : CALL_AS_METHOD;
9438 call = New<HCallFunction>(function, argument_count, flags);
9440 PushArgumentsFromEnvironment(argument_count);
9443 VariableProxy* proxy = expr->expression()->AsVariableProxy();
9444 if (proxy != NULL && proxy->var()->is_possibly_eval(isolate())) {
9445 return Bailout(kPossibleDirectCallToEval);
9448 // The function is on the stack in the unoptimized code during
9449 // evaluation of the arguments.
9450 CHECK_ALIVE(VisitForValue(expr->expression()));
9451 HValue* function = Top();
9452 if (expr->global_call()) {
9453 Variable* var = proxy->var();
9454 bool known_global_function = false;
9455 // If there is a global property cell for the name at compile time and
9456 // access check is not enabled we assume that the function will not change
9457 // and generate optimized code for calling the function.
9458 LookupResult lookup(isolate());
9459 GlobalPropertyAccess type = LookupGlobalProperty(var, &lookup, LOAD);
9460 if (type == kUseCell &&
9461 !current_info()->global_object()->IsAccessCheckNeeded()) {
9462 Handle<GlobalObject> global(current_info()->global_object());
9463 known_global_function = expr->ComputeGlobalTarget(global, &lookup);
9465 if (known_global_function) {
9466 Add<HCheckValue>(function, expr->target());
9468 // Placeholder for the receiver.
9469 Push(graph()->GetConstantUndefined());
9470 CHECK_ALIVE(VisitExpressions(expr->arguments()));
9472 // Patch the global object on the stack by the expected receiver.
9473 HValue* receiver = ImplicitReceiverFor(function, expr->target());
9474 const int receiver_index = argument_count - 1;
9475 environment()->SetExpressionStackAt(receiver_index, receiver);
9477 if (TryInlineBuiltinFunctionCall(expr)) {
9478 if (FLAG_trace_inlining) {
9479 PrintF("Inlining builtin ");
9480 expr->target()->ShortPrint();
9485 if (TryInlineApiFunctionCall(expr, receiver)) return;
9486 if (TryHandleArrayCall(expr, function)) return;
9487 if (TryInlineCall(expr)) return;
9489 PushArgumentsFromEnvironment(argument_count);
9490 call = BuildCallConstantFunction(expr->target(), argument_count);
9492 Push(graph()->GetConstantUndefined());
9493 CHECK_ALIVE(VisitExpressions(expr->arguments()));
9494 PushArgumentsFromEnvironment(argument_count);
9495 call = New<HCallFunction>(function, argument_count);
9498 } else if (expr->IsMonomorphic()) {
9499 Add<HCheckValue>(function, expr->target());
9501 Push(graph()->GetConstantUndefined());
9502 CHECK_ALIVE(VisitExpressions(expr->arguments()));
9504 HValue* receiver = ImplicitReceiverFor(function, expr->target());
9505 const int receiver_index = argument_count - 1;
9506 environment()->SetExpressionStackAt(receiver_index, receiver);
9508 if (TryInlineBuiltinFunctionCall(expr)) {
9509 if (FLAG_trace_inlining) {
9510 PrintF("Inlining builtin ");
9511 expr->target()->ShortPrint();
9516 if (TryInlineApiFunctionCall(expr, receiver)) return;
9518 if (TryInlineCall(expr)) return;
9520 call = PreProcessCall(New<HInvokeFunction>(
9521 function, expr->target(), argument_count));
9524 Push(graph()->GetConstantUndefined());
9525 CHECK_ALIVE(VisitExpressions(expr->arguments()));
9526 PushArgumentsFromEnvironment(argument_count);
9527 call = New<HCallFunction>(function, argument_count);
9531 Drop(1); // Drop the function.
9532 return ast_context()->ReturnInstruction(call, expr->id());
9536 void HOptimizedGraphBuilder::BuildInlinedCallArray(
9537 Expression* expression,
9539 Handle<AllocationSite> site) {
9540 DCHECK(!site.is_null());
9541 DCHECK(argument_count >= 0 && argument_count <= 1);
9542 NoObservableSideEffectsScope no_effects(this);
9544 // We should at least have the constructor on the expression stack.
9545 HValue* constructor = environment()->ExpressionStackAt(argument_count);
9547 // Register on the site for deoptimization if the transition feedback changes.
9548 AllocationSite::AddDependentCompilationInfo(
9549 site, AllocationSite::TRANSITIONS, top_info());
9550 ElementsKind kind = site->GetElementsKind();
9551 HInstruction* site_instruction = Add<HConstant>(site);
9553 // In the single constant argument case, we may have to adjust elements kind
9554 // to avoid creating a packed non-empty array.
9555 if (argument_count == 1 && !IsHoleyElementsKind(kind)) {
9556 HValue* argument = environment()->Top();
9557 if (argument->IsConstant()) {
9558 HConstant* constant_argument = HConstant::cast(argument);
9559 DCHECK(constant_argument->HasSmiValue());
9560 int constant_array_size = constant_argument->Integer32Value();
9561 if (constant_array_size != 0) {
9562 kind = GetHoleyElementsKind(kind);
9568 JSArrayBuilder array_builder(this,
9572 DISABLE_ALLOCATION_SITES);
9573 HValue* new_object = argument_count == 0
9574 ? array_builder.AllocateEmptyArray()
9575 : BuildAllocateArrayFromLength(&array_builder, Top());
9577 int args_to_drop = argument_count + (expression->IsCall() ? 2 : 1);
9579 ast_context()->ReturnValue(new_object);
9583 // Checks whether allocation using the given constructor can be inlined.
9584 static bool IsAllocationInlineable(Handle<JSFunction> constructor) {
9585 return constructor->has_initial_map() &&
9586 constructor->initial_map()->instance_type() == JS_OBJECT_TYPE &&
9587 constructor->initial_map()->instance_size() < HAllocate::kMaxInlineSize &&
9588 constructor->initial_map()->InitialPropertiesLength() == 0;
9592 bool HOptimizedGraphBuilder::IsCallArrayInlineable(
9594 Handle<AllocationSite> site) {
9595 Handle<JSFunction> caller = current_info()->closure();
9596 Handle<JSFunction> target = array_function();
9597 // We should have the function plus array arguments on the environment stack.
9598 DCHECK(environment()->length() >= (argument_count + 1));
9599 DCHECK(!site.is_null());
9601 bool inline_ok = false;
9602 if (site->CanInlineCall()) {
9603 // We also want to avoid inlining in certain 1 argument scenarios.
9604 if (argument_count == 1) {
9605 HValue* argument = Top();
9606 if (argument->IsConstant()) {
9607 // Do not inline if the constant length argument is not a smi or
9608 // outside the valid range for unrolled loop initialization.
9609 HConstant* constant_argument = HConstant::cast(argument);
9610 if (constant_argument->HasSmiValue()) {
9611 int value = constant_argument->Integer32Value();
9612 inline_ok = value >= 0 && value <= kElementLoopUnrollThreshold;
9614 TraceInline(target, caller,
9615 "Constant length outside of valid inlining range.");
9619 TraceInline(target, caller,
9620 "Dont inline [new] Array(n) where n isn't constant.");
9622 } else if (argument_count == 0) {
9625 TraceInline(target, caller, "Too many arguments to inline.");
9628 TraceInline(target, caller, "AllocationSite requested no inlining.");
9632 TraceInline(target, caller, NULL);
9638 void HOptimizedGraphBuilder::VisitCallNew(CallNew* expr) {
9639 DCHECK(!HasStackOverflow());
9640 DCHECK(current_block() != NULL);
9641 DCHECK(current_block()->HasPredecessor());
9642 if (!FLAG_hydrogen_track_positions) SetSourcePosition(expr->position());
9643 int argument_count = expr->arguments()->length() + 1; // Plus constructor.
9644 Factory* factory = isolate()->factory();
9646 // The constructor function is on the stack in the unoptimized code
9647 // during evaluation of the arguments.
9648 CHECK_ALIVE(VisitForValue(expr->expression()));
9649 HValue* function = Top();
9650 CHECK_ALIVE(VisitExpressions(expr->arguments()));
9652 if (FLAG_inline_construct &&
9653 expr->IsMonomorphic() &&
9654 IsAllocationInlineable(expr->target())) {
9655 Handle<JSFunction> constructor = expr->target();
9656 HValue* check = Add<HCheckValue>(function, constructor);
9658 // Force completion of inobject slack tracking before generating
9659 // allocation code to finalize instance size.
9660 if (constructor->IsInobjectSlackTrackingInProgress()) {
9661 constructor->CompleteInobjectSlackTracking();
9664 // Calculate instance size from initial map of constructor.
9665 DCHECK(constructor->has_initial_map());
9666 Handle<Map> initial_map(constructor->initial_map());
9667 int instance_size = initial_map->instance_size();
9668 DCHECK(initial_map->InitialPropertiesLength() == 0);
9670 // Allocate an instance of the implicit receiver object.
9671 HValue* size_in_bytes = Add<HConstant>(instance_size);
9672 HAllocationMode allocation_mode;
9673 if (FLAG_pretenuring_call_new) {
9674 if (FLAG_allocation_site_pretenuring) {
9675 // Try to use pretenuring feedback.
9676 Handle<AllocationSite> allocation_site = expr->allocation_site();
9677 allocation_mode = HAllocationMode(allocation_site);
9678 // Take a dependency on allocation site.
9679 AllocationSite::AddDependentCompilationInfo(allocation_site,
9680 AllocationSite::TENURING,
9685 HAllocate* receiver = BuildAllocate(
9686 size_in_bytes, HType::JSObject(), JS_OBJECT_TYPE, allocation_mode);
9687 receiver->set_known_initial_map(initial_map);
9689 // Initialize map and fields of the newly allocated object.
9690 { NoObservableSideEffectsScope no_effects(this);
9691 DCHECK(initial_map->instance_type() == JS_OBJECT_TYPE);
9692 Add<HStoreNamedField>(receiver,
9693 HObjectAccess::ForMapAndOffset(initial_map, JSObject::kMapOffset),
9694 Add<HConstant>(initial_map));
9695 HValue* empty_fixed_array = Add<HConstant>(factory->empty_fixed_array());
9696 Add<HStoreNamedField>(receiver,
9697 HObjectAccess::ForMapAndOffset(initial_map,
9698 JSObject::kPropertiesOffset),
9700 Add<HStoreNamedField>(receiver,
9701 HObjectAccess::ForMapAndOffset(initial_map,
9702 JSObject::kElementsOffset),
9704 if (initial_map->inobject_properties() != 0) {
9705 HConstant* undefined = graph()->GetConstantUndefined();
9706 for (int i = 0; i < initial_map->inobject_properties(); i++) {
9707 int property_offset = initial_map->GetInObjectPropertyOffset(i);
9708 Add<HStoreNamedField>(receiver,
9709 HObjectAccess::ForMapAndOffset(initial_map, property_offset),
9715 // Replace the constructor function with a newly allocated receiver using
9716 // the index of the receiver from the top of the expression stack.
9717 const int receiver_index = argument_count - 1;
9718 DCHECK(environment()->ExpressionStackAt(receiver_index) == function);
9719 environment()->SetExpressionStackAt(receiver_index, receiver);
9721 if (TryInlineConstruct(expr, receiver)) {
9722 // Inlining worked, add a dependency on the initial map to make sure that
9723 // this code is deoptimized whenever the initial map of the constructor
9725 Map::AddDependentCompilationInfo(
9726 initial_map, DependentCode::kInitialMapChangedGroup, top_info());
9730 // TODO(mstarzinger): For now we remove the previous HAllocate and all
9731 // corresponding instructions and instead add HPushArguments for the
9732 // arguments in case inlining failed. What we actually should do is for
9733 // inlining to try to build a subgraph without mutating the parent graph.
9734 HInstruction* instr = current_block()->last();
9736 HInstruction* prev_instr = instr->previous();
9737 instr->DeleteAndReplaceWith(NULL);
9739 } while (instr != check);
9740 environment()->SetExpressionStackAt(receiver_index, function);
9741 HInstruction* call =
9742 PreProcessCall(New<HCallNew>(function, argument_count));
9743 return ast_context()->ReturnInstruction(call, expr->id());
9745 // The constructor function is both an operand to the instruction and an
9746 // argument to the construct call.
9747 if (TryHandleArrayCallNew(expr, function)) return;
9749 HInstruction* call =
9750 PreProcessCall(New<HCallNew>(function, argument_count));
9751 return ast_context()->ReturnInstruction(call, expr->id());
9756 // Support for generating inlined runtime functions.
9758 // Lookup table for generators for runtime calls that are generated inline.
9759 // Elements of the table are member pointers to functions of
9760 // HOptimizedGraphBuilder.
9761 #define INLINE_FUNCTION_GENERATOR_ADDRESS(Name, argc, ressize) \
9762 &HOptimizedGraphBuilder::Generate##Name,
9764 const HOptimizedGraphBuilder::InlineFunctionGenerator
9765 HOptimizedGraphBuilder::kInlineFunctionGenerators[] = {
9766 INLINE_FUNCTION_LIST(INLINE_FUNCTION_GENERATOR_ADDRESS)
9767 INLINE_OPTIMIZED_FUNCTION_LIST(INLINE_FUNCTION_GENERATOR_ADDRESS)
9769 #undef INLINE_FUNCTION_GENERATOR_ADDRESS
9772 template <class ViewClass>
9773 void HGraphBuilder::BuildArrayBufferViewInitialization(
9776 HValue* byte_offset,
9777 HValue* byte_length) {
9779 for (int offset = ViewClass::kSize;
9780 offset < ViewClass::kSizeWithInternalFields;
9781 offset += kPointerSize) {
9782 Add<HStoreNamedField>(obj,
9783 HObjectAccess::ForObservableJSObjectOffset(offset),
9784 graph()->GetConstant0());
9787 Add<HStoreNamedField>(
9789 HObjectAccess::ForJSArrayBufferViewByteOffset(),
9791 Add<HStoreNamedField>(
9793 HObjectAccess::ForJSArrayBufferViewByteLength(),
9796 if (buffer != NULL) {
9797 Add<HStoreNamedField>(
9799 HObjectAccess::ForJSArrayBufferViewBuffer(), buffer);
9800 HObjectAccess weak_first_view_access =
9801 HObjectAccess::ForJSArrayBufferWeakFirstView();
9802 Add<HStoreNamedField>(obj,
9803 HObjectAccess::ForJSArrayBufferViewWeakNext(),
9804 Add<HLoadNamedField>(buffer,
9805 static_cast<HValue*>(NULL),
9806 weak_first_view_access));
9807 Add<HStoreNamedField>(buffer, weak_first_view_access, obj);
9809 Add<HStoreNamedField>(
9811 HObjectAccess::ForJSArrayBufferViewBuffer(),
9812 Add<HConstant>(static_cast<int32_t>(0)));
9813 Add<HStoreNamedField>(obj,
9814 HObjectAccess::ForJSArrayBufferViewWeakNext(),
9815 graph()->GetConstantUndefined());
9820 void HOptimizedGraphBuilder::GenerateDataViewInitialize(
9821 CallRuntime* expr) {
9822 ZoneList<Expression*>* arguments = expr->arguments();
9824 DCHECK(arguments->length()== 4);
9825 CHECK_ALIVE(VisitForValue(arguments->at(0)));
9826 HValue* obj = Pop();
9828 CHECK_ALIVE(VisitForValue(arguments->at(1)));
9829 HValue* buffer = Pop();
9831 CHECK_ALIVE(VisitForValue(arguments->at(2)));
9832 HValue* byte_offset = Pop();
9834 CHECK_ALIVE(VisitForValue(arguments->at(3)));
9835 HValue* byte_length = Pop();
9838 NoObservableSideEffectsScope scope(this);
9839 BuildArrayBufferViewInitialization<JSDataView>(
9840 obj, buffer, byte_offset, byte_length);
9845 static Handle<Map> TypedArrayMap(Isolate* isolate,
9846 ExternalArrayType array_type,
9847 ElementsKind target_kind) {
9848 Handle<Context> native_context = isolate->native_context();
9849 Handle<JSFunction> fun;
9850 switch (array_type) {
9851 #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
9852 case kExternal##Type##Array: \
9853 fun = Handle<JSFunction>(native_context->type##_array_fun()); \
9856 TYPED_ARRAYS(TYPED_ARRAY_CASE)
9857 #undef TYPED_ARRAY_CASE
9859 Handle<Map> map(fun->initial_map());
9860 return Map::AsElementsKind(map, target_kind);
9864 HValue* HOptimizedGraphBuilder::BuildAllocateExternalElements(
9865 ExternalArrayType array_type,
9866 bool is_zero_byte_offset,
9867 HValue* buffer, HValue* byte_offset, HValue* length) {
9868 Handle<Map> external_array_map(
9869 isolate()->heap()->MapForExternalArrayType(array_type));
9871 // The HForceRepresentation is to prevent possible deopt on int-smi
9872 // conversion after allocation but before the new object fields are set.
9873 length = AddUncasted<HForceRepresentation>(length, Representation::Smi());
9876 Add<HConstant>(ExternalArray::kAlignedSize),
9877 HType::HeapObject(),
9879 external_array_map->instance_type());
9881 AddStoreMapConstant(elements, external_array_map);
9882 Add<HStoreNamedField>(elements,
9883 HObjectAccess::ForFixedArrayLength(), length);
9885 HValue* backing_store = Add<HLoadNamedField>(
9886 buffer, static_cast<HValue*>(NULL),
9887 HObjectAccess::ForJSArrayBufferBackingStore());
9889 HValue* typed_array_start;
9890 if (is_zero_byte_offset) {
9891 typed_array_start = backing_store;
9893 HInstruction* external_pointer =
9894 AddUncasted<HAdd>(backing_store, byte_offset);
9895 // Arguments are checked prior to call to TypedArrayInitialize,
9896 // including byte_offset.
9897 external_pointer->ClearFlag(HValue::kCanOverflow);
9898 typed_array_start = external_pointer;
9901 Add<HStoreNamedField>(elements,
9902 HObjectAccess::ForExternalArrayExternalPointer(),
9909 HValue* HOptimizedGraphBuilder::BuildAllocateFixedTypedArray(
9910 ExternalArrayType array_type, size_t element_size,
9911 ElementsKind fixed_elements_kind,
9912 HValue* byte_length, HValue* length) {
9914 (FixedTypedArrayBase::kHeaderSize & kObjectAlignmentMask) == 0);
9917 // if fixed array's elements are not aligned to object's alignment,
9918 // we need to align the whole array to object alignment.
9919 if (element_size % kObjectAlignment != 0) {
9920 total_size = BuildObjectSizeAlignment(
9921 byte_length, FixedTypedArrayBase::kHeaderSize);
9923 total_size = AddUncasted<HAdd>(byte_length,
9924 Add<HConstant>(FixedTypedArrayBase::kHeaderSize));
9925 total_size->ClearFlag(HValue::kCanOverflow);
9928 // The HForceRepresentation is to prevent possible deopt on int-smi
9929 // conversion after allocation but before the new object fields are set.
9930 length = AddUncasted<HForceRepresentation>(length, Representation::Smi());
9931 Handle<Map> fixed_typed_array_map(
9932 isolate()->heap()->MapForFixedTypedArray(array_type));
9934 Add<HAllocate>(total_size, HType::HeapObject(),
9935 NOT_TENURED, fixed_typed_array_map->instance_type());
9936 AddStoreMapConstant(elements, fixed_typed_array_map);
9938 Add<HStoreNamedField>(elements,
9939 HObjectAccess::ForFixedArrayLength(),
9942 HValue* filler = Add<HConstant>(static_cast<int32_t>(0));
9943 if (IsFixedFloat32x4ElementsKind(fixed_elements_kind)) {
9944 filler = AddUncasted<HNullarySIMDOperation>(kFloat32x4Zero);
9945 } else if (IsFixedFloat64x2ElementsKind(fixed_elements_kind)) {
9946 filler = AddUncasted<HNullarySIMDOperation>(kFloat64x2Zero);
9947 } else if (IsFixedInt32x4ElementsKind(fixed_elements_kind)) {
9948 filler = AddUncasted<HNullarySIMDOperation>(kInt32x4Zero);
9952 LoopBuilder builder(this, context(), LoopBuilder::kPostIncrement);
9954 HValue* key = builder.BeginBody(
9955 Add<HConstant>(static_cast<int32_t>(0)),
9957 Add<HStoreKeyed>(elements, key, filler, fixed_elements_kind);
9965 void HOptimizedGraphBuilder::GenerateTypedArrayInitialize(
9966 CallRuntime* expr) {
9967 ZoneList<Expression*>* arguments = expr->arguments();
9969 static const int kObjectArg = 0;
9970 static const int kArrayIdArg = 1;
9971 static const int kBufferArg = 2;
9972 static const int kByteOffsetArg = 3;
9973 static const int kByteLengthArg = 4;
9974 static const int kArgsLength = 5;
9975 DCHECK(arguments->length() == kArgsLength);
9978 CHECK_ALIVE(VisitForValue(arguments->at(kObjectArg)));
9979 HValue* obj = Pop();
9981 if (arguments->at(kArrayIdArg)->IsLiteral()) {
9982 // This should never happen in real use, but can happen when fuzzing.
9984 Bailout(kNeedSmiLiteral);
9987 Handle<Object> value =
9988 static_cast<Literal*>(arguments->at(kArrayIdArg))->value();
9989 if (!value->IsSmi()) {
9990 // This should never happen in real use, but can happen when fuzzing.
9992 Bailout(kNeedSmiLiteral);
9995 int array_id = Smi::cast(*value)->value();
9998 if (!arguments->at(kBufferArg)->IsNullLiteral()) {
9999 CHECK_ALIVE(VisitForValue(arguments->at(kBufferArg)));
10005 HValue* byte_offset;
10006 bool is_zero_byte_offset;
10008 if (arguments->at(kByteOffsetArg)->IsLiteral()
10009 && Smi::FromInt(0) ==
10010 *static_cast<Literal*>(arguments->at(kByteOffsetArg))->value()) {
10011 byte_offset = Add<HConstant>(static_cast<int32_t>(0));
10012 is_zero_byte_offset = true;
10014 CHECK_ALIVE(VisitForValue(arguments->at(kByteOffsetArg)));
10015 byte_offset = Pop();
10016 is_zero_byte_offset = false;
10017 DCHECK(buffer != NULL);
10020 CHECK_ALIVE(VisitForValue(arguments->at(kByteLengthArg)));
10021 HValue* byte_length = Pop();
10023 NoObservableSideEffectsScope scope(this);
10024 IfBuilder byte_offset_smi(this);
10026 if (!is_zero_byte_offset) {
10027 byte_offset_smi.If<HIsSmiAndBranch>(byte_offset);
10028 byte_offset_smi.Then();
10031 ExternalArrayType array_type =
10032 kExternalInt8Array; // Bogus initialization.
10033 size_t element_size = 1; // Bogus initialization.
10034 ElementsKind external_elements_kind = // Bogus initialization.
10035 EXTERNAL_INT8_ELEMENTS;
10036 ElementsKind fixed_elements_kind = // Bogus initialization.
10038 Runtime::ArrayIdToTypeAndSize(array_id,
10040 &external_elements_kind,
10041 &fixed_elements_kind,
10045 { // byte_offset is Smi.
10046 BuildArrayBufferViewInitialization<JSTypedArray>(
10047 obj, buffer, byte_offset, byte_length);
10050 HInstruction* length = AddUncasted<HDiv>(byte_length,
10051 Add<HConstant>(static_cast<int32_t>(element_size)));
10053 Add<HStoreNamedField>(obj,
10054 HObjectAccess::ForJSTypedArrayLength(),
10058 if (buffer != NULL) {
10059 elements = BuildAllocateExternalElements(
10060 array_type, is_zero_byte_offset, buffer, byte_offset, length);
10061 Handle<Map> obj_map = TypedArrayMap(
10062 isolate(), array_type, external_elements_kind);
10063 AddStoreMapConstant(obj, obj_map);
10065 DCHECK(is_zero_byte_offset);
10066 elements = BuildAllocateFixedTypedArray(
10067 array_type, element_size, fixed_elements_kind,
10068 byte_length, length);
10070 Add<HStoreNamedField>(
10071 obj, HObjectAccess::ForElementsPointer(), elements);
10074 if (!is_zero_byte_offset) {
10075 byte_offset_smi.Else();
10076 { // byte_offset is not Smi.
10078 CHECK_ALIVE(VisitForValue(arguments->at(kArrayIdArg)));
10082 PushArgumentsFromEnvironment(kArgsLength);
10083 Add<HCallRuntime>(expr->name(), expr->function(), kArgsLength);
10086 byte_offset_smi.End();
10090 void HOptimizedGraphBuilder::GenerateMaxSmi(CallRuntime* expr) {
10091 DCHECK(expr->arguments()->length() == 0);
10092 HConstant* max_smi = New<HConstant>(static_cast<int32_t>(Smi::kMaxValue));
10093 return ast_context()->ReturnInstruction(max_smi, expr->id());
10097 void HOptimizedGraphBuilder::GenerateTypedArrayMaxSizeInHeap(
10098 CallRuntime* expr) {
10099 DCHECK(expr->arguments()->length() == 0);
10100 HConstant* result = New<HConstant>(static_cast<int32_t>(
10101 FLAG_typed_array_max_size_in_heap));
10102 return ast_context()->ReturnInstruction(result, expr->id());
10106 void HOptimizedGraphBuilder::GenerateArrayBufferGetByteLength(
10107 CallRuntime* expr) {
10108 DCHECK(expr->arguments()->length() == 1);
10109 CHECK_ALIVE(VisitForValue(expr->arguments()->at(0)));
10110 HValue* buffer = Pop();
10111 HInstruction* result = New<HLoadNamedField>(
10113 static_cast<HValue*>(NULL),
10114 HObjectAccess::ForJSArrayBufferByteLength());
10115 return ast_context()->ReturnInstruction(result, expr->id());
10119 void HOptimizedGraphBuilder::GenerateArrayBufferViewGetByteLength(
10120 CallRuntime* expr) {
10121 DCHECK(expr->arguments()->length() == 1);
10122 CHECK_ALIVE(VisitForValue(expr->arguments()->at(0)));
10123 HValue* buffer = Pop();
10124 HInstruction* result = New<HLoadNamedField>(
10126 static_cast<HValue*>(NULL),
10127 HObjectAccess::ForJSArrayBufferViewByteLength());
10128 return ast_context()->ReturnInstruction(result, expr->id());
10132 void HOptimizedGraphBuilder::GenerateArrayBufferViewGetByteOffset(
10133 CallRuntime* expr) {
10134 DCHECK(expr->arguments()->length() == 1);
10135 CHECK_ALIVE(VisitForValue(expr->arguments()->at(0)));
10136 HValue* buffer = Pop();
10137 HInstruction* result = New<HLoadNamedField>(
10139 static_cast<HValue*>(NULL),
10140 HObjectAccess::ForJSArrayBufferViewByteOffset());
10141 return ast_context()->ReturnInstruction(result, expr->id());
10145 void HOptimizedGraphBuilder::GenerateTypedArrayGetLength(
10146 CallRuntime* expr) {
10147 DCHECK(expr->arguments()->length() == 1);
10148 CHECK_ALIVE(VisitForValue(expr->arguments()->at(0)));
10149 HValue* buffer = Pop();
10150 HInstruction* result = New<HLoadNamedField>(
10152 static_cast<HValue*>(NULL),
10153 HObjectAccess::ForJSTypedArrayLength());
10154 return ast_context()->ReturnInstruction(result, expr->id());
10158 void HOptimizedGraphBuilder::VisitCallRuntime(CallRuntime* expr) {
10159 DCHECK(!HasStackOverflow());
10160 DCHECK(current_block() != NULL);
10161 DCHECK(current_block()->HasPredecessor());
10162 if (expr->is_jsruntime()) {
10163 return Bailout(kCallToAJavaScriptRuntimeFunction);
10166 const Runtime::Function* function = expr->function();
10167 DCHECK(function != NULL);
10169 if (function->intrinsic_type == Runtime::INLINE ||
10170 function->intrinsic_type == Runtime::INLINE_OPTIMIZED) {
10171 DCHECK(expr->name()->length() > 0);
10172 DCHECK(expr->name()->Get(0) == '_');
10173 // Call to an inline function.
10174 int lookup_index = static_cast<int>(function->function_id) -
10175 static_cast<int>(Runtime::kFirstInlineFunction);
10176 DCHECK(lookup_index >= 0);
10177 DCHECK(static_cast<size_t>(lookup_index) <
10178 ARRAY_SIZE(kInlineFunctionGenerators));
10179 InlineFunctionGenerator generator = kInlineFunctionGenerators[lookup_index];
10181 // Call the inline code generator using the pointer-to-member.
10182 (this->*generator)(expr);
10184 DCHECK(function->intrinsic_type == Runtime::RUNTIME);
10185 Handle<String> name = expr->name();
10186 int argument_count = expr->arguments()->length();
10187 CHECK_ALIVE(VisitExpressions(expr->arguments()));
10188 PushArgumentsFromEnvironment(argument_count);
10189 HCallRuntime* call = New<HCallRuntime>(name, function,
10191 return ast_context()->ReturnInstruction(call, expr->id());
10196 void HOptimizedGraphBuilder::VisitUnaryOperation(UnaryOperation* expr) {
10197 DCHECK(!HasStackOverflow());
10198 DCHECK(current_block() != NULL);
10199 DCHECK(current_block()->HasPredecessor());
10200 switch (expr->op()) {
10201 case Token::DELETE: return VisitDelete(expr);
10202 case Token::VOID: return VisitVoid(expr);
10203 case Token::TYPEOF: return VisitTypeof(expr);
10204 case Token::NOT: return VisitNot(expr);
10205 default: UNREACHABLE();
10210 void HOptimizedGraphBuilder::VisitDelete(UnaryOperation* expr) {
10211 Property* prop = expr->expression()->AsProperty();
10212 VariableProxy* proxy = expr->expression()->AsVariableProxy();
10213 if (prop != NULL) {
10214 CHECK_ALIVE(VisitForValue(prop->obj()));
10215 CHECK_ALIVE(VisitForValue(prop->key()));
10216 HValue* key = Pop();
10217 HValue* obj = Pop();
10218 HValue* function = AddLoadJSBuiltin(Builtins::DELETE);
10219 Add<HPushArguments>(obj, key, Add<HConstant>(function_strict_mode()));
10220 // TODO(olivf) InvokeFunction produces a check for the parameter count,
10221 // even though we are certain to pass the correct number of arguments here.
10222 HInstruction* instr = New<HInvokeFunction>(function, 3);
10223 return ast_context()->ReturnInstruction(instr, expr->id());
10224 } else if (proxy != NULL) {
10225 Variable* var = proxy->var();
10226 if (var->IsUnallocated()) {
10227 Bailout(kDeleteWithGlobalVariable);
10228 } else if (var->IsStackAllocated() || var->IsContextSlot()) {
10229 // Result of deleting non-global variables is false. 'this' is not
10230 // really a variable, though we implement it as one. The
10231 // subexpression does not have side effects.
10232 HValue* value = var->is_this()
10233 ? graph()->GetConstantTrue()
10234 : graph()->GetConstantFalse();
10235 return ast_context()->ReturnValue(value);
10237 Bailout(kDeleteWithNonGlobalVariable);
10240 // Result of deleting non-property, non-variable reference is true.
10241 // Evaluate the subexpression for side effects.
10242 CHECK_ALIVE(VisitForEffect(expr->expression()));
10243 return ast_context()->ReturnValue(graph()->GetConstantTrue());
10248 void HOptimizedGraphBuilder::VisitVoid(UnaryOperation* expr) {
10249 CHECK_ALIVE(VisitForEffect(expr->expression()));
10250 return ast_context()->ReturnValue(graph()->GetConstantUndefined());
10254 void HOptimizedGraphBuilder::VisitTypeof(UnaryOperation* expr) {
10255 CHECK_ALIVE(VisitForTypeOf(expr->expression()));
10256 HValue* value = Pop();
10257 HInstruction* instr = New<HTypeof>(value);
10258 return ast_context()->ReturnInstruction(instr, expr->id());
10262 void HOptimizedGraphBuilder::VisitNot(UnaryOperation* expr) {
10263 if (ast_context()->IsTest()) {
10264 TestContext* context = TestContext::cast(ast_context());
10265 VisitForControl(expr->expression(),
10266 context->if_false(),
10267 context->if_true());
10271 if (ast_context()->IsEffect()) {
10272 VisitForEffect(expr->expression());
10276 DCHECK(ast_context()->IsValue());
10277 HBasicBlock* materialize_false = graph()->CreateBasicBlock();
10278 HBasicBlock* materialize_true = graph()->CreateBasicBlock();
10279 CHECK_BAILOUT(VisitForControl(expr->expression(),
10281 materialize_true));
10283 if (materialize_false->HasPredecessor()) {
10284 materialize_false->SetJoinId(expr->MaterializeFalseId());
10285 set_current_block(materialize_false);
10286 Push(graph()->GetConstantFalse());
10288 materialize_false = NULL;
10291 if (materialize_true->HasPredecessor()) {
10292 materialize_true->SetJoinId(expr->MaterializeTrueId());
10293 set_current_block(materialize_true);
10294 Push(graph()->GetConstantTrue());
10296 materialize_true = NULL;
10299 HBasicBlock* join =
10300 CreateJoin(materialize_false, materialize_true, expr->id());
10301 set_current_block(join);
10302 if (join != NULL) return ast_context()->ReturnValue(Pop());
10306 HInstruction* HOptimizedGraphBuilder::BuildIncrement(
10307 bool returns_original_input,
10308 CountOperation* expr) {
10309 // The input to the count operation is on top of the expression stack.
10310 Representation rep = Representation::FromType(expr->type());
10311 if (rep.IsNone() || rep.IsTagged()) {
10312 rep = Representation::Smi();
10315 if (returns_original_input) {
10316 // We need an explicit HValue representing ToNumber(input). The
10317 // actual HChange instruction we need is (sometimes) added in a later
10318 // phase, so it is not available now to be used as an input to HAdd and
10319 // as the return value.
10320 HInstruction* number_input = AddUncasted<HForceRepresentation>(Pop(), rep);
10321 if (!rep.IsDouble()) {
10322 number_input->SetFlag(HInstruction::kFlexibleRepresentation);
10323 number_input->SetFlag(HInstruction::kCannotBeTagged);
10325 Push(number_input);
10328 // The addition has no side effects, so we do not need
10329 // to simulate the expression stack after this instruction.
10330 // Any later failures deopt to the load of the input or earlier.
10331 HConstant* delta = (expr->op() == Token::INC)
10332 ? graph()->GetConstant1()
10333 : graph()->GetConstantMinus1();
10334 HInstruction* instr = AddUncasted<HAdd>(Top(), delta);
10335 if (instr->IsAdd()) {
10336 HAdd* add = HAdd::cast(instr);
10337 add->set_observed_input_representation(1, rep);
10338 add->set_observed_input_representation(2, Representation::Smi());
10340 instr->SetFlag(HInstruction::kCannotBeTagged);
10341 instr->ClearAllSideEffects();
10346 void HOptimizedGraphBuilder::BuildStoreForEffect(Expression* expr,
10349 BailoutId return_id,
10353 EffectContext for_effect(this);
10355 if (key != NULL) Push(key);
10357 BuildStore(expr, prop, ast_id, return_id);
10361 void HOptimizedGraphBuilder::VisitCountOperation(CountOperation* expr) {
10362 DCHECK(!HasStackOverflow());
10363 DCHECK(current_block() != NULL);
10364 DCHECK(current_block()->HasPredecessor());
10365 if (!FLAG_hydrogen_track_positions) SetSourcePosition(expr->position());
10366 Expression* target = expr->expression();
10367 VariableProxy* proxy = target->AsVariableProxy();
10368 Property* prop = target->AsProperty();
10369 if (proxy == NULL && prop == NULL) {
10370 return Bailout(kInvalidLhsInCountOperation);
10373 // Match the full code generator stack by simulating an extra stack
10374 // element for postfix operations in a non-effect context. The return
10375 // value is ToNumber(input).
10376 bool returns_original_input =
10377 expr->is_postfix() && !ast_context()->IsEffect();
10378 HValue* input = NULL; // ToNumber(original_input).
10379 HValue* after = NULL; // The result after incrementing or decrementing.
10381 if (proxy != NULL) {
10382 Variable* var = proxy->var();
10383 if (var->mode() == CONST_LEGACY) {
10384 return Bailout(kUnsupportedCountOperationWithConst);
10386 // Argument of the count operation is a variable, not a property.
10387 DCHECK(prop == NULL);
10388 CHECK_ALIVE(VisitForValue(target));
10390 after = BuildIncrement(returns_original_input, expr);
10391 input = returns_original_input ? Top() : Pop();
10394 switch (var->location()) {
10395 case Variable::UNALLOCATED:
10396 HandleGlobalVariableAssignment(var,
10398 expr->AssignmentId());
10401 case Variable::PARAMETER:
10402 case Variable::LOCAL:
10403 BindIfLive(var, after);
10406 case Variable::CONTEXT: {
10407 // Bail out if we try to mutate a parameter value in a function
10408 // using the arguments object. We do not (yet) correctly handle the
10409 // arguments property of the function.
10410 if (current_info()->scope()->arguments() != NULL) {
10411 // Parameters will rewrite to context slots. We have no direct
10412 // way to detect that the variable is a parameter so we use a
10413 // linear search of the parameter list.
10414 int count = current_info()->scope()->num_parameters();
10415 for (int i = 0; i < count; ++i) {
10416 if (var == current_info()->scope()->parameter(i)) {
10417 return Bailout(kAssignmentToParameterInArgumentsObject);
10422 HValue* context = BuildContextChainWalk(var);
10423 HStoreContextSlot::Mode mode = IsLexicalVariableMode(var->mode())
10424 ? HStoreContextSlot::kCheckDeoptimize : HStoreContextSlot::kNoCheck;
10425 HStoreContextSlot* instr = Add<HStoreContextSlot>(context, var->index(),
10427 if (instr->HasObservableSideEffects()) {
10428 Add<HSimulate>(expr->AssignmentId(), REMOVABLE_SIMULATE);
10433 case Variable::LOOKUP:
10434 return Bailout(kLookupVariableInCountOperation);
10437 Drop(returns_original_input ? 2 : 1);
10438 return ast_context()->ReturnValue(expr->is_postfix() ? input : after);
10441 // Argument of the count operation is a property.
10442 DCHECK(prop != NULL);
10443 if (returns_original_input) Push(graph()->GetConstantUndefined());
10445 CHECK_ALIVE(VisitForValue(prop->obj()));
10446 HValue* object = Top();
10448 HValue* key = NULL;
10449 if (!prop->key()->IsPropertyName() || prop->IsStringAccess()) {
10450 CHECK_ALIVE(VisitForValue(prop->key()));
10454 CHECK_ALIVE(PushLoad(prop, object, key));
10456 after = BuildIncrement(returns_original_input, expr);
10458 if (returns_original_input) {
10460 // Drop object and key to push it again in the effect context below.
10461 Drop(key == NULL ? 1 : 2);
10462 environment()->SetExpressionStackAt(0, input);
10463 CHECK_ALIVE(BuildStoreForEffect(
10464 expr, prop, expr->id(), expr->AssignmentId(), object, key, after));
10465 return ast_context()->ReturnValue(Pop());
10468 environment()->SetExpressionStackAt(0, after);
10469 return BuildStore(expr, prop, expr->id(), expr->AssignmentId());
10473 HInstruction* HOptimizedGraphBuilder::BuildStringCharCodeAt(
10476 if (string->IsConstant() && index->IsConstant()) {
10477 HConstant* c_string = HConstant::cast(string);
10478 HConstant* c_index = HConstant::cast(index);
10479 if (c_string->HasStringValue() && c_index->HasNumberValue()) {
10480 int32_t i = c_index->NumberValueAsInteger32();
10481 Handle<String> s = c_string->StringValue();
10482 if (i < 0 || i >= s->length()) {
10483 return New<HConstant>(base::OS::nan_value());
10485 return New<HConstant>(s->Get(i));
10488 string = BuildCheckString(string);
10489 index = Add<HBoundsCheck>(index, AddLoadStringLength(string));
10490 return New<HStringCharCodeAt>(string, index);
10494 // Checks if the given shift amounts have following forms:
10495 // (N1) and (N2) with N1 + N2 = 32; (sa) and (32 - sa).
10496 static bool ShiftAmountsAllowReplaceByRotate(HValue* sa,
10497 HValue* const32_minus_sa) {
10498 if (sa->IsConstant() && const32_minus_sa->IsConstant()) {
10499 const HConstant* c1 = HConstant::cast(sa);
10500 const HConstant* c2 = HConstant::cast(const32_minus_sa);
10501 return c1->HasInteger32Value() && c2->HasInteger32Value() &&
10502 (c1->Integer32Value() + c2->Integer32Value() == 32);
10504 if (!const32_minus_sa->IsSub()) return false;
10505 HSub* sub = HSub::cast(const32_minus_sa);
10506 return sub->left()->EqualsInteger32Constant(32) && sub->right() == sa;
10510 // Checks if the left and the right are shift instructions with the oposite
10511 // directions that can be replaced by one rotate right instruction or not.
10512 // Returns the operand and the shift amount for the rotate instruction in the
10514 bool HGraphBuilder::MatchRotateRight(HValue* left,
10517 HValue** shift_amount) {
10520 if (left->IsShl() && right->IsShr()) {
10521 shl = HShl::cast(left);
10522 shr = HShr::cast(right);
10523 } else if (left->IsShr() && right->IsShl()) {
10524 shl = HShl::cast(right);
10525 shr = HShr::cast(left);
10529 if (shl->left() != shr->left()) return false;
10531 if (!ShiftAmountsAllowReplaceByRotate(shl->right(), shr->right()) &&
10532 !ShiftAmountsAllowReplaceByRotate(shr->right(), shl->right())) {
10535 *operand= shr->left();
10536 *shift_amount = shr->right();
10541 bool CanBeZero(HValue* right) {
10542 if (right->IsConstant()) {
10543 HConstant* right_const = HConstant::cast(right);
10544 if (right_const->HasInteger32Value() &&
10545 (right_const->Integer32Value() & 0x1f) != 0) {
10553 HValue* HGraphBuilder::EnforceNumberType(HValue* number,
10555 if (expected->Is(Type::SignedSmall())) {
10556 return AddUncasted<HForceRepresentation>(number, Representation::Smi());
10558 if (expected->Is(Type::Signed32())) {
10559 return AddUncasted<HForceRepresentation>(number,
10560 Representation::Integer32());
10566 HValue* HGraphBuilder::TruncateToNumber(HValue* value, Type** expected) {
10567 if (value->IsConstant()) {
10568 HConstant* constant = HConstant::cast(value);
10569 Maybe<HConstant*> number = constant->CopyToTruncatedNumber(zone());
10570 if (number.has_value) {
10571 *expected = Type::Number(zone());
10572 return AddInstruction(number.value);
10576 // We put temporary values on the stack, which don't correspond to anything
10577 // in baseline code. Since nothing is observable we avoid recording those
10578 // pushes with a NoObservableSideEffectsScope.
10579 NoObservableSideEffectsScope no_effects(this);
10581 Type* expected_type = *expected;
10583 // Separate the number type from the rest.
10584 Type* expected_obj =
10585 Type::Intersect(expected_type, Type::NonNumber(zone()), zone());
10586 Type* expected_number =
10587 Type::Intersect(expected_type, Type::Number(zone()), zone());
10589 // We expect to get a number.
10590 // (We need to check first, since Type::None->Is(Type::Any()) == true.
10591 if (expected_obj->Is(Type::None())) {
10592 DCHECK(!expected_number->Is(Type::None(zone())));
10596 if (expected_obj->Is(Type::Undefined(zone()))) {
10597 // This is already done by HChange.
10598 *expected = Type::Union(expected_number, Type::Number(zone()), zone());
10606 HValue* HOptimizedGraphBuilder::BuildBinaryOperation(
10607 BinaryOperation* expr,
10610 PushBeforeSimulateBehavior push_sim_result) {
10611 Type* left_type = expr->left()->bounds().lower;
10612 Type* right_type = expr->right()->bounds().lower;
10613 Type* result_type = expr->bounds().lower;
10614 Maybe<int> fixed_right_arg = expr->fixed_right_arg();
10615 Handle<AllocationSite> allocation_site = expr->allocation_site();
10617 HAllocationMode allocation_mode;
10618 if (FLAG_allocation_site_pretenuring && !allocation_site.is_null()) {
10619 allocation_mode = HAllocationMode(allocation_site);
10622 HValue* result = HGraphBuilder::BuildBinaryOperation(
10623 expr->op(), left, right, left_type, right_type, result_type,
10624 fixed_right_arg, allocation_mode);
10625 // Add a simulate after instructions with observable side effects, and
10626 // after phis, which are the result of BuildBinaryOperation when we
10627 // inlined some complex subgraph.
10628 if (result->HasObservableSideEffects() || result->IsPhi()) {
10629 if (push_sim_result == PUSH_BEFORE_SIMULATE) {
10631 Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
10634 Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
10641 HValue* HGraphBuilder::BuildBinaryOperation(
10648 Maybe<int> fixed_right_arg,
10649 HAllocationMode allocation_mode) {
10651 Representation left_rep = Representation::FromType(left_type);
10652 Representation right_rep = Representation::FromType(right_type);
10654 bool maybe_string_add = op == Token::ADD &&
10655 (left_type->Maybe(Type::String()) ||
10656 left_type->Maybe(Type::Receiver()) ||
10657 right_type->Maybe(Type::String()) ||
10658 right_type->Maybe(Type::Receiver()));
10660 if (left_type->Is(Type::None())) {
10661 Add<HDeoptimize>("Insufficient type feedback for LHS of binary operation",
10662 Deoptimizer::SOFT);
10663 // TODO(rossberg): we should be able to get rid of non-continuous
10665 left_type = Type::Any(zone());
10667 if (!maybe_string_add) left = TruncateToNumber(left, &left_type);
10668 left_rep = Representation::FromType(left_type);
10671 if (right_type->Is(Type::None())) {
10672 Add<HDeoptimize>("Insufficient type feedback for RHS of binary operation",
10673 Deoptimizer::SOFT);
10674 right_type = Type::Any(zone());
10676 if (!maybe_string_add) right = TruncateToNumber(right, &right_type);
10677 right_rep = Representation::FromType(right_type);
10680 // Special case for string addition here.
10681 if (op == Token::ADD &&
10682 (left_type->Is(Type::String()) || right_type->Is(Type::String()))) {
10683 // Validate type feedback for left argument.
10684 if (left_type->Is(Type::String())) {
10685 left = BuildCheckString(left);
10688 // Validate type feedback for right argument.
10689 if (right_type->Is(Type::String())) {
10690 right = BuildCheckString(right);
10693 // Convert left argument as necessary.
10694 if (left_type->Is(Type::Number())) {
10695 DCHECK(right_type->Is(Type::String()));
10696 left = BuildNumberToString(left, left_type);
10697 } else if (!left_type->Is(Type::String())) {
10698 DCHECK(right_type->Is(Type::String()));
10699 HValue* function = AddLoadJSBuiltin(Builtins::STRING_ADD_RIGHT);
10700 Add<HPushArguments>(left, right);
10701 return AddUncasted<HInvokeFunction>(function, 2);
10704 // Convert right argument as necessary.
10705 if (right_type->Is(Type::Number())) {
10706 DCHECK(left_type->Is(Type::String()));
10707 right = BuildNumberToString(right, right_type);
10708 } else if (!right_type->Is(Type::String())) {
10709 DCHECK(left_type->Is(Type::String()));
10710 HValue* function = AddLoadJSBuiltin(Builtins::STRING_ADD_LEFT);
10711 Add<HPushArguments>(left, right);
10712 return AddUncasted<HInvokeFunction>(function, 2);
10715 // Fast path for empty constant strings.
10716 if (left->IsConstant() &&
10717 HConstant::cast(left)->HasStringValue() &&
10718 HConstant::cast(left)->StringValue()->length() == 0) {
10721 if (right->IsConstant() &&
10722 HConstant::cast(right)->HasStringValue() &&
10723 HConstant::cast(right)->StringValue()->length() == 0) {
10727 // Register the dependent code with the allocation site.
10728 if (!allocation_mode.feedback_site().is_null()) {
10729 DCHECK(!graph()->info()->IsStub());
10730 Handle<AllocationSite> site(allocation_mode.feedback_site());
10731 AllocationSite::AddDependentCompilationInfo(
10732 site, AllocationSite::TENURING, top_info());
10735 // Inline the string addition into the stub when creating allocation
10736 // mementos to gather allocation site feedback, or if we can statically
10737 // infer that we're going to create a cons string.
10738 if ((graph()->info()->IsStub() &&
10739 allocation_mode.CreateAllocationMementos()) ||
10740 (left->IsConstant() &&
10741 HConstant::cast(left)->HasStringValue() &&
10742 HConstant::cast(left)->StringValue()->length() + 1 >=
10743 ConsString::kMinLength) ||
10744 (right->IsConstant() &&
10745 HConstant::cast(right)->HasStringValue() &&
10746 HConstant::cast(right)->StringValue()->length() + 1 >=
10747 ConsString::kMinLength)) {
10748 return BuildStringAdd(left, right, allocation_mode);
10751 // Fallback to using the string add stub.
10752 return AddUncasted<HStringAdd>(
10753 left, right, allocation_mode.GetPretenureMode(),
10754 STRING_ADD_CHECK_NONE, allocation_mode.feedback_site());
10757 if (graph()->info()->IsStub()) {
10758 left = EnforceNumberType(left, left_type);
10759 right = EnforceNumberType(right, right_type);
10762 Representation result_rep = Representation::FromType(result_type);
10764 bool is_non_primitive = (left_rep.IsTagged() && !left_rep.IsSmi()) ||
10765 (right_rep.IsTagged() && !right_rep.IsSmi());
10767 HInstruction* instr = NULL;
10768 // Only the stub is allowed to call into the runtime, since otherwise we would
10769 // inline several instructions (including the two pushes) for every tagged
10770 // operation in optimized code, which is more expensive, than a stub call.
10771 if (graph()->info()->IsStub() && is_non_primitive) {
10772 HValue* function = AddLoadJSBuiltin(BinaryOpIC::TokenToJSBuiltin(op));
10773 Add<HPushArguments>(left, right);
10774 instr = AddUncasted<HInvokeFunction>(function, 2);
10778 instr = AddUncasted<HAdd>(left, right);
10781 instr = AddUncasted<HSub>(left, right);
10784 instr = AddUncasted<HMul>(left, right);
10787 if (fixed_right_arg.has_value &&
10788 !right->EqualsInteger32Constant(fixed_right_arg.value)) {
10789 HConstant* fixed_right = Add<HConstant>(
10790 static_cast<int>(fixed_right_arg.value));
10791 IfBuilder if_same(this);
10792 if_same.If<HCompareNumericAndBranch>(right, fixed_right, Token::EQ);
10794 if_same.ElseDeopt("Unexpected RHS of binary operation");
10795 right = fixed_right;
10797 instr = AddUncasted<HMod>(left, right);
10801 instr = AddUncasted<HDiv>(left, right);
10803 case Token::BIT_XOR:
10804 case Token::BIT_AND:
10805 instr = AddUncasted<HBitwise>(op, left, right);
10807 case Token::BIT_OR: {
10808 HValue* operand, *shift_amount;
10809 if (left_type->Is(Type::Signed32()) &&
10810 right_type->Is(Type::Signed32()) &&
10811 MatchRotateRight(left, right, &operand, &shift_amount)) {
10812 instr = AddUncasted<HRor>(operand, shift_amount);
10814 instr = AddUncasted<HBitwise>(op, left, right);
10819 instr = AddUncasted<HSar>(left, right);
10822 instr = AddUncasted<HShr>(left, right);
10823 if (FLAG_opt_safe_uint32_operations && instr->IsShr() &&
10824 CanBeZero(right)) {
10825 graph()->RecordUint32Instruction(instr);
10829 instr = AddUncasted<HShl>(left, right);
10836 if (instr->IsBinaryOperation()) {
10837 HBinaryOperation* binop = HBinaryOperation::cast(instr);
10838 binop->set_observed_input_representation(1, left_rep);
10839 binop->set_observed_input_representation(2, right_rep);
10840 binop->initialize_output_representation(result_rep);
10841 if (graph()->info()->IsStub()) {
10842 // Stub should not call into stub.
10843 instr->SetFlag(HValue::kCannotBeTagged);
10844 // And should truncate on HForceRepresentation already.
10845 if (left->IsForceRepresentation()) {
10846 left->CopyFlag(HValue::kTruncatingToSmi, instr);
10847 left->CopyFlag(HValue::kTruncatingToInt32, instr);
10849 if (right->IsForceRepresentation()) {
10850 right->CopyFlag(HValue::kTruncatingToSmi, instr);
10851 right->CopyFlag(HValue::kTruncatingToInt32, instr);
10859 // Check for the form (%_ClassOf(foo) === 'BarClass').
10860 static bool IsClassOfTest(CompareOperation* expr) {
10861 if (expr->op() != Token::EQ_STRICT) return false;
10862 CallRuntime* call = expr->left()->AsCallRuntime();
10863 if (call == NULL) return false;
10864 Literal* literal = expr->right()->AsLiteral();
10865 if (literal == NULL) return false;
10866 if (!literal->value()->IsString()) return false;
10867 if (!call->name()->IsOneByteEqualTo(STATIC_ASCII_VECTOR("_ClassOf"))) {
10870 DCHECK(call->arguments()->length() == 1);
10875 void HOptimizedGraphBuilder::VisitBinaryOperation(BinaryOperation* expr) {
10876 DCHECK(!HasStackOverflow());
10877 DCHECK(current_block() != NULL);
10878 DCHECK(current_block()->HasPredecessor());
10879 switch (expr->op()) {
10881 return VisitComma(expr);
10884 return VisitLogicalExpression(expr);
10886 return VisitArithmeticExpression(expr);
10891 void HOptimizedGraphBuilder::VisitComma(BinaryOperation* expr) {
10892 CHECK_ALIVE(VisitForEffect(expr->left()));
10893 // Visit the right subexpression in the same AST context as the entire
10895 Visit(expr->right());
10899 void HOptimizedGraphBuilder::VisitLogicalExpression(BinaryOperation* expr) {
10900 bool is_logical_and = expr->op() == Token::AND;
10901 if (ast_context()->IsTest()) {
10902 TestContext* context = TestContext::cast(ast_context());
10903 // Translate left subexpression.
10904 HBasicBlock* eval_right = graph()->CreateBasicBlock();
10905 if (is_logical_and) {
10906 CHECK_BAILOUT(VisitForControl(expr->left(),
10908 context->if_false()));
10910 CHECK_BAILOUT(VisitForControl(expr->left(),
10911 context->if_true(),
10915 // Translate right subexpression by visiting it in the same AST
10916 // context as the entire expression.
10917 if (eval_right->HasPredecessor()) {
10918 eval_right->SetJoinId(expr->RightId());
10919 set_current_block(eval_right);
10920 Visit(expr->right());
10923 } else if (ast_context()->IsValue()) {
10924 CHECK_ALIVE(VisitForValue(expr->left()));
10925 DCHECK(current_block() != NULL);
10926 HValue* left_value = Top();
10928 // Short-circuit left values that always evaluate to the same boolean value.
10929 if (expr->left()->ToBooleanIsTrue() || expr->left()->ToBooleanIsFalse()) {
10930 // l (evals true) && r -> r
10931 // l (evals true) || r -> l
10932 // l (evals false) && r -> l
10933 // l (evals false) || r -> r
10934 if (is_logical_and == expr->left()->ToBooleanIsTrue()) {
10936 CHECK_ALIVE(VisitForValue(expr->right()));
10938 return ast_context()->ReturnValue(Pop());
10941 // We need an extra block to maintain edge-split form.
10942 HBasicBlock* empty_block = graph()->CreateBasicBlock();
10943 HBasicBlock* eval_right = graph()->CreateBasicBlock();
10944 ToBooleanStub::Types expected(expr->left()->to_boolean_types());
10945 HBranch* test = is_logical_and
10946 ? New<HBranch>(left_value, expected, eval_right, empty_block)
10947 : New<HBranch>(left_value, expected, empty_block, eval_right);
10948 FinishCurrentBlock(test);
10950 set_current_block(eval_right);
10951 Drop(1); // Value of the left subexpression.
10952 CHECK_BAILOUT(VisitForValue(expr->right()));
10954 HBasicBlock* join_block =
10955 CreateJoin(empty_block, current_block(), expr->id());
10956 set_current_block(join_block);
10957 return ast_context()->ReturnValue(Pop());
10960 DCHECK(ast_context()->IsEffect());
10961 // In an effect context, we don't need the value of the left subexpression,
10962 // only its control flow and side effects. We need an extra block to
10963 // maintain edge-split form.
10964 HBasicBlock* empty_block = graph()->CreateBasicBlock();
10965 HBasicBlock* right_block = graph()->CreateBasicBlock();
10966 if (is_logical_and) {
10967 CHECK_BAILOUT(VisitForControl(expr->left(), right_block, empty_block));
10969 CHECK_BAILOUT(VisitForControl(expr->left(), empty_block, right_block));
10972 // TODO(kmillikin): Find a way to fix this. It's ugly that there are
10973 // actually two empty blocks (one here and one inserted by
10974 // TestContext::BuildBranch, and that they both have an HSimulate though the
10975 // second one is not a merge node, and that we really have no good AST ID to
10976 // put on that first HSimulate.
10978 if (empty_block->HasPredecessor()) {
10979 empty_block->SetJoinId(expr->id());
10981 empty_block = NULL;
10984 if (right_block->HasPredecessor()) {
10985 right_block->SetJoinId(expr->RightId());
10986 set_current_block(right_block);
10987 CHECK_BAILOUT(VisitForEffect(expr->right()));
10988 right_block = current_block();
10990 right_block = NULL;
10993 HBasicBlock* join_block =
10994 CreateJoin(empty_block, right_block, expr->id());
10995 set_current_block(join_block);
10996 // We did not materialize any value in the predecessor environments,
10997 // so there is no need to handle it here.
11002 void HOptimizedGraphBuilder::VisitArithmeticExpression(BinaryOperation* expr) {
11003 CHECK_ALIVE(VisitForValue(expr->left()));
11004 CHECK_ALIVE(VisitForValue(expr->right()));
11005 SetSourcePosition(expr->position());
11006 HValue* right = Pop();
11007 HValue* left = Pop();
11009 BuildBinaryOperation(expr, left, right,
11010 ast_context()->IsEffect() ? NO_PUSH_BEFORE_SIMULATE
11011 : PUSH_BEFORE_SIMULATE);
11012 if (FLAG_hydrogen_track_positions && result->IsBinaryOperation()) {
11013 HBinaryOperation::cast(result)->SetOperandPositions(
11015 ScriptPositionToSourcePosition(expr->left()->position()),
11016 ScriptPositionToSourcePosition(expr->right()->position()));
11018 return ast_context()->ReturnValue(result);
11022 void HOptimizedGraphBuilder::HandleLiteralCompareTypeof(CompareOperation* expr,
11023 Expression* sub_expr,
11024 Handle<String> check) {
11025 CHECK_ALIVE(VisitForTypeOf(sub_expr));
11026 SetSourcePosition(expr->position());
11027 HValue* value = Pop();
11028 HTypeofIsAndBranch* instr = New<HTypeofIsAndBranch>(value, check);
11029 return ast_context()->ReturnControl(instr, expr->id());
11033 static bool IsLiteralCompareBool(Isolate* isolate,
11037 return op == Token::EQ_STRICT &&
11038 ((left->IsConstant() &&
11039 HConstant::cast(left)->handle(isolate)->IsBoolean()) ||
11040 (right->IsConstant() &&
11041 HConstant::cast(right)->handle(isolate)->IsBoolean()));
11045 void HOptimizedGraphBuilder::VisitCompareOperation(CompareOperation* expr) {
11046 DCHECK(!HasStackOverflow());
11047 DCHECK(current_block() != NULL);
11048 DCHECK(current_block()->HasPredecessor());
11050 if (!FLAG_hydrogen_track_positions) SetSourcePosition(expr->position());
11052 // Check for a few fast cases. The AST visiting behavior must be in sync
11053 // with the full codegen: We don't push both left and right values onto
11054 // the expression stack when one side is a special-case literal.
11055 Expression* sub_expr = NULL;
11056 Handle<String> check;
11057 if (expr->IsLiteralCompareTypeof(&sub_expr, &check)) {
11058 return HandleLiteralCompareTypeof(expr, sub_expr, check);
11060 if (expr->IsLiteralCompareUndefined(&sub_expr, isolate())) {
11061 return HandleLiteralCompareNil(expr, sub_expr, kUndefinedValue);
11063 if (expr->IsLiteralCompareNull(&sub_expr)) {
11064 return HandleLiteralCompareNil(expr, sub_expr, kNullValue);
11067 if (IsClassOfTest(expr)) {
11068 CallRuntime* call = expr->left()->AsCallRuntime();
11069 DCHECK(call->arguments()->length() == 1);
11070 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11071 HValue* value = Pop();
11072 Literal* literal = expr->right()->AsLiteral();
11073 Handle<String> rhs = Handle<String>::cast(literal->value());
11074 HClassOfTestAndBranch* instr = New<HClassOfTestAndBranch>(value, rhs);
11075 return ast_context()->ReturnControl(instr, expr->id());
11078 Type* left_type = expr->left()->bounds().lower;
11079 Type* right_type = expr->right()->bounds().lower;
11080 Type* combined_type = expr->combined_type();
11082 CHECK_ALIVE(VisitForValue(expr->left()));
11083 CHECK_ALIVE(VisitForValue(expr->right()));
11085 if (FLAG_hydrogen_track_positions) SetSourcePosition(expr->position());
11087 HValue* right = Pop();
11088 HValue* left = Pop();
11089 Token::Value op = expr->op();
11091 if (IsLiteralCompareBool(isolate(), left, op, right)) {
11092 HCompareObjectEqAndBranch* result =
11093 New<HCompareObjectEqAndBranch>(left, right);
11094 return ast_context()->ReturnControl(result, expr->id());
11097 if (op == Token::INSTANCEOF) {
11098 // Check to see if the rhs of the instanceof is a global function not
11099 // residing in new space. If it is we assume that the function will stay the
11101 Handle<JSFunction> target = Handle<JSFunction>::null();
11102 VariableProxy* proxy = expr->right()->AsVariableProxy();
11103 bool global_function = (proxy != NULL) && proxy->var()->IsUnallocated();
11104 if (global_function &&
11105 current_info()->has_global_object() &&
11106 !current_info()->global_object()->IsAccessCheckNeeded()) {
11107 Handle<String> name = proxy->name();
11108 Handle<GlobalObject> global(current_info()->global_object());
11109 LookupResult lookup(isolate());
11110 global->Lookup(name, &lookup);
11111 if (lookup.IsNormal() && lookup.GetValue()->IsJSFunction()) {
11112 Handle<JSFunction> candidate(JSFunction::cast(lookup.GetValue()));
11113 // If the function is in new space we assume it's more likely to
11114 // change and thus prefer the general IC code.
11115 if (!isolate()->heap()->InNewSpace(*candidate)) {
11116 target = candidate;
11121 // If the target is not null we have found a known global function that is
11122 // assumed to stay the same for this instanceof.
11123 if (target.is_null()) {
11124 HInstanceOf* result = New<HInstanceOf>(left, right);
11125 return ast_context()->ReturnInstruction(result, expr->id());
11127 Add<HCheckValue>(right, target);
11128 HInstanceOfKnownGlobal* result =
11129 New<HInstanceOfKnownGlobal>(left, target);
11130 return ast_context()->ReturnInstruction(result, expr->id());
11133 // Code below assumes that we don't fall through.
11135 } else if (op == Token::IN) {
11136 HValue* function = AddLoadJSBuiltin(Builtins::IN);
11137 Add<HPushArguments>(left, right);
11138 // TODO(olivf) InvokeFunction produces a check for the parameter count,
11139 // even though we are certain to pass the correct number of arguments here.
11140 HInstruction* result = New<HInvokeFunction>(function, 2);
11141 return ast_context()->ReturnInstruction(result, expr->id());
11144 PushBeforeSimulateBehavior push_behavior =
11145 ast_context()->IsEffect() ? NO_PUSH_BEFORE_SIMULATE
11146 : PUSH_BEFORE_SIMULATE;
11147 HControlInstruction* compare = BuildCompareInstruction(
11148 op, left, right, left_type, right_type, combined_type,
11149 ScriptPositionToSourcePosition(expr->left()->position()),
11150 ScriptPositionToSourcePosition(expr->right()->position()),
11151 push_behavior, expr->id());
11152 if (compare == NULL) return; // Bailed out.
11153 return ast_context()->ReturnControl(compare, expr->id());
11157 HControlInstruction* HOptimizedGraphBuilder::BuildCompareInstruction(
11163 Type* combined_type,
11164 HSourcePosition left_position,
11165 HSourcePosition right_position,
11166 PushBeforeSimulateBehavior push_sim_result,
11167 BailoutId bailout_id) {
11168 // Cases handled below depend on collected type feedback. They should
11169 // soft deoptimize when there is no type feedback.
11170 if (combined_type->Is(Type::None())) {
11171 Add<HDeoptimize>("Insufficient type feedback for combined type "
11172 "of binary operation",
11173 Deoptimizer::SOFT);
11174 combined_type = left_type = right_type = Type::Any(zone());
11177 Representation left_rep = Representation::FromType(left_type);
11178 Representation right_rep = Representation::FromType(right_type);
11179 Representation combined_rep = Representation::FromType(combined_type);
11181 if (combined_type->Is(Type::Receiver())) {
11182 if (Token::IsEqualityOp(op)) {
11183 // HCompareObjectEqAndBranch can only deal with object, so
11184 // exclude numbers.
11185 if ((left->IsConstant() &&
11186 HConstant::cast(left)->HasNumberValue()) ||
11187 (right->IsConstant() &&
11188 HConstant::cast(right)->HasNumberValue())) {
11189 Add<HDeoptimize>("Type mismatch between feedback and constant",
11190 Deoptimizer::SOFT);
11191 // The caller expects a branch instruction, so make it happy.
11192 return New<HBranch>(graph()->GetConstantTrue());
11194 // Can we get away with map check and not instance type check?
11195 HValue* operand_to_check =
11196 left->block()->block_id() < right->block()->block_id() ? left : right;
11197 if (combined_type->IsClass()) {
11198 Handle<Map> map = combined_type->AsClass()->Map();
11199 AddCheckMap(operand_to_check, map);
11200 HCompareObjectEqAndBranch* result =
11201 New<HCompareObjectEqAndBranch>(left, right);
11202 if (FLAG_hydrogen_track_positions) {
11203 result->set_operand_position(zone(), 0, left_position);
11204 result->set_operand_position(zone(), 1, right_position);
11208 BuildCheckHeapObject(operand_to_check);
11209 Add<HCheckInstanceType>(operand_to_check,
11210 HCheckInstanceType::IS_SPEC_OBJECT);
11211 HCompareObjectEqAndBranch* result =
11212 New<HCompareObjectEqAndBranch>(left, right);
11216 Bailout(kUnsupportedNonPrimitiveCompare);
11219 } else if (combined_type->Is(Type::InternalizedString()) &&
11220 Token::IsEqualityOp(op)) {
11221 // If we have a constant argument, it should be consistent with the type
11222 // feedback (otherwise we fail assertions in HCompareObjectEqAndBranch).
11223 if ((left->IsConstant() &&
11224 !HConstant::cast(left)->HasInternalizedStringValue()) ||
11225 (right->IsConstant() &&
11226 !HConstant::cast(right)->HasInternalizedStringValue())) {
11227 Add<HDeoptimize>("Type mismatch between feedback and constant",
11228 Deoptimizer::SOFT);
11229 // The caller expects a branch instruction, so make it happy.
11230 return New<HBranch>(graph()->GetConstantTrue());
11232 BuildCheckHeapObject(left);
11233 Add<HCheckInstanceType>(left, HCheckInstanceType::IS_INTERNALIZED_STRING);
11234 BuildCheckHeapObject(right);
11235 Add<HCheckInstanceType>(right, HCheckInstanceType::IS_INTERNALIZED_STRING);
11236 HCompareObjectEqAndBranch* result =
11237 New<HCompareObjectEqAndBranch>(left, right);
11239 } else if (combined_type->Is(Type::String())) {
11240 BuildCheckHeapObject(left);
11241 Add<HCheckInstanceType>(left, HCheckInstanceType::IS_STRING);
11242 BuildCheckHeapObject(right);
11243 Add<HCheckInstanceType>(right, HCheckInstanceType::IS_STRING);
11244 HStringCompareAndBranch* result =
11245 New<HStringCompareAndBranch>(left, right, op);
11248 if (combined_rep.IsTagged() || combined_rep.IsNone()) {
11249 HCompareGeneric* result = Add<HCompareGeneric>(left, right, op);
11250 result->set_observed_input_representation(1, left_rep);
11251 result->set_observed_input_representation(2, right_rep);
11252 if (result->HasObservableSideEffects()) {
11253 if (push_sim_result == PUSH_BEFORE_SIMULATE) {
11255 AddSimulate(bailout_id, REMOVABLE_SIMULATE);
11258 AddSimulate(bailout_id, REMOVABLE_SIMULATE);
11261 // TODO(jkummerow): Can we make this more efficient?
11262 HBranch* branch = New<HBranch>(result);
11265 HCompareNumericAndBranch* result =
11266 New<HCompareNumericAndBranch>(left, right, op);
11267 result->set_observed_input_representation(left_rep, right_rep);
11268 if (FLAG_hydrogen_track_positions) {
11269 result->SetOperandPositions(zone(), left_position, right_position);
11277 void HOptimizedGraphBuilder::HandleLiteralCompareNil(CompareOperation* expr,
11278 Expression* sub_expr,
11280 DCHECK(!HasStackOverflow());
11281 DCHECK(current_block() != NULL);
11282 DCHECK(current_block()->HasPredecessor());
11283 DCHECK(expr->op() == Token::EQ || expr->op() == Token::EQ_STRICT);
11284 if (!FLAG_hydrogen_track_positions) SetSourcePosition(expr->position());
11285 CHECK_ALIVE(VisitForValue(sub_expr));
11286 HValue* value = Pop();
11287 if (expr->op() == Token::EQ_STRICT) {
11288 HConstant* nil_constant = nil == kNullValue
11289 ? graph()->GetConstantNull()
11290 : graph()->GetConstantUndefined();
11291 HCompareObjectEqAndBranch* instr =
11292 New<HCompareObjectEqAndBranch>(value, nil_constant);
11293 return ast_context()->ReturnControl(instr, expr->id());
11295 DCHECK_EQ(Token::EQ, expr->op());
11296 Type* type = expr->combined_type()->Is(Type::None())
11297 ? Type::Any(zone()) : expr->combined_type();
11298 HIfContinuation continuation;
11299 BuildCompareNil(value, type, &continuation);
11300 return ast_context()->ReturnContinuation(&continuation, expr->id());
11305 HInstruction* HOptimizedGraphBuilder::BuildThisFunction() {
11306 // If we share optimized code between different closures, the
11307 // this-function is not a constant, except inside an inlined body.
11308 if (function_state()->outer() != NULL) {
11309 return New<HConstant>(
11310 function_state()->compilation_info()->closure());
11312 return New<HThisFunction>();
11317 HInstruction* HOptimizedGraphBuilder::BuildFastLiteral(
11318 Handle<JSObject> boilerplate_object,
11319 AllocationSiteUsageContext* site_context) {
11320 NoObservableSideEffectsScope no_effects(this);
11321 InstanceType instance_type = boilerplate_object->map()->instance_type();
11322 DCHECK(instance_type == JS_ARRAY_TYPE || instance_type == JS_OBJECT_TYPE);
11324 HType type = instance_type == JS_ARRAY_TYPE
11325 ? HType::JSArray() : HType::JSObject();
11326 HValue* object_size_constant = Add<HConstant>(
11327 boilerplate_object->map()->instance_size());
11329 PretenureFlag pretenure_flag = NOT_TENURED;
11330 if (FLAG_allocation_site_pretenuring) {
11331 pretenure_flag = site_context->current()->GetPretenureMode();
11332 Handle<AllocationSite> site(site_context->current());
11333 AllocationSite::AddDependentCompilationInfo(
11334 site, AllocationSite::TENURING, top_info());
11337 HInstruction* object = Add<HAllocate>(object_size_constant, type,
11338 pretenure_flag, instance_type, site_context->current());
11340 // If allocation folding reaches Page::kMaxRegularHeapObjectSize the
11341 // elements array may not get folded into the object. Hence, we set the
11342 // elements pointer to empty fixed array and let store elimination remove
11343 // this store in the folding case.
11344 HConstant* empty_fixed_array = Add<HConstant>(
11345 isolate()->factory()->empty_fixed_array());
11346 Add<HStoreNamedField>(object, HObjectAccess::ForElementsPointer(),
11347 empty_fixed_array);
11349 BuildEmitObjectHeader(boilerplate_object, object);
11351 Handle<FixedArrayBase> elements(boilerplate_object->elements());
11352 int elements_size = (elements->length() > 0 &&
11353 elements->map() != isolate()->heap()->fixed_cow_array_map()) ?
11354 elements->Size() : 0;
11356 if (pretenure_flag == TENURED &&
11357 elements->map() == isolate()->heap()->fixed_cow_array_map() &&
11358 isolate()->heap()->InNewSpace(*elements)) {
11359 // If we would like to pretenure a fixed cow array, we must ensure that the
11360 // array is already in old space, otherwise we'll create too many old-to-
11361 // new-space pointers (overflowing the store buffer).
11362 elements = Handle<FixedArrayBase>(
11363 isolate()->factory()->CopyAndTenureFixedCOWArray(
11364 Handle<FixedArray>::cast(elements)));
11365 boilerplate_object->set_elements(*elements);
11368 HInstruction* object_elements = NULL;
11369 if (elements_size > 0) {
11370 HValue* object_elements_size = Add<HConstant>(elements_size);
11371 InstanceType instance_type = boilerplate_object->HasFastDoubleElements()
11372 ? FIXED_DOUBLE_ARRAY_TYPE : FIXED_ARRAY_TYPE;
11373 object_elements = Add<HAllocate>(
11374 object_elements_size, HType::HeapObject(),
11375 pretenure_flag, instance_type, site_context->current());
11377 BuildInitElementsInObjectHeader(boilerplate_object, object, object_elements);
11379 // Copy object elements if non-COW.
11380 if (object_elements != NULL) {
11381 BuildEmitElements(boilerplate_object, elements, object_elements,
11385 // Copy in-object properties.
11386 if (boilerplate_object->map()->NumberOfFields() != 0) {
11387 BuildEmitInObjectProperties(boilerplate_object, object, site_context,
11394 void HOptimizedGraphBuilder::BuildEmitObjectHeader(
11395 Handle<JSObject> boilerplate_object,
11396 HInstruction* object) {
11397 DCHECK(boilerplate_object->properties()->length() == 0);
11399 Handle<Map> boilerplate_object_map(boilerplate_object->map());
11400 AddStoreMapConstant(object, boilerplate_object_map);
11402 Handle<Object> properties_field =
11403 Handle<Object>(boilerplate_object->properties(), isolate());
11404 DCHECK(*properties_field == isolate()->heap()->empty_fixed_array());
11405 HInstruction* properties = Add<HConstant>(properties_field);
11406 HObjectAccess access = HObjectAccess::ForPropertiesPointer();
11407 Add<HStoreNamedField>(object, access, properties);
11409 if (boilerplate_object->IsJSArray()) {
11410 Handle<JSArray> boilerplate_array =
11411 Handle<JSArray>::cast(boilerplate_object);
11412 Handle<Object> length_field =
11413 Handle<Object>(boilerplate_array->length(), isolate());
11414 HInstruction* length = Add<HConstant>(length_field);
11416 DCHECK(boilerplate_array->length()->IsSmi());
11417 Add<HStoreNamedField>(object, HObjectAccess::ForArrayLength(
11418 boilerplate_array->GetElementsKind()), length);
11423 void HOptimizedGraphBuilder::BuildInitElementsInObjectHeader(
11424 Handle<JSObject> boilerplate_object,
11425 HInstruction* object,
11426 HInstruction* object_elements) {
11427 DCHECK(boilerplate_object->properties()->length() == 0);
11428 if (object_elements == NULL) {
11429 Handle<Object> elements_field =
11430 Handle<Object>(boilerplate_object->elements(), isolate());
11431 object_elements = Add<HConstant>(elements_field);
11433 Add<HStoreNamedField>(object, HObjectAccess::ForElementsPointer(),
11438 void HOptimizedGraphBuilder::BuildEmitInObjectProperties(
11439 Handle<JSObject> boilerplate_object,
11440 HInstruction* object,
11441 AllocationSiteUsageContext* site_context,
11442 PretenureFlag pretenure_flag) {
11443 Handle<Map> boilerplate_map(boilerplate_object->map());
11444 Handle<DescriptorArray> descriptors(boilerplate_map->instance_descriptors());
11445 int limit = boilerplate_map->NumberOfOwnDescriptors();
11447 int copied_fields = 0;
11448 for (int i = 0; i < limit; i++) {
11449 PropertyDetails details = descriptors->GetDetails(i);
11450 if (details.type() != FIELD) continue;
11452 int index = descriptors->GetFieldIndex(i);
11453 int property_offset = boilerplate_object->GetInObjectPropertyOffset(index);
11454 Handle<Name> name(descriptors->GetKey(i));
11455 Handle<Object> value =
11456 Handle<Object>(boilerplate_object->InObjectPropertyAt(index),
11459 // The access for the store depends on the type of the boilerplate.
11460 HObjectAccess access = boilerplate_object->IsJSArray() ?
11461 HObjectAccess::ForJSArrayOffset(property_offset) :
11462 HObjectAccess::ForMapAndOffset(boilerplate_map, property_offset);
11464 if (value->IsJSObject()) {
11465 Handle<JSObject> value_object = Handle<JSObject>::cast(value);
11466 Handle<AllocationSite> current_site = site_context->EnterNewScope();
11467 HInstruction* result =
11468 BuildFastLiteral(value_object, site_context);
11469 site_context->ExitScope(current_site, value_object);
11470 Add<HStoreNamedField>(object, access, result);
11472 Representation representation = details.representation();
11473 HInstruction* value_instruction;
11475 if (representation.IsDouble()) {
11476 // Allocate a HeapNumber box and store the value into it.
11477 HValue* heap_number_constant = Add<HConstant>(HeapNumber::kSize);
11478 // This heap number alloc does not have a corresponding
11479 // AllocationSite. That is okay because
11480 // 1) it's a child object of another object with a valid allocation site
11481 // 2) we can just use the mode of the parent object for pretenuring
11482 HInstruction* double_box =
11483 Add<HAllocate>(heap_number_constant, HType::HeapObject(),
11484 pretenure_flag, MUTABLE_HEAP_NUMBER_TYPE);
11485 AddStoreMapConstant(double_box,
11486 isolate()->factory()->mutable_heap_number_map());
11487 // Unwrap the mutable heap number from the boilerplate.
11488 HValue* double_value =
11489 Add<HConstant>(Handle<HeapNumber>::cast(value)->value());
11490 Add<HStoreNamedField>(
11491 double_box, HObjectAccess::ForHeapNumberValue(), double_value);
11492 value_instruction = double_box;
11493 } else if (representation.IsSmi()) {
11494 value_instruction = value->IsUninitialized()
11495 ? graph()->GetConstant0()
11496 : Add<HConstant>(value);
11497 // Ensure that value is stored as smi.
11498 access = access.WithRepresentation(representation);
11500 value_instruction = Add<HConstant>(value);
11503 Add<HStoreNamedField>(object, access, value_instruction);
11507 int inobject_properties = boilerplate_object->map()->inobject_properties();
11508 HInstruction* value_instruction =
11509 Add<HConstant>(isolate()->factory()->one_pointer_filler_map());
11510 for (int i = copied_fields; i < inobject_properties; i++) {
11511 DCHECK(boilerplate_object->IsJSObject());
11512 int property_offset = boilerplate_object->GetInObjectPropertyOffset(i);
11513 HObjectAccess access =
11514 HObjectAccess::ForMapAndOffset(boilerplate_map, property_offset);
11515 Add<HStoreNamedField>(object, access, value_instruction);
11520 void HOptimizedGraphBuilder::BuildEmitElements(
11521 Handle<JSObject> boilerplate_object,
11522 Handle<FixedArrayBase> elements,
11523 HValue* object_elements,
11524 AllocationSiteUsageContext* site_context) {
11525 ElementsKind kind = boilerplate_object->map()->elements_kind();
11526 int elements_length = elements->length();
11527 HValue* object_elements_length = Add<HConstant>(elements_length);
11528 BuildInitializeElementsHeader(object_elements, kind, object_elements_length);
11530 // Copy elements backing store content.
11531 if (elements->IsFixedDoubleArray()) {
11532 BuildEmitFixedDoubleArray(elements, kind, object_elements);
11533 } else if (elements->IsFixedArray()) {
11534 BuildEmitFixedArray(elements, kind, object_elements,
11542 void HOptimizedGraphBuilder::BuildEmitFixedDoubleArray(
11543 Handle<FixedArrayBase> elements,
11545 HValue* object_elements) {
11546 HInstruction* boilerplate_elements = Add<HConstant>(elements);
11547 int elements_length = elements->length();
11548 for (int i = 0; i < elements_length; i++) {
11549 HValue* key_constant = Add<HConstant>(i);
11550 HInstruction* value_instruction =
11551 Add<HLoadKeyed>(boilerplate_elements, key_constant,
11552 static_cast<HValue*>(NULL), kind,
11553 ALLOW_RETURN_HOLE);
11554 HInstruction* store = Add<HStoreKeyed>(object_elements, key_constant,
11555 value_instruction, kind);
11556 store->SetFlag(HValue::kAllowUndefinedAsNaN);
11561 void HOptimizedGraphBuilder::BuildEmitFixedArray(
11562 Handle<FixedArrayBase> elements,
11564 HValue* object_elements,
11565 AllocationSiteUsageContext* site_context) {
11566 HInstruction* boilerplate_elements = Add<HConstant>(elements);
11567 int elements_length = elements->length();
11568 Handle<FixedArray> fast_elements = Handle<FixedArray>::cast(elements);
11569 for (int i = 0; i < elements_length; i++) {
11570 Handle<Object> value(fast_elements->get(i), isolate());
11571 HValue* key_constant = Add<HConstant>(i);
11572 if (value->IsJSObject()) {
11573 Handle<JSObject> value_object = Handle<JSObject>::cast(value);
11574 Handle<AllocationSite> current_site = site_context->EnterNewScope();
11575 HInstruction* result =
11576 BuildFastLiteral(value_object, site_context);
11577 site_context->ExitScope(current_site, value_object);
11578 Add<HStoreKeyed>(object_elements, key_constant, result, kind);
11580 HInstruction* value_instruction =
11581 Add<HLoadKeyed>(boilerplate_elements, key_constant,
11582 static_cast<HValue*>(NULL), kind,
11583 ALLOW_RETURN_HOLE);
11584 Add<HStoreKeyed>(object_elements, key_constant, value_instruction, kind);
11590 void HOptimizedGraphBuilder::VisitThisFunction(ThisFunction* expr) {
11591 DCHECK(!HasStackOverflow());
11592 DCHECK(current_block() != NULL);
11593 DCHECK(current_block()->HasPredecessor());
11594 HInstruction* instr = BuildThisFunction();
11595 return ast_context()->ReturnInstruction(instr, expr->id());
11599 void HOptimizedGraphBuilder::VisitDeclarations(
11600 ZoneList<Declaration*>* declarations) {
11601 DCHECK(globals_.is_empty());
11602 AstVisitor::VisitDeclarations(declarations);
11603 if (!globals_.is_empty()) {
11604 Handle<FixedArray> array =
11605 isolate()->factory()->NewFixedArray(globals_.length(), TENURED);
11606 for (int i = 0; i < globals_.length(); ++i) array->set(i, *globals_.at(i));
11607 int flags = DeclareGlobalsEvalFlag::encode(current_info()->is_eval()) |
11608 DeclareGlobalsNativeFlag::encode(current_info()->is_native()) |
11609 DeclareGlobalsStrictMode::encode(current_info()->strict_mode());
11610 Add<HDeclareGlobals>(array, flags);
11611 globals_.Rewind(0);
11616 void HOptimizedGraphBuilder::VisitVariableDeclaration(
11617 VariableDeclaration* declaration) {
11618 VariableProxy* proxy = declaration->proxy();
11619 VariableMode mode = declaration->mode();
11620 Variable* variable = proxy->var();
11621 bool hole_init = mode == LET || mode == CONST || mode == CONST_LEGACY;
11622 switch (variable->location()) {
11623 case Variable::UNALLOCATED:
11624 globals_.Add(variable->name(), zone());
11625 globals_.Add(variable->binding_needs_init()
11626 ? isolate()->factory()->the_hole_value()
11627 : isolate()->factory()->undefined_value(), zone());
11629 case Variable::PARAMETER:
11630 case Variable::LOCAL:
11632 HValue* value = graph()->GetConstantHole();
11633 environment()->Bind(variable, value);
11636 case Variable::CONTEXT:
11638 HValue* value = graph()->GetConstantHole();
11639 HValue* context = environment()->context();
11640 HStoreContextSlot* store = Add<HStoreContextSlot>(
11641 context, variable->index(), HStoreContextSlot::kNoCheck, value);
11642 if (store->HasObservableSideEffects()) {
11643 Add<HSimulate>(proxy->id(), REMOVABLE_SIMULATE);
11647 case Variable::LOOKUP:
11648 return Bailout(kUnsupportedLookupSlotInDeclaration);
11653 void HOptimizedGraphBuilder::VisitFunctionDeclaration(
11654 FunctionDeclaration* declaration) {
11655 VariableProxy* proxy = declaration->proxy();
11656 Variable* variable = proxy->var();
11657 switch (variable->location()) {
11658 case Variable::UNALLOCATED: {
11659 globals_.Add(variable->name(), zone());
11660 Handle<SharedFunctionInfo> function = Compiler::BuildFunctionInfo(
11661 declaration->fun(), current_info()->script(), top_info());
11662 // Check for stack-overflow exception.
11663 if (function.is_null()) return SetStackOverflow();
11664 globals_.Add(function, zone());
11667 case Variable::PARAMETER:
11668 case Variable::LOCAL: {
11669 CHECK_ALIVE(VisitForValue(declaration->fun()));
11670 HValue* value = Pop();
11671 BindIfLive(variable, value);
11674 case Variable::CONTEXT: {
11675 CHECK_ALIVE(VisitForValue(declaration->fun()));
11676 HValue* value = Pop();
11677 HValue* context = environment()->context();
11678 HStoreContextSlot* store = Add<HStoreContextSlot>(
11679 context, variable->index(), HStoreContextSlot::kNoCheck, value);
11680 if (store->HasObservableSideEffects()) {
11681 Add<HSimulate>(proxy->id(), REMOVABLE_SIMULATE);
11685 case Variable::LOOKUP:
11686 return Bailout(kUnsupportedLookupSlotInDeclaration);
11691 void HOptimizedGraphBuilder::VisitModuleDeclaration(
11692 ModuleDeclaration* declaration) {
11697 void HOptimizedGraphBuilder::VisitImportDeclaration(
11698 ImportDeclaration* declaration) {
11703 void HOptimizedGraphBuilder::VisitExportDeclaration(
11704 ExportDeclaration* declaration) {
11709 void HOptimizedGraphBuilder::VisitModuleLiteral(ModuleLiteral* module) {
11714 void HOptimizedGraphBuilder::VisitModuleVariable(ModuleVariable* module) {
11719 void HOptimizedGraphBuilder::VisitModulePath(ModulePath* module) {
11724 void HOptimizedGraphBuilder::VisitModuleUrl(ModuleUrl* module) {
11729 void HOptimizedGraphBuilder::VisitModuleStatement(ModuleStatement* stmt) {
11734 // Generators for inline runtime functions.
11735 // Support for types.
11736 void HOptimizedGraphBuilder::GenerateIsSmi(CallRuntime* call) {
11737 DCHECK(call->arguments()->length() == 1);
11738 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11739 HValue* value = Pop();
11740 HIsSmiAndBranch* result = New<HIsSmiAndBranch>(value);
11741 return ast_context()->ReturnControl(result, call->id());
11745 void HOptimizedGraphBuilder::GenerateIsSpecObject(CallRuntime* call) {
11746 DCHECK(call->arguments()->length() == 1);
11747 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11748 HValue* value = Pop();
11749 HHasInstanceTypeAndBranch* result =
11750 New<HHasInstanceTypeAndBranch>(value,
11751 FIRST_SPEC_OBJECT_TYPE,
11752 LAST_SPEC_OBJECT_TYPE);
11753 return ast_context()->ReturnControl(result, call->id());
11757 void HOptimizedGraphBuilder::GenerateIsFunction(CallRuntime* call) {
11758 DCHECK(call->arguments()->length() == 1);
11759 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11760 HValue* value = Pop();
11761 HHasInstanceTypeAndBranch* result =
11762 New<HHasInstanceTypeAndBranch>(value, JS_FUNCTION_TYPE);
11763 return ast_context()->ReturnControl(result, call->id());
11767 void HOptimizedGraphBuilder::GenerateIsMinusZero(CallRuntime* call) {
11768 DCHECK(call->arguments()->length() == 1);
11769 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11770 HValue* value = Pop();
11771 HCompareMinusZeroAndBranch* result = New<HCompareMinusZeroAndBranch>(value);
11772 return ast_context()->ReturnControl(result, call->id());
11776 void HOptimizedGraphBuilder::GenerateHasCachedArrayIndex(CallRuntime* call) {
11777 DCHECK(call->arguments()->length() == 1);
11778 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11779 HValue* value = Pop();
11780 HHasCachedArrayIndexAndBranch* result =
11781 New<HHasCachedArrayIndexAndBranch>(value);
11782 return ast_context()->ReturnControl(result, call->id());
11786 void HOptimizedGraphBuilder::GenerateIsArray(CallRuntime* call) {
11787 DCHECK(call->arguments()->length() == 1);
11788 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11789 HValue* value = Pop();
11790 HHasInstanceTypeAndBranch* result =
11791 New<HHasInstanceTypeAndBranch>(value, JS_ARRAY_TYPE);
11792 return ast_context()->ReturnControl(result, call->id());
11796 void HOptimizedGraphBuilder::GenerateIsRegExp(CallRuntime* call) {
11797 DCHECK(call->arguments()->length() == 1);
11798 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11799 HValue* value = Pop();
11800 HHasInstanceTypeAndBranch* result =
11801 New<HHasInstanceTypeAndBranch>(value, JS_REGEXP_TYPE);
11802 return ast_context()->ReturnControl(result, call->id());
11806 void HOptimizedGraphBuilder::GenerateIsObject(CallRuntime* call) {
11807 DCHECK(call->arguments()->length() == 1);
11808 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11809 HValue* value = Pop();
11810 HIsObjectAndBranch* result = New<HIsObjectAndBranch>(value);
11811 return ast_context()->ReturnControl(result, call->id());
11815 void HOptimizedGraphBuilder::GenerateIsNonNegativeSmi(CallRuntime* call) {
11816 return Bailout(kInlinedRuntimeFunctionIsNonNegativeSmi);
11820 void HOptimizedGraphBuilder::GenerateIsUndetectableObject(CallRuntime* call) {
11821 DCHECK(call->arguments()->length() == 1);
11822 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11823 HValue* value = Pop();
11824 HIsUndetectableAndBranch* result = New<HIsUndetectableAndBranch>(value);
11825 return ast_context()->ReturnControl(result, call->id());
11829 void HOptimizedGraphBuilder::GenerateIsStringWrapperSafeForDefaultValueOf(
11830 CallRuntime* call) {
11831 return Bailout(kInlinedRuntimeFunctionIsStringWrapperSafeForDefaultValueOf);
11835 // Support for construct call checks.
11836 void HOptimizedGraphBuilder::GenerateIsConstructCall(CallRuntime* call) {
11837 DCHECK(call->arguments()->length() == 0);
11838 if (function_state()->outer() != NULL) {
11839 // We are generating graph for inlined function.
11840 HValue* value = function_state()->inlining_kind() == CONSTRUCT_CALL_RETURN
11841 ? graph()->GetConstantTrue()
11842 : graph()->GetConstantFalse();
11843 return ast_context()->ReturnValue(value);
11845 return ast_context()->ReturnControl(New<HIsConstructCallAndBranch>(),
11851 // Support for arguments.length and arguments[?].
11852 void HOptimizedGraphBuilder::GenerateArgumentsLength(CallRuntime* call) {
11853 DCHECK(call->arguments()->length() == 0);
11854 HInstruction* result = NULL;
11855 if (function_state()->outer() == NULL) {
11856 HInstruction* elements = Add<HArgumentsElements>(false);
11857 result = New<HArgumentsLength>(elements);
11859 // Number of arguments without receiver.
11860 int argument_count = environment()->
11861 arguments_environment()->parameter_count() - 1;
11862 result = New<HConstant>(argument_count);
11864 return ast_context()->ReturnInstruction(result, call->id());
11868 void HOptimizedGraphBuilder::GenerateArguments(CallRuntime* call) {
11869 DCHECK(call->arguments()->length() == 1);
11870 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11871 HValue* index = Pop();
11872 HInstruction* result = NULL;
11873 if (function_state()->outer() == NULL) {
11874 HInstruction* elements = Add<HArgumentsElements>(false);
11875 HInstruction* length = Add<HArgumentsLength>(elements);
11876 HInstruction* checked_index = Add<HBoundsCheck>(index, length);
11877 result = New<HAccessArgumentsAt>(elements, length, checked_index);
11879 EnsureArgumentsArePushedForAccess();
11881 // Number of arguments without receiver.
11882 HInstruction* elements = function_state()->arguments_elements();
11883 int argument_count = environment()->
11884 arguments_environment()->parameter_count() - 1;
11885 HInstruction* length = Add<HConstant>(argument_count);
11886 HInstruction* checked_key = Add<HBoundsCheck>(index, length);
11887 result = New<HAccessArgumentsAt>(elements, length, checked_key);
11889 return ast_context()->ReturnInstruction(result, call->id());
11893 // Support for accessing the class and value fields of an object.
11894 void HOptimizedGraphBuilder::GenerateClassOf(CallRuntime* call) {
11895 // The special form detected by IsClassOfTest is detected before we get here
11896 // and does not cause a bailout.
11897 return Bailout(kInlinedRuntimeFunctionClassOf);
11901 void HOptimizedGraphBuilder::GenerateValueOf(CallRuntime* call) {
11902 DCHECK(call->arguments()->length() == 1);
11903 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11904 HValue* object = Pop();
11906 IfBuilder if_objectisvalue(this);
11907 HValue* objectisvalue = if_objectisvalue.If<HHasInstanceTypeAndBranch>(
11908 object, JS_VALUE_TYPE);
11909 if_objectisvalue.Then();
11911 // Return the actual value.
11912 Push(Add<HLoadNamedField>(
11913 object, objectisvalue,
11914 HObjectAccess::ForObservableJSObjectOffset(
11915 JSValue::kValueOffset)));
11916 Add<HSimulate>(call->id(), FIXED_SIMULATE);
11918 if_objectisvalue.Else();
11920 // If the object is not a value return the object.
11922 Add<HSimulate>(call->id(), FIXED_SIMULATE);
11924 if_objectisvalue.End();
11925 return ast_context()->ReturnValue(Pop());
11929 void HOptimizedGraphBuilder::GenerateDateField(CallRuntime* call) {
11930 DCHECK(call->arguments()->length() == 2);
11931 DCHECK_NE(NULL, call->arguments()->at(1)->AsLiteral());
11932 Smi* index = Smi::cast(*(call->arguments()->at(1)->AsLiteral()->value()));
11933 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11934 HValue* date = Pop();
11935 HDateField* result = New<HDateField>(date, index);
11936 return ast_context()->ReturnInstruction(result, call->id());
11940 void HOptimizedGraphBuilder::GenerateOneByteSeqStringSetChar(
11941 CallRuntime* call) {
11942 DCHECK(call->arguments()->length() == 3);
11943 // We need to follow the evaluation order of full codegen.
11944 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
11945 CHECK_ALIVE(VisitForValue(call->arguments()->at(2)));
11946 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11947 HValue* string = Pop();
11948 HValue* value = Pop();
11949 HValue* index = Pop();
11950 Add<HSeqStringSetChar>(String::ONE_BYTE_ENCODING, string,
11952 Add<HSimulate>(call->id(), FIXED_SIMULATE);
11953 return ast_context()->ReturnValue(graph()->GetConstantUndefined());
11957 void HOptimizedGraphBuilder::GenerateTwoByteSeqStringSetChar(
11958 CallRuntime* call) {
11959 DCHECK(call->arguments()->length() == 3);
11960 // We need to follow the evaluation order of full codegen.
11961 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
11962 CHECK_ALIVE(VisitForValue(call->arguments()->at(2)));
11963 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11964 HValue* string = Pop();
11965 HValue* value = Pop();
11966 HValue* index = Pop();
11967 Add<HSeqStringSetChar>(String::TWO_BYTE_ENCODING, string,
11969 Add<HSimulate>(call->id(), FIXED_SIMULATE);
11970 return ast_context()->ReturnValue(graph()->GetConstantUndefined());
11974 void HOptimizedGraphBuilder::GenerateSetValueOf(CallRuntime* call) {
11975 DCHECK(call->arguments()->length() == 2);
11976 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11977 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
11978 HValue* value = Pop();
11979 HValue* object = Pop();
11981 // Check if object is a JSValue.
11982 IfBuilder if_objectisvalue(this);
11983 if_objectisvalue.If<HHasInstanceTypeAndBranch>(object, JS_VALUE_TYPE);
11984 if_objectisvalue.Then();
11986 // Create in-object property store to kValueOffset.
11987 Add<HStoreNamedField>(object,
11988 HObjectAccess::ForObservableJSObjectOffset(JSValue::kValueOffset),
11990 if (!ast_context()->IsEffect()) {
11993 Add<HSimulate>(call->id(), FIXED_SIMULATE);
11995 if_objectisvalue.Else();
11997 // Nothing to do in this case.
11998 if (!ast_context()->IsEffect()) {
12001 Add<HSimulate>(call->id(), FIXED_SIMULATE);
12003 if_objectisvalue.End();
12004 if (!ast_context()->IsEffect()) {
12007 return ast_context()->ReturnValue(value);
12011 // Fast support for charCodeAt(n).
12012 void HOptimizedGraphBuilder::GenerateStringCharCodeAt(CallRuntime* call) {
12013 DCHECK(call->arguments()->length() == 2);
12014 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12015 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12016 HValue* index = Pop();
12017 HValue* string = Pop();
12018 HInstruction* result = BuildStringCharCodeAt(string, index);
12019 return ast_context()->ReturnInstruction(result, call->id());
12023 // Fast support for string.charAt(n) and string[n].
12024 void HOptimizedGraphBuilder::GenerateStringCharFromCode(CallRuntime* call) {
12025 DCHECK(call->arguments()->length() == 1);
12026 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12027 HValue* char_code = Pop();
12028 HInstruction* result = NewUncasted<HStringCharFromCode>(char_code);
12029 return ast_context()->ReturnInstruction(result, call->id());
12033 // Fast support for string.charAt(n) and string[n].
12034 void HOptimizedGraphBuilder::GenerateStringCharAt(CallRuntime* call) {
12035 DCHECK(call->arguments()->length() == 2);
12036 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12037 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12038 HValue* index = Pop();
12039 HValue* string = Pop();
12040 HInstruction* char_code = BuildStringCharCodeAt(string, index);
12041 AddInstruction(char_code);
12042 HInstruction* result = NewUncasted<HStringCharFromCode>(char_code);
12043 return ast_context()->ReturnInstruction(result, call->id());
12047 // Fast support for object equality testing.
12048 void HOptimizedGraphBuilder::GenerateObjectEquals(CallRuntime* call) {
12049 DCHECK(call->arguments()->length() == 2);
12050 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12051 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12052 HValue* right = Pop();
12053 HValue* left = Pop();
12054 HCompareObjectEqAndBranch* result =
12055 New<HCompareObjectEqAndBranch>(left, right);
12056 return ast_context()->ReturnControl(result, call->id());
12060 // Fast support for StringAdd.
12061 void HOptimizedGraphBuilder::GenerateStringAdd(CallRuntime* call) {
12062 DCHECK_EQ(2, call->arguments()->length());
12063 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12064 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12065 HValue* right = Pop();
12066 HValue* left = Pop();
12067 HInstruction* result = NewUncasted<HStringAdd>(left, right);
12068 return ast_context()->ReturnInstruction(result, call->id());
12072 // Fast support for SubString.
12073 void HOptimizedGraphBuilder::GenerateSubString(CallRuntime* call) {
12074 DCHECK_EQ(3, call->arguments()->length());
12075 CHECK_ALIVE(VisitExpressions(call->arguments()));
12076 PushArgumentsFromEnvironment(call->arguments()->length());
12077 HCallStub* result = New<HCallStub>(CodeStub::SubString, 3);
12078 return ast_context()->ReturnInstruction(result, call->id());
12082 // Fast support for StringCompare.
12083 void HOptimizedGraphBuilder::GenerateStringCompare(CallRuntime* call) {
12084 DCHECK_EQ(2, call->arguments()->length());
12085 CHECK_ALIVE(VisitExpressions(call->arguments()));
12086 PushArgumentsFromEnvironment(call->arguments()->length());
12087 HCallStub* result = New<HCallStub>(CodeStub::StringCompare, 2);
12088 return ast_context()->ReturnInstruction(result, call->id());
12092 // Support for direct calls from JavaScript to native RegExp code.
12093 void HOptimizedGraphBuilder::GenerateRegExpExec(CallRuntime* call) {
12094 DCHECK_EQ(4, call->arguments()->length());
12095 CHECK_ALIVE(VisitExpressions(call->arguments()));
12096 PushArgumentsFromEnvironment(call->arguments()->length());
12097 HCallStub* result = New<HCallStub>(CodeStub::RegExpExec, 4);
12098 return ast_context()->ReturnInstruction(result, call->id());
12102 void HOptimizedGraphBuilder::GenerateDoubleLo(CallRuntime* call) {
12103 DCHECK_EQ(1, call->arguments()->length());
12104 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12105 HValue* value = Pop();
12106 HInstruction* result = NewUncasted<HDoubleBits>(value, HDoubleBits::LOW);
12107 return ast_context()->ReturnInstruction(result, call->id());
12111 void HOptimizedGraphBuilder::GenerateDoubleHi(CallRuntime* call) {
12112 DCHECK_EQ(1, call->arguments()->length());
12113 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12114 HValue* value = Pop();
12115 HInstruction* result = NewUncasted<HDoubleBits>(value, HDoubleBits::HIGH);
12116 return ast_context()->ReturnInstruction(result, call->id());
12120 void HOptimizedGraphBuilder::GenerateConstructDouble(CallRuntime* call) {
12121 DCHECK_EQ(2, call->arguments()->length());
12122 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12123 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12124 HValue* lo = Pop();
12125 HValue* hi = Pop();
12126 HInstruction* result = NewUncasted<HConstructDouble>(hi, lo);
12127 return ast_context()->ReturnInstruction(result, call->id());
12131 // Construct a RegExp exec result with two in-object properties.
12132 void HOptimizedGraphBuilder::GenerateRegExpConstructResult(CallRuntime* call) {
12133 DCHECK_EQ(3, call->arguments()->length());
12134 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12135 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12136 CHECK_ALIVE(VisitForValue(call->arguments()->at(2)));
12137 HValue* input = Pop();
12138 HValue* index = Pop();
12139 HValue* length = Pop();
12140 HValue* result = BuildRegExpConstructResult(length, index, input);
12141 return ast_context()->ReturnValue(result);
12145 // Support for fast native caches.
12146 void HOptimizedGraphBuilder::GenerateGetFromCache(CallRuntime* call) {
12147 return Bailout(kInlinedRuntimeFunctionGetFromCache);
12151 // Fast support for number to string.
12152 void HOptimizedGraphBuilder::GenerateNumberToString(CallRuntime* call) {
12153 DCHECK_EQ(1, call->arguments()->length());
12154 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12155 HValue* number = Pop();
12156 HValue* result = BuildNumberToString(number, Type::Any(zone()));
12157 return ast_context()->ReturnValue(result);
12161 // Fast call for custom callbacks.
12162 void HOptimizedGraphBuilder::GenerateCallFunction(CallRuntime* call) {
12163 // 1 ~ The function to call is not itself an argument to the call.
12164 int arg_count = call->arguments()->length() - 1;
12165 DCHECK(arg_count >= 1); // There's always at least a receiver.
12167 CHECK_ALIVE(VisitExpressions(call->arguments()));
12168 // The function is the last argument
12169 HValue* function = Pop();
12170 // Push the arguments to the stack
12171 PushArgumentsFromEnvironment(arg_count);
12173 IfBuilder if_is_jsfunction(this);
12174 if_is_jsfunction.If<HHasInstanceTypeAndBranch>(function, JS_FUNCTION_TYPE);
12176 if_is_jsfunction.Then();
12178 HInstruction* invoke_result =
12179 Add<HInvokeFunction>(function, arg_count);
12180 if (!ast_context()->IsEffect()) {
12181 Push(invoke_result);
12183 Add<HSimulate>(call->id(), FIXED_SIMULATE);
12186 if_is_jsfunction.Else();
12188 HInstruction* call_result =
12189 Add<HCallFunction>(function, arg_count);
12190 if (!ast_context()->IsEffect()) {
12193 Add<HSimulate>(call->id(), FIXED_SIMULATE);
12195 if_is_jsfunction.End();
12197 if (ast_context()->IsEffect()) {
12198 // EffectContext::ReturnValue ignores the value, so we can just pass
12199 // 'undefined' (as we do not have the call result anymore).
12200 return ast_context()->ReturnValue(graph()->GetConstantUndefined());
12202 return ast_context()->ReturnValue(Pop());
12207 // Fast call to math functions.
12208 void HOptimizedGraphBuilder::GenerateMathPow(CallRuntime* call) {
12209 DCHECK_EQ(2, call->arguments()->length());
12210 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12211 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12212 HValue* right = Pop();
12213 HValue* left = Pop();
12214 HInstruction* result = NewUncasted<HPower>(left, right);
12215 return ast_context()->ReturnInstruction(result, call->id());
12219 void HOptimizedGraphBuilder::GenerateMathLogRT(CallRuntime* call) {
12220 DCHECK(call->arguments()->length() == 1);
12221 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12222 HValue* value = Pop();
12223 HInstruction* result = NewUncasted<HUnaryMathOperation>(value, kMathLog);
12224 return ast_context()->ReturnInstruction(result, call->id());
12228 void HOptimizedGraphBuilder::GenerateMathSqrtRT(CallRuntime* call) {
12229 DCHECK(call->arguments()->length() == 1);
12230 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12231 HValue* value = Pop();
12232 HInstruction* result = NewUncasted<HUnaryMathOperation>(value, kMathSqrt);
12233 return ast_context()->ReturnInstruction(result, call->id());
12237 void HOptimizedGraphBuilder::GenerateGetCachedArrayIndex(CallRuntime* call) {
12238 DCHECK(call->arguments()->length() == 1);
12239 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12240 HValue* value = Pop();
12241 HGetCachedArrayIndex* result = New<HGetCachedArrayIndex>(value);
12242 return ast_context()->ReturnInstruction(result, call->id());
12246 void HOptimizedGraphBuilder::GenerateFastAsciiArrayJoin(CallRuntime* call) {
12247 return Bailout(kInlinedRuntimeFunctionFastAsciiArrayJoin);
12251 // Support for generators.
12252 void HOptimizedGraphBuilder::GenerateGeneratorNext(CallRuntime* call) {
12253 return Bailout(kInlinedRuntimeFunctionGeneratorNext);
12257 void HOptimizedGraphBuilder::GenerateGeneratorThrow(CallRuntime* call) {
12258 return Bailout(kInlinedRuntimeFunctionGeneratorThrow);
12262 void HOptimizedGraphBuilder::GenerateDebugBreakInOptimizedCode(
12263 CallRuntime* call) {
12264 Add<HDebugBreak>();
12265 return ast_context()->ReturnValue(graph()->GetConstant0());
12269 void HOptimizedGraphBuilder::GenerateDebugIsActive(CallRuntime* call) {
12270 DCHECK(call->arguments()->length() == 0);
12272 Add<HConstant>(ExternalReference::debug_is_active_address(isolate()));
12273 HValue* value = Add<HLoadNamedField>(
12274 ref, static_cast<HValue*>(NULL), HObjectAccess::ForExternalUInteger8());
12275 return ast_context()->ReturnValue(value);
12279 #undef CHECK_BAILOUT
12283 HEnvironment::HEnvironment(HEnvironment* outer,
12285 Handle<JSFunction> closure,
12287 : closure_(closure),
12289 frame_type_(JS_FUNCTION),
12290 parameter_count_(0),
12291 specials_count_(1),
12297 ast_id_(BailoutId::None()),
12299 Scope* declaration_scope = scope->DeclarationScope();
12300 Initialize(declaration_scope->num_parameters() + 1,
12301 declaration_scope->num_stack_slots(), 0);
12305 HEnvironment::HEnvironment(Zone* zone, int parameter_count)
12306 : values_(0, zone),
12308 parameter_count_(parameter_count),
12309 specials_count_(1),
12315 ast_id_(BailoutId::None()),
12317 Initialize(parameter_count, 0, 0);
12321 HEnvironment::HEnvironment(const HEnvironment* other, Zone* zone)
12322 : values_(0, zone),
12323 frame_type_(JS_FUNCTION),
12324 parameter_count_(0),
12325 specials_count_(0),
12331 ast_id_(other->ast_id()),
12337 HEnvironment::HEnvironment(HEnvironment* outer,
12338 Handle<JSFunction> closure,
12339 FrameType frame_type,
12342 : closure_(closure),
12343 values_(arguments, zone),
12344 frame_type_(frame_type),
12345 parameter_count_(arguments),
12346 specials_count_(0),
12352 ast_id_(BailoutId::None()),
12357 void HEnvironment::Initialize(int parameter_count,
12359 int stack_height) {
12360 parameter_count_ = parameter_count;
12361 local_count_ = local_count;
12363 // Avoid reallocating the temporaries' backing store on the first Push.
12364 int total = parameter_count + specials_count_ + local_count + stack_height;
12365 values_.Initialize(total + 4, zone());
12366 for (int i = 0; i < total; ++i) values_.Add(NULL, zone());
12370 void HEnvironment::Initialize(const HEnvironment* other) {
12371 closure_ = other->closure();
12372 values_.AddAll(other->values_, zone());
12373 assigned_variables_.Union(other->assigned_variables_, zone());
12374 frame_type_ = other->frame_type_;
12375 parameter_count_ = other->parameter_count_;
12376 local_count_ = other->local_count_;
12377 if (other->outer_ != NULL) outer_ = other->outer_->Copy(); // Deep copy.
12378 entry_ = other->entry_;
12379 pop_count_ = other->pop_count_;
12380 push_count_ = other->push_count_;
12381 specials_count_ = other->specials_count_;
12382 ast_id_ = other->ast_id_;
12386 void HEnvironment::AddIncomingEdge(HBasicBlock* block, HEnvironment* other) {
12387 DCHECK(!block->IsLoopHeader());
12388 DCHECK(values_.length() == other->values_.length());
12390 int length = values_.length();
12391 for (int i = 0; i < length; ++i) {
12392 HValue* value = values_[i];
12393 if (value != NULL && value->IsPhi() && value->block() == block) {
12394 // There is already a phi for the i'th value.
12395 HPhi* phi = HPhi::cast(value);
12396 // Assert index is correct and that we haven't missed an incoming edge.
12397 DCHECK(phi->merged_index() == i || !phi->HasMergedIndex());
12398 DCHECK(phi->OperandCount() == block->predecessors()->length());
12399 phi->AddInput(other->values_[i]);
12400 } else if (values_[i] != other->values_[i]) {
12401 // There is a fresh value on the incoming edge, a phi is needed.
12402 DCHECK(values_[i] != NULL && other->values_[i] != NULL);
12403 HPhi* phi = block->AddNewPhi(i);
12404 HValue* old_value = values_[i];
12405 for (int j = 0; j < block->predecessors()->length(); j++) {
12406 phi->AddInput(old_value);
12408 phi->AddInput(other->values_[i]);
12409 this->values_[i] = phi;
12415 void HEnvironment::Bind(int index, HValue* value) {
12416 DCHECK(value != NULL);
12417 assigned_variables_.Add(index, zone());
12418 values_[index] = value;
12422 bool HEnvironment::HasExpressionAt(int index) const {
12423 return index >= parameter_count_ + specials_count_ + local_count_;
12427 bool HEnvironment::ExpressionStackIsEmpty() const {
12428 DCHECK(length() >= first_expression_index());
12429 return length() == first_expression_index();
12433 void HEnvironment::SetExpressionStackAt(int index_from_top, HValue* value) {
12434 int count = index_from_top + 1;
12435 int index = values_.length() - count;
12436 DCHECK(HasExpressionAt(index));
12437 // The push count must include at least the element in question or else
12438 // the new value will not be included in this environment's history.
12439 if (push_count_ < count) {
12440 // This is the same effect as popping then re-pushing 'count' elements.
12441 pop_count_ += (count - push_count_);
12442 push_count_ = count;
12444 values_[index] = value;
12448 void HEnvironment::Drop(int count) {
12449 for (int i = 0; i < count; ++i) {
12455 HEnvironment* HEnvironment::Copy() const {
12456 return new(zone()) HEnvironment(this, zone());
12460 HEnvironment* HEnvironment::CopyWithoutHistory() const {
12461 HEnvironment* result = Copy();
12462 result->ClearHistory();
12467 HEnvironment* HEnvironment::CopyAsLoopHeader(HBasicBlock* loop_header) const {
12468 HEnvironment* new_env = Copy();
12469 for (int i = 0; i < values_.length(); ++i) {
12470 HPhi* phi = loop_header->AddNewPhi(i);
12471 phi->AddInput(values_[i]);
12472 new_env->values_[i] = phi;
12474 new_env->ClearHistory();
12479 HEnvironment* HEnvironment::CreateStubEnvironment(HEnvironment* outer,
12480 Handle<JSFunction> target,
12481 FrameType frame_type,
12482 int arguments) const {
12483 HEnvironment* new_env =
12484 new(zone()) HEnvironment(outer, target, frame_type,
12485 arguments + 1, zone());
12486 for (int i = 0; i <= arguments; ++i) { // Include receiver.
12487 new_env->Push(ExpressionStackAt(arguments - i));
12489 new_env->ClearHistory();
12494 HEnvironment* HEnvironment::CopyForInlining(
12495 Handle<JSFunction> target,
12497 FunctionLiteral* function,
12498 HConstant* undefined,
12499 InliningKind inlining_kind) const {
12500 DCHECK(frame_type() == JS_FUNCTION);
12502 // Outer environment is a copy of this one without the arguments.
12503 int arity = function->scope()->num_parameters();
12505 HEnvironment* outer = Copy();
12506 outer->Drop(arguments + 1); // Including receiver.
12507 outer->ClearHistory();
12509 if (inlining_kind == CONSTRUCT_CALL_RETURN) {
12510 // Create artificial constructor stub environment. The receiver should
12511 // actually be the constructor function, but we pass the newly allocated
12512 // object instead, DoComputeConstructStubFrame() relies on that.
12513 outer = CreateStubEnvironment(outer, target, JS_CONSTRUCT, arguments);
12514 } else if (inlining_kind == GETTER_CALL_RETURN) {
12515 // We need an additional StackFrame::INTERNAL frame for restoring the
12516 // correct context.
12517 outer = CreateStubEnvironment(outer, target, JS_GETTER, arguments);
12518 } else if (inlining_kind == SETTER_CALL_RETURN) {
12519 // We need an additional StackFrame::INTERNAL frame for temporarily saving
12520 // the argument of the setter, see StoreStubCompiler::CompileStoreViaSetter.
12521 outer = CreateStubEnvironment(outer, target, JS_SETTER, arguments);
12524 if (arity != arguments) {
12525 // Create artificial arguments adaptation environment.
12526 outer = CreateStubEnvironment(outer, target, ARGUMENTS_ADAPTOR, arguments);
12529 HEnvironment* inner =
12530 new(zone()) HEnvironment(outer, function->scope(), target, zone());
12531 // Get the argument values from the original environment.
12532 for (int i = 0; i <= arity; ++i) { // Include receiver.
12533 HValue* push = (i <= arguments) ?
12534 ExpressionStackAt(arguments - i) : undefined;
12535 inner->SetValueAt(i, push);
12537 inner->SetValueAt(arity + 1, context());
12538 for (int i = arity + 2; i < inner->length(); ++i) {
12539 inner->SetValueAt(i, undefined);
12542 inner->set_ast_id(BailoutId::FunctionEntry());
12547 OStream& operator<<(OStream& os, const HEnvironment& env) {
12548 for (int i = 0; i < env.length(); i++) {
12549 if (i == 0) os << "parameters\n";
12550 if (i == env.parameter_count()) os << "specials\n";
12551 if (i == env.parameter_count() + env.specials_count()) os << "locals\n";
12552 if (i == env.parameter_count() + env.specials_count() + env.local_count()) {
12553 os << "expressions\n";
12555 HValue* val = env.values()->at(i);
12568 void HTracer::TraceCompilation(CompilationInfo* info) {
12569 Tag tag(this, "compilation");
12570 if (info->IsOptimizing()) {
12571 Handle<String> name = info->function()->debug_name();
12572 PrintStringProperty("name", name->ToCString().get());
12574 trace_.Add("method \"%s:%d\"\n",
12575 name->ToCString().get(),
12576 info->optimization_id());
12578 CodeStub::Major major_key = info->code_stub()->MajorKey();
12579 PrintStringProperty("name", CodeStub::MajorName(major_key, false));
12580 PrintStringProperty("method", "stub");
12582 PrintLongProperty("date",
12583 static_cast<int64_t>(base::OS::TimeCurrentMillis()));
12587 void HTracer::TraceLithium(const char* name, LChunk* chunk) {
12588 DCHECK(!chunk->isolate()->concurrent_recompilation_enabled());
12589 AllowHandleDereference allow_deref;
12590 AllowDeferredHandleDereference allow_deferred_deref;
12591 Trace(name, chunk->graph(), chunk);
12595 void HTracer::TraceHydrogen(const char* name, HGraph* graph) {
12596 DCHECK(!graph->isolate()->concurrent_recompilation_enabled());
12597 AllowHandleDereference allow_deref;
12598 AllowDeferredHandleDereference allow_deferred_deref;
12599 Trace(name, graph, NULL);
12603 void HTracer::Trace(const char* name, HGraph* graph, LChunk* chunk) {
12604 Tag tag(this, "cfg");
12605 PrintStringProperty("name", name);
12606 const ZoneList<HBasicBlock*>* blocks = graph->blocks();
12607 for (int i = 0; i < blocks->length(); i++) {
12608 HBasicBlock* current = blocks->at(i);
12609 Tag block_tag(this, "block");
12610 PrintBlockProperty("name", current->block_id());
12611 PrintIntProperty("from_bci", -1);
12612 PrintIntProperty("to_bci", -1);
12614 if (!current->predecessors()->is_empty()) {
12616 trace_.Add("predecessors");
12617 for (int j = 0; j < current->predecessors()->length(); ++j) {
12618 trace_.Add(" \"B%d\"", current->predecessors()->at(j)->block_id());
12622 PrintEmptyProperty("predecessors");
12625 if (current->end()->SuccessorCount() == 0) {
12626 PrintEmptyProperty("successors");
12629 trace_.Add("successors");
12630 for (HSuccessorIterator it(current->end()); !it.Done(); it.Advance()) {
12631 trace_.Add(" \"B%d\"", it.Current()->block_id());
12636 PrintEmptyProperty("xhandlers");
12640 trace_.Add("flags");
12641 if (current->IsLoopSuccessorDominator()) {
12642 trace_.Add(" \"dom-loop-succ\"");
12644 if (current->IsUnreachable()) {
12645 trace_.Add(" \"dead\"");
12647 if (current->is_osr_entry()) {
12648 trace_.Add(" \"osr\"");
12653 if (current->dominator() != NULL) {
12654 PrintBlockProperty("dominator", current->dominator()->block_id());
12657 PrintIntProperty("loop_depth", current->LoopNestingDepth());
12659 if (chunk != NULL) {
12660 int first_index = current->first_instruction_index();
12661 int last_index = current->last_instruction_index();
12664 LifetimePosition::FromInstructionIndex(first_index).Value());
12667 LifetimePosition::FromInstructionIndex(last_index).Value());
12671 Tag states_tag(this, "states");
12672 Tag locals_tag(this, "locals");
12673 int total = current->phis()->length();
12674 PrintIntProperty("size", current->phis()->length());
12675 PrintStringProperty("method", "None");
12676 for (int j = 0; j < total; ++j) {
12677 HPhi* phi = current->phis()->at(j);
12680 os << phi->merged_index() << " " << NameOf(phi) << " " << *phi << "\n";
12681 trace_.Add(os.c_str());
12686 Tag HIR_tag(this, "HIR");
12687 for (HInstructionIterator it(current); !it.Done(); it.Advance()) {
12688 HInstruction* instruction = it.Current();
12689 int uses = instruction->UseCount();
12692 os << "0 " << uses << " " << NameOf(instruction) << " " << *instruction;
12693 if (FLAG_hydrogen_track_positions &&
12694 instruction->has_position() &&
12695 instruction->position().raw() != 0) {
12696 const HSourcePosition pos = instruction->position();
12698 if (pos.inlining_id() != 0) os << pos.inlining_id() << "_";
12699 os << pos.position();
12702 trace_.Add(os.c_str());
12707 if (chunk != NULL) {
12708 Tag LIR_tag(this, "LIR");
12709 int first_index = current->first_instruction_index();
12710 int last_index = current->last_instruction_index();
12711 if (first_index != -1 && last_index != -1) {
12712 const ZoneList<LInstruction*>* instructions = chunk->instructions();
12713 for (int i = first_index; i <= last_index; ++i) {
12714 LInstruction* linstr = instructions->at(i);
12715 if (linstr != NULL) {
12718 LifetimePosition::FromInstructionIndex(i).Value());
12719 linstr->PrintTo(&trace_);
12721 os << " [hir:" << NameOf(linstr->hydrogen_value()) << "] <|@\n";
12722 trace_.Add(os.c_str());
12731 void HTracer::TraceLiveRanges(const char* name, LAllocator* allocator) {
12732 Tag tag(this, "intervals");
12733 PrintStringProperty("name", name);
12735 const Vector<LiveRange*>* fixed_d = allocator->fixed_double_live_ranges();
12736 for (int i = 0; i < fixed_d->length(); ++i) {
12737 TraceLiveRange(fixed_d->at(i), "fixed", allocator->zone());
12740 const Vector<LiveRange*>* fixed = allocator->fixed_live_ranges();
12741 for (int i = 0; i < fixed->length(); ++i) {
12742 TraceLiveRange(fixed->at(i), "fixed", allocator->zone());
12745 const ZoneList<LiveRange*>* live_ranges = allocator->live_ranges();
12746 for (int i = 0; i < live_ranges->length(); ++i) {
12747 TraceLiveRange(live_ranges->at(i), "object", allocator->zone());
12752 void HTracer::TraceLiveRange(LiveRange* range, const char* type,
12754 if (range != NULL && !range->IsEmpty()) {
12756 trace_.Add("%d %s", range->id(), type);
12757 if (range->HasRegisterAssigned()) {
12758 LOperand* op = range->CreateAssignedOperand(zone);
12759 int assigned_reg = op->index();
12760 if (op->IsDoubleRegister()) {
12761 trace_.Add(" \"%s\"",
12762 DoubleRegister::AllocationIndexToString(assigned_reg));
12763 } else if (op->IsFloat32x4Register()) {
12764 trace_.Add(" \"%s\"",
12765 SIMD128Register::AllocationIndexToString(assigned_reg));
12766 } else if (op->IsFloat64x2Register()) {
12767 trace_.Add(" \"%s\"",
12768 SIMD128Register::AllocationIndexToString(assigned_reg));
12769 } else if (op->IsInt32x4Register()) {
12770 trace_.Add(" \"%s\"",
12771 SIMD128Register::AllocationIndexToString(assigned_reg));
12773 DCHECK(op->IsRegister());
12774 trace_.Add(" \"%s\"", Register::AllocationIndexToString(assigned_reg));
12776 } else if (range->IsSpilled()) {
12777 LOperand* op = range->TopLevel()->GetSpillOperand();
12778 if (op->IsDoubleStackSlot()) {
12779 trace_.Add(" \"double_stack:%d\"", op->index());
12780 } else if (op->IsFloat32x4StackSlot()) {
12781 trace_.Add(" \"float32x4_stack:%d\"", op->index());
12782 } else if (op->IsFloat64x2StackSlot()) {
12783 trace_.Add(" \"float64x2_stack:%d\"", op->index());
12784 } else if (op->IsInt32x4StackSlot()) {
12785 trace_.Add(" \"int32x4_stack:%d\"", op->index());
12787 DCHECK(op->IsStackSlot());
12788 trace_.Add(" \"stack:%d\"", op->index());
12791 int parent_index = -1;
12792 if (range->IsChild()) {
12793 parent_index = range->parent()->id();
12795 parent_index = range->id();
12797 LOperand* op = range->FirstHint();
12798 int hint_index = -1;
12799 if (op != NULL && op->IsUnallocated()) {
12800 hint_index = LUnallocated::cast(op)->virtual_register();
12802 trace_.Add(" %d %d", parent_index, hint_index);
12803 UseInterval* cur_interval = range->first_interval();
12804 while (cur_interval != NULL && range->Covers(cur_interval->start())) {
12805 trace_.Add(" [%d, %d[",
12806 cur_interval->start().Value(),
12807 cur_interval->end().Value());
12808 cur_interval = cur_interval->next();
12811 UsePosition* current_pos = range->first_pos();
12812 while (current_pos != NULL) {
12813 if (current_pos->RegisterIsBeneficial() || FLAG_trace_all_uses) {
12814 trace_.Add(" %d M", current_pos->pos().Value());
12816 current_pos = current_pos->next();
12819 trace_.Add(" \"\"\n");
12824 void HTracer::FlushToFile() {
12825 AppendChars(filename_.start(), trace_.ToCString().get(), trace_.length(),
12831 void HStatistics::Initialize(CompilationInfo* info) {
12832 if (info->shared_info().is_null()) return;
12833 source_size_ += info->shared_info()->SourceSize();
12837 void HStatistics::Print(const char* stats_name) {
12840 "----------------------------------------"
12841 "----------------------------------------\n"
12842 "--- %s timing results:\n"
12843 "----------------------------------------"
12844 "----------------------------------------\n",
12846 base::TimeDelta sum;
12847 for (int i = 0; i < times_.length(); ++i) {
12851 for (int i = 0; i < names_.length(); ++i) {
12852 PrintF("%33s", names_[i]);
12853 double ms = times_[i].InMillisecondsF();
12854 double percent = times_[i].PercentOf(sum);
12855 PrintF(" %8.3f ms / %4.1f %% ", ms, percent);
12857 unsigned size = sizes_[i];
12858 double size_percent = static_cast<double>(size) * 100 / total_size_;
12859 PrintF(" %9u bytes / %4.1f %%\n", size, size_percent);
12863 "----------------------------------------"
12864 "----------------------------------------\n");
12865 base::TimeDelta total = create_graph_ + optimize_graph_ + generate_code_;
12866 PrintF("%33s %8.3f ms / %4.1f %% \n", "Create graph",
12867 create_graph_.InMillisecondsF(), create_graph_.PercentOf(total));
12868 PrintF("%33s %8.3f ms / %4.1f %% \n", "Optimize graph",
12869 optimize_graph_.InMillisecondsF(), optimize_graph_.PercentOf(total));
12870 PrintF("%33s %8.3f ms / %4.1f %% \n", "Generate and install code",
12871 generate_code_.InMillisecondsF(), generate_code_.PercentOf(total));
12873 "----------------------------------------"
12874 "----------------------------------------\n");
12875 PrintF("%33s %8.3f ms %9u bytes\n", "Total",
12876 total.InMillisecondsF(), total_size_);
12877 PrintF("%33s (%.1f times slower than full code gen)\n", "",
12878 total.TimesOf(full_code_gen_));
12880 double source_size_in_kb = static_cast<double>(source_size_) / 1024;
12881 double normalized_time = source_size_in_kb > 0
12882 ? total.InMillisecondsF() / source_size_in_kb
12884 double normalized_size_in_kb = source_size_in_kb > 0
12885 ? total_size_ / 1024 / source_size_in_kb
12887 PrintF("%33s %8.3f ms %7.3f kB allocated\n",
12888 "Average per kB source", normalized_time, normalized_size_in_kb);
12892 void HStatistics::SaveTiming(const char* name, base::TimeDelta time,
12894 total_size_ += size;
12895 for (int i = 0; i < names_.length(); ++i) {
12896 if (strcmp(names_[i], name) == 0) {
12908 HPhase::~HPhase() {
12909 if (ShouldProduceTraceOutput()) {
12910 isolate()->GetHTracer()->TraceHydrogen(name(), graph_);
12914 graph_->Verify(false); // No full verify.
12918 } } // namespace v8::internal