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(this, STORE, ToType(map), name);
5604 if (info.CanAccessMonomorphic()) {
5605 HValue* checked_literal = Add<HCheckMaps>(literal, map);
5606 DCHECK(!info.lookup()->IsPropertyCallbacks());
5607 store = BuildMonomorphicAccess(
5608 &info, literal, checked_literal, value,
5609 BailoutId::None(), BailoutId::None());
5611 CHECK_ALIVE(store = BuildNamedGeneric(
5612 STORE, NULL, literal, name, value));
5615 AddInstruction(store);
5616 if (store->HasObservableSideEffects()) {
5617 Add<HSimulate>(key->id(), REMOVABLE_SIMULATE);
5620 CHECK_ALIVE(VisitForEffect(value));
5625 case ObjectLiteral::Property::PROTOTYPE:
5626 case ObjectLiteral::Property::SETTER:
5627 case ObjectLiteral::Property::GETTER:
5628 return Bailout(kObjectLiteralWithComplexProperty);
5629 default: UNREACHABLE();
5633 if (expr->has_function()) {
5634 // Return the result of the transformation to fast properties
5635 // instead of the original since this operation changes the map
5636 // of the object. This makes sure that the original object won't
5637 // be used by other optimized code before it is transformed
5638 // (e.g. because of code motion).
5639 HToFastProperties* result = Add<HToFastProperties>(Pop());
5640 return ast_context()->ReturnValue(result);
5642 return ast_context()->ReturnValue(Pop());
5647 void HOptimizedGraphBuilder::VisitArrayLiteral(ArrayLiteral* expr) {
5648 DCHECK(!HasStackOverflow());
5649 DCHECK(current_block() != NULL);
5650 DCHECK(current_block()->HasPredecessor());
5651 expr->BuildConstantElements(isolate());
5652 ZoneList<Expression*>* subexprs = expr->values();
5653 int length = subexprs->length();
5654 HInstruction* literal;
5656 Handle<AllocationSite> site;
5657 Handle<FixedArray> literals(environment()->closure()->literals(), isolate());
5658 bool uninitialized = false;
5659 Handle<Object> literals_cell(literals->get(expr->literal_index()),
5661 Handle<JSObject> boilerplate_object;
5662 if (literals_cell->IsUndefined()) {
5663 uninitialized = true;
5664 Handle<Object> raw_boilerplate;
5665 ASSIGN_RETURN_ON_EXCEPTION_VALUE(
5666 isolate(), raw_boilerplate,
5667 Runtime::CreateArrayLiteralBoilerplate(
5668 isolate(), literals, expr->constant_elements()),
5669 Bailout(kArrayBoilerplateCreationFailed));
5671 boilerplate_object = Handle<JSObject>::cast(raw_boilerplate);
5672 AllocationSiteCreationContext creation_context(isolate());
5673 site = creation_context.EnterNewScope();
5674 if (JSObject::DeepWalk(boilerplate_object, &creation_context).is_null()) {
5675 return Bailout(kArrayBoilerplateCreationFailed);
5677 creation_context.ExitScope(site, boilerplate_object);
5678 literals->set(expr->literal_index(), *site);
5680 if (boilerplate_object->elements()->map() ==
5681 isolate()->heap()->fixed_cow_array_map()) {
5682 isolate()->counters()->cow_arrays_created_runtime()->Increment();
5685 DCHECK(literals_cell->IsAllocationSite());
5686 site = Handle<AllocationSite>::cast(literals_cell);
5687 boilerplate_object = Handle<JSObject>(
5688 JSObject::cast(site->transition_info()), isolate());
5691 DCHECK(!boilerplate_object.is_null());
5692 DCHECK(site->SitePointsToLiteral());
5694 ElementsKind boilerplate_elements_kind =
5695 boilerplate_object->GetElementsKind();
5697 // Check whether to use fast or slow deep-copying for boilerplate.
5698 int max_properties = kMaxFastLiteralProperties;
5699 if (IsFastLiteral(boilerplate_object,
5700 kMaxFastLiteralDepth,
5702 AllocationSiteUsageContext usage_context(isolate(), site, false);
5703 usage_context.EnterNewScope();
5704 literal = BuildFastLiteral(boilerplate_object, &usage_context);
5705 usage_context.ExitScope(site, boilerplate_object);
5707 NoObservableSideEffectsScope no_effects(this);
5708 // Boilerplate already exists and constant elements are never accessed,
5709 // pass an empty fixed array to the runtime function instead.
5710 Handle<FixedArray> constants = isolate()->factory()->empty_fixed_array();
5711 int literal_index = expr->literal_index();
5712 int flags = expr->depth() == 1
5713 ? ArrayLiteral::kShallowElements
5714 : ArrayLiteral::kNoFlags;
5715 flags |= ArrayLiteral::kDisableMementos;
5717 Add<HPushArguments>(Add<HConstant>(literals),
5718 Add<HConstant>(literal_index),
5719 Add<HConstant>(constants),
5720 Add<HConstant>(flags));
5722 // TODO(mvstanton): Consider a flag to turn off creation of any
5723 // AllocationMementos for this call: we are in crankshaft and should have
5724 // learned enough about transition behavior to stop emitting mementos.
5725 Runtime::FunctionId function_id = Runtime::kCreateArrayLiteral;
5726 literal = Add<HCallRuntime>(isolate()->factory()->empty_string(),
5727 Runtime::FunctionForId(function_id),
5730 // De-opt if elements kind changed from boilerplate_elements_kind.
5731 Handle<Map> map = Handle<Map>(boilerplate_object->map(), isolate());
5732 literal = Add<HCheckMaps>(literal, map);
5735 // The array is expected in the bailout environment during computation
5736 // of the property values and is the value of the entire expression.
5738 // The literal index is on the stack, too.
5739 Push(Add<HConstant>(expr->literal_index()));
5741 HInstruction* elements = NULL;
5743 for (int i = 0; i < length; i++) {
5744 Expression* subexpr = subexprs->at(i);
5745 // If the subexpression is a literal or a simple materialized literal it
5746 // is already set in the cloned array.
5747 if (CompileTimeValue::IsCompileTimeValue(subexpr)) continue;
5749 CHECK_ALIVE(VisitForValue(subexpr));
5750 HValue* value = Pop();
5751 if (!Smi::IsValid(i)) return Bailout(kNonSmiKeyInArrayLiteral);
5753 elements = AddLoadElements(literal);
5755 HValue* key = Add<HConstant>(i);
5757 switch (boilerplate_elements_kind) {
5758 case FAST_SMI_ELEMENTS:
5759 case FAST_HOLEY_SMI_ELEMENTS:
5761 case FAST_HOLEY_ELEMENTS:
5762 case FAST_DOUBLE_ELEMENTS:
5763 case FAST_HOLEY_DOUBLE_ELEMENTS: {
5764 HStoreKeyed* instr = Add<HStoreKeyed>(elements, key, value,
5765 boilerplate_elements_kind);
5766 instr->SetUninitialized(uninitialized);
5774 Add<HSimulate>(expr->GetIdForElement(i));
5777 Drop(1); // array literal index
5778 return ast_context()->ReturnValue(Pop());
5782 HCheckMaps* HOptimizedGraphBuilder::AddCheckMap(HValue* object,
5784 BuildCheckHeapObject(object);
5785 return Add<HCheckMaps>(object, map);
5789 HInstruction* HOptimizedGraphBuilder::BuildLoadNamedField(
5790 PropertyAccessInfo* info,
5791 HValue* checked_object) {
5792 // See if this is a load for an immutable property
5793 if (checked_object->ActualValue()->IsConstant() &&
5794 info->lookup()->IsCacheable() &&
5795 info->lookup()->IsReadOnly() && info->lookup()->IsDontDelete()) {
5796 Handle<Object> object(
5797 HConstant::cast(checked_object->ActualValue())->handle(isolate()));
5799 if (object->IsJSObject()) {
5800 LookupResult lookup(isolate());
5801 Handle<JSObject>::cast(object)->Lookup(info->name(), &lookup);
5802 Handle<Object> value(lookup.GetLazyValue(), isolate());
5804 DCHECK(!value->IsTheHole());
5805 return New<HConstant>(value);
5809 HObjectAccess access = info->access();
5810 if (access.representation().IsDouble()) {
5811 // Load the heap number.
5812 checked_object = Add<HLoadNamedField>(
5813 checked_object, static_cast<HValue*>(NULL),
5814 access.WithRepresentation(Representation::Tagged()));
5815 // Load the double value from it.
5816 access = HObjectAccess::ForHeapNumberValue();
5819 SmallMapList* map_list = info->field_maps();
5820 if (map_list->length() == 0) {
5821 return New<HLoadNamedField>(checked_object, checked_object, access);
5824 UniqueSet<Map>* maps = new(zone()) UniqueSet<Map>(map_list->length(), zone());
5825 for (int i = 0; i < map_list->length(); ++i) {
5826 maps->Add(Unique<Map>::CreateImmovable(map_list->at(i)), zone());
5828 return New<HLoadNamedField>(
5829 checked_object, checked_object, access, maps, info->field_type());
5833 HInstruction* HOptimizedGraphBuilder::BuildStoreNamedField(
5834 PropertyAccessInfo* info,
5835 HValue* checked_object,
5837 bool transition_to_field = info->lookup()->IsTransition();
5838 // TODO(verwaest): Move this logic into PropertyAccessInfo.
5839 HObjectAccess field_access = info->access();
5841 HStoreNamedField *instr;
5842 if (field_access.representation().IsDouble()) {
5843 HObjectAccess heap_number_access =
5844 field_access.WithRepresentation(Representation::Tagged());
5845 if (transition_to_field) {
5846 // The store requires a mutable HeapNumber to be allocated.
5847 NoObservableSideEffectsScope no_side_effects(this);
5848 HInstruction* heap_number_size = Add<HConstant>(HeapNumber::kSize);
5850 // TODO(hpayer): Allocation site pretenuring support.
5851 HInstruction* heap_number = Add<HAllocate>(heap_number_size,
5852 HType::HeapObject(),
5854 MUTABLE_HEAP_NUMBER_TYPE);
5855 AddStoreMapConstant(
5856 heap_number, isolate()->factory()->mutable_heap_number_map());
5857 Add<HStoreNamedField>(heap_number, HObjectAccess::ForHeapNumberValue(),
5859 instr = New<HStoreNamedField>(checked_object->ActualValue(),
5863 // Already holds a HeapNumber; load the box and write its value field.
5864 HInstruction* heap_number = Add<HLoadNamedField>(
5865 checked_object, static_cast<HValue*>(NULL), heap_number_access);
5866 instr = New<HStoreNamedField>(heap_number,
5867 HObjectAccess::ForHeapNumberValue(),
5868 value, STORE_TO_INITIALIZED_ENTRY);
5871 if (field_access.representation().IsHeapObject()) {
5872 BuildCheckHeapObject(value);
5875 if (!info->field_maps()->is_empty()) {
5876 DCHECK(field_access.representation().IsHeapObject());
5877 value = Add<HCheckMaps>(value, info->field_maps());
5880 // This is a normal store.
5881 instr = New<HStoreNamedField>(
5882 checked_object->ActualValue(), field_access, value,
5883 transition_to_field ? INITIALIZING_STORE : STORE_TO_INITIALIZED_ENTRY);
5886 if (transition_to_field) {
5887 Handle<Map> transition(info->transition());
5888 DCHECK(!transition->is_deprecated());
5889 instr->SetTransition(Add<HConstant>(transition));
5895 bool HOptimizedGraphBuilder::PropertyAccessInfo::IsCompatible(
5896 PropertyAccessInfo* info) {
5897 if (!CanInlinePropertyAccess(type_)) return false;
5899 // Currently only handle Type::Number as a polymorphic case.
5900 // TODO(verwaest): Support monomorphic handling of numbers with a HCheckNumber
5902 if (type_->Is(Type::Number())) return false;
5904 // Values are only compatible for monomorphic load if they all behave the same
5905 // regarding value wrappers.
5906 if (type_->Is(Type::NumberOrString())) {
5907 if (!info->type_->Is(Type::NumberOrString())) return false;
5909 if (info->type_->Is(Type::NumberOrString())) return false;
5912 if (!LookupDescriptor()) return false;
5914 if (!lookup_.IsFound()) {
5915 return (!info->lookup_.IsFound() || info->has_holder()) &&
5916 map()->prototype() == info->map()->prototype();
5919 // Mismatch if the other access info found the property in the prototype
5921 if (info->has_holder()) return false;
5923 if (lookup_.IsPropertyCallbacks()) {
5924 return accessor_.is_identical_to(info->accessor_) &&
5925 api_holder_.is_identical_to(info->api_holder_);
5928 if (lookup_.IsConstant()) {
5929 return constant_.is_identical_to(info->constant_);
5932 DCHECK(lookup_.IsField());
5933 if (!info->lookup_.IsField()) return false;
5935 Representation r = access_.representation();
5937 if (!info->access_.representation().IsCompatibleForLoad(r)) return false;
5939 if (!info->access_.representation().IsCompatibleForStore(r)) return false;
5941 if (info->access_.offset() != access_.offset()) return false;
5942 if (info->access_.IsInobject() != access_.IsInobject()) return false;
5944 if (field_maps_.is_empty()) {
5945 info->field_maps_.Clear();
5946 } else if (!info->field_maps_.is_empty()) {
5947 for (int i = 0; i < field_maps_.length(); ++i) {
5948 info->field_maps_.AddMapIfMissing(field_maps_.at(i), info->zone());
5950 info->field_maps_.Sort();
5953 // We can only merge stores that agree on their field maps. The comparison
5954 // below is safe, since we keep the field maps sorted.
5955 if (field_maps_.length() != info->field_maps_.length()) return false;
5956 for (int i = 0; i < field_maps_.length(); ++i) {
5957 if (!field_maps_.at(i).is_identical_to(info->field_maps_.at(i))) {
5962 info->GeneralizeRepresentation(r);
5963 info->field_type_ = info->field_type_.Combine(field_type_);
5968 bool HOptimizedGraphBuilder::PropertyAccessInfo::LookupDescriptor() {
5969 if (!type_->IsClass()) return true;
5970 map()->LookupDescriptor(NULL, *name_, &lookup_);
5971 return LoadResult(map());
5975 bool HOptimizedGraphBuilder::PropertyAccessInfo::LoadResult(Handle<Map> map) {
5976 if (!IsLoad() && lookup_.IsProperty() &&
5977 (lookup_.IsReadOnly() || !lookup_.IsCacheable())) {
5981 if (lookup_.IsField()) {
5982 // Construct the object field access.
5983 access_ = HObjectAccess::ForField(map, &lookup_, name_);
5985 // Load field map for heap objects.
5987 } else if (lookup_.IsPropertyCallbacks()) {
5988 Handle<Object> callback(lookup_.GetValueFromMap(*map), isolate());
5989 if (!callback->IsAccessorPair()) return false;
5990 Object* raw_accessor = IsLoad()
5991 ? Handle<AccessorPair>::cast(callback)->getter()
5992 : Handle<AccessorPair>::cast(callback)->setter();
5993 if (!raw_accessor->IsJSFunction()) return false;
5994 Handle<JSFunction> accessor = handle(JSFunction::cast(raw_accessor));
5995 if (accessor->shared()->IsApiFunction()) {
5996 CallOptimization call_optimization(accessor);
5997 if (call_optimization.is_simple_api_call()) {
5998 CallOptimization::HolderLookup holder_lookup;
5999 Handle<Map> receiver_map = this->map();
6000 api_holder_ = call_optimization.LookupHolderOfExpectedType(
6001 receiver_map, &holder_lookup);
6004 accessor_ = accessor;
6005 } else if (lookup_.IsConstant()) {
6006 constant_ = handle(lookup_.GetConstantFromMap(*map), isolate());
6013 void HOptimizedGraphBuilder::PropertyAccessInfo::LoadFieldMaps(
6015 // Clear any previously collected field maps/type.
6016 field_maps_.Clear();
6017 field_type_ = HType::Tagged();
6019 // Figure out the field type from the accessor map.
6020 Handle<HeapType> field_type(lookup_.GetFieldTypeFromMap(*map), isolate());
6022 // Collect the (stable) maps from the field type.
6023 int num_field_maps = field_type->NumClasses();
6024 if (num_field_maps == 0) return;
6025 DCHECK(access_.representation().IsHeapObject());
6026 field_maps_.Reserve(num_field_maps, zone());
6027 HeapType::Iterator<Map> it = field_type->Classes();
6028 while (!it.Done()) {
6029 Handle<Map> field_map = it.Current();
6030 if (!field_map->is_stable()) {
6031 field_maps_.Clear();
6034 field_maps_.Add(field_map, zone());
6038 DCHECK_EQ(num_field_maps, field_maps_.length());
6040 // Determine field HType from field HeapType.
6041 field_type_ = HType::FromType<HeapType>(field_type);
6042 DCHECK(field_type_.IsHeapObject());
6044 // Add dependency on the map that introduced the field.
6045 Map::AddDependentCompilationInfo(
6046 handle(lookup_.GetFieldOwnerFromMap(*map), isolate()),
6047 DependentCode::kFieldTypeGroup, top_info());
6051 bool HOptimizedGraphBuilder::PropertyAccessInfo::LookupInPrototypes() {
6052 Handle<Map> map = this->map();
6054 while (map->prototype()->IsJSObject()) {
6055 holder_ = handle(JSObject::cast(map->prototype()));
6056 if (holder_->map()->is_deprecated()) {
6057 JSObject::TryMigrateInstance(holder_);
6059 map = Handle<Map>(holder_->map());
6060 if (!CanInlinePropertyAccess(ToType(map))) {
6064 map->LookupDescriptor(*holder_, *name_, &lookup_);
6065 if (lookup_.IsFound()) return LoadResult(map);
6072 bool HOptimizedGraphBuilder::PropertyAccessInfo::CanAccessMonomorphic() {
6073 if (!CanInlinePropertyAccess(type_)) return false;
6074 if (IsJSObjectFieldAccessor()) return IsLoad();
6075 if (this->map()->function_with_prototype() &&
6076 !this->map()->has_non_instance_prototype() &&
6077 name_.is_identical_to(isolate()->factory()->prototype_string())) {
6080 if (!LookupDescriptor()) return false;
6081 if (lookup_.IsFound()) {
6082 if (IsLoad()) return true;
6083 return !lookup_.IsReadOnly() && lookup_.IsCacheable();
6085 if (!LookupInPrototypes()) return false;
6086 if (IsLoad()) return true;
6088 if (lookup_.IsPropertyCallbacks()) return true;
6089 Handle<Map> map = this->map();
6090 map->LookupTransition(NULL, *name_, &lookup_);
6091 if (lookup_.IsTransitionToField() && map->unused_property_fields() > 0) {
6092 // Construct the object field access.
6093 access_ = HObjectAccess::ForField(map, &lookup_, name_);
6095 // Load field map for heap objects.
6096 LoadFieldMaps(transition());
6103 bool HOptimizedGraphBuilder::PropertyAccessInfo::CanAccessAsMonomorphic(
6104 SmallMapList* types) {
6105 DCHECK(type_->Is(ToType(types->first())));
6106 if (!CanAccessMonomorphic()) return false;
6107 STATIC_ASSERT(kMaxLoadPolymorphism == kMaxStorePolymorphism);
6108 if (types->length() > kMaxLoadPolymorphism) return false;
6110 HObjectAccess access = HObjectAccess::ForMap(); // bogus default
6111 if (GetJSObjectFieldAccess(&access)) {
6112 for (int i = 1; i < types->length(); ++i) {
6113 PropertyAccessInfo test_info(
6114 builder_, access_type_, ToType(types->at(i)), name_);
6115 HObjectAccess test_access = HObjectAccess::ForMap(); // bogus default
6116 if (!test_info.GetJSObjectFieldAccess(&test_access)) return false;
6117 if (!access.Equals(test_access)) return false;
6122 // Currently only handle Type::Number as a polymorphic case.
6123 // TODO(verwaest): Support monomorphic handling of numbers with a HCheckNumber
6125 if (type_->Is(Type::Number())) return false;
6127 // Multiple maps cannot transition to the same target map.
6128 DCHECK(!IsLoad() || !lookup_.IsTransition());
6129 if (lookup_.IsTransition() && types->length() > 1) return false;
6131 for (int i = 1; i < types->length(); ++i) {
6132 PropertyAccessInfo test_info(
6133 builder_, access_type_, ToType(types->at(i)), name_);
6134 if (!test_info.IsCompatible(this)) return false;
6141 Handle<Map> HOptimizedGraphBuilder::PropertyAccessInfo::map() {
6142 JSFunction* ctor = IC::GetRootConstructor(
6143 type_, current_info()->closure()->context()->native_context());
6144 if (ctor != NULL) return handle(ctor->initial_map());
6145 return type_->AsClass()->Map();
6149 static bool NeedsWrappingFor(Type* type, Handle<JSFunction> target) {
6150 return type->Is(Type::NumberOrString()) &&
6151 target->shared()->strict_mode() == SLOPPY &&
6152 !target->shared()->native();
6156 HInstruction* HOptimizedGraphBuilder::BuildMonomorphicAccess(
6157 PropertyAccessInfo* info,
6159 HValue* checked_object,
6162 BailoutId return_id,
6163 bool can_inline_accessor) {
6165 HObjectAccess access = HObjectAccess::ForMap(); // bogus default
6166 if (info->GetJSObjectFieldAccess(&access)) {
6167 DCHECK(info->IsLoad());
6168 return New<HLoadNamedField>(object, checked_object, access);
6171 if (info->name().is_identical_to(isolate()->factory()->prototype_string()) &&
6172 info->map()->function_with_prototype()) {
6173 DCHECK(!info->map()->has_non_instance_prototype());
6174 return New<HLoadFunctionPrototype>(checked_object);
6177 HValue* checked_holder = checked_object;
6178 if (info->has_holder()) {
6179 Handle<JSObject> prototype(JSObject::cast(info->map()->prototype()));
6180 checked_holder = BuildCheckPrototypeMaps(prototype, info->holder());
6183 if (!info->lookup()->IsFound()) {
6184 DCHECK(info->IsLoad());
6185 return graph()->GetConstantUndefined();
6188 if (info->lookup()->IsField()) {
6189 if (info->IsLoad()) {
6190 return BuildLoadNamedField(info, checked_holder);
6192 return BuildStoreNamedField(info, checked_object, value);
6196 if (info->lookup()->IsTransition()) {
6197 DCHECK(!info->IsLoad());
6198 return BuildStoreNamedField(info, checked_object, value);
6201 if (info->lookup()->IsPropertyCallbacks()) {
6202 Push(checked_object);
6203 int argument_count = 1;
6204 if (!info->IsLoad()) {
6209 if (NeedsWrappingFor(info->type(), info->accessor())) {
6210 HValue* function = Add<HConstant>(info->accessor());
6211 PushArgumentsFromEnvironment(argument_count);
6212 return New<HCallFunction>(function, argument_count, WRAP_AND_CALL);
6213 } else if (FLAG_inline_accessors && can_inline_accessor) {
6214 bool success = info->IsLoad()
6215 ? TryInlineGetter(info->accessor(), info->map(), ast_id, return_id)
6217 info->accessor(), info->map(), ast_id, return_id, value);
6218 if (success || HasStackOverflow()) return NULL;
6221 PushArgumentsFromEnvironment(argument_count);
6222 return BuildCallConstantFunction(info->accessor(), argument_count);
6225 DCHECK(info->lookup()->IsConstant());
6226 if (info->IsLoad()) {
6227 return New<HConstant>(info->constant());
6229 return New<HCheckValue>(value, Handle<JSFunction>::cast(info->constant()));
6234 void HOptimizedGraphBuilder::HandlePolymorphicNamedFieldAccess(
6235 PropertyAccessType access_type,
6238 BailoutId return_id,
6241 SmallMapList* types,
6242 Handle<String> name) {
6243 // Something did not match; must use a polymorphic load.
6245 HBasicBlock* join = NULL;
6246 HBasicBlock* number_block = NULL;
6247 bool handled_string = false;
6249 bool handle_smi = false;
6250 STATIC_ASSERT(kMaxLoadPolymorphism == kMaxStorePolymorphism);
6251 for (int i = 0; i < types->length() && count < kMaxLoadPolymorphism; ++i) {
6252 PropertyAccessInfo info(this, access_type, ToType(types->at(i)), name);
6253 if (info.type()->Is(Type::String())) {
6254 if (handled_string) continue;
6255 handled_string = true;
6257 if (info.CanAccessMonomorphic()) {
6259 if (info.type()->Is(Type::Number())) {
6267 HControlInstruction* smi_check = NULL;
6268 handled_string = false;
6270 for (int i = 0; i < types->length() && count < kMaxLoadPolymorphism; ++i) {
6271 PropertyAccessInfo info(this, access_type, ToType(types->at(i)), name);
6272 if (info.type()->Is(Type::String())) {
6273 if (handled_string) continue;
6274 handled_string = true;
6276 if (!info.CanAccessMonomorphic()) continue;
6279 join = graph()->CreateBasicBlock();
6281 HBasicBlock* empty_smi_block = graph()->CreateBasicBlock();
6282 HBasicBlock* not_smi_block = graph()->CreateBasicBlock();
6283 number_block = graph()->CreateBasicBlock();
6284 smi_check = New<HIsSmiAndBranch>(
6285 object, empty_smi_block, not_smi_block);
6286 FinishCurrentBlock(smi_check);
6287 GotoNoSimulate(empty_smi_block, number_block);
6288 set_current_block(not_smi_block);
6290 BuildCheckHeapObject(object);
6294 HBasicBlock* if_true = graph()->CreateBasicBlock();
6295 HBasicBlock* if_false = graph()->CreateBasicBlock();
6296 HUnaryControlInstruction* compare;
6299 if (info.type()->Is(Type::Number())) {
6300 Handle<Map> heap_number_map = isolate()->factory()->heap_number_map();
6301 compare = New<HCompareMap>(object, heap_number_map, if_true, if_false);
6302 dependency = smi_check;
6303 } else if (info.type()->Is(Type::String())) {
6304 compare = New<HIsStringAndBranch>(object, if_true, if_false);
6305 dependency = compare;
6307 compare = New<HCompareMap>(object, info.map(), if_true, if_false);
6308 dependency = compare;
6310 FinishCurrentBlock(compare);
6312 if (info.type()->Is(Type::Number())) {
6313 GotoNoSimulate(if_true, number_block);
6314 if_true = number_block;
6317 set_current_block(if_true);
6319 HInstruction* access = BuildMonomorphicAccess(
6320 &info, object, dependency, value, ast_id,
6321 return_id, FLAG_polymorphic_inlining);
6323 HValue* result = NULL;
6324 switch (access_type) {
6333 if (access == NULL) {
6334 if (HasStackOverflow()) return;
6336 if (!access->IsLinked()) AddInstruction(access);
6337 if (!ast_context()->IsEffect()) Push(result);
6340 if (current_block() != NULL) Goto(join);
6341 set_current_block(if_false);
6344 // Finish up. Unconditionally deoptimize if we've handled all the maps we
6345 // know about and do not want to handle ones we've never seen. Otherwise
6346 // use a generic IC.
6347 if (count == types->length() && FLAG_deoptimize_uncommon_cases) {
6348 FinishExitWithHardDeoptimization("Uknown map in polymorphic access");
6350 HInstruction* instr = BuildNamedGeneric(access_type, expr, object, name,
6352 AddInstruction(instr);
6353 if (!ast_context()->IsEffect()) Push(access_type == LOAD ? instr : value);
6358 Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6359 if (!ast_context()->IsEffect()) ast_context()->ReturnValue(Pop());
6364 DCHECK(join != NULL);
6365 if (join->HasPredecessor()) {
6366 join->SetJoinId(ast_id);
6367 set_current_block(join);
6368 if (!ast_context()->IsEffect()) ast_context()->ReturnValue(Pop());
6370 set_current_block(NULL);
6375 static bool ComputeReceiverTypes(Expression* expr,
6379 SmallMapList* types = expr->GetReceiverTypes();
6381 bool monomorphic = expr->IsMonomorphic();
6382 if (types != NULL && receiver->HasMonomorphicJSObjectType()) {
6383 Map* root_map = receiver->GetMonomorphicJSObjectMap()->FindRootMap();
6384 types->FilterForPossibleTransitions(root_map);
6385 monomorphic = types->length() == 1;
6387 return monomorphic && CanInlinePropertyAccess(
6388 IC::MapToType<Type>(types->first(), zone));
6392 static bool AreStringTypes(SmallMapList* types) {
6393 for (int i = 0; i < types->length(); i++) {
6394 if (types->at(i)->instance_type() >= FIRST_NONSTRING_TYPE) return false;
6400 void HOptimizedGraphBuilder::BuildStore(Expression* expr,
6403 BailoutId return_id,
6404 bool is_uninitialized) {
6405 if (!prop->key()->IsPropertyName()) {
6407 HValue* value = environment()->ExpressionStackAt(0);
6408 HValue* key = environment()->ExpressionStackAt(1);
6409 HValue* object = environment()->ExpressionStackAt(2);
6410 bool has_side_effects = false;
6411 HandleKeyedElementAccess(object, key, value, expr,
6412 STORE, &has_side_effects);
6415 Add<HSimulate>(return_id, REMOVABLE_SIMULATE);
6416 return ast_context()->ReturnValue(Pop());
6420 HValue* value = Pop();
6421 HValue* object = Pop();
6423 Literal* key = prop->key()->AsLiteral();
6424 Handle<String> name = Handle<String>::cast(key->value());
6425 DCHECK(!name.is_null());
6427 HInstruction* instr = BuildNamedAccess(STORE, ast_id, return_id, expr,
6428 object, name, value, is_uninitialized);
6429 if (instr == NULL) return;
6431 if (!ast_context()->IsEffect()) Push(value);
6432 AddInstruction(instr);
6433 if (instr->HasObservableSideEffects()) {
6434 Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6436 if (!ast_context()->IsEffect()) Drop(1);
6437 return ast_context()->ReturnValue(value);
6441 void HOptimizedGraphBuilder::HandlePropertyAssignment(Assignment* expr) {
6442 Property* prop = expr->target()->AsProperty();
6443 DCHECK(prop != NULL);
6444 CHECK_ALIVE(VisitForValue(prop->obj()));
6445 if (!prop->key()->IsPropertyName()) {
6446 CHECK_ALIVE(VisitForValue(prop->key()));
6448 CHECK_ALIVE(VisitForValue(expr->value()));
6449 BuildStore(expr, prop, expr->id(),
6450 expr->AssignmentId(), expr->IsUninitialized());
6454 // Because not every expression has a position and there is not common
6455 // superclass of Assignment and CountOperation, we cannot just pass the
6456 // owning expression instead of position and ast_id separately.
6457 void HOptimizedGraphBuilder::HandleGlobalVariableAssignment(
6461 LookupResult lookup(isolate());
6462 GlobalPropertyAccess type = LookupGlobalProperty(var, &lookup, STORE);
6463 if (type == kUseCell) {
6464 Handle<GlobalObject> global(current_info()->global_object());
6465 Handle<PropertyCell> cell(global->GetPropertyCell(&lookup));
6466 if (cell->type()->IsConstant()) {
6467 Handle<Object> constant = cell->type()->AsConstant()->Value();
6468 if (value->IsConstant()) {
6469 HConstant* c_value = HConstant::cast(value);
6470 if (!constant.is_identical_to(c_value->handle(isolate()))) {
6471 Add<HDeoptimize>("Constant global variable assignment",
6472 Deoptimizer::EAGER);
6475 HValue* c_constant = Add<HConstant>(constant);
6476 IfBuilder builder(this);
6477 if (constant->IsNumber()) {
6478 builder.If<HCompareNumericAndBranch>(value, c_constant, Token::EQ);
6480 builder.If<HCompareObjectEqAndBranch>(value, c_constant);
6484 Add<HDeoptimize>("Constant global variable assignment",
6485 Deoptimizer::EAGER);
6489 HInstruction* instr =
6490 Add<HStoreGlobalCell>(value, cell, lookup.GetPropertyDetails());
6491 if (instr->HasObservableSideEffects()) {
6492 Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6495 HValue* global_object = Add<HLoadNamedField>(
6496 context(), static_cast<HValue*>(NULL),
6497 HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
6498 HStoreNamedGeneric* instr =
6499 Add<HStoreNamedGeneric>(global_object, var->name(),
6500 value, function_strict_mode());
6502 DCHECK(instr->HasObservableSideEffects());
6503 Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6508 void HOptimizedGraphBuilder::HandleCompoundAssignment(Assignment* expr) {
6509 Expression* target = expr->target();
6510 VariableProxy* proxy = target->AsVariableProxy();
6511 Property* prop = target->AsProperty();
6512 DCHECK(proxy == NULL || prop == NULL);
6514 // We have a second position recorded in the FullCodeGenerator to have
6515 // type feedback for the binary operation.
6516 BinaryOperation* operation = expr->binary_operation();
6518 if (proxy != NULL) {
6519 Variable* var = proxy->var();
6520 if (var->mode() == LET) {
6521 return Bailout(kUnsupportedLetCompoundAssignment);
6524 CHECK_ALIVE(VisitForValue(operation));
6526 switch (var->location()) {
6527 case Variable::UNALLOCATED:
6528 HandleGlobalVariableAssignment(var,
6530 expr->AssignmentId());
6533 case Variable::PARAMETER:
6534 case Variable::LOCAL:
6535 if (var->mode() == CONST_LEGACY) {
6536 return Bailout(kUnsupportedConstCompoundAssignment);
6538 BindIfLive(var, Top());
6541 case Variable::CONTEXT: {
6542 // Bail out if we try to mutate a parameter value in a function
6543 // using the arguments object. We do not (yet) correctly handle the
6544 // arguments property of the function.
6545 if (current_info()->scope()->arguments() != NULL) {
6546 // Parameters will be allocated to context slots. We have no
6547 // direct way to detect that the variable is a parameter so we do
6548 // a linear search of the parameter variables.
6549 int count = current_info()->scope()->num_parameters();
6550 for (int i = 0; i < count; ++i) {
6551 if (var == current_info()->scope()->parameter(i)) {
6552 Bailout(kAssignmentToParameterFunctionUsesArgumentsObject);
6557 HStoreContextSlot::Mode mode;
6559 switch (var->mode()) {
6561 mode = HStoreContextSlot::kCheckDeoptimize;
6564 // This case is checked statically so no need to
6565 // perform checks here
6568 return ast_context()->ReturnValue(Pop());
6570 mode = HStoreContextSlot::kNoCheck;
6573 HValue* context = BuildContextChainWalk(var);
6574 HStoreContextSlot* instr = Add<HStoreContextSlot>(
6575 context, var->index(), mode, Top());
6576 if (instr->HasObservableSideEffects()) {
6577 Add<HSimulate>(expr->AssignmentId(), REMOVABLE_SIMULATE);
6582 case Variable::LOOKUP:
6583 return Bailout(kCompoundAssignmentToLookupSlot);
6585 return ast_context()->ReturnValue(Pop());
6587 } else if (prop != NULL) {
6588 CHECK_ALIVE(VisitForValue(prop->obj()));
6589 HValue* object = Top();
6591 if (!prop->key()->IsPropertyName() || prop->IsStringAccess()) {
6592 CHECK_ALIVE(VisitForValue(prop->key()));
6596 CHECK_ALIVE(PushLoad(prop, object, key));
6598 CHECK_ALIVE(VisitForValue(expr->value()));
6599 HValue* right = Pop();
6600 HValue* left = Pop();
6602 Push(BuildBinaryOperation(operation, left, right, PUSH_BEFORE_SIMULATE));
6604 BuildStore(expr, prop, expr->id(),
6605 expr->AssignmentId(), expr->IsUninitialized());
6607 return Bailout(kInvalidLhsInCompoundAssignment);
6612 void HOptimizedGraphBuilder::VisitAssignment(Assignment* expr) {
6613 DCHECK(!HasStackOverflow());
6614 DCHECK(current_block() != NULL);
6615 DCHECK(current_block()->HasPredecessor());
6616 VariableProxy* proxy = expr->target()->AsVariableProxy();
6617 Property* prop = expr->target()->AsProperty();
6618 DCHECK(proxy == NULL || prop == NULL);
6620 if (expr->is_compound()) {
6621 HandleCompoundAssignment(expr);
6626 HandlePropertyAssignment(expr);
6627 } else if (proxy != NULL) {
6628 Variable* var = proxy->var();
6630 if (var->mode() == CONST) {
6631 if (expr->op() != Token::INIT_CONST) {
6632 return Bailout(kNonInitializerAssignmentToConst);
6634 } else if (var->mode() == CONST_LEGACY) {
6635 if (expr->op() != Token::INIT_CONST_LEGACY) {
6636 CHECK_ALIVE(VisitForValue(expr->value()));
6637 return ast_context()->ReturnValue(Pop());
6640 if (var->IsStackAllocated()) {
6641 // We insert a use of the old value to detect unsupported uses of const
6642 // variables (e.g. initialization inside a loop).
6643 HValue* old_value = environment()->Lookup(var);
6644 Add<HUseConst>(old_value);
6648 if (proxy->IsArguments()) return Bailout(kAssignmentToArguments);
6650 // Handle the assignment.
6651 switch (var->location()) {
6652 case Variable::UNALLOCATED:
6653 CHECK_ALIVE(VisitForValue(expr->value()));
6654 HandleGlobalVariableAssignment(var,
6656 expr->AssignmentId());
6657 return ast_context()->ReturnValue(Pop());
6659 case Variable::PARAMETER:
6660 case Variable::LOCAL: {
6661 // Perform an initialization check for let declared variables
6663 if (var->mode() == LET && expr->op() == Token::ASSIGN) {
6664 HValue* env_value = environment()->Lookup(var);
6665 if (env_value == graph()->GetConstantHole()) {
6666 return Bailout(kAssignmentToLetVariableBeforeInitialization);
6669 // We do not allow the arguments object to occur in a context where it
6670 // may escape, but assignments to stack-allocated locals are
6672 CHECK_ALIVE(VisitForValue(expr->value(), ARGUMENTS_ALLOWED));
6673 HValue* value = Pop();
6674 BindIfLive(var, value);
6675 return ast_context()->ReturnValue(value);
6678 case Variable::CONTEXT: {
6679 // Bail out if we try to mutate a parameter value in a function using
6680 // the arguments object. We do not (yet) correctly handle the
6681 // arguments property of the function.
6682 if (current_info()->scope()->arguments() != NULL) {
6683 // Parameters will rewrite to context slots. We have no direct way
6684 // to detect that the variable is a parameter.
6685 int count = current_info()->scope()->num_parameters();
6686 for (int i = 0; i < count; ++i) {
6687 if (var == current_info()->scope()->parameter(i)) {
6688 return Bailout(kAssignmentToParameterInArgumentsObject);
6693 CHECK_ALIVE(VisitForValue(expr->value()));
6694 HStoreContextSlot::Mode mode;
6695 if (expr->op() == Token::ASSIGN) {
6696 switch (var->mode()) {
6698 mode = HStoreContextSlot::kCheckDeoptimize;
6701 // This case is checked statically so no need to
6702 // perform checks here
6705 return ast_context()->ReturnValue(Pop());
6707 mode = HStoreContextSlot::kNoCheck;
6709 } else if (expr->op() == Token::INIT_VAR ||
6710 expr->op() == Token::INIT_LET ||
6711 expr->op() == Token::INIT_CONST) {
6712 mode = HStoreContextSlot::kNoCheck;
6714 DCHECK(expr->op() == Token::INIT_CONST_LEGACY);
6716 mode = HStoreContextSlot::kCheckIgnoreAssignment;
6719 HValue* context = BuildContextChainWalk(var);
6720 HStoreContextSlot* instr = Add<HStoreContextSlot>(
6721 context, var->index(), mode, Top());
6722 if (instr->HasObservableSideEffects()) {
6723 Add<HSimulate>(expr->AssignmentId(), REMOVABLE_SIMULATE);
6725 return ast_context()->ReturnValue(Pop());
6728 case Variable::LOOKUP:
6729 return Bailout(kAssignmentToLOOKUPVariable);
6732 return Bailout(kInvalidLeftHandSideInAssignment);
6737 void HOptimizedGraphBuilder::VisitYield(Yield* expr) {
6738 // Generators are not optimized, so we should never get here.
6743 void HOptimizedGraphBuilder::VisitThrow(Throw* expr) {
6744 DCHECK(!HasStackOverflow());
6745 DCHECK(current_block() != NULL);
6746 DCHECK(current_block()->HasPredecessor());
6747 // We don't optimize functions with invalid left-hand sides in
6748 // assignments, count operations, or for-in. Consequently throw can
6749 // currently only occur in an effect context.
6750 DCHECK(ast_context()->IsEffect());
6751 CHECK_ALIVE(VisitForValue(expr->exception()));
6753 HValue* value = environment()->Pop();
6754 if (!FLAG_hydrogen_track_positions) SetSourcePosition(expr->position());
6755 Add<HPushArguments>(value);
6756 Add<HCallRuntime>(isolate()->factory()->empty_string(),
6757 Runtime::FunctionForId(Runtime::kThrow), 1);
6758 Add<HSimulate>(expr->id());
6760 // If the throw definitely exits the function, we can finish with a dummy
6761 // control flow at this point. This is not the case if the throw is inside
6762 // an inlined function which may be replaced.
6763 if (call_context() == NULL) {
6764 FinishExitCurrentBlock(New<HAbnormalExit>());
6769 HInstruction* HGraphBuilder::AddLoadStringInstanceType(HValue* string) {
6770 if (string->IsConstant()) {
6771 HConstant* c_string = HConstant::cast(string);
6772 if (c_string->HasStringValue()) {
6773 return Add<HConstant>(c_string->StringValue()->map()->instance_type());
6776 return Add<HLoadNamedField>(
6777 Add<HLoadNamedField>(string, static_cast<HValue*>(NULL),
6778 HObjectAccess::ForMap()),
6779 static_cast<HValue*>(NULL), HObjectAccess::ForMapInstanceType());
6783 HInstruction* HGraphBuilder::AddLoadStringLength(HValue* string) {
6784 if (string->IsConstant()) {
6785 HConstant* c_string = HConstant::cast(string);
6786 if (c_string->HasStringValue()) {
6787 return Add<HConstant>(c_string->StringValue()->length());
6790 return Add<HLoadNamedField>(string, static_cast<HValue*>(NULL),
6791 HObjectAccess::ForStringLength());
6795 HInstruction* HOptimizedGraphBuilder::BuildNamedGeneric(
6796 PropertyAccessType access_type,
6799 Handle<String> name,
6801 bool is_uninitialized) {
6802 if (is_uninitialized) {
6803 Add<HDeoptimize>("Insufficient type feedback for generic named access",
6806 if (access_type == LOAD) {
6807 HLoadNamedGeneric* result = New<HLoadNamedGeneric>(object, name);
6808 if (FLAG_vector_ics) {
6809 Handle<SharedFunctionInfo> current_shared =
6810 function_state()->compilation_info()->shared_info();
6811 result->SetVectorAndSlot(
6812 handle(current_shared->feedback_vector(), isolate()),
6813 expr->AsProperty()->PropertyFeedbackSlot());
6817 return New<HStoreNamedGeneric>(object, name, value, function_strict_mode());
6823 HInstruction* HOptimizedGraphBuilder::BuildKeyedGeneric(
6824 PropertyAccessType access_type,
6829 if (access_type == LOAD) {
6830 HLoadKeyedGeneric* result = New<HLoadKeyedGeneric>(object, key);
6831 if (FLAG_vector_ics) {
6832 Handle<SharedFunctionInfo> current_shared =
6833 function_state()->compilation_info()->shared_info();
6834 result->SetVectorAndSlot(
6835 handle(current_shared->feedback_vector(), isolate()),
6836 expr->AsProperty()->PropertyFeedbackSlot());
6840 return New<HStoreKeyedGeneric>(object, key, value, function_strict_mode());
6845 LoadKeyedHoleMode HOptimizedGraphBuilder::BuildKeyedHoleMode(Handle<Map> map) {
6846 // Loads from a "stock" fast holey double arrays can elide the hole check.
6847 LoadKeyedHoleMode load_mode = NEVER_RETURN_HOLE;
6848 if (*map == isolate()->get_initial_js_array_map(FAST_HOLEY_DOUBLE_ELEMENTS) &&
6849 isolate()->IsFastArrayConstructorPrototypeChainIntact()) {
6850 Handle<JSObject> prototype(JSObject::cast(map->prototype()), isolate());
6851 Handle<JSObject> object_prototype = isolate()->initial_object_prototype();
6852 BuildCheckPrototypeMaps(prototype, object_prototype);
6853 load_mode = ALLOW_RETURN_HOLE;
6854 graph()->MarkDependsOnEmptyArrayProtoElements();
6861 HInstruction* HOptimizedGraphBuilder::BuildMonomorphicElementAccess(
6867 PropertyAccessType access_type,
6868 KeyedAccessStoreMode store_mode) {
6869 HCheckMaps* checked_object = Add<HCheckMaps>(object, map, dependency);
6871 checked_object->ClearDependsOnFlag(kElementsKind);
6874 if (access_type == STORE && map->prototype()->IsJSObject()) {
6875 // monomorphic stores need a prototype chain check because shape
6876 // changes could allow callbacks on elements in the chain that
6877 // aren't compatible with monomorphic keyed stores.
6878 PrototypeIterator iter(map);
6879 JSObject* holder = NULL;
6880 while (!iter.IsAtEnd()) {
6881 holder = JSObject::cast(*PrototypeIterator::GetCurrent(iter));
6884 DCHECK(holder && holder->IsJSObject());
6886 BuildCheckPrototypeMaps(handle(JSObject::cast(map->prototype())),
6887 Handle<JSObject>(holder));
6890 LoadKeyedHoleMode load_mode = BuildKeyedHoleMode(map);
6891 return BuildUncheckedMonomorphicElementAccess(
6892 checked_object, key, val,
6893 map->instance_type() == JS_ARRAY_TYPE,
6894 map->elements_kind(), access_type,
6895 load_mode, store_mode);
6899 HInstruction* HOptimizedGraphBuilder::TryBuildConsolidatedElementLoad(
6903 SmallMapList* maps) {
6904 // For polymorphic loads of similar elements kinds (i.e. all tagged or all
6905 // double), always use the "worst case" code without a transition. This is
6906 // much faster than transitioning the elements to the worst case, trading a
6907 // HTransitionElements for a HCheckMaps, and avoiding mutation of the array.
6908 bool has_double_maps = false;
6909 bool has_smi_or_object_maps = false;
6910 bool has_js_array_access = false;
6911 bool has_non_js_array_access = false;
6912 bool has_seen_holey_elements = false;
6913 Handle<Map> most_general_consolidated_map;
6914 for (int i = 0; i < maps->length(); ++i) {
6915 Handle<Map> map = maps->at(i);
6916 if (!map->IsJSObjectMap()) return NULL;
6917 // Don't allow mixing of JSArrays with JSObjects.
6918 if (map->instance_type() == JS_ARRAY_TYPE) {
6919 if (has_non_js_array_access) return NULL;
6920 has_js_array_access = true;
6921 } else if (has_js_array_access) {
6924 has_non_js_array_access = true;
6926 // Don't allow mixed, incompatible elements kinds.
6927 if (map->has_fast_double_elements()) {
6928 if (has_smi_or_object_maps) return NULL;
6929 has_double_maps = true;
6930 } else if (map->has_fast_smi_or_object_elements()) {
6931 if (has_double_maps) return NULL;
6932 has_smi_or_object_maps = true;
6936 // Remember if we've ever seen holey elements.
6937 if (IsHoleyElementsKind(map->elements_kind())) {
6938 has_seen_holey_elements = true;
6940 // Remember the most general elements kind, the code for its load will
6941 // properly handle all of the more specific cases.
6942 if ((i == 0) || IsMoreGeneralElementsKindTransition(
6943 most_general_consolidated_map->elements_kind(),
6944 map->elements_kind())) {
6945 most_general_consolidated_map = map;
6948 if (!has_double_maps && !has_smi_or_object_maps) return NULL;
6950 HCheckMaps* checked_object = Add<HCheckMaps>(object, maps);
6951 // FAST_ELEMENTS is considered more general than FAST_HOLEY_SMI_ELEMENTS.
6952 // If we've seen both, the consolidated load must use FAST_HOLEY_ELEMENTS.
6953 ElementsKind consolidated_elements_kind = has_seen_holey_elements
6954 ? GetHoleyElementsKind(most_general_consolidated_map->elements_kind())
6955 : most_general_consolidated_map->elements_kind();
6956 HInstruction* instr = BuildUncheckedMonomorphicElementAccess(
6957 checked_object, key, val,
6958 most_general_consolidated_map->instance_type() == JS_ARRAY_TYPE,
6959 consolidated_elements_kind,
6960 LOAD, NEVER_RETURN_HOLE, STANDARD_STORE);
6965 HValue* HOptimizedGraphBuilder::HandlePolymorphicElementAccess(
6971 PropertyAccessType access_type,
6972 KeyedAccessStoreMode store_mode,
6973 bool* has_side_effects) {
6974 *has_side_effects = false;
6975 BuildCheckHeapObject(object);
6977 if (access_type == LOAD) {
6978 HInstruction* consolidated_load =
6979 TryBuildConsolidatedElementLoad(object, key, val, maps);
6980 if (consolidated_load != NULL) {
6981 *has_side_effects |= consolidated_load->HasObservableSideEffects();
6982 return consolidated_load;
6986 // Elements_kind transition support.
6987 MapHandleList transition_target(maps->length());
6988 // Collect possible transition targets.
6989 MapHandleList possible_transitioned_maps(maps->length());
6990 for (int i = 0; i < maps->length(); ++i) {
6991 Handle<Map> map = maps->at(i);
6992 ElementsKind elements_kind = map->elements_kind();
6993 if (IsFastElementsKind(elements_kind) &&
6994 elements_kind != GetInitialFastElementsKind()) {
6995 possible_transitioned_maps.Add(map);
6997 if (elements_kind == SLOPPY_ARGUMENTS_ELEMENTS) {
6998 HInstruction* result = BuildKeyedGeneric(access_type, expr, object, key,
7000 *has_side_effects = result->HasObservableSideEffects();
7001 return AddInstruction(result);
7004 // Get transition target for each map (NULL == no transition).
7005 for (int i = 0; i < maps->length(); ++i) {
7006 Handle<Map> map = maps->at(i);
7007 Handle<Map> transitioned_map =
7008 map->FindTransitionedMap(&possible_transitioned_maps);
7009 transition_target.Add(transitioned_map);
7012 MapHandleList untransitionable_maps(maps->length());
7013 HTransitionElementsKind* transition = NULL;
7014 for (int i = 0; i < maps->length(); ++i) {
7015 Handle<Map> map = maps->at(i);
7016 DCHECK(map->IsMap());
7017 if (!transition_target.at(i).is_null()) {
7018 DCHECK(Map::IsValidElementsTransition(
7019 map->elements_kind(),
7020 transition_target.at(i)->elements_kind()));
7021 transition = Add<HTransitionElementsKind>(object, map,
7022 transition_target.at(i));
7024 untransitionable_maps.Add(map);
7028 // If only one map is left after transitioning, handle this case
7030 DCHECK(untransitionable_maps.length() >= 1);
7031 if (untransitionable_maps.length() == 1) {
7032 Handle<Map> untransitionable_map = untransitionable_maps[0];
7033 HInstruction* instr = NULL;
7034 if (untransitionable_map->has_slow_elements_kind() ||
7035 !untransitionable_map->IsJSObjectMap()) {
7036 instr = AddInstruction(BuildKeyedGeneric(access_type, expr, object, key,
7039 instr = BuildMonomorphicElementAccess(
7040 object, key, val, transition, untransitionable_map, access_type,
7043 *has_side_effects |= instr->HasObservableSideEffects();
7044 return access_type == STORE ? NULL : instr;
7047 HBasicBlock* join = graph()->CreateBasicBlock();
7049 for (int i = 0; i < untransitionable_maps.length(); ++i) {
7050 Handle<Map> map = untransitionable_maps[i];
7051 if (!map->IsJSObjectMap()) continue;
7052 ElementsKind elements_kind = map->elements_kind();
7053 HBasicBlock* this_map = graph()->CreateBasicBlock();
7054 HBasicBlock* other_map = graph()->CreateBasicBlock();
7055 HCompareMap* mapcompare =
7056 New<HCompareMap>(object, map, this_map, other_map);
7057 FinishCurrentBlock(mapcompare);
7059 set_current_block(this_map);
7060 HInstruction* access = NULL;
7061 if (IsDictionaryElementsKind(elements_kind)) {
7062 access = AddInstruction(BuildKeyedGeneric(access_type, expr, object, key,
7065 DCHECK(IsFastElementsKind(elements_kind) ||
7066 IsExternalArrayElementsKind(elements_kind) ||
7067 IsFixedTypedArrayElementsKind(elements_kind));
7068 LoadKeyedHoleMode load_mode = BuildKeyedHoleMode(map);
7069 // Happily, mapcompare is a checked object.
7070 access = BuildUncheckedMonomorphicElementAccess(
7071 mapcompare, key, val,
7072 map->instance_type() == JS_ARRAY_TYPE,
7073 elements_kind, access_type,
7077 *has_side_effects |= access->HasObservableSideEffects();
7078 // The caller will use has_side_effects and add a correct Simulate.
7079 access->SetFlag(HValue::kHasNoObservableSideEffects);
7080 if (access_type == LOAD) {
7083 NoObservableSideEffectsScope scope(this);
7084 GotoNoSimulate(join);
7085 set_current_block(other_map);
7088 // Ensure that we visited at least one map above that goes to join. This is
7089 // necessary because FinishExitWithHardDeoptimization does an AbnormalExit
7090 // rather than joining the join block. If this becomes an issue, insert a
7091 // generic access in the case length() == 0.
7092 DCHECK(join->predecessors()->length() > 0);
7093 // Deopt if none of the cases matched.
7094 NoObservableSideEffectsScope scope(this);
7095 FinishExitWithHardDeoptimization("Unknown map in polymorphic element access");
7096 set_current_block(join);
7097 return access_type == STORE ? NULL : Pop();
7101 HValue* HOptimizedGraphBuilder::HandleKeyedElementAccess(
7106 PropertyAccessType access_type,
7107 bool* has_side_effects) {
7108 DCHECK(!expr->IsPropertyName());
7109 HInstruction* instr = NULL;
7111 SmallMapList* types;
7112 bool monomorphic = ComputeReceiverTypes(expr, obj, &types, zone());
7114 bool force_generic = false;
7115 if (access_type == STORE &&
7116 (monomorphic || (types != NULL && !types->is_empty()))) {
7117 // Stores can't be mono/polymorphic if their prototype chain has dictionary
7118 // elements. However a receiver map that has dictionary elements itself
7119 // should be left to normal mono/poly behavior (the other maps may benefit
7120 // from highly optimized stores).
7121 for (int i = 0; i < types->length(); i++) {
7122 Handle<Map> current_map = types->at(i);
7123 if (current_map->DictionaryElementsInPrototypeChainOnly()) {
7124 force_generic = true;
7125 monomorphic = false;
7132 Handle<Map> map = types->first();
7133 if (map->has_slow_elements_kind() || !map->IsJSObjectMap()) {
7134 instr = AddInstruction(BuildKeyedGeneric(access_type, expr, obj, key,
7137 BuildCheckHeapObject(obj);
7138 instr = BuildMonomorphicElementAccess(
7139 obj, key, val, NULL, map, access_type, expr->GetStoreMode());
7141 } else if (!force_generic && (types != NULL && !types->is_empty())) {
7142 return HandlePolymorphicElementAccess(
7143 expr, obj, key, val, types, access_type,
7144 expr->GetStoreMode(), has_side_effects);
7146 if (access_type == STORE) {
7147 if (expr->IsAssignment() &&
7148 expr->AsAssignment()->HasNoTypeInformation()) {
7149 Add<HDeoptimize>("Insufficient type feedback for keyed store",
7153 if (expr->AsProperty()->HasNoTypeInformation()) {
7154 Add<HDeoptimize>("Insufficient type feedback for keyed load",
7158 instr = AddInstruction(BuildKeyedGeneric(access_type, expr, obj, key, val));
7160 *has_side_effects = instr->HasObservableSideEffects();
7165 void HOptimizedGraphBuilder::EnsureArgumentsArePushedForAccess() {
7166 // Outermost function already has arguments on the stack.
7167 if (function_state()->outer() == NULL) return;
7169 if (function_state()->arguments_pushed()) return;
7171 // Push arguments when entering inlined function.
7172 HEnterInlined* entry = function_state()->entry();
7173 entry->set_arguments_pushed();
7175 HArgumentsObject* arguments = entry->arguments_object();
7176 const ZoneList<HValue*>* arguments_values = arguments->arguments_values();
7178 HInstruction* insert_after = entry;
7179 for (int i = 0; i < arguments_values->length(); i++) {
7180 HValue* argument = arguments_values->at(i);
7181 HInstruction* push_argument = New<HPushArguments>(argument);
7182 push_argument->InsertAfter(insert_after);
7183 insert_after = push_argument;
7186 HArgumentsElements* arguments_elements = New<HArgumentsElements>(true);
7187 arguments_elements->ClearFlag(HValue::kUseGVN);
7188 arguments_elements->InsertAfter(insert_after);
7189 function_state()->set_arguments_elements(arguments_elements);
7193 bool HOptimizedGraphBuilder::TryArgumentsAccess(Property* expr) {
7194 VariableProxy* proxy = expr->obj()->AsVariableProxy();
7195 if (proxy == NULL) return false;
7196 if (!proxy->var()->IsStackAllocated()) return false;
7197 if (!environment()->Lookup(proxy->var())->CheckFlag(HValue::kIsArguments)) {
7201 HInstruction* result = NULL;
7202 if (expr->key()->IsPropertyName()) {
7203 Handle<String> name = expr->key()->AsLiteral()->AsPropertyName();
7204 if (!name->IsOneByteEqualTo(STATIC_ASCII_VECTOR("length"))) return false;
7206 if (function_state()->outer() == NULL) {
7207 HInstruction* elements = Add<HArgumentsElements>(false);
7208 result = New<HArgumentsLength>(elements);
7210 // Number of arguments without receiver.
7211 int argument_count = environment()->
7212 arguments_environment()->parameter_count() - 1;
7213 result = New<HConstant>(argument_count);
7216 Push(graph()->GetArgumentsObject());
7217 CHECK_ALIVE_OR_RETURN(VisitForValue(expr->key()), true);
7218 HValue* key = Pop();
7219 Drop(1); // Arguments object.
7220 if (function_state()->outer() == NULL) {
7221 HInstruction* elements = Add<HArgumentsElements>(false);
7222 HInstruction* length = Add<HArgumentsLength>(elements);
7223 HInstruction* checked_key = Add<HBoundsCheck>(key, length);
7224 result = New<HAccessArgumentsAt>(elements, length, checked_key);
7226 EnsureArgumentsArePushedForAccess();
7228 // Number of arguments without receiver.
7229 HInstruction* elements = function_state()->arguments_elements();
7230 int argument_count = environment()->
7231 arguments_environment()->parameter_count() - 1;
7232 HInstruction* length = Add<HConstant>(argument_count);
7233 HInstruction* checked_key = Add<HBoundsCheck>(key, length);
7234 result = New<HAccessArgumentsAt>(elements, length, checked_key);
7237 ast_context()->ReturnInstruction(result, expr->id());
7242 HInstruction* HOptimizedGraphBuilder::BuildNamedAccess(
7243 PropertyAccessType access,
7245 BailoutId return_id,
7248 Handle<String> name,
7250 bool is_uninitialized) {
7251 SmallMapList* types;
7252 ComputeReceiverTypes(expr, object, &types, zone());
7253 DCHECK(types != NULL);
7255 if (types->length() > 0) {
7256 PropertyAccessInfo info(this, access, ToType(types->first()), name);
7257 if (!info.CanAccessAsMonomorphic(types)) {
7258 HandlePolymorphicNamedFieldAccess(
7259 access, expr, ast_id, return_id, object, value, types, name);
7263 HValue* checked_object;
7264 // Type::Number() is only supported by polymorphic load/call handling.
7265 DCHECK(!info.type()->Is(Type::Number()));
7266 BuildCheckHeapObject(object);
7267 if (AreStringTypes(types)) {
7269 Add<HCheckInstanceType>(object, HCheckInstanceType::IS_STRING);
7271 checked_object = Add<HCheckMaps>(object, types);
7273 return BuildMonomorphicAccess(
7274 &info, object, checked_object, value, ast_id, return_id);
7277 return BuildNamedGeneric(access, expr, object, name, value, is_uninitialized);
7281 void HOptimizedGraphBuilder::PushLoad(Property* expr,
7284 ValueContext for_value(this, ARGUMENTS_NOT_ALLOWED);
7286 if (key != NULL) Push(key);
7287 BuildLoad(expr, expr->LoadId());
7291 void HOptimizedGraphBuilder::BuildLoad(Property* expr,
7293 HInstruction* instr = NULL;
7294 if (expr->IsStringAccess()) {
7295 HValue* index = Pop();
7296 HValue* string = Pop();
7297 HInstruction* char_code = BuildStringCharCodeAt(string, index);
7298 AddInstruction(char_code);
7299 instr = NewUncasted<HStringCharFromCode>(char_code);
7301 } else if (expr->key()->IsPropertyName()) {
7302 Handle<String> name = expr->key()->AsLiteral()->AsPropertyName();
7303 HValue* object = Pop();
7305 instr = BuildNamedAccess(LOAD, ast_id, expr->LoadId(), expr,
7306 object, name, NULL, expr->IsUninitialized());
7307 if (instr == NULL) return;
7308 if (instr->IsLinked()) return ast_context()->ReturnValue(instr);
7311 HValue* key = Pop();
7312 HValue* obj = Pop();
7314 bool has_side_effects = false;
7315 HValue* load = HandleKeyedElementAccess(
7316 obj, key, NULL, expr, LOAD, &has_side_effects);
7317 if (has_side_effects) {
7318 if (ast_context()->IsEffect()) {
7319 Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
7322 Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
7326 return ast_context()->ReturnValue(load);
7328 return ast_context()->ReturnInstruction(instr, ast_id);
7332 void HOptimizedGraphBuilder::VisitProperty(Property* expr) {
7333 DCHECK(!HasStackOverflow());
7334 DCHECK(current_block() != NULL);
7335 DCHECK(current_block()->HasPredecessor());
7337 if (TryArgumentsAccess(expr)) return;
7339 CHECK_ALIVE(VisitForValue(expr->obj()));
7340 if (!expr->key()->IsPropertyName() || expr->IsStringAccess()) {
7341 CHECK_ALIVE(VisitForValue(expr->key()));
7344 BuildLoad(expr, expr->id());
7348 HInstruction* HGraphBuilder::BuildConstantMapCheck(Handle<JSObject> constant) {
7349 HCheckMaps* check = Add<HCheckMaps>(
7350 Add<HConstant>(constant), handle(constant->map()));
7351 check->ClearDependsOnFlag(kElementsKind);
7356 HInstruction* HGraphBuilder::BuildCheckPrototypeMaps(Handle<JSObject> prototype,
7357 Handle<JSObject> holder) {
7358 PrototypeIterator iter(isolate(), prototype,
7359 PrototypeIterator::START_AT_RECEIVER);
7360 while (holder.is_null() ||
7361 !PrototypeIterator::GetCurrent(iter).is_identical_to(holder)) {
7362 BuildConstantMapCheck(
7363 Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter)));
7365 if (iter.IsAtEnd()) {
7369 return BuildConstantMapCheck(
7370 Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter)));
7374 void HOptimizedGraphBuilder::AddCheckPrototypeMaps(Handle<JSObject> holder,
7375 Handle<Map> receiver_map) {
7376 if (!holder.is_null()) {
7377 Handle<JSObject> prototype(JSObject::cast(receiver_map->prototype()));
7378 BuildCheckPrototypeMaps(prototype, holder);
7383 HInstruction* HOptimizedGraphBuilder::NewPlainFunctionCall(
7384 HValue* fun, int argument_count, bool pass_argument_count) {
7385 return New<HCallJSFunction>(
7386 fun, argument_count, pass_argument_count);
7390 HInstruction* HOptimizedGraphBuilder::NewArgumentAdaptorCall(
7391 HValue* fun, HValue* context,
7392 int argument_count, HValue* expected_param_count) {
7393 CallInterfaceDescriptor* descriptor =
7394 isolate()->call_descriptor(Isolate::ArgumentAdaptorCall);
7396 HValue* arity = Add<HConstant>(argument_count - 1);
7398 HValue* op_vals[] = { context, fun, arity, expected_param_count };
7400 Handle<Code> adaptor =
7401 isolate()->builtins()->ArgumentsAdaptorTrampoline();
7402 HConstant* adaptor_value = Add<HConstant>(adaptor);
7404 return New<HCallWithDescriptor>(
7405 adaptor_value, argument_count, descriptor,
7406 Vector<HValue*>(op_vals, descriptor->GetEnvironmentLength()));
7410 HInstruction* HOptimizedGraphBuilder::BuildCallConstantFunction(
7411 Handle<JSFunction> jsfun, int argument_count) {
7412 HValue* target = Add<HConstant>(jsfun);
7413 // For constant functions, we try to avoid calling the
7414 // argument adaptor and instead call the function directly
7415 int formal_parameter_count = jsfun->shared()->formal_parameter_count();
7416 bool dont_adapt_arguments =
7417 (formal_parameter_count ==
7418 SharedFunctionInfo::kDontAdaptArgumentsSentinel);
7419 int arity = argument_count - 1;
7420 bool can_invoke_directly =
7421 dont_adapt_arguments || formal_parameter_count == arity;
7422 if (can_invoke_directly) {
7423 if (jsfun.is_identical_to(current_info()->closure())) {
7424 graph()->MarkRecursive();
7426 return NewPlainFunctionCall(target, argument_count, dont_adapt_arguments);
7428 HValue* param_count_value = Add<HConstant>(formal_parameter_count);
7429 HValue* context = Add<HLoadNamedField>(
7430 target, static_cast<HValue*>(NULL),
7431 HObjectAccess::ForFunctionContextPointer());
7432 return NewArgumentAdaptorCall(target, context,
7433 argument_count, param_count_value);
7440 class FunctionSorter {
7442 explicit FunctionSorter(int index = 0, int ticks = 0, int size = 0)
7443 : index_(index), ticks_(ticks), size_(size) {}
7445 int index() const { return index_; }
7446 int ticks() const { return ticks_; }
7447 int size() const { return size_; }
7456 inline bool operator<(const FunctionSorter& lhs, const FunctionSorter& rhs) {
7457 int diff = lhs.ticks() - rhs.ticks();
7458 if (diff != 0) return diff > 0;
7459 return lhs.size() < rhs.size();
7463 void HOptimizedGraphBuilder::HandlePolymorphicCallNamed(
7466 SmallMapList* types,
7467 Handle<String> name) {
7468 int argument_count = expr->arguments()->length() + 1; // Includes receiver.
7469 FunctionSorter order[kMaxCallPolymorphism];
7471 bool handle_smi = false;
7472 bool handled_string = false;
7473 int ordered_functions = 0;
7476 i < types->length() && ordered_functions < kMaxCallPolymorphism;
7478 PropertyAccessInfo info(this, LOAD, ToType(types->at(i)), name);
7479 if (info.CanAccessMonomorphic() &&
7480 info.lookup()->IsConstant() &&
7481 info.constant()->IsJSFunction()) {
7482 if (info.type()->Is(Type::String())) {
7483 if (handled_string) continue;
7484 handled_string = true;
7486 Handle<JSFunction> target = Handle<JSFunction>::cast(info.constant());
7487 if (info.type()->Is(Type::Number())) {
7490 expr->set_target(target);
7491 order[ordered_functions++] = FunctionSorter(
7492 i, target->shared()->profiler_ticks(), InliningAstSize(target));
7496 std::sort(order, order + ordered_functions);
7498 HBasicBlock* number_block = NULL;
7499 HBasicBlock* join = NULL;
7500 handled_string = false;
7503 for (int fn = 0; fn < ordered_functions; ++fn) {
7504 int i = order[fn].index();
7505 PropertyAccessInfo info(this, LOAD, ToType(types->at(i)), name);
7506 if (info.type()->Is(Type::String())) {
7507 if (handled_string) continue;
7508 handled_string = true;
7510 // Reloads the target.
7511 info.CanAccessMonomorphic();
7512 Handle<JSFunction> target = Handle<JSFunction>::cast(info.constant());
7514 expr->set_target(target);
7516 // Only needed once.
7517 join = graph()->CreateBasicBlock();
7519 HBasicBlock* empty_smi_block = graph()->CreateBasicBlock();
7520 HBasicBlock* not_smi_block = graph()->CreateBasicBlock();
7521 number_block = graph()->CreateBasicBlock();
7522 FinishCurrentBlock(New<HIsSmiAndBranch>(
7523 receiver, empty_smi_block, not_smi_block));
7524 GotoNoSimulate(empty_smi_block, number_block);
7525 set_current_block(not_smi_block);
7527 BuildCheckHeapObject(receiver);
7531 HBasicBlock* if_true = graph()->CreateBasicBlock();
7532 HBasicBlock* if_false = graph()->CreateBasicBlock();
7533 HUnaryControlInstruction* compare;
7535 Handle<Map> map = info.map();
7536 if (info.type()->Is(Type::Number())) {
7537 Handle<Map> heap_number_map = isolate()->factory()->heap_number_map();
7538 compare = New<HCompareMap>(receiver, heap_number_map, if_true, if_false);
7539 } else if (info.type()->Is(Type::String())) {
7540 compare = New<HIsStringAndBranch>(receiver, if_true, if_false);
7542 compare = New<HCompareMap>(receiver, map, if_true, if_false);
7544 FinishCurrentBlock(compare);
7546 if (info.type()->Is(Type::Number())) {
7547 GotoNoSimulate(if_true, number_block);
7548 if_true = number_block;
7551 set_current_block(if_true);
7553 AddCheckPrototypeMaps(info.holder(), map);
7555 HValue* function = Add<HConstant>(expr->target());
7556 environment()->SetExpressionStackAt(0, function);
7558 CHECK_ALIVE(VisitExpressions(expr->arguments()));
7559 bool needs_wrapping = NeedsWrappingFor(info.type(), target);
7560 bool try_inline = FLAG_polymorphic_inlining && !needs_wrapping;
7561 if (FLAG_trace_inlining && try_inline) {
7562 Handle<JSFunction> caller = current_info()->closure();
7563 SmartArrayPointer<char> caller_name =
7564 caller->shared()->DebugName()->ToCString();
7565 PrintF("Trying to inline the polymorphic call to %s from %s\n",
7566 name->ToCString().get(),
7569 if (try_inline && TryInlineCall(expr)) {
7570 // Trying to inline will signal that we should bailout from the
7571 // entire compilation by setting stack overflow on the visitor.
7572 if (HasStackOverflow()) return;
7574 // Since HWrapReceiver currently cannot actually wrap numbers and strings,
7575 // use the regular CallFunctionStub for method calls to wrap the receiver.
7576 // TODO(verwaest): Support creation of value wrappers directly in
7578 HInstruction* call = needs_wrapping
7579 ? NewUncasted<HCallFunction>(
7580 function, argument_count, WRAP_AND_CALL)
7581 : BuildCallConstantFunction(target, argument_count);
7582 PushArgumentsFromEnvironment(argument_count);
7583 AddInstruction(call);
7584 Drop(1); // Drop the function.
7585 if (!ast_context()->IsEffect()) Push(call);
7588 if (current_block() != NULL) Goto(join);
7589 set_current_block(if_false);
7592 // Finish up. Unconditionally deoptimize if we've handled all the maps we
7593 // know about and do not want to handle ones we've never seen. Otherwise
7594 // use a generic IC.
7595 if (ordered_functions == types->length() && FLAG_deoptimize_uncommon_cases) {
7596 FinishExitWithHardDeoptimization("Unknown map in polymorphic call");
7598 Property* prop = expr->expression()->AsProperty();
7599 HInstruction* function = BuildNamedGeneric(
7600 LOAD, prop, receiver, name, NULL, prop->IsUninitialized());
7601 AddInstruction(function);
7603 AddSimulate(prop->LoadId(), REMOVABLE_SIMULATE);
7605 environment()->SetExpressionStackAt(1, function);
7606 environment()->SetExpressionStackAt(0, receiver);
7607 CHECK_ALIVE(VisitExpressions(expr->arguments()));
7609 CallFunctionFlags flags = receiver->type().IsJSObject()
7610 ? NO_CALL_FUNCTION_FLAGS : CALL_AS_METHOD;
7611 HInstruction* call = New<HCallFunction>(
7612 function, argument_count, flags);
7614 PushArgumentsFromEnvironment(argument_count);
7616 Drop(1); // Function.
7619 AddInstruction(call);
7620 if (!ast_context()->IsEffect()) Push(call);
7623 return ast_context()->ReturnInstruction(call, expr->id());
7627 // We assume that control flow is always live after an expression. So
7628 // even without predecessors to the join block, we set it as the exit
7629 // block and continue by adding instructions there.
7630 DCHECK(join != NULL);
7631 if (join->HasPredecessor()) {
7632 set_current_block(join);
7633 join->SetJoinId(expr->id());
7634 if (!ast_context()->IsEffect()) return ast_context()->ReturnValue(Pop());
7636 set_current_block(NULL);
7641 void HOptimizedGraphBuilder::TraceInline(Handle<JSFunction> target,
7642 Handle<JSFunction> caller,
7643 const char* reason) {
7644 if (FLAG_trace_inlining) {
7645 SmartArrayPointer<char> target_name =
7646 target->shared()->DebugName()->ToCString();
7647 SmartArrayPointer<char> caller_name =
7648 caller->shared()->DebugName()->ToCString();
7649 if (reason == NULL) {
7650 PrintF("Inlined %s called from %s.\n", target_name.get(),
7653 PrintF("Did not inline %s called from %s (%s).\n",
7654 target_name.get(), caller_name.get(), reason);
7660 static const int kNotInlinable = 1000000000;
7663 int HOptimizedGraphBuilder::InliningAstSize(Handle<JSFunction> target) {
7664 if (!FLAG_use_inlining) return kNotInlinable;
7666 // Precondition: call is monomorphic and we have found a target with the
7667 // appropriate arity.
7668 Handle<JSFunction> caller = current_info()->closure();
7669 Handle<SharedFunctionInfo> target_shared(target->shared());
7671 // Always inline builtins marked for inlining.
7672 if (target->IsBuiltin()) {
7673 return target_shared->inline_builtin() ? 0 : kNotInlinable;
7676 if (target_shared->IsApiFunction()) {
7677 TraceInline(target, caller, "target is api function");
7678 return kNotInlinable;
7681 // Do a quick check on source code length to avoid parsing large
7682 // inlining candidates.
7683 if (target_shared->SourceSize() >
7684 Min(FLAG_max_inlined_source_size, kUnlimitedMaxInlinedSourceSize)) {
7685 TraceInline(target, caller, "target text too big");
7686 return kNotInlinable;
7689 // Target must be inlineable.
7690 if (!target_shared->IsInlineable()) {
7691 TraceInline(target, caller, "target not inlineable");
7692 return kNotInlinable;
7694 if (target_shared->DisableOptimizationReason() != kNoReason) {
7695 TraceInline(target, caller, "target contains unsupported syntax [early]");
7696 return kNotInlinable;
7699 int nodes_added = target_shared->ast_node_count();
7704 bool HOptimizedGraphBuilder::TryInline(Handle<JSFunction> target,
7705 int arguments_count,
7706 HValue* implicit_return_value,
7708 BailoutId return_id,
7709 InliningKind inlining_kind,
7710 HSourcePosition position) {
7711 int nodes_added = InliningAstSize(target);
7712 if (nodes_added == kNotInlinable) return false;
7714 Handle<JSFunction> caller = current_info()->closure();
7716 if (nodes_added > Min(FLAG_max_inlined_nodes, kUnlimitedMaxInlinedNodes)) {
7717 TraceInline(target, caller, "target AST is too large [early]");
7721 // Don't inline deeper than the maximum number of inlining levels.
7722 HEnvironment* env = environment();
7723 int current_level = 1;
7724 while (env->outer() != NULL) {
7725 if (current_level == FLAG_max_inlining_levels) {
7726 TraceInline(target, caller, "inline depth limit reached");
7729 if (env->outer()->frame_type() == JS_FUNCTION) {
7735 // Don't inline recursive functions.
7736 for (FunctionState* state = function_state();
7738 state = state->outer()) {
7739 if (*state->compilation_info()->closure() == *target) {
7740 TraceInline(target, caller, "target is recursive");
7745 // We don't want to add more than a certain number of nodes from inlining.
7746 if (inlined_count_ > Min(FLAG_max_inlined_nodes_cumulative,
7747 kUnlimitedMaxInlinedNodesCumulative)) {
7748 TraceInline(target, caller, "cumulative AST node limit reached");
7752 // Parse and allocate variables.
7753 CompilationInfo target_info(target, zone());
7754 // Use the same AstValueFactory for creating strings in the sub-compilation
7755 // step, but don't transfer ownership to target_info.
7756 target_info.SetAstValueFactory(top_info()->ast_value_factory(), false);
7757 Handle<SharedFunctionInfo> target_shared(target->shared());
7758 if (!Parser::Parse(&target_info) || !Scope::Analyze(&target_info)) {
7759 if (target_info.isolate()->has_pending_exception()) {
7760 // Parse or scope error, never optimize this function.
7762 target_shared->DisableOptimization(kParseScopeError);
7764 TraceInline(target, caller, "parse failure");
7768 if (target_info.scope()->num_heap_slots() > 0) {
7769 TraceInline(target, caller, "target has context-allocated variables");
7772 FunctionLiteral* function = target_info.function();
7774 // The following conditions must be checked again after re-parsing, because
7775 // earlier the information might not have been complete due to lazy parsing.
7776 nodes_added = function->ast_node_count();
7777 if (nodes_added > Min(FLAG_max_inlined_nodes, kUnlimitedMaxInlinedNodes)) {
7778 TraceInline(target, caller, "target AST is too large [late]");
7781 if (function->dont_optimize()) {
7782 TraceInline(target, caller, "target contains unsupported syntax [late]");
7786 // If the function uses the arguments object check that inlining of functions
7787 // with arguments object is enabled and the arguments-variable is
7789 if (function->scope()->arguments() != NULL) {
7790 if (!FLAG_inline_arguments) {
7791 TraceInline(target, caller, "target uses arguments object");
7795 if (!function->scope()->arguments()->IsStackAllocated()) {
7798 "target uses non-stackallocated arguments object");
7803 // All declarations must be inlineable.
7804 ZoneList<Declaration*>* decls = target_info.scope()->declarations();
7805 int decl_count = decls->length();
7806 for (int i = 0; i < decl_count; ++i) {
7807 if (!decls->at(i)->IsInlineable()) {
7808 TraceInline(target, caller, "target has non-trivial declaration");
7813 // Generate the deoptimization data for the unoptimized version of
7814 // the target function if we don't already have it.
7815 if (!target_shared->has_deoptimization_support()) {
7816 // Note that we compile here using the same AST that we will use for
7817 // generating the optimized inline code.
7818 target_info.EnableDeoptimizationSupport();
7819 if (!FullCodeGenerator::MakeCode(&target_info)) {
7820 TraceInline(target, caller, "could not generate deoptimization info");
7823 if (target_shared->scope_info() == ScopeInfo::Empty(isolate())) {
7824 // The scope info might not have been set if a lazily compiled
7825 // function is inlined before being called for the first time.
7826 Handle<ScopeInfo> target_scope_info =
7827 ScopeInfo::Create(target_info.scope(), zone());
7828 target_shared->set_scope_info(*target_scope_info);
7830 target_shared->EnableDeoptimizationSupport(*target_info.code());
7831 target_shared->set_feedback_vector(*target_info.feedback_vector());
7832 Compiler::RecordFunctionCompilation(Logger::FUNCTION_TAG,
7837 // ----------------------------------------------------------------
7838 // After this point, we've made a decision to inline this function (so
7839 // TryInline should always return true).
7841 // Type-check the inlined function.
7842 DCHECK(target_shared->has_deoptimization_support());
7843 AstTyper::Run(&target_info);
7845 int function_id = graph()->TraceInlinedFunction(target_shared, position);
7847 // Save the pending call context. Set up new one for the inlined function.
7848 // The function state is new-allocated because we need to delete it
7849 // in two different places.
7850 FunctionState* target_state = new FunctionState(
7851 this, &target_info, inlining_kind, function_id);
7853 HConstant* undefined = graph()->GetConstantUndefined();
7855 HEnvironment* inner_env =
7856 environment()->CopyForInlining(target,
7860 function_state()->inlining_kind());
7862 HConstant* context = Add<HConstant>(Handle<Context>(target->context()));
7863 inner_env->BindContext(context);
7865 // Create a dematerialized arguments object for the function, also copy the
7866 // current arguments values to use them for materialization.
7867 HEnvironment* arguments_env = inner_env->arguments_environment();
7868 int parameter_count = arguments_env->parameter_count();
7869 HArgumentsObject* arguments_object = Add<HArgumentsObject>(parameter_count);
7870 for (int i = 0; i < parameter_count; i++) {
7871 arguments_object->AddArgument(arguments_env->Lookup(i), zone());
7874 // If the function uses arguments object then bind bind one.
7875 if (function->scope()->arguments() != NULL) {
7876 DCHECK(function->scope()->arguments()->IsStackAllocated());
7877 inner_env->Bind(function->scope()->arguments(), arguments_object);
7880 // Capture the state before invoking the inlined function for deopt in the
7881 // inlined function. This simulate has no bailout-id since it's not directly
7882 // reachable for deopt, and is only used to capture the state. If the simulate
7883 // becomes reachable by merging, the ast id of the simulate merged into it is
7885 Add<HSimulate>(BailoutId::None());
7887 current_block()->UpdateEnvironment(inner_env);
7888 Scope* saved_scope = scope();
7889 set_scope(target_info.scope());
7890 HEnterInlined* enter_inlined =
7891 Add<HEnterInlined>(return_id, target, arguments_count, function,
7892 function_state()->inlining_kind(),
7893 function->scope()->arguments(),
7895 function_state()->set_entry(enter_inlined);
7897 VisitDeclarations(target_info.scope()->declarations());
7898 VisitStatements(function->body());
7899 set_scope(saved_scope);
7900 if (HasStackOverflow()) {
7901 // Bail out if the inline function did, as we cannot residualize a call
7903 TraceInline(target, caller, "inline graph construction failed");
7904 target_shared->DisableOptimization(kInliningBailedOut);
7905 inline_bailout_ = true;
7906 delete target_state;
7910 // Update inlined nodes count.
7911 inlined_count_ += nodes_added;
7913 Handle<Code> unoptimized_code(target_shared->code());
7914 DCHECK(unoptimized_code->kind() == Code::FUNCTION);
7915 Handle<TypeFeedbackInfo> type_info(
7916 TypeFeedbackInfo::cast(unoptimized_code->type_feedback_info()));
7917 graph()->update_type_change_checksum(type_info->own_type_change_checksum());
7919 TraceInline(target, caller, NULL);
7921 if (current_block() != NULL) {
7922 FunctionState* state = function_state();
7923 if (state->inlining_kind() == CONSTRUCT_CALL_RETURN) {
7924 // Falling off the end of an inlined construct call. In a test context the
7925 // return value will always evaluate to true, in a value context the
7926 // return value is the newly allocated receiver.
7927 if (call_context()->IsTest()) {
7928 Goto(inlined_test_context()->if_true(), state);
7929 } else if (call_context()->IsEffect()) {
7930 Goto(function_return(), state);
7932 DCHECK(call_context()->IsValue());
7933 AddLeaveInlined(implicit_return_value, state);
7935 } else if (state->inlining_kind() == SETTER_CALL_RETURN) {
7936 // Falling off the end of an inlined setter call. The returned value is
7937 // never used, the value of an assignment is always the value of the RHS
7938 // of the assignment.
7939 if (call_context()->IsTest()) {
7940 inlined_test_context()->ReturnValue(implicit_return_value);
7941 } else if (call_context()->IsEffect()) {
7942 Goto(function_return(), state);
7944 DCHECK(call_context()->IsValue());
7945 AddLeaveInlined(implicit_return_value, state);
7948 // Falling off the end of a normal inlined function. This basically means
7949 // returning undefined.
7950 if (call_context()->IsTest()) {
7951 Goto(inlined_test_context()->if_false(), state);
7952 } else if (call_context()->IsEffect()) {
7953 Goto(function_return(), state);
7955 DCHECK(call_context()->IsValue());
7956 AddLeaveInlined(undefined, state);
7961 // Fix up the function exits.
7962 if (inlined_test_context() != NULL) {
7963 HBasicBlock* if_true = inlined_test_context()->if_true();
7964 HBasicBlock* if_false = inlined_test_context()->if_false();
7966 HEnterInlined* entry = function_state()->entry();
7968 // Pop the return test context from the expression context stack.
7969 DCHECK(ast_context() == inlined_test_context());
7970 ClearInlinedTestContext();
7971 delete target_state;
7973 // Forward to the real test context.
7974 if (if_true->HasPredecessor()) {
7975 entry->RegisterReturnTarget(if_true, zone());
7976 if_true->SetJoinId(ast_id);
7977 HBasicBlock* true_target = TestContext::cast(ast_context())->if_true();
7978 Goto(if_true, true_target, function_state());
7980 if (if_false->HasPredecessor()) {
7981 entry->RegisterReturnTarget(if_false, zone());
7982 if_false->SetJoinId(ast_id);
7983 HBasicBlock* false_target = TestContext::cast(ast_context())->if_false();
7984 Goto(if_false, false_target, function_state());
7986 set_current_block(NULL);
7989 } else if (function_return()->HasPredecessor()) {
7990 function_state()->entry()->RegisterReturnTarget(function_return(), zone());
7991 function_return()->SetJoinId(ast_id);
7992 set_current_block(function_return());
7994 set_current_block(NULL);
7996 delete target_state;
8001 bool HOptimizedGraphBuilder::TryInlineCall(Call* expr) {
8002 return TryInline(expr->target(),
8003 expr->arguments()->length(),
8008 ScriptPositionToSourcePosition(expr->position()));
8012 bool HOptimizedGraphBuilder::TryInlineConstruct(CallNew* expr,
8013 HValue* implicit_return_value) {
8014 return TryInline(expr->target(),
8015 expr->arguments()->length(),
8016 implicit_return_value,
8019 CONSTRUCT_CALL_RETURN,
8020 ScriptPositionToSourcePosition(expr->position()));
8024 bool HOptimizedGraphBuilder::TryInlineGetter(Handle<JSFunction> getter,
8025 Handle<Map> receiver_map,
8027 BailoutId return_id) {
8028 if (TryInlineApiGetter(getter, receiver_map, ast_id)) return true;
8029 return TryInline(getter,
8039 bool HOptimizedGraphBuilder::TryInlineSetter(Handle<JSFunction> setter,
8040 Handle<Map> receiver_map,
8042 BailoutId assignment_id,
8043 HValue* implicit_return_value) {
8044 if (TryInlineApiSetter(setter, receiver_map, id)) return true;
8045 return TryInline(setter,
8047 implicit_return_value,
8054 bool HOptimizedGraphBuilder::TryInlineApply(Handle<JSFunction> function,
8056 int arguments_count) {
8057 return TryInline(function,
8063 ScriptPositionToSourcePosition(expr->position()));
8067 bool HOptimizedGraphBuilder::TryInlineBuiltinFunctionCall(Call* expr) {
8068 if (!expr->target()->shared()->HasBuiltinFunctionId()) return false;
8069 BuiltinFunctionId id = expr->target()->shared()->builtin_function_id();
8072 if (!FLAG_fast_math) break;
8073 // Fall through if FLAG_fast_math.
8081 if (expr->arguments()->length() == 1) {
8082 HValue* argument = Pop();
8083 Drop(2); // Receiver and function.
8084 HInstruction* op = NewUncasted<HUnaryMathOperation>(argument, id);
8085 ast_context()->ReturnInstruction(op, expr->id());
8090 if (expr->arguments()->length() == 2) {
8091 HValue* right = Pop();
8092 HValue* left = Pop();
8093 Drop(2); // Receiver and function.
8094 HInstruction* op = HMul::NewImul(zone(), context(), left, right);
8095 ast_context()->ReturnInstruction(op, expr->id());
8100 // Not supported for inlining yet.
8107 bool HOptimizedGraphBuilder::TryInlineBuiltinMethodCall(
8110 Handle<Map> receiver_map) {
8111 // Try to inline calls like Math.* as operations in the calling function.
8112 if (!expr->target()->shared()->HasBuiltinFunctionId()) return false;
8113 BuiltinFunctionId id = expr->target()->shared()->builtin_function_id();
8114 int argument_count = expr->arguments()->length() + 1; // Plus receiver.
8116 case kStringCharCodeAt:
8118 if (argument_count == 2) {
8119 HValue* index = Pop();
8120 HValue* string = Pop();
8121 Drop(1); // Function.
8122 HInstruction* char_code =
8123 BuildStringCharCodeAt(string, index);
8124 if (id == kStringCharCodeAt) {
8125 ast_context()->ReturnInstruction(char_code, expr->id());
8128 AddInstruction(char_code);
8129 HInstruction* result = NewUncasted<HStringCharFromCode>(char_code);
8130 ast_context()->ReturnInstruction(result, expr->id());
8134 case kStringFromCharCode:
8135 if (argument_count == 2) {
8136 HValue* argument = Pop();
8137 Drop(2); // Receiver and function.
8138 HInstruction* result = NewUncasted<HStringCharFromCode>(argument);
8139 ast_context()->ReturnInstruction(result, expr->id());
8144 if (!FLAG_fast_math) break;
8145 // Fall through if FLAG_fast_math.
8153 if (argument_count == 2) {
8154 HValue* argument = Pop();
8155 Drop(2); // Receiver and function.
8156 HInstruction* op = NewUncasted<HUnaryMathOperation>(argument, id);
8157 ast_context()->ReturnInstruction(op, expr->id());
8162 if (argument_count == 3) {
8163 HValue* right = Pop();
8164 HValue* left = Pop();
8165 Drop(2); // Receiver and function.
8166 HInstruction* result = NULL;
8167 // Use sqrt() if exponent is 0.5 or -0.5.
8168 if (right->IsConstant() && HConstant::cast(right)->HasDoubleValue()) {
8169 double exponent = HConstant::cast(right)->DoubleValue();
8170 if (exponent == 0.5) {
8171 result = NewUncasted<HUnaryMathOperation>(left, kMathPowHalf);
8172 } else if (exponent == -0.5) {
8173 HValue* one = graph()->GetConstant1();
8174 HInstruction* sqrt = AddUncasted<HUnaryMathOperation>(
8175 left, kMathPowHalf);
8176 // MathPowHalf doesn't have side effects so there's no need for
8177 // an environment simulation here.
8178 DCHECK(!sqrt->HasObservableSideEffects());
8179 result = NewUncasted<HDiv>(one, sqrt);
8180 } else if (exponent == 2.0) {
8181 result = NewUncasted<HMul>(left, left);
8185 if (result == NULL) {
8186 result = NewUncasted<HPower>(left, right);
8188 ast_context()->ReturnInstruction(result, expr->id());
8194 if (argument_count == 3) {
8195 HValue* right = Pop();
8196 HValue* left = Pop();
8197 Drop(2); // Receiver and function.
8198 HMathMinMax::Operation op = (id == kMathMin) ? HMathMinMax::kMathMin
8199 : HMathMinMax::kMathMax;
8200 HInstruction* result = NewUncasted<HMathMinMax>(left, right, op);
8201 ast_context()->ReturnInstruction(result, expr->id());
8206 if (argument_count == 3) {
8207 HValue* right = Pop();
8208 HValue* left = Pop();
8209 Drop(2); // Receiver and function.
8210 HInstruction* result = HMul::NewImul(zone(), context(), left, right);
8211 ast_context()->ReturnInstruction(result, expr->id());
8216 if (receiver_map.is_null()) return false;
8217 if (receiver_map->instance_type() != JS_ARRAY_TYPE) return false;
8218 ElementsKind elements_kind = receiver_map->elements_kind();
8219 if (!IsFastElementsKind(elements_kind)) return false;
8220 if (receiver_map->is_observed()) return false;
8221 DCHECK(receiver_map->is_extensible());
8223 Drop(expr->arguments()->length());
8225 HValue* reduced_length;
8226 HValue* receiver = Pop();
8228 HValue* checked_object = AddCheckMap(receiver, receiver_map);
8229 HValue* length = Add<HLoadNamedField>(
8230 checked_object, static_cast<HValue*>(NULL),
8231 HObjectAccess::ForArrayLength(elements_kind));
8233 Drop(1); // Function.
8235 { NoObservableSideEffectsScope scope(this);
8236 IfBuilder length_checker(this);
8238 HValue* bounds_check = length_checker.If<HCompareNumericAndBranch>(
8239 length, graph()->GetConstant0(), Token::EQ);
8240 length_checker.Then();
8242 if (!ast_context()->IsEffect()) Push(graph()->GetConstantUndefined());
8244 length_checker.Else();
8245 HValue* elements = AddLoadElements(checked_object);
8246 // Ensure that we aren't popping from a copy-on-write array.
8247 if (IsFastSmiOrObjectElementsKind(elements_kind)) {
8248 elements = BuildCopyElementsOnWrite(checked_object, elements,
8249 elements_kind, length);
8251 reduced_length = AddUncasted<HSub>(length, graph()->GetConstant1());
8252 result = AddElementAccess(elements, reduced_length, NULL,
8253 bounds_check, elements_kind, LOAD);
8254 Factory* factory = isolate()->factory();
8255 double nan_double = FixedDoubleArray::hole_nan_as_double();
8256 HValue* hole = IsFastSmiOrObjectElementsKind(elements_kind)
8257 ? Add<HConstant>(factory->the_hole_value())
8258 : Add<HConstant>(nan_double);
8259 if (IsFastSmiOrObjectElementsKind(elements_kind)) {
8260 elements_kind = FAST_HOLEY_ELEMENTS;
8263 elements, reduced_length, hole, bounds_check, elements_kind, STORE);
8264 Add<HStoreNamedField>(
8265 checked_object, HObjectAccess::ForArrayLength(elements_kind),
8266 reduced_length, STORE_TO_INITIALIZED_ENTRY);
8268 if (!ast_context()->IsEffect()) Push(result);
8270 length_checker.End();
8272 result = ast_context()->IsEffect() ? graph()->GetConstant0() : Top();
8273 Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
8274 if (!ast_context()->IsEffect()) Drop(1);
8276 ast_context()->ReturnValue(result);
8280 if (receiver_map.is_null()) return false;
8281 if (receiver_map->instance_type() != JS_ARRAY_TYPE) return false;
8282 ElementsKind elements_kind = receiver_map->elements_kind();
8283 if (!IsFastElementsKind(elements_kind)) return false;
8284 if (receiver_map->is_observed()) return false;
8285 if (JSArray::IsReadOnlyLengthDescriptor(receiver_map)) return false;
8286 DCHECK(receiver_map->is_extensible());
8288 // If there may be elements accessors in the prototype chain, the fast
8289 // inlined version can't be used.
8290 if (receiver_map->DictionaryElementsInPrototypeChainOnly()) return false;
8291 // If there currently can be no elements accessors on the prototype chain,
8292 // it doesn't mean that there won't be any later. Install a full prototype
8293 // chain check to trap element accessors being installed on the prototype
8294 // chain, which would cause elements to go to dictionary mode and result
8296 Handle<JSObject> prototype(JSObject::cast(receiver_map->prototype()));
8297 BuildCheckPrototypeMaps(prototype, Handle<JSObject>());
8299 const int argc = expr->arguments()->length();
8300 if (argc != 1) return false;
8302 HValue* value_to_push = Pop();
8303 HValue* array = Pop();
8304 Drop(1); // Drop function.
8306 HInstruction* new_size = NULL;
8307 HValue* length = NULL;
8310 NoObservableSideEffectsScope scope(this);
8312 length = Add<HLoadNamedField>(array, static_cast<HValue*>(NULL),
8313 HObjectAccess::ForArrayLength(elements_kind));
8315 new_size = AddUncasted<HAdd>(length, graph()->GetConstant1());
8317 bool is_array = receiver_map->instance_type() == JS_ARRAY_TYPE;
8318 BuildUncheckedMonomorphicElementAccess(array, length,
8319 value_to_push, is_array,
8320 elements_kind, STORE,
8322 STORE_AND_GROW_NO_TRANSITION);
8324 if (!ast_context()->IsEffect()) Push(new_size);
8325 Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
8326 if (!ast_context()->IsEffect()) Drop(1);
8329 ast_context()->ReturnValue(new_size);
8333 if (receiver_map.is_null()) return false;
8334 if (receiver_map->instance_type() != JS_ARRAY_TYPE) return false;
8335 ElementsKind kind = receiver_map->elements_kind();
8336 if (!IsFastElementsKind(kind)) return false;
8337 if (receiver_map->is_observed()) return false;
8338 DCHECK(receiver_map->is_extensible());
8340 // If there may be elements accessors in the prototype chain, the fast
8341 // inlined version can't be used.
8342 if (receiver_map->DictionaryElementsInPrototypeChainOnly()) return false;
8344 // If there currently can be no elements accessors on the prototype chain,
8345 // it doesn't mean that there won't be any later. Install a full prototype
8346 // chain check to trap element accessors being installed on the prototype
8347 // chain, which would cause elements to go to dictionary mode and result
8349 BuildCheckPrototypeMaps(
8350 handle(JSObject::cast(receiver_map->prototype()), isolate()),
8351 Handle<JSObject>::null());
8353 // Threshold for fast inlined Array.shift().
8354 HConstant* inline_threshold = Add<HConstant>(static_cast<int32_t>(16));
8356 Drop(expr->arguments()->length());
8357 HValue* receiver = Pop();
8358 HValue* function = Pop();
8362 NoObservableSideEffectsScope scope(this);
8364 HValue* length = Add<HLoadNamedField>(
8365 receiver, static_cast<HValue*>(NULL),
8366 HObjectAccess::ForArrayLength(kind));
8368 IfBuilder if_lengthiszero(this);
8369 HValue* lengthiszero = if_lengthiszero.If<HCompareNumericAndBranch>(
8370 length, graph()->GetConstant0(), Token::EQ);
8371 if_lengthiszero.Then();
8373 if (!ast_context()->IsEffect()) Push(graph()->GetConstantUndefined());
8375 if_lengthiszero.Else();
8377 HValue* elements = AddLoadElements(receiver);
8379 // Check if we can use the fast inlined Array.shift().
8380 IfBuilder if_inline(this);
8381 if_inline.If<HCompareNumericAndBranch>(
8382 length, inline_threshold, Token::LTE);
8383 if (IsFastSmiOrObjectElementsKind(kind)) {
8384 // We cannot handle copy-on-write backing stores here.
8385 if_inline.AndIf<HCompareMap>(
8386 elements, isolate()->factory()->fixed_array_map());
8390 // Remember the result.
8391 if (!ast_context()->IsEffect()) {
8392 Push(AddElementAccess(elements, graph()->GetConstant0(), NULL,
8393 lengthiszero, kind, LOAD));
8396 // Compute the new length.
8397 HValue* new_length = AddUncasted<HSub>(
8398 length, graph()->GetConstant1());
8399 new_length->ClearFlag(HValue::kCanOverflow);
8401 // Copy the remaining elements.
8402 LoopBuilder loop(this, context(), LoopBuilder::kPostIncrement);
8404 HValue* new_key = loop.BeginBody(
8405 graph()->GetConstant0(), new_length, Token::LT);
8406 HValue* key = AddUncasted<HAdd>(new_key, graph()->GetConstant1());
8407 key->ClearFlag(HValue::kCanOverflow);
8408 HValue* element = AddUncasted<HLoadKeyed>(
8409 elements, key, lengthiszero, kind, ALLOW_RETURN_HOLE);
8410 HStoreKeyed* store = Add<HStoreKeyed>(
8411 elements, new_key, element, kind);
8412 store->SetFlag(HValue::kAllowUndefinedAsNaN);
8416 // Put a hole at the end.
8417 HValue* hole = IsFastSmiOrObjectElementsKind(kind)
8418 ? Add<HConstant>(isolate()->factory()->the_hole_value())
8419 : Add<HConstant>(FixedDoubleArray::hole_nan_as_double());
8420 if (IsFastSmiOrObjectElementsKind(kind)) kind = FAST_HOLEY_ELEMENTS;
8422 elements, new_length, hole, kind, INITIALIZING_STORE);
8424 // Remember new length.
8425 Add<HStoreNamedField>(
8426 receiver, HObjectAccess::ForArrayLength(kind),
8427 new_length, STORE_TO_INITIALIZED_ENTRY);
8431 Add<HPushArguments>(receiver);
8432 result = Add<HCallJSFunction>(function, 1, true);
8433 if (!ast_context()->IsEffect()) Push(result);
8437 if_lengthiszero.End();
8439 result = ast_context()->IsEffect() ? graph()->GetConstant0() : Top();
8440 Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
8441 if (!ast_context()->IsEffect()) Drop(1);
8442 ast_context()->ReturnValue(result);
8446 case kArrayLastIndexOf: {
8447 if (receiver_map.is_null()) return false;
8448 if (receiver_map->instance_type() != JS_ARRAY_TYPE) return false;
8449 ElementsKind kind = receiver_map->elements_kind();
8450 if (!IsFastElementsKind(kind)) return false;
8451 if (receiver_map->is_observed()) return false;
8452 if (argument_count != 2) return false;
8453 DCHECK(receiver_map->is_extensible());
8455 // If there may be elements accessors in the prototype chain, the fast
8456 // inlined version can't be used.
8457 if (receiver_map->DictionaryElementsInPrototypeChainOnly()) return false;
8459 // If there currently can be no elements accessors on the prototype chain,
8460 // it doesn't mean that there won't be any later. Install a full prototype
8461 // chain check to trap element accessors being installed on the prototype
8462 // chain, which would cause elements to go to dictionary mode and result
8464 BuildCheckPrototypeMaps(
8465 handle(JSObject::cast(receiver_map->prototype()), isolate()),
8466 Handle<JSObject>::null());
8468 HValue* search_element = Pop();
8469 HValue* receiver = Pop();
8470 Drop(1); // Drop function.
8472 ArrayIndexOfMode mode = (id == kArrayIndexOf)
8473 ? kFirstIndexOf : kLastIndexOf;
8474 HValue* index = BuildArrayIndexOf(receiver, search_element, kind, mode);
8476 if (!ast_context()->IsEffect()) Push(index);
8477 Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
8478 if (!ast_context()->IsEffect()) Drop(1);
8479 ast_context()->ReturnValue(index);
8483 // Not yet supported for inlining.
8490 bool HOptimizedGraphBuilder::TryInlineApiFunctionCall(Call* expr,
8492 Handle<JSFunction> function = expr->target();
8493 int argc = expr->arguments()->length();
8494 SmallMapList receiver_maps;
8495 return TryInlineApiCall(function,
8504 bool HOptimizedGraphBuilder::TryInlineApiMethodCall(
8507 SmallMapList* receiver_maps) {
8508 Handle<JSFunction> function = expr->target();
8509 int argc = expr->arguments()->length();
8510 return TryInlineApiCall(function,
8519 bool HOptimizedGraphBuilder::TryInlineApiGetter(Handle<JSFunction> function,
8520 Handle<Map> receiver_map,
8522 SmallMapList receiver_maps(1, zone());
8523 receiver_maps.Add(receiver_map, zone());
8524 return TryInlineApiCall(function,
8525 NULL, // Receiver is on expression stack.
8533 bool HOptimizedGraphBuilder::TryInlineApiSetter(Handle<JSFunction> function,
8534 Handle<Map> receiver_map,
8536 SmallMapList receiver_maps(1, zone());
8537 receiver_maps.Add(receiver_map, zone());
8538 return TryInlineApiCall(function,
8539 NULL, // Receiver is on expression stack.
8547 bool HOptimizedGraphBuilder::TryInlineApiCall(Handle<JSFunction> function,
8549 SmallMapList* receiver_maps,
8552 ApiCallType call_type) {
8553 CallOptimization optimization(function);
8554 if (!optimization.is_simple_api_call()) return false;
8555 Handle<Map> holder_map;
8556 if (call_type == kCallApiFunction) {
8557 // Cannot embed a direct reference to the global proxy map
8558 // as it maybe dropped on deserialization.
8559 CHECK(!isolate()->serializer_enabled());
8560 DCHECK_EQ(0, receiver_maps->length());
8561 receiver_maps->Add(handle(function->global_proxy()->map()), zone());
8563 CallOptimization::HolderLookup holder_lookup =
8564 CallOptimization::kHolderNotFound;
8565 Handle<JSObject> api_holder = optimization.LookupHolderOfExpectedType(
8566 receiver_maps->first(), &holder_lookup);
8567 if (holder_lookup == CallOptimization::kHolderNotFound) return false;
8569 if (FLAG_trace_inlining) {
8570 PrintF("Inlining api function ");
8571 function->ShortPrint();
8575 bool drop_extra = false;
8576 bool is_store = false;
8577 switch (call_type) {
8578 case kCallApiFunction:
8579 case kCallApiMethod:
8580 // Need to check that none of the receiver maps could have changed.
8581 Add<HCheckMaps>(receiver, receiver_maps);
8582 // Need to ensure the chain between receiver and api_holder is intact.
8583 if (holder_lookup == CallOptimization::kHolderFound) {
8584 AddCheckPrototypeMaps(api_holder, receiver_maps->first());
8586 DCHECK_EQ(holder_lookup, CallOptimization::kHolderIsReceiver);
8588 // Includes receiver.
8589 PushArgumentsFromEnvironment(argc + 1);
8590 // Drop function after call.
8593 case kCallApiGetter:
8594 // Receiver and prototype chain cannot have changed.
8596 DCHECK_EQ(NULL, receiver);
8597 // Receiver is on expression stack.
8599 Add<HPushArguments>(receiver);
8601 case kCallApiSetter:
8604 // Receiver and prototype chain cannot have changed.
8606 DCHECK_EQ(NULL, receiver);
8607 // Receiver and value are on expression stack.
8608 HValue* value = Pop();
8610 Add<HPushArguments>(receiver, value);
8615 HValue* holder = NULL;
8616 switch (holder_lookup) {
8617 case CallOptimization::kHolderFound:
8618 holder = Add<HConstant>(api_holder);
8620 case CallOptimization::kHolderIsReceiver:
8623 case CallOptimization::kHolderNotFound:
8627 Handle<CallHandlerInfo> api_call_info = optimization.api_call_info();
8628 Handle<Object> call_data_obj(api_call_info->data(), isolate());
8629 bool call_data_is_undefined = call_data_obj->IsUndefined();
8630 HValue* call_data = Add<HConstant>(call_data_obj);
8631 ApiFunction fun(v8::ToCData<Address>(api_call_info->callback()));
8632 ExternalReference ref = ExternalReference(&fun,
8633 ExternalReference::DIRECT_API_CALL,
8635 HValue* api_function_address = Add<HConstant>(ExternalReference(ref));
8637 HValue* op_vals[] = {
8639 Add<HConstant>(function),
8642 api_function_address
8645 CallInterfaceDescriptor* descriptor =
8646 isolate()->call_descriptor(Isolate::ApiFunctionCall);
8648 CallApiFunctionStub stub(isolate(), is_store, call_data_is_undefined, argc);
8649 Handle<Code> code = stub.GetCode();
8650 HConstant* code_value = Add<HConstant>(code);
8652 DCHECK((sizeof(op_vals) / kPointerSize) ==
8653 descriptor->GetEnvironmentLength());
8655 HInstruction* call = New<HCallWithDescriptor>(
8656 code_value, argc + 1, descriptor,
8657 Vector<HValue*>(op_vals, descriptor->GetEnvironmentLength()));
8659 if (drop_extra) Drop(1); // Drop function.
8660 ast_context()->ReturnInstruction(call, ast_id);
8665 bool HOptimizedGraphBuilder::TryCallApply(Call* expr) {
8666 DCHECK(expr->expression()->IsProperty());
8668 if (!expr->IsMonomorphic()) {
8671 Handle<Map> function_map = expr->GetReceiverTypes()->first();
8672 if (function_map->instance_type() != JS_FUNCTION_TYPE ||
8673 !expr->target()->shared()->HasBuiltinFunctionId() ||
8674 expr->target()->shared()->builtin_function_id() != kFunctionApply) {
8678 if (current_info()->scope()->arguments() == NULL) return false;
8680 ZoneList<Expression*>* args = expr->arguments();
8681 if (args->length() != 2) return false;
8683 VariableProxy* arg_two = args->at(1)->AsVariableProxy();
8684 if (arg_two == NULL || !arg_two->var()->IsStackAllocated()) return false;
8685 HValue* arg_two_value = LookupAndMakeLive(arg_two->var());
8686 if (!arg_two_value->CheckFlag(HValue::kIsArguments)) return false;
8688 // Found pattern f.apply(receiver, arguments).
8689 CHECK_ALIVE_OR_RETURN(VisitForValue(args->at(0)), true);
8690 HValue* receiver = Pop(); // receiver
8691 HValue* function = Pop(); // f
8694 HValue* checked_function = AddCheckMap(function, function_map);
8696 if (function_state()->outer() == NULL) {
8697 HInstruction* elements = Add<HArgumentsElements>(false);
8698 HInstruction* length = Add<HArgumentsLength>(elements);
8699 HValue* wrapped_receiver = BuildWrapReceiver(receiver, checked_function);
8700 HInstruction* result = New<HApplyArguments>(function,
8704 ast_context()->ReturnInstruction(result, expr->id());
8707 // We are inside inlined function and we know exactly what is inside
8708 // arguments object. But we need to be able to materialize at deopt.
8709 DCHECK_EQ(environment()->arguments_environment()->parameter_count(),
8710 function_state()->entry()->arguments_object()->arguments_count());
8711 HArgumentsObject* args = function_state()->entry()->arguments_object();
8712 const ZoneList<HValue*>* arguments_values = args->arguments_values();
8713 int arguments_count = arguments_values->length();
8715 Push(BuildWrapReceiver(receiver, checked_function));
8716 for (int i = 1; i < arguments_count; i++) {
8717 Push(arguments_values->at(i));
8720 Handle<JSFunction> known_function;
8721 if (function->IsConstant() &&
8722 HConstant::cast(function)->handle(isolate())->IsJSFunction()) {
8723 known_function = Handle<JSFunction>::cast(
8724 HConstant::cast(function)->handle(isolate()));
8725 int args_count = arguments_count - 1; // Excluding receiver.
8726 if (TryInlineApply(known_function, expr, args_count)) return true;
8729 PushArgumentsFromEnvironment(arguments_count);
8730 HInvokeFunction* call = New<HInvokeFunction>(
8731 function, known_function, arguments_count);
8732 Drop(1); // Function.
8733 ast_context()->ReturnInstruction(call, expr->id());
8739 HValue* HOptimizedGraphBuilder::ImplicitReceiverFor(HValue* function,
8740 Handle<JSFunction> target) {
8741 SharedFunctionInfo* shared = target->shared();
8742 if (shared->strict_mode() == SLOPPY && !shared->native()) {
8743 // Cannot embed a direct reference to the global proxy
8744 // as is it dropped on deserialization.
8745 CHECK(!isolate()->serializer_enabled());
8746 Handle<JSObject> global_proxy(target->context()->global_proxy());
8747 return Add<HConstant>(global_proxy);
8749 return graph()->GetConstantUndefined();
8753 void HOptimizedGraphBuilder::BuildArrayCall(Expression* expression,
8754 int arguments_count,
8756 Handle<AllocationSite> site) {
8757 Add<HCheckValue>(function, array_function());
8759 if (IsCallArrayInlineable(arguments_count, site)) {
8760 BuildInlinedCallArray(expression, arguments_count, site);
8764 HInstruction* call = PreProcessCall(New<HCallNewArray>(
8765 function, arguments_count + 1, site->GetElementsKind()));
8766 if (expression->IsCall()) {
8769 ast_context()->ReturnInstruction(call, expression->id());
8773 HValue* HOptimizedGraphBuilder::BuildArrayIndexOf(HValue* receiver,
8774 HValue* search_element,
8776 ArrayIndexOfMode mode) {
8777 DCHECK(IsFastElementsKind(kind));
8779 NoObservableSideEffectsScope no_effects(this);
8781 HValue* elements = AddLoadElements(receiver);
8782 HValue* length = AddLoadArrayLength(receiver, kind);
8785 HValue* terminating;
8787 LoopBuilder::Direction direction;
8788 if (mode == kFirstIndexOf) {
8789 initial = graph()->GetConstant0();
8790 terminating = length;
8792 direction = LoopBuilder::kPostIncrement;
8794 DCHECK_EQ(kLastIndexOf, mode);
8796 terminating = graph()->GetConstant0();
8798 direction = LoopBuilder::kPreDecrement;
8801 Push(graph()->GetConstantMinus1());
8802 if (IsFastDoubleElementsKind(kind) || IsFastSmiElementsKind(kind)) {
8803 LoopBuilder loop(this, context(), direction);
8805 HValue* index = loop.BeginBody(initial, terminating, token);
8806 HValue* element = AddUncasted<HLoadKeyed>(
8807 elements, index, static_cast<HValue*>(NULL),
8808 kind, ALLOW_RETURN_HOLE);
8809 IfBuilder if_issame(this);
8810 if (IsFastDoubleElementsKind(kind)) {
8811 if_issame.If<HCompareNumericAndBranch>(
8812 element, search_element, Token::EQ_STRICT);
8814 if_issame.If<HCompareObjectEqAndBranch>(element, search_element);
8826 IfBuilder if_isstring(this);
8827 if_isstring.If<HIsStringAndBranch>(search_element);
8830 LoopBuilder loop(this, context(), direction);
8832 HValue* index = loop.BeginBody(initial, terminating, token);
8833 HValue* element = AddUncasted<HLoadKeyed>(
8834 elements, index, static_cast<HValue*>(NULL),
8835 kind, ALLOW_RETURN_HOLE);
8836 IfBuilder if_issame(this);
8837 if_issame.If<HIsStringAndBranch>(element);
8838 if_issame.AndIf<HStringCompareAndBranch>(
8839 element, search_element, Token::EQ_STRICT);
8852 IfBuilder if_isnumber(this);
8853 if_isnumber.If<HIsSmiAndBranch>(search_element);
8854 if_isnumber.OrIf<HCompareMap>(
8855 search_element, isolate()->factory()->heap_number_map());
8858 HValue* search_number =
8859 AddUncasted<HForceRepresentation>(search_element,
8860 Representation::Double());
8861 LoopBuilder loop(this, context(), direction);
8863 HValue* index = loop.BeginBody(initial, terminating, token);
8864 HValue* element = AddUncasted<HLoadKeyed>(
8865 elements, index, static_cast<HValue*>(NULL),
8866 kind, ALLOW_RETURN_HOLE);
8868 IfBuilder if_element_isnumber(this);
8869 if_element_isnumber.If<HIsSmiAndBranch>(element);
8870 if_element_isnumber.OrIf<HCompareMap>(
8871 element, isolate()->factory()->heap_number_map());
8872 if_element_isnumber.Then();
8875 AddUncasted<HForceRepresentation>(element,
8876 Representation::Double());
8877 IfBuilder if_issame(this);
8878 if_issame.If<HCompareNumericAndBranch>(
8879 number, search_number, Token::EQ_STRICT);
8888 if_element_isnumber.End();
8894 LoopBuilder loop(this, context(), direction);
8896 HValue* index = loop.BeginBody(initial, terminating, token);
8897 HValue* element = AddUncasted<HLoadKeyed>(
8898 elements, index, static_cast<HValue*>(NULL),
8899 kind, ALLOW_RETURN_HOLE);
8900 IfBuilder if_issame(this);
8901 if_issame.If<HCompareObjectEqAndBranch>(
8902 element, search_element);
8922 bool HOptimizedGraphBuilder::TryHandleArrayCall(Call* expr, HValue* function) {
8923 if (!array_function().is_identical_to(expr->target())) {
8927 Handle<AllocationSite> site = expr->allocation_site();
8928 if (site.is_null()) return false;
8930 BuildArrayCall(expr,
8931 expr->arguments()->length(),
8938 bool HOptimizedGraphBuilder::TryHandleArrayCallNew(CallNew* expr,
8940 if (!array_function().is_identical_to(expr->target())) {
8944 BuildArrayCall(expr,
8945 expr->arguments()->length(),
8947 expr->allocation_site());
8952 void HOptimizedGraphBuilder::VisitCall(Call* expr) {
8953 DCHECK(!HasStackOverflow());
8954 DCHECK(current_block() != NULL);
8955 DCHECK(current_block()->HasPredecessor());
8956 Expression* callee = expr->expression();
8957 int argument_count = expr->arguments()->length() + 1; // Plus receiver.
8958 HInstruction* call = NULL;
8960 Property* prop = callee->AsProperty();
8962 CHECK_ALIVE(VisitForValue(prop->obj()));
8963 HValue* receiver = Top();
8965 SmallMapList* types;
8966 ComputeReceiverTypes(expr, receiver, &types, zone());
8968 if (prop->key()->IsPropertyName() && types->length() > 0) {
8969 Handle<String> name = prop->key()->AsLiteral()->AsPropertyName();
8970 PropertyAccessInfo info(this, LOAD, ToType(types->first()), name);
8971 if (!info.CanAccessAsMonomorphic(types)) {
8972 HandlePolymorphicCallNamed(expr, receiver, types, name);
8978 if (!prop->key()->IsPropertyName()) {
8979 CHECK_ALIVE(VisitForValue(prop->key()));
8983 CHECK_ALIVE(PushLoad(prop, receiver, key));
8984 HValue* function = Pop();
8986 if (FLAG_hydrogen_track_positions) SetSourcePosition(expr->position());
8988 // Push the function under the receiver.
8989 environment()->SetExpressionStackAt(0, function);
8993 if (function->IsConstant() &&
8994 HConstant::cast(function)->handle(isolate())->IsJSFunction()) {
8995 Handle<JSFunction> known_function = Handle<JSFunction>::cast(
8996 HConstant::cast(function)->handle(isolate()));
8997 expr->set_target(known_function);
8999 if (TryCallApply(expr)) return;
9000 CHECK_ALIVE(VisitExpressions(expr->arguments()));
9002 Handle<Map> map = types->length() == 1 ? types->first() : Handle<Map>();
9003 if (TryInlineBuiltinMethodCall(expr, receiver, map)) {
9004 if (FLAG_trace_inlining) {
9005 PrintF("Inlining builtin ");
9006 known_function->ShortPrint();
9011 if (TryInlineApiMethodCall(expr, receiver, types)) return;
9013 // Wrap the receiver if necessary.
9014 if (NeedsWrappingFor(ToType(types->first()), known_function)) {
9015 // Since HWrapReceiver currently cannot actually wrap numbers and
9016 // strings, use the regular CallFunctionStub for method calls to wrap
9018 // TODO(verwaest): Support creation of value wrappers directly in
9020 call = New<HCallFunction>(
9021 function, argument_count, WRAP_AND_CALL);
9022 } else if (TryInlineCall(expr)) {
9025 call = BuildCallConstantFunction(known_function, argument_count);
9029 CHECK_ALIVE(VisitExpressions(expr->arguments()));
9030 CallFunctionFlags flags = receiver->type().IsJSObject()
9031 ? NO_CALL_FUNCTION_FLAGS : CALL_AS_METHOD;
9032 call = New<HCallFunction>(function, argument_count, flags);
9034 PushArgumentsFromEnvironment(argument_count);
9037 VariableProxy* proxy = expr->expression()->AsVariableProxy();
9038 if (proxy != NULL && proxy->var()->is_possibly_eval(isolate())) {
9039 return Bailout(kPossibleDirectCallToEval);
9042 // The function is on the stack in the unoptimized code during
9043 // evaluation of the arguments.
9044 CHECK_ALIVE(VisitForValue(expr->expression()));
9045 HValue* function = Top();
9046 if (expr->global_call()) {
9047 Variable* var = proxy->var();
9048 bool known_global_function = false;
9049 // If there is a global property cell for the name at compile time and
9050 // access check is not enabled we assume that the function will not change
9051 // and generate optimized code for calling the function.
9052 LookupResult lookup(isolate());
9053 GlobalPropertyAccess type = LookupGlobalProperty(var, &lookup, LOAD);
9054 if (type == kUseCell &&
9055 !current_info()->global_object()->IsAccessCheckNeeded()) {
9056 Handle<GlobalObject> global(current_info()->global_object());
9057 known_global_function = expr->ComputeGlobalTarget(global, &lookup);
9059 if (known_global_function) {
9060 Add<HCheckValue>(function, expr->target());
9062 // Placeholder for the receiver.
9063 Push(graph()->GetConstantUndefined());
9064 CHECK_ALIVE(VisitExpressions(expr->arguments()));
9066 // Patch the global object on the stack by the expected receiver.
9067 HValue* receiver = ImplicitReceiverFor(function, expr->target());
9068 const int receiver_index = argument_count - 1;
9069 environment()->SetExpressionStackAt(receiver_index, receiver);
9071 if (TryInlineBuiltinFunctionCall(expr)) {
9072 if (FLAG_trace_inlining) {
9073 PrintF("Inlining builtin ");
9074 expr->target()->ShortPrint();
9079 if (TryInlineApiFunctionCall(expr, receiver)) return;
9080 if (TryHandleArrayCall(expr, function)) return;
9081 if (TryInlineCall(expr)) return;
9083 PushArgumentsFromEnvironment(argument_count);
9084 call = BuildCallConstantFunction(expr->target(), argument_count);
9086 Push(graph()->GetConstantUndefined());
9087 CHECK_ALIVE(VisitExpressions(expr->arguments()));
9088 PushArgumentsFromEnvironment(argument_count);
9089 call = New<HCallFunction>(function, argument_count);
9092 } else if (expr->IsMonomorphic()) {
9093 Add<HCheckValue>(function, expr->target());
9095 Push(graph()->GetConstantUndefined());
9096 CHECK_ALIVE(VisitExpressions(expr->arguments()));
9098 HValue* receiver = ImplicitReceiverFor(function, expr->target());
9099 const int receiver_index = argument_count - 1;
9100 environment()->SetExpressionStackAt(receiver_index, receiver);
9102 if (TryInlineBuiltinFunctionCall(expr)) {
9103 if (FLAG_trace_inlining) {
9104 PrintF("Inlining builtin ");
9105 expr->target()->ShortPrint();
9110 if (TryInlineApiFunctionCall(expr, receiver)) return;
9112 if (TryInlineCall(expr)) return;
9114 call = PreProcessCall(New<HInvokeFunction>(
9115 function, expr->target(), argument_count));
9118 Push(graph()->GetConstantUndefined());
9119 CHECK_ALIVE(VisitExpressions(expr->arguments()));
9120 PushArgumentsFromEnvironment(argument_count);
9121 call = New<HCallFunction>(function, argument_count);
9125 Drop(1); // Drop the function.
9126 return ast_context()->ReturnInstruction(call, expr->id());
9130 void HOptimizedGraphBuilder::BuildInlinedCallArray(
9131 Expression* expression,
9133 Handle<AllocationSite> site) {
9134 DCHECK(!site.is_null());
9135 DCHECK(argument_count >= 0 && argument_count <= 1);
9136 NoObservableSideEffectsScope no_effects(this);
9138 // We should at least have the constructor on the expression stack.
9139 HValue* constructor = environment()->ExpressionStackAt(argument_count);
9141 // Register on the site for deoptimization if the transition feedback changes.
9142 AllocationSite::AddDependentCompilationInfo(
9143 site, AllocationSite::TRANSITIONS, top_info());
9144 ElementsKind kind = site->GetElementsKind();
9145 HInstruction* site_instruction = Add<HConstant>(site);
9147 // In the single constant argument case, we may have to adjust elements kind
9148 // to avoid creating a packed non-empty array.
9149 if (argument_count == 1 && !IsHoleyElementsKind(kind)) {
9150 HValue* argument = environment()->Top();
9151 if (argument->IsConstant()) {
9152 HConstant* constant_argument = HConstant::cast(argument);
9153 DCHECK(constant_argument->HasSmiValue());
9154 int constant_array_size = constant_argument->Integer32Value();
9155 if (constant_array_size != 0) {
9156 kind = GetHoleyElementsKind(kind);
9162 JSArrayBuilder array_builder(this,
9166 DISABLE_ALLOCATION_SITES);
9167 HValue* new_object = argument_count == 0
9168 ? array_builder.AllocateEmptyArray()
9169 : BuildAllocateArrayFromLength(&array_builder, Top());
9171 int args_to_drop = argument_count + (expression->IsCall() ? 2 : 1);
9173 ast_context()->ReturnValue(new_object);
9177 // Checks whether allocation using the given constructor can be inlined.
9178 static bool IsAllocationInlineable(Handle<JSFunction> constructor) {
9179 return constructor->has_initial_map() &&
9180 constructor->initial_map()->instance_type() == JS_OBJECT_TYPE &&
9181 constructor->initial_map()->instance_size() < HAllocate::kMaxInlineSize &&
9182 constructor->initial_map()->InitialPropertiesLength() == 0;
9186 bool HOptimizedGraphBuilder::IsCallArrayInlineable(
9188 Handle<AllocationSite> site) {
9189 Handle<JSFunction> caller = current_info()->closure();
9190 Handle<JSFunction> target = array_function();
9191 // We should have the function plus array arguments on the environment stack.
9192 DCHECK(environment()->length() >= (argument_count + 1));
9193 DCHECK(!site.is_null());
9195 bool inline_ok = false;
9196 if (site->CanInlineCall()) {
9197 // We also want to avoid inlining in certain 1 argument scenarios.
9198 if (argument_count == 1) {
9199 HValue* argument = Top();
9200 if (argument->IsConstant()) {
9201 // Do not inline if the constant length argument is not a smi or
9202 // outside the valid range for unrolled loop initialization.
9203 HConstant* constant_argument = HConstant::cast(argument);
9204 if (constant_argument->HasSmiValue()) {
9205 int value = constant_argument->Integer32Value();
9206 inline_ok = value >= 0 && value <= kElementLoopUnrollThreshold;
9208 TraceInline(target, caller,
9209 "Constant length outside of valid inlining range.");
9213 TraceInline(target, caller,
9214 "Dont inline [new] Array(n) where n isn't constant.");
9216 } else if (argument_count == 0) {
9219 TraceInline(target, caller, "Too many arguments to inline.");
9222 TraceInline(target, caller, "AllocationSite requested no inlining.");
9226 TraceInline(target, caller, NULL);
9232 void HOptimizedGraphBuilder::VisitCallNew(CallNew* expr) {
9233 DCHECK(!HasStackOverflow());
9234 DCHECK(current_block() != NULL);
9235 DCHECK(current_block()->HasPredecessor());
9236 if (!FLAG_hydrogen_track_positions) SetSourcePosition(expr->position());
9237 int argument_count = expr->arguments()->length() + 1; // Plus constructor.
9238 Factory* factory = isolate()->factory();
9240 // The constructor function is on the stack in the unoptimized code
9241 // during evaluation of the arguments.
9242 CHECK_ALIVE(VisitForValue(expr->expression()));
9243 HValue* function = Top();
9244 CHECK_ALIVE(VisitExpressions(expr->arguments()));
9246 if (FLAG_inline_construct &&
9247 expr->IsMonomorphic() &&
9248 IsAllocationInlineable(expr->target())) {
9249 Handle<JSFunction> constructor = expr->target();
9250 HValue* check = Add<HCheckValue>(function, constructor);
9252 // Force completion of inobject slack tracking before generating
9253 // allocation code to finalize instance size.
9254 if (constructor->IsInobjectSlackTrackingInProgress()) {
9255 constructor->CompleteInobjectSlackTracking();
9258 // Calculate instance size from initial map of constructor.
9259 DCHECK(constructor->has_initial_map());
9260 Handle<Map> initial_map(constructor->initial_map());
9261 int instance_size = initial_map->instance_size();
9262 DCHECK(initial_map->InitialPropertiesLength() == 0);
9264 // Allocate an instance of the implicit receiver object.
9265 HValue* size_in_bytes = Add<HConstant>(instance_size);
9266 HAllocationMode allocation_mode;
9267 if (FLAG_pretenuring_call_new) {
9268 if (FLAG_allocation_site_pretenuring) {
9269 // Try to use pretenuring feedback.
9270 Handle<AllocationSite> allocation_site = expr->allocation_site();
9271 allocation_mode = HAllocationMode(allocation_site);
9272 // Take a dependency on allocation site.
9273 AllocationSite::AddDependentCompilationInfo(allocation_site,
9274 AllocationSite::TENURING,
9279 HAllocate* receiver = BuildAllocate(
9280 size_in_bytes, HType::JSObject(), JS_OBJECT_TYPE, allocation_mode);
9281 receiver->set_known_initial_map(initial_map);
9283 // Initialize map and fields of the newly allocated object.
9284 { NoObservableSideEffectsScope no_effects(this);
9285 DCHECK(initial_map->instance_type() == JS_OBJECT_TYPE);
9286 Add<HStoreNamedField>(receiver,
9287 HObjectAccess::ForMapAndOffset(initial_map, JSObject::kMapOffset),
9288 Add<HConstant>(initial_map));
9289 HValue* empty_fixed_array = Add<HConstant>(factory->empty_fixed_array());
9290 Add<HStoreNamedField>(receiver,
9291 HObjectAccess::ForMapAndOffset(initial_map,
9292 JSObject::kPropertiesOffset),
9294 Add<HStoreNamedField>(receiver,
9295 HObjectAccess::ForMapAndOffset(initial_map,
9296 JSObject::kElementsOffset),
9298 if (initial_map->inobject_properties() != 0) {
9299 HConstant* undefined = graph()->GetConstantUndefined();
9300 for (int i = 0; i < initial_map->inobject_properties(); i++) {
9301 int property_offset = initial_map->GetInObjectPropertyOffset(i);
9302 Add<HStoreNamedField>(receiver,
9303 HObjectAccess::ForMapAndOffset(initial_map, property_offset),
9309 // Replace the constructor function with a newly allocated receiver using
9310 // the index of the receiver from the top of the expression stack.
9311 const int receiver_index = argument_count - 1;
9312 DCHECK(environment()->ExpressionStackAt(receiver_index) == function);
9313 environment()->SetExpressionStackAt(receiver_index, receiver);
9315 if (TryInlineConstruct(expr, receiver)) {
9316 // Inlining worked, add a dependency on the initial map to make sure that
9317 // this code is deoptimized whenever the initial map of the constructor
9319 Map::AddDependentCompilationInfo(
9320 initial_map, DependentCode::kInitialMapChangedGroup, top_info());
9324 // TODO(mstarzinger): For now we remove the previous HAllocate and all
9325 // corresponding instructions and instead add HPushArguments for the
9326 // arguments in case inlining failed. What we actually should do is for
9327 // inlining to try to build a subgraph without mutating the parent graph.
9328 HInstruction* instr = current_block()->last();
9330 HInstruction* prev_instr = instr->previous();
9331 instr->DeleteAndReplaceWith(NULL);
9333 } while (instr != check);
9334 environment()->SetExpressionStackAt(receiver_index, function);
9335 HInstruction* call =
9336 PreProcessCall(New<HCallNew>(function, argument_count));
9337 return ast_context()->ReturnInstruction(call, expr->id());
9339 // The constructor function is both an operand to the instruction and an
9340 // argument to the construct call.
9341 if (TryHandleArrayCallNew(expr, function)) return;
9343 HInstruction* call =
9344 PreProcessCall(New<HCallNew>(function, argument_count));
9345 return ast_context()->ReturnInstruction(call, expr->id());
9350 // Support for generating inlined runtime functions.
9352 // Lookup table for generators for runtime calls that are generated inline.
9353 // Elements of the table are member pointers to functions of
9354 // HOptimizedGraphBuilder.
9355 #define INLINE_FUNCTION_GENERATOR_ADDRESS(Name, argc, ressize) \
9356 &HOptimizedGraphBuilder::Generate##Name,
9358 const HOptimizedGraphBuilder::InlineFunctionGenerator
9359 HOptimizedGraphBuilder::kInlineFunctionGenerators[] = {
9360 INLINE_FUNCTION_LIST(INLINE_FUNCTION_GENERATOR_ADDRESS)
9361 INLINE_OPTIMIZED_FUNCTION_LIST(INLINE_FUNCTION_GENERATOR_ADDRESS)
9363 #undef INLINE_FUNCTION_GENERATOR_ADDRESS
9366 template <class ViewClass>
9367 void HGraphBuilder::BuildArrayBufferViewInitialization(
9370 HValue* byte_offset,
9371 HValue* byte_length) {
9373 for (int offset = ViewClass::kSize;
9374 offset < ViewClass::kSizeWithInternalFields;
9375 offset += kPointerSize) {
9376 Add<HStoreNamedField>(obj,
9377 HObjectAccess::ForObservableJSObjectOffset(offset),
9378 graph()->GetConstant0());
9381 Add<HStoreNamedField>(
9383 HObjectAccess::ForJSArrayBufferViewByteOffset(),
9385 Add<HStoreNamedField>(
9387 HObjectAccess::ForJSArrayBufferViewByteLength(),
9390 if (buffer != NULL) {
9391 Add<HStoreNamedField>(
9393 HObjectAccess::ForJSArrayBufferViewBuffer(), buffer);
9394 HObjectAccess weak_first_view_access =
9395 HObjectAccess::ForJSArrayBufferWeakFirstView();
9396 Add<HStoreNamedField>(obj,
9397 HObjectAccess::ForJSArrayBufferViewWeakNext(),
9398 Add<HLoadNamedField>(buffer,
9399 static_cast<HValue*>(NULL),
9400 weak_first_view_access));
9401 Add<HStoreNamedField>(buffer, weak_first_view_access, obj);
9403 Add<HStoreNamedField>(
9405 HObjectAccess::ForJSArrayBufferViewBuffer(),
9406 Add<HConstant>(static_cast<int32_t>(0)));
9407 Add<HStoreNamedField>(obj,
9408 HObjectAccess::ForJSArrayBufferViewWeakNext(),
9409 graph()->GetConstantUndefined());
9414 void HOptimizedGraphBuilder::GenerateDataViewInitialize(
9415 CallRuntime* expr) {
9416 ZoneList<Expression*>* arguments = expr->arguments();
9418 DCHECK(arguments->length()== 4);
9419 CHECK_ALIVE(VisitForValue(arguments->at(0)));
9420 HValue* obj = Pop();
9422 CHECK_ALIVE(VisitForValue(arguments->at(1)));
9423 HValue* buffer = Pop();
9425 CHECK_ALIVE(VisitForValue(arguments->at(2)));
9426 HValue* byte_offset = Pop();
9428 CHECK_ALIVE(VisitForValue(arguments->at(3)));
9429 HValue* byte_length = Pop();
9432 NoObservableSideEffectsScope scope(this);
9433 BuildArrayBufferViewInitialization<JSDataView>(
9434 obj, buffer, byte_offset, byte_length);
9439 static Handle<Map> TypedArrayMap(Isolate* isolate,
9440 ExternalArrayType array_type,
9441 ElementsKind target_kind) {
9442 Handle<Context> native_context = isolate->native_context();
9443 Handle<JSFunction> fun;
9444 switch (array_type) {
9445 #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
9446 case kExternal##Type##Array: \
9447 fun = Handle<JSFunction>(native_context->type##_array_fun()); \
9450 TYPED_ARRAYS(TYPED_ARRAY_CASE)
9451 #undef TYPED_ARRAY_CASE
9453 Handle<Map> map(fun->initial_map());
9454 return Map::AsElementsKind(map, target_kind);
9458 HValue* HOptimizedGraphBuilder::BuildAllocateExternalElements(
9459 ExternalArrayType array_type,
9460 bool is_zero_byte_offset,
9461 HValue* buffer, HValue* byte_offset, HValue* length) {
9462 Handle<Map> external_array_map(
9463 isolate()->heap()->MapForExternalArrayType(array_type));
9465 // The HForceRepresentation is to prevent possible deopt on int-smi
9466 // conversion after allocation but before the new object fields are set.
9467 length = AddUncasted<HForceRepresentation>(length, Representation::Smi());
9470 Add<HConstant>(ExternalArray::kAlignedSize),
9471 HType::HeapObject(),
9473 external_array_map->instance_type());
9475 AddStoreMapConstant(elements, external_array_map);
9476 Add<HStoreNamedField>(elements,
9477 HObjectAccess::ForFixedArrayLength(), length);
9479 HValue* backing_store = Add<HLoadNamedField>(
9480 buffer, static_cast<HValue*>(NULL),
9481 HObjectAccess::ForJSArrayBufferBackingStore());
9483 HValue* typed_array_start;
9484 if (is_zero_byte_offset) {
9485 typed_array_start = backing_store;
9487 HInstruction* external_pointer =
9488 AddUncasted<HAdd>(backing_store, byte_offset);
9489 // Arguments are checked prior to call to TypedArrayInitialize,
9490 // including byte_offset.
9491 external_pointer->ClearFlag(HValue::kCanOverflow);
9492 typed_array_start = external_pointer;
9495 Add<HStoreNamedField>(elements,
9496 HObjectAccess::ForExternalArrayExternalPointer(),
9503 HValue* HOptimizedGraphBuilder::BuildAllocateFixedTypedArray(
9504 ExternalArrayType array_type, size_t element_size,
9505 ElementsKind fixed_elements_kind,
9506 HValue* byte_length, HValue* length) {
9508 (FixedTypedArrayBase::kHeaderSize & kObjectAlignmentMask) == 0);
9511 // if fixed array's elements are not aligned to object's alignment,
9512 // we need to align the whole array to object alignment.
9513 if (element_size % kObjectAlignment != 0) {
9514 total_size = BuildObjectSizeAlignment(
9515 byte_length, FixedTypedArrayBase::kHeaderSize);
9517 total_size = AddUncasted<HAdd>(byte_length,
9518 Add<HConstant>(FixedTypedArrayBase::kHeaderSize));
9519 total_size->ClearFlag(HValue::kCanOverflow);
9522 // The HForceRepresentation is to prevent possible deopt on int-smi
9523 // conversion after allocation but before the new object fields are set.
9524 length = AddUncasted<HForceRepresentation>(length, Representation::Smi());
9525 Handle<Map> fixed_typed_array_map(
9526 isolate()->heap()->MapForFixedTypedArray(array_type));
9528 Add<HAllocate>(total_size, HType::HeapObject(),
9529 NOT_TENURED, fixed_typed_array_map->instance_type());
9530 AddStoreMapConstant(elements, fixed_typed_array_map);
9532 Add<HStoreNamedField>(elements,
9533 HObjectAccess::ForFixedArrayLength(),
9536 HValue* filler = Add<HConstant>(static_cast<int32_t>(0));
9539 LoopBuilder builder(this, context(), LoopBuilder::kPostIncrement);
9541 HValue* key = builder.BeginBody(
9542 Add<HConstant>(static_cast<int32_t>(0)),
9544 Add<HStoreKeyed>(elements, key, filler, fixed_elements_kind);
9552 void HOptimizedGraphBuilder::GenerateTypedArrayInitialize(
9553 CallRuntime* expr) {
9554 ZoneList<Expression*>* arguments = expr->arguments();
9556 static const int kObjectArg = 0;
9557 static const int kArrayIdArg = 1;
9558 static const int kBufferArg = 2;
9559 static const int kByteOffsetArg = 3;
9560 static const int kByteLengthArg = 4;
9561 static const int kArgsLength = 5;
9562 DCHECK(arguments->length() == kArgsLength);
9565 CHECK_ALIVE(VisitForValue(arguments->at(kObjectArg)));
9566 HValue* obj = Pop();
9568 if (arguments->at(kArrayIdArg)->IsLiteral()) {
9569 // This should never happen in real use, but can happen when fuzzing.
9571 Bailout(kNeedSmiLiteral);
9574 Handle<Object> value =
9575 static_cast<Literal*>(arguments->at(kArrayIdArg))->value();
9576 if (!value->IsSmi()) {
9577 // This should never happen in real use, but can happen when fuzzing.
9579 Bailout(kNeedSmiLiteral);
9582 int array_id = Smi::cast(*value)->value();
9585 if (!arguments->at(kBufferArg)->IsNullLiteral()) {
9586 CHECK_ALIVE(VisitForValue(arguments->at(kBufferArg)));
9592 HValue* byte_offset;
9593 bool is_zero_byte_offset;
9595 if (arguments->at(kByteOffsetArg)->IsLiteral()
9596 && Smi::FromInt(0) ==
9597 *static_cast<Literal*>(arguments->at(kByteOffsetArg))->value()) {
9598 byte_offset = Add<HConstant>(static_cast<int32_t>(0));
9599 is_zero_byte_offset = true;
9601 CHECK_ALIVE(VisitForValue(arguments->at(kByteOffsetArg)));
9602 byte_offset = Pop();
9603 is_zero_byte_offset = false;
9604 DCHECK(buffer != NULL);
9607 CHECK_ALIVE(VisitForValue(arguments->at(kByteLengthArg)));
9608 HValue* byte_length = Pop();
9610 NoObservableSideEffectsScope scope(this);
9611 IfBuilder byte_offset_smi(this);
9613 if (!is_zero_byte_offset) {
9614 byte_offset_smi.If<HIsSmiAndBranch>(byte_offset);
9615 byte_offset_smi.Then();
9618 ExternalArrayType array_type =
9619 kExternalInt8Array; // Bogus initialization.
9620 size_t element_size = 1; // Bogus initialization.
9621 ElementsKind external_elements_kind = // Bogus initialization.
9622 EXTERNAL_INT8_ELEMENTS;
9623 ElementsKind fixed_elements_kind = // Bogus initialization.
9625 Runtime::ArrayIdToTypeAndSize(array_id,
9627 &external_elements_kind,
9628 &fixed_elements_kind,
9632 { // byte_offset is Smi.
9633 BuildArrayBufferViewInitialization<JSTypedArray>(
9634 obj, buffer, byte_offset, byte_length);
9637 HInstruction* length = AddUncasted<HDiv>(byte_length,
9638 Add<HConstant>(static_cast<int32_t>(element_size)));
9640 Add<HStoreNamedField>(obj,
9641 HObjectAccess::ForJSTypedArrayLength(),
9645 if (buffer != NULL) {
9646 elements = BuildAllocateExternalElements(
9647 array_type, is_zero_byte_offset, buffer, byte_offset, length);
9648 Handle<Map> obj_map = TypedArrayMap(
9649 isolate(), array_type, external_elements_kind);
9650 AddStoreMapConstant(obj, obj_map);
9652 DCHECK(is_zero_byte_offset);
9653 elements = BuildAllocateFixedTypedArray(
9654 array_type, element_size, fixed_elements_kind,
9655 byte_length, length);
9657 Add<HStoreNamedField>(
9658 obj, HObjectAccess::ForElementsPointer(), elements);
9661 if (!is_zero_byte_offset) {
9662 byte_offset_smi.Else();
9663 { // byte_offset is not Smi.
9665 CHECK_ALIVE(VisitForValue(arguments->at(kArrayIdArg)));
9669 PushArgumentsFromEnvironment(kArgsLength);
9670 Add<HCallRuntime>(expr->name(), expr->function(), kArgsLength);
9673 byte_offset_smi.End();
9677 void HOptimizedGraphBuilder::GenerateMaxSmi(CallRuntime* expr) {
9678 DCHECK(expr->arguments()->length() == 0);
9679 HConstant* max_smi = New<HConstant>(static_cast<int32_t>(Smi::kMaxValue));
9680 return ast_context()->ReturnInstruction(max_smi, expr->id());
9684 void HOptimizedGraphBuilder::GenerateTypedArrayMaxSizeInHeap(
9685 CallRuntime* expr) {
9686 DCHECK(expr->arguments()->length() == 0);
9687 HConstant* result = New<HConstant>(static_cast<int32_t>(
9688 FLAG_typed_array_max_size_in_heap));
9689 return ast_context()->ReturnInstruction(result, expr->id());
9693 void HOptimizedGraphBuilder::GenerateArrayBufferGetByteLength(
9694 CallRuntime* expr) {
9695 DCHECK(expr->arguments()->length() == 1);
9696 CHECK_ALIVE(VisitForValue(expr->arguments()->at(0)));
9697 HValue* buffer = Pop();
9698 HInstruction* result = New<HLoadNamedField>(
9700 static_cast<HValue*>(NULL),
9701 HObjectAccess::ForJSArrayBufferByteLength());
9702 return ast_context()->ReturnInstruction(result, expr->id());
9706 void HOptimizedGraphBuilder::GenerateArrayBufferViewGetByteLength(
9707 CallRuntime* expr) {
9708 DCHECK(expr->arguments()->length() == 1);
9709 CHECK_ALIVE(VisitForValue(expr->arguments()->at(0)));
9710 HValue* buffer = Pop();
9711 HInstruction* result = New<HLoadNamedField>(
9713 static_cast<HValue*>(NULL),
9714 HObjectAccess::ForJSArrayBufferViewByteLength());
9715 return ast_context()->ReturnInstruction(result, expr->id());
9719 void HOptimizedGraphBuilder::GenerateArrayBufferViewGetByteOffset(
9720 CallRuntime* expr) {
9721 DCHECK(expr->arguments()->length() == 1);
9722 CHECK_ALIVE(VisitForValue(expr->arguments()->at(0)));
9723 HValue* buffer = Pop();
9724 HInstruction* result = New<HLoadNamedField>(
9726 static_cast<HValue*>(NULL),
9727 HObjectAccess::ForJSArrayBufferViewByteOffset());
9728 return ast_context()->ReturnInstruction(result, expr->id());
9732 void HOptimizedGraphBuilder::GenerateTypedArrayGetLength(
9733 CallRuntime* expr) {
9734 DCHECK(expr->arguments()->length() == 1);
9735 CHECK_ALIVE(VisitForValue(expr->arguments()->at(0)));
9736 HValue* buffer = Pop();
9737 HInstruction* result = New<HLoadNamedField>(
9739 static_cast<HValue*>(NULL),
9740 HObjectAccess::ForJSTypedArrayLength());
9741 return ast_context()->ReturnInstruction(result, expr->id());
9745 void HOptimizedGraphBuilder::VisitCallRuntime(CallRuntime* expr) {
9746 DCHECK(!HasStackOverflow());
9747 DCHECK(current_block() != NULL);
9748 DCHECK(current_block()->HasPredecessor());
9749 if (expr->is_jsruntime()) {
9750 return Bailout(kCallToAJavaScriptRuntimeFunction);
9753 const Runtime::Function* function = expr->function();
9754 DCHECK(function != NULL);
9756 if (function->intrinsic_type == Runtime::INLINE ||
9757 function->intrinsic_type == Runtime::INLINE_OPTIMIZED) {
9758 DCHECK(expr->name()->length() > 0);
9759 DCHECK(expr->name()->Get(0) == '_');
9760 // Call to an inline function.
9761 int lookup_index = static_cast<int>(function->function_id) -
9762 static_cast<int>(Runtime::kFirstInlineFunction);
9763 DCHECK(lookup_index >= 0);
9764 DCHECK(static_cast<size_t>(lookup_index) <
9765 ARRAY_SIZE(kInlineFunctionGenerators));
9766 InlineFunctionGenerator generator = kInlineFunctionGenerators[lookup_index];
9768 // Call the inline code generator using the pointer-to-member.
9769 (this->*generator)(expr);
9771 DCHECK(function->intrinsic_type == Runtime::RUNTIME);
9772 Handle<String> name = expr->name();
9773 int argument_count = expr->arguments()->length();
9774 CHECK_ALIVE(VisitExpressions(expr->arguments()));
9775 PushArgumentsFromEnvironment(argument_count);
9776 HCallRuntime* call = New<HCallRuntime>(name, function,
9778 return ast_context()->ReturnInstruction(call, expr->id());
9783 void HOptimizedGraphBuilder::VisitUnaryOperation(UnaryOperation* expr) {
9784 DCHECK(!HasStackOverflow());
9785 DCHECK(current_block() != NULL);
9786 DCHECK(current_block()->HasPredecessor());
9787 switch (expr->op()) {
9788 case Token::DELETE: return VisitDelete(expr);
9789 case Token::VOID: return VisitVoid(expr);
9790 case Token::TYPEOF: return VisitTypeof(expr);
9791 case Token::NOT: return VisitNot(expr);
9792 default: UNREACHABLE();
9797 void HOptimizedGraphBuilder::VisitDelete(UnaryOperation* expr) {
9798 Property* prop = expr->expression()->AsProperty();
9799 VariableProxy* proxy = expr->expression()->AsVariableProxy();
9801 CHECK_ALIVE(VisitForValue(prop->obj()));
9802 CHECK_ALIVE(VisitForValue(prop->key()));
9803 HValue* key = Pop();
9804 HValue* obj = Pop();
9805 HValue* function = AddLoadJSBuiltin(Builtins::DELETE);
9806 Add<HPushArguments>(obj, key, Add<HConstant>(function_strict_mode()));
9807 // TODO(olivf) InvokeFunction produces a check for the parameter count,
9808 // even though we are certain to pass the correct number of arguments here.
9809 HInstruction* instr = New<HInvokeFunction>(function, 3);
9810 return ast_context()->ReturnInstruction(instr, expr->id());
9811 } else if (proxy != NULL) {
9812 Variable* var = proxy->var();
9813 if (var->IsUnallocated()) {
9814 Bailout(kDeleteWithGlobalVariable);
9815 } else if (var->IsStackAllocated() || var->IsContextSlot()) {
9816 // Result of deleting non-global variables is false. 'this' is not
9817 // really a variable, though we implement it as one. The
9818 // subexpression does not have side effects.
9819 HValue* value = var->is_this()
9820 ? graph()->GetConstantTrue()
9821 : graph()->GetConstantFalse();
9822 return ast_context()->ReturnValue(value);
9824 Bailout(kDeleteWithNonGlobalVariable);
9827 // Result of deleting non-property, non-variable reference is true.
9828 // Evaluate the subexpression for side effects.
9829 CHECK_ALIVE(VisitForEffect(expr->expression()));
9830 return ast_context()->ReturnValue(graph()->GetConstantTrue());
9835 void HOptimizedGraphBuilder::VisitVoid(UnaryOperation* expr) {
9836 CHECK_ALIVE(VisitForEffect(expr->expression()));
9837 return ast_context()->ReturnValue(graph()->GetConstantUndefined());
9841 void HOptimizedGraphBuilder::VisitTypeof(UnaryOperation* expr) {
9842 CHECK_ALIVE(VisitForTypeOf(expr->expression()));
9843 HValue* value = Pop();
9844 HInstruction* instr = New<HTypeof>(value);
9845 return ast_context()->ReturnInstruction(instr, expr->id());
9849 void HOptimizedGraphBuilder::VisitNot(UnaryOperation* expr) {
9850 if (ast_context()->IsTest()) {
9851 TestContext* context = TestContext::cast(ast_context());
9852 VisitForControl(expr->expression(),
9853 context->if_false(),
9854 context->if_true());
9858 if (ast_context()->IsEffect()) {
9859 VisitForEffect(expr->expression());
9863 DCHECK(ast_context()->IsValue());
9864 HBasicBlock* materialize_false = graph()->CreateBasicBlock();
9865 HBasicBlock* materialize_true = graph()->CreateBasicBlock();
9866 CHECK_BAILOUT(VisitForControl(expr->expression(),
9870 if (materialize_false->HasPredecessor()) {
9871 materialize_false->SetJoinId(expr->MaterializeFalseId());
9872 set_current_block(materialize_false);
9873 Push(graph()->GetConstantFalse());
9875 materialize_false = NULL;
9878 if (materialize_true->HasPredecessor()) {
9879 materialize_true->SetJoinId(expr->MaterializeTrueId());
9880 set_current_block(materialize_true);
9881 Push(graph()->GetConstantTrue());
9883 materialize_true = NULL;
9887 CreateJoin(materialize_false, materialize_true, expr->id());
9888 set_current_block(join);
9889 if (join != NULL) return ast_context()->ReturnValue(Pop());
9893 HInstruction* HOptimizedGraphBuilder::BuildIncrement(
9894 bool returns_original_input,
9895 CountOperation* expr) {
9896 // The input to the count operation is on top of the expression stack.
9897 Representation rep = Representation::FromType(expr->type());
9898 if (rep.IsNone() || rep.IsTagged()) {
9899 rep = Representation::Smi();
9902 if (returns_original_input) {
9903 // We need an explicit HValue representing ToNumber(input). The
9904 // actual HChange instruction we need is (sometimes) added in a later
9905 // phase, so it is not available now to be used as an input to HAdd and
9906 // as the return value.
9907 HInstruction* number_input = AddUncasted<HForceRepresentation>(Pop(), rep);
9908 if (!rep.IsDouble()) {
9909 number_input->SetFlag(HInstruction::kFlexibleRepresentation);
9910 number_input->SetFlag(HInstruction::kCannotBeTagged);
9915 // The addition has no side effects, so we do not need
9916 // to simulate the expression stack after this instruction.
9917 // Any later failures deopt to the load of the input or earlier.
9918 HConstant* delta = (expr->op() == Token::INC)
9919 ? graph()->GetConstant1()
9920 : graph()->GetConstantMinus1();
9921 HInstruction* instr = AddUncasted<HAdd>(Top(), delta);
9922 if (instr->IsAdd()) {
9923 HAdd* add = HAdd::cast(instr);
9924 add->set_observed_input_representation(1, rep);
9925 add->set_observed_input_representation(2, Representation::Smi());
9927 instr->SetFlag(HInstruction::kCannotBeTagged);
9928 instr->ClearAllSideEffects();
9933 void HOptimizedGraphBuilder::BuildStoreForEffect(Expression* expr,
9936 BailoutId return_id,
9940 EffectContext for_effect(this);
9942 if (key != NULL) Push(key);
9944 BuildStore(expr, prop, ast_id, return_id);
9948 void HOptimizedGraphBuilder::VisitCountOperation(CountOperation* expr) {
9949 DCHECK(!HasStackOverflow());
9950 DCHECK(current_block() != NULL);
9951 DCHECK(current_block()->HasPredecessor());
9952 if (!FLAG_hydrogen_track_positions) SetSourcePosition(expr->position());
9953 Expression* target = expr->expression();
9954 VariableProxy* proxy = target->AsVariableProxy();
9955 Property* prop = target->AsProperty();
9956 if (proxy == NULL && prop == NULL) {
9957 return Bailout(kInvalidLhsInCountOperation);
9960 // Match the full code generator stack by simulating an extra stack
9961 // element for postfix operations in a non-effect context. The return
9962 // value is ToNumber(input).
9963 bool returns_original_input =
9964 expr->is_postfix() && !ast_context()->IsEffect();
9965 HValue* input = NULL; // ToNumber(original_input).
9966 HValue* after = NULL; // The result after incrementing or decrementing.
9968 if (proxy != NULL) {
9969 Variable* var = proxy->var();
9970 if (var->mode() == CONST_LEGACY) {
9971 return Bailout(kUnsupportedCountOperationWithConst);
9973 // Argument of the count operation is a variable, not a property.
9974 DCHECK(prop == NULL);
9975 CHECK_ALIVE(VisitForValue(target));
9977 after = BuildIncrement(returns_original_input, expr);
9978 input = returns_original_input ? Top() : Pop();
9981 switch (var->location()) {
9982 case Variable::UNALLOCATED:
9983 HandleGlobalVariableAssignment(var,
9985 expr->AssignmentId());
9988 case Variable::PARAMETER:
9989 case Variable::LOCAL:
9990 BindIfLive(var, after);
9993 case Variable::CONTEXT: {
9994 // Bail out if we try to mutate a parameter value in a function
9995 // using the arguments object. We do not (yet) correctly handle the
9996 // arguments property of the function.
9997 if (current_info()->scope()->arguments() != NULL) {
9998 // Parameters will rewrite to context slots. We have no direct
9999 // way to detect that the variable is a parameter so we use a
10000 // linear search of the parameter list.
10001 int count = current_info()->scope()->num_parameters();
10002 for (int i = 0; i < count; ++i) {
10003 if (var == current_info()->scope()->parameter(i)) {
10004 return Bailout(kAssignmentToParameterInArgumentsObject);
10009 HValue* context = BuildContextChainWalk(var);
10010 HStoreContextSlot::Mode mode = IsLexicalVariableMode(var->mode())
10011 ? HStoreContextSlot::kCheckDeoptimize : HStoreContextSlot::kNoCheck;
10012 HStoreContextSlot* instr = Add<HStoreContextSlot>(context, var->index(),
10014 if (instr->HasObservableSideEffects()) {
10015 Add<HSimulate>(expr->AssignmentId(), REMOVABLE_SIMULATE);
10020 case Variable::LOOKUP:
10021 return Bailout(kLookupVariableInCountOperation);
10024 Drop(returns_original_input ? 2 : 1);
10025 return ast_context()->ReturnValue(expr->is_postfix() ? input : after);
10028 // Argument of the count operation is a property.
10029 DCHECK(prop != NULL);
10030 if (returns_original_input) Push(graph()->GetConstantUndefined());
10032 CHECK_ALIVE(VisitForValue(prop->obj()));
10033 HValue* object = Top();
10035 HValue* key = NULL;
10036 if (!prop->key()->IsPropertyName() || prop->IsStringAccess()) {
10037 CHECK_ALIVE(VisitForValue(prop->key()));
10041 CHECK_ALIVE(PushLoad(prop, object, key));
10043 after = BuildIncrement(returns_original_input, expr);
10045 if (returns_original_input) {
10047 // Drop object and key to push it again in the effect context below.
10048 Drop(key == NULL ? 1 : 2);
10049 environment()->SetExpressionStackAt(0, input);
10050 CHECK_ALIVE(BuildStoreForEffect(
10051 expr, prop, expr->id(), expr->AssignmentId(), object, key, after));
10052 return ast_context()->ReturnValue(Pop());
10055 environment()->SetExpressionStackAt(0, after);
10056 return BuildStore(expr, prop, expr->id(), expr->AssignmentId());
10060 HInstruction* HOptimizedGraphBuilder::BuildStringCharCodeAt(
10063 if (string->IsConstant() && index->IsConstant()) {
10064 HConstant* c_string = HConstant::cast(string);
10065 HConstant* c_index = HConstant::cast(index);
10066 if (c_string->HasStringValue() && c_index->HasNumberValue()) {
10067 int32_t i = c_index->NumberValueAsInteger32();
10068 Handle<String> s = c_string->StringValue();
10069 if (i < 0 || i >= s->length()) {
10070 return New<HConstant>(base::OS::nan_value());
10072 return New<HConstant>(s->Get(i));
10075 string = BuildCheckString(string);
10076 index = Add<HBoundsCheck>(index, AddLoadStringLength(string));
10077 return New<HStringCharCodeAt>(string, index);
10081 // Checks if the given shift amounts have following forms:
10082 // (N1) and (N2) with N1 + N2 = 32; (sa) and (32 - sa).
10083 static bool ShiftAmountsAllowReplaceByRotate(HValue* sa,
10084 HValue* const32_minus_sa) {
10085 if (sa->IsConstant() && const32_minus_sa->IsConstant()) {
10086 const HConstant* c1 = HConstant::cast(sa);
10087 const HConstant* c2 = HConstant::cast(const32_minus_sa);
10088 return c1->HasInteger32Value() && c2->HasInteger32Value() &&
10089 (c1->Integer32Value() + c2->Integer32Value() == 32);
10091 if (!const32_minus_sa->IsSub()) return false;
10092 HSub* sub = HSub::cast(const32_minus_sa);
10093 return sub->left()->EqualsInteger32Constant(32) && sub->right() == sa;
10097 // Checks if the left and the right are shift instructions with the oposite
10098 // directions that can be replaced by one rotate right instruction or not.
10099 // Returns the operand and the shift amount for the rotate instruction in the
10101 bool HGraphBuilder::MatchRotateRight(HValue* left,
10104 HValue** shift_amount) {
10107 if (left->IsShl() && right->IsShr()) {
10108 shl = HShl::cast(left);
10109 shr = HShr::cast(right);
10110 } else if (left->IsShr() && right->IsShl()) {
10111 shl = HShl::cast(right);
10112 shr = HShr::cast(left);
10116 if (shl->left() != shr->left()) return false;
10118 if (!ShiftAmountsAllowReplaceByRotate(shl->right(), shr->right()) &&
10119 !ShiftAmountsAllowReplaceByRotate(shr->right(), shl->right())) {
10122 *operand= shr->left();
10123 *shift_amount = shr->right();
10128 bool CanBeZero(HValue* right) {
10129 if (right->IsConstant()) {
10130 HConstant* right_const = HConstant::cast(right);
10131 if (right_const->HasInteger32Value() &&
10132 (right_const->Integer32Value() & 0x1f) != 0) {
10140 HValue* HGraphBuilder::EnforceNumberType(HValue* number,
10142 if (expected->Is(Type::SignedSmall())) {
10143 return AddUncasted<HForceRepresentation>(number, Representation::Smi());
10145 if (expected->Is(Type::Signed32())) {
10146 return AddUncasted<HForceRepresentation>(number,
10147 Representation::Integer32());
10153 HValue* HGraphBuilder::TruncateToNumber(HValue* value, Type** expected) {
10154 if (value->IsConstant()) {
10155 HConstant* constant = HConstant::cast(value);
10156 Maybe<HConstant*> number = constant->CopyToTruncatedNumber(zone());
10157 if (number.has_value) {
10158 *expected = Type::Number(zone());
10159 return AddInstruction(number.value);
10163 // We put temporary values on the stack, which don't correspond to anything
10164 // in baseline code. Since nothing is observable we avoid recording those
10165 // pushes with a NoObservableSideEffectsScope.
10166 NoObservableSideEffectsScope no_effects(this);
10168 Type* expected_type = *expected;
10170 // Separate the number type from the rest.
10171 Type* expected_obj =
10172 Type::Intersect(expected_type, Type::NonNumber(zone()), zone());
10173 Type* expected_number =
10174 Type::Intersect(expected_type, Type::Number(zone()), zone());
10176 // We expect to get a number.
10177 // (We need to check first, since Type::None->Is(Type::Any()) == true.
10178 if (expected_obj->Is(Type::None())) {
10179 DCHECK(!expected_number->Is(Type::None(zone())));
10183 if (expected_obj->Is(Type::Undefined(zone()))) {
10184 // This is already done by HChange.
10185 *expected = Type::Union(expected_number, Type::Number(zone()), zone());
10193 HValue* HOptimizedGraphBuilder::BuildBinaryOperation(
10194 BinaryOperation* expr,
10197 PushBeforeSimulateBehavior push_sim_result) {
10198 Type* left_type = expr->left()->bounds().lower;
10199 Type* right_type = expr->right()->bounds().lower;
10200 Type* result_type = expr->bounds().lower;
10201 Maybe<int> fixed_right_arg = expr->fixed_right_arg();
10202 Handle<AllocationSite> allocation_site = expr->allocation_site();
10204 HAllocationMode allocation_mode;
10205 if (FLAG_allocation_site_pretenuring && !allocation_site.is_null()) {
10206 allocation_mode = HAllocationMode(allocation_site);
10209 HValue* result = HGraphBuilder::BuildBinaryOperation(
10210 expr->op(), left, right, left_type, right_type, result_type,
10211 fixed_right_arg, allocation_mode);
10212 // Add a simulate after instructions with observable side effects, and
10213 // after phis, which are the result of BuildBinaryOperation when we
10214 // inlined some complex subgraph.
10215 if (result->HasObservableSideEffects() || result->IsPhi()) {
10216 if (push_sim_result == PUSH_BEFORE_SIMULATE) {
10218 Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
10221 Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
10228 HValue* HGraphBuilder::BuildBinaryOperation(
10235 Maybe<int> fixed_right_arg,
10236 HAllocationMode allocation_mode) {
10238 Representation left_rep = Representation::FromType(left_type);
10239 Representation right_rep = Representation::FromType(right_type);
10241 bool maybe_string_add = op == Token::ADD &&
10242 (left_type->Maybe(Type::String()) ||
10243 left_type->Maybe(Type::Receiver()) ||
10244 right_type->Maybe(Type::String()) ||
10245 right_type->Maybe(Type::Receiver()));
10247 if (left_type->Is(Type::None())) {
10248 Add<HDeoptimize>("Insufficient type feedback for LHS of binary operation",
10249 Deoptimizer::SOFT);
10250 // TODO(rossberg): we should be able to get rid of non-continuous
10252 left_type = Type::Any(zone());
10254 if (!maybe_string_add) left = TruncateToNumber(left, &left_type);
10255 left_rep = Representation::FromType(left_type);
10258 if (right_type->Is(Type::None())) {
10259 Add<HDeoptimize>("Insufficient type feedback for RHS of binary operation",
10260 Deoptimizer::SOFT);
10261 right_type = Type::Any(zone());
10263 if (!maybe_string_add) right = TruncateToNumber(right, &right_type);
10264 right_rep = Representation::FromType(right_type);
10267 // Special case for string addition here.
10268 if (op == Token::ADD &&
10269 (left_type->Is(Type::String()) || right_type->Is(Type::String()))) {
10270 // Validate type feedback for left argument.
10271 if (left_type->Is(Type::String())) {
10272 left = BuildCheckString(left);
10275 // Validate type feedback for right argument.
10276 if (right_type->Is(Type::String())) {
10277 right = BuildCheckString(right);
10280 // Convert left argument as necessary.
10281 if (left_type->Is(Type::Number())) {
10282 DCHECK(right_type->Is(Type::String()));
10283 left = BuildNumberToString(left, left_type);
10284 } else if (!left_type->Is(Type::String())) {
10285 DCHECK(right_type->Is(Type::String()));
10286 HValue* function = AddLoadJSBuiltin(Builtins::STRING_ADD_RIGHT);
10287 Add<HPushArguments>(left, right);
10288 return AddUncasted<HInvokeFunction>(function, 2);
10291 // Convert right argument as necessary.
10292 if (right_type->Is(Type::Number())) {
10293 DCHECK(left_type->Is(Type::String()));
10294 right = BuildNumberToString(right, right_type);
10295 } else if (!right_type->Is(Type::String())) {
10296 DCHECK(left_type->Is(Type::String()));
10297 HValue* function = AddLoadJSBuiltin(Builtins::STRING_ADD_LEFT);
10298 Add<HPushArguments>(left, right);
10299 return AddUncasted<HInvokeFunction>(function, 2);
10302 // Fast path for empty constant strings.
10303 if (left->IsConstant() &&
10304 HConstant::cast(left)->HasStringValue() &&
10305 HConstant::cast(left)->StringValue()->length() == 0) {
10308 if (right->IsConstant() &&
10309 HConstant::cast(right)->HasStringValue() &&
10310 HConstant::cast(right)->StringValue()->length() == 0) {
10314 // Register the dependent code with the allocation site.
10315 if (!allocation_mode.feedback_site().is_null()) {
10316 DCHECK(!graph()->info()->IsStub());
10317 Handle<AllocationSite> site(allocation_mode.feedback_site());
10318 AllocationSite::AddDependentCompilationInfo(
10319 site, AllocationSite::TENURING, top_info());
10322 // Inline the string addition into the stub when creating allocation
10323 // mementos to gather allocation site feedback, or if we can statically
10324 // infer that we're going to create a cons string.
10325 if ((graph()->info()->IsStub() &&
10326 allocation_mode.CreateAllocationMementos()) ||
10327 (left->IsConstant() &&
10328 HConstant::cast(left)->HasStringValue() &&
10329 HConstant::cast(left)->StringValue()->length() + 1 >=
10330 ConsString::kMinLength) ||
10331 (right->IsConstant() &&
10332 HConstant::cast(right)->HasStringValue() &&
10333 HConstant::cast(right)->StringValue()->length() + 1 >=
10334 ConsString::kMinLength)) {
10335 return BuildStringAdd(left, right, allocation_mode);
10338 // Fallback to using the string add stub.
10339 return AddUncasted<HStringAdd>(
10340 left, right, allocation_mode.GetPretenureMode(),
10341 STRING_ADD_CHECK_NONE, allocation_mode.feedback_site());
10344 if (graph()->info()->IsStub()) {
10345 left = EnforceNumberType(left, left_type);
10346 right = EnforceNumberType(right, right_type);
10349 Representation result_rep = Representation::FromType(result_type);
10351 bool is_non_primitive = (left_rep.IsTagged() && !left_rep.IsSmi()) ||
10352 (right_rep.IsTagged() && !right_rep.IsSmi());
10354 HInstruction* instr = NULL;
10355 // Only the stub is allowed to call into the runtime, since otherwise we would
10356 // inline several instructions (including the two pushes) for every tagged
10357 // operation in optimized code, which is more expensive, than a stub call.
10358 if (graph()->info()->IsStub() && is_non_primitive) {
10359 HValue* function = AddLoadJSBuiltin(BinaryOpIC::TokenToJSBuiltin(op));
10360 Add<HPushArguments>(left, right);
10361 instr = AddUncasted<HInvokeFunction>(function, 2);
10365 instr = AddUncasted<HAdd>(left, right);
10368 instr = AddUncasted<HSub>(left, right);
10371 instr = AddUncasted<HMul>(left, right);
10374 if (fixed_right_arg.has_value &&
10375 !right->EqualsInteger32Constant(fixed_right_arg.value)) {
10376 HConstant* fixed_right = Add<HConstant>(
10377 static_cast<int>(fixed_right_arg.value));
10378 IfBuilder if_same(this);
10379 if_same.If<HCompareNumericAndBranch>(right, fixed_right, Token::EQ);
10381 if_same.ElseDeopt("Unexpected RHS of binary operation");
10382 right = fixed_right;
10384 instr = AddUncasted<HMod>(left, right);
10388 instr = AddUncasted<HDiv>(left, right);
10390 case Token::BIT_XOR:
10391 case Token::BIT_AND:
10392 instr = AddUncasted<HBitwise>(op, left, right);
10394 case Token::BIT_OR: {
10395 HValue* operand, *shift_amount;
10396 if (left_type->Is(Type::Signed32()) &&
10397 right_type->Is(Type::Signed32()) &&
10398 MatchRotateRight(left, right, &operand, &shift_amount)) {
10399 instr = AddUncasted<HRor>(operand, shift_amount);
10401 instr = AddUncasted<HBitwise>(op, left, right);
10406 instr = AddUncasted<HSar>(left, right);
10409 instr = AddUncasted<HShr>(left, right);
10410 if (FLAG_opt_safe_uint32_operations && instr->IsShr() &&
10411 CanBeZero(right)) {
10412 graph()->RecordUint32Instruction(instr);
10416 instr = AddUncasted<HShl>(left, right);
10423 if (instr->IsBinaryOperation()) {
10424 HBinaryOperation* binop = HBinaryOperation::cast(instr);
10425 binop->set_observed_input_representation(1, left_rep);
10426 binop->set_observed_input_representation(2, right_rep);
10427 binop->initialize_output_representation(result_rep);
10428 if (graph()->info()->IsStub()) {
10429 // Stub should not call into stub.
10430 instr->SetFlag(HValue::kCannotBeTagged);
10431 // And should truncate on HForceRepresentation already.
10432 if (left->IsForceRepresentation()) {
10433 left->CopyFlag(HValue::kTruncatingToSmi, instr);
10434 left->CopyFlag(HValue::kTruncatingToInt32, instr);
10436 if (right->IsForceRepresentation()) {
10437 right->CopyFlag(HValue::kTruncatingToSmi, instr);
10438 right->CopyFlag(HValue::kTruncatingToInt32, instr);
10446 // Check for the form (%_ClassOf(foo) === 'BarClass').
10447 static bool IsClassOfTest(CompareOperation* expr) {
10448 if (expr->op() != Token::EQ_STRICT) return false;
10449 CallRuntime* call = expr->left()->AsCallRuntime();
10450 if (call == NULL) return false;
10451 Literal* literal = expr->right()->AsLiteral();
10452 if (literal == NULL) return false;
10453 if (!literal->value()->IsString()) return false;
10454 if (!call->name()->IsOneByteEqualTo(STATIC_ASCII_VECTOR("_ClassOf"))) {
10457 DCHECK(call->arguments()->length() == 1);
10462 void HOptimizedGraphBuilder::VisitBinaryOperation(BinaryOperation* expr) {
10463 DCHECK(!HasStackOverflow());
10464 DCHECK(current_block() != NULL);
10465 DCHECK(current_block()->HasPredecessor());
10466 switch (expr->op()) {
10468 return VisitComma(expr);
10471 return VisitLogicalExpression(expr);
10473 return VisitArithmeticExpression(expr);
10478 void HOptimizedGraphBuilder::VisitComma(BinaryOperation* expr) {
10479 CHECK_ALIVE(VisitForEffect(expr->left()));
10480 // Visit the right subexpression in the same AST context as the entire
10482 Visit(expr->right());
10486 void HOptimizedGraphBuilder::VisitLogicalExpression(BinaryOperation* expr) {
10487 bool is_logical_and = expr->op() == Token::AND;
10488 if (ast_context()->IsTest()) {
10489 TestContext* context = TestContext::cast(ast_context());
10490 // Translate left subexpression.
10491 HBasicBlock* eval_right = graph()->CreateBasicBlock();
10492 if (is_logical_and) {
10493 CHECK_BAILOUT(VisitForControl(expr->left(),
10495 context->if_false()));
10497 CHECK_BAILOUT(VisitForControl(expr->left(),
10498 context->if_true(),
10502 // Translate right subexpression by visiting it in the same AST
10503 // context as the entire expression.
10504 if (eval_right->HasPredecessor()) {
10505 eval_right->SetJoinId(expr->RightId());
10506 set_current_block(eval_right);
10507 Visit(expr->right());
10510 } else if (ast_context()->IsValue()) {
10511 CHECK_ALIVE(VisitForValue(expr->left()));
10512 DCHECK(current_block() != NULL);
10513 HValue* left_value = Top();
10515 // Short-circuit left values that always evaluate to the same boolean value.
10516 if (expr->left()->ToBooleanIsTrue() || expr->left()->ToBooleanIsFalse()) {
10517 // l (evals true) && r -> r
10518 // l (evals true) || r -> l
10519 // l (evals false) && r -> l
10520 // l (evals false) || r -> r
10521 if (is_logical_and == expr->left()->ToBooleanIsTrue()) {
10523 CHECK_ALIVE(VisitForValue(expr->right()));
10525 return ast_context()->ReturnValue(Pop());
10528 // We need an extra block to maintain edge-split form.
10529 HBasicBlock* empty_block = graph()->CreateBasicBlock();
10530 HBasicBlock* eval_right = graph()->CreateBasicBlock();
10531 ToBooleanStub::Types expected(expr->left()->to_boolean_types());
10532 HBranch* test = is_logical_and
10533 ? New<HBranch>(left_value, expected, eval_right, empty_block)
10534 : New<HBranch>(left_value, expected, empty_block, eval_right);
10535 FinishCurrentBlock(test);
10537 set_current_block(eval_right);
10538 Drop(1); // Value of the left subexpression.
10539 CHECK_BAILOUT(VisitForValue(expr->right()));
10541 HBasicBlock* join_block =
10542 CreateJoin(empty_block, current_block(), expr->id());
10543 set_current_block(join_block);
10544 return ast_context()->ReturnValue(Pop());
10547 DCHECK(ast_context()->IsEffect());
10548 // In an effect context, we don't need the value of the left subexpression,
10549 // only its control flow and side effects. We need an extra block to
10550 // maintain edge-split form.
10551 HBasicBlock* empty_block = graph()->CreateBasicBlock();
10552 HBasicBlock* right_block = graph()->CreateBasicBlock();
10553 if (is_logical_and) {
10554 CHECK_BAILOUT(VisitForControl(expr->left(), right_block, empty_block));
10556 CHECK_BAILOUT(VisitForControl(expr->left(), empty_block, right_block));
10559 // TODO(kmillikin): Find a way to fix this. It's ugly that there are
10560 // actually two empty blocks (one here and one inserted by
10561 // TestContext::BuildBranch, and that they both have an HSimulate though the
10562 // second one is not a merge node, and that we really have no good AST ID to
10563 // put on that first HSimulate.
10565 if (empty_block->HasPredecessor()) {
10566 empty_block->SetJoinId(expr->id());
10568 empty_block = NULL;
10571 if (right_block->HasPredecessor()) {
10572 right_block->SetJoinId(expr->RightId());
10573 set_current_block(right_block);
10574 CHECK_BAILOUT(VisitForEffect(expr->right()));
10575 right_block = current_block();
10577 right_block = NULL;
10580 HBasicBlock* join_block =
10581 CreateJoin(empty_block, right_block, expr->id());
10582 set_current_block(join_block);
10583 // We did not materialize any value in the predecessor environments,
10584 // so there is no need to handle it here.
10589 void HOptimizedGraphBuilder::VisitArithmeticExpression(BinaryOperation* expr) {
10590 CHECK_ALIVE(VisitForValue(expr->left()));
10591 CHECK_ALIVE(VisitForValue(expr->right()));
10592 SetSourcePosition(expr->position());
10593 HValue* right = Pop();
10594 HValue* left = Pop();
10596 BuildBinaryOperation(expr, left, right,
10597 ast_context()->IsEffect() ? NO_PUSH_BEFORE_SIMULATE
10598 : PUSH_BEFORE_SIMULATE);
10599 if (FLAG_hydrogen_track_positions && result->IsBinaryOperation()) {
10600 HBinaryOperation::cast(result)->SetOperandPositions(
10602 ScriptPositionToSourcePosition(expr->left()->position()),
10603 ScriptPositionToSourcePosition(expr->right()->position()));
10605 return ast_context()->ReturnValue(result);
10609 void HOptimizedGraphBuilder::HandleLiteralCompareTypeof(CompareOperation* expr,
10610 Expression* sub_expr,
10611 Handle<String> check) {
10612 CHECK_ALIVE(VisitForTypeOf(sub_expr));
10613 SetSourcePosition(expr->position());
10614 HValue* value = Pop();
10615 HTypeofIsAndBranch* instr = New<HTypeofIsAndBranch>(value, check);
10616 return ast_context()->ReturnControl(instr, expr->id());
10620 static bool IsLiteralCompareBool(Isolate* isolate,
10624 return op == Token::EQ_STRICT &&
10625 ((left->IsConstant() &&
10626 HConstant::cast(left)->handle(isolate)->IsBoolean()) ||
10627 (right->IsConstant() &&
10628 HConstant::cast(right)->handle(isolate)->IsBoolean()));
10632 void HOptimizedGraphBuilder::VisitCompareOperation(CompareOperation* expr) {
10633 DCHECK(!HasStackOverflow());
10634 DCHECK(current_block() != NULL);
10635 DCHECK(current_block()->HasPredecessor());
10637 if (!FLAG_hydrogen_track_positions) SetSourcePosition(expr->position());
10639 // Check for a few fast cases. The AST visiting behavior must be in sync
10640 // with the full codegen: We don't push both left and right values onto
10641 // the expression stack when one side is a special-case literal.
10642 Expression* sub_expr = NULL;
10643 Handle<String> check;
10644 if (expr->IsLiteralCompareTypeof(&sub_expr, &check)) {
10645 return HandleLiteralCompareTypeof(expr, sub_expr, check);
10647 if (expr->IsLiteralCompareUndefined(&sub_expr, isolate())) {
10648 return HandleLiteralCompareNil(expr, sub_expr, kUndefinedValue);
10650 if (expr->IsLiteralCompareNull(&sub_expr)) {
10651 return HandleLiteralCompareNil(expr, sub_expr, kNullValue);
10654 if (IsClassOfTest(expr)) {
10655 CallRuntime* call = expr->left()->AsCallRuntime();
10656 DCHECK(call->arguments()->length() == 1);
10657 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
10658 HValue* value = Pop();
10659 Literal* literal = expr->right()->AsLiteral();
10660 Handle<String> rhs = Handle<String>::cast(literal->value());
10661 HClassOfTestAndBranch* instr = New<HClassOfTestAndBranch>(value, rhs);
10662 return ast_context()->ReturnControl(instr, expr->id());
10665 Type* left_type = expr->left()->bounds().lower;
10666 Type* right_type = expr->right()->bounds().lower;
10667 Type* combined_type = expr->combined_type();
10669 CHECK_ALIVE(VisitForValue(expr->left()));
10670 CHECK_ALIVE(VisitForValue(expr->right()));
10672 if (FLAG_hydrogen_track_positions) SetSourcePosition(expr->position());
10674 HValue* right = Pop();
10675 HValue* left = Pop();
10676 Token::Value op = expr->op();
10678 if (IsLiteralCompareBool(isolate(), left, op, right)) {
10679 HCompareObjectEqAndBranch* result =
10680 New<HCompareObjectEqAndBranch>(left, right);
10681 return ast_context()->ReturnControl(result, expr->id());
10684 if (op == Token::INSTANCEOF) {
10685 // Check to see if the rhs of the instanceof is a global function not
10686 // residing in new space. If it is we assume that the function will stay the
10688 Handle<JSFunction> target = Handle<JSFunction>::null();
10689 VariableProxy* proxy = expr->right()->AsVariableProxy();
10690 bool global_function = (proxy != NULL) && proxy->var()->IsUnallocated();
10691 if (global_function &&
10692 current_info()->has_global_object() &&
10693 !current_info()->global_object()->IsAccessCheckNeeded()) {
10694 Handle<String> name = proxy->name();
10695 Handle<GlobalObject> global(current_info()->global_object());
10696 LookupResult lookup(isolate());
10697 global->Lookup(name, &lookup);
10698 if (lookup.IsNormal() && lookup.GetValue()->IsJSFunction()) {
10699 Handle<JSFunction> candidate(JSFunction::cast(lookup.GetValue()));
10700 // If the function is in new space we assume it's more likely to
10701 // change and thus prefer the general IC code.
10702 if (!isolate()->heap()->InNewSpace(*candidate)) {
10703 target = candidate;
10708 // If the target is not null we have found a known global function that is
10709 // assumed to stay the same for this instanceof.
10710 if (target.is_null()) {
10711 HInstanceOf* result = New<HInstanceOf>(left, right);
10712 return ast_context()->ReturnInstruction(result, expr->id());
10714 Add<HCheckValue>(right, target);
10715 HInstanceOfKnownGlobal* result =
10716 New<HInstanceOfKnownGlobal>(left, target);
10717 return ast_context()->ReturnInstruction(result, expr->id());
10720 // Code below assumes that we don't fall through.
10722 } else if (op == Token::IN) {
10723 HValue* function = AddLoadJSBuiltin(Builtins::IN);
10724 Add<HPushArguments>(left, right);
10725 // TODO(olivf) InvokeFunction produces a check for the parameter count,
10726 // even though we are certain to pass the correct number of arguments here.
10727 HInstruction* result = New<HInvokeFunction>(function, 2);
10728 return ast_context()->ReturnInstruction(result, expr->id());
10731 PushBeforeSimulateBehavior push_behavior =
10732 ast_context()->IsEffect() ? NO_PUSH_BEFORE_SIMULATE
10733 : PUSH_BEFORE_SIMULATE;
10734 HControlInstruction* compare = BuildCompareInstruction(
10735 op, left, right, left_type, right_type, combined_type,
10736 ScriptPositionToSourcePosition(expr->left()->position()),
10737 ScriptPositionToSourcePosition(expr->right()->position()),
10738 push_behavior, expr->id());
10739 if (compare == NULL) return; // Bailed out.
10740 return ast_context()->ReturnControl(compare, expr->id());
10744 HControlInstruction* HOptimizedGraphBuilder::BuildCompareInstruction(
10750 Type* combined_type,
10751 HSourcePosition left_position,
10752 HSourcePosition right_position,
10753 PushBeforeSimulateBehavior push_sim_result,
10754 BailoutId bailout_id) {
10755 // Cases handled below depend on collected type feedback. They should
10756 // soft deoptimize when there is no type feedback.
10757 if (combined_type->Is(Type::None())) {
10758 Add<HDeoptimize>("Insufficient type feedback for combined type "
10759 "of binary operation",
10760 Deoptimizer::SOFT);
10761 combined_type = left_type = right_type = Type::Any(zone());
10764 Representation left_rep = Representation::FromType(left_type);
10765 Representation right_rep = Representation::FromType(right_type);
10766 Representation combined_rep = Representation::FromType(combined_type);
10768 if (combined_type->Is(Type::Receiver())) {
10769 if (Token::IsEqualityOp(op)) {
10770 // HCompareObjectEqAndBranch can only deal with object, so
10771 // exclude numbers.
10772 if ((left->IsConstant() &&
10773 HConstant::cast(left)->HasNumberValue()) ||
10774 (right->IsConstant() &&
10775 HConstant::cast(right)->HasNumberValue())) {
10776 Add<HDeoptimize>("Type mismatch between feedback and constant",
10777 Deoptimizer::SOFT);
10778 // The caller expects a branch instruction, so make it happy.
10779 return New<HBranch>(graph()->GetConstantTrue());
10781 // Can we get away with map check and not instance type check?
10782 HValue* operand_to_check =
10783 left->block()->block_id() < right->block()->block_id() ? left : right;
10784 if (combined_type->IsClass()) {
10785 Handle<Map> map = combined_type->AsClass()->Map();
10786 AddCheckMap(operand_to_check, map);
10787 HCompareObjectEqAndBranch* result =
10788 New<HCompareObjectEqAndBranch>(left, right);
10789 if (FLAG_hydrogen_track_positions) {
10790 result->set_operand_position(zone(), 0, left_position);
10791 result->set_operand_position(zone(), 1, right_position);
10795 BuildCheckHeapObject(operand_to_check);
10796 Add<HCheckInstanceType>(operand_to_check,
10797 HCheckInstanceType::IS_SPEC_OBJECT);
10798 HCompareObjectEqAndBranch* result =
10799 New<HCompareObjectEqAndBranch>(left, right);
10803 Bailout(kUnsupportedNonPrimitiveCompare);
10806 } else if (combined_type->Is(Type::InternalizedString()) &&
10807 Token::IsEqualityOp(op)) {
10808 // If we have a constant argument, it should be consistent with the type
10809 // feedback (otherwise we fail assertions in HCompareObjectEqAndBranch).
10810 if ((left->IsConstant() &&
10811 !HConstant::cast(left)->HasInternalizedStringValue()) ||
10812 (right->IsConstant() &&
10813 !HConstant::cast(right)->HasInternalizedStringValue())) {
10814 Add<HDeoptimize>("Type mismatch between feedback and constant",
10815 Deoptimizer::SOFT);
10816 // The caller expects a branch instruction, so make it happy.
10817 return New<HBranch>(graph()->GetConstantTrue());
10819 BuildCheckHeapObject(left);
10820 Add<HCheckInstanceType>(left, HCheckInstanceType::IS_INTERNALIZED_STRING);
10821 BuildCheckHeapObject(right);
10822 Add<HCheckInstanceType>(right, HCheckInstanceType::IS_INTERNALIZED_STRING);
10823 HCompareObjectEqAndBranch* result =
10824 New<HCompareObjectEqAndBranch>(left, right);
10826 } else if (combined_type->Is(Type::String())) {
10827 BuildCheckHeapObject(left);
10828 Add<HCheckInstanceType>(left, HCheckInstanceType::IS_STRING);
10829 BuildCheckHeapObject(right);
10830 Add<HCheckInstanceType>(right, HCheckInstanceType::IS_STRING);
10831 HStringCompareAndBranch* result =
10832 New<HStringCompareAndBranch>(left, right, op);
10835 if (combined_rep.IsTagged() || combined_rep.IsNone()) {
10836 HCompareGeneric* result = Add<HCompareGeneric>(left, right, op);
10837 result->set_observed_input_representation(1, left_rep);
10838 result->set_observed_input_representation(2, right_rep);
10839 if (result->HasObservableSideEffects()) {
10840 if (push_sim_result == PUSH_BEFORE_SIMULATE) {
10842 AddSimulate(bailout_id, REMOVABLE_SIMULATE);
10845 AddSimulate(bailout_id, REMOVABLE_SIMULATE);
10848 // TODO(jkummerow): Can we make this more efficient?
10849 HBranch* branch = New<HBranch>(result);
10852 HCompareNumericAndBranch* result =
10853 New<HCompareNumericAndBranch>(left, right, op);
10854 result->set_observed_input_representation(left_rep, right_rep);
10855 if (FLAG_hydrogen_track_positions) {
10856 result->SetOperandPositions(zone(), left_position, right_position);
10864 void HOptimizedGraphBuilder::HandleLiteralCompareNil(CompareOperation* expr,
10865 Expression* sub_expr,
10867 DCHECK(!HasStackOverflow());
10868 DCHECK(current_block() != NULL);
10869 DCHECK(current_block()->HasPredecessor());
10870 DCHECK(expr->op() == Token::EQ || expr->op() == Token::EQ_STRICT);
10871 if (!FLAG_hydrogen_track_positions) SetSourcePosition(expr->position());
10872 CHECK_ALIVE(VisitForValue(sub_expr));
10873 HValue* value = Pop();
10874 if (expr->op() == Token::EQ_STRICT) {
10875 HConstant* nil_constant = nil == kNullValue
10876 ? graph()->GetConstantNull()
10877 : graph()->GetConstantUndefined();
10878 HCompareObjectEqAndBranch* instr =
10879 New<HCompareObjectEqAndBranch>(value, nil_constant);
10880 return ast_context()->ReturnControl(instr, expr->id());
10882 DCHECK_EQ(Token::EQ, expr->op());
10883 Type* type = expr->combined_type()->Is(Type::None())
10884 ? Type::Any(zone()) : expr->combined_type();
10885 HIfContinuation continuation;
10886 BuildCompareNil(value, type, &continuation);
10887 return ast_context()->ReturnContinuation(&continuation, expr->id());
10892 HInstruction* HOptimizedGraphBuilder::BuildThisFunction() {
10893 // If we share optimized code between different closures, the
10894 // this-function is not a constant, except inside an inlined body.
10895 if (function_state()->outer() != NULL) {
10896 return New<HConstant>(
10897 function_state()->compilation_info()->closure());
10899 return New<HThisFunction>();
10904 HInstruction* HOptimizedGraphBuilder::BuildFastLiteral(
10905 Handle<JSObject> boilerplate_object,
10906 AllocationSiteUsageContext* site_context) {
10907 NoObservableSideEffectsScope no_effects(this);
10908 InstanceType instance_type = boilerplate_object->map()->instance_type();
10909 DCHECK(instance_type == JS_ARRAY_TYPE || instance_type == JS_OBJECT_TYPE);
10911 HType type = instance_type == JS_ARRAY_TYPE
10912 ? HType::JSArray() : HType::JSObject();
10913 HValue* object_size_constant = Add<HConstant>(
10914 boilerplate_object->map()->instance_size());
10916 PretenureFlag pretenure_flag = NOT_TENURED;
10917 if (FLAG_allocation_site_pretenuring) {
10918 pretenure_flag = site_context->current()->GetPretenureMode();
10919 Handle<AllocationSite> site(site_context->current());
10920 AllocationSite::AddDependentCompilationInfo(
10921 site, AllocationSite::TENURING, top_info());
10924 HInstruction* object = Add<HAllocate>(object_size_constant, type,
10925 pretenure_flag, instance_type, site_context->current());
10927 // If allocation folding reaches Page::kMaxRegularHeapObjectSize the
10928 // elements array may not get folded into the object. Hence, we set the
10929 // elements pointer to empty fixed array and let store elimination remove
10930 // this store in the folding case.
10931 HConstant* empty_fixed_array = Add<HConstant>(
10932 isolate()->factory()->empty_fixed_array());
10933 Add<HStoreNamedField>(object, HObjectAccess::ForElementsPointer(),
10934 empty_fixed_array);
10936 BuildEmitObjectHeader(boilerplate_object, object);
10938 Handle<FixedArrayBase> elements(boilerplate_object->elements());
10939 int elements_size = (elements->length() > 0 &&
10940 elements->map() != isolate()->heap()->fixed_cow_array_map()) ?
10941 elements->Size() : 0;
10943 if (pretenure_flag == TENURED &&
10944 elements->map() == isolate()->heap()->fixed_cow_array_map() &&
10945 isolate()->heap()->InNewSpace(*elements)) {
10946 // If we would like to pretenure a fixed cow array, we must ensure that the
10947 // array is already in old space, otherwise we'll create too many old-to-
10948 // new-space pointers (overflowing the store buffer).
10949 elements = Handle<FixedArrayBase>(
10950 isolate()->factory()->CopyAndTenureFixedCOWArray(
10951 Handle<FixedArray>::cast(elements)));
10952 boilerplate_object->set_elements(*elements);
10955 HInstruction* object_elements = NULL;
10956 if (elements_size > 0) {
10957 HValue* object_elements_size = Add<HConstant>(elements_size);
10958 InstanceType instance_type = boilerplate_object->HasFastDoubleElements()
10959 ? FIXED_DOUBLE_ARRAY_TYPE : FIXED_ARRAY_TYPE;
10960 object_elements = Add<HAllocate>(
10961 object_elements_size, HType::HeapObject(),
10962 pretenure_flag, instance_type, site_context->current());
10964 BuildInitElementsInObjectHeader(boilerplate_object, object, object_elements);
10966 // Copy object elements if non-COW.
10967 if (object_elements != NULL) {
10968 BuildEmitElements(boilerplate_object, elements, object_elements,
10972 // Copy in-object properties.
10973 if (boilerplate_object->map()->NumberOfFields() != 0) {
10974 BuildEmitInObjectProperties(boilerplate_object, object, site_context,
10981 void HOptimizedGraphBuilder::BuildEmitObjectHeader(
10982 Handle<JSObject> boilerplate_object,
10983 HInstruction* object) {
10984 DCHECK(boilerplate_object->properties()->length() == 0);
10986 Handle<Map> boilerplate_object_map(boilerplate_object->map());
10987 AddStoreMapConstant(object, boilerplate_object_map);
10989 Handle<Object> properties_field =
10990 Handle<Object>(boilerplate_object->properties(), isolate());
10991 DCHECK(*properties_field == isolate()->heap()->empty_fixed_array());
10992 HInstruction* properties = Add<HConstant>(properties_field);
10993 HObjectAccess access = HObjectAccess::ForPropertiesPointer();
10994 Add<HStoreNamedField>(object, access, properties);
10996 if (boilerplate_object->IsJSArray()) {
10997 Handle<JSArray> boilerplate_array =
10998 Handle<JSArray>::cast(boilerplate_object);
10999 Handle<Object> length_field =
11000 Handle<Object>(boilerplate_array->length(), isolate());
11001 HInstruction* length = Add<HConstant>(length_field);
11003 DCHECK(boilerplate_array->length()->IsSmi());
11004 Add<HStoreNamedField>(object, HObjectAccess::ForArrayLength(
11005 boilerplate_array->GetElementsKind()), length);
11010 void HOptimizedGraphBuilder::BuildInitElementsInObjectHeader(
11011 Handle<JSObject> boilerplate_object,
11012 HInstruction* object,
11013 HInstruction* object_elements) {
11014 DCHECK(boilerplate_object->properties()->length() == 0);
11015 if (object_elements == NULL) {
11016 Handle<Object> elements_field =
11017 Handle<Object>(boilerplate_object->elements(), isolate());
11018 object_elements = Add<HConstant>(elements_field);
11020 Add<HStoreNamedField>(object, HObjectAccess::ForElementsPointer(),
11025 void HOptimizedGraphBuilder::BuildEmitInObjectProperties(
11026 Handle<JSObject> boilerplate_object,
11027 HInstruction* object,
11028 AllocationSiteUsageContext* site_context,
11029 PretenureFlag pretenure_flag) {
11030 Handle<Map> boilerplate_map(boilerplate_object->map());
11031 Handle<DescriptorArray> descriptors(boilerplate_map->instance_descriptors());
11032 int limit = boilerplate_map->NumberOfOwnDescriptors();
11034 int copied_fields = 0;
11035 for (int i = 0; i < limit; i++) {
11036 PropertyDetails details = descriptors->GetDetails(i);
11037 if (details.type() != FIELD) continue;
11039 int index = descriptors->GetFieldIndex(i);
11040 int property_offset = boilerplate_object->GetInObjectPropertyOffset(index);
11041 Handle<Name> name(descriptors->GetKey(i));
11042 Handle<Object> value =
11043 Handle<Object>(boilerplate_object->InObjectPropertyAt(index),
11046 // The access for the store depends on the type of the boilerplate.
11047 HObjectAccess access = boilerplate_object->IsJSArray() ?
11048 HObjectAccess::ForJSArrayOffset(property_offset) :
11049 HObjectAccess::ForMapAndOffset(boilerplate_map, property_offset);
11051 if (value->IsJSObject()) {
11052 Handle<JSObject> value_object = Handle<JSObject>::cast(value);
11053 Handle<AllocationSite> current_site = site_context->EnterNewScope();
11054 HInstruction* result =
11055 BuildFastLiteral(value_object, site_context);
11056 site_context->ExitScope(current_site, value_object);
11057 Add<HStoreNamedField>(object, access, result);
11059 Representation representation = details.representation();
11060 HInstruction* value_instruction;
11062 if (representation.IsDouble()) {
11063 // Allocate a HeapNumber box and store the value into it.
11064 HValue* heap_number_constant = Add<HConstant>(HeapNumber::kSize);
11065 // This heap number alloc does not have a corresponding
11066 // AllocationSite. That is okay because
11067 // 1) it's a child object of another object with a valid allocation site
11068 // 2) we can just use the mode of the parent object for pretenuring
11069 HInstruction* double_box =
11070 Add<HAllocate>(heap_number_constant, HType::HeapObject(),
11071 pretenure_flag, MUTABLE_HEAP_NUMBER_TYPE);
11072 AddStoreMapConstant(double_box,
11073 isolate()->factory()->mutable_heap_number_map());
11074 // Unwrap the mutable heap number from the boilerplate.
11075 HValue* double_value =
11076 Add<HConstant>(Handle<HeapNumber>::cast(value)->value());
11077 Add<HStoreNamedField>(
11078 double_box, HObjectAccess::ForHeapNumberValue(), double_value);
11079 value_instruction = double_box;
11080 } else if (representation.IsSmi()) {
11081 value_instruction = value->IsUninitialized()
11082 ? graph()->GetConstant0()
11083 : Add<HConstant>(value);
11084 // Ensure that value is stored as smi.
11085 access = access.WithRepresentation(representation);
11087 value_instruction = Add<HConstant>(value);
11090 Add<HStoreNamedField>(object, access, value_instruction);
11094 int inobject_properties = boilerplate_object->map()->inobject_properties();
11095 HInstruction* value_instruction =
11096 Add<HConstant>(isolate()->factory()->one_pointer_filler_map());
11097 for (int i = copied_fields; i < inobject_properties; i++) {
11098 DCHECK(boilerplate_object->IsJSObject());
11099 int property_offset = boilerplate_object->GetInObjectPropertyOffset(i);
11100 HObjectAccess access =
11101 HObjectAccess::ForMapAndOffset(boilerplate_map, property_offset);
11102 Add<HStoreNamedField>(object, access, value_instruction);
11107 void HOptimizedGraphBuilder::BuildEmitElements(
11108 Handle<JSObject> boilerplate_object,
11109 Handle<FixedArrayBase> elements,
11110 HValue* object_elements,
11111 AllocationSiteUsageContext* site_context) {
11112 ElementsKind kind = boilerplate_object->map()->elements_kind();
11113 int elements_length = elements->length();
11114 HValue* object_elements_length = Add<HConstant>(elements_length);
11115 BuildInitializeElementsHeader(object_elements, kind, object_elements_length);
11117 // Copy elements backing store content.
11118 if (elements->IsFixedDoubleArray()) {
11119 BuildEmitFixedDoubleArray(elements, kind, object_elements);
11120 } else if (elements->IsFixedArray()) {
11121 BuildEmitFixedArray(elements, kind, object_elements,
11129 void HOptimizedGraphBuilder::BuildEmitFixedDoubleArray(
11130 Handle<FixedArrayBase> elements,
11132 HValue* object_elements) {
11133 HInstruction* boilerplate_elements = Add<HConstant>(elements);
11134 int elements_length = elements->length();
11135 for (int i = 0; i < elements_length; i++) {
11136 HValue* key_constant = Add<HConstant>(i);
11137 HInstruction* value_instruction =
11138 Add<HLoadKeyed>(boilerplate_elements, key_constant,
11139 static_cast<HValue*>(NULL), kind,
11140 ALLOW_RETURN_HOLE);
11141 HInstruction* store = Add<HStoreKeyed>(object_elements, key_constant,
11142 value_instruction, kind);
11143 store->SetFlag(HValue::kAllowUndefinedAsNaN);
11148 void HOptimizedGraphBuilder::BuildEmitFixedArray(
11149 Handle<FixedArrayBase> elements,
11151 HValue* object_elements,
11152 AllocationSiteUsageContext* site_context) {
11153 HInstruction* boilerplate_elements = Add<HConstant>(elements);
11154 int elements_length = elements->length();
11155 Handle<FixedArray> fast_elements = Handle<FixedArray>::cast(elements);
11156 for (int i = 0; i < elements_length; i++) {
11157 Handle<Object> value(fast_elements->get(i), isolate());
11158 HValue* key_constant = Add<HConstant>(i);
11159 if (value->IsJSObject()) {
11160 Handle<JSObject> value_object = Handle<JSObject>::cast(value);
11161 Handle<AllocationSite> current_site = site_context->EnterNewScope();
11162 HInstruction* result =
11163 BuildFastLiteral(value_object, site_context);
11164 site_context->ExitScope(current_site, value_object);
11165 Add<HStoreKeyed>(object_elements, key_constant, result, kind);
11167 HInstruction* value_instruction =
11168 Add<HLoadKeyed>(boilerplate_elements, key_constant,
11169 static_cast<HValue*>(NULL), kind,
11170 ALLOW_RETURN_HOLE);
11171 Add<HStoreKeyed>(object_elements, key_constant, value_instruction, kind);
11177 void HOptimizedGraphBuilder::VisitThisFunction(ThisFunction* expr) {
11178 DCHECK(!HasStackOverflow());
11179 DCHECK(current_block() != NULL);
11180 DCHECK(current_block()->HasPredecessor());
11181 HInstruction* instr = BuildThisFunction();
11182 return ast_context()->ReturnInstruction(instr, expr->id());
11186 void HOptimizedGraphBuilder::VisitDeclarations(
11187 ZoneList<Declaration*>* declarations) {
11188 DCHECK(globals_.is_empty());
11189 AstVisitor::VisitDeclarations(declarations);
11190 if (!globals_.is_empty()) {
11191 Handle<FixedArray> array =
11192 isolate()->factory()->NewFixedArray(globals_.length(), TENURED);
11193 for (int i = 0; i < globals_.length(); ++i) array->set(i, *globals_.at(i));
11194 int flags = DeclareGlobalsEvalFlag::encode(current_info()->is_eval()) |
11195 DeclareGlobalsNativeFlag::encode(current_info()->is_native()) |
11196 DeclareGlobalsStrictMode::encode(current_info()->strict_mode());
11197 Add<HDeclareGlobals>(array, flags);
11198 globals_.Rewind(0);
11203 void HOptimizedGraphBuilder::VisitVariableDeclaration(
11204 VariableDeclaration* declaration) {
11205 VariableProxy* proxy = declaration->proxy();
11206 VariableMode mode = declaration->mode();
11207 Variable* variable = proxy->var();
11208 bool hole_init = mode == LET || mode == CONST || mode == CONST_LEGACY;
11209 switch (variable->location()) {
11210 case Variable::UNALLOCATED:
11211 globals_.Add(variable->name(), zone());
11212 globals_.Add(variable->binding_needs_init()
11213 ? isolate()->factory()->the_hole_value()
11214 : isolate()->factory()->undefined_value(), zone());
11216 case Variable::PARAMETER:
11217 case Variable::LOCAL:
11219 HValue* value = graph()->GetConstantHole();
11220 environment()->Bind(variable, value);
11223 case Variable::CONTEXT:
11225 HValue* value = graph()->GetConstantHole();
11226 HValue* context = environment()->context();
11227 HStoreContextSlot* store = Add<HStoreContextSlot>(
11228 context, variable->index(), HStoreContextSlot::kNoCheck, value);
11229 if (store->HasObservableSideEffects()) {
11230 Add<HSimulate>(proxy->id(), REMOVABLE_SIMULATE);
11234 case Variable::LOOKUP:
11235 return Bailout(kUnsupportedLookupSlotInDeclaration);
11240 void HOptimizedGraphBuilder::VisitFunctionDeclaration(
11241 FunctionDeclaration* declaration) {
11242 VariableProxy* proxy = declaration->proxy();
11243 Variable* variable = proxy->var();
11244 switch (variable->location()) {
11245 case Variable::UNALLOCATED: {
11246 globals_.Add(variable->name(), zone());
11247 Handle<SharedFunctionInfo> function = Compiler::BuildFunctionInfo(
11248 declaration->fun(), current_info()->script(), top_info());
11249 // Check for stack-overflow exception.
11250 if (function.is_null()) return SetStackOverflow();
11251 globals_.Add(function, zone());
11254 case Variable::PARAMETER:
11255 case Variable::LOCAL: {
11256 CHECK_ALIVE(VisitForValue(declaration->fun()));
11257 HValue* value = Pop();
11258 BindIfLive(variable, value);
11261 case Variable::CONTEXT: {
11262 CHECK_ALIVE(VisitForValue(declaration->fun()));
11263 HValue* value = Pop();
11264 HValue* context = environment()->context();
11265 HStoreContextSlot* store = Add<HStoreContextSlot>(
11266 context, variable->index(), HStoreContextSlot::kNoCheck, value);
11267 if (store->HasObservableSideEffects()) {
11268 Add<HSimulate>(proxy->id(), REMOVABLE_SIMULATE);
11272 case Variable::LOOKUP:
11273 return Bailout(kUnsupportedLookupSlotInDeclaration);
11278 void HOptimizedGraphBuilder::VisitModuleDeclaration(
11279 ModuleDeclaration* declaration) {
11284 void HOptimizedGraphBuilder::VisitImportDeclaration(
11285 ImportDeclaration* declaration) {
11290 void HOptimizedGraphBuilder::VisitExportDeclaration(
11291 ExportDeclaration* declaration) {
11296 void HOptimizedGraphBuilder::VisitModuleLiteral(ModuleLiteral* module) {
11301 void HOptimizedGraphBuilder::VisitModuleVariable(ModuleVariable* module) {
11306 void HOptimizedGraphBuilder::VisitModulePath(ModulePath* module) {
11311 void HOptimizedGraphBuilder::VisitModuleUrl(ModuleUrl* module) {
11316 void HOptimizedGraphBuilder::VisitModuleStatement(ModuleStatement* stmt) {
11321 // Generators for inline runtime functions.
11322 // Support for types.
11323 void HOptimizedGraphBuilder::GenerateIsSmi(CallRuntime* call) {
11324 DCHECK(call->arguments()->length() == 1);
11325 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11326 HValue* value = Pop();
11327 HIsSmiAndBranch* result = New<HIsSmiAndBranch>(value);
11328 return ast_context()->ReturnControl(result, call->id());
11332 void HOptimizedGraphBuilder::GenerateIsSpecObject(CallRuntime* call) {
11333 DCHECK(call->arguments()->length() == 1);
11334 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11335 HValue* value = Pop();
11336 HHasInstanceTypeAndBranch* result =
11337 New<HHasInstanceTypeAndBranch>(value,
11338 FIRST_SPEC_OBJECT_TYPE,
11339 LAST_SPEC_OBJECT_TYPE);
11340 return ast_context()->ReturnControl(result, call->id());
11344 void HOptimizedGraphBuilder::GenerateIsFunction(CallRuntime* call) {
11345 DCHECK(call->arguments()->length() == 1);
11346 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11347 HValue* value = Pop();
11348 HHasInstanceTypeAndBranch* result =
11349 New<HHasInstanceTypeAndBranch>(value, JS_FUNCTION_TYPE);
11350 return ast_context()->ReturnControl(result, call->id());
11354 void HOptimizedGraphBuilder::GenerateIsMinusZero(CallRuntime* call) {
11355 DCHECK(call->arguments()->length() == 1);
11356 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11357 HValue* value = Pop();
11358 HCompareMinusZeroAndBranch* result = New<HCompareMinusZeroAndBranch>(value);
11359 return ast_context()->ReturnControl(result, call->id());
11363 void HOptimizedGraphBuilder::GenerateHasCachedArrayIndex(CallRuntime* call) {
11364 DCHECK(call->arguments()->length() == 1);
11365 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11366 HValue* value = Pop();
11367 HHasCachedArrayIndexAndBranch* result =
11368 New<HHasCachedArrayIndexAndBranch>(value);
11369 return ast_context()->ReturnControl(result, call->id());
11373 void HOptimizedGraphBuilder::GenerateIsArray(CallRuntime* call) {
11374 DCHECK(call->arguments()->length() == 1);
11375 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11376 HValue* value = Pop();
11377 HHasInstanceTypeAndBranch* result =
11378 New<HHasInstanceTypeAndBranch>(value, JS_ARRAY_TYPE);
11379 return ast_context()->ReturnControl(result, call->id());
11383 void HOptimizedGraphBuilder::GenerateIsRegExp(CallRuntime* call) {
11384 DCHECK(call->arguments()->length() == 1);
11385 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11386 HValue* value = Pop();
11387 HHasInstanceTypeAndBranch* result =
11388 New<HHasInstanceTypeAndBranch>(value, JS_REGEXP_TYPE);
11389 return ast_context()->ReturnControl(result, call->id());
11393 void HOptimizedGraphBuilder::GenerateIsObject(CallRuntime* call) {
11394 DCHECK(call->arguments()->length() == 1);
11395 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11396 HValue* value = Pop();
11397 HIsObjectAndBranch* result = New<HIsObjectAndBranch>(value);
11398 return ast_context()->ReturnControl(result, call->id());
11402 void HOptimizedGraphBuilder::GenerateIsNonNegativeSmi(CallRuntime* call) {
11403 return Bailout(kInlinedRuntimeFunctionIsNonNegativeSmi);
11407 void HOptimizedGraphBuilder::GenerateIsUndetectableObject(CallRuntime* call) {
11408 DCHECK(call->arguments()->length() == 1);
11409 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11410 HValue* value = Pop();
11411 HIsUndetectableAndBranch* result = New<HIsUndetectableAndBranch>(value);
11412 return ast_context()->ReturnControl(result, call->id());
11416 void HOptimizedGraphBuilder::GenerateIsStringWrapperSafeForDefaultValueOf(
11417 CallRuntime* call) {
11418 return Bailout(kInlinedRuntimeFunctionIsStringWrapperSafeForDefaultValueOf);
11422 // Support for construct call checks.
11423 void HOptimizedGraphBuilder::GenerateIsConstructCall(CallRuntime* call) {
11424 DCHECK(call->arguments()->length() == 0);
11425 if (function_state()->outer() != NULL) {
11426 // We are generating graph for inlined function.
11427 HValue* value = function_state()->inlining_kind() == CONSTRUCT_CALL_RETURN
11428 ? graph()->GetConstantTrue()
11429 : graph()->GetConstantFalse();
11430 return ast_context()->ReturnValue(value);
11432 return ast_context()->ReturnControl(New<HIsConstructCallAndBranch>(),
11438 // Support for arguments.length and arguments[?].
11439 void HOptimizedGraphBuilder::GenerateArgumentsLength(CallRuntime* call) {
11440 DCHECK(call->arguments()->length() == 0);
11441 HInstruction* result = NULL;
11442 if (function_state()->outer() == NULL) {
11443 HInstruction* elements = Add<HArgumentsElements>(false);
11444 result = New<HArgumentsLength>(elements);
11446 // Number of arguments without receiver.
11447 int argument_count = environment()->
11448 arguments_environment()->parameter_count() - 1;
11449 result = New<HConstant>(argument_count);
11451 return ast_context()->ReturnInstruction(result, call->id());
11455 void HOptimizedGraphBuilder::GenerateArguments(CallRuntime* call) {
11456 DCHECK(call->arguments()->length() == 1);
11457 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11458 HValue* index = Pop();
11459 HInstruction* result = NULL;
11460 if (function_state()->outer() == NULL) {
11461 HInstruction* elements = Add<HArgumentsElements>(false);
11462 HInstruction* length = Add<HArgumentsLength>(elements);
11463 HInstruction* checked_index = Add<HBoundsCheck>(index, length);
11464 result = New<HAccessArgumentsAt>(elements, length, checked_index);
11466 EnsureArgumentsArePushedForAccess();
11468 // Number of arguments without receiver.
11469 HInstruction* elements = function_state()->arguments_elements();
11470 int argument_count = environment()->
11471 arguments_environment()->parameter_count() - 1;
11472 HInstruction* length = Add<HConstant>(argument_count);
11473 HInstruction* checked_key = Add<HBoundsCheck>(index, length);
11474 result = New<HAccessArgumentsAt>(elements, length, checked_key);
11476 return ast_context()->ReturnInstruction(result, call->id());
11480 // Support for accessing the class and value fields of an object.
11481 void HOptimizedGraphBuilder::GenerateClassOf(CallRuntime* call) {
11482 // The special form detected by IsClassOfTest is detected before we get here
11483 // and does not cause a bailout.
11484 return Bailout(kInlinedRuntimeFunctionClassOf);
11488 void HOptimizedGraphBuilder::GenerateValueOf(CallRuntime* call) {
11489 DCHECK(call->arguments()->length() == 1);
11490 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11491 HValue* object = Pop();
11493 IfBuilder if_objectisvalue(this);
11494 HValue* objectisvalue = if_objectisvalue.If<HHasInstanceTypeAndBranch>(
11495 object, JS_VALUE_TYPE);
11496 if_objectisvalue.Then();
11498 // Return the actual value.
11499 Push(Add<HLoadNamedField>(
11500 object, objectisvalue,
11501 HObjectAccess::ForObservableJSObjectOffset(
11502 JSValue::kValueOffset)));
11503 Add<HSimulate>(call->id(), FIXED_SIMULATE);
11505 if_objectisvalue.Else();
11507 // If the object is not a value return the object.
11509 Add<HSimulate>(call->id(), FIXED_SIMULATE);
11511 if_objectisvalue.End();
11512 return ast_context()->ReturnValue(Pop());
11516 void HOptimizedGraphBuilder::GenerateDateField(CallRuntime* call) {
11517 DCHECK(call->arguments()->length() == 2);
11518 DCHECK_NE(NULL, call->arguments()->at(1)->AsLiteral());
11519 Smi* index = Smi::cast(*(call->arguments()->at(1)->AsLiteral()->value()));
11520 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11521 HValue* date = Pop();
11522 HDateField* result = New<HDateField>(date, index);
11523 return ast_context()->ReturnInstruction(result, call->id());
11527 void HOptimizedGraphBuilder::GenerateOneByteSeqStringSetChar(
11528 CallRuntime* call) {
11529 DCHECK(call->arguments()->length() == 3);
11530 // We need to follow the evaluation order of full codegen.
11531 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
11532 CHECK_ALIVE(VisitForValue(call->arguments()->at(2)));
11533 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11534 HValue* string = Pop();
11535 HValue* value = Pop();
11536 HValue* index = Pop();
11537 Add<HSeqStringSetChar>(String::ONE_BYTE_ENCODING, string,
11539 Add<HSimulate>(call->id(), FIXED_SIMULATE);
11540 return ast_context()->ReturnValue(graph()->GetConstantUndefined());
11544 void HOptimizedGraphBuilder::GenerateTwoByteSeqStringSetChar(
11545 CallRuntime* call) {
11546 DCHECK(call->arguments()->length() == 3);
11547 // We need to follow the evaluation order of full codegen.
11548 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
11549 CHECK_ALIVE(VisitForValue(call->arguments()->at(2)));
11550 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11551 HValue* string = Pop();
11552 HValue* value = Pop();
11553 HValue* index = Pop();
11554 Add<HSeqStringSetChar>(String::TWO_BYTE_ENCODING, string,
11556 Add<HSimulate>(call->id(), FIXED_SIMULATE);
11557 return ast_context()->ReturnValue(graph()->GetConstantUndefined());
11561 void HOptimizedGraphBuilder::GenerateSetValueOf(CallRuntime* call) {
11562 DCHECK(call->arguments()->length() == 2);
11563 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11564 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
11565 HValue* value = Pop();
11566 HValue* object = Pop();
11568 // Check if object is a JSValue.
11569 IfBuilder if_objectisvalue(this);
11570 if_objectisvalue.If<HHasInstanceTypeAndBranch>(object, JS_VALUE_TYPE);
11571 if_objectisvalue.Then();
11573 // Create in-object property store to kValueOffset.
11574 Add<HStoreNamedField>(object,
11575 HObjectAccess::ForObservableJSObjectOffset(JSValue::kValueOffset),
11577 if (!ast_context()->IsEffect()) {
11580 Add<HSimulate>(call->id(), FIXED_SIMULATE);
11582 if_objectisvalue.Else();
11584 // Nothing to do in this case.
11585 if (!ast_context()->IsEffect()) {
11588 Add<HSimulate>(call->id(), FIXED_SIMULATE);
11590 if_objectisvalue.End();
11591 if (!ast_context()->IsEffect()) {
11594 return ast_context()->ReturnValue(value);
11598 // Fast support for charCodeAt(n).
11599 void HOptimizedGraphBuilder::GenerateStringCharCodeAt(CallRuntime* call) {
11600 DCHECK(call->arguments()->length() == 2);
11601 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11602 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
11603 HValue* index = Pop();
11604 HValue* string = Pop();
11605 HInstruction* result = BuildStringCharCodeAt(string, index);
11606 return ast_context()->ReturnInstruction(result, call->id());
11610 // Fast support for string.charAt(n) and string[n].
11611 void HOptimizedGraphBuilder::GenerateStringCharFromCode(CallRuntime* call) {
11612 DCHECK(call->arguments()->length() == 1);
11613 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11614 HValue* char_code = Pop();
11615 HInstruction* result = NewUncasted<HStringCharFromCode>(char_code);
11616 return ast_context()->ReturnInstruction(result, call->id());
11620 // Fast support for string.charAt(n) and string[n].
11621 void HOptimizedGraphBuilder::GenerateStringCharAt(CallRuntime* call) {
11622 DCHECK(call->arguments()->length() == 2);
11623 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11624 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
11625 HValue* index = Pop();
11626 HValue* string = Pop();
11627 HInstruction* char_code = BuildStringCharCodeAt(string, index);
11628 AddInstruction(char_code);
11629 HInstruction* result = NewUncasted<HStringCharFromCode>(char_code);
11630 return ast_context()->ReturnInstruction(result, call->id());
11634 // Fast support for object equality testing.
11635 void HOptimizedGraphBuilder::GenerateObjectEquals(CallRuntime* call) {
11636 DCHECK(call->arguments()->length() == 2);
11637 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11638 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
11639 HValue* right = Pop();
11640 HValue* left = Pop();
11641 HCompareObjectEqAndBranch* result =
11642 New<HCompareObjectEqAndBranch>(left, right);
11643 return ast_context()->ReturnControl(result, call->id());
11647 // Fast support for StringAdd.
11648 void HOptimizedGraphBuilder::GenerateStringAdd(CallRuntime* call) {
11649 DCHECK_EQ(2, call->arguments()->length());
11650 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11651 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
11652 HValue* right = Pop();
11653 HValue* left = Pop();
11654 HInstruction* result = NewUncasted<HStringAdd>(left, right);
11655 return ast_context()->ReturnInstruction(result, call->id());
11659 // Fast support for SubString.
11660 void HOptimizedGraphBuilder::GenerateSubString(CallRuntime* call) {
11661 DCHECK_EQ(3, call->arguments()->length());
11662 CHECK_ALIVE(VisitExpressions(call->arguments()));
11663 PushArgumentsFromEnvironment(call->arguments()->length());
11664 HCallStub* result = New<HCallStub>(CodeStub::SubString, 3);
11665 return ast_context()->ReturnInstruction(result, call->id());
11669 // Fast support for StringCompare.
11670 void HOptimizedGraphBuilder::GenerateStringCompare(CallRuntime* call) {
11671 DCHECK_EQ(2, call->arguments()->length());
11672 CHECK_ALIVE(VisitExpressions(call->arguments()));
11673 PushArgumentsFromEnvironment(call->arguments()->length());
11674 HCallStub* result = New<HCallStub>(CodeStub::StringCompare, 2);
11675 return ast_context()->ReturnInstruction(result, call->id());
11679 // Support for direct calls from JavaScript to native RegExp code.
11680 void HOptimizedGraphBuilder::GenerateRegExpExec(CallRuntime* call) {
11681 DCHECK_EQ(4, call->arguments()->length());
11682 CHECK_ALIVE(VisitExpressions(call->arguments()));
11683 PushArgumentsFromEnvironment(call->arguments()->length());
11684 HCallStub* result = New<HCallStub>(CodeStub::RegExpExec, 4);
11685 return ast_context()->ReturnInstruction(result, call->id());
11689 void HOptimizedGraphBuilder::GenerateDoubleLo(CallRuntime* call) {
11690 DCHECK_EQ(1, call->arguments()->length());
11691 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11692 HValue* value = Pop();
11693 HInstruction* result = NewUncasted<HDoubleBits>(value, HDoubleBits::LOW);
11694 return ast_context()->ReturnInstruction(result, call->id());
11698 void HOptimizedGraphBuilder::GenerateDoubleHi(CallRuntime* call) {
11699 DCHECK_EQ(1, call->arguments()->length());
11700 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11701 HValue* value = Pop();
11702 HInstruction* result = NewUncasted<HDoubleBits>(value, HDoubleBits::HIGH);
11703 return ast_context()->ReturnInstruction(result, call->id());
11707 void HOptimizedGraphBuilder::GenerateConstructDouble(CallRuntime* call) {
11708 DCHECK_EQ(2, call->arguments()->length());
11709 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11710 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
11711 HValue* lo = Pop();
11712 HValue* hi = Pop();
11713 HInstruction* result = NewUncasted<HConstructDouble>(hi, lo);
11714 return ast_context()->ReturnInstruction(result, call->id());
11718 // Construct a RegExp exec result with two in-object properties.
11719 void HOptimizedGraphBuilder::GenerateRegExpConstructResult(CallRuntime* call) {
11720 DCHECK_EQ(3, call->arguments()->length());
11721 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11722 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
11723 CHECK_ALIVE(VisitForValue(call->arguments()->at(2)));
11724 HValue* input = Pop();
11725 HValue* index = Pop();
11726 HValue* length = Pop();
11727 HValue* result = BuildRegExpConstructResult(length, index, input);
11728 return ast_context()->ReturnValue(result);
11732 // Support for fast native caches.
11733 void HOptimizedGraphBuilder::GenerateGetFromCache(CallRuntime* call) {
11734 return Bailout(kInlinedRuntimeFunctionGetFromCache);
11738 // Fast support for number to string.
11739 void HOptimizedGraphBuilder::GenerateNumberToString(CallRuntime* call) {
11740 DCHECK_EQ(1, call->arguments()->length());
11741 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11742 HValue* number = Pop();
11743 HValue* result = BuildNumberToString(number, Type::Any(zone()));
11744 return ast_context()->ReturnValue(result);
11748 // Fast call for custom callbacks.
11749 void HOptimizedGraphBuilder::GenerateCallFunction(CallRuntime* call) {
11750 // 1 ~ The function to call is not itself an argument to the call.
11751 int arg_count = call->arguments()->length() - 1;
11752 DCHECK(arg_count >= 1); // There's always at least a receiver.
11754 CHECK_ALIVE(VisitExpressions(call->arguments()));
11755 // The function is the last argument
11756 HValue* function = Pop();
11757 // Push the arguments to the stack
11758 PushArgumentsFromEnvironment(arg_count);
11760 IfBuilder if_is_jsfunction(this);
11761 if_is_jsfunction.If<HHasInstanceTypeAndBranch>(function, JS_FUNCTION_TYPE);
11763 if_is_jsfunction.Then();
11765 HInstruction* invoke_result =
11766 Add<HInvokeFunction>(function, arg_count);
11767 if (!ast_context()->IsEffect()) {
11768 Push(invoke_result);
11770 Add<HSimulate>(call->id(), FIXED_SIMULATE);
11773 if_is_jsfunction.Else();
11775 HInstruction* call_result =
11776 Add<HCallFunction>(function, arg_count);
11777 if (!ast_context()->IsEffect()) {
11780 Add<HSimulate>(call->id(), FIXED_SIMULATE);
11782 if_is_jsfunction.End();
11784 if (ast_context()->IsEffect()) {
11785 // EffectContext::ReturnValue ignores the value, so we can just pass
11786 // 'undefined' (as we do not have the call result anymore).
11787 return ast_context()->ReturnValue(graph()->GetConstantUndefined());
11789 return ast_context()->ReturnValue(Pop());
11794 // Fast call to math functions.
11795 void HOptimizedGraphBuilder::GenerateMathPow(CallRuntime* call) {
11796 DCHECK_EQ(2, call->arguments()->length());
11797 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11798 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
11799 HValue* right = Pop();
11800 HValue* left = Pop();
11801 HInstruction* result = NewUncasted<HPower>(left, right);
11802 return ast_context()->ReturnInstruction(result, call->id());
11806 void HOptimizedGraphBuilder::GenerateMathLogRT(CallRuntime* call) {
11807 DCHECK(call->arguments()->length() == 1);
11808 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11809 HValue* value = Pop();
11810 HInstruction* result = NewUncasted<HUnaryMathOperation>(value, kMathLog);
11811 return ast_context()->ReturnInstruction(result, call->id());
11815 void HOptimizedGraphBuilder::GenerateMathSqrtRT(CallRuntime* call) {
11816 DCHECK(call->arguments()->length() == 1);
11817 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11818 HValue* value = Pop();
11819 HInstruction* result = NewUncasted<HUnaryMathOperation>(value, kMathSqrt);
11820 return ast_context()->ReturnInstruction(result, call->id());
11824 void HOptimizedGraphBuilder::GenerateGetCachedArrayIndex(CallRuntime* call) {
11825 DCHECK(call->arguments()->length() == 1);
11826 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11827 HValue* value = Pop();
11828 HGetCachedArrayIndex* result = New<HGetCachedArrayIndex>(value);
11829 return ast_context()->ReturnInstruction(result, call->id());
11833 void HOptimizedGraphBuilder::GenerateFastAsciiArrayJoin(CallRuntime* call) {
11834 return Bailout(kInlinedRuntimeFunctionFastAsciiArrayJoin);
11838 // Support for generators.
11839 void HOptimizedGraphBuilder::GenerateGeneratorNext(CallRuntime* call) {
11840 return Bailout(kInlinedRuntimeFunctionGeneratorNext);
11844 void HOptimizedGraphBuilder::GenerateGeneratorThrow(CallRuntime* call) {
11845 return Bailout(kInlinedRuntimeFunctionGeneratorThrow);
11849 void HOptimizedGraphBuilder::GenerateDebugBreakInOptimizedCode(
11850 CallRuntime* call) {
11851 Add<HDebugBreak>();
11852 return ast_context()->ReturnValue(graph()->GetConstant0());
11856 void HOptimizedGraphBuilder::GenerateDebugIsActive(CallRuntime* call) {
11857 DCHECK(call->arguments()->length() == 0);
11859 Add<HConstant>(ExternalReference::debug_is_active_address(isolate()));
11860 HValue* value = Add<HLoadNamedField>(
11861 ref, static_cast<HValue*>(NULL), HObjectAccess::ForExternalUInteger8());
11862 return ast_context()->ReturnValue(value);
11866 #undef CHECK_BAILOUT
11870 HEnvironment::HEnvironment(HEnvironment* outer,
11872 Handle<JSFunction> closure,
11874 : closure_(closure),
11876 frame_type_(JS_FUNCTION),
11877 parameter_count_(0),
11878 specials_count_(1),
11884 ast_id_(BailoutId::None()),
11886 Scope* declaration_scope = scope->DeclarationScope();
11887 Initialize(declaration_scope->num_parameters() + 1,
11888 declaration_scope->num_stack_slots(), 0);
11892 HEnvironment::HEnvironment(Zone* zone, int parameter_count)
11893 : values_(0, zone),
11895 parameter_count_(parameter_count),
11896 specials_count_(1),
11902 ast_id_(BailoutId::None()),
11904 Initialize(parameter_count, 0, 0);
11908 HEnvironment::HEnvironment(const HEnvironment* other, Zone* zone)
11909 : values_(0, zone),
11910 frame_type_(JS_FUNCTION),
11911 parameter_count_(0),
11912 specials_count_(0),
11918 ast_id_(other->ast_id()),
11924 HEnvironment::HEnvironment(HEnvironment* outer,
11925 Handle<JSFunction> closure,
11926 FrameType frame_type,
11929 : closure_(closure),
11930 values_(arguments, zone),
11931 frame_type_(frame_type),
11932 parameter_count_(arguments),
11933 specials_count_(0),
11939 ast_id_(BailoutId::None()),
11944 void HEnvironment::Initialize(int parameter_count,
11946 int stack_height) {
11947 parameter_count_ = parameter_count;
11948 local_count_ = local_count;
11950 // Avoid reallocating the temporaries' backing store on the first Push.
11951 int total = parameter_count + specials_count_ + local_count + stack_height;
11952 values_.Initialize(total + 4, zone());
11953 for (int i = 0; i < total; ++i) values_.Add(NULL, zone());
11957 void HEnvironment::Initialize(const HEnvironment* other) {
11958 closure_ = other->closure();
11959 values_.AddAll(other->values_, zone());
11960 assigned_variables_.Union(other->assigned_variables_, zone());
11961 frame_type_ = other->frame_type_;
11962 parameter_count_ = other->parameter_count_;
11963 local_count_ = other->local_count_;
11964 if (other->outer_ != NULL) outer_ = other->outer_->Copy(); // Deep copy.
11965 entry_ = other->entry_;
11966 pop_count_ = other->pop_count_;
11967 push_count_ = other->push_count_;
11968 specials_count_ = other->specials_count_;
11969 ast_id_ = other->ast_id_;
11973 void HEnvironment::AddIncomingEdge(HBasicBlock* block, HEnvironment* other) {
11974 DCHECK(!block->IsLoopHeader());
11975 DCHECK(values_.length() == other->values_.length());
11977 int length = values_.length();
11978 for (int i = 0; i < length; ++i) {
11979 HValue* value = values_[i];
11980 if (value != NULL && value->IsPhi() && value->block() == block) {
11981 // There is already a phi for the i'th value.
11982 HPhi* phi = HPhi::cast(value);
11983 // Assert index is correct and that we haven't missed an incoming edge.
11984 DCHECK(phi->merged_index() == i || !phi->HasMergedIndex());
11985 DCHECK(phi->OperandCount() == block->predecessors()->length());
11986 phi->AddInput(other->values_[i]);
11987 } else if (values_[i] != other->values_[i]) {
11988 // There is a fresh value on the incoming edge, a phi is needed.
11989 DCHECK(values_[i] != NULL && other->values_[i] != NULL);
11990 HPhi* phi = block->AddNewPhi(i);
11991 HValue* old_value = values_[i];
11992 for (int j = 0; j < block->predecessors()->length(); j++) {
11993 phi->AddInput(old_value);
11995 phi->AddInput(other->values_[i]);
11996 this->values_[i] = phi;
12002 void HEnvironment::Bind(int index, HValue* value) {
12003 DCHECK(value != NULL);
12004 assigned_variables_.Add(index, zone());
12005 values_[index] = value;
12009 bool HEnvironment::HasExpressionAt(int index) const {
12010 return index >= parameter_count_ + specials_count_ + local_count_;
12014 bool HEnvironment::ExpressionStackIsEmpty() const {
12015 DCHECK(length() >= first_expression_index());
12016 return length() == first_expression_index();
12020 void HEnvironment::SetExpressionStackAt(int index_from_top, HValue* value) {
12021 int count = index_from_top + 1;
12022 int index = values_.length() - count;
12023 DCHECK(HasExpressionAt(index));
12024 // The push count must include at least the element in question or else
12025 // the new value will not be included in this environment's history.
12026 if (push_count_ < count) {
12027 // This is the same effect as popping then re-pushing 'count' elements.
12028 pop_count_ += (count - push_count_);
12029 push_count_ = count;
12031 values_[index] = value;
12035 void HEnvironment::Drop(int count) {
12036 for (int i = 0; i < count; ++i) {
12042 HEnvironment* HEnvironment::Copy() const {
12043 return new(zone()) HEnvironment(this, zone());
12047 HEnvironment* HEnvironment::CopyWithoutHistory() const {
12048 HEnvironment* result = Copy();
12049 result->ClearHistory();
12054 HEnvironment* HEnvironment::CopyAsLoopHeader(HBasicBlock* loop_header) const {
12055 HEnvironment* new_env = Copy();
12056 for (int i = 0; i < values_.length(); ++i) {
12057 HPhi* phi = loop_header->AddNewPhi(i);
12058 phi->AddInput(values_[i]);
12059 new_env->values_[i] = phi;
12061 new_env->ClearHistory();
12066 HEnvironment* HEnvironment::CreateStubEnvironment(HEnvironment* outer,
12067 Handle<JSFunction> target,
12068 FrameType frame_type,
12069 int arguments) const {
12070 HEnvironment* new_env =
12071 new(zone()) HEnvironment(outer, target, frame_type,
12072 arguments + 1, zone());
12073 for (int i = 0; i <= arguments; ++i) { // Include receiver.
12074 new_env->Push(ExpressionStackAt(arguments - i));
12076 new_env->ClearHistory();
12081 HEnvironment* HEnvironment::CopyForInlining(
12082 Handle<JSFunction> target,
12084 FunctionLiteral* function,
12085 HConstant* undefined,
12086 InliningKind inlining_kind) const {
12087 DCHECK(frame_type() == JS_FUNCTION);
12089 // Outer environment is a copy of this one without the arguments.
12090 int arity = function->scope()->num_parameters();
12092 HEnvironment* outer = Copy();
12093 outer->Drop(arguments + 1); // Including receiver.
12094 outer->ClearHistory();
12096 if (inlining_kind == CONSTRUCT_CALL_RETURN) {
12097 // Create artificial constructor stub environment. The receiver should
12098 // actually be the constructor function, but we pass the newly allocated
12099 // object instead, DoComputeConstructStubFrame() relies on that.
12100 outer = CreateStubEnvironment(outer, target, JS_CONSTRUCT, arguments);
12101 } else if (inlining_kind == GETTER_CALL_RETURN) {
12102 // We need an additional StackFrame::INTERNAL frame for restoring the
12103 // correct context.
12104 outer = CreateStubEnvironment(outer, target, JS_GETTER, arguments);
12105 } else if (inlining_kind == SETTER_CALL_RETURN) {
12106 // We need an additional StackFrame::INTERNAL frame for temporarily saving
12107 // the argument of the setter, see StoreStubCompiler::CompileStoreViaSetter.
12108 outer = CreateStubEnvironment(outer, target, JS_SETTER, arguments);
12111 if (arity != arguments) {
12112 // Create artificial arguments adaptation environment.
12113 outer = CreateStubEnvironment(outer, target, ARGUMENTS_ADAPTOR, arguments);
12116 HEnvironment* inner =
12117 new(zone()) HEnvironment(outer, function->scope(), target, zone());
12118 // Get the argument values from the original environment.
12119 for (int i = 0; i <= arity; ++i) { // Include receiver.
12120 HValue* push = (i <= arguments) ?
12121 ExpressionStackAt(arguments - i) : undefined;
12122 inner->SetValueAt(i, push);
12124 inner->SetValueAt(arity + 1, context());
12125 for (int i = arity + 2; i < inner->length(); ++i) {
12126 inner->SetValueAt(i, undefined);
12129 inner->set_ast_id(BailoutId::FunctionEntry());
12134 OStream& operator<<(OStream& os, const HEnvironment& env) {
12135 for (int i = 0; i < env.length(); i++) {
12136 if (i == 0) os << "parameters\n";
12137 if (i == env.parameter_count()) os << "specials\n";
12138 if (i == env.parameter_count() + env.specials_count()) os << "locals\n";
12139 if (i == env.parameter_count() + env.specials_count() + env.local_count()) {
12140 os << "expressions\n";
12142 HValue* val = env.values()->at(i);
12155 void HTracer::TraceCompilation(CompilationInfo* info) {
12156 Tag tag(this, "compilation");
12157 if (info->IsOptimizing()) {
12158 Handle<String> name = info->function()->debug_name();
12159 PrintStringProperty("name", name->ToCString().get());
12161 trace_.Add("method \"%s:%d\"\n",
12162 name->ToCString().get(),
12163 info->optimization_id());
12165 CodeStub::Major major_key = info->code_stub()->MajorKey();
12166 PrintStringProperty("name", CodeStub::MajorName(major_key, false));
12167 PrintStringProperty("method", "stub");
12169 PrintLongProperty("date",
12170 static_cast<int64_t>(base::OS::TimeCurrentMillis()));
12174 void HTracer::TraceLithium(const char* name, LChunk* chunk) {
12175 DCHECK(!chunk->isolate()->concurrent_recompilation_enabled());
12176 AllowHandleDereference allow_deref;
12177 AllowDeferredHandleDereference allow_deferred_deref;
12178 Trace(name, chunk->graph(), chunk);
12182 void HTracer::TraceHydrogen(const char* name, HGraph* graph) {
12183 DCHECK(!graph->isolate()->concurrent_recompilation_enabled());
12184 AllowHandleDereference allow_deref;
12185 AllowDeferredHandleDereference allow_deferred_deref;
12186 Trace(name, graph, NULL);
12190 void HTracer::Trace(const char* name, HGraph* graph, LChunk* chunk) {
12191 Tag tag(this, "cfg");
12192 PrintStringProperty("name", name);
12193 const ZoneList<HBasicBlock*>* blocks = graph->blocks();
12194 for (int i = 0; i < blocks->length(); i++) {
12195 HBasicBlock* current = blocks->at(i);
12196 Tag block_tag(this, "block");
12197 PrintBlockProperty("name", current->block_id());
12198 PrintIntProperty("from_bci", -1);
12199 PrintIntProperty("to_bci", -1);
12201 if (!current->predecessors()->is_empty()) {
12203 trace_.Add("predecessors");
12204 for (int j = 0; j < current->predecessors()->length(); ++j) {
12205 trace_.Add(" \"B%d\"", current->predecessors()->at(j)->block_id());
12209 PrintEmptyProperty("predecessors");
12212 if (current->end()->SuccessorCount() == 0) {
12213 PrintEmptyProperty("successors");
12216 trace_.Add("successors");
12217 for (HSuccessorIterator it(current->end()); !it.Done(); it.Advance()) {
12218 trace_.Add(" \"B%d\"", it.Current()->block_id());
12223 PrintEmptyProperty("xhandlers");
12227 trace_.Add("flags");
12228 if (current->IsLoopSuccessorDominator()) {
12229 trace_.Add(" \"dom-loop-succ\"");
12231 if (current->IsUnreachable()) {
12232 trace_.Add(" \"dead\"");
12234 if (current->is_osr_entry()) {
12235 trace_.Add(" \"osr\"");
12240 if (current->dominator() != NULL) {
12241 PrintBlockProperty("dominator", current->dominator()->block_id());
12244 PrintIntProperty("loop_depth", current->LoopNestingDepth());
12246 if (chunk != NULL) {
12247 int first_index = current->first_instruction_index();
12248 int last_index = current->last_instruction_index();
12251 LifetimePosition::FromInstructionIndex(first_index).Value());
12254 LifetimePosition::FromInstructionIndex(last_index).Value());
12258 Tag states_tag(this, "states");
12259 Tag locals_tag(this, "locals");
12260 int total = current->phis()->length();
12261 PrintIntProperty("size", current->phis()->length());
12262 PrintStringProperty("method", "None");
12263 for (int j = 0; j < total; ++j) {
12264 HPhi* phi = current->phis()->at(j);
12267 os << phi->merged_index() << " " << NameOf(phi) << " " << *phi << "\n";
12268 trace_.Add(os.c_str());
12273 Tag HIR_tag(this, "HIR");
12274 for (HInstructionIterator it(current); !it.Done(); it.Advance()) {
12275 HInstruction* instruction = it.Current();
12276 int uses = instruction->UseCount();
12279 os << "0 " << uses << " " << NameOf(instruction) << " " << *instruction;
12280 if (FLAG_hydrogen_track_positions &&
12281 instruction->has_position() &&
12282 instruction->position().raw() != 0) {
12283 const HSourcePosition pos = instruction->position();
12285 if (pos.inlining_id() != 0) os << pos.inlining_id() << "_";
12286 os << pos.position();
12289 trace_.Add(os.c_str());
12294 if (chunk != NULL) {
12295 Tag LIR_tag(this, "LIR");
12296 int first_index = current->first_instruction_index();
12297 int last_index = current->last_instruction_index();
12298 if (first_index != -1 && last_index != -1) {
12299 const ZoneList<LInstruction*>* instructions = chunk->instructions();
12300 for (int i = first_index; i <= last_index; ++i) {
12301 LInstruction* linstr = instructions->at(i);
12302 if (linstr != NULL) {
12305 LifetimePosition::FromInstructionIndex(i).Value());
12306 linstr->PrintTo(&trace_);
12308 os << " [hir:" << NameOf(linstr->hydrogen_value()) << "] <|@\n";
12309 trace_.Add(os.c_str());
12318 void HTracer::TraceLiveRanges(const char* name, LAllocator* allocator) {
12319 Tag tag(this, "intervals");
12320 PrintStringProperty("name", name);
12322 const Vector<LiveRange*>* fixed_d = allocator->fixed_double_live_ranges();
12323 for (int i = 0; i < fixed_d->length(); ++i) {
12324 TraceLiveRange(fixed_d->at(i), "fixed", allocator->zone());
12327 const Vector<LiveRange*>* fixed = allocator->fixed_live_ranges();
12328 for (int i = 0; i < fixed->length(); ++i) {
12329 TraceLiveRange(fixed->at(i), "fixed", allocator->zone());
12332 const ZoneList<LiveRange*>* live_ranges = allocator->live_ranges();
12333 for (int i = 0; i < live_ranges->length(); ++i) {
12334 TraceLiveRange(live_ranges->at(i), "object", allocator->zone());
12339 void HTracer::TraceLiveRange(LiveRange* range, const char* type,
12341 if (range != NULL && !range->IsEmpty()) {
12343 trace_.Add("%d %s", range->id(), type);
12344 if (range->HasRegisterAssigned()) {
12345 LOperand* op = range->CreateAssignedOperand(zone);
12346 int assigned_reg = op->index();
12347 if (op->IsDoubleRegister()) {
12348 trace_.Add(" \"%s\"",
12349 DoubleRegister::AllocationIndexToString(assigned_reg));
12351 DCHECK(op->IsRegister());
12352 trace_.Add(" \"%s\"", Register::AllocationIndexToString(assigned_reg));
12354 } else if (range->IsSpilled()) {
12355 LOperand* op = range->TopLevel()->GetSpillOperand();
12356 if (op->IsDoubleStackSlot()) {
12357 trace_.Add(" \"double_stack:%d\"", op->index());
12359 DCHECK(op->IsStackSlot());
12360 trace_.Add(" \"stack:%d\"", op->index());
12363 int parent_index = -1;
12364 if (range->IsChild()) {
12365 parent_index = range->parent()->id();
12367 parent_index = range->id();
12369 LOperand* op = range->FirstHint();
12370 int hint_index = -1;
12371 if (op != NULL && op->IsUnallocated()) {
12372 hint_index = LUnallocated::cast(op)->virtual_register();
12374 trace_.Add(" %d %d", parent_index, hint_index);
12375 UseInterval* cur_interval = range->first_interval();
12376 while (cur_interval != NULL && range->Covers(cur_interval->start())) {
12377 trace_.Add(" [%d, %d[",
12378 cur_interval->start().Value(),
12379 cur_interval->end().Value());
12380 cur_interval = cur_interval->next();
12383 UsePosition* current_pos = range->first_pos();
12384 while (current_pos != NULL) {
12385 if (current_pos->RegisterIsBeneficial() || FLAG_trace_all_uses) {
12386 trace_.Add(" %d M", current_pos->pos().Value());
12388 current_pos = current_pos->next();
12391 trace_.Add(" \"\"\n");
12396 void HTracer::FlushToFile() {
12397 AppendChars(filename_.start(), trace_.ToCString().get(), trace_.length(),
12403 void HStatistics::Initialize(CompilationInfo* info) {
12404 if (info->shared_info().is_null()) return;
12405 source_size_ += info->shared_info()->SourceSize();
12409 void HStatistics::Print(const char* stats_name) {
12412 "----------------------------------------"
12413 "----------------------------------------\n"
12414 "--- %s timing results:\n"
12415 "----------------------------------------"
12416 "----------------------------------------\n",
12418 base::TimeDelta sum;
12419 for (int i = 0; i < times_.length(); ++i) {
12423 for (int i = 0; i < names_.length(); ++i) {
12424 PrintF("%33s", names_[i]);
12425 double ms = times_[i].InMillisecondsF();
12426 double percent = times_[i].PercentOf(sum);
12427 PrintF(" %8.3f ms / %4.1f %% ", ms, percent);
12429 unsigned size = sizes_[i];
12430 double size_percent = static_cast<double>(size) * 100 / total_size_;
12431 PrintF(" %9u bytes / %4.1f %%\n", size, size_percent);
12435 "----------------------------------------"
12436 "----------------------------------------\n");
12437 base::TimeDelta total = create_graph_ + optimize_graph_ + generate_code_;
12438 PrintF("%33s %8.3f ms / %4.1f %% \n", "Create graph",
12439 create_graph_.InMillisecondsF(), create_graph_.PercentOf(total));
12440 PrintF("%33s %8.3f ms / %4.1f %% \n", "Optimize graph",
12441 optimize_graph_.InMillisecondsF(), optimize_graph_.PercentOf(total));
12442 PrintF("%33s %8.3f ms / %4.1f %% \n", "Generate and install code",
12443 generate_code_.InMillisecondsF(), generate_code_.PercentOf(total));
12445 "----------------------------------------"
12446 "----------------------------------------\n");
12447 PrintF("%33s %8.3f ms %9u bytes\n", "Total",
12448 total.InMillisecondsF(), total_size_);
12449 PrintF("%33s (%.1f times slower than full code gen)\n", "",
12450 total.TimesOf(full_code_gen_));
12452 double source_size_in_kb = static_cast<double>(source_size_) / 1024;
12453 double normalized_time = source_size_in_kb > 0
12454 ? total.InMillisecondsF() / source_size_in_kb
12456 double normalized_size_in_kb = source_size_in_kb > 0
12457 ? total_size_ / 1024 / source_size_in_kb
12459 PrintF("%33s %8.3f ms %7.3f kB allocated\n",
12460 "Average per kB source", normalized_time, normalized_size_in_kb);
12464 void HStatistics::SaveTiming(const char* name, base::TimeDelta time,
12466 total_size_ += size;
12467 for (int i = 0; i < names_.length(); ++i) {
12468 if (strcmp(names_[i], name) == 0) {
12480 HPhase::~HPhase() {
12481 if (ShouldProduceTraceOutput()) {
12482 isolate()->GetHTracer()->TraceHydrogen(name(), graph_);
12486 graph_->Verify(false); // No full verify.
12490 } } // namespace v8::internal