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/ast-numbering.h"
13 #include "src/full-codegen/full-codegen.h"
14 #include "src/hydrogen-bce.h"
15 #include "src/hydrogen-bch.h"
16 #include "src/hydrogen-canonicalize.h"
17 #include "src/hydrogen-check-elimination.h"
18 #include "src/hydrogen-dce.h"
19 #include "src/hydrogen-dehoist.h"
20 #include "src/hydrogen-environment-liveness.h"
21 #include "src/hydrogen-escape-analysis.h"
22 #include "src/hydrogen-gvn.h"
23 #include "src/hydrogen-infer-representation.h"
24 #include "src/hydrogen-infer-types.h"
25 #include "src/hydrogen-load-elimination.h"
26 #include "src/hydrogen-mark-deoptimize.h"
27 #include "src/hydrogen-mark-unreachable.h"
28 #include "src/hydrogen-osr.h"
29 #include "src/hydrogen-range-analysis.h"
30 #include "src/hydrogen-redundant-phi.h"
31 #include "src/hydrogen-removable-simulates.h"
32 #include "src/hydrogen-representation-changes.h"
33 #include "src/hydrogen-sce.h"
34 #include "src/hydrogen-store-elimination.h"
35 #include "src/hydrogen-uint32-analysis.h"
36 #include "src/ic/call-optimization.h"
37 #include "src/ic/ic.h"
39 #include "src/ic/ic-inl.h"
40 #include "src/lithium-allocator.h"
41 #include "src/parser.h"
42 #include "src/runtime/runtime.h"
43 #include "src/scopeinfo.h"
44 #include "src/typing.h"
46 #if V8_TARGET_ARCH_IA32
47 #include "src/ia32/lithium-codegen-ia32.h" // NOLINT
48 #elif V8_TARGET_ARCH_X64
49 #include "src/x64/lithium-codegen-x64.h" // NOLINT
50 #elif V8_TARGET_ARCH_ARM64
51 #include "src/arm64/lithium-codegen-arm64.h" // NOLINT
52 #elif V8_TARGET_ARCH_ARM
53 #include "src/arm/lithium-codegen-arm.h" // NOLINT
54 #elif V8_TARGET_ARCH_PPC
55 #include "src/ppc/lithium-codegen-ppc.h" // NOLINT
56 #elif V8_TARGET_ARCH_MIPS
57 #include "src/mips/lithium-codegen-mips.h" // NOLINT
58 #elif V8_TARGET_ARCH_MIPS64
59 #include "src/mips64/lithium-codegen-mips64.h" // NOLINT
60 #elif V8_TARGET_ARCH_X87
61 #include "src/x87/lithium-codegen-x87.h" // NOLINT
63 #error Unsupported target architecture.
69 HBasicBlock::HBasicBlock(HGraph* graph)
70 : block_id_(graph->GetNextBlockID()),
72 phis_(4, graph->zone()),
76 loop_information_(NULL),
77 predecessors_(2, graph->zone()),
79 dominated_blocks_(4, graph->zone()),
80 last_environment_(NULL),
82 first_instruction_index_(-1),
83 last_instruction_index_(-1),
84 deleted_phis_(4, graph->zone()),
85 parent_loop_header_(NULL),
86 inlined_entry_block_(NULL),
87 is_inline_return_target_(false),
89 dominates_loop_successors_(false),
91 is_ordered_(false) { }
94 Isolate* HBasicBlock::isolate() const {
95 return graph_->isolate();
99 void HBasicBlock::MarkUnreachable() {
100 is_reachable_ = false;
104 void HBasicBlock::AttachLoopInformation() {
105 DCHECK(!IsLoopHeader());
106 loop_information_ = new(zone()) HLoopInformation(this, zone());
110 void HBasicBlock::DetachLoopInformation() {
111 DCHECK(IsLoopHeader());
112 loop_information_ = NULL;
116 void HBasicBlock::AddPhi(HPhi* phi) {
117 DCHECK(!IsStartBlock());
118 phis_.Add(phi, zone());
123 void HBasicBlock::RemovePhi(HPhi* phi) {
124 DCHECK(phi->block() == this);
125 DCHECK(phis_.Contains(phi));
127 phis_.RemoveElement(phi);
132 void HBasicBlock::AddInstruction(HInstruction* instr, SourcePosition position) {
133 DCHECK(!IsStartBlock() || !IsFinished());
134 DCHECK(!instr->IsLinked());
135 DCHECK(!IsFinished());
137 if (!position.IsUnknown()) {
138 instr->set_position(position);
140 if (first_ == NULL) {
141 DCHECK(last_environment() != NULL);
142 DCHECK(!last_environment()->ast_id().IsNone());
143 HBlockEntry* entry = new(zone()) HBlockEntry();
144 entry->InitializeAsFirst(this);
145 if (!position.IsUnknown()) {
146 entry->set_position(position);
148 DCHECK(!FLAG_hydrogen_track_positions ||
149 !graph()->info()->IsOptimizing() || instr->IsAbnormalExit());
151 first_ = last_ = entry;
153 instr->InsertAfter(last_);
157 HPhi* HBasicBlock::AddNewPhi(int merged_index) {
158 if (graph()->IsInsideNoSideEffectsScope()) {
159 merged_index = HPhi::kInvalidMergedIndex;
161 HPhi* phi = new(zone()) HPhi(merged_index, zone());
167 HSimulate* HBasicBlock::CreateSimulate(BailoutId ast_id,
168 RemovableSimulate removable) {
169 DCHECK(HasEnvironment());
170 HEnvironment* environment = last_environment();
171 DCHECK(ast_id.IsNone() ||
172 ast_id == BailoutId::StubEntry() ||
173 environment->closure()->shared()->VerifyBailoutId(ast_id));
175 int push_count = environment->push_count();
176 int pop_count = environment->pop_count();
179 new(zone()) HSimulate(ast_id, pop_count, zone(), removable);
181 instr->set_closure(environment->closure());
183 // Order of pushed values: newest (top of stack) first. This allows
184 // HSimulate::MergeWith() to easily append additional pushed values
185 // that are older (from further down the stack).
186 for (int i = 0; i < push_count; ++i) {
187 instr->AddPushedValue(environment->ExpressionStackAt(i));
189 for (GrowableBitVector::Iterator it(environment->assigned_variables(),
193 int index = it.Current();
194 instr->AddAssignedValue(index, environment->Lookup(index));
196 environment->ClearHistory();
201 void HBasicBlock::Finish(HControlInstruction* end, SourcePosition position) {
202 DCHECK(!IsFinished());
203 AddInstruction(end, position);
205 for (HSuccessorIterator it(end); !it.Done(); it.Advance()) {
206 it.Current()->RegisterPredecessor(this);
211 void HBasicBlock::Goto(HBasicBlock* block, SourcePosition position,
212 FunctionState* state, bool add_simulate) {
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, FunctionState* state,
232 SourcePosition position) {
233 HBasicBlock* target = state->function_return();
234 bool drop_extra = state->inlining_kind() == NORMAL_RETURN;
236 DCHECK(target->IsInlineReturnTarget());
237 DCHECK(return_value != NULL);
238 HEnvironment* env = last_environment();
239 int argument_count = env->arguments_environment()->parameter_count();
240 AddInstruction(new(zone()) HLeaveInlined(state->entry(), argument_count),
242 UpdateEnvironment(last_environment()->DiscardInlined(drop_extra));
243 last_environment()->Push(return_value);
244 AddNewSimulate(BailoutId::None(), position);
245 HGoto* instr = new(zone()) HGoto(target);
246 Finish(instr, position);
250 void HBasicBlock::SetInitialEnvironment(HEnvironment* env) {
251 DCHECK(!HasEnvironment());
252 DCHECK(first() == NULL);
253 UpdateEnvironment(env);
257 void HBasicBlock::UpdateEnvironment(HEnvironment* env) {
258 last_environment_ = env;
259 graph()->update_maximum_environment_size(env->first_expression_index());
263 void HBasicBlock::SetJoinId(BailoutId ast_id) {
264 int length = predecessors_.length();
266 for (int i = 0; i < length; i++) {
267 HBasicBlock* predecessor = predecessors_[i];
268 DCHECK(predecessor->end()->IsGoto());
269 HSimulate* simulate = HSimulate::cast(predecessor->end()->previous());
271 (predecessor->last_environment()->closure().is_null() ||
272 predecessor->last_environment()->closure()->shared()
273 ->VerifyBailoutId(ast_id)));
274 simulate->set_ast_id(ast_id);
275 predecessor->last_environment()->set_ast_id(ast_id);
280 bool HBasicBlock::Dominates(HBasicBlock* other) const {
281 HBasicBlock* current = other->dominator();
282 while (current != NULL) {
283 if (current == this) return true;
284 current = current->dominator();
290 bool HBasicBlock::EqualToOrDominates(HBasicBlock* other) const {
291 if (this == other) return true;
292 return Dominates(other);
296 int HBasicBlock::LoopNestingDepth() const {
297 const HBasicBlock* current = this;
298 int result = (current->IsLoopHeader()) ? 1 : 0;
299 while (current->parent_loop_header() != NULL) {
300 current = current->parent_loop_header();
307 void HBasicBlock::PostProcessLoopHeader(IterationStatement* stmt) {
308 DCHECK(IsLoopHeader());
310 SetJoinId(stmt->EntryId());
311 if (predecessors()->length() == 1) {
312 // This is a degenerated loop.
313 DetachLoopInformation();
317 // Only the first entry into the loop is from outside the loop. All other
318 // entries must be back edges.
319 for (int i = 1; i < predecessors()->length(); ++i) {
320 loop_information()->RegisterBackEdge(predecessors()->at(i));
325 void HBasicBlock::MarkSuccEdgeUnreachable(int succ) {
326 DCHECK(IsFinished());
327 HBasicBlock* succ_block = end()->SuccessorAt(succ);
329 DCHECK(succ_block->predecessors()->length() == 1);
330 succ_block->MarkUnreachable();
334 void HBasicBlock::RegisterPredecessor(HBasicBlock* pred) {
335 if (HasPredecessor()) {
336 // Only loop header blocks can have a predecessor added after
337 // instructions have been added to the block (they have phis for all
338 // values in the environment, these phis may be eliminated later).
339 DCHECK(IsLoopHeader() || first_ == NULL);
340 HEnvironment* incoming_env = pred->last_environment();
341 if (IsLoopHeader()) {
342 DCHECK_EQ(phis()->length(), incoming_env->length());
343 for (int i = 0; i < phis_.length(); ++i) {
344 phis_[i]->AddInput(incoming_env->values()->at(i));
347 last_environment()->AddIncomingEdge(this, pred->last_environment());
349 } else if (!HasEnvironment() && !IsFinished()) {
350 DCHECK(!IsLoopHeader());
351 SetInitialEnvironment(pred->last_environment()->Copy());
354 predecessors_.Add(pred, zone());
358 void HBasicBlock::AddDominatedBlock(HBasicBlock* block) {
359 DCHECK(!dominated_blocks_.Contains(block));
360 // Keep the list of dominated blocks sorted such that if there is two
361 // succeeding block in this list, the predecessor is before the successor.
363 while (index < dominated_blocks_.length() &&
364 dominated_blocks_[index]->block_id() < block->block_id()) {
367 dominated_blocks_.InsertAt(index, block, zone());
371 void HBasicBlock::AssignCommonDominator(HBasicBlock* other) {
372 if (dominator_ == NULL) {
374 other->AddDominatedBlock(this);
375 } else if (other->dominator() != NULL) {
376 HBasicBlock* first = dominator_;
377 HBasicBlock* second = other;
379 while (first != second) {
380 if (first->block_id() > second->block_id()) {
381 first = first->dominator();
383 second = second->dominator();
385 DCHECK(first != NULL && second != NULL);
388 if (dominator_ != first) {
389 DCHECK(dominator_->dominated_blocks_.Contains(this));
390 dominator_->dominated_blocks_.RemoveElement(this);
392 first->AddDominatedBlock(this);
398 void HBasicBlock::AssignLoopSuccessorDominators() {
399 // Mark blocks that dominate all subsequent reachable blocks inside their
400 // loop. Exploit the fact that blocks are sorted in reverse post order. When
401 // the loop is visited in increasing block id order, if the number of
402 // non-loop-exiting successor edges at the dominator_candidate block doesn't
403 // exceed the number of previously encountered predecessor edges, there is no
404 // path from the loop header to any block with higher id that doesn't go
405 // through the dominator_candidate block. In this case, the
406 // dominator_candidate block is guaranteed to dominate all blocks reachable
407 // from it with higher ids.
408 HBasicBlock* last = loop_information()->GetLastBackEdge();
409 int outstanding_successors = 1; // one edge from the pre-header
410 // Header always dominates everything.
411 MarkAsLoopSuccessorDominator();
412 for (int j = block_id(); j <= last->block_id(); ++j) {
413 HBasicBlock* dominator_candidate = graph_->blocks()->at(j);
414 for (HPredecessorIterator it(dominator_candidate); !it.Done();
416 HBasicBlock* predecessor = it.Current();
417 // Don't count back edges.
418 if (predecessor->block_id() < dominator_candidate->block_id()) {
419 outstanding_successors--;
423 // If more successors than predecessors have been seen in the loop up to
424 // now, it's not possible to guarantee that the current block dominates
425 // all of the blocks with higher IDs. In this case, assume conservatively
426 // that those paths through loop that don't go through the current block
427 // contain all of the loop's dependencies. Also be careful to record
428 // dominator information about the current loop that's being processed,
429 // and not nested loops, which will be processed when
430 // AssignLoopSuccessorDominators gets called on their header.
431 DCHECK(outstanding_successors >= 0);
432 HBasicBlock* parent_loop_header = dominator_candidate->parent_loop_header();
433 if (outstanding_successors == 0 &&
434 (parent_loop_header == this && !dominator_candidate->IsLoopHeader())) {
435 dominator_candidate->MarkAsLoopSuccessorDominator();
437 HControlInstruction* end = dominator_candidate->end();
438 for (HSuccessorIterator it(end); !it.Done(); it.Advance()) {
439 HBasicBlock* successor = it.Current();
440 // Only count successors that remain inside the loop and don't loop back
442 if (successor->block_id() > dominator_candidate->block_id() &&
443 successor->block_id() <= last->block_id()) {
444 // Backwards edges must land on loop headers.
445 DCHECK(successor->block_id() > dominator_candidate->block_id() ||
446 successor->IsLoopHeader());
447 outstanding_successors++;
454 int HBasicBlock::PredecessorIndexOf(HBasicBlock* predecessor) const {
455 for (int i = 0; i < predecessors_.length(); ++i) {
456 if (predecessors_[i] == predecessor) return i;
464 void HBasicBlock::Verify() {
465 // Check that every block is finished.
466 DCHECK(IsFinished());
467 DCHECK(block_id() >= 0);
469 // Check that the incoming edges are in edge split form.
470 if (predecessors_.length() > 1) {
471 for (int i = 0; i < predecessors_.length(); ++i) {
472 DCHECK(predecessors_[i]->end()->SecondSuccessor() == NULL);
479 void HLoopInformation::RegisterBackEdge(HBasicBlock* block) {
480 this->back_edges_.Add(block, block->zone());
485 HBasicBlock* HLoopInformation::GetLastBackEdge() const {
487 HBasicBlock* result = NULL;
488 for (int i = 0; i < back_edges_.length(); ++i) {
489 HBasicBlock* cur = back_edges_[i];
490 if (cur->block_id() > max_id) {
491 max_id = cur->block_id();
499 void HLoopInformation::AddBlock(HBasicBlock* block) {
500 if (block == loop_header()) return;
501 if (block->parent_loop_header() == loop_header()) return;
502 if (block->parent_loop_header() != NULL) {
503 AddBlock(block->parent_loop_header());
505 block->set_parent_loop_header(loop_header());
506 blocks_.Add(block, block->zone());
507 for (int i = 0; i < block->predecessors()->length(); ++i) {
508 AddBlock(block->predecessors()->at(i));
516 // Checks reachability of the blocks in this graph and stores a bit in
517 // the BitVector "reachable()" for every block that can be reached
518 // from the start block of the graph. If "dont_visit" is non-null, the given
519 // block is treated as if it would not be part of the graph. "visited_count()"
520 // returns the number of reachable blocks.
521 class ReachabilityAnalyzer BASE_EMBEDDED {
523 ReachabilityAnalyzer(HBasicBlock* entry_block,
525 HBasicBlock* dont_visit)
527 stack_(16, entry_block->zone()),
528 reachable_(block_count, entry_block->zone()),
529 dont_visit_(dont_visit) {
530 PushBlock(entry_block);
534 int visited_count() const { return visited_count_; }
535 const BitVector* reachable() const { return &reachable_; }
538 void PushBlock(HBasicBlock* block) {
539 if (block != NULL && block != dont_visit_ &&
540 !reachable_.Contains(block->block_id())) {
541 reachable_.Add(block->block_id());
542 stack_.Add(block, block->zone());
548 while (!stack_.is_empty()) {
549 HControlInstruction* end = stack_.RemoveLast()->end();
550 for (HSuccessorIterator it(end); !it.Done(); it.Advance()) {
551 PushBlock(it.Current());
557 ZoneList<HBasicBlock*> stack_;
558 BitVector reachable_;
559 HBasicBlock* dont_visit_;
563 void HGraph::Verify(bool do_full_verify) const {
564 Heap::RelocationLock relocation_lock(isolate()->heap());
565 AllowHandleDereference allow_deref;
566 AllowDeferredHandleDereference allow_deferred_deref;
567 for (int i = 0; i < blocks_.length(); i++) {
568 HBasicBlock* block = blocks_.at(i);
572 // Check that every block contains at least one node and that only the last
573 // node is a control instruction.
574 HInstruction* current = block->first();
575 DCHECK(current != NULL && current->IsBlockEntry());
576 while (current != NULL) {
577 DCHECK((current->next() == NULL) == current->IsControlInstruction());
578 DCHECK(current->block() == block);
580 current = current->next();
583 // Check that successors are correctly set.
584 HBasicBlock* first = block->end()->FirstSuccessor();
585 HBasicBlock* second = block->end()->SecondSuccessor();
586 DCHECK(second == NULL || first != NULL);
588 // Check that the predecessor array is correct.
590 DCHECK(first->predecessors()->Contains(block));
591 if (second != NULL) {
592 DCHECK(second->predecessors()->Contains(block));
596 // Check that phis have correct arguments.
597 for (int j = 0; j < block->phis()->length(); j++) {
598 HPhi* phi = block->phis()->at(j);
602 // Check that all join blocks have predecessors that end with an
603 // unconditional goto and agree on their environment node id.
604 if (block->predecessors()->length() >= 2) {
606 block->predecessors()->first()->last_environment()->ast_id();
607 for (int k = 0; k < block->predecessors()->length(); k++) {
608 HBasicBlock* predecessor = block->predecessors()->at(k);
609 DCHECK(predecessor->end()->IsGoto() ||
610 predecessor->end()->IsDeoptimize());
611 DCHECK(predecessor->last_environment()->ast_id() == id);
616 // Check special property of first block to have no predecessors.
617 DCHECK(blocks_.at(0)->predecessors()->is_empty());
619 if (do_full_verify) {
620 // Check that the graph is fully connected.
621 ReachabilityAnalyzer analyzer(entry_block_, blocks_.length(), NULL);
622 DCHECK(analyzer.visited_count() == blocks_.length());
624 // Check that entry block dominator is NULL.
625 DCHECK(entry_block_->dominator() == NULL);
628 for (int i = 0; i < blocks_.length(); ++i) {
629 HBasicBlock* block = blocks_.at(i);
630 if (block->dominator() == NULL) {
631 // Only start block may have no dominator assigned to.
634 // Assert that block is unreachable if dominator must not be visited.
635 ReachabilityAnalyzer dominator_analyzer(entry_block_,
638 DCHECK(!dominator_analyzer.reachable()->Contains(block->block_id()));
647 HConstant* HGraph::GetConstant(SetOncePointer<HConstant>* pointer,
649 if (!pointer->is_set()) {
650 // Can't pass GetInvalidContext() to HConstant::New, because that will
651 // recursively call GetConstant
652 HConstant* constant = HConstant::New(isolate(), zone(), NULL, value);
653 constant->InsertAfter(entry_block()->first());
654 pointer->set(constant);
657 return ReinsertConstantIfNecessary(pointer->get());
661 HConstant* HGraph::ReinsertConstantIfNecessary(HConstant* constant) {
662 if (!constant->IsLinked()) {
663 // The constant was removed from the graph. Reinsert.
664 constant->ClearFlag(HValue::kIsDead);
665 constant->InsertAfter(entry_block()->first());
671 HConstant* HGraph::GetConstant0() {
672 return GetConstant(&constant_0_, 0);
676 HConstant* HGraph::GetConstant1() {
677 return GetConstant(&constant_1_, 1);
681 HConstant* HGraph::GetConstantMinus1() {
682 return GetConstant(&constant_minus1_, -1);
686 HConstant* HGraph::GetConstantBool(bool value) {
687 return value ? GetConstantTrue() : GetConstantFalse();
691 #define DEFINE_GET_CONSTANT(Name, name, type, htype, boolean_value) \
692 HConstant* HGraph::GetConstant##Name() { \
693 if (!constant_##name##_.is_set()) { \
694 HConstant* constant = new(zone()) HConstant( \
695 Unique<Object>::CreateImmovable(isolate()->factory()->name##_value()), \
696 Unique<Map>::CreateImmovable(isolate()->factory()->type##_map()), \
698 Representation::Tagged(), \
704 constant->InsertAfter(entry_block()->first()); \
705 constant_##name##_.set(constant); \
707 return ReinsertConstantIfNecessary(constant_##name##_.get()); \
711 DEFINE_GET_CONSTANT(Undefined, undefined, undefined, HType::Undefined(), false)
712 DEFINE_GET_CONSTANT(True, true, boolean, HType::Boolean(), true)
713 DEFINE_GET_CONSTANT(False, false, boolean, HType::Boolean(), false)
714 DEFINE_GET_CONSTANT(Hole, the_hole, the_hole, HType::None(), false)
715 DEFINE_GET_CONSTANT(Null, null, null, HType::Null(), false)
718 #undef DEFINE_GET_CONSTANT
720 #define DEFINE_IS_CONSTANT(Name, name) \
721 bool HGraph::IsConstant##Name(HConstant* constant) { \
722 return constant_##name##_.is_set() && constant == constant_##name##_.get(); \
724 DEFINE_IS_CONSTANT(Undefined, undefined)
725 DEFINE_IS_CONSTANT(0, 0)
726 DEFINE_IS_CONSTANT(1, 1)
727 DEFINE_IS_CONSTANT(Minus1, minus1)
728 DEFINE_IS_CONSTANT(True, true)
729 DEFINE_IS_CONSTANT(False, false)
730 DEFINE_IS_CONSTANT(Hole, the_hole)
731 DEFINE_IS_CONSTANT(Null, null)
733 #undef DEFINE_IS_CONSTANT
736 HConstant* HGraph::GetInvalidContext() {
737 return GetConstant(&constant_invalid_context_, 0xFFFFC0C7);
741 bool HGraph::IsStandardConstant(HConstant* constant) {
742 if (IsConstantUndefined(constant)) return true;
743 if (IsConstant0(constant)) return true;
744 if (IsConstant1(constant)) return true;
745 if (IsConstantMinus1(constant)) return true;
746 if (IsConstantTrue(constant)) return true;
747 if (IsConstantFalse(constant)) return true;
748 if (IsConstantHole(constant)) return true;
749 if (IsConstantNull(constant)) return true;
754 HGraphBuilder::IfBuilder::IfBuilder() : builder_(NULL), needs_compare_(true) {}
757 HGraphBuilder::IfBuilder::IfBuilder(HGraphBuilder* builder)
758 : needs_compare_(true) {
763 HGraphBuilder::IfBuilder::IfBuilder(HGraphBuilder* builder,
764 HIfContinuation* continuation)
765 : needs_compare_(false), first_true_block_(NULL), first_false_block_(NULL) {
766 InitializeDontCreateBlocks(builder);
767 continuation->Continue(&first_true_block_, &first_false_block_);
771 void HGraphBuilder::IfBuilder::InitializeDontCreateBlocks(
772 HGraphBuilder* builder) {
777 did_else_if_ = false;
781 pending_merge_block_ = false;
782 split_edge_merge_block_ = NULL;
783 merge_at_join_blocks_ = NULL;
784 normal_merge_at_join_block_count_ = 0;
785 deopt_merge_at_join_block_count_ = 0;
789 void HGraphBuilder::IfBuilder::Initialize(HGraphBuilder* builder) {
790 InitializeDontCreateBlocks(builder);
791 HEnvironment* env = builder->environment();
792 first_true_block_ = builder->CreateBasicBlock(env->Copy());
793 first_false_block_ = builder->CreateBasicBlock(env->Copy());
797 HControlInstruction* HGraphBuilder::IfBuilder::AddCompare(
798 HControlInstruction* compare) {
799 DCHECK(did_then_ == did_else_);
801 // Handle if-then-elseif
807 pending_merge_block_ = false;
808 split_edge_merge_block_ = NULL;
809 HEnvironment* env = builder()->environment();
810 first_true_block_ = builder()->CreateBasicBlock(env->Copy());
811 first_false_block_ = builder()->CreateBasicBlock(env->Copy());
813 if (split_edge_merge_block_ != NULL) {
814 HEnvironment* env = first_false_block_->last_environment();
815 HBasicBlock* split_edge = builder()->CreateBasicBlock(env->Copy());
817 compare->SetSuccessorAt(0, split_edge);
818 compare->SetSuccessorAt(1, first_false_block_);
820 compare->SetSuccessorAt(0, first_true_block_);
821 compare->SetSuccessorAt(1, split_edge);
823 builder()->GotoNoSimulate(split_edge, split_edge_merge_block_);
825 compare->SetSuccessorAt(0, first_true_block_);
826 compare->SetSuccessorAt(1, first_false_block_);
828 builder()->FinishCurrentBlock(compare);
829 needs_compare_ = false;
834 void HGraphBuilder::IfBuilder::Or() {
835 DCHECK(!needs_compare_);
838 HEnvironment* env = first_false_block_->last_environment();
839 if (split_edge_merge_block_ == NULL) {
840 split_edge_merge_block_ = builder()->CreateBasicBlock(env->Copy());
841 builder()->GotoNoSimulate(first_true_block_, split_edge_merge_block_);
842 first_true_block_ = split_edge_merge_block_;
844 builder()->set_current_block(first_false_block_);
845 first_false_block_ = builder()->CreateBasicBlock(env->Copy());
849 void HGraphBuilder::IfBuilder::And() {
850 DCHECK(!needs_compare_);
853 HEnvironment* env = first_false_block_->last_environment();
854 if (split_edge_merge_block_ == NULL) {
855 split_edge_merge_block_ = builder()->CreateBasicBlock(env->Copy());
856 builder()->GotoNoSimulate(first_false_block_, split_edge_merge_block_);
857 first_false_block_ = split_edge_merge_block_;
859 builder()->set_current_block(first_true_block_);
860 first_true_block_ = builder()->CreateBasicBlock(env->Copy());
864 void HGraphBuilder::IfBuilder::CaptureContinuation(
865 HIfContinuation* continuation) {
866 DCHECK(!did_else_if_);
870 HBasicBlock* true_block = NULL;
871 HBasicBlock* false_block = NULL;
872 Finish(&true_block, &false_block);
873 DCHECK(true_block != NULL);
874 DCHECK(false_block != NULL);
875 continuation->Capture(true_block, false_block);
877 builder()->set_current_block(NULL);
882 void HGraphBuilder::IfBuilder::JoinContinuation(HIfContinuation* continuation) {
883 DCHECK(!did_else_if_);
886 HBasicBlock* true_block = NULL;
887 HBasicBlock* false_block = NULL;
888 Finish(&true_block, &false_block);
889 merge_at_join_blocks_ = NULL;
890 if (true_block != NULL && !true_block->IsFinished()) {
891 DCHECK(continuation->IsTrueReachable());
892 builder()->GotoNoSimulate(true_block, continuation->true_branch());
894 if (false_block != NULL && !false_block->IsFinished()) {
895 DCHECK(continuation->IsFalseReachable());
896 builder()->GotoNoSimulate(false_block, continuation->false_branch());
903 void HGraphBuilder::IfBuilder::Then() {
907 if (needs_compare_) {
908 // Handle if's without any expressions, they jump directly to the "else"
909 // branch. However, we must pretend that the "then" branch is reachable,
910 // so that the graph builder visits it and sees any live range extending
911 // constructs within it.
912 HConstant* constant_false = builder()->graph()->GetConstantFalse();
913 ToBooleanStub::Types boolean_type = ToBooleanStub::Types();
914 boolean_type.Add(ToBooleanStub::BOOLEAN);
915 HBranch* branch = builder()->New<HBranch>(
916 constant_false, boolean_type, first_true_block_, first_false_block_);
917 builder()->FinishCurrentBlock(branch);
919 builder()->set_current_block(first_true_block_);
920 pending_merge_block_ = true;
924 void HGraphBuilder::IfBuilder::Else() {
928 AddMergeAtJoinBlock(false);
929 builder()->set_current_block(first_false_block_);
930 pending_merge_block_ = true;
935 void HGraphBuilder::IfBuilder::Deopt(Deoptimizer::DeoptReason reason) {
937 builder()->Add<HDeoptimize>(reason, Deoptimizer::EAGER);
938 AddMergeAtJoinBlock(true);
942 void HGraphBuilder::IfBuilder::Return(HValue* value) {
943 HValue* parameter_count = builder()->graph()->GetConstantMinus1();
944 builder()->FinishExitCurrentBlock(
945 builder()->New<HReturn>(value, parameter_count));
946 AddMergeAtJoinBlock(false);
950 void HGraphBuilder::IfBuilder::AddMergeAtJoinBlock(bool deopt) {
951 if (!pending_merge_block_) return;
952 HBasicBlock* block = builder()->current_block();
953 DCHECK(block == NULL || !block->IsFinished());
954 MergeAtJoinBlock* record = new (builder()->zone())
955 MergeAtJoinBlock(block, deopt, merge_at_join_blocks_);
956 merge_at_join_blocks_ = record;
958 DCHECK(block->end() == NULL);
960 normal_merge_at_join_block_count_++;
962 deopt_merge_at_join_block_count_++;
965 builder()->set_current_block(NULL);
966 pending_merge_block_ = false;
970 void HGraphBuilder::IfBuilder::Finish() {
975 AddMergeAtJoinBlock(false);
978 AddMergeAtJoinBlock(false);
984 void HGraphBuilder::IfBuilder::Finish(HBasicBlock** then_continuation,
985 HBasicBlock** else_continuation) {
988 MergeAtJoinBlock* else_record = merge_at_join_blocks_;
989 if (else_continuation != NULL) {
990 *else_continuation = else_record->block_;
992 MergeAtJoinBlock* then_record = else_record->next_;
993 if (then_continuation != NULL) {
994 *then_continuation = then_record->block_;
996 DCHECK(then_record->next_ == NULL);
1000 void HGraphBuilder::IfBuilder::EndUnreachable() {
1001 if (captured_) return;
1003 builder()->set_current_block(nullptr);
1007 void HGraphBuilder::IfBuilder::End() {
1008 if (captured_) return;
1011 int total_merged_blocks = normal_merge_at_join_block_count_ +
1012 deopt_merge_at_join_block_count_;
1013 DCHECK(total_merged_blocks >= 1);
1014 HBasicBlock* merge_block =
1015 total_merged_blocks == 1 ? NULL : builder()->graph()->CreateBasicBlock();
1017 // Merge non-deopt blocks first to ensure environment has right size for
1019 MergeAtJoinBlock* current = merge_at_join_blocks_;
1020 while (current != NULL) {
1021 if (!current->deopt_ && current->block_ != NULL) {
1022 // If there is only one block that makes it through to the end of the
1023 // if, then just set it as the current block and continue rather then
1024 // creating an unnecessary merge block.
1025 if (total_merged_blocks == 1) {
1026 builder()->set_current_block(current->block_);
1029 builder()->GotoNoSimulate(current->block_, merge_block);
1031 current = current->next_;
1034 // Merge deopt blocks, padding when necessary.
1035 current = merge_at_join_blocks_;
1036 while (current != NULL) {
1037 if (current->deopt_ && current->block_ != NULL) {
1038 current->block_->FinishExit(
1039 HAbnormalExit::New(builder()->isolate(), builder()->zone(), NULL),
1040 SourcePosition::Unknown());
1042 current = current->next_;
1044 builder()->set_current_block(merge_block);
1048 HGraphBuilder::LoopBuilder::LoopBuilder(HGraphBuilder* builder) {
1049 Initialize(builder, NULL, kWhileTrue, NULL);
1053 HGraphBuilder::LoopBuilder::LoopBuilder(HGraphBuilder* builder, HValue* context,
1054 LoopBuilder::Direction direction) {
1055 Initialize(builder, context, direction, builder->graph()->GetConstant1());
1059 HGraphBuilder::LoopBuilder::LoopBuilder(HGraphBuilder* builder, HValue* context,
1060 LoopBuilder::Direction direction,
1061 HValue* increment_amount) {
1062 Initialize(builder, context, direction, increment_amount);
1063 increment_amount_ = increment_amount;
1067 void HGraphBuilder::LoopBuilder::Initialize(HGraphBuilder* builder,
1069 Direction direction,
1070 HValue* increment_amount) {
1073 direction_ = direction;
1074 increment_amount_ = increment_amount;
1077 header_block_ = builder->CreateLoopHeaderBlock();
1080 exit_trampoline_block_ = NULL;
1084 HValue* HGraphBuilder::LoopBuilder::BeginBody(
1086 HValue* terminating,
1087 Token::Value token) {
1088 DCHECK(direction_ != kWhileTrue);
1089 HEnvironment* env = builder_->environment();
1090 phi_ = header_block_->AddNewPhi(env->values()->length());
1091 phi_->AddInput(initial);
1093 builder_->GotoNoSimulate(header_block_);
1095 HEnvironment* body_env = env->Copy();
1096 HEnvironment* exit_env = env->Copy();
1097 // Remove the phi from the expression stack
1100 body_block_ = builder_->CreateBasicBlock(body_env);
1101 exit_block_ = builder_->CreateBasicBlock(exit_env);
1103 builder_->set_current_block(header_block_);
1105 builder_->FinishCurrentBlock(builder_->New<HCompareNumericAndBranch>(
1106 phi_, terminating, token, body_block_, exit_block_));
1108 builder_->set_current_block(body_block_);
1109 if (direction_ == kPreIncrement || direction_ == kPreDecrement) {
1110 Isolate* isolate = builder_->isolate();
1111 HValue* one = builder_->graph()->GetConstant1();
1112 if (direction_ == kPreIncrement) {
1113 increment_ = HAdd::New(isolate, zone(), context_, phi_, one);
1115 increment_ = HSub::New(isolate, zone(), context_, phi_, one);
1117 increment_->ClearFlag(HValue::kCanOverflow);
1118 builder_->AddInstruction(increment_);
1126 void HGraphBuilder::LoopBuilder::BeginBody(int drop_count) {
1127 DCHECK(direction_ == kWhileTrue);
1128 HEnvironment* env = builder_->environment();
1129 builder_->GotoNoSimulate(header_block_);
1130 builder_->set_current_block(header_block_);
1131 env->Drop(drop_count);
1135 void HGraphBuilder::LoopBuilder::Break() {
1136 if (exit_trampoline_block_ == NULL) {
1137 // Its the first time we saw a break.
1138 if (direction_ == kWhileTrue) {
1139 HEnvironment* env = builder_->environment()->Copy();
1140 exit_trampoline_block_ = builder_->CreateBasicBlock(env);
1142 HEnvironment* env = exit_block_->last_environment()->Copy();
1143 exit_trampoline_block_ = builder_->CreateBasicBlock(env);
1144 builder_->GotoNoSimulate(exit_block_, exit_trampoline_block_);
1148 builder_->GotoNoSimulate(exit_trampoline_block_);
1149 builder_->set_current_block(NULL);
1153 void HGraphBuilder::LoopBuilder::EndBody() {
1156 if (direction_ == kPostIncrement || direction_ == kPostDecrement) {
1157 Isolate* isolate = builder_->isolate();
1158 if (direction_ == kPostIncrement) {
1160 HAdd::New(isolate, zone(), context_, phi_, increment_amount_);
1163 HSub::New(isolate, zone(), context_, phi_, increment_amount_);
1165 increment_->ClearFlag(HValue::kCanOverflow);
1166 builder_->AddInstruction(increment_);
1169 if (direction_ != kWhileTrue) {
1170 // Push the new increment value on the expression stack to merge into
1172 builder_->environment()->Push(increment_);
1174 HBasicBlock* last_block = builder_->current_block();
1175 builder_->GotoNoSimulate(last_block, header_block_);
1176 header_block_->loop_information()->RegisterBackEdge(last_block);
1178 if (exit_trampoline_block_ != NULL) {
1179 builder_->set_current_block(exit_trampoline_block_);
1181 builder_->set_current_block(exit_block_);
1187 HGraph* HGraphBuilder::CreateGraph() {
1188 graph_ = new(zone()) HGraph(info_);
1189 if (FLAG_hydrogen_stats) isolate()->GetHStatistics()->Initialize(info_);
1190 CompilationPhase phase("H_Block building", info_);
1191 set_current_block(graph()->entry_block());
1192 if (!BuildGraph()) return NULL;
1193 graph()->FinalizeUniqueness();
1198 HInstruction* HGraphBuilder::AddInstruction(HInstruction* instr) {
1199 DCHECK(current_block() != NULL);
1200 DCHECK(!FLAG_hydrogen_track_positions ||
1201 !position_.IsUnknown() ||
1202 !info_->IsOptimizing());
1203 current_block()->AddInstruction(instr, source_position());
1204 if (graph()->IsInsideNoSideEffectsScope()) {
1205 instr->SetFlag(HValue::kHasNoObservableSideEffects);
1211 void HGraphBuilder::FinishCurrentBlock(HControlInstruction* last) {
1212 DCHECK(!FLAG_hydrogen_track_positions ||
1213 !info_->IsOptimizing() ||
1214 !position_.IsUnknown());
1215 current_block()->Finish(last, source_position());
1216 if (last->IsReturn() || last->IsAbnormalExit()) {
1217 set_current_block(NULL);
1222 void HGraphBuilder::FinishExitCurrentBlock(HControlInstruction* instruction) {
1223 DCHECK(!FLAG_hydrogen_track_positions || !info_->IsOptimizing() ||
1224 !position_.IsUnknown());
1225 current_block()->FinishExit(instruction, source_position());
1226 if (instruction->IsReturn() || instruction->IsAbnormalExit()) {
1227 set_current_block(NULL);
1232 void HGraphBuilder::AddIncrementCounter(StatsCounter* counter) {
1233 if (FLAG_native_code_counters && counter->Enabled()) {
1234 HValue* reference = Add<HConstant>(ExternalReference(counter));
1236 Add<HLoadNamedField>(reference, nullptr, HObjectAccess::ForCounter());
1237 HValue* new_value = AddUncasted<HAdd>(old_value, graph()->GetConstant1());
1238 new_value->ClearFlag(HValue::kCanOverflow); // Ignore counter overflow
1239 Add<HStoreNamedField>(reference, HObjectAccess::ForCounter(),
1240 new_value, STORE_TO_INITIALIZED_ENTRY);
1245 void HGraphBuilder::AddSimulate(BailoutId id,
1246 RemovableSimulate removable) {
1247 DCHECK(current_block() != NULL);
1248 DCHECK(!graph()->IsInsideNoSideEffectsScope());
1249 current_block()->AddNewSimulate(id, source_position(), removable);
1253 HBasicBlock* HGraphBuilder::CreateBasicBlock(HEnvironment* env) {
1254 HBasicBlock* b = graph()->CreateBasicBlock();
1255 b->SetInitialEnvironment(env);
1260 HBasicBlock* HGraphBuilder::CreateLoopHeaderBlock() {
1261 HBasicBlock* header = graph()->CreateBasicBlock();
1262 HEnvironment* entry_env = environment()->CopyAsLoopHeader(header);
1263 header->SetInitialEnvironment(entry_env);
1264 header->AttachLoopInformation();
1269 HValue* HGraphBuilder::BuildGetElementsKind(HValue* object) {
1270 HValue* map = Add<HLoadNamedField>(object, nullptr, HObjectAccess::ForMap());
1272 HValue* bit_field2 =
1273 Add<HLoadNamedField>(map, nullptr, HObjectAccess::ForMapBitField2());
1274 return BuildDecodeField<Map::ElementsKindBits>(bit_field2);
1278 HValue* HGraphBuilder::BuildCheckHeapObject(HValue* obj) {
1279 if (obj->type().IsHeapObject()) return obj;
1280 return Add<HCheckHeapObject>(obj);
1284 void HGraphBuilder::FinishExitWithHardDeoptimization(
1285 Deoptimizer::DeoptReason reason) {
1286 Add<HDeoptimize>(reason, Deoptimizer::EAGER);
1287 FinishExitCurrentBlock(New<HAbnormalExit>());
1291 HValue* HGraphBuilder::BuildCheckString(HValue* string) {
1292 if (!string->type().IsString()) {
1293 DCHECK(!string->IsConstant() ||
1294 !HConstant::cast(string)->HasStringValue());
1295 BuildCheckHeapObject(string);
1296 return Add<HCheckInstanceType>(string, HCheckInstanceType::IS_STRING);
1302 HValue* HGraphBuilder::BuildWrapReceiver(HValue* object, HValue* function) {
1303 if (object->type().IsJSObject()) return object;
1304 if (function->IsConstant() &&
1305 HConstant::cast(function)->handle(isolate())->IsJSFunction()) {
1306 Handle<JSFunction> f = Handle<JSFunction>::cast(
1307 HConstant::cast(function)->handle(isolate()));
1308 SharedFunctionInfo* shared = f->shared();
1309 if (is_strict(shared->language_mode()) || shared->native()) return object;
1311 return Add<HWrapReceiver>(object, function);
1315 HValue* HGraphBuilder::BuildCheckAndGrowElementsCapacity(
1316 HValue* object, HValue* elements, ElementsKind kind, HValue* length,
1317 HValue* capacity, HValue* key) {
1318 HValue* max_gap = Add<HConstant>(static_cast<int32_t>(JSObject::kMaxGap));
1319 HValue* max_capacity = AddUncasted<HAdd>(capacity, max_gap);
1320 Add<HBoundsCheck>(key, max_capacity);
1322 HValue* new_capacity = BuildNewElementsCapacity(key);
1323 HValue* new_elements = BuildGrowElementsCapacity(object, elements, kind, kind,
1324 length, new_capacity);
1325 return new_elements;
1329 HValue* HGraphBuilder::BuildCheckForCapacityGrow(
1336 PropertyAccessType access_type) {
1337 IfBuilder length_checker(this);
1339 Token::Value token = IsHoleyElementsKind(kind) ? Token::GTE : Token::EQ;
1340 length_checker.If<HCompareNumericAndBranch>(key, length, token);
1342 length_checker.Then();
1344 HValue* current_capacity = AddLoadFixedArrayLength(elements);
1346 if (top_info()->IsStub()) {
1347 IfBuilder capacity_checker(this);
1348 capacity_checker.If<HCompareNumericAndBranch>(key, current_capacity,
1350 capacity_checker.Then();
1351 HValue* new_elements = BuildCheckAndGrowElementsCapacity(
1352 object, elements, kind, length, current_capacity, key);
1353 environment()->Push(new_elements);
1354 capacity_checker.Else();
1355 environment()->Push(elements);
1356 capacity_checker.End();
1358 HValue* result = Add<HMaybeGrowElements>(
1359 object, elements, key, current_capacity, is_js_array, kind);
1360 environment()->Push(result);
1364 HValue* new_length = AddUncasted<HAdd>(key, graph_->GetConstant1());
1365 new_length->ClearFlag(HValue::kCanOverflow);
1367 Add<HStoreNamedField>(object, HObjectAccess::ForArrayLength(kind),
1371 if (access_type == STORE && kind == FAST_SMI_ELEMENTS) {
1372 HValue* checked_elements = environment()->Top();
1374 // Write zero to ensure that the new element is initialized with some smi.
1375 Add<HStoreKeyed>(checked_elements, key, graph()->GetConstant0(), kind);
1378 length_checker.Else();
1379 Add<HBoundsCheck>(key, length);
1381 environment()->Push(elements);
1382 length_checker.End();
1384 return environment()->Pop();
1388 HValue* HGraphBuilder::BuildCopyElementsOnWrite(HValue* object,
1392 Factory* factory = isolate()->factory();
1394 IfBuilder cow_checker(this);
1396 cow_checker.If<HCompareMap>(elements, factory->fixed_cow_array_map());
1399 HValue* capacity = AddLoadFixedArrayLength(elements);
1401 HValue* new_elements = BuildGrowElementsCapacity(object, elements, kind,
1402 kind, length, capacity);
1404 environment()->Push(new_elements);
1408 environment()->Push(elements);
1412 return environment()->Pop();
1416 void HGraphBuilder::BuildTransitionElementsKind(HValue* object,
1418 ElementsKind from_kind,
1419 ElementsKind to_kind,
1421 DCHECK(!IsFastHoleyElementsKind(from_kind) ||
1422 IsFastHoleyElementsKind(to_kind));
1424 if (AllocationSite::GetMode(from_kind, to_kind) == TRACK_ALLOCATION_SITE) {
1425 Add<HTrapAllocationMemento>(object);
1428 if (!IsSimpleMapChangeTransition(from_kind, to_kind)) {
1429 HInstruction* elements = AddLoadElements(object);
1431 HInstruction* empty_fixed_array = Add<HConstant>(
1432 isolate()->factory()->empty_fixed_array());
1434 IfBuilder if_builder(this);
1436 if_builder.IfNot<HCompareObjectEqAndBranch>(elements, empty_fixed_array);
1440 HInstruction* elements_length = AddLoadFixedArrayLength(elements);
1442 HInstruction* array_length =
1444 ? Add<HLoadNamedField>(object, nullptr,
1445 HObjectAccess::ForArrayLength(from_kind))
1448 BuildGrowElementsCapacity(object, elements, from_kind, to_kind,
1449 array_length, elements_length);
1454 Add<HStoreNamedField>(object, HObjectAccess::ForMap(), map);
1458 void HGraphBuilder::BuildJSObjectCheck(HValue* receiver,
1459 int bit_field_mask) {
1460 // Check that the object isn't a smi.
1461 Add<HCheckHeapObject>(receiver);
1463 // Get the map of the receiver.
1465 Add<HLoadNamedField>(receiver, nullptr, HObjectAccess::ForMap());
1467 // Check the instance type and if an access check is needed, this can be
1468 // done with a single load, since both bytes are adjacent in the map.
1469 HObjectAccess access(HObjectAccess::ForMapInstanceTypeAndBitField());
1470 HValue* instance_type_and_bit_field =
1471 Add<HLoadNamedField>(map, nullptr, access);
1473 HValue* mask = Add<HConstant>(0x00FF | (bit_field_mask << 8));
1474 HValue* and_result = AddUncasted<HBitwise>(Token::BIT_AND,
1475 instance_type_and_bit_field,
1477 HValue* sub_result = AddUncasted<HSub>(and_result,
1478 Add<HConstant>(JS_OBJECT_TYPE));
1479 Add<HBoundsCheck>(sub_result,
1480 Add<HConstant>(LAST_JS_OBJECT_TYPE + 1 - JS_OBJECT_TYPE));
1484 void HGraphBuilder::BuildKeyedIndexCheck(HValue* key,
1485 HIfContinuation* join_continuation) {
1486 // The sometimes unintuitively backward ordering of the ifs below is
1487 // convoluted, but necessary. All of the paths must guarantee that the
1488 // if-true of the continuation returns a smi element index and the if-false of
1489 // the continuation returns either a symbol or a unique string key. All other
1490 // object types cause a deopt to fall back to the runtime.
1492 IfBuilder key_smi_if(this);
1493 key_smi_if.If<HIsSmiAndBranch>(key);
1496 Push(key); // Nothing to do, just continue to true of continuation.
1500 HValue* map = Add<HLoadNamedField>(key, nullptr, HObjectAccess::ForMap());
1501 HValue* instance_type =
1502 Add<HLoadNamedField>(map, nullptr, HObjectAccess::ForMapInstanceType());
1504 // Non-unique string, check for a string with a hash code that is actually
1506 STATIC_ASSERT(LAST_UNIQUE_NAME_TYPE == FIRST_NONSTRING_TYPE);
1507 IfBuilder not_string_or_name_if(this);
1508 not_string_or_name_if.If<HCompareNumericAndBranch>(
1510 Add<HConstant>(LAST_UNIQUE_NAME_TYPE),
1513 not_string_or_name_if.Then();
1515 // Non-smi, non-Name, non-String: Try to convert to smi in case of
1517 // TODO(danno): This could call some variant of ToString
1518 Push(AddUncasted<HForceRepresentation>(key, Representation::Smi()));
1520 not_string_or_name_if.Else();
1522 // String or Name: check explicitly for Name, they can short-circuit
1523 // directly to unique non-index key path.
1524 IfBuilder not_symbol_if(this);
1525 not_symbol_if.If<HCompareNumericAndBranch>(
1527 Add<HConstant>(SYMBOL_TYPE),
1530 not_symbol_if.Then();
1532 // String: check whether the String is a String of an index. If it is,
1533 // extract the index value from the hash.
1534 HValue* hash = Add<HLoadNamedField>(key, nullptr,
1535 HObjectAccess::ForNameHashField());
1536 HValue* not_index_mask = Add<HConstant>(static_cast<int>(
1537 String::kContainsCachedArrayIndexMask));
1539 HValue* not_index_test = AddUncasted<HBitwise>(
1540 Token::BIT_AND, hash, not_index_mask);
1542 IfBuilder string_index_if(this);
1543 string_index_if.If<HCompareNumericAndBranch>(not_index_test,
1544 graph()->GetConstant0(),
1546 string_index_if.Then();
1548 // String with index in hash: extract string and merge to index path.
1549 Push(BuildDecodeField<String::ArrayIndexValueBits>(hash));
1551 string_index_if.Else();
1553 // Key is a non-index String, check for uniqueness/internalization.
1554 // If it's not internalized yet, internalize it now.
1555 HValue* not_internalized_bit = AddUncasted<HBitwise>(
1558 Add<HConstant>(static_cast<int>(kIsNotInternalizedMask)));
1560 IfBuilder internalized(this);
1561 internalized.If<HCompareNumericAndBranch>(not_internalized_bit,
1562 graph()->GetConstant0(),
1564 internalized.Then();
1567 internalized.Else();
1568 Add<HPushArguments>(key);
1569 HValue* intern_key = Add<HCallRuntime>(
1570 isolate()->factory()->empty_string(),
1571 Runtime::FunctionForId(Runtime::kInternalizeString), 1);
1575 // Key guaranteed to be a unique string
1577 string_index_if.JoinContinuation(join_continuation);
1579 not_symbol_if.Else();
1581 Push(key); // Key is symbol
1583 not_symbol_if.JoinContinuation(join_continuation);
1585 not_string_or_name_if.JoinContinuation(join_continuation);
1587 key_smi_if.JoinContinuation(join_continuation);
1591 void HGraphBuilder::BuildNonGlobalObjectCheck(HValue* receiver) {
1592 // Get the the instance type of the receiver, and make sure that it is
1593 // not one of the global object types.
1595 Add<HLoadNamedField>(receiver, nullptr, HObjectAccess::ForMap());
1596 HValue* instance_type =
1597 Add<HLoadNamedField>(map, nullptr, HObjectAccess::ForMapInstanceType());
1598 STATIC_ASSERT(JS_BUILTINS_OBJECT_TYPE == JS_GLOBAL_OBJECT_TYPE + 1);
1599 HValue* min_global_type = Add<HConstant>(JS_GLOBAL_OBJECT_TYPE);
1600 HValue* max_global_type = Add<HConstant>(JS_BUILTINS_OBJECT_TYPE);
1602 IfBuilder if_global_object(this);
1603 if_global_object.If<HCompareNumericAndBranch>(instance_type,
1606 if_global_object.And();
1607 if_global_object.If<HCompareNumericAndBranch>(instance_type,
1610 if_global_object.ThenDeopt(Deoptimizer::kReceiverWasAGlobalObject);
1611 if_global_object.End();
1615 void HGraphBuilder::BuildTestForDictionaryProperties(
1617 HIfContinuation* continuation) {
1618 HValue* properties = Add<HLoadNamedField>(
1619 object, nullptr, HObjectAccess::ForPropertiesPointer());
1620 HValue* properties_map =
1621 Add<HLoadNamedField>(properties, nullptr, HObjectAccess::ForMap());
1622 HValue* hash_map = Add<HLoadRoot>(Heap::kHashTableMapRootIndex);
1623 IfBuilder builder(this);
1624 builder.If<HCompareObjectEqAndBranch>(properties_map, hash_map);
1625 builder.CaptureContinuation(continuation);
1629 HValue* HGraphBuilder::BuildKeyedLookupCacheHash(HValue* object,
1631 // Load the map of the receiver, compute the keyed lookup cache hash
1632 // based on 32 bits of the map pointer and the string hash.
1633 HValue* object_map =
1634 Add<HLoadNamedField>(object, nullptr, HObjectAccess::ForMapAsInteger32());
1635 HValue* shifted_map = AddUncasted<HShr>(
1636 object_map, Add<HConstant>(KeyedLookupCache::kMapHashShift));
1637 HValue* string_hash =
1638 Add<HLoadNamedField>(key, nullptr, HObjectAccess::ForStringHashField());
1639 HValue* shifted_hash = AddUncasted<HShr>(
1640 string_hash, Add<HConstant>(String::kHashShift));
1641 HValue* xor_result = AddUncasted<HBitwise>(Token::BIT_XOR, shifted_map,
1643 int mask = (KeyedLookupCache::kCapacityMask & KeyedLookupCache::kHashMask);
1644 return AddUncasted<HBitwise>(Token::BIT_AND, xor_result,
1645 Add<HConstant>(mask));
1649 HValue* HGraphBuilder::BuildElementIndexHash(HValue* index) {
1650 int32_t seed_value = static_cast<uint32_t>(isolate()->heap()->HashSeed());
1651 HValue* seed = Add<HConstant>(seed_value);
1652 HValue* hash = AddUncasted<HBitwise>(Token::BIT_XOR, index, seed);
1654 // hash = ~hash + (hash << 15);
1655 HValue* shifted_hash = AddUncasted<HShl>(hash, Add<HConstant>(15));
1656 HValue* not_hash = AddUncasted<HBitwise>(Token::BIT_XOR, hash,
1657 graph()->GetConstantMinus1());
1658 hash = AddUncasted<HAdd>(shifted_hash, not_hash);
1660 // hash = hash ^ (hash >> 12);
1661 shifted_hash = AddUncasted<HShr>(hash, Add<HConstant>(12));
1662 hash = AddUncasted<HBitwise>(Token::BIT_XOR, hash, shifted_hash);
1664 // hash = hash + (hash << 2);
1665 shifted_hash = AddUncasted<HShl>(hash, Add<HConstant>(2));
1666 hash = AddUncasted<HAdd>(hash, shifted_hash);
1668 // hash = hash ^ (hash >> 4);
1669 shifted_hash = AddUncasted<HShr>(hash, Add<HConstant>(4));
1670 hash = AddUncasted<HBitwise>(Token::BIT_XOR, hash, shifted_hash);
1672 // hash = hash * 2057;
1673 hash = AddUncasted<HMul>(hash, Add<HConstant>(2057));
1674 hash->ClearFlag(HValue::kCanOverflow);
1676 // hash = hash ^ (hash >> 16);
1677 shifted_hash = AddUncasted<HShr>(hash, Add<HConstant>(16));
1678 return AddUncasted<HBitwise>(Token::BIT_XOR, hash, shifted_hash);
1682 HValue* HGraphBuilder::BuildUncheckedDictionaryElementLoad(
1683 HValue* receiver, HValue* elements, HValue* key, HValue* hash,
1684 LanguageMode language_mode) {
1686 Add<HLoadKeyed>(elements, Add<HConstant>(NameDictionary::kCapacityIndex),
1687 nullptr, FAST_ELEMENTS);
1689 HValue* mask = AddUncasted<HSub>(capacity, graph()->GetConstant1());
1690 mask->ChangeRepresentation(Representation::Integer32());
1691 mask->ClearFlag(HValue::kCanOverflow);
1693 HValue* entry = hash;
1694 HValue* count = graph()->GetConstant1();
1698 HIfContinuation return_or_loop_continuation(graph()->CreateBasicBlock(),
1699 graph()->CreateBasicBlock());
1700 HIfContinuation found_key_match_continuation(graph()->CreateBasicBlock(),
1701 graph()->CreateBasicBlock());
1702 LoopBuilder probe_loop(this);
1703 probe_loop.BeginBody(2); // Drop entry, count from last environment to
1704 // appease live range building without simulates.
1708 entry = AddUncasted<HBitwise>(Token::BIT_AND, entry, mask);
1709 int entry_size = SeededNumberDictionary::kEntrySize;
1710 HValue* base_index = AddUncasted<HMul>(entry, Add<HConstant>(entry_size));
1711 base_index->ClearFlag(HValue::kCanOverflow);
1712 int start_offset = SeededNumberDictionary::kElementsStartIndex;
1714 AddUncasted<HAdd>(base_index, Add<HConstant>(start_offset));
1715 key_index->ClearFlag(HValue::kCanOverflow);
1717 HValue* candidate_key =
1718 Add<HLoadKeyed>(elements, key_index, nullptr, FAST_ELEMENTS);
1719 IfBuilder if_undefined(this);
1720 if_undefined.If<HCompareObjectEqAndBranch>(candidate_key,
1721 graph()->GetConstantUndefined());
1722 if_undefined.Then();
1724 // element == undefined means "not found". Call the runtime.
1725 // TODO(jkummerow): walk the prototype chain instead.
1726 Add<HPushArguments>(receiver, key);
1727 Push(Add<HCallRuntime>(
1728 isolate()->factory()->empty_string(),
1729 Runtime::FunctionForId(is_strong(language_mode)
1730 ? Runtime::kKeyedGetPropertyStrong
1731 : Runtime::kKeyedGetProperty),
1734 if_undefined.Else();
1736 IfBuilder if_match(this);
1737 if_match.If<HCompareObjectEqAndBranch>(candidate_key, key);
1741 // Update non-internalized string in the dictionary with internalized key?
1742 IfBuilder if_update_with_internalized(this);
1744 if_update_with_internalized.IfNot<HIsSmiAndBranch>(candidate_key);
1745 if_update_with_internalized.And();
1746 HValue* map = AddLoadMap(candidate_key, smi_check);
1747 HValue* instance_type =
1748 Add<HLoadNamedField>(map, nullptr, HObjectAccess::ForMapInstanceType());
1749 HValue* not_internalized_bit = AddUncasted<HBitwise>(
1750 Token::BIT_AND, instance_type,
1751 Add<HConstant>(static_cast<int>(kIsNotInternalizedMask)));
1752 if_update_with_internalized.If<HCompareNumericAndBranch>(
1753 not_internalized_bit, graph()->GetConstant0(), Token::NE);
1754 if_update_with_internalized.And();
1755 if_update_with_internalized.IfNot<HCompareObjectEqAndBranch>(
1756 candidate_key, graph()->GetConstantHole());
1757 if_update_with_internalized.AndIf<HStringCompareAndBranch>(candidate_key,
1759 if_update_with_internalized.Then();
1760 // Replace a key that is a non-internalized string by the equivalent
1761 // internalized string for faster further lookups.
1762 Add<HStoreKeyed>(elements, key_index, key, FAST_ELEMENTS);
1763 if_update_with_internalized.Else();
1765 if_update_with_internalized.JoinContinuation(&found_key_match_continuation);
1766 if_match.JoinContinuation(&found_key_match_continuation);
1768 IfBuilder found_key_match(this, &found_key_match_continuation);
1769 found_key_match.Then();
1770 // Key at current probe matches. Relevant bits in the |details| field must
1771 // be zero, otherwise the dictionary element requires special handling.
1772 HValue* details_index =
1773 AddUncasted<HAdd>(base_index, Add<HConstant>(start_offset + 2));
1774 details_index->ClearFlag(HValue::kCanOverflow);
1776 Add<HLoadKeyed>(elements, details_index, nullptr, FAST_ELEMENTS);
1777 int details_mask = PropertyDetails::TypeField::kMask;
1778 details = AddUncasted<HBitwise>(Token::BIT_AND, details,
1779 Add<HConstant>(details_mask));
1780 IfBuilder details_compare(this);
1781 details_compare.If<HCompareNumericAndBranch>(
1782 details, graph()->GetConstant0(), Token::EQ);
1783 details_compare.Then();
1784 HValue* result_index =
1785 AddUncasted<HAdd>(base_index, Add<HConstant>(start_offset + 1));
1786 result_index->ClearFlag(HValue::kCanOverflow);
1787 Push(Add<HLoadKeyed>(elements, result_index, nullptr, FAST_ELEMENTS));
1788 details_compare.Else();
1789 Add<HPushArguments>(receiver, key);
1790 Push(Add<HCallRuntime>(
1791 isolate()->factory()->empty_string(),
1792 Runtime::FunctionForId(is_strong(language_mode)
1793 ? Runtime::kKeyedGetPropertyStrong
1794 : Runtime::kKeyedGetProperty),
1796 details_compare.End();
1798 found_key_match.Else();
1799 found_key_match.JoinContinuation(&return_or_loop_continuation);
1801 if_undefined.JoinContinuation(&return_or_loop_continuation);
1803 IfBuilder return_or_loop(this, &return_or_loop_continuation);
1804 return_or_loop.Then();
1807 return_or_loop.Else();
1808 entry = AddUncasted<HAdd>(entry, count);
1809 entry->ClearFlag(HValue::kCanOverflow);
1810 count = AddUncasted<HAdd>(count, graph()->GetConstant1());
1811 count->ClearFlag(HValue::kCanOverflow);
1815 probe_loop.EndBody();
1817 return_or_loop.End();
1823 HValue* HGraphBuilder::BuildRegExpConstructResult(HValue* length,
1826 NoObservableSideEffectsScope scope(this);
1827 HConstant* max_length = Add<HConstant>(JSObject::kInitialMaxFastElementArray);
1828 Add<HBoundsCheck>(length, max_length);
1830 // Generate size calculation code here in order to make it dominate
1831 // the JSRegExpResult allocation.
1832 ElementsKind elements_kind = FAST_ELEMENTS;
1833 HValue* size = BuildCalculateElementsSize(elements_kind, length);
1835 // Allocate the JSRegExpResult and the FixedArray in one step.
1836 HValue* result = Add<HAllocate>(
1837 Add<HConstant>(JSRegExpResult::kSize), HType::JSArray(),
1838 NOT_TENURED, JS_ARRAY_TYPE);
1840 // Initialize the JSRegExpResult header.
1841 HValue* global_object = Add<HLoadNamedField>(
1843 HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
1844 HValue* native_context = Add<HLoadNamedField>(
1845 global_object, nullptr, HObjectAccess::ForGlobalObjectNativeContext());
1846 Add<HStoreNamedField>(
1847 result, HObjectAccess::ForMap(),
1848 Add<HLoadNamedField>(
1849 native_context, nullptr,
1850 HObjectAccess::ForContextSlot(Context::REGEXP_RESULT_MAP_INDEX)));
1851 HConstant* empty_fixed_array =
1852 Add<HConstant>(isolate()->factory()->empty_fixed_array());
1853 Add<HStoreNamedField>(
1854 result, HObjectAccess::ForJSArrayOffset(JSArray::kPropertiesOffset),
1856 Add<HStoreNamedField>(
1857 result, HObjectAccess::ForJSArrayOffset(JSArray::kElementsOffset),
1859 Add<HStoreNamedField>(
1860 result, HObjectAccess::ForJSArrayOffset(JSArray::kLengthOffset), length);
1862 // Initialize the additional fields.
1863 Add<HStoreNamedField>(
1864 result, HObjectAccess::ForJSArrayOffset(JSRegExpResult::kIndexOffset),
1866 Add<HStoreNamedField>(
1867 result, HObjectAccess::ForJSArrayOffset(JSRegExpResult::kInputOffset),
1870 // Allocate and initialize the elements header.
1871 HAllocate* elements = BuildAllocateElements(elements_kind, size);
1872 BuildInitializeElementsHeader(elements, elements_kind, length);
1874 if (!elements->has_size_upper_bound()) {
1875 HConstant* size_in_bytes_upper_bound = EstablishElementsAllocationSize(
1876 elements_kind, max_length->Integer32Value());
1877 elements->set_size_upper_bound(size_in_bytes_upper_bound);
1880 Add<HStoreNamedField>(
1881 result, HObjectAccess::ForJSArrayOffset(JSArray::kElementsOffset),
1884 // Initialize the elements contents with undefined.
1885 BuildFillElementsWithValue(
1886 elements, elements_kind, graph()->GetConstant0(), length,
1887 graph()->GetConstantUndefined());
1893 HValue* HGraphBuilder::BuildNumberToString(HValue* object, Type* type) {
1894 NoObservableSideEffectsScope scope(this);
1896 // Convert constant numbers at compile time.
1897 if (object->IsConstant() && HConstant::cast(object)->HasNumberValue()) {
1898 Handle<Object> number = HConstant::cast(object)->handle(isolate());
1899 Handle<String> result = isolate()->factory()->NumberToString(number);
1900 return Add<HConstant>(result);
1903 // Create a joinable continuation.
1904 HIfContinuation found(graph()->CreateBasicBlock(),
1905 graph()->CreateBasicBlock());
1907 // Load the number string cache.
1908 HValue* number_string_cache =
1909 Add<HLoadRoot>(Heap::kNumberStringCacheRootIndex);
1911 // Make the hash mask from the length of the number string cache. It
1912 // contains two elements (number and string) for each cache entry.
1913 HValue* mask = AddLoadFixedArrayLength(number_string_cache);
1914 mask->set_type(HType::Smi());
1915 mask = AddUncasted<HSar>(mask, graph()->GetConstant1());
1916 mask = AddUncasted<HSub>(mask, graph()->GetConstant1());
1918 // Check whether object is a smi.
1919 IfBuilder if_objectissmi(this);
1920 if_objectissmi.If<HIsSmiAndBranch>(object);
1921 if_objectissmi.Then();
1923 // Compute hash for smi similar to smi_get_hash().
1924 HValue* hash = AddUncasted<HBitwise>(Token::BIT_AND, object, mask);
1927 HValue* key_index = AddUncasted<HShl>(hash, graph()->GetConstant1());
1928 HValue* key = Add<HLoadKeyed>(number_string_cache, key_index, nullptr,
1929 FAST_ELEMENTS, ALLOW_RETURN_HOLE);
1931 // Check if object == key.
1932 IfBuilder if_objectiskey(this);
1933 if_objectiskey.If<HCompareObjectEqAndBranch>(object, key);
1934 if_objectiskey.Then();
1936 // Make the key_index available.
1939 if_objectiskey.JoinContinuation(&found);
1941 if_objectissmi.Else();
1943 if (type->Is(Type::SignedSmall())) {
1944 if_objectissmi.Deopt(Deoptimizer::kExpectedSmi);
1946 // Check if the object is a heap number.
1947 IfBuilder if_objectisnumber(this);
1948 HValue* objectisnumber = if_objectisnumber.If<HCompareMap>(
1949 object, isolate()->factory()->heap_number_map());
1950 if_objectisnumber.Then();
1952 // Compute hash for heap number similar to double_get_hash().
1953 HValue* low = Add<HLoadNamedField>(
1954 object, objectisnumber,
1955 HObjectAccess::ForHeapNumberValueLowestBits());
1956 HValue* high = Add<HLoadNamedField>(
1957 object, objectisnumber,
1958 HObjectAccess::ForHeapNumberValueHighestBits());
1959 HValue* hash = AddUncasted<HBitwise>(Token::BIT_XOR, low, high);
1960 hash = AddUncasted<HBitwise>(Token::BIT_AND, hash, mask);
1963 HValue* key_index = AddUncasted<HShl>(hash, graph()->GetConstant1());
1964 HValue* key = Add<HLoadKeyed>(number_string_cache, key_index, nullptr,
1965 FAST_ELEMENTS, ALLOW_RETURN_HOLE);
1967 // Check if the key is a heap number and compare it with the object.
1968 IfBuilder if_keyisnotsmi(this);
1969 HValue* keyisnotsmi = if_keyisnotsmi.IfNot<HIsSmiAndBranch>(key);
1970 if_keyisnotsmi.Then();
1972 IfBuilder if_keyisheapnumber(this);
1973 if_keyisheapnumber.If<HCompareMap>(
1974 key, isolate()->factory()->heap_number_map());
1975 if_keyisheapnumber.Then();
1977 // Check if values of key and object match.
1978 IfBuilder if_keyeqobject(this);
1979 if_keyeqobject.If<HCompareNumericAndBranch>(
1980 Add<HLoadNamedField>(key, keyisnotsmi,
1981 HObjectAccess::ForHeapNumberValue()),
1982 Add<HLoadNamedField>(object, objectisnumber,
1983 HObjectAccess::ForHeapNumberValue()),
1985 if_keyeqobject.Then();
1987 // Make the key_index available.
1990 if_keyeqobject.JoinContinuation(&found);
1992 if_keyisheapnumber.JoinContinuation(&found);
1994 if_keyisnotsmi.JoinContinuation(&found);
1996 if_objectisnumber.Else();
1998 if (type->Is(Type::Number())) {
1999 if_objectisnumber.Deopt(Deoptimizer::kExpectedHeapNumber);
2002 if_objectisnumber.JoinContinuation(&found);
2005 if_objectissmi.JoinContinuation(&found);
2007 // Check for cache hit.
2008 IfBuilder if_found(this, &found);
2011 // Count number to string operation in native code.
2012 AddIncrementCounter(isolate()->counters()->number_to_string_native());
2014 // Load the value in case of cache hit.
2015 HValue* key_index = Pop();
2016 HValue* value_index = AddUncasted<HAdd>(key_index, graph()->GetConstant1());
2017 Push(Add<HLoadKeyed>(number_string_cache, value_index, nullptr,
2018 FAST_ELEMENTS, ALLOW_RETURN_HOLE));
2022 // Cache miss, fallback to runtime.
2023 Add<HPushArguments>(object);
2024 Push(Add<HCallRuntime>(
2025 isolate()->factory()->empty_string(),
2026 Runtime::FunctionForId(Runtime::kNumberToStringSkipCache),
2035 HAllocate* HGraphBuilder::BuildAllocate(
2036 HValue* object_size,
2038 InstanceType instance_type,
2039 HAllocationMode allocation_mode) {
2040 // Compute the effective allocation size.
2041 HValue* size = object_size;
2042 if (allocation_mode.CreateAllocationMementos()) {
2043 size = AddUncasted<HAdd>(size, Add<HConstant>(AllocationMemento::kSize));
2044 size->ClearFlag(HValue::kCanOverflow);
2047 // Perform the actual allocation.
2048 HAllocate* object = Add<HAllocate>(
2049 size, type, allocation_mode.GetPretenureMode(),
2050 instance_type, allocation_mode.feedback_site());
2052 // Setup the allocation memento.
2053 if (allocation_mode.CreateAllocationMementos()) {
2054 BuildCreateAllocationMemento(
2055 object, object_size, allocation_mode.current_site());
2062 HValue* HGraphBuilder::BuildAddStringLengths(HValue* left_length,
2063 HValue* right_length) {
2064 // Compute the combined string length and check against max string length.
2065 HValue* length = AddUncasted<HAdd>(left_length, right_length);
2066 // Check that length <= kMaxLength <=> length < MaxLength + 1.
2067 HValue* max_length = Add<HConstant>(String::kMaxLength + 1);
2068 Add<HBoundsCheck>(length, max_length);
2073 HValue* HGraphBuilder::BuildCreateConsString(
2077 HAllocationMode allocation_mode) {
2078 // Determine the string instance types.
2079 HInstruction* left_instance_type = AddLoadStringInstanceType(left);
2080 HInstruction* right_instance_type = AddLoadStringInstanceType(right);
2082 // Allocate the cons string object. HAllocate does not care whether we
2083 // pass CONS_STRING_TYPE or CONS_ONE_BYTE_STRING_TYPE here, so we just use
2084 // CONS_STRING_TYPE here. Below we decide whether the cons string is
2085 // one-byte or two-byte and set the appropriate map.
2086 DCHECK(HAllocate::CompatibleInstanceTypes(CONS_STRING_TYPE,
2087 CONS_ONE_BYTE_STRING_TYPE));
2088 HAllocate* result = BuildAllocate(Add<HConstant>(ConsString::kSize),
2089 HType::String(), CONS_STRING_TYPE,
2092 // Compute intersection and difference of instance types.
2093 HValue* anded_instance_types = AddUncasted<HBitwise>(
2094 Token::BIT_AND, left_instance_type, right_instance_type);
2095 HValue* xored_instance_types = AddUncasted<HBitwise>(
2096 Token::BIT_XOR, left_instance_type, right_instance_type);
2098 // We create a one-byte cons string if
2099 // 1. both strings are one-byte, or
2100 // 2. at least one of the strings is two-byte, but happens to contain only
2101 // one-byte characters.
2102 // To do this, we check
2103 // 1. if both strings are one-byte, or if the one-byte data hint is set in
2105 // 2. if one of the strings has the one-byte data hint set and the other
2106 // string is one-byte.
2107 IfBuilder if_onebyte(this);
2108 STATIC_ASSERT(kOneByteStringTag != 0);
2109 STATIC_ASSERT(kOneByteDataHintMask != 0);
2110 if_onebyte.If<HCompareNumericAndBranch>(
2111 AddUncasted<HBitwise>(
2112 Token::BIT_AND, anded_instance_types,
2113 Add<HConstant>(static_cast<int32_t>(
2114 kStringEncodingMask | kOneByteDataHintMask))),
2115 graph()->GetConstant0(), Token::NE);
2117 STATIC_ASSERT(kOneByteStringTag != 0 &&
2118 kOneByteDataHintTag != 0 &&
2119 kOneByteDataHintTag != kOneByteStringTag);
2120 if_onebyte.If<HCompareNumericAndBranch>(
2121 AddUncasted<HBitwise>(
2122 Token::BIT_AND, xored_instance_types,
2123 Add<HConstant>(static_cast<int32_t>(
2124 kOneByteStringTag | kOneByteDataHintTag))),
2125 Add<HConstant>(static_cast<int32_t>(
2126 kOneByteStringTag | kOneByteDataHintTag)), Token::EQ);
2129 // We can safely skip the write barrier for storing the map here.
2130 Add<HStoreNamedField>(
2131 result, HObjectAccess::ForMap(),
2132 Add<HConstant>(isolate()->factory()->cons_one_byte_string_map()));
2136 // We can safely skip the write barrier for storing the map here.
2137 Add<HStoreNamedField>(
2138 result, HObjectAccess::ForMap(),
2139 Add<HConstant>(isolate()->factory()->cons_string_map()));
2143 // Initialize the cons string fields.
2144 Add<HStoreNamedField>(result, HObjectAccess::ForStringHashField(),
2145 Add<HConstant>(String::kEmptyHashField));
2146 Add<HStoreNamedField>(result, HObjectAccess::ForStringLength(), length);
2147 Add<HStoreNamedField>(result, HObjectAccess::ForConsStringFirst(), left);
2148 Add<HStoreNamedField>(result, HObjectAccess::ForConsStringSecond(), right);
2150 // Count the native string addition.
2151 AddIncrementCounter(isolate()->counters()->string_add_native());
2157 void HGraphBuilder::BuildCopySeqStringChars(HValue* src,
2159 String::Encoding src_encoding,
2162 String::Encoding dst_encoding,
2164 DCHECK(dst_encoding != String::ONE_BYTE_ENCODING ||
2165 src_encoding == String::ONE_BYTE_ENCODING);
2166 LoopBuilder loop(this, context(), LoopBuilder::kPostIncrement);
2167 HValue* index = loop.BeginBody(graph()->GetConstant0(), length, Token::LT);
2169 HValue* src_index = AddUncasted<HAdd>(src_offset, index);
2171 AddUncasted<HSeqStringGetChar>(src_encoding, src, src_index);
2172 HValue* dst_index = AddUncasted<HAdd>(dst_offset, index);
2173 Add<HSeqStringSetChar>(dst_encoding, dst, dst_index, value);
2179 HValue* HGraphBuilder::BuildObjectSizeAlignment(
2180 HValue* unaligned_size, int header_size) {
2181 DCHECK((header_size & kObjectAlignmentMask) == 0);
2182 HValue* size = AddUncasted<HAdd>(
2183 unaligned_size, Add<HConstant>(static_cast<int32_t>(
2184 header_size + kObjectAlignmentMask)));
2185 size->ClearFlag(HValue::kCanOverflow);
2186 return AddUncasted<HBitwise>(
2187 Token::BIT_AND, size, Add<HConstant>(static_cast<int32_t>(
2188 ~kObjectAlignmentMask)));
2192 HValue* HGraphBuilder::BuildUncheckedStringAdd(
2195 HAllocationMode allocation_mode) {
2196 // Determine the string lengths.
2197 HValue* left_length = AddLoadStringLength(left);
2198 HValue* right_length = AddLoadStringLength(right);
2200 // Compute the combined string length.
2201 HValue* length = BuildAddStringLengths(left_length, right_length);
2203 // Do some manual constant folding here.
2204 if (left_length->IsConstant()) {
2205 HConstant* c_left_length = HConstant::cast(left_length);
2206 DCHECK_NE(0, c_left_length->Integer32Value());
2207 if (c_left_length->Integer32Value() + 1 >= ConsString::kMinLength) {
2208 // The right string contains at least one character.
2209 return BuildCreateConsString(length, left, right, allocation_mode);
2211 } else if (right_length->IsConstant()) {
2212 HConstant* c_right_length = HConstant::cast(right_length);
2213 DCHECK_NE(0, c_right_length->Integer32Value());
2214 if (c_right_length->Integer32Value() + 1 >= ConsString::kMinLength) {
2215 // The left string contains at least one character.
2216 return BuildCreateConsString(length, left, right, allocation_mode);
2220 // Check if we should create a cons string.
2221 IfBuilder if_createcons(this);
2222 if_createcons.If<HCompareNumericAndBranch>(
2223 length, Add<HConstant>(ConsString::kMinLength), Token::GTE);
2224 if_createcons.Then();
2226 // Create a cons string.
2227 Push(BuildCreateConsString(length, left, right, allocation_mode));
2229 if_createcons.Else();
2231 // Determine the string instance types.
2232 HValue* left_instance_type = AddLoadStringInstanceType(left);
2233 HValue* right_instance_type = AddLoadStringInstanceType(right);
2235 // Compute union and difference of instance types.
2236 HValue* ored_instance_types = AddUncasted<HBitwise>(
2237 Token::BIT_OR, left_instance_type, right_instance_type);
2238 HValue* xored_instance_types = AddUncasted<HBitwise>(
2239 Token::BIT_XOR, left_instance_type, right_instance_type);
2241 // Check if both strings have the same encoding and both are
2243 IfBuilder if_sameencodingandsequential(this);
2244 if_sameencodingandsequential.If<HCompareNumericAndBranch>(
2245 AddUncasted<HBitwise>(
2246 Token::BIT_AND, xored_instance_types,
2247 Add<HConstant>(static_cast<int32_t>(kStringEncodingMask))),
2248 graph()->GetConstant0(), Token::EQ);
2249 if_sameencodingandsequential.And();
2250 STATIC_ASSERT(kSeqStringTag == 0);
2251 if_sameencodingandsequential.If<HCompareNumericAndBranch>(
2252 AddUncasted<HBitwise>(
2253 Token::BIT_AND, ored_instance_types,
2254 Add<HConstant>(static_cast<int32_t>(kStringRepresentationMask))),
2255 graph()->GetConstant0(), Token::EQ);
2256 if_sameencodingandsequential.Then();
2258 HConstant* string_map =
2259 Add<HConstant>(isolate()->factory()->string_map());
2260 HConstant* one_byte_string_map =
2261 Add<HConstant>(isolate()->factory()->one_byte_string_map());
2263 // Determine map and size depending on whether result is one-byte string.
2264 IfBuilder if_onebyte(this);
2265 STATIC_ASSERT(kOneByteStringTag != 0);
2266 if_onebyte.If<HCompareNumericAndBranch>(
2267 AddUncasted<HBitwise>(
2268 Token::BIT_AND, ored_instance_types,
2269 Add<HConstant>(static_cast<int32_t>(kStringEncodingMask))),
2270 graph()->GetConstant0(), Token::NE);
2273 // Allocate sequential one-byte string object.
2275 Push(one_byte_string_map);
2279 // Allocate sequential two-byte string object.
2280 HValue* size = AddUncasted<HShl>(length, graph()->GetConstant1());
2281 size->ClearFlag(HValue::kCanOverflow);
2282 size->SetFlag(HValue::kUint32);
2287 HValue* map = Pop();
2289 // Calculate the number of bytes needed for the characters in the
2290 // string while observing object alignment.
2291 STATIC_ASSERT((SeqString::kHeaderSize & kObjectAlignmentMask) == 0);
2292 HValue* size = BuildObjectSizeAlignment(Pop(), SeqString::kHeaderSize);
2294 // Allocate the string object. HAllocate does not care whether we pass
2295 // STRING_TYPE or ONE_BYTE_STRING_TYPE here, so we just use STRING_TYPE.
2296 HAllocate* result = BuildAllocate(
2297 size, HType::String(), STRING_TYPE, allocation_mode);
2298 Add<HStoreNamedField>(result, HObjectAccess::ForMap(), map);
2300 // Initialize the string fields.
2301 Add<HStoreNamedField>(result, HObjectAccess::ForStringHashField(),
2302 Add<HConstant>(String::kEmptyHashField));
2303 Add<HStoreNamedField>(result, HObjectAccess::ForStringLength(), length);
2305 // Copy characters to the result string.
2306 IfBuilder if_twobyte(this);
2307 if_twobyte.If<HCompareObjectEqAndBranch>(map, string_map);
2310 // Copy characters from the left string.
2311 BuildCopySeqStringChars(
2312 left, graph()->GetConstant0(), String::TWO_BYTE_ENCODING,
2313 result, graph()->GetConstant0(), String::TWO_BYTE_ENCODING,
2316 // Copy characters from the right string.
2317 BuildCopySeqStringChars(
2318 right, graph()->GetConstant0(), String::TWO_BYTE_ENCODING,
2319 result, left_length, String::TWO_BYTE_ENCODING,
2324 // Copy characters from the left string.
2325 BuildCopySeqStringChars(
2326 left, graph()->GetConstant0(), String::ONE_BYTE_ENCODING,
2327 result, graph()->GetConstant0(), String::ONE_BYTE_ENCODING,
2330 // Copy characters from the right string.
2331 BuildCopySeqStringChars(
2332 right, graph()->GetConstant0(), String::ONE_BYTE_ENCODING,
2333 result, left_length, String::ONE_BYTE_ENCODING,
2338 // Count the native string addition.
2339 AddIncrementCounter(isolate()->counters()->string_add_native());
2341 // Return the sequential string.
2344 if_sameencodingandsequential.Else();
2346 // Fallback to the runtime to add the two strings.
2347 Add<HPushArguments>(left, right);
2348 Push(Add<HCallRuntime>(isolate()->factory()->empty_string(),
2349 Runtime::FunctionForId(Runtime::kStringAddRT), 2));
2351 if_sameencodingandsequential.End();
2353 if_createcons.End();
2359 HValue* HGraphBuilder::BuildStringAdd(
2362 HAllocationMode allocation_mode) {
2363 NoObservableSideEffectsScope no_effects(this);
2365 // Determine string lengths.
2366 HValue* left_length = AddLoadStringLength(left);
2367 HValue* right_length = AddLoadStringLength(right);
2369 // Check if left string is empty.
2370 IfBuilder if_leftempty(this);
2371 if_leftempty.If<HCompareNumericAndBranch>(
2372 left_length, graph()->GetConstant0(), Token::EQ);
2373 if_leftempty.Then();
2375 // Count the native string addition.
2376 AddIncrementCounter(isolate()->counters()->string_add_native());
2378 // Just return the right string.
2381 if_leftempty.Else();
2383 // Check if right string is empty.
2384 IfBuilder if_rightempty(this);
2385 if_rightempty.If<HCompareNumericAndBranch>(
2386 right_length, graph()->GetConstant0(), Token::EQ);
2387 if_rightempty.Then();
2389 // Count the native string addition.
2390 AddIncrementCounter(isolate()->counters()->string_add_native());
2392 // Just return the left string.
2395 if_rightempty.Else();
2397 // Add the two non-empty strings.
2398 Push(BuildUncheckedStringAdd(left, right, allocation_mode));
2400 if_rightempty.End();
2408 HInstruction* HGraphBuilder::BuildUncheckedMonomorphicElementAccess(
2409 HValue* checked_object,
2413 ElementsKind elements_kind,
2414 PropertyAccessType access_type,
2415 LoadKeyedHoleMode load_mode,
2416 KeyedAccessStoreMode store_mode) {
2417 DCHECK(top_info()->IsStub() || checked_object->IsCompareMap() ||
2418 checked_object->IsCheckMaps());
2419 DCHECK(!IsFixedTypedArrayElementsKind(elements_kind) || !is_js_array);
2420 // No GVNFlag is necessary for ElementsKind if there is an explicit dependency
2421 // on a HElementsTransition instruction. The flag can also be removed if the
2422 // map to check has FAST_HOLEY_ELEMENTS, since there can be no further
2423 // ElementsKind transitions. Finally, the dependency can be removed for stores
2424 // for FAST_ELEMENTS, since a transition to HOLEY elements won't change the
2425 // generated store code.
2426 if ((elements_kind == FAST_HOLEY_ELEMENTS) ||
2427 (elements_kind == FAST_ELEMENTS && access_type == STORE)) {
2428 checked_object->ClearDependsOnFlag(kElementsKind);
2431 bool fast_smi_only_elements = IsFastSmiElementsKind(elements_kind);
2432 bool fast_elements = IsFastObjectElementsKind(elements_kind);
2433 HValue* elements = AddLoadElements(checked_object);
2434 if (access_type == STORE && (fast_elements || fast_smi_only_elements) &&
2435 store_mode != STORE_NO_TRANSITION_HANDLE_COW) {
2436 HCheckMaps* check_cow_map = Add<HCheckMaps>(
2437 elements, isolate()->factory()->fixed_array_map());
2438 check_cow_map->ClearDependsOnFlag(kElementsKind);
2440 HInstruction* length = NULL;
2442 length = Add<HLoadNamedField>(
2443 checked_object->ActualValue(), checked_object,
2444 HObjectAccess::ForArrayLength(elements_kind));
2446 length = AddLoadFixedArrayLength(elements);
2448 length->set_type(HType::Smi());
2449 HValue* checked_key = NULL;
2450 if (IsFixedTypedArrayElementsKind(elements_kind)) {
2451 checked_object = Add<HCheckArrayBufferNotNeutered>(checked_object);
2453 HValue* external_pointer = Add<HLoadNamedField>(
2455 HObjectAccess::ForFixedTypedArrayBaseExternalPointer());
2456 HValue* base_pointer = Add<HLoadNamedField>(
2457 elements, nullptr, HObjectAccess::ForFixedTypedArrayBaseBasePointer());
2458 HValue* backing_store = AddUncasted<HAdd>(
2459 external_pointer, base_pointer, Strength::WEAK, AddOfExternalAndTagged);
2461 if (store_mode == STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
2462 NoObservableSideEffectsScope no_effects(this);
2463 IfBuilder length_checker(this);
2464 length_checker.If<HCompareNumericAndBranch>(key, length, Token::LT);
2465 length_checker.Then();
2466 IfBuilder negative_checker(this);
2467 HValue* bounds_check = negative_checker.If<HCompareNumericAndBranch>(
2468 key, graph()->GetConstant0(), Token::GTE);
2469 negative_checker.Then();
2470 HInstruction* result = AddElementAccess(
2471 backing_store, key, val, bounds_check, elements_kind, access_type);
2472 negative_checker.ElseDeopt(Deoptimizer::kNegativeKeyEncountered);
2473 negative_checker.End();
2474 length_checker.End();
2477 DCHECK(store_mode == STANDARD_STORE);
2478 checked_key = Add<HBoundsCheck>(key, length);
2479 return AddElementAccess(
2480 backing_store, checked_key, val,
2481 checked_object, elements_kind, access_type);
2484 DCHECK(fast_smi_only_elements ||
2486 IsFastDoubleElementsKind(elements_kind));
2488 // In case val is stored into a fast smi array, assure that the value is a smi
2489 // before manipulating the backing store. Otherwise the actual store may
2490 // deopt, leaving the backing store in an invalid state.
2491 if (access_type == STORE && IsFastSmiElementsKind(elements_kind) &&
2492 !val->type().IsSmi()) {
2493 val = AddUncasted<HForceRepresentation>(val, Representation::Smi());
2496 if (IsGrowStoreMode(store_mode)) {
2497 NoObservableSideEffectsScope no_effects(this);
2498 Representation representation = HStoreKeyed::RequiredValueRepresentation(
2499 elements_kind, STORE_TO_INITIALIZED_ENTRY);
2500 val = AddUncasted<HForceRepresentation>(val, representation);
2501 elements = BuildCheckForCapacityGrow(checked_object, elements,
2502 elements_kind, length, key,
2503 is_js_array, access_type);
2506 checked_key = Add<HBoundsCheck>(key, length);
2508 if (access_type == STORE && (fast_elements || fast_smi_only_elements)) {
2509 if (store_mode == STORE_NO_TRANSITION_HANDLE_COW) {
2510 NoObservableSideEffectsScope no_effects(this);
2511 elements = BuildCopyElementsOnWrite(checked_object, elements,
2512 elements_kind, length);
2514 HCheckMaps* check_cow_map = Add<HCheckMaps>(
2515 elements, isolate()->factory()->fixed_array_map());
2516 check_cow_map->ClearDependsOnFlag(kElementsKind);
2520 return AddElementAccess(elements, checked_key, val, checked_object,
2521 elements_kind, access_type, load_mode);
2525 HValue* HGraphBuilder::BuildAllocateArrayFromLength(
2526 JSArrayBuilder* array_builder,
2527 HValue* length_argument) {
2528 if (length_argument->IsConstant() &&
2529 HConstant::cast(length_argument)->HasSmiValue()) {
2530 int array_length = HConstant::cast(length_argument)->Integer32Value();
2531 if (array_length == 0) {
2532 return array_builder->AllocateEmptyArray();
2534 return array_builder->AllocateArray(length_argument,
2540 HValue* constant_zero = graph()->GetConstant0();
2541 HConstant* max_alloc_length =
2542 Add<HConstant>(JSObject::kInitialMaxFastElementArray);
2543 HInstruction* checked_length = Add<HBoundsCheck>(length_argument,
2545 IfBuilder if_builder(this);
2546 if_builder.If<HCompareNumericAndBranch>(checked_length, constant_zero,
2549 const int initial_capacity = JSArray::kPreallocatedArrayElements;
2550 HConstant* initial_capacity_node = Add<HConstant>(initial_capacity);
2551 Push(initial_capacity_node); // capacity
2552 Push(constant_zero); // length
2554 if (!(top_info()->IsStub()) &&
2555 IsFastPackedElementsKind(array_builder->kind())) {
2556 // We'll come back later with better (holey) feedback.
2558 Deoptimizer::kHoleyArrayDespitePackedElements_kindFeedback);
2560 Push(checked_length); // capacity
2561 Push(checked_length); // length
2565 // Figure out total size
2566 HValue* length = Pop();
2567 HValue* capacity = Pop();
2568 return array_builder->AllocateArray(capacity, max_alloc_length, length);
2572 HValue* HGraphBuilder::BuildCalculateElementsSize(ElementsKind kind,
2574 int elements_size = IsFastDoubleElementsKind(kind)
2578 HConstant* elements_size_value = Add<HConstant>(elements_size);
2580 HMul::NewImul(isolate(), zone(), context(), capacity->ActualValue(),
2581 elements_size_value);
2582 AddInstruction(mul);
2583 mul->ClearFlag(HValue::kCanOverflow);
2585 STATIC_ASSERT(FixedDoubleArray::kHeaderSize == FixedArray::kHeaderSize);
2587 HConstant* header_size = Add<HConstant>(FixedArray::kHeaderSize);
2588 HValue* total_size = AddUncasted<HAdd>(mul, header_size);
2589 total_size->ClearFlag(HValue::kCanOverflow);
2594 HAllocate* HGraphBuilder::AllocateJSArrayObject(AllocationSiteMode mode) {
2595 int base_size = JSArray::kSize;
2596 if (mode == TRACK_ALLOCATION_SITE) {
2597 base_size += AllocationMemento::kSize;
2599 HConstant* size_in_bytes = Add<HConstant>(base_size);
2600 return Add<HAllocate>(
2601 size_in_bytes, HType::JSArray(), NOT_TENURED, JS_OBJECT_TYPE);
2605 HConstant* HGraphBuilder::EstablishElementsAllocationSize(
2608 int base_size = IsFastDoubleElementsKind(kind)
2609 ? FixedDoubleArray::SizeFor(capacity)
2610 : FixedArray::SizeFor(capacity);
2612 return Add<HConstant>(base_size);
2616 HAllocate* HGraphBuilder::BuildAllocateElements(ElementsKind kind,
2617 HValue* size_in_bytes) {
2618 InstanceType instance_type = IsFastDoubleElementsKind(kind)
2619 ? FIXED_DOUBLE_ARRAY_TYPE
2622 return Add<HAllocate>(size_in_bytes, HType::HeapObject(), NOT_TENURED,
2627 void HGraphBuilder::BuildInitializeElementsHeader(HValue* elements,
2630 Factory* factory = isolate()->factory();
2631 Handle<Map> map = IsFastDoubleElementsKind(kind)
2632 ? factory->fixed_double_array_map()
2633 : factory->fixed_array_map();
2635 Add<HStoreNamedField>(elements, HObjectAccess::ForMap(), Add<HConstant>(map));
2636 Add<HStoreNamedField>(elements, HObjectAccess::ForFixedArrayLength(),
2641 HValue* HGraphBuilder::BuildAllocateAndInitializeArray(ElementsKind kind,
2643 // The HForceRepresentation is to prevent possible deopt on int-smi
2644 // conversion after allocation but before the new object fields are set.
2645 capacity = AddUncasted<HForceRepresentation>(capacity, Representation::Smi());
2646 HValue* size_in_bytes = BuildCalculateElementsSize(kind, capacity);
2647 HValue* new_array = BuildAllocateElements(kind, size_in_bytes);
2648 BuildInitializeElementsHeader(new_array, kind, capacity);
2653 void HGraphBuilder::BuildJSArrayHeader(HValue* array,
2656 AllocationSiteMode mode,
2657 ElementsKind elements_kind,
2658 HValue* allocation_site_payload,
2659 HValue* length_field) {
2660 Add<HStoreNamedField>(array, HObjectAccess::ForMap(), array_map);
2662 HConstant* empty_fixed_array =
2663 Add<HConstant>(isolate()->factory()->empty_fixed_array());
2665 Add<HStoreNamedField>(
2666 array, HObjectAccess::ForPropertiesPointer(), empty_fixed_array);
2668 Add<HStoreNamedField>(
2669 array, HObjectAccess::ForElementsPointer(),
2670 elements != NULL ? elements : empty_fixed_array);
2672 Add<HStoreNamedField>(
2673 array, HObjectAccess::ForArrayLength(elements_kind), length_field);
2675 if (mode == TRACK_ALLOCATION_SITE) {
2676 BuildCreateAllocationMemento(
2677 array, Add<HConstant>(JSArray::kSize), allocation_site_payload);
2682 HInstruction* HGraphBuilder::AddElementAccess(
2684 HValue* checked_key,
2687 ElementsKind elements_kind,
2688 PropertyAccessType access_type,
2689 LoadKeyedHoleMode load_mode) {
2690 if (access_type == STORE) {
2691 DCHECK(val != NULL);
2692 if (elements_kind == UINT8_CLAMPED_ELEMENTS) {
2693 val = Add<HClampToUint8>(val);
2695 return Add<HStoreKeyed>(elements, checked_key, val, elements_kind,
2696 STORE_TO_INITIALIZED_ENTRY);
2699 DCHECK(access_type == LOAD);
2700 DCHECK(val == NULL);
2701 HLoadKeyed* load = Add<HLoadKeyed>(
2702 elements, checked_key, dependency, elements_kind, load_mode);
2703 if (elements_kind == UINT32_ELEMENTS) {
2704 graph()->RecordUint32Instruction(load);
2710 HLoadNamedField* HGraphBuilder::AddLoadMap(HValue* object,
2711 HValue* dependency) {
2712 return Add<HLoadNamedField>(object, dependency, HObjectAccess::ForMap());
2716 HLoadNamedField* HGraphBuilder::AddLoadElements(HValue* object,
2717 HValue* dependency) {
2718 return Add<HLoadNamedField>(
2719 object, dependency, HObjectAccess::ForElementsPointer());
2723 HLoadNamedField* HGraphBuilder::AddLoadFixedArrayLength(
2725 HValue* dependency) {
2726 return Add<HLoadNamedField>(
2727 array, dependency, HObjectAccess::ForFixedArrayLength());
2731 HLoadNamedField* HGraphBuilder::AddLoadArrayLength(HValue* array,
2733 HValue* dependency) {
2734 return Add<HLoadNamedField>(
2735 array, dependency, HObjectAccess::ForArrayLength(kind));
2739 HValue* HGraphBuilder::BuildNewElementsCapacity(HValue* old_capacity) {
2740 HValue* half_old_capacity = AddUncasted<HShr>(old_capacity,
2741 graph_->GetConstant1());
2743 HValue* new_capacity = AddUncasted<HAdd>(half_old_capacity, old_capacity);
2744 new_capacity->ClearFlag(HValue::kCanOverflow);
2746 HValue* min_growth = Add<HConstant>(16);
2748 new_capacity = AddUncasted<HAdd>(new_capacity, min_growth);
2749 new_capacity->ClearFlag(HValue::kCanOverflow);
2751 return new_capacity;
2755 HValue* HGraphBuilder::BuildGrowElementsCapacity(HValue* object,
2758 ElementsKind new_kind,
2760 HValue* new_capacity) {
2761 Add<HBoundsCheck>(new_capacity, Add<HConstant>(
2762 (Page::kMaxRegularHeapObjectSize - FixedArray::kHeaderSize) >>
2763 ElementsKindToShiftSize(new_kind)));
2765 HValue* new_elements =
2766 BuildAllocateAndInitializeArray(new_kind, new_capacity);
2768 BuildCopyElements(elements, kind, new_elements,
2769 new_kind, length, new_capacity);
2771 Add<HStoreNamedField>(object, HObjectAccess::ForElementsPointer(),
2774 return new_elements;
2778 void HGraphBuilder::BuildFillElementsWithValue(HValue* elements,
2779 ElementsKind elements_kind,
2784 to = AddLoadFixedArrayLength(elements);
2787 // Special loop unfolding case
2788 STATIC_ASSERT(JSArray::kPreallocatedArrayElements <=
2789 kElementLoopUnrollThreshold);
2790 int initial_capacity = -1;
2791 if (from->IsInteger32Constant() && to->IsInteger32Constant()) {
2792 int constant_from = from->GetInteger32Constant();
2793 int constant_to = to->GetInteger32Constant();
2795 if (constant_from == 0 && constant_to <= kElementLoopUnrollThreshold) {
2796 initial_capacity = constant_to;
2800 if (initial_capacity >= 0) {
2801 for (int i = 0; i < initial_capacity; i++) {
2802 HInstruction* key = Add<HConstant>(i);
2803 Add<HStoreKeyed>(elements, key, value, elements_kind);
2806 // Carefully loop backwards so that the "from" remains live through the loop
2807 // rather than the to. This often corresponds to keeping length live rather
2808 // then capacity, which helps register allocation, since length is used more
2809 // other than capacity after filling with holes.
2810 LoopBuilder builder(this, context(), LoopBuilder::kPostDecrement);
2812 HValue* key = builder.BeginBody(to, from, Token::GT);
2814 HValue* adjusted_key = AddUncasted<HSub>(key, graph()->GetConstant1());
2815 adjusted_key->ClearFlag(HValue::kCanOverflow);
2817 Add<HStoreKeyed>(elements, adjusted_key, value, elements_kind);
2824 void HGraphBuilder::BuildFillElementsWithHole(HValue* elements,
2825 ElementsKind elements_kind,
2828 // Fast elements kinds need to be initialized in case statements below cause a
2829 // garbage collection.
2831 HValue* hole = IsFastSmiOrObjectElementsKind(elements_kind)
2832 ? graph()->GetConstantHole()
2833 : Add<HConstant>(HConstant::kHoleNaN);
2835 // Since we're about to store a hole value, the store instruction below must
2836 // assume an elements kind that supports heap object values.
2837 if (IsFastSmiOrObjectElementsKind(elements_kind)) {
2838 elements_kind = FAST_HOLEY_ELEMENTS;
2841 BuildFillElementsWithValue(elements, elements_kind, from, to, hole);
2845 void HGraphBuilder::BuildCopyProperties(HValue* from_properties,
2846 HValue* to_properties, HValue* length,
2848 ElementsKind kind = FAST_ELEMENTS;
2850 BuildFillElementsWithValue(to_properties, kind, length, capacity,
2851 graph()->GetConstantUndefined());
2853 LoopBuilder builder(this, context(), LoopBuilder::kPostDecrement);
2855 HValue* key = builder.BeginBody(length, graph()->GetConstant0(), Token::GT);
2857 key = AddUncasted<HSub>(key, graph()->GetConstant1());
2858 key->ClearFlag(HValue::kCanOverflow);
2860 HValue* element = Add<HLoadKeyed>(from_properties, key, nullptr, kind);
2862 Add<HStoreKeyed>(to_properties, key, element, kind);
2868 void HGraphBuilder::BuildCopyElements(HValue* from_elements,
2869 ElementsKind from_elements_kind,
2870 HValue* to_elements,
2871 ElementsKind to_elements_kind,
2874 int constant_capacity = -1;
2875 if (capacity != NULL &&
2876 capacity->IsConstant() &&
2877 HConstant::cast(capacity)->HasInteger32Value()) {
2878 int constant_candidate = HConstant::cast(capacity)->Integer32Value();
2879 if (constant_candidate <= kElementLoopUnrollThreshold) {
2880 constant_capacity = constant_candidate;
2884 bool pre_fill_with_holes =
2885 IsFastDoubleElementsKind(from_elements_kind) &&
2886 IsFastObjectElementsKind(to_elements_kind);
2887 if (pre_fill_with_holes) {
2888 // If the copy might trigger a GC, make sure that the FixedArray is
2889 // pre-initialized with holes to make sure that it's always in a
2890 // consistent state.
2891 BuildFillElementsWithHole(to_elements, to_elements_kind,
2892 graph()->GetConstant0(), NULL);
2895 if (constant_capacity != -1) {
2896 // Unroll the loop for small elements kinds.
2897 for (int i = 0; i < constant_capacity; i++) {
2898 HValue* key_constant = Add<HConstant>(i);
2899 HInstruction* value = Add<HLoadKeyed>(from_elements, key_constant,
2900 nullptr, from_elements_kind);
2901 Add<HStoreKeyed>(to_elements, key_constant, value, to_elements_kind);
2904 if (!pre_fill_with_holes &&
2905 (capacity == NULL || !length->Equals(capacity))) {
2906 BuildFillElementsWithHole(to_elements, to_elements_kind,
2910 LoopBuilder builder(this, context(), LoopBuilder::kPostDecrement);
2912 HValue* key = builder.BeginBody(length, graph()->GetConstant0(),
2915 key = AddUncasted<HSub>(key, graph()->GetConstant1());
2916 key->ClearFlag(HValue::kCanOverflow);
2918 HValue* element = Add<HLoadKeyed>(from_elements, key, nullptr,
2919 from_elements_kind, ALLOW_RETURN_HOLE);
2921 ElementsKind kind = (IsHoleyElementsKind(from_elements_kind) &&
2922 IsFastSmiElementsKind(to_elements_kind))
2923 ? FAST_HOLEY_ELEMENTS : to_elements_kind;
2925 if (IsHoleyElementsKind(from_elements_kind) &&
2926 from_elements_kind != to_elements_kind) {
2927 IfBuilder if_hole(this);
2928 if_hole.If<HCompareHoleAndBranch>(element);
2930 HConstant* hole_constant = IsFastDoubleElementsKind(to_elements_kind)
2931 ? Add<HConstant>(HConstant::kHoleNaN)
2932 : graph()->GetConstantHole();
2933 Add<HStoreKeyed>(to_elements, key, hole_constant, kind);
2935 HStoreKeyed* store = Add<HStoreKeyed>(to_elements, key, element, kind);
2936 store->SetFlag(HValue::kAllowUndefinedAsNaN);
2939 HStoreKeyed* store = Add<HStoreKeyed>(to_elements, key, element, kind);
2940 store->SetFlag(HValue::kAllowUndefinedAsNaN);
2946 Counters* counters = isolate()->counters();
2947 AddIncrementCounter(counters->inlined_copied_elements());
2951 HValue* HGraphBuilder::BuildCloneShallowArrayCow(HValue* boilerplate,
2952 HValue* allocation_site,
2953 AllocationSiteMode mode,
2954 ElementsKind kind) {
2955 HAllocate* array = AllocateJSArrayObject(mode);
2957 HValue* map = AddLoadMap(boilerplate);
2958 HValue* elements = AddLoadElements(boilerplate);
2959 HValue* length = AddLoadArrayLength(boilerplate, kind);
2961 BuildJSArrayHeader(array,
2972 HValue* HGraphBuilder::BuildCloneShallowArrayEmpty(HValue* boilerplate,
2973 HValue* allocation_site,
2974 AllocationSiteMode mode) {
2975 HAllocate* array = AllocateJSArrayObject(mode);
2977 HValue* map = AddLoadMap(boilerplate);
2979 BuildJSArrayHeader(array,
2981 NULL, // set elements to empty fixed array
2985 graph()->GetConstant0());
2990 HValue* HGraphBuilder::BuildCloneShallowArrayNonEmpty(HValue* boilerplate,
2991 HValue* allocation_site,
2992 AllocationSiteMode mode,
2993 ElementsKind kind) {
2994 HValue* boilerplate_elements = AddLoadElements(boilerplate);
2995 HValue* capacity = AddLoadFixedArrayLength(boilerplate_elements);
2997 // Generate size calculation code here in order to make it dominate
2998 // the JSArray allocation.
2999 HValue* elements_size = BuildCalculateElementsSize(kind, capacity);
3001 // Create empty JSArray object for now, store elimination should remove
3002 // redundant initialization of elements and length fields and at the same
3003 // time the object will be fully prepared for GC if it happens during
3004 // elements allocation.
3005 HValue* result = BuildCloneShallowArrayEmpty(
3006 boilerplate, allocation_site, mode);
3008 HAllocate* elements = BuildAllocateElements(kind, elements_size);
3010 // This function implicitly relies on the fact that the
3011 // FastCloneShallowArrayStub is called only for literals shorter than
3012 // JSObject::kInitialMaxFastElementArray.
3013 // Can't add HBoundsCheck here because otherwise the stub will eager a frame.
3014 HConstant* size_upper_bound = EstablishElementsAllocationSize(
3015 kind, JSObject::kInitialMaxFastElementArray);
3016 elements->set_size_upper_bound(size_upper_bound);
3018 Add<HStoreNamedField>(result, HObjectAccess::ForElementsPointer(), elements);
3020 // The allocation for the cloned array above causes register pressure on
3021 // machines with low register counts. Force a reload of the boilerplate
3022 // elements here to free up a register for the allocation to avoid unnecessary
3024 boilerplate_elements = AddLoadElements(boilerplate);
3025 boilerplate_elements->SetFlag(HValue::kCantBeReplaced);
3027 // Copy the elements array header.
3028 for (int i = 0; i < FixedArrayBase::kHeaderSize; i += kPointerSize) {
3029 HObjectAccess access = HObjectAccess::ForFixedArrayHeader(i);
3030 Add<HStoreNamedField>(
3032 Add<HLoadNamedField>(boilerplate_elements, nullptr, access));
3035 // And the result of the length
3036 HValue* length = AddLoadArrayLength(boilerplate, kind);
3037 Add<HStoreNamedField>(result, HObjectAccess::ForArrayLength(kind), length);
3039 BuildCopyElements(boilerplate_elements, kind, elements,
3040 kind, length, NULL);
3045 void HGraphBuilder::BuildCompareNil(HValue* value, Type* type,
3046 HIfContinuation* continuation,
3047 MapEmbedding map_embedding) {
3048 IfBuilder if_nil(this);
3049 bool some_case_handled = false;
3050 bool some_case_missing = false;
3052 if (type->Maybe(Type::Null())) {
3053 if (some_case_handled) if_nil.Or();
3054 if_nil.If<HCompareObjectEqAndBranch>(value, graph()->GetConstantNull());
3055 some_case_handled = true;
3057 some_case_missing = true;
3060 if (type->Maybe(Type::Undefined())) {
3061 if (some_case_handled) if_nil.Or();
3062 if_nil.If<HCompareObjectEqAndBranch>(value,
3063 graph()->GetConstantUndefined());
3064 some_case_handled = true;
3066 some_case_missing = true;
3069 if (type->Maybe(Type::Undetectable())) {
3070 if (some_case_handled) if_nil.Or();
3071 if_nil.If<HIsUndetectableAndBranch>(value);
3072 some_case_handled = true;
3074 some_case_missing = true;
3077 if (some_case_missing) {
3080 if (type->NumClasses() == 1) {
3081 BuildCheckHeapObject(value);
3082 // For ICs, the map checked below is a sentinel map that gets replaced by
3083 // the monomorphic map when the code is used as a template to generate a
3084 // new IC. For optimized functions, there is no sentinel map, the map
3085 // emitted below is the actual monomorphic map.
3086 if (map_embedding == kEmbedMapsViaWeakCells) {
3088 Add<HConstant>(Map::WeakCellForMap(type->Classes().Current()));
3089 HValue* expected_map = Add<HLoadNamedField>(
3090 cell, nullptr, HObjectAccess::ForWeakCellValue());
3092 Add<HLoadNamedField>(value, nullptr, HObjectAccess::ForMap());
3093 IfBuilder map_check(this);
3094 map_check.IfNot<HCompareObjectEqAndBranch>(expected_map, map);
3095 map_check.ThenDeopt(Deoptimizer::kUnknownMap);
3098 DCHECK(map_embedding == kEmbedMapsDirectly);
3099 Add<HCheckMaps>(value, type->Classes().Current());
3102 if_nil.Deopt(Deoptimizer::kTooManyUndetectableTypes);
3106 if_nil.CaptureContinuation(continuation);
3110 void HGraphBuilder::BuildCreateAllocationMemento(
3111 HValue* previous_object,
3112 HValue* previous_object_size,
3113 HValue* allocation_site) {
3114 DCHECK(allocation_site != NULL);
3115 HInnerAllocatedObject* allocation_memento = Add<HInnerAllocatedObject>(
3116 previous_object, previous_object_size, HType::HeapObject());
3117 AddStoreMapConstant(
3118 allocation_memento, isolate()->factory()->allocation_memento_map());
3119 Add<HStoreNamedField>(
3121 HObjectAccess::ForAllocationMementoSite(),
3123 if (FLAG_allocation_site_pretenuring) {
3124 HValue* memento_create_count =
3125 Add<HLoadNamedField>(allocation_site, nullptr,
3126 HObjectAccess::ForAllocationSiteOffset(
3127 AllocationSite::kPretenureCreateCountOffset));
3128 memento_create_count = AddUncasted<HAdd>(
3129 memento_create_count, graph()->GetConstant1());
3130 // This smi value is reset to zero after every gc, overflow isn't a problem
3131 // since the counter is bounded by the new space size.
3132 memento_create_count->ClearFlag(HValue::kCanOverflow);
3133 Add<HStoreNamedField>(
3134 allocation_site, HObjectAccess::ForAllocationSiteOffset(
3135 AllocationSite::kPretenureCreateCountOffset), memento_create_count);
3140 HInstruction* HGraphBuilder::BuildGetNativeContext() {
3141 // Get the global object, then the native context
3142 HValue* global_object = Add<HLoadNamedField>(
3144 HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
3145 return Add<HLoadNamedField>(global_object, nullptr,
3146 HObjectAccess::ForObservableJSObjectOffset(
3147 GlobalObject::kNativeContextOffset));
3151 HInstruction* HGraphBuilder::BuildGetNativeContext(HValue* closure) {
3152 // Get the global object, then the native context
3153 HInstruction* context = Add<HLoadNamedField>(
3154 closure, nullptr, HObjectAccess::ForFunctionContextPointer());
3155 HInstruction* global_object = Add<HLoadNamedField>(
3157 HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
3158 HObjectAccess access = HObjectAccess::ForObservableJSObjectOffset(
3159 GlobalObject::kNativeContextOffset);
3160 return Add<HLoadNamedField>(global_object, nullptr, access);
3164 HInstruction* HGraphBuilder::BuildGetScriptContext(int context_index) {
3165 HValue* native_context = BuildGetNativeContext();
3166 HValue* script_context_table = Add<HLoadNamedField>(
3167 native_context, nullptr,
3168 HObjectAccess::ForContextSlot(Context::SCRIPT_CONTEXT_TABLE_INDEX));
3169 return Add<HLoadNamedField>(script_context_table, nullptr,
3170 HObjectAccess::ForScriptContext(context_index));
3174 HValue* HGraphBuilder::BuildGetParentContext(HValue* depth, int depth_value) {
3175 HValue* script_context = context();
3176 if (depth != NULL) {
3177 HValue* zero = graph()->GetConstant0();
3179 Push(script_context);
3182 LoopBuilder loop(this);
3183 loop.BeginBody(2); // Drop script_context and depth from last environment
3184 // to appease live range building without simulates.
3186 script_context = Pop();
3188 script_context = Add<HLoadNamedField>(
3189 script_context, nullptr,
3190 HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX));
3191 depth = AddUncasted<HSub>(depth, graph()->GetConstant1());
3192 depth->ClearFlag(HValue::kCanOverflow);
3194 IfBuilder if_break(this);
3195 if_break.If<HCompareNumericAndBranch, HValue*>(depth, zero, Token::EQ);
3198 Push(script_context); // The result.
3203 Push(script_context);
3209 script_context = Pop();
3210 } else if (depth_value > 0) {
3211 // Unroll the above loop.
3212 for (int i = 0; i < depth_value; i++) {
3213 script_context = Add<HLoadNamedField>(
3214 script_context, nullptr,
3215 HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX));
3218 return script_context;
3222 HInstruction* HGraphBuilder::BuildGetArrayFunction() {
3223 HInstruction* native_context = BuildGetNativeContext();
3224 HInstruction* index =
3225 Add<HConstant>(static_cast<int32_t>(Context::ARRAY_FUNCTION_INDEX));
3226 return Add<HLoadKeyed>(native_context, index, nullptr, FAST_ELEMENTS);
3230 HValue* HGraphBuilder::BuildArrayBufferViewFieldAccessor(HValue* object,
3231 HValue* checked_object,
3233 NoObservableSideEffectsScope scope(this);
3234 HObjectAccess access = HObjectAccess::ForObservableJSObjectOffset(
3235 index.offset(), Representation::Tagged());
3236 HInstruction* buffer = Add<HLoadNamedField>(
3237 object, checked_object, HObjectAccess::ForJSArrayBufferViewBuffer());
3238 HInstruction* field = Add<HLoadNamedField>(object, checked_object, access);
3240 HInstruction* flags = Add<HLoadNamedField>(
3241 buffer, nullptr, HObjectAccess::ForJSArrayBufferBitField());
3242 HValue* was_neutered_mask =
3243 Add<HConstant>(1 << JSArrayBuffer::WasNeutered::kShift);
3244 HValue* was_neutered_test =
3245 AddUncasted<HBitwise>(Token::BIT_AND, flags, was_neutered_mask);
3247 IfBuilder if_was_neutered(this);
3248 if_was_neutered.If<HCompareNumericAndBranch>(
3249 was_neutered_test, graph()->GetConstant0(), Token::NE);
3250 if_was_neutered.Then();
3251 Push(graph()->GetConstant0());
3252 if_was_neutered.Else();
3254 if_was_neutered.End();
3260 HGraphBuilder::JSArrayBuilder::JSArrayBuilder(HGraphBuilder* builder,
3262 HValue* allocation_site_payload,
3263 HValue* constructor_function,
3264 AllocationSiteOverrideMode override_mode) :
3267 allocation_site_payload_(allocation_site_payload),
3268 constructor_function_(constructor_function) {
3269 DCHECK(!allocation_site_payload->IsConstant() ||
3270 HConstant::cast(allocation_site_payload)->handle(
3271 builder_->isolate())->IsAllocationSite());
3272 mode_ = override_mode == DISABLE_ALLOCATION_SITES
3273 ? DONT_TRACK_ALLOCATION_SITE
3274 : AllocationSite::GetMode(kind);
3278 HGraphBuilder::JSArrayBuilder::JSArrayBuilder(HGraphBuilder* builder,
3280 HValue* constructor_function) :
3283 mode_(DONT_TRACK_ALLOCATION_SITE),
3284 allocation_site_payload_(NULL),
3285 constructor_function_(constructor_function) {
3289 HValue* HGraphBuilder::JSArrayBuilder::EmitMapCode() {
3290 if (!builder()->top_info()->IsStub()) {
3291 // A constant map is fine.
3292 Handle<Map> map(builder()->isolate()->get_initial_js_array_map(kind_),
3293 builder()->isolate());
3294 return builder()->Add<HConstant>(map);
3297 if (constructor_function_ != NULL && kind_ == GetInitialFastElementsKind()) {
3298 // No need for a context lookup if the kind_ matches the initial
3299 // map, because we can just load the map in that case.
3300 HObjectAccess access = HObjectAccess::ForPrototypeOrInitialMap();
3301 return builder()->Add<HLoadNamedField>(constructor_function_, nullptr,
3305 // TODO(mvstanton): we should always have a constructor function if we
3306 // are creating a stub.
3307 HInstruction* native_context = constructor_function_ != NULL
3308 ? builder()->BuildGetNativeContext(constructor_function_)
3309 : builder()->BuildGetNativeContext();
3311 HInstruction* index = builder()->Add<HConstant>(
3312 static_cast<int32_t>(Context::JS_ARRAY_MAPS_INDEX));
3314 HInstruction* map_array =
3315 builder()->Add<HLoadKeyed>(native_context, index, nullptr, FAST_ELEMENTS);
3317 HInstruction* kind_index = builder()->Add<HConstant>(kind_);
3319 return builder()->Add<HLoadKeyed>(map_array, kind_index, nullptr,
3324 HValue* HGraphBuilder::JSArrayBuilder::EmitInternalMapCode() {
3325 // Find the map near the constructor function
3326 HObjectAccess access = HObjectAccess::ForPrototypeOrInitialMap();
3327 return builder()->Add<HLoadNamedField>(constructor_function_, nullptr,
3332 HAllocate* HGraphBuilder::JSArrayBuilder::AllocateEmptyArray() {
3333 HConstant* capacity = builder()->Add<HConstant>(initial_capacity());
3334 return AllocateArray(capacity,
3336 builder()->graph()->GetConstant0());
3340 HAllocate* HGraphBuilder::JSArrayBuilder::AllocateArray(
3342 HConstant* capacity_upper_bound,
3343 HValue* length_field,
3344 FillMode fill_mode) {
3345 return AllocateArray(capacity,
3346 capacity_upper_bound->GetInteger32Constant(),
3352 HAllocate* HGraphBuilder::JSArrayBuilder::AllocateArray(
3354 int capacity_upper_bound,
3355 HValue* length_field,
3356 FillMode fill_mode) {
3357 HConstant* elememts_size_upper_bound = capacity->IsInteger32Constant()
3358 ? HConstant::cast(capacity)
3359 : builder()->EstablishElementsAllocationSize(kind_, capacity_upper_bound);
3361 HAllocate* array = AllocateArray(capacity, length_field, fill_mode);
3362 if (!elements_location_->has_size_upper_bound()) {
3363 elements_location_->set_size_upper_bound(elememts_size_upper_bound);
3369 HAllocate* HGraphBuilder::JSArrayBuilder::AllocateArray(
3371 HValue* length_field,
3372 FillMode fill_mode) {
3373 // These HForceRepresentations are because we store these as fields in the
3374 // objects we construct, and an int32-to-smi HChange could deopt. Accept
3375 // the deopt possibility now, before allocation occurs.
3377 builder()->AddUncasted<HForceRepresentation>(capacity,
3378 Representation::Smi());
3380 builder()->AddUncasted<HForceRepresentation>(length_field,
3381 Representation::Smi());
3383 // Generate size calculation code here in order to make it dominate
3384 // the JSArray allocation.
3385 HValue* elements_size =
3386 builder()->BuildCalculateElementsSize(kind_, capacity);
3388 // Allocate (dealing with failure appropriately)
3389 HAllocate* array_object = builder()->AllocateJSArrayObject(mode_);
3391 // Fill in the fields: map, properties, length
3393 if (allocation_site_payload_ == NULL) {
3394 map = EmitInternalMapCode();
3396 map = EmitMapCode();
3399 builder()->BuildJSArrayHeader(array_object,
3401 NULL, // set elements to empty fixed array
3404 allocation_site_payload_,
3407 // Allocate and initialize the elements
3408 elements_location_ = builder()->BuildAllocateElements(kind_, elements_size);
3410 builder()->BuildInitializeElementsHeader(elements_location_, kind_, capacity);
3413 builder()->Add<HStoreNamedField>(
3414 array_object, HObjectAccess::ForElementsPointer(), elements_location_);
3416 if (fill_mode == FILL_WITH_HOLE) {
3417 builder()->BuildFillElementsWithHole(elements_location_, kind_,
3418 graph()->GetConstant0(), capacity);
3421 return array_object;
3425 HValue* HGraphBuilder::AddLoadJSBuiltin(Builtins::JavaScript builtin) {
3426 HValue* global_object = Add<HLoadNamedField>(
3428 HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
3429 HObjectAccess access = HObjectAccess::ForObservableJSObjectOffset(
3430 GlobalObject::kBuiltinsOffset);
3431 HValue* builtins = Add<HLoadNamedField>(global_object, nullptr, access);
3432 HObjectAccess function_access = HObjectAccess::ForObservableJSObjectOffset(
3433 JSBuiltinsObject::OffsetOfFunctionWithId(builtin));
3434 return Add<HLoadNamedField>(builtins, nullptr, function_access);
3438 HOptimizedGraphBuilder::HOptimizedGraphBuilder(CompilationInfo* info)
3439 : HGraphBuilder(info),
3440 function_state_(NULL),
3441 initial_function_state_(this, info, NORMAL_RETURN, 0),
3445 globals_(10, info->zone()),
3446 osr_(new(info->zone()) HOsrBuilder(this)) {
3447 // This is not initialized in the initializer list because the
3448 // constructor for the initial state relies on function_state_ == NULL
3449 // to know it's the initial state.
3450 function_state_ = &initial_function_state_;
3451 InitializeAstVisitor(info->isolate(), info->zone());
3452 if (top_info()->is_tracking_positions()) {
3453 SetSourcePosition(info->shared_info()->start_position());
3458 HBasicBlock* HOptimizedGraphBuilder::CreateJoin(HBasicBlock* first,
3459 HBasicBlock* second,
3460 BailoutId join_id) {
3461 if (first == NULL) {
3463 } else if (second == NULL) {
3466 HBasicBlock* join_block = graph()->CreateBasicBlock();
3467 Goto(first, join_block);
3468 Goto(second, join_block);
3469 join_block->SetJoinId(join_id);
3475 HBasicBlock* HOptimizedGraphBuilder::JoinContinue(IterationStatement* statement,
3476 HBasicBlock* exit_block,
3477 HBasicBlock* continue_block) {
3478 if (continue_block != NULL) {
3479 if (exit_block != NULL) Goto(exit_block, continue_block);
3480 continue_block->SetJoinId(statement->ContinueId());
3481 return continue_block;
3487 HBasicBlock* HOptimizedGraphBuilder::CreateLoop(IterationStatement* statement,
3488 HBasicBlock* loop_entry,
3489 HBasicBlock* body_exit,
3490 HBasicBlock* loop_successor,
3491 HBasicBlock* break_block) {
3492 if (body_exit != NULL) Goto(body_exit, loop_entry);
3493 loop_entry->PostProcessLoopHeader(statement);
3494 if (break_block != NULL) {
3495 if (loop_successor != NULL) Goto(loop_successor, break_block);
3496 break_block->SetJoinId(statement->ExitId());
3499 return loop_successor;
3503 // Build a new loop header block and set it as the current block.
3504 HBasicBlock* HOptimizedGraphBuilder::BuildLoopEntry() {
3505 HBasicBlock* loop_entry = CreateLoopHeaderBlock();
3507 set_current_block(loop_entry);
3512 HBasicBlock* HOptimizedGraphBuilder::BuildLoopEntry(
3513 IterationStatement* statement) {
3514 HBasicBlock* loop_entry = osr()->HasOsrEntryAt(statement)
3515 ? osr()->BuildOsrLoopEntry(statement)
3521 void HBasicBlock::FinishExit(HControlInstruction* instruction,
3522 SourcePosition position) {
3523 Finish(instruction, position);
3528 std::ostream& operator<<(std::ostream& os, const HBasicBlock& b) {
3529 return os << "B" << b.block_id();
3533 HGraph::HGraph(CompilationInfo* info)
3534 : isolate_(info->isolate()),
3537 blocks_(8, info->zone()),
3538 values_(16, info->zone()),
3540 uint32_instructions_(NULL),
3543 zone_(info->zone()),
3544 is_recursive_(false),
3545 use_optimistic_licm_(false),
3546 depends_on_empty_array_proto_elements_(false),
3547 type_change_checksum_(0),
3548 maximum_environment_size_(0),
3549 no_side_effects_scope_count_(0),
3550 disallow_adding_new_values_(false) {
3551 if (info->IsStub()) {
3552 CallInterfaceDescriptor descriptor =
3553 info->code_stub()->GetCallInterfaceDescriptor();
3554 start_environment_ =
3555 new (zone_) HEnvironment(zone_, descriptor.GetRegisterParameterCount());
3557 if (info->is_tracking_positions()) {
3558 info->TraceInlinedFunction(info->shared_info(), SourcePosition::Unknown(),
3559 InlinedFunctionInfo::kNoParentId);
3561 start_environment_ =
3562 new(zone_) HEnvironment(NULL, info->scope(), info->closure(), zone_);
3564 start_environment_->set_ast_id(BailoutId::FunctionEntry());
3565 entry_block_ = CreateBasicBlock();
3566 entry_block_->SetInitialEnvironment(start_environment_);
3570 HBasicBlock* HGraph::CreateBasicBlock() {
3571 HBasicBlock* result = new(zone()) HBasicBlock(this);
3572 blocks_.Add(result, zone());
3577 void HGraph::FinalizeUniqueness() {
3578 DisallowHeapAllocation no_gc;
3579 for (int i = 0; i < blocks()->length(); ++i) {
3580 for (HInstructionIterator it(blocks()->at(i)); !it.Done(); it.Advance()) {
3581 it.Current()->FinalizeUniqueness();
3587 int HGraph::SourcePositionToScriptPosition(SourcePosition pos) {
3588 return (FLAG_hydrogen_track_positions && !pos.IsUnknown())
3589 ? info()->start_position_for(pos.inlining_id()) + pos.position()
3594 // Block ordering was implemented with two mutually recursive methods,
3595 // HGraph::Postorder and HGraph::PostorderLoopBlocks.
3596 // The recursion could lead to stack overflow so the algorithm has been
3597 // implemented iteratively.
3598 // At a high level the algorithm looks like this:
3600 // Postorder(block, loop_header) : {
3601 // if (block has already been visited or is of another loop) return;
3602 // mark block as visited;
3603 // if (block is a loop header) {
3604 // VisitLoopMembers(block, loop_header);
3605 // VisitSuccessorsOfLoopHeader(block);
3607 // VisitSuccessors(block)
3609 // put block in result list;
3612 // VisitLoopMembers(block, outer_loop_header) {
3613 // foreach (block b in block loop members) {
3614 // VisitSuccessorsOfLoopMember(b, outer_loop_header);
3615 // if (b is loop header) VisitLoopMembers(b);
3619 // VisitSuccessorsOfLoopMember(block, outer_loop_header) {
3620 // foreach (block b in block successors) Postorder(b, outer_loop_header)
3623 // VisitSuccessorsOfLoopHeader(block) {
3624 // foreach (block b in block successors) Postorder(b, block)
3627 // VisitSuccessors(block, loop_header) {
3628 // foreach (block b in block successors) Postorder(b, loop_header)
3631 // The ordering is started calling Postorder(entry, NULL).
3633 // Each instance of PostorderProcessor represents the "stack frame" of the
3634 // recursion, and particularly keeps the state of the loop (iteration) of the
3635 // "Visit..." function it represents.
3636 // To recycle memory we keep all the frames in a double linked list but
3637 // this means that we cannot use constructors to initialize the frames.
3639 class PostorderProcessor : public ZoneObject {
3641 // Back link (towards the stack bottom).
3642 PostorderProcessor* parent() {return father_; }
3643 // Forward link (towards the stack top).
3644 PostorderProcessor* child() {return child_; }
3645 HBasicBlock* block() { return block_; }
3646 HLoopInformation* loop() { return loop_; }
3647 HBasicBlock* loop_header() { return loop_header_; }
3649 static PostorderProcessor* CreateEntryProcessor(Zone* zone,
3650 HBasicBlock* block) {
3651 PostorderProcessor* result = new(zone) PostorderProcessor(NULL);
3652 return result->SetupSuccessors(zone, block, NULL);
3655 PostorderProcessor* PerformStep(Zone* zone,
3656 ZoneList<HBasicBlock*>* order) {
3657 PostorderProcessor* next =
3658 PerformNonBacktrackingStep(zone, order);
3662 return Backtrack(zone, order);
3667 explicit PostorderProcessor(PostorderProcessor* father)
3668 : father_(father), child_(NULL), successor_iterator(NULL) { }
3670 // Each enum value states the cycle whose state is kept by this instance.
3674 SUCCESSORS_OF_LOOP_HEADER,
3676 SUCCESSORS_OF_LOOP_MEMBER
3679 // Each "Setup..." method is like a constructor for a cycle state.
3680 PostorderProcessor* SetupSuccessors(Zone* zone,
3682 HBasicBlock* loop_header) {
3683 if (block == NULL || block->IsOrdered() ||
3684 block->parent_loop_header() != loop_header) {
3688 loop_header_ = NULL;
3693 block->MarkAsOrdered();
3695 if (block->IsLoopHeader()) {
3696 kind_ = SUCCESSORS_OF_LOOP_HEADER;
3697 loop_header_ = block;
3698 InitializeSuccessors();
3699 PostorderProcessor* result = Push(zone);
3700 return result->SetupLoopMembers(zone, block, block->loop_information(),
3703 DCHECK(block->IsFinished());
3705 loop_header_ = loop_header;
3706 InitializeSuccessors();
3712 PostorderProcessor* SetupLoopMembers(Zone* zone,
3714 HLoopInformation* loop,
3715 HBasicBlock* loop_header) {
3716 kind_ = LOOP_MEMBERS;
3719 loop_header_ = loop_header;
3720 InitializeLoopMembers();
3724 PostorderProcessor* SetupSuccessorsOfLoopMember(
3726 HLoopInformation* loop,
3727 HBasicBlock* loop_header) {
3728 kind_ = SUCCESSORS_OF_LOOP_MEMBER;
3731 loop_header_ = loop_header;
3732 InitializeSuccessors();
3736 // This method "allocates" a new stack frame.
3737 PostorderProcessor* Push(Zone* zone) {
3738 if (child_ == NULL) {
3739 child_ = new(zone) PostorderProcessor(this);
3744 void ClosePostorder(ZoneList<HBasicBlock*>* order, Zone* zone) {
3745 DCHECK(block_->end()->FirstSuccessor() == NULL ||
3746 order->Contains(block_->end()->FirstSuccessor()) ||
3747 block_->end()->FirstSuccessor()->IsLoopHeader());
3748 DCHECK(block_->end()->SecondSuccessor() == NULL ||
3749 order->Contains(block_->end()->SecondSuccessor()) ||
3750 block_->end()->SecondSuccessor()->IsLoopHeader());
3751 order->Add(block_, zone);
3754 // This method is the basic block to walk up the stack.
3755 PostorderProcessor* Pop(Zone* zone,
3756 ZoneList<HBasicBlock*>* order) {
3759 case SUCCESSORS_OF_LOOP_HEADER:
3760 ClosePostorder(order, zone);
3764 case SUCCESSORS_OF_LOOP_MEMBER:
3765 if (block()->IsLoopHeader() && block() != loop_->loop_header()) {
3766 // In this case we need to perform a LOOP_MEMBERS cycle so we
3767 // initialize it and return this instead of father.
3768 return SetupLoopMembers(zone, block(),
3769 block()->loop_information(), loop_header_);
3780 // Walks up the stack.
3781 PostorderProcessor* Backtrack(Zone* zone,
3782 ZoneList<HBasicBlock*>* order) {
3783 PostorderProcessor* parent = Pop(zone, order);
3784 while (parent != NULL) {
3785 PostorderProcessor* next =
3786 parent->PerformNonBacktrackingStep(zone, order);
3790 parent = parent->Pop(zone, order);
3796 PostorderProcessor* PerformNonBacktrackingStep(
3798 ZoneList<HBasicBlock*>* order) {
3799 HBasicBlock* next_block;
3802 next_block = AdvanceSuccessors();
3803 if (next_block != NULL) {
3804 PostorderProcessor* result = Push(zone);
3805 return result->SetupSuccessors(zone, next_block, loop_header_);
3808 case SUCCESSORS_OF_LOOP_HEADER:
3809 next_block = AdvanceSuccessors();
3810 if (next_block != NULL) {
3811 PostorderProcessor* result = Push(zone);
3812 return result->SetupSuccessors(zone, next_block, block());
3816 next_block = AdvanceLoopMembers();
3817 if (next_block != NULL) {
3818 PostorderProcessor* result = Push(zone);
3819 return result->SetupSuccessorsOfLoopMember(next_block,
3820 loop_, loop_header_);
3823 case SUCCESSORS_OF_LOOP_MEMBER:
3824 next_block = AdvanceSuccessors();
3825 if (next_block != NULL) {
3826 PostorderProcessor* result = Push(zone);
3827 return result->SetupSuccessors(zone, next_block, loop_header_);
3836 // The following two methods implement a "foreach b in successors" cycle.
3837 void InitializeSuccessors() {
3840 successor_iterator = HSuccessorIterator(block_->end());
3843 HBasicBlock* AdvanceSuccessors() {
3844 if (!successor_iterator.Done()) {
3845 HBasicBlock* result = successor_iterator.Current();
3846 successor_iterator.Advance();
3852 // The following two methods implement a "foreach b in loop members" cycle.
3853 void InitializeLoopMembers() {
3855 loop_length = loop_->blocks()->length();
3858 HBasicBlock* AdvanceLoopMembers() {
3859 if (loop_index < loop_length) {
3860 HBasicBlock* result = loop_->blocks()->at(loop_index);
3869 PostorderProcessor* father_;
3870 PostorderProcessor* child_;
3871 HLoopInformation* loop_;
3872 HBasicBlock* block_;
3873 HBasicBlock* loop_header_;
3876 HSuccessorIterator successor_iterator;
3880 void HGraph::OrderBlocks() {
3881 CompilationPhase phase("H_Block ordering", info());
3884 // Initially the blocks must not be ordered.
3885 for (int i = 0; i < blocks_.length(); ++i) {
3886 DCHECK(!blocks_[i]->IsOrdered());
3890 PostorderProcessor* postorder =
3891 PostorderProcessor::CreateEntryProcessor(zone(), blocks_[0]);
3894 postorder = postorder->PerformStep(zone(), &blocks_);
3898 // Now all blocks must be marked as ordered.
3899 for (int i = 0; i < blocks_.length(); ++i) {
3900 DCHECK(blocks_[i]->IsOrdered());
3904 // Reverse block list and assign block IDs.
3905 for (int i = 0, j = blocks_.length(); --j >= i; ++i) {
3906 HBasicBlock* bi = blocks_[i];
3907 HBasicBlock* bj = blocks_[j];
3908 bi->set_block_id(j);
3909 bj->set_block_id(i);
3916 void HGraph::AssignDominators() {
3917 HPhase phase("H_Assign dominators", this);
3918 for (int i = 0; i < blocks_.length(); ++i) {
3919 HBasicBlock* block = blocks_[i];
3920 if (block->IsLoopHeader()) {
3921 // Only the first predecessor of a loop header is from outside the loop.
3922 // All others are back edges, and thus cannot dominate the loop header.
3923 block->AssignCommonDominator(block->predecessors()->first());
3924 block->AssignLoopSuccessorDominators();
3926 for (int j = blocks_[i]->predecessors()->length() - 1; j >= 0; --j) {
3927 blocks_[i]->AssignCommonDominator(blocks_[i]->predecessors()->at(j));
3934 bool HGraph::CheckArgumentsPhiUses() {
3935 int block_count = blocks_.length();
3936 for (int i = 0; i < block_count; ++i) {
3937 for (int j = 0; j < blocks_[i]->phis()->length(); ++j) {
3938 HPhi* phi = blocks_[i]->phis()->at(j);
3939 // We don't support phi uses of arguments for now.
3940 if (phi->CheckFlag(HValue::kIsArguments)) return false;
3947 bool HGraph::CheckConstPhiUses() {
3948 int block_count = blocks_.length();
3949 for (int i = 0; i < block_count; ++i) {
3950 for (int j = 0; j < blocks_[i]->phis()->length(); ++j) {
3951 HPhi* phi = blocks_[i]->phis()->at(j);
3952 // Check for the hole value (from an uninitialized const).
3953 for (int k = 0; k < phi->OperandCount(); k++) {
3954 if (phi->OperandAt(k) == GetConstantHole()) return false;
3962 void HGraph::CollectPhis() {
3963 int block_count = blocks_.length();
3964 phi_list_ = new(zone()) ZoneList<HPhi*>(block_count, zone());
3965 for (int i = 0; i < block_count; ++i) {
3966 for (int j = 0; j < blocks_[i]->phis()->length(); ++j) {
3967 HPhi* phi = blocks_[i]->phis()->at(j);
3968 phi_list_->Add(phi, zone());
3974 // Implementation of utility class to encapsulate the translation state for
3975 // a (possibly inlined) function.
3976 FunctionState::FunctionState(HOptimizedGraphBuilder* owner,
3977 CompilationInfo* info, InliningKind inlining_kind,
3980 compilation_info_(info),
3981 call_context_(NULL),
3982 inlining_kind_(inlining_kind),
3983 function_return_(NULL),
3984 test_context_(NULL),
3986 arguments_object_(NULL),
3987 arguments_elements_(NULL),
3988 inlining_id_(inlining_id),
3989 outer_source_position_(SourcePosition::Unknown()),
3990 outer_(owner->function_state()) {
3991 if (outer_ != NULL) {
3992 // State for an inline function.
3993 if (owner->ast_context()->IsTest()) {
3994 HBasicBlock* if_true = owner->graph()->CreateBasicBlock();
3995 HBasicBlock* if_false = owner->graph()->CreateBasicBlock();
3996 if_true->MarkAsInlineReturnTarget(owner->current_block());
3997 if_false->MarkAsInlineReturnTarget(owner->current_block());
3998 TestContext* outer_test_context = TestContext::cast(owner->ast_context());
3999 Expression* cond = outer_test_context->condition();
4000 // The AstContext constructor pushed on the context stack. This newed
4001 // instance is the reason that AstContext can't be BASE_EMBEDDED.
4002 test_context_ = new TestContext(owner, cond, if_true, if_false);
4004 function_return_ = owner->graph()->CreateBasicBlock();
4005 function_return()->MarkAsInlineReturnTarget(owner->current_block());
4007 // Set this after possibly allocating a new TestContext above.
4008 call_context_ = owner->ast_context();
4011 // Push on the state stack.
4012 owner->set_function_state(this);
4014 if (compilation_info_->is_tracking_positions()) {
4015 outer_source_position_ = owner->source_position();
4016 owner->EnterInlinedSource(
4017 info->shared_info()->start_position(),
4019 owner->SetSourcePosition(info->shared_info()->start_position());
4024 FunctionState::~FunctionState() {
4025 delete test_context_;
4026 owner_->set_function_state(outer_);
4028 if (compilation_info_->is_tracking_positions()) {
4029 owner_->set_source_position(outer_source_position_);
4030 owner_->EnterInlinedSource(
4031 outer_->compilation_info()->shared_info()->start_position(),
4032 outer_->inlining_id());
4037 // Implementation of utility classes to represent an expression's context in
4039 AstContext::AstContext(HOptimizedGraphBuilder* owner, Expression::Context kind)
4042 outer_(owner->ast_context()),
4043 typeof_mode_(NOT_INSIDE_TYPEOF) {
4044 owner->set_ast_context(this); // Push.
4046 DCHECK(owner->environment()->frame_type() == JS_FUNCTION);
4047 original_length_ = owner->environment()->length();
4052 AstContext::~AstContext() {
4053 owner_->set_ast_context(outer_); // Pop.
4057 EffectContext::~EffectContext() {
4058 DCHECK(owner()->HasStackOverflow() ||
4059 owner()->current_block() == NULL ||
4060 (owner()->environment()->length() == original_length_ &&
4061 owner()->environment()->frame_type() == JS_FUNCTION));
4065 ValueContext::~ValueContext() {
4066 DCHECK(owner()->HasStackOverflow() ||
4067 owner()->current_block() == NULL ||
4068 (owner()->environment()->length() == original_length_ + 1 &&
4069 owner()->environment()->frame_type() == JS_FUNCTION));
4073 void EffectContext::ReturnValue(HValue* value) {
4074 // The value is simply ignored.
4078 void ValueContext::ReturnValue(HValue* value) {
4079 // The value is tracked in the bailout environment, and communicated
4080 // through the environment as the result of the expression.
4081 if (value->CheckFlag(HValue::kIsArguments)) {
4082 if (flag_ == ARGUMENTS_FAKED) {
4083 value = owner()->graph()->GetConstantUndefined();
4084 } else if (!arguments_allowed()) {
4085 owner()->Bailout(kBadValueContextForArgumentsValue);
4088 owner()->Push(value);
4092 void TestContext::ReturnValue(HValue* value) {
4097 void EffectContext::ReturnInstruction(HInstruction* instr, BailoutId ast_id) {
4098 DCHECK(!instr->IsControlInstruction());
4099 owner()->AddInstruction(instr);
4100 if (instr->HasObservableSideEffects()) {
4101 owner()->Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
4106 void EffectContext::ReturnControl(HControlInstruction* instr,
4108 DCHECK(!instr->HasObservableSideEffects());
4109 HBasicBlock* empty_true = owner()->graph()->CreateBasicBlock();
4110 HBasicBlock* empty_false = owner()->graph()->CreateBasicBlock();
4111 instr->SetSuccessorAt(0, empty_true);
4112 instr->SetSuccessorAt(1, empty_false);
4113 owner()->FinishCurrentBlock(instr);
4114 HBasicBlock* join = owner()->CreateJoin(empty_true, empty_false, ast_id);
4115 owner()->set_current_block(join);
4119 void EffectContext::ReturnContinuation(HIfContinuation* continuation,
4121 HBasicBlock* true_branch = NULL;
4122 HBasicBlock* false_branch = NULL;
4123 continuation->Continue(&true_branch, &false_branch);
4124 if (!continuation->IsTrueReachable()) {
4125 owner()->set_current_block(false_branch);
4126 } else if (!continuation->IsFalseReachable()) {
4127 owner()->set_current_block(true_branch);
4129 HBasicBlock* join = owner()->CreateJoin(true_branch, false_branch, ast_id);
4130 owner()->set_current_block(join);
4135 void ValueContext::ReturnInstruction(HInstruction* instr, BailoutId ast_id) {
4136 DCHECK(!instr->IsControlInstruction());
4137 if (!arguments_allowed() && instr->CheckFlag(HValue::kIsArguments)) {
4138 return owner()->Bailout(kBadValueContextForArgumentsObjectValue);
4140 owner()->AddInstruction(instr);
4141 owner()->Push(instr);
4142 if (instr->HasObservableSideEffects()) {
4143 owner()->Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
4148 void ValueContext::ReturnControl(HControlInstruction* instr, BailoutId ast_id) {
4149 DCHECK(!instr->HasObservableSideEffects());
4150 if (!arguments_allowed() && instr->CheckFlag(HValue::kIsArguments)) {
4151 return owner()->Bailout(kBadValueContextForArgumentsObjectValue);
4153 HBasicBlock* materialize_false = owner()->graph()->CreateBasicBlock();
4154 HBasicBlock* materialize_true = owner()->graph()->CreateBasicBlock();
4155 instr->SetSuccessorAt(0, materialize_true);
4156 instr->SetSuccessorAt(1, materialize_false);
4157 owner()->FinishCurrentBlock(instr);
4158 owner()->set_current_block(materialize_true);
4159 owner()->Push(owner()->graph()->GetConstantTrue());
4160 owner()->set_current_block(materialize_false);
4161 owner()->Push(owner()->graph()->GetConstantFalse());
4163 owner()->CreateJoin(materialize_true, materialize_false, ast_id);
4164 owner()->set_current_block(join);
4168 void ValueContext::ReturnContinuation(HIfContinuation* continuation,
4170 HBasicBlock* materialize_true = NULL;
4171 HBasicBlock* materialize_false = NULL;
4172 continuation->Continue(&materialize_true, &materialize_false);
4173 if (continuation->IsTrueReachable()) {
4174 owner()->set_current_block(materialize_true);
4175 owner()->Push(owner()->graph()->GetConstantTrue());
4176 owner()->set_current_block(materialize_true);
4178 if (continuation->IsFalseReachable()) {
4179 owner()->set_current_block(materialize_false);
4180 owner()->Push(owner()->graph()->GetConstantFalse());
4181 owner()->set_current_block(materialize_false);
4183 if (continuation->TrueAndFalseReachable()) {
4185 owner()->CreateJoin(materialize_true, materialize_false, ast_id);
4186 owner()->set_current_block(join);
4191 void TestContext::ReturnInstruction(HInstruction* instr, BailoutId ast_id) {
4192 DCHECK(!instr->IsControlInstruction());
4193 HOptimizedGraphBuilder* builder = owner();
4194 builder->AddInstruction(instr);
4195 // We expect a simulate after every expression with side effects, though
4196 // this one isn't actually needed (and wouldn't work if it were targeted).
4197 if (instr->HasObservableSideEffects()) {
4198 builder->Push(instr);
4199 builder->Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
4206 void TestContext::ReturnControl(HControlInstruction* instr, BailoutId ast_id) {
4207 DCHECK(!instr->HasObservableSideEffects());
4208 HBasicBlock* empty_true = owner()->graph()->CreateBasicBlock();
4209 HBasicBlock* empty_false = owner()->graph()->CreateBasicBlock();
4210 instr->SetSuccessorAt(0, empty_true);
4211 instr->SetSuccessorAt(1, empty_false);
4212 owner()->FinishCurrentBlock(instr);
4213 owner()->Goto(empty_true, if_true(), owner()->function_state());
4214 owner()->Goto(empty_false, if_false(), owner()->function_state());
4215 owner()->set_current_block(NULL);
4219 void TestContext::ReturnContinuation(HIfContinuation* continuation,
4221 HBasicBlock* true_branch = NULL;
4222 HBasicBlock* false_branch = NULL;
4223 continuation->Continue(&true_branch, &false_branch);
4224 if (continuation->IsTrueReachable()) {
4225 owner()->Goto(true_branch, if_true(), owner()->function_state());
4227 if (continuation->IsFalseReachable()) {
4228 owner()->Goto(false_branch, if_false(), owner()->function_state());
4230 owner()->set_current_block(NULL);
4234 void TestContext::BuildBranch(HValue* value) {
4235 // We expect the graph to be in edge-split form: there is no edge that
4236 // connects a branch node to a join node. We conservatively ensure that
4237 // property by always adding an empty block on the outgoing edges of this
4239 HOptimizedGraphBuilder* builder = owner();
4240 if (value != NULL && value->CheckFlag(HValue::kIsArguments)) {
4241 builder->Bailout(kArgumentsObjectValueInATestContext);
4243 ToBooleanStub::Types expected(condition()->to_boolean_types());
4244 ReturnControl(owner()->New<HBranch>(value, expected), BailoutId::None());
4248 // HOptimizedGraphBuilder infrastructure for bailing out and checking bailouts.
4249 #define CHECK_BAILOUT(call) \
4252 if (HasStackOverflow()) return; \
4256 #define CHECK_ALIVE(call) \
4259 if (HasStackOverflow() || current_block() == NULL) return; \
4263 #define CHECK_ALIVE_OR_RETURN(call, value) \
4266 if (HasStackOverflow() || current_block() == NULL) return value; \
4270 void HOptimizedGraphBuilder::Bailout(BailoutReason reason) {
4271 current_info()->AbortOptimization(reason);
4276 void HOptimizedGraphBuilder::VisitForEffect(Expression* expr) {
4277 EffectContext for_effect(this);
4282 void HOptimizedGraphBuilder::VisitForValue(Expression* expr,
4283 ArgumentsAllowedFlag flag) {
4284 ValueContext for_value(this, flag);
4289 void HOptimizedGraphBuilder::VisitForTypeOf(Expression* expr) {
4290 ValueContext for_value(this, ARGUMENTS_NOT_ALLOWED);
4291 for_value.set_typeof_mode(INSIDE_TYPEOF);
4296 void HOptimizedGraphBuilder::VisitForControl(Expression* expr,
4297 HBasicBlock* true_block,
4298 HBasicBlock* false_block) {
4299 TestContext for_test(this, expr, true_block, false_block);
4304 void HOptimizedGraphBuilder::VisitExpressions(
4305 ZoneList<Expression*>* exprs) {
4306 for (int i = 0; i < exprs->length(); ++i) {
4307 CHECK_ALIVE(VisitForValue(exprs->at(i)));
4312 void HOptimizedGraphBuilder::VisitExpressions(ZoneList<Expression*>* exprs,
4313 ArgumentsAllowedFlag flag) {
4314 for (int i = 0; i < exprs->length(); ++i) {
4315 CHECK_ALIVE(VisitForValue(exprs->at(i), flag));
4320 bool HOptimizedGraphBuilder::BuildGraph() {
4321 if (IsSubclassConstructor(current_info()->function()->kind())) {
4322 Bailout(kSuperReference);
4326 int slots = current_info()->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
4327 if (current_info()->scope()->is_script_scope() && slots > 0) {
4328 Bailout(kScriptContext);
4332 Scope* scope = current_info()->scope();
4335 // Add an edge to the body entry. This is warty: the graph's start
4336 // environment will be used by the Lithium translation as the initial
4337 // environment on graph entry, but it has now been mutated by the
4338 // Hydrogen translation of the instructions in the start block. This
4339 // environment uses values which have not been defined yet. These
4340 // Hydrogen instructions will then be replayed by the Lithium
4341 // translation, so they cannot have an environment effect. The edge to
4342 // the body's entry block (along with some special logic for the start
4343 // block in HInstruction::InsertAfter) seals the start block from
4344 // getting unwanted instructions inserted.
4346 // TODO(kmillikin): Fix this. Stop mutating the initial environment.
4347 // Make the Hydrogen instructions in the initial block into Hydrogen
4348 // values (but not instructions), present in the initial environment and
4349 // not replayed by the Lithium translation.
4350 HEnvironment* initial_env = environment()->CopyWithoutHistory();
4351 HBasicBlock* body_entry = CreateBasicBlock(initial_env);
4353 body_entry->SetJoinId(BailoutId::FunctionEntry());
4354 set_current_block(body_entry);
4356 VisitDeclarations(scope->declarations());
4357 Add<HSimulate>(BailoutId::Declarations());
4359 Add<HStackCheck>(HStackCheck::kFunctionEntry);
4361 VisitStatements(current_info()->function()->body());
4362 if (HasStackOverflow()) return false;
4364 if (current_block() != NULL) {
4365 Add<HReturn>(graph()->GetConstantUndefined());
4366 set_current_block(NULL);
4369 // If the checksum of the number of type info changes is the same as the
4370 // last time this function was compiled, then this recompile is likely not
4371 // due to missing/inadequate type feedback, but rather too aggressive
4372 // optimization. Disable optimistic LICM in that case.
4373 Handle<Code> unoptimized_code(current_info()->shared_info()->code());
4374 DCHECK(unoptimized_code->kind() == Code::FUNCTION);
4375 Handle<TypeFeedbackInfo> type_info(
4376 TypeFeedbackInfo::cast(unoptimized_code->type_feedback_info()));
4377 int checksum = type_info->own_type_change_checksum();
4378 int composite_checksum = graph()->update_type_change_checksum(checksum);
4379 graph()->set_use_optimistic_licm(
4380 !type_info->matches_inlined_type_change_checksum(composite_checksum));
4381 type_info->set_inlined_type_change_checksum(composite_checksum);
4383 // Perform any necessary OSR-specific cleanups or changes to the graph.
4384 osr()->FinishGraph();
4390 bool HGraph::Optimize(BailoutReason* bailout_reason) {
4394 // We need to create a HConstant "zero" now so that GVN will fold every
4395 // zero-valued constant in the graph together.
4396 // The constant is needed to make idef-based bounds check work: the pass
4397 // evaluates relations with "zero" and that zero cannot be created after GVN.
4401 // Do a full verify after building the graph and computing dominators.
4405 if (FLAG_analyze_environment_liveness && maximum_environment_size() != 0) {
4406 Run<HEnvironmentLivenessAnalysisPhase>();
4409 if (!CheckConstPhiUses()) {
4410 *bailout_reason = kUnsupportedPhiUseOfConstVariable;
4413 Run<HRedundantPhiEliminationPhase>();
4414 if (!CheckArgumentsPhiUses()) {
4415 *bailout_reason = kUnsupportedPhiUseOfArguments;
4419 // Find and mark unreachable code to simplify optimizations, especially gvn,
4420 // where unreachable code could unnecessarily defeat LICM.
4421 Run<HMarkUnreachableBlocksPhase>();
4423 if (FLAG_dead_code_elimination) Run<HDeadCodeEliminationPhase>();
4424 if (FLAG_use_escape_analysis) Run<HEscapeAnalysisPhase>();
4426 if (FLAG_load_elimination) Run<HLoadEliminationPhase>();
4430 if (has_osr()) osr()->FinishOsrValues();
4432 Run<HInferRepresentationPhase>();
4434 // Remove HSimulate instructions that have turned out not to be needed
4435 // after all by folding them into the following HSimulate.
4436 // This must happen after inferring representations.
4437 Run<HMergeRemovableSimulatesPhase>();
4439 Run<HMarkDeoptimizeOnUndefinedPhase>();
4440 Run<HRepresentationChangesPhase>();
4442 Run<HInferTypesPhase>();
4444 // Must be performed before canonicalization to ensure that Canonicalize
4445 // will not remove semantically meaningful ToInt32 operations e.g. BIT_OR with
4447 Run<HUint32AnalysisPhase>();
4449 if (FLAG_use_canonicalizing) Run<HCanonicalizePhase>();
4451 if (FLAG_use_gvn) Run<HGlobalValueNumberingPhase>();
4453 if (FLAG_check_elimination) Run<HCheckEliminationPhase>();
4455 if (FLAG_store_elimination) Run<HStoreEliminationPhase>();
4457 Run<HRangeAnalysisPhase>();
4459 Run<HComputeChangeUndefinedToNaN>();
4461 // Eliminate redundant stack checks on backwards branches.
4462 Run<HStackCheckEliminationPhase>();
4464 if (FLAG_array_bounds_checks_elimination) Run<HBoundsCheckEliminationPhase>();
4465 if (FLAG_array_bounds_checks_hoisting) Run<HBoundsCheckHoistingPhase>();
4466 if (FLAG_array_index_dehoisting) Run<HDehoistIndexComputationsPhase>();
4467 if (FLAG_dead_code_elimination) Run<HDeadCodeEliminationPhase>();
4469 RestoreActualValues();
4471 // Find unreachable code a second time, GVN and other optimizations may have
4472 // made blocks unreachable that were previously reachable.
4473 Run<HMarkUnreachableBlocksPhase>();
4479 void HGraph::RestoreActualValues() {
4480 HPhase phase("H_Restore actual values", this);
4482 for (int block_index = 0; block_index < blocks()->length(); block_index++) {
4483 HBasicBlock* block = blocks()->at(block_index);
4486 for (int i = 0; i < block->phis()->length(); i++) {
4487 HPhi* phi = block->phis()->at(i);
4488 DCHECK(phi->ActualValue() == phi);
4492 for (HInstructionIterator it(block); !it.Done(); it.Advance()) {
4493 HInstruction* instruction = it.Current();
4494 if (instruction->ActualValue() == instruction) continue;
4495 if (instruction->CheckFlag(HValue::kIsDead)) {
4496 // The instruction was marked as deleted but left in the graph
4497 // as a control flow dependency point for subsequent
4499 instruction->DeleteAndReplaceWith(instruction->ActualValue());
4501 DCHECK(instruction->IsInformativeDefinition());
4502 if (instruction->IsPurelyInformativeDefinition()) {
4503 instruction->DeleteAndReplaceWith(instruction->RedefinedOperand());
4505 instruction->ReplaceAllUsesWith(instruction->ActualValue());
4513 void HOptimizedGraphBuilder::PushArgumentsFromEnvironment(int count) {
4514 ZoneList<HValue*> arguments(count, zone());
4515 for (int i = 0; i < count; ++i) {
4516 arguments.Add(Pop(), zone());
4519 HPushArguments* push_args = New<HPushArguments>();
4520 while (!arguments.is_empty()) {
4521 push_args->AddInput(arguments.RemoveLast());
4523 AddInstruction(push_args);
4527 template <class Instruction>
4528 HInstruction* HOptimizedGraphBuilder::PreProcessCall(Instruction* call) {
4529 PushArgumentsFromEnvironment(call->argument_count());
4534 void HOptimizedGraphBuilder::SetUpScope(Scope* scope) {
4535 // First special is HContext.
4536 HInstruction* context = Add<HContext>();
4537 environment()->BindContext(context);
4539 // Create an arguments object containing the initial parameters. Set the
4540 // initial values of parameters including "this" having parameter index 0.
4541 DCHECK_EQ(scope->num_parameters() + 1, environment()->parameter_count());
4542 HArgumentsObject* arguments_object =
4543 New<HArgumentsObject>(environment()->parameter_count());
4544 for (int i = 0; i < environment()->parameter_count(); ++i) {
4545 HInstruction* parameter = Add<HParameter>(i);
4546 arguments_object->AddArgument(parameter, zone());
4547 environment()->Bind(i, parameter);
4549 AddInstruction(arguments_object);
4550 graph()->SetArgumentsObject(arguments_object);
4552 HConstant* undefined_constant = graph()->GetConstantUndefined();
4553 // Initialize specials and locals to undefined.
4554 for (int i = environment()->parameter_count() + 1;
4555 i < environment()->length();
4557 environment()->Bind(i, undefined_constant);
4560 // Handle the arguments and arguments shadow variables specially (they do
4561 // not have declarations).
4562 if (scope->arguments() != NULL) {
4563 environment()->Bind(scope->arguments(),
4564 graph()->GetArgumentsObject());
4568 Variable* rest = scope->rest_parameter(&rest_index);
4570 return Bailout(kRestParameter);
4573 if (scope->this_function_var() != nullptr ||
4574 scope->new_target_var() != nullptr) {
4575 return Bailout(kSuperReference);
4580 void HOptimizedGraphBuilder::VisitStatements(ZoneList<Statement*>* statements) {
4581 for (int i = 0; i < statements->length(); i++) {
4582 Statement* stmt = statements->at(i);
4583 CHECK_ALIVE(Visit(stmt));
4584 if (stmt->IsJump()) break;
4589 void HOptimizedGraphBuilder::VisitBlock(Block* stmt) {
4590 DCHECK(!HasStackOverflow());
4591 DCHECK(current_block() != NULL);
4592 DCHECK(current_block()->HasPredecessor());
4594 Scope* outer_scope = scope();
4595 Scope* scope = stmt->scope();
4596 BreakAndContinueInfo break_info(stmt, outer_scope);
4598 { BreakAndContinueScope push(&break_info, this);
4599 if (scope != NULL) {
4600 if (scope->ContextLocalCount() > 0) {
4601 // Load the function object.
4602 Scope* declaration_scope = scope->DeclarationScope();
4603 HInstruction* function;
4604 HValue* outer_context = environment()->context();
4605 if (declaration_scope->is_script_scope() ||
4606 declaration_scope->is_eval_scope()) {
4607 function = new (zone())
4608 HLoadContextSlot(outer_context, Context::CLOSURE_INDEX,
4609 HLoadContextSlot::kNoCheck);
4611 function = New<HThisFunction>();
4613 AddInstruction(function);
4614 // Allocate a block context and store it to the stack frame.
4615 HInstruction* inner_context = Add<HAllocateBlockContext>(
4616 outer_context, function, scope->GetScopeInfo(isolate()));
4617 HInstruction* instr = Add<HStoreFrameContext>(inner_context);
4619 environment()->BindContext(inner_context);
4620 if (instr->HasObservableSideEffects()) {
4621 AddSimulate(stmt->EntryId(), REMOVABLE_SIMULATE);
4624 VisitDeclarations(scope->declarations());
4625 AddSimulate(stmt->DeclsId(), REMOVABLE_SIMULATE);
4627 CHECK_BAILOUT(VisitStatements(stmt->statements()));
4629 set_scope(outer_scope);
4630 if (scope != NULL && current_block() != NULL &&
4631 scope->ContextLocalCount() > 0) {
4632 HValue* inner_context = environment()->context();
4633 HValue* outer_context = Add<HLoadNamedField>(
4634 inner_context, nullptr,
4635 HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX));
4637 HInstruction* instr = Add<HStoreFrameContext>(outer_context);
4638 environment()->BindContext(outer_context);
4639 if (instr->HasObservableSideEffects()) {
4640 AddSimulate(stmt->ExitId(), REMOVABLE_SIMULATE);
4643 HBasicBlock* break_block = break_info.break_block();
4644 if (break_block != NULL) {
4645 if (current_block() != NULL) Goto(break_block);
4646 break_block->SetJoinId(stmt->ExitId());
4647 set_current_block(break_block);
4652 void HOptimizedGraphBuilder::VisitExpressionStatement(
4653 ExpressionStatement* stmt) {
4654 DCHECK(!HasStackOverflow());
4655 DCHECK(current_block() != NULL);
4656 DCHECK(current_block()->HasPredecessor());
4657 VisitForEffect(stmt->expression());
4661 void HOptimizedGraphBuilder::VisitEmptyStatement(EmptyStatement* stmt) {
4662 DCHECK(!HasStackOverflow());
4663 DCHECK(current_block() != NULL);
4664 DCHECK(current_block()->HasPredecessor());
4668 void HOptimizedGraphBuilder::VisitIfStatement(IfStatement* stmt) {
4669 DCHECK(!HasStackOverflow());
4670 DCHECK(current_block() != NULL);
4671 DCHECK(current_block()->HasPredecessor());
4672 if (stmt->condition()->ToBooleanIsTrue()) {
4673 Add<HSimulate>(stmt->ThenId());
4674 Visit(stmt->then_statement());
4675 } else if (stmt->condition()->ToBooleanIsFalse()) {
4676 Add<HSimulate>(stmt->ElseId());
4677 Visit(stmt->else_statement());
4679 HBasicBlock* cond_true = graph()->CreateBasicBlock();
4680 HBasicBlock* cond_false = graph()->CreateBasicBlock();
4681 CHECK_BAILOUT(VisitForControl(stmt->condition(), cond_true, cond_false));
4683 if (cond_true->HasPredecessor()) {
4684 cond_true->SetJoinId(stmt->ThenId());
4685 set_current_block(cond_true);
4686 CHECK_BAILOUT(Visit(stmt->then_statement()));
4687 cond_true = current_block();
4692 if (cond_false->HasPredecessor()) {
4693 cond_false->SetJoinId(stmt->ElseId());
4694 set_current_block(cond_false);
4695 CHECK_BAILOUT(Visit(stmt->else_statement()));
4696 cond_false = current_block();
4701 HBasicBlock* join = CreateJoin(cond_true, cond_false, stmt->IfId());
4702 set_current_block(join);
4707 HBasicBlock* HOptimizedGraphBuilder::BreakAndContinueScope::Get(
4708 BreakableStatement* stmt,
4713 BreakAndContinueScope* current = this;
4714 while (current != NULL && current->info()->target() != stmt) {
4715 *drop_extra += current->info()->drop_extra();
4716 current = current->next();
4718 DCHECK(current != NULL); // Always found (unless stack is malformed).
4719 *scope = current->info()->scope();
4721 if (type == BREAK) {
4722 *drop_extra += current->info()->drop_extra();
4725 HBasicBlock* block = NULL;
4728 block = current->info()->break_block();
4729 if (block == NULL) {
4730 block = current->owner()->graph()->CreateBasicBlock();
4731 current->info()->set_break_block(block);
4736 block = current->info()->continue_block();
4737 if (block == NULL) {
4738 block = current->owner()->graph()->CreateBasicBlock();
4739 current->info()->set_continue_block(block);
4748 void HOptimizedGraphBuilder::VisitContinueStatement(
4749 ContinueStatement* stmt) {
4750 DCHECK(!HasStackOverflow());
4751 DCHECK(current_block() != NULL);
4752 DCHECK(current_block()->HasPredecessor());
4753 Scope* outer_scope = NULL;
4754 Scope* inner_scope = scope();
4756 HBasicBlock* continue_block = break_scope()->Get(
4757 stmt->target(), BreakAndContinueScope::CONTINUE,
4758 &outer_scope, &drop_extra);
4759 HValue* context = environment()->context();
4761 int context_pop_count = inner_scope->ContextChainLength(outer_scope);
4762 if (context_pop_count > 0) {
4763 while (context_pop_count-- > 0) {
4764 HInstruction* context_instruction = Add<HLoadNamedField>(
4766 HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX));
4767 context = context_instruction;
4769 HInstruction* instr = Add<HStoreFrameContext>(context);
4770 if (instr->HasObservableSideEffects()) {
4771 AddSimulate(stmt->target()->EntryId(), REMOVABLE_SIMULATE);
4773 environment()->BindContext(context);
4776 Goto(continue_block);
4777 set_current_block(NULL);
4781 void HOptimizedGraphBuilder::VisitBreakStatement(BreakStatement* stmt) {
4782 DCHECK(!HasStackOverflow());
4783 DCHECK(current_block() != NULL);
4784 DCHECK(current_block()->HasPredecessor());
4785 Scope* outer_scope = NULL;
4786 Scope* inner_scope = scope();
4788 HBasicBlock* break_block = break_scope()->Get(
4789 stmt->target(), BreakAndContinueScope::BREAK,
4790 &outer_scope, &drop_extra);
4791 HValue* context = environment()->context();
4793 int context_pop_count = inner_scope->ContextChainLength(outer_scope);
4794 if (context_pop_count > 0) {
4795 while (context_pop_count-- > 0) {
4796 HInstruction* context_instruction = Add<HLoadNamedField>(
4798 HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX));
4799 context = context_instruction;
4801 HInstruction* instr = Add<HStoreFrameContext>(context);
4802 if (instr->HasObservableSideEffects()) {
4803 AddSimulate(stmt->target()->ExitId(), REMOVABLE_SIMULATE);
4805 environment()->BindContext(context);
4808 set_current_block(NULL);
4812 void HOptimizedGraphBuilder::VisitReturnStatement(ReturnStatement* stmt) {
4813 DCHECK(!HasStackOverflow());
4814 DCHECK(current_block() != NULL);
4815 DCHECK(current_block()->HasPredecessor());
4816 FunctionState* state = function_state();
4817 AstContext* context = call_context();
4818 if (context == NULL) {
4819 // Not an inlined return, so an actual one.
4820 CHECK_ALIVE(VisitForValue(stmt->expression()));
4821 HValue* result = environment()->Pop();
4822 Add<HReturn>(result);
4823 } else if (state->inlining_kind() == CONSTRUCT_CALL_RETURN) {
4824 // Return from an inlined construct call. In a test context the return value
4825 // will always evaluate to true, in a value context the return value needs
4826 // to be a JSObject.
4827 if (context->IsTest()) {
4828 TestContext* test = TestContext::cast(context);
4829 CHECK_ALIVE(VisitForEffect(stmt->expression()));
4830 Goto(test->if_true(), state);
4831 } else if (context->IsEffect()) {
4832 CHECK_ALIVE(VisitForEffect(stmt->expression()));
4833 Goto(function_return(), state);
4835 DCHECK(context->IsValue());
4836 CHECK_ALIVE(VisitForValue(stmt->expression()));
4837 HValue* return_value = Pop();
4838 HValue* receiver = environment()->arguments_environment()->Lookup(0);
4839 HHasInstanceTypeAndBranch* typecheck =
4840 New<HHasInstanceTypeAndBranch>(return_value,
4841 FIRST_SPEC_OBJECT_TYPE,
4842 LAST_SPEC_OBJECT_TYPE);
4843 HBasicBlock* if_spec_object = graph()->CreateBasicBlock();
4844 HBasicBlock* not_spec_object = graph()->CreateBasicBlock();
4845 typecheck->SetSuccessorAt(0, if_spec_object);
4846 typecheck->SetSuccessorAt(1, not_spec_object);
4847 FinishCurrentBlock(typecheck);
4848 AddLeaveInlined(if_spec_object, return_value, state);
4849 AddLeaveInlined(not_spec_object, receiver, state);
4851 } else if (state->inlining_kind() == SETTER_CALL_RETURN) {
4852 // Return from an inlined setter call. The returned value is never used, the
4853 // value of an assignment is always the value of the RHS of the assignment.
4854 CHECK_ALIVE(VisitForEffect(stmt->expression()));
4855 if (context->IsTest()) {
4856 HValue* rhs = environment()->arguments_environment()->Lookup(1);
4857 context->ReturnValue(rhs);
4858 } else if (context->IsEffect()) {
4859 Goto(function_return(), state);
4861 DCHECK(context->IsValue());
4862 HValue* rhs = environment()->arguments_environment()->Lookup(1);
4863 AddLeaveInlined(rhs, state);
4866 // Return from a normal inlined function. Visit the subexpression in the
4867 // expression context of the call.
4868 if (context->IsTest()) {
4869 TestContext* test = TestContext::cast(context);
4870 VisitForControl(stmt->expression(), test->if_true(), test->if_false());
4871 } else if (context->IsEffect()) {
4872 // Visit in value context and ignore the result. This is needed to keep
4873 // environment in sync with full-codegen since some visitors (e.g.
4874 // VisitCountOperation) use the operand stack differently depending on
4876 CHECK_ALIVE(VisitForValue(stmt->expression()));
4878 Goto(function_return(), state);
4880 DCHECK(context->IsValue());
4881 CHECK_ALIVE(VisitForValue(stmt->expression()));
4882 AddLeaveInlined(Pop(), state);
4885 set_current_block(NULL);
4889 void HOptimizedGraphBuilder::VisitWithStatement(WithStatement* stmt) {
4890 DCHECK(!HasStackOverflow());
4891 DCHECK(current_block() != NULL);
4892 DCHECK(current_block()->HasPredecessor());
4893 return Bailout(kWithStatement);
4897 void HOptimizedGraphBuilder::VisitSwitchStatement(SwitchStatement* stmt) {
4898 DCHECK(!HasStackOverflow());
4899 DCHECK(current_block() != NULL);
4900 DCHECK(current_block()->HasPredecessor());
4902 ZoneList<CaseClause*>* clauses = stmt->cases();
4903 int clause_count = clauses->length();
4904 ZoneList<HBasicBlock*> body_blocks(clause_count, zone());
4906 CHECK_ALIVE(VisitForValue(stmt->tag()));
4907 Add<HSimulate>(stmt->EntryId());
4908 HValue* tag_value = Top();
4909 Type* tag_type = stmt->tag()->bounds().lower;
4911 // 1. Build all the tests, with dangling true branches
4912 BailoutId default_id = BailoutId::None();
4913 for (int i = 0; i < clause_count; ++i) {
4914 CaseClause* clause = clauses->at(i);
4915 if (clause->is_default()) {
4916 body_blocks.Add(NULL, zone());
4917 if (default_id.IsNone()) default_id = clause->EntryId();
4921 // Generate a compare and branch.
4922 CHECK_ALIVE(VisitForValue(clause->label()));
4923 HValue* label_value = Pop();
4925 Type* label_type = clause->label()->bounds().lower;
4926 Type* combined_type = clause->compare_type();
4927 HControlInstruction* compare = BuildCompareInstruction(
4928 Token::EQ_STRICT, tag_value, label_value, tag_type, label_type,
4930 ScriptPositionToSourcePosition(stmt->tag()->position()),
4931 ScriptPositionToSourcePosition(clause->label()->position()),
4932 PUSH_BEFORE_SIMULATE, clause->id());
4934 HBasicBlock* next_test_block = graph()->CreateBasicBlock();
4935 HBasicBlock* body_block = graph()->CreateBasicBlock();
4936 body_blocks.Add(body_block, zone());
4937 compare->SetSuccessorAt(0, body_block);
4938 compare->SetSuccessorAt(1, next_test_block);
4939 FinishCurrentBlock(compare);
4941 set_current_block(body_block);
4942 Drop(1); // tag_value
4944 set_current_block(next_test_block);
4947 // Save the current block to use for the default or to join with the
4949 HBasicBlock* last_block = current_block();
4950 Drop(1); // tag_value
4952 // 2. Loop over the clauses and the linked list of tests in lockstep,
4953 // translating the clause bodies.
4954 HBasicBlock* fall_through_block = NULL;
4956 BreakAndContinueInfo break_info(stmt, scope());
4957 { BreakAndContinueScope push(&break_info, this);
4958 for (int i = 0; i < clause_count; ++i) {
4959 CaseClause* clause = clauses->at(i);
4961 // Identify the block where normal (non-fall-through) control flow
4963 HBasicBlock* normal_block = NULL;
4964 if (clause->is_default()) {
4965 if (last_block == NULL) continue;
4966 normal_block = last_block;
4967 last_block = NULL; // Cleared to indicate we've handled it.
4969 normal_block = body_blocks[i];
4972 if (fall_through_block == NULL) {
4973 set_current_block(normal_block);
4975 HBasicBlock* join = CreateJoin(fall_through_block,
4978 set_current_block(join);
4981 CHECK_BAILOUT(VisitStatements(clause->statements()));
4982 fall_through_block = current_block();
4986 // Create an up-to-3-way join. Use the break block if it exists since
4987 // it's already a join block.
4988 HBasicBlock* break_block = break_info.break_block();
4989 if (break_block == NULL) {
4990 set_current_block(CreateJoin(fall_through_block,
4994 if (fall_through_block != NULL) Goto(fall_through_block, break_block);
4995 if (last_block != NULL) Goto(last_block, break_block);
4996 break_block->SetJoinId(stmt->ExitId());
4997 set_current_block(break_block);
5002 void HOptimizedGraphBuilder::VisitLoopBody(IterationStatement* stmt,
5003 HBasicBlock* loop_entry) {
5004 Add<HSimulate>(stmt->StackCheckId());
5005 HStackCheck* stack_check =
5006 HStackCheck::cast(Add<HStackCheck>(HStackCheck::kBackwardsBranch));
5007 DCHECK(loop_entry->IsLoopHeader());
5008 loop_entry->loop_information()->set_stack_check(stack_check);
5009 CHECK_BAILOUT(Visit(stmt->body()));
5013 void HOptimizedGraphBuilder::VisitDoWhileStatement(DoWhileStatement* stmt) {
5014 DCHECK(!HasStackOverflow());
5015 DCHECK(current_block() != NULL);
5016 DCHECK(current_block()->HasPredecessor());
5017 DCHECK(current_block() != NULL);
5018 HBasicBlock* loop_entry = BuildLoopEntry(stmt);
5020 BreakAndContinueInfo break_info(stmt, scope());
5022 BreakAndContinueScope push(&break_info, this);
5023 CHECK_BAILOUT(VisitLoopBody(stmt, loop_entry));
5025 HBasicBlock* body_exit =
5026 JoinContinue(stmt, current_block(), break_info.continue_block());
5027 HBasicBlock* loop_successor = NULL;
5028 if (body_exit != NULL && !stmt->cond()->ToBooleanIsTrue()) {
5029 set_current_block(body_exit);
5030 loop_successor = graph()->CreateBasicBlock();
5031 if (stmt->cond()->ToBooleanIsFalse()) {
5032 loop_entry->loop_information()->stack_check()->Eliminate();
5033 Goto(loop_successor);
5036 // The block for a true condition, the actual predecessor block of the
5038 body_exit = graph()->CreateBasicBlock();
5039 CHECK_BAILOUT(VisitForControl(stmt->cond(), body_exit, loop_successor));
5041 if (body_exit != NULL && body_exit->HasPredecessor()) {
5042 body_exit->SetJoinId(stmt->BackEdgeId());
5046 if (loop_successor->HasPredecessor()) {
5047 loop_successor->SetJoinId(stmt->ExitId());
5049 loop_successor = NULL;
5052 HBasicBlock* loop_exit = CreateLoop(stmt,
5056 break_info.break_block());
5057 set_current_block(loop_exit);
5061 void HOptimizedGraphBuilder::VisitWhileStatement(WhileStatement* stmt) {
5062 DCHECK(!HasStackOverflow());
5063 DCHECK(current_block() != NULL);
5064 DCHECK(current_block()->HasPredecessor());
5065 DCHECK(current_block() != NULL);
5066 HBasicBlock* loop_entry = BuildLoopEntry(stmt);
5068 // If the condition is constant true, do not generate a branch.
5069 HBasicBlock* loop_successor = NULL;
5070 if (!stmt->cond()->ToBooleanIsTrue()) {
5071 HBasicBlock* body_entry = graph()->CreateBasicBlock();
5072 loop_successor = graph()->CreateBasicBlock();
5073 CHECK_BAILOUT(VisitForControl(stmt->cond(), body_entry, loop_successor));
5074 if (body_entry->HasPredecessor()) {
5075 body_entry->SetJoinId(stmt->BodyId());
5076 set_current_block(body_entry);
5078 if (loop_successor->HasPredecessor()) {
5079 loop_successor->SetJoinId(stmt->ExitId());
5081 loop_successor = NULL;
5085 BreakAndContinueInfo break_info(stmt, scope());
5086 if (current_block() != NULL) {
5087 BreakAndContinueScope push(&break_info, this);
5088 CHECK_BAILOUT(VisitLoopBody(stmt, loop_entry));
5090 HBasicBlock* body_exit =
5091 JoinContinue(stmt, current_block(), break_info.continue_block());
5092 HBasicBlock* loop_exit = CreateLoop(stmt,
5096 break_info.break_block());
5097 set_current_block(loop_exit);
5101 void HOptimizedGraphBuilder::VisitForStatement(ForStatement* stmt) {
5102 DCHECK(!HasStackOverflow());
5103 DCHECK(current_block() != NULL);
5104 DCHECK(current_block()->HasPredecessor());
5105 if (stmt->init() != NULL) {
5106 CHECK_ALIVE(Visit(stmt->init()));
5108 DCHECK(current_block() != NULL);
5109 HBasicBlock* loop_entry = BuildLoopEntry(stmt);
5111 HBasicBlock* loop_successor = NULL;
5112 if (stmt->cond() != NULL) {
5113 HBasicBlock* body_entry = graph()->CreateBasicBlock();
5114 loop_successor = graph()->CreateBasicBlock();
5115 CHECK_BAILOUT(VisitForControl(stmt->cond(), body_entry, loop_successor));
5116 if (body_entry->HasPredecessor()) {
5117 body_entry->SetJoinId(stmt->BodyId());
5118 set_current_block(body_entry);
5120 if (loop_successor->HasPredecessor()) {
5121 loop_successor->SetJoinId(stmt->ExitId());
5123 loop_successor = NULL;
5127 BreakAndContinueInfo break_info(stmt, scope());
5128 if (current_block() != NULL) {
5129 BreakAndContinueScope push(&break_info, this);
5130 CHECK_BAILOUT(VisitLoopBody(stmt, loop_entry));
5132 HBasicBlock* body_exit =
5133 JoinContinue(stmt, current_block(), break_info.continue_block());
5135 if (stmt->next() != NULL && body_exit != NULL) {
5136 set_current_block(body_exit);
5137 CHECK_BAILOUT(Visit(stmt->next()));
5138 body_exit = current_block();
5141 HBasicBlock* loop_exit = CreateLoop(stmt,
5145 break_info.break_block());
5146 set_current_block(loop_exit);
5150 void HOptimizedGraphBuilder::VisitForInStatement(ForInStatement* stmt) {
5151 DCHECK(!HasStackOverflow());
5152 DCHECK(current_block() != NULL);
5153 DCHECK(current_block()->HasPredecessor());
5155 if (!FLAG_optimize_for_in) {
5156 return Bailout(kForInStatementOptimizationIsDisabled);
5159 if (!stmt->each()->IsVariableProxy() ||
5160 !stmt->each()->AsVariableProxy()->var()->IsStackLocal()) {
5161 return Bailout(kForInStatementWithNonLocalEachVariable);
5164 Variable* each_var = stmt->each()->AsVariableProxy()->var();
5166 CHECK_ALIVE(VisitForValue(stmt->enumerable()));
5167 HValue* enumerable = Top(); // Leave enumerable at the top.
5169 IfBuilder if_undefined_or_null(this);
5170 if_undefined_or_null.If<HCompareObjectEqAndBranch>(
5171 enumerable, graph()->GetConstantUndefined());
5172 if_undefined_or_null.Or();
5173 if_undefined_or_null.If<HCompareObjectEqAndBranch>(
5174 enumerable, graph()->GetConstantNull());
5175 if_undefined_or_null.ThenDeopt(Deoptimizer::kUndefinedOrNullInForIn);
5176 if_undefined_or_null.End();
5177 BuildForInBody(stmt, each_var, enumerable);
5181 void HOptimizedGraphBuilder::BuildForInBody(ForInStatement* stmt,
5183 HValue* enumerable) {
5185 HInstruction* array;
5186 HInstruction* enum_length;
5187 bool fast = stmt->for_in_type() == ForInStatement::FAST_FOR_IN;
5189 map = Add<HForInPrepareMap>(enumerable);
5190 Add<HSimulate>(stmt->PrepareId());
5192 array = Add<HForInCacheArray>(enumerable, map,
5193 DescriptorArray::kEnumCacheBridgeCacheIndex);
5194 enum_length = Add<HMapEnumLength>(map);
5196 HInstruction* index_cache = Add<HForInCacheArray>(
5197 enumerable, map, DescriptorArray::kEnumCacheBridgeIndicesCacheIndex);
5198 HForInCacheArray::cast(array)
5199 ->set_index_cache(HForInCacheArray::cast(index_cache));
5201 Add<HSimulate>(stmt->PrepareId());
5203 NoObservableSideEffectsScope no_effects(this);
5204 BuildJSObjectCheck(enumerable, 0);
5206 Add<HSimulate>(stmt->ToObjectId());
5208 map = graph()->GetConstant1();
5209 Runtime::FunctionId function_id = Runtime::kGetPropertyNamesFast;
5210 Add<HPushArguments>(enumerable);
5211 array = Add<HCallRuntime>(isolate()->factory()->empty_string(),
5212 Runtime::FunctionForId(function_id), 1);
5214 Add<HSimulate>(stmt->EnumId());
5216 Handle<Map> array_map = isolate()->factory()->fixed_array_map();
5217 HValue* check = Add<HCheckMaps>(array, array_map);
5218 enum_length = AddLoadFixedArrayLength(array, check);
5221 HInstruction* start_index = Add<HConstant>(0);
5228 HBasicBlock* loop_entry = BuildLoopEntry(stmt);
5230 // Reload the values to ensure we have up-to-date values inside of the loop.
5231 // This is relevant especially for OSR where the values don't come from the
5232 // computation above, but from the OSR entry block.
5233 enumerable = environment()->ExpressionStackAt(4);
5234 HValue* index = environment()->ExpressionStackAt(0);
5235 HValue* limit = environment()->ExpressionStackAt(1);
5237 // Check that we still have more keys.
5238 HCompareNumericAndBranch* compare_index =
5239 New<HCompareNumericAndBranch>(index, limit, Token::LT);
5240 compare_index->set_observed_input_representation(
5241 Representation::Smi(), Representation::Smi());
5243 HBasicBlock* loop_body = graph()->CreateBasicBlock();
5244 HBasicBlock* loop_successor = graph()->CreateBasicBlock();
5246 compare_index->SetSuccessorAt(0, loop_body);
5247 compare_index->SetSuccessorAt(1, loop_successor);
5248 FinishCurrentBlock(compare_index);
5250 set_current_block(loop_successor);
5253 set_current_block(loop_body);
5256 Add<HLoadKeyed>(environment()->ExpressionStackAt(2), // Enum cache.
5257 index, index, FAST_ELEMENTS);
5260 // Check if the expected map still matches that of the enumerable.
5261 // If not just deoptimize.
5262 Add<HCheckMapValue>(enumerable, environment()->ExpressionStackAt(3));
5263 Bind(each_var, key);
5265 Add<HPushArguments>(enumerable, key);
5266 Runtime::FunctionId function_id = Runtime::kForInFilter;
5267 key = Add<HCallRuntime>(isolate()->factory()->empty_string(),
5268 Runtime::FunctionForId(function_id), 2);
5270 Add<HSimulate>(stmt->FilterId());
5272 Bind(each_var, key);
5273 IfBuilder if_undefined(this);
5274 if_undefined.If<HCompareObjectEqAndBranch>(key,
5275 graph()->GetConstantUndefined());
5276 if_undefined.ThenDeopt(Deoptimizer::kUndefined);
5278 Add<HSimulate>(stmt->AssignmentId());
5281 BreakAndContinueInfo break_info(stmt, scope(), 5);
5283 BreakAndContinueScope push(&break_info, this);
5284 CHECK_BAILOUT(VisitLoopBody(stmt, loop_entry));
5287 HBasicBlock* body_exit =
5288 JoinContinue(stmt, current_block(), break_info.continue_block());
5290 if (body_exit != NULL) {
5291 set_current_block(body_exit);
5293 HValue* current_index = Pop();
5294 Push(AddUncasted<HAdd>(current_index, graph()->GetConstant1()));
5295 body_exit = current_block();
5298 HBasicBlock* loop_exit = CreateLoop(stmt,
5302 break_info.break_block());
5304 set_current_block(loop_exit);
5308 void HOptimizedGraphBuilder::VisitForOfStatement(ForOfStatement* stmt) {
5309 DCHECK(!HasStackOverflow());
5310 DCHECK(current_block() != NULL);
5311 DCHECK(current_block()->HasPredecessor());
5312 return Bailout(kForOfStatement);
5316 void HOptimizedGraphBuilder::VisitTryCatchStatement(TryCatchStatement* stmt) {
5317 DCHECK(!HasStackOverflow());
5318 DCHECK(current_block() != NULL);
5319 DCHECK(current_block()->HasPredecessor());
5320 return Bailout(kTryCatchStatement);
5324 void HOptimizedGraphBuilder::VisitTryFinallyStatement(
5325 TryFinallyStatement* stmt) {
5326 DCHECK(!HasStackOverflow());
5327 DCHECK(current_block() != NULL);
5328 DCHECK(current_block()->HasPredecessor());
5329 return Bailout(kTryFinallyStatement);
5333 void HOptimizedGraphBuilder::VisitDebuggerStatement(DebuggerStatement* stmt) {
5334 DCHECK(!HasStackOverflow());
5335 DCHECK(current_block() != NULL);
5336 DCHECK(current_block()->HasPredecessor());
5337 return Bailout(kDebuggerStatement);
5341 void HOptimizedGraphBuilder::VisitCaseClause(CaseClause* clause) {
5346 void HOptimizedGraphBuilder::VisitFunctionLiteral(FunctionLiteral* expr) {
5347 DCHECK(!HasStackOverflow());
5348 DCHECK(current_block() != NULL);
5349 DCHECK(current_block()->HasPredecessor());
5350 Handle<SharedFunctionInfo> shared_info = Compiler::GetSharedFunctionInfo(
5351 expr, current_info()->script(), top_info());
5352 // We also have a stack overflow if the recursive compilation did.
5353 if (HasStackOverflow()) return;
5354 HFunctionLiteral* instr =
5355 New<HFunctionLiteral>(shared_info, expr->pretenure());
5356 return ast_context()->ReturnInstruction(instr, expr->id());
5360 void HOptimizedGraphBuilder::VisitClassLiteral(ClassLiteral* lit) {
5361 DCHECK(!HasStackOverflow());
5362 DCHECK(current_block() != NULL);
5363 DCHECK(current_block()->HasPredecessor());
5364 return Bailout(kClassLiteral);
5368 void HOptimizedGraphBuilder::VisitNativeFunctionLiteral(
5369 NativeFunctionLiteral* expr) {
5370 DCHECK(!HasStackOverflow());
5371 DCHECK(current_block() != NULL);
5372 DCHECK(current_block()->HasPredecessor());
5373 return Bailout(kNativeFunctionLiteral);
5377 void HOptimizedGraphBuilder::VisitConditional(Conditional* expr) {
5378 DCHECK(!HasStackOverflow());
5379 DCHECK(current_block() != NULL);
5380 DCHECK(current_block()->HasPredecessor());
5381 HBasicBlock* cond_true = graph()->CreateBasicBlock();
5382 HBasicBlock* cond_false = graph()->CreateBasicBlock();
5383 CHECK_BAILOUT(VisitForControl(expr->condition(), cond_true, cond_false));
5385 // Visit the true and false subexpressions in the same AST context as the
5386 // whole expression.
5387 if (cond_true->HasPredecessor()) {
5388 cond_true->SetJoinId(expr->ThenId());
5389 set_current_block(cond_true);
5390 CHECK_BAILOUT(Visit(expr->then_expression()));
5391 cond_true = current_block();
5396 if (cond_false->HasPredecessor()) {
5397 cond_false->SetJoinId(expr->ElseId());
5398 set_current_block(cond_false);
5399 CHECK_BAILOUT(Visit(expr->else_expression()));
5400 cond_false = current_block();
5405 if (!ast_context()->IsTest()) {
5406 HBasicBlock* join = CreateJoin(cond_true, cond_false, expr->id());
5407 set_current_block(join);
5408 if (join != NULL && !ast_context()->IsEffect()) {
5409 return ast_context()->ReturnValue(Pop());
5415 HOptimizedGraphBuilder::GlobalPropertyAccess
5416 HOptimizedGraphBuilder::LookupGlobalProperty(Variable* var, LookupIterator* it,
5417 PropertyAccessType access_type) {
5418 if (var->is_this() || !current_info()->has_global_object()) {
5422 switch (it->state()) {
5423 case LookupIterator::ACCESSOR:
5424 case LookupIterator::ACCESS_CHECK:
5425 case LookupIterator::INTERCEPTOR:
5426 case LookupIterator::INTEGER_INDEXED_EXOTIC:
5427 case LookupIterator::NOT_FOUND:
5429 case LookupIterator::DATA:
5430 if (access_type == STORE && it->IsReadOnly()) return kUseGeneric;
5432 case LookupIterator::JSPROXY:
5433 case LookupIterator::TRANSITION:
5441 HValue* HOptimizedGraphBuilder::BuildContextChainWalk(Variable* var) {
5442 DCHECK(var->IsContextSlot());
5443 HValue* context = environment()->context();
5444 int length = scope()->ContextChainLength(var->scope());
5445 while (length-- > 0) {
5446 context = Add<HLoadNamedField>(
5448 HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX));
5454 void HOptimizedGraphBuilder::VisitVariableProxy(VariableProxy* expr) {
5455 DCHECK(!HasStackOverflow());
5456 DCHECK(current_block() != NULL);
5457 DCHECK(current_block()->HasPredecessor());
5458 Variable* variable = expr->var();
5459 switch (variable->location()) {
5460 case VariableLocation::GLOBAL:
5461 case VariableLocation::UNALLOCATED: {
5462 if (IsLexicalVariableMode(variable->mode())) {
5463 // TODO(rossberg): should this be an DCHECK?
5464 return Bailout(kReferenceToGlobalLexicalVariable);
5466 // Handle known global constants like 'undefined' specially to avoid a
5467 // load from a global cell for them.
5468 Handle<Object> constant_value =
5469 isolate()->factory()->GlobalConstantFor(variable->name());
5470 if (!constant_value.is_null()) {
5471 HConstant* instr = New<HConstant>(constant_value);
5472 return ast_context()->ReturnInstruction(instr, expr->id());
5475 Handle<GlobalObject> global(current_info()->global_object());
5477 // Lookup in script contexts.
5479 Handle<ScriptContextTable> script_contexts(
5480 global->native_context()->script_context_table());
5481 ScriptContextTable::LookupResult lookup;
5482 if (ScriptContextTable::Lookup(script_contexts, variable->name(),
5484 Handle<Context> script_context = ScriptContextTable::GetContext(
5485 script_contexts, lookup.context_index);
5486 Handle<Object> current_value =
5487 FixedArray::get(script_context, lookup.slot_index);
5489 // If the values is not the hole, it will stay initialized,
5490 // so no need to generate a check.
5491 if (*current_value == *isolate()->factory()->the_hole_value()) {
5492 return Bailout(kReferenceToUninitializedVariable);
5494 HInstruction* result = New<HLoadNamedField>(
5495 Add<HConstant>(script_context), nullptr,
5496 HObjectAccess::ForContextSlot(lookup.slot_index));
5497 return ast_context()->ReturnInstruction(result, expr->id());
5501 LookupIterator it(global, variable->name(), LookupIterator::OWN);
5502 GlobalPropertyAccess type = LookupGlobalProperty(variable, &it, LOAD);
5504 if (type == kUseCell) {
5505 Handle<PropertyCell> cell = it.GetPropertyCell();
5506 top_info()->dependencies()->AssumePropertyCell(cell);
5507 auto cell_type = it.property_details().cell_type();
5508 if (cell_type == PropertyCellType::kConstant ||
5509 cell_type == PropertyCellType::kUndefined) {
5510 Handle<Object> constant_object(cell->value(), isolate());
5511 if (constant_object->IsConsString()) {
5513 String::Flatten(Handle<String>::cast(constant_object));
5515 HConstant* constant = New<HConstant>(constant_object);
5516 return ast_context()->ReturnInstruction(constant, expr->id());
5518 auto access = HObjectAccess::ForPropertyCellValue();
5519 UniqueSet<Map>* field_maps = nullptr;
5520 if (cell_type == PropertyCellType::kConstantType) {
5521 switch (cell->GetConstantType()) {
5522 case PropertyCellConstantType::kSmi:
5523 access = access.WithRepresentation(Representation::Smi());
5525 case PropertyCellConstantType::kStableMap: {
5526 // Check that the map really is stable. The heap object could
5527 // have mutated without the cell updating state. In that case,
5528 // make no promises about the loaded value except that it's a
5531 access.WithRepresentation(Representation::HeapObject());
5532 Handle<Map> map(HeapObject::cast(cell->value())->map());
5533 if (map->is_stable()) {
5534 field_maps = new (zone())
5535 UniqueSet<Map>(Unique<Map>::CreateImmovable(map), zone());
5541 HConstant* cell_constant = Add<HConstant>(cell);
5542 HLoadNamedField* instr;
5543 if (field_maps == nullptr) {
5544 instr = New<HLoadNamedField>(cell_constant, nullptr, access);
5546 instr = New<HLoadNamedField>(cell_constant, nullptr, access,
5547 field_maps, HType::HeapObject());
5549 instr->ClearDependsOnFlag(kInobjectFields);
5550 instr->SetDependsOnFlag(kGlobalVars);
5551 return ast_context()->ReturnInstruction(instr, expr->id());
5553 } else if (variable->IsGlobalSlot()) {
5554 DCHECK(variable->index() > 0);
5555 DCHECK(variable->IsStaticGlobalObjectProperty());
5556 int slot_index = variable->index();
5557 int depth = scope()->ContextChainLength(variable->scope());
5559 HLoadGlobalViaContext* instr =
5560 New<HLoadGlobalViaContext>(depth, slot_index);
5561 return ast_context()->ReturnInstruction(instr, expr->id());
5564 HValue* global_object = Add<HLoadNamedField>(
5566 HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
5567 HLoadGlobalGeneric* instr = New<HLoadGlobalGeneric>(
5568 global_object, variable->name(), ast_context()->typeof_mode());
5569 instr->SetVectorAndSlot(handle(current_feedback_vector(), isolate()),
5570 expr->VariableFeedbackSlot());
5571 return ast_context()->ReturnInstruction(instr, expr->id());
5575 case VariableLocation::PARAMETER:
5576 case VariableLocation::LOCAL: {
5577 HValue* value = LookupAndMakeLive(variable);
5578 if (value == graph()->GetConstantHole()) {
5579 DCHECK(IsDeclaredVariableMode(variable->mode()) &&
5580 variable->mode() != VAR);
5581 return Bailout(kReferenceToUninitializedVariable);
5583 return ast_context()->ReturnValue(value);
5586 case VariableLocation::CONTEXT: {
5587 HValue* context = BuildContextChainWalk(variable);
5588 HLoadContextSlot::Mode mode;
5589 switch (variable->mode()) {
5592 mode = HLoadContextSlot::kCheckDeoptimize;
5595 mode = HLoadContextSlot::kCheckReturnUndefined;
5598 mode = HLoadContextSlot::kNoCheck;
5601 HLoadContextSlot* instr =
5602 new(zone()) HLoadContextSlot(context, variable->index(), mode);
5603 return ast_context()->ReturnInstruction(instr, expr->id());
5606 case VariableLocation::LOOKUP:
5607 return Bailout(kReferenceToAVariableWhichRequiresDynamicLookup);
5612 void HOptimizedGraphBuilder::VisitLiteral(Literal* expr) {
5613 DCHECK(!HasStackOverflow());
5614 DCHECK(current_block() != NULL);
5615 DCHECK(current_block()->HasPredecessor());
5616 HConstant* instr = New<HConstant>(expr->value());
5617 return ast_context()->ReturnInstruction(instr, expr->id());
5621 void HOptimizedGraphBuilder::VisitRegExpLiteral(RegExpLiteral* expr) {
5622 DCHECK(!HasStackOverflow());
5623 DCHECK(current_block() != NULL);
5624 DCHECK(current_block()->HasPredecessor());
5625 Handle<JSFunction> closure = function_state()->compilation_info()->closure();
5626 Handle<FixedArray> literals(closure->literals());
5627 HRegExpLiteral* instr = New<HRegExpLiteral>(literals,
5630 expr->literal_index());
5631 return ast_context()->ReturnInstruction(instr, expr->id());
5635 static bool CanInlinePropertyAccess(Handle<Map> map) {
5636 if (map->instance_type() == HEAP_NUMBER_TYPE) return true;
5637 if (map->instance_type() < FIRST_NONSTRING_TYPE) return true;
5638 return map->IsJSObjectMap() && !map->is_dictionary_map() &&
5639 !map->has_named_interceptor() &&
5640 // TODO(verwaest): Whitelist contexts to which we have access.
5641 !map->is_access_check_needed();
5645 // Determines whether the given array or object literal boilerplate satisfies
5646 // all limits to be considered for fast deep-copying and computes the total
5647 // size of all objects that are part of the graph.
5648 static bool IsFastLiteral(Handle<JSObject> boilerplate,
5650 int* max_properties) {
5651 if (boilerplate->map()->is_deprecated() &&
5652 !JSObject::TryMigrateInstance(boilerplate)) {
5656 DCHECK(max_depth >= 0 && *max_properties >= 0);
5657 if (max_depth == 0) return false;
5659 Isolate* isolate = boilerplate->GetIsolate();
5660 Handle<FixedArrayBase> elements(boilerplate->elements());
5661 if (elements->length() > 0 &&
5662 elements->map() != isolate->heap()->fixed_cow_array_map()) {
5663 if (boilerplate->HasFastSmiOrObjectElements()) {
5664 Handle<FixedArray> fast_elements = Handle<FixedArray>::cast(elements);
5665 int length = elements->length();
5666 for (int i = 0; i < length; i++) {
5667 if ((*max_properties)-- == 0) return false;
5668 Handle<Object> value(fast_elements->get(i), isolate);
5669 if (value->IsJSObject()) {
5670 Handle<JSObject> value_object = Handle<JSObject>::cast(value);
5671 if (!IsFastLiteral(value_object,
5678 } else if (!boilerplate->HasFastDoubleElements()) {
5683 Handle<FixedArray> properties(boilerplate->properties());
5684 if (properties->length() > 0) {
5687 Handle<DescriptorArray> descriptors(
5688 boilerplate->map()->instance_descriptors());
5689 int limit = boilerplate->map()->NumberOfOwnDescriptors();
5690 for (int i = 0; i < limit; i++) {
5691 PropertyDetails details = descriptors->GetDetails(i);
5692 if (details.type() != DATA) continue;
5693 if ((*max_properties)-- == 0) return false;
5694 FieldIndex field_index = FieldIndex::ForDescriptor(boilerplate->map(), i);
5695 if (boilerplate->IsUnboxedDoubleField(field_index)) continue;
5696 Handle<Object> value(boilerplate->RawFastPropertyAt(field_index),
5698 if (value->IsJSObject()) {
5699 Handle<JSObject> value_object = Handle<JSObject>::cast(value);
5700 if (!IsFastLiteral(value_object,
5712 void HOptimizedGraphBuilder::VisitObjectLiteral(ObjectLiteral* expr) {
5713 DCHECK(!HasStackOverflow());
5714 DCHECK(current_block() != NULL);
5715 DCHECK(current_block()->HasPredecessor());
5717 Handle<JSFunction> closure = function_state()->compilation_info()->closure();
5718 HInstruction* literal;
5720 // Check whether to use fast or slow deep-copying for boilerplate.
5721 int max_properties = kMaxFastLiteralProperties;
5722 Handle<Object> literals_cell(closure->literals()->get(expr->literal_index()),
5724 Handle<AllocationSite> site;
5725 Handle<JSObject> boilerplate;
5726 if (!literals_cell->IsUndefined()) {
5727 // Retrieve the boilerplate
5728 site = Handle<AllocationSite>::cast(literals_cell);
5729 boilerplate = Handle<JSObject>(JSObject::cast(site->transition_info()),
5733 if (!boilerplate.is_null() &&
5734 IsFastLiteral(boilerplate, kMaxFastLiteralDepth, &max_properties)) {
5735 AllocationSiteUsageContext site_context(isolate(), site, false);
5736 site_context.EnterNewScope();
5737 literal = BuildFastLiteral(boilerplate, &site_context);
5738 site_context.ExitScope(site, boilerplate);
5740 NoObservableSideEffectsScope no_effects(this);
5741 Handle<FixedArray> closure_literals(closure->literals(), isolate());
5742 Handle<FixedArray> constant_properties = expr->constant_properties();
5743 int literal_index = expr->literal_index();
5744 int flags = expr->ComputeFlags(true);
5746 Add<HPushArguments>(Add<HConstant>(closure_literals),
5747 Add<HConstant>(literal_index),
5748 Add<HConstant>(constant_properties),
5749 Add<HConstant>(flags));
5751 Runtime::FunctionId function_id = Runtime::kCreateObjectLiteral;
5752 literal = Add<HCallRuntime>(isolate()->factory()->empty_string(),
5753 Runtime::FunctionForId(function_id),
5757 // The object is expected in the bailout environment during computation
5758 // of the property values and is the value of the entire expression.
5760 int store_slot_index = 0;
5761 for (int i = 0; i < expr->properties()->length(); i++) {
5762 ObjectLiteral::Property* property = expr->properties()->at(i);
5763 if (property->is_computed_name()) return Bailout(kComputedPropertyName);
5764 if (property->IsCompileTimeValue()) continue;
5766 Literal* key = property->key()->AsLiteral();
5767 Expression* value = property->value();
5769 switch (property->kind()) {
5770 case ObjectLiteral::Property::MATERIALIZED_LITERAL:
5771 DCHECK(!CompileTimeValue::IsCompileTimeValue(value));
5773 case ObjectLiteral::Property::COMPUTED:
5774 // It is safe to use [[Put]] here because the boilerplate already
5775 // contains computed properties with an uninitialized value.
5776 if (key->value()->IsInternalizedString()) {
5777 if (property->emit_store()) {
5778 CHECK_ALIVE(VisitForValue(value));
5779 HValue* value = Pop();
5781 Handle<Map> map = property->GetReceiverType();
5782 Handle<String> name = key->AsPropertyName();
5784 FeedbackVectorICSlot slot = expr->GetNthSlot(store_slot_index++);
5785 if (map.is_null()) {
5786 // If we don't know the monomorphic type, do a generic store.
5787 CHECK_ALIVE(store = BuildNamedGeneric(STORE, NULL, slot, literal,
5790 PropertyAccessInfo info(this, STORE, map, name);
5791 if (info.CanAccessMonomorphic()) {
5792 HValue* checked_literal = Add<HCheckMaps>(literal, map);
5793 DCHECK(!info.IsAccessorConstant());
5794 store = BuildMonomorphicAccess(
5795 &info, literal, checked_literal, value,
5796 BailoutId::None(), BailoutId::None());
5798 CHECK_ALIVE(store = BuildNamedGeneric(STORE, NULL, slot,
5799 literal, name, value));
5802 if (store->IsInstruction()) {
5803 AddInstruction(HInstruction::cast(store));
5805 DCHECK(store->HasObservableSideEffects());
5806 Add<HSimulate>(key->id(), REMOVABLE_SIMULATE);
5808 // Add [[HomeObject]] to function literals.
5809 if (FunctionLiteral::NeedsHomeObject(property->value())) {
5810 Handle<Symbol> sym = isolate()->factory()->home_object_symbol();
5811 HInstruction* store_home = BuildNamedGeneric(
5812 STORE, NULL, expr->GetNthSlot(store_slot_index++), value, sym,
5814 AddInstruction(store_home);
5815 DCHECK(store_home->HasObservableSideEffects());
5816 Add<HSimulate>(property->value()->id(), REMOVABLE_SIMULATE);
5819 CHECK_ALIVE(VisitForEffect(value));
5824 case ObjectLiteral::Property::PROTOTYPE:
5825 case ObjectLiteral::Property::SETTER:
5826 case ObjectLiteral::Property::GETTER:
5827 return Bailout(kObjectLiteralWithComplexProperty);
5828 default: UNREACHABLE();
5832 // Crankshaft may not consume all the slots because it doesn't emit accessors.
5833 DCHECK(!FLAG_vector_stores || store_slot_index <= expr->slot_count());
5835 if (expr->has_function()) {
5836 // Return the result of the transformation to fast properties
5837 // instead of the original since this operation changes the map
5838 // of the object. This makes sure that the original object won't
5839 // be used by other optimized code before it is transformed
5840 // (e.g. because of code motion).
5841 HToFastProperties* result = Add<HToFastProperties>(Pop());
5842 return ast_context()->ReturnValue(result);
5844 return ast_context()->ReturnValue(Pop());
5849 void HOptimizedGraphBuilder::VisitArrayLiteral(ArrayLiteral* expr) {
5850 DCHECK(!HasStackOverflow());
5851 DCHECK(current_block() != NULL);
5852 DCHECK(current_block()->HasPredecessor());
5853 expr->BuildConstantElements(isolate());
5854 ZoneList<Expression*>* subexprs = expr->values();
5855 int length = subexprs->length();
5856 HInstruction* literal;
5858 Handle<AllocationSite> site;
5859 Handle<FixedArray> literals(environment()->closure()->literals(), isolate());
5860 bool uninitialized = false;
5861 Handle<Object> literals_cell(literals->get(expr->literal_index()),
5863 Handle<JSObject> boilerplate_object;
5864 if (literals_cell->IsUndefined()) {
5865 uninitialized = true;
5866 Handle<Object> raw_boilerplate;
5867 ASSIGN_RETURN_ON_EXCEPTION_VALUE(
5868 isolate(), raw_boilerplate,
5869 Runtime::CreateArrayLiteralBoilerplate(
5870 isolate(), literals, expr->constant_elements(),
5871 is_strong(function_language_mode())),
5872 Bailout(kArrayBoilerplateCreationFailed));
5874 boilerplate_object = Handle<JSObject>::cast(raw_boilerplate);
5875 AllocationSiteCreationContext creation_context(isolate());
5876 site = creation_context.EnterNewScope();
5877 if (JSObject::DeepWalk(boilerplate_object, &creation_context).is_null()) {
5878 return Bailout(kArrayBoilerplateCreationFailed);
5880 creation_context.ExitScope(site, boilerplate_object);
5881 literals->set(expr->literal_index(), *site);
5883 if (boilerplate_object->elements()->map() ==
5884 isolate()->heap()->fixed_cow_array_map()) {
5885 isolate()->counters()->cow_arrays_created_runtime()->Increment();
5888 DCHECK(literals_cell->IsAllocationSite());
5889 site = Handle<AllocationSite>::cast(literals_cell);
5890 boilerplate_object = Handle<JSObject>(
5891 JSObject::cast(site->transition_info()), isolate());
5894 DCHECK(!boilerplate_object.is_null());
5895 DCHECK(site->SitePointsToLiteral());
5897 ElementsKind boilerplate_elements_kind =
5898 boilerplate_object->GetElementsKind();
5900 // Check whether to use fast or slow deep-copying for boilerplate.
5901 int max_properties = kMaxFastLiteralProperties;
5902 if (IsFastLiteral(boilerplate_object,
5903 kMaxFastLiteralDepth,
5905 AllocationSiteUsageContext site_context(isolate(), site, false);
5906 site_context.EnterNewScope();
5907 literal = BuildFastLiteral(boilerplate_object, &site_context);
5908 site_context.ExitScope(site, boilerplate_object);
5910 NoObservableSideEffectsScope no_effects(this);
5911 // Boilerplate already exists and constant elements are never accessed,
5912 // pass an empty fixed array to the runtime function instead.
5913 Handle<FixedArray> constants = isolate()->factory()->empty_fixed_array();
5914 int literal_index = expr->literal_index();
5915 int flags = expr->ComputeFlags(true);
5917 Add<HPushArguments>(Add<HConstant>(literals),
5918 Add<HConstant>(literal_index),
5919 Add<HConstant>(constants),
5920 Add<HConstant>(flags));
5922 Runtime::FunctionId function_id = Runtime::kCreateArrayLiteral;
5923 literal = Add<HCallRuntime>(isolate()->factory()->empty_string(),
5924 Runtime::FunctionForId(function_id),
5927 // Register to deopt if the boilerplate ElementsKind changes.
5928 top_info()->dependencies()->AssumeTransitionStable(site);
5931 // The array is expected in the bailout environment during computation
5932 // of the property values and is the value of the entire expression.
5934 // The literal index is on the stack, too.
5935 Push(Add<HConstant>(expr->literal_index()));
5937 HInstruction* elements = NULL;
5939 for (int i = 0; i < length; i++) {
5940 Expression* subexpr = subexprs->at(i);
5941 if (subexpr->IsSpread()) {
5942 return Bailout(kSpread);
5945 // If the subexpression is a literal or a simple materialized literal it
5946 // is already set in the cloned array.
5947 if (CompileTimeValue::IsCompileTimeValue(subexpr)) continue;
5949 CHECK_ALIVE(VisitForValue(subexpr));
5950 HValue* value = Pop();
5951 if (!Smi::IsValid(i)) return Bailout(kNonSmiKeyInArrayLiteral);
5953 elements = AddLoadElements(literal);
5955 HValue* key = Add<HConstant>(i);
5957 switch (boilerplate_elements_kind) {
5958 case FAST_SMI_ELEMENTS:
5959 case FAST_HOLEY_SMI_ELEMENTS:
5961 case FAST_HOLEY_ELEMENTS:
5962 case FAST_DOUBLE_ELEMENTS:
5963 case FAST_HOLEY_DOUBLE_ELEMENTS: {
5964 HStoreKeyed* instr = Add<HStoreKeyed>(elements, key, value,
5965 boilerplate_elements_kind);
5966 instr->SetUninitialized(uninitialized);
5974 Add<HSimulate>(expr->GetIdForElement(i));
5977 Drop(1); // array literal index
5978 return ast_context()->ReturnValue(Pop());
5982 HCheckMaps* HOptimizedGraphBuilder::AddCheckMap(HValue* object,
5984 BuildCheckHeapObject(object);
5985 return Add<HCheckMaps>(object, map);
5989 HInstruction* HOptimizedGraphBuilder::BuildLoadNamedField(
5990 PropertyAccessInfo* info,
5991 HValue* checked_object) {
5992 // See if this is a load for an immutable property
5993 if (checked_object->ActualValue()->IsConstant()) {
5994 Handle<Object> object(
5995 HConstant::cast(checked_object->ActualValue())->handle(isolate()));
5997 if (object->IsJSObject()) {
5998 LookupIterator it(object, info->name(),
5999 LookupIterator::OWN_SKIP_INTERCEPTOR);
6000 Handle<Object> value = JSReceiver::GetDataProperty(&it);
6001 if (it.IsFound() && it.IsReadOnly() && !it.IsConfigurable()) {
6002 return New<HConstant>(value);
6007 HObjectAccess access = info->access();
6008 if (access.representation().IsDouble() &&
6009 (!FLAG_unbox_double_fields || !access.IsInobject())) {
6010 // Load the heap number.
6011 checked_object = Add<HLoadNamedField>(
6012 checked_object, nullptr,
6013 access.WithRepresentation(Representation::Tagged()));
6014 // Load the double value from it.
6015 access = HObjectAccess::ForHeapNumberValue();
6018 SmallMapList* map_list = info->field_maps();
6019 if (map_list->length() == 0) {
6020 return New<HLoadNamedField>(checked_object, checked_object, access);
6023 UniqueSet<Map>* maps = new(zone()) UniqueSet<Map>(map_list->length(), zone());
6024 for (int i = 0; i < map_list->length(); ++i) {
6025 maps->Add(Unique<Map>::CreateImmovable(map_list->at(i)), zone());
6027 return New<HLoadNamedField>(
6028 checked_object, checked_object, access, maps, info->field_type());
6032 HInstruction* HOptimizedGraphBuilder::BuildStoreNamedField(
6033 PropertyAccessInfo* info,
6034 HValue* checked_object,
6036 bool transition_to_field = info->IsTransition();
6037 // TODO(verwaest): Move this logic into PropertyAccessInfo.
6038 HObjectAccess field_access = info->access();
6040 HStoreNamedField *instr;
6041 if (field_access.representation().IsDouble() &&
6042 (!FLAG_unbox_double_fields || !field_access.IsInobject())) {
6043 HObjectAccess heap_number_access =
6044 field_access.WithRepresentation(Representation::Tagged());
6045 if (transition_to_field) {
6046 // The store requires a mutable HeapNumber to be allocated.
6047 NoObservableSideEffectsScope no_side_effects(this);
6048 HInstruction* heap_number_size = Add<HConstant>(HeapNumber::kSize);
6050 // TODO(hpayer): Allocation site pretenuring support.
6051 HInstruction* heap_number = Add<HAllocate>(heap_number_size,
6052 HType::HeapObject(),
6054 MUTABLE_HEAP_NUMBER_TYPE);
6055 AddStoreMapConstant(
6056 heap_number, isolate()->factory()->mutable_heap_number_map());
6057 Add<HStoreNamedField>(heap_number, HObjectAccess::ForHeapNumberValue(),
6059 instr = New<HStoreNamedField>(checked_object->ActualValue(),
6063 // Already holds a HeapNumber; load the box and write its value field.
6064 HInstruction* heap_number =
6065 Add<HLoadNamedField>(checked_object, nullptr, heap_number_access);
6066 instr = New<HStoreNamedField>(heap_number,
6067 HObjectAccess::ForHeapNumberValue(),
6068 value, STORE_TO_INITIALIZED_ENTRY);
6071 if (field_access.representation().IsHeapObject()) {
6072 BuildCheckHeapObject(value);
6075 if (!info->field_maps()->is_empty()) {
6076 DCHECK(field_access.representation().IsHeapObject());
6077 value = Add<HCheckMaps>(value, info->field_maps());
6080 // This is a normal store.
6081 instr = New<HStoreNamedField>(
6082 checked_object->ActualValue(), field_access, value,
6083 transition_to_field ? INITIALIZING_STORE : STORE_TO_INITIALIZED_ENTRY);
6086 if (transition_to_field) {
6087 Handle<Map> transition(info->transition());
6088 DCHECK(!transition->is_deprecated());
6089 instr->SetTransition(Add<HConstant>(transition));
6095 bool HOptimizedGraphBuilder::PropertyAccessInfo::IsCompatible(
6096 PropertyAccessInfo* info) {
6097 if (!CanInlinePropertyAccess(map_)) return false;
6099 // Currently only handle Type::Number as a polymorphic case.
6100 // TODO(verwaest): Support monomorphic handling of numbers with a HCheckNumber
6102 if (IsNumberType()) return false;
6104 // Values are only compatible for monomorphic load if they all behave the same
6105 // regarding value wrappers.
6106 if (IsValueWrapped() != info->IsValueWrapped()) return false;
6108 if (!LookupDescriptor()) return false;
6111 return (!info->IsFound() || info->has_holder()) &&
6112 map()->prototype() == info->map()->prototype();
6115 // Mismatch if the other access info found the property in the prototype
6117 if (info->has_holder()) return false;
6119 if (IsAccessorConstant()) {
6120 return accessor_.is_identical_to(info->accessor_) &&
6121 api_holder_.is_identical_to(info->api_holder_);
6124 if (IsDataConstant()) {
6125 return constant_.is_identical_to(info->constant_);
6129 if (!info->IsData()) return false;
6131 Representation r = access_.representation();
6133 if (!info->access_.representation().IsCompatibleForLoad(r)) return false;
6135 if (!info->access_.representation().IsCompatibleForStore(r)) return false;
6137 if (info->access_.offset() != access_.offset()) return false;
6138 if (info->access_.IsInobject() != access_.IsInobject()) return false;
6140 if (field_maps_.is_empty()) {
6141 info->field_maps_.Clear();
6142 } else if (!info->field_maps_.is_empty()) {
6143 for (int i = 0; i < field_maps_.length(); ++i) {
6144 info->field_maps_.AddMapIfMissing(field_maps_.at(i), info->zone());
6146 info->field_maps_.Sort();
6149 // We can only merge stores that agree on their field maps. The comparison
6150 // below is safe, since we keep the field maps sorted.
6151 if (field_maps_.length() != info->field_maps_.length()) return false;
6152 for (int i = 0; i < field_maps_.length(); ++i) {
6153 if (!field_maps_.at(i).is_identical_to(info->field_maps_.at(i))) {
6158 info->GeneralizeRepresentation(r);
6159 info->field_type_ = info->field_type_.Combine(field_type_);
6164 bool HOptimizedGraphBuilder::PropertyAccessInfo::LookupDescriptor() {
6165 if (!map_->IsJSObjectMap()) return true;
6166 LookupDescriptor(*map_, *name_);
6167 return LoadResult(map_);
6171 bool HOptimizedGraphBuilder::PropertyAccessInfo::LoadResult(Handle<Map> map) {
6172 if (!IsLoad() && IsProperty() && IsReadOnly()) {
6177 // Construct the object field access.
6178 int index = GetLocalFieldIndexFromMap(map);
6179 access_ = HObjectAccess::ForField(map, index, representation(), name_);
6181 // Load field map for heap objects.
6182 return LoadFieldMaps(map);
6183 } else if (IsAccessorConstant()) {
6184 Handle<Object> accessors = GetAccessorsFromMap(map);
6185 if (!accessors->IsAccessorPair()) return false;
6186 Object* raw_accessor =
6187 IsLoad() ? Handle<AccessorPair>::cast(accessors)->getter()
6188 : Handle<AccessorPair>::cast(accessors)->setter();
6189 if (!raw_accessor->IsJSFunction()) return false;
6190 Handle<JSFunction> accessor = handle(JSFunction::cast(raw_accessor));
6191 if (accessor->shared()->IsApiFunction()) {
6192 CallOptimization call_optimization(accessor);
6193 if (call_optimization.is_simple_api_call()) {
6194 CallOptimization::HolderLookup holder_lookup;
6196 call_optimization.LookupHolderOfExpectedType(map_, &holder_lookup);
6199 accessor_ = accessor;
6200 } else if (IsDataConstant()) {
6201 constant_ = GetConstantFromMap(map);
6208 bool HOptimizedGraphBuilder::PropertyAccessInfo::LoadFieldMaps(
6210 // Clear any previously collected field maps/type.
6211 field_maps_.Clear();
6212 field_type_ = HType::Tagged();
6214 // Figure out the field type from the accessor map.
6215 Handle<HeapType> field_type = GetFieldTypeFromMap(map);
6217 // Collect the (stable) maps from the field type.
6218 int num_field_maps = field_type->NumClasses();
6219 if (num_field_maps > 0) {
6220 DCHECK(access_.representation().IsHeapObject());
6221 field_maps_.Reserve(num_field_maps, zone());
6222 HeapType::Iterator<Map> it = field_type->Classes();
6223 while (!it.Done()) {
6224 Handle<Map> field_map = it.Current();
6225 if (!field_map->is_stable()) {
6226 field_maps_.Clear();
6229 field_maps_.Add(field_map, zone());
6234 if (field_maps_.is_empty()) {
6235 // Store is not safe if the field map was cleared.
6236 return IsLoad() || !field_type->Is(HeapType::None());
6240 DCHECK_EQ(num_field_maps, field_maps_.length());
6242 // Determine field HType from field HeapType.
6243 field_type_ = HType::FromType<HeapType>(field_type);
6244 DCHECK(field_type_.IsHeapObject());
6246 // Add dependency on the map that introduced the field.
6247 top_info()->dependencies()->AssumeFieldType(GetFieldOwnerFromMap(map));
6252 bool HOptimizedGraphBuilder::PropertyAccessInfo::LookupInPrototypes() {
6253 Handle<Map> map = this->map();
6255 while (map->prototype()->IsJSObject()) {
6256 holder_ = handle(JSObject::cast(map->prototype()));
6257 if (holder_->map()->is_deprecated()) {
6258 JSObject::TryMigrateInstance(holder_);
6260 map = Handle<Map>(holder_->map());
6261 if (!CanInlinePropertyAccess(map)) {
6265 LookupDescriptor(*map, *name_);
6266 if (IsFound()) return LoadResult(map);
6270 return !map->prototype()->IsJSReceiver();
6274 bool HOptimizedGraphBuilder::PropertyAccessInfo::IsIntegerIndexedExotic() {
6275 InstanceType instance_type = map_->instance_type();
6276 return instance_type == JS_TYPED_ARRAY_TYPE &&
6277 IsSpecialIndex(isolate()->unicode_cache(), *name_);
6281 bool HOptimizedGraphBuilder::PropertyAccessInfo::CanAccessMonomorphic() {
6282 if (!CanInlinePropertyAccess(map_)) return false;
6283 if (IsJSObjectFieldAccessor()) return IsLoad();
6284 if (IsJSArrayBufferViewFieldAccessor()) return IsLoad();
6285 if (map_->function_with_prototype() && !map_->has_non_instance_prototype() &&
6286 name_.is_identical_to(isolate()->factory()->prototype_string())) {
6289 if (!LookupDescriptor()) return false;
6290 if (IsFound()) return IsLoad() || !IsReadOnly();
6291 if (IsIntegerIndexedExotic()) return false;
6292 if (!LookupInPrototypes()) return false;
6293 if (IsLoad()) return true;
6295 if (IsAccessorConstant()) return true;
6296 LookupTransition(*map_, *name_, NONE);
6297 if (IsTransitionToData() && map_->unused_property_fields() > 0) {
6298 // Construct the object field access.
6299 int descriptor = transition()->LastAdded();
6301 transition()->instance_descriptors()->GetFieldIndex(descriptor) -
6302 map_->inobject_properties();
6303 PropertyDetails details =
6304 transition()->instance_descriptors()->GetDetails(descriptor);
6305 Representation representation = details.representation();
6306 access_ = HObjectAccess::ForField(map_, index, representation, name_);
6308 // Load field map for heap objects.
6309 return LoadFieldMaps(transition());
6315 bool HOptimizedGraphBuilder::PropertyAccessInfo::CanAccessAsMonomorphic(
6316 SmallMapList* maps) {
6317 DCHECK(map_.is_identical_to(maps->first()));
6318 if (!CanAccessMonomorphic()) return false;
6319 STATIC_ASSERT(kMaxLoadPolymorphism == kMaxStorePolymorphism);
6320 if (maps->length() > kMaxLoadPolymorphism) return false;
6321 HObjectAccess access = HObjectAccess::ForMap(); // bogus default
6322 if (GetJSObjectFieldAccess(&access)) {
6323 for (int i = 1; i < maps->length(); ++i) {
6324 PropertyAccessInfo test_info(builder_, access_type_, maps->at(i), name_);
6325 HObjectAccess test_access = HObjectAccess::ForMap(); // bogus default
6326 if (!test_info.GetJSObjectFieldAccess(&test_access)) return false;
6327 if (!access.Equals(test_access)) return false;
6331 if (GetJSArrayBufferViewFieldAccess(&access)) {
6332 for (int i = 1; i < maps->length(); ++i) {
6333 PropertyAccessInfo test_info(builder_, access_type_, maps->at(i), name_);
6334 HObjectAccess test_access = HObjectAccess::ForMap(); // bogus default
6335 if (!test_info.GetJSArrayBufferViewFieldAccess(&test_access)) {
6338 if (!access.Equals(test_access)) return false;
6343 // Currently only handle numbers as a polymorphic case.
6344 // TODO(verwaest): Support monomorphic handling of numbers with a HCheckNumber
6346 if (IsNumberType()) return false;
6348 // Multiple maps cannot transition to the same target map.
6349 DCHECK(!IsLoad() || !IsTransition());
6350 if (IsTransition() && maps->length() > 1) return false;
6352 for (int i = 1; i < maps->length(); ++i) {
6353 PropertyAccessInfo test_info(builder_, access_type_, maps->at(i), name_);
6354 if (!test_info.IsCompatible(this)) return false;
6361 Handle<Map> HOptimizedGraphBuilder::PropertyAccessInfo::map() {
6362 JSFunction* ctor = IC::GetRootConstructor(
6363 *map_, current_info()->closure()->context()->native_context());
6364 if (ctor != NULL) return handle(ctor->initial_map());
6369 static bool NeedsWrapping(Handle<Map> map, Handle<JSFunction> target) {
6370 return !map->IsJSObjectMap() &&
6371 is_sloppy(target->shared()->language_mode()) &&
6372 !target->shared()->native();
6376 bool HOptimizedGraphBuilder::PropertyAccessInfo::NeedsWrappingFor(
6377 Handle<JSFunction> target) const {
6378 return NeedsWrapping(map_, target);
6382 HValue* HOptimizedGraphBuilder::BuildMonomorphicAccess(
6383 PropertyAccessInfo* info, HValue* object, HValue* checked_object,
6384 HValue* value, BailoutId ast_id, BailoutId return_id,
6385 bool can_inline_accessor) {
6386 HObjectAccess access = HObjectAccess::ForMap(); // bogus default
6387 if (info->GetJSObjectFieldAccess(&access)) {
6388 DCHECK(info->IsLoad());
6389 return New<HLoadNamedField>(object, checked_object, access);
6392 if (info->GetJSArrayBufferViewFieldAccess(&access)) {
6393 DCHECK(info->IsLoad());
6394 checked_object = Add<HCheckArrayBufferNotNeutered>(checked_object);
6395 return New<HLoadNamedField>(object, checked_object, access);
6398 if (info->name().is_identical_to(isolate()->factory()->prototype_string()) &&
6399 info->map()->function_with_prototype()) {
6400 DCHECK(!info->map()->has_non_instance_prototype());
6401 return New<HLoadFunctionPrototype>(checked_object);
6404 HValue* checked_holder = checked_object;
6405 if (info->has_holder()) {
6406 Handle<JSObject> prototype(JSObject::cast(info->map()->prototype()));
6407 checked_holder = BuildCheckPrototypeMaps(prototype, info->holder());
6410 if (!info->IsFound()) {
6411 DCHECK(info->IsLoad());
6412 if (is_strong(function_language_mode())) {
6413 return New<HCallRuntime>(
6414 isolate()->factory()->empty_string(),
6415 Runtime::FunctionForId(Runtime::kThrowStrongModeImplicitConversion),
6418 return graph()->GetConstantUndefined();
6422 if (info->IsData()) {
6423 if (info->IsLoad()) {
6424 return BuildLoadNamedField(info, checked_holder);
6426 return BuildStoreNamedField(info, checked_object, value);
6430 if (info->IsTransition()) {
6431 DCHECK(!info->IsLoad());
6432 return BuildStoreNamedField(info, checked_object, value);
6435 if (info->IsAccessorConstant()) {
6436 Push(checked_object);
6437 int argument_count = 1;
6438 if (!info->IsLoad()) {
6443 if (info->NeedsWrappingFor(info->accessor())) {
6444 HValue* function = Add<HConstant>(info->accessor());
6445 PushArgumentsFromEnvironment(argument_count);
6446 return New<HCallFunction>(function, argument_count, WRAP_AND_CALL);
6447 } else if (FLAG_inline_accessors && can_inline_accessor) {
6448 bool success = info->IsLoad()
6449 ? TryInlineGetter(info->accessor(), info->map(), ast_id, return_id)
6451 info->accessor(), info->map(), ast_id, return_id, value);
6452 if (success || HasStackOverflow()) return NULL;
6455 PushArgumentsFromEnvironment(argument_count);
6456 return BuildCallConstantFunction(info->accessor(), argument_count);
6459 DCHECK(info->IsDataConstant());
6460 if (info->IsLoad()) {
6461 return New<HConstant>(info->constant());
6463 return New<HCheckValue>(value, Handle<JSFunction>::cast(info->constant()));
6468 void HOptimizedGraphBuilder::HandlePolymorphicNamedFieldAccess(
6469 PropertyAccessType access_type, Expression* expr, FeedbackVectorICSlot slot,
6470 BailoutId ast_id, BailoutId return_id, HValue* object, HValue* value,
6471 SmallMapList* maps, Handle<String> name) {
6472 // Something did not match; must use a polymorphic load.
6474 HBasicBlock* join = NULL;
6475 HBasicBlock* number_block = NULL;
6476 bool handled_string = false;
6478 bool handle_smi = false;
6479 STATIC_ASSERT(kMaxLoadPolymorphism == kMaxStorePolymorphism);
6481 for (i = 0; i < maps->length() && count < kMaxLoadPolymorphism; ++i) {
6482 PropertyAccessInfo info(this, access_type, maps->at(i), name);
6483 if (info.IsStringType()) {
6484 if (handled_string) continue;
6485 handled_string = true;
6487 if (info.CanAccessMonomorphic()) {
6489 if (info.IsNumberType()) {
6496 if (i < maps->length()) {
6502 HControlInstruction* smi_check = NULL;
6503 handled_string = false;
6505 for (i = 0; i < maps->length() && count < kMaxLoadPolymorphism; ++i) {
6506 PropertyAccessInfo info(this, access_type, maps->at(i), name);
6507 if (info.IsStringType()) {
6508 if (handled_string) continue;
6509 handled_string = true;
6511 if (!info.CanAccessMonomorphic()) continue;
6514 join = graph()->CreateBasicBlock();
6516 HBasicBlock* empty_smi_block = graph()->CreateBasicBlock();
6517 HBasicBlock* not_smi_block = graph()->CreateBasicBlock();
6518 number_block = graph()->CreateBasicBlock();
6519 smi_check = New<HIsSmiAndBranch>(
6520 object, empty_smi_block, not_smi_block);
6521 FinishCurrentBlock(smi_check);
6522 GotoNoSimulate(empty_smi_block, number_block);
6523 set_current_block(not_smi_block);
6525 BuildCheckHeapObject(object);
6529 HBasicBlock* if_true = graph()->CreateBasicBlock();
6530 HBasicBlock* if_false = graph()->CreateBasicBlock();
6531 HUnaryControlInstruction* compare;
6534 if (info.IsNumberType()) {
6535 Handle<Map> heap_number_map = isolate()->factory()->heap_number_map();
6536 compare = New<HCompareMap>(object, heap_number_map, if_true, if_false);
6537 dependency = smi_check;
6538 } else if (info.IsStringType()) {
6539 compare = New<HIsStringAndBranch>(object, if_true, if_false);
6540 dependency = compare;
6542 compare = New<HCompareMap>(object, info.map(), if_true, if_false);
6543 dependency = compare;
6545 FinishCurrentBlock(compare);
6547 if (info.IsNumberType()) {
6548 GotoNoSimulate(if_true, number_block);
6549 if_true = number_block;
6552 set_current_block(if_true);
6555 BuildMonomorphicAccess(&info, object, dependency, value, ast_id,
6556 return_id, FLAG_polymorphic_inlining);
6558 HValue* result = NULL;
6559 switch (access_type) {
6568 if (access == NULL) {
6569 if (HasStackOverflow()) return;
6571 if (access->IsInstruction()) {
6572 HInstruction* instr = HInstruction::cast(access);
6573 if (!instr->IsLinked()) AddInstruction(instr);
6575 if (!ast_context()->IsEffect()) Push(result);
6578 if (current_block() != NULL) Goto(join);
6579 set_current_block(if_false);
6582 // Finish up. Unconditionally deoptimize if we've handled all the maps we
6583 // know about and do not want to handle ones we've never seen. Otherwise
6584 // use a generic IC.
6585 if (count == maps->length() && FLAG_deoptimize_uncommon_cases) {
6586 FinishExitWithHardDeoptimization(
6587 Deoptimizer::kUnknownMapInPolymorphicAccess);
6589 HInstruction* instr =
6590 BuildNamedGeneric(access_type, expr, slot, object, name, value);
6591 AddInstruction(instr);
6592 if (!ast_context()->IsEffect()) Push(access_type == LOAD ? instr : value);
6597 Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6598 if (!ast_context()->IsEffect()) ast_context()->ReturnValue(Pop());
6603 DCHECK(join != NULL);
6604 if (join->HasPredecessor()) {
6605 join->SetJoinId(ast_id);
6606 set_current_block(join);
6607 if (!ast_context()->IsEffect()) ast_context()->ReturnValue(Pop());
6609 set_current_block(NULL);
6614 static bool ComputeReceiverTypes(Expression* expr,
6618 SmallMapList* maps = expr->GetReceiverTypes();
6620 bool monomorphic = expr->IsMonomorphic();
6621 if (maps != NULL && receiver->HasMonomorphicJSObjectType()) {
6622 Map* root_map = receiver->GetMonomorphicJSObjectMap()->FindRootMap();
6623 maps->FilterForPossibleTransitions(root_map);
6624 monomorphic = maps->length() == 1;
6626 return monomorphic && CanInlinePropertyAccess(maps->first());
6630 static bool AreStringTypes(SmallMapList* maps) {
6631 for (int i = 0; i < maps->length(); i++) {
6632 if (maps->at(i)->instance_type() >= FIRST_NONSTRING_TYPE) return false;
6638 void HOptimizedGraphBuilder::BuildStore(Expression* expr, Property* prop,
6639 FeedbackVectorICSlot slot,
6640 BailoutId ast_id, BailoutId return_id,
6641 bool is_uninitialized) {
6642 if (!prop->key()->IsPropertyName()) {
6644 HValue* value = Pop();
6645 HValue* key = Pop();
6646 HValue* object = Pop();
6647 bool has_side_effects = false;
6649 HandleKeyedElementAccess(object, key, value, expr, slot, ast_id,
6650 return_id, STORE, &has_side_effects);
6651 if (has_side_effects) {
6652 if (!ast_context()->IsEffect()) Push(value);
6653 Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6654 if (!ast_context()->IsEffect()) Drop(1);
6656 if (result == NULL) return;
6657 return ast_context()->ReturnValue(value);
6661 HValue* value = Pop();
6662 HValue* object = Pop();
6664 Literal* key = prop->key()->AsLiteral();
6665 Handle<String> name = Handle<String>::cast(key->value());
6666 DCHECK(!name.is_null());
6668 HValue* access = BuildNamedAccess(STORE, ast_id, return_id, expr, slot,
6669 object, name, value, is_uninitialized);
6670 if (access == NULL) return;
6672 if (!ast_context()->IsEffect()) Push(value);
6673 if (access->IsInstruction()) AddInstruction(HInstruction::cast(access));
6674 if (access->HasObservableSideEffects()) {
6675 Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6677 if (!ast_context()->IsEffect()) Drop(1);
6678 return ast_context()->ReturnValue(value);
6682 void HOptimizedGraphBuilder::HandlePropertyAssignment(Assignment* expr) {
6683 Property* prop = expr->target()->AsProperty();
6684 DCHECK(prop != NULL);
6685 CHECK_ALIVE(VisitForValue(prop->obj()));
6686 if (!prop->key()->IsPropertyName()) {
6687 CHECK_ALIVE(VisitForValue(prop->key()));
6689 CHECK_ALIVE(VisitForValue(expr->value()));
6690 BuildStore(expr, prop, expr->AssignmentSlot(), expr->id(),
6691 expr->AssignmentId(), expr->IsUninitialized());
6695 // Because not every expression has a position and there is not common
6696 // superclass of Assignment and CountOperation, we cannot just pass the
6697 // owning expression instead of position and ast_id separately.
6698 void HOptimizedGraphBuilder::HandleGlobalVariableAssignment(
6699 Variable* var, HValue* value, FeedbackVectorICSlot ic_slot,
6701 Handle<GlobalObject> global(current_info()->global_object());
6703 // Lookup in script contexts.
6705 Handle<ScriptContextTable> script_contexts(
6706 global->native_context()->script_context_table());
6707 ScriptContextTable::LookupResult lookup;
6708 if (ScriptContextTable::Lookup(script_contexts, var->name(), &lookup)) {
6709 if (lookup.mode == CONST) {
6710 return Bailout(kNonInitializerAssignmentToConst);
6712 Handle<Context> script_context =
6713 ScriptContextTable::GetContext(script_contexts, lookup.context_index);
6715 Handle<Object> current_value =
6716 FixedArray::get(script_context, lookup.slot_index);
6718 // If the values is not the hole, it will stay initialized,
6719 // so no need to generate a check.
6720 if (*current_value == *isolate()->factory()->the_hole_value()) {
6721 return Bailout(kReferenceToUninitializedVariable);
6724 HStoreNamedField* instr = Add<HStoreNamedField>(
6725 Add<HConstant>(script_context),
6726 HObjectAccess::ForContextSlot(lookup.slot_index), value);
6728 DCHECK(instr->HasObservableSideEffects());
6729 Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6734 LookupIterator it(global, var->name(), LookupIterator::OWN);
6735 GlobalPropertyAccess type = LookupGlobalProperty(var, &it, STORE);
6736 if (type == kUseCell) {
6737 Handle<PropertyCell> cell = it.GetPropertyCell();
6738 top_info()->dependencies()->AssumePropertyCell(cell);
6739 auto cell_type = it.property_details().cell_type();
6740 if (cell_type == PropertyCellType::kConstant ||
6741 cell_type == PropertyCellType::kUndefined) {
6742 Handle<Object> constant(cell->value(), isolate());
6743 if (value->IsConstant()) {
6744 HConstant* c_value = HConstant::cast(value);
6745 if (!constant.is_identical_to(c_value->handle(isolate()))) {
6746 Add<HDeoptimize>(Deoptimizer::kConstantGlobalVariableAssignment,
6747 Deoptimizer::EAGER);
6750 HValue* c_constant = Add<HConstant>(constant);
6751 IfBuilder builder(this);
6752 if (constant->IsNumber()) {
6753 builder.If<HCompareNumericAndBranch>(value, c_constant, Token::EQ);
6755 builder.If<HCompareObjectEqAndBranch>(value, c_constant);
6759 Add<HDeoptimize>(Deoptimizer::kConstantGlobalVariableAssignment,
6760 Deoptimizer::EAGER);
6764 HConstant* cell_constant = Add<HConstant>(cell);
6765 auto access = HObjectAccess::ForPropertyCellValue();
6766 if (cell_type == PropertyCellType::kConstantType) {
6767 switch (cell->GetConstantType()) {
6768 case PropertyCellConstantType::kSmi:
6769 access = access.WithRepresentation(Representation::Smi());
6771 case PropertyCellConstantType::kStableMap: {
6772 // The map may no longer be stable, deopt if it's ever different from
6773 // what is currently there, which will allow for restablization.
6774 Handle<Map> map(HeapObject::cast(cell->value())->map());
6775 Add<HCheckHeapObject>(value);
6776 value = Add<HCheckMaps>(value, map);
6777 access = access.WithRepresentation(Representation::HeapObject());
6782 HInstruction* instr = Add<HStoreNamedField>(cell_constant, access, value);
6783 instr->ClearChangesFlag(kInobjectFields);
6784 instr->SetChangesFlag(kGlobalVars);
6785 if (instr->HasObservableSideEffects()) {
6786 Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6788 } else if (var->IsGlobalSlot()) {
6789 DCHECK(var->index() > 0);
6790 DCHECK(var->IsStaticGlobalObjectProperty());
6791 int slot_index = var->index();
6792 int depth = scope()->ContextChainLength(var->scope());
6794 HStoreGlobalViaContext* instr = Add<HStoreGlobalViaContext>(
6795 value, depth, slot_index, function_language_mode());
6797 DCHECK(instr->HasObservableSideEffects());
6798 Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6801 HValue* global_object = Add<HLoadNamedField>(
6803 HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
6804 HStoreNamedGeneric* instr =
6805 Add<HStoreNamedGeneric>(global_object, var->name(), value,
6806 function_language_mode(), PREMONOMORPHIC);
6807 if (FLAG_vector_stores) {
6808 Handle<TypeFeedbackVector> vector =
6809 handle(current_feedback_vector(), isolate());
6810 instr->SetVectorAndSlot(vector, ic_slot);
6813 DCHECK(instr->HasObservableSideEffects());
6814 Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6819 void HOptimizedGraphBuilder::HandleCompoundAssignment(Assignment* expr) {
6820 Expression* target = expr->target();
6821 VariableProxy* proxy = target->AsVariableProxy();
6822 Property* prop = target->AsProperty();
6823 DCHECK(proxy == NULL || prop == NULL);
6825 // We have a second position recorded in the FullCodeGenerator to have
6826 // type feedback for the binary operation.
6827 BinaryOperation* operation = expr->binary_operation();
6829 if (proxy != NULL) {
6830 Variable* var = proxy->var();
6831 if (var->mode() == LET) {
6832 return Bailout(kUnsupportedLetCompoundAssignment);
6835 CHECK_ALIVE(VisitForValue(operation));
6837 switch (var->location()) {
6838 case VariableLocation::GLOBAL:
6839 case VariableLocation::UNALLOCATED:
6840 HandleGlobalVariableAssignment(var, Top(), expr->AssignmentSlot(),
6841 expr->AssignmentId());
6844 case VariableLocation::PARAMETER:
6845 case VariableLocation::LOCAL:
6846 if (var->mode() == CONST_LEGACY) {
6847 return Bailout(kUnsupportedConstCompoundAssignment);
6849 if (var->mode() == CONST) {
6850 return Bailout(kNonInitializerAssignmentToConst);
6852 BindIfLive(var, Top());
6855 case VariableLocation::CONTEXT: {
6856 // Bail out if we try to mutate a parameter value in a function
6857 // using the arguments object. We do not (yet) correctly handle the
6858 // arguments property of the function.
6859 if (current_info()->scope()->arguments() != NULL) {
6860 // Parameters will be allocated to context slots. We have no
6861 // direct way to detect that the variable is a parameter so we do
6862 // a linear search of the parameter variables.
6863 int count = current_info()->scope()->num_parameters();
6864 for (int i = 0; i < count; ++i) {
6865 if (var == current_info()->scope()->parameter(i)) {
6866 Bailout(kAssignmentToParameterFunctionUsesArgumentsObject);
6871 HStoreContextSlot::Mode mode;
6873 switch (var->mode()) {
6875 mode = HStoreContextSlot::kCheckDeoptimize;
6878 return Bailout(kNonInitializerAssignmentToConst);
6880 return ast_context()->ReturnValue(Pop());
6882 mode = HStoreContextSlot::kNoCheck;
6885 HValue* context = BuildContextChainWalk(var);
6886 HStoreContextSlot* instr = Add<HStoreContextSlot>(
6887 context, var->index(), mode, Top());
6888 if (instr->HasObservableSideEffects()) {
6889 Add<HSimulate>(expr->AssignmentId(), REMOVABLE_SIMULATE);
6894 case VariableLocation::LOOKUP:
6895 return Bailout(kCompoundAssignmentToLookupSlot);
6897 return ast_context()->ReturnValue(Pop());
6899 } else if (prop != NULL) {
6900 CHECK_ALIVE(VisitForValue(prop->obj()));
6901 HValue* object = Top();
6903 if (!prop->key()->IsPropertyName() || prop->IsStringAccess()) {
6904 CHECK_ALIVE(VisitForValue(prop->key()));
6908 CHECK_ALIVE(PushLoad(prop, object, key));
6910 CHECK_ALIVE(VisitForValue(expr->value()));
6911 HValue* right = Pop();
6912 HValue* left = Pop();
6914 Push(BuildBinaryOperation(operation, left, right, PUSH_BEFORE_SIMULATE));
6916 BuildStore(expr, prop, expr->AssignmentSlot(), expr->id(),
6917 expr->AssignmentId(), expr->IsUninitialized());
6919 return Bailout(kInvalidLhsInCompoundAssignment);
6924 void HOptimizedGraphBuilder::VisitAssignment(Assignment* expr) {
6925 DCHECK(!HasStackOverflow());
6926 DCHECK(current_block() != NULL);
6927 DCHECK(current_block()->HasPredecessor());
6928 VariableProxy* proxy = expr->target()->AsVariableProxy();
6929 Property* prop = expr->target()->AsProperty();
6930 DCHECK(proxy == NULL || prop == NULL);
6932 if (expr->is_compound()) {
6933 HandleCompoundAssignment(expr);
6938 HandlePropertyAssignment(expr);
6939 } else if (proxy != NULL) {
6940 Variable* var = proxy->var();
6942 if (var->mode() == CONST) {
6943 if (expr->op() != Token::INIT_CONST) {
6944 return Bailout(kNonInitializerAssignmentToConst);
6946 } else if (var->mode() == CONST_LEGACY) {
6947 if (expr->op() != Token::INIT_CONST_LEGACY) {
6948 CHECK_ALIVE(VisitForValue(expr->value()));
6949 return ast_context()->ReturnValue(Pop());
6952 if (var->IsStackAllocated()) {
6953 // We insert a use of the old value to detect unsupported uses of const
6954 // variables (e.g. initialization inside a loop).
6955 HValue* old_value = environment()->Lookup(var);
6956 Add<HUseConst>(old_value);
6960 if (proxy->IsArguments()) return Bailout(kAssignmentToArguments);
6962 // Handle the assignment.
6963 switch (var->location()) {
6964 case VariableLocation::GLOBAL:
6965 case VariableLocation::UNALLOCATED:
6966 CHECK_ALIVE(VisitForValue(expr->value()));
6967 HandleGlobalVariableAssignment(var, Top(), expr->AssignmentSlot(),
6968 expr->AssignmentId());
6969 return ast_context()->ReturnValue(Pop());
6971 case VariableLocation::PARAMETER:
6972 case VariableLocation::LOCAL: {
6973 // Perform an initialization check for let declared variables
6975 if (var->mode() == LET && expr->op() == Token::ASSIGN) {
6976 HValue* env_value = environment()->Lookup(var);
6977 if (env_value == graph()->GetConstantHole()) {
6978 return Bailout(kAssignmentToLetVariableBeforeInitialization);
6981 // We do not allow the arguments object to occur in a context where it
6982 // may escape, but assignments to stack-allocated locals are
6984 CHECK_ALIVE(VisitForValue(expr->value(), ARGUMENTS_ALLOWED));
6985 HValue* value = Pop();
6986 BindIfLive(var, value);
6987 return ast_context()->ReturnValue(value);
6990 case VariableLocation::CONTEXT: {
6991 // Bail out if we try to mutate a parameter value in a function using
6992 // the arguments object. We do not (yet) correctly handle the
6993 // arguments property of the function.
6994 if (current_info()->scope()->arguments() != NULL) {
6995 // Parameters will rewrite to context slots. We have no direct way
6996 // to detect that the variable is a parameter.
6997 int count = current_info()->scope()->num_parameters();
6998 for (int i = 0; i < count; ++i) {
6999 if (var == current_info()->scope()->parameter(i)) {
7000 return Bailout(kAssignmentToParameterInArgumentsObject);
7005 CHECK_ALIVE(VisitForValue(expr->value()));
7006 HStoreContextSlot::Mode mode;
7007 if (expr->op() == Token::ASSIGN) {
7008 switch (var->mode()) {
7010 mode = HStoreContextSlot::kCheckDeoptimize;
7013 // This case is checked statically so no need to
7014 // perform checks here
7017 return ast_context()->ReturnValue(Pop());
7019 mode = HStoreContextSlot::kNoCheck;
7021 } else if (expr->op() == Token::INIT_VAR ||
7022 expr->op() == Token::INIT_LET ||
7023 expr->op() == Token::INIT_CONST) {
7024 mode = HStoreContextSlot::kNoCheck;
7026 DCHECK(expr->op() == Token::INIT_CONST_LEGACY);
7028 mode = HStoreContextSlot::kCheckIgnoreAssignment;
7031 HValue* context = BuildContextChainWalk(var);
7032 HStoreContextSlot* instr = Add<HStoreContextSlot>(
7033 context, var->index(), mode, Top());
7034 if (instr->HasObservableSideEffects()) {
7035 Add<HSimulate>(expr->AssignmentId(), REMOVABLE_SIMULATE);
7037 return ast_context()->ReturnValue(Pop());
7040 case VariableLocation::LOOKUP:
7041 return Bailout(kAssignmentToLOOKUPVariable);
7044 return Bailout(kInvalidLeftHandSideInAssignment);
7049 void HOptimizedGraphBuilder::VisitYield(Yield* expr) {
7050 // Generators are not optimized, so we should never get here.
7055 void HOptimizedGraphBuilder::VisitThrow(Throw* expr) {
7056 DCHECK(!HasStackOverflow());
7057 DCHECK(current_block() != NULL);
7058 DCHECK(current_block()->HasPredecessor());
7059 if (!ast_context()->IsEffect()) {
7060 // The parser turns invalid left-hand sides in assignments into throw
7061 // statements, which may not be in effect contexts. We might still try
7062 // to optimize such functions; bail out now if we do.
7063 return Bailout(kInvalidLeftHandSideInAssignment);
7065 CHECK_ALIVE(VisitForValue(expr->exception()));
7067 HValue* value = environment()->Pop();
7068 if (!top_info()->is_tracking_positions()) SetSourcePosition(expr->position());
7069 Add<HPushArguments>(value);
7070 Add<HCallRuntime>(isolate()->factory()->empty_string(),
7071 Runtime::FunctionForId(Runtime::kThrow), 1);
7072 Add<HSimulate>(expr->id());
7074 // If the throw definitely exits the function, we can finish with a dummy
7075 // control flow at this point. This is not the case if the throw is inside
7076 // an inlined function which may be replaced.
7077 if (call_context() == NULL) {
7078 FinishExitCurrentBlock(New<HAbnormalExit>());
7083 HInstruction* HGraphBuilder::AddLoadStringInstanceType(HValue* string) {
7084 if (string->IsConstant()) {
7085 HConstant* c_string = HConstant::cast(string);
7086 if (c_string->HasStringValue()) {
7087 return Add<HConstant>(c_string->StringValue()->map()->instance_type());
7090 return Add<HLoadNamedField>(
7091 Add<HLoadNamedField>(string, nullptr, HObjectAccess::ForMap()), nullptr,
7092 HObjectAccess::ForMapInstanceType());
7096 HInstruction* HGraphBuilder::AddLoadStringLength(HValue* string) {
7097 return AddInstruction(BuildLoadStringLength(string));
7101 HInstruction* HGraphBuilder::BuildLoadStringLength(HValue* string) {
7102 if (string->IsConstant()) {
7103 HConstant* c_string = HConstant::cast(string);
7104 if (c_string->HasStringValue()) {
7105 return New<HConstant>(c_string->StringValue()->length());
7108 return New<HLoadNamedField>(string, nullptr,
7109 HObjectAccess::ForStringLength());
7113 HInstruction* HOptimizedGraphBuilder::BuildNamedGeneric(
7114 PropertyAccessType access_type, Expression* expr, FeedbackVectorICSlot slot,
7115 HValue* object, Handle<Name> name, HValue* value, bool is_uninitialized) {
7116 if (is_uninitialized) {
7118 Deoptimizer::kInsufficientTypeFeedbackForGenericNamedAccess,
7121 if (access_type == LOAD) {
7122 Handle<TypeFeedbackVector> vector =
7123 handle(current_feedback_vector(), isolate());
7125 if (!expr->AsProperty()->key()->IsPropertyName()) {
7126 // It's possible that a keyed load of a constant string was converted
7127 // to a named load. Here, at the last minute, we need to make sure to
7128 // use a generic Keyed Load if we are using the type vector, because
7129 // it has to share information with full code.
7130 HConstant* key = Add<HConstant>(name);
7131 HLoadKeyedGeneric* result = New<HLoadKeyedGeneric>(
7132 object, key, function_language_mode(), PREMONOMORPHIC);
7133 result->SetVectorAndSlot(vector, slot);
7137 HLoadNamedGeneric* result = New<HLoadNamedGeneric>(
7138 object, name, function_language_mode(), PREMONOMORPHIC);
7139 result->SetVectorAndSlot(vector, slot);
7142 if (FLAG_vector_stores &&
7143 current_feedback_vector()->GetKind(slot) == Code::KEYED_STORE_IC) {
7144 // It's possible that a keyed store of a constant string was converted
7145 // to a named store. Here, at the last minute, we need to make sure to
7146 // use a generic Keyed Store if we are using the type vector, because
7147 // it has to share information with full code.
7148 HConstant* key = Add<HConstant>(name);
7149 HStoreKeyedGeneric* result = New<HStoreKeyedGeneric>(
7150 object, key, value, function_language_mode(), PREMONOMORPHIC);
7151 Handle<TypeFeedbackVector> vector =
7152 handle(current_feedback_vector(), isolate());
7153 result->SetVectorAndSlot(vector, slot);
7157 HStoreNamedGeneric* result = New<HStoreNamedGeneric>(
7158 object, name, value, function_language_mode(), PREMONOMORPHIC);
7159 if (FLAG_vector_stores) {
7160 Handle<TypeFeedbackVector> vector =
7161 handle(current_feedback_vector(), isolate());
7162 result->SetVectorAndSlot(vector, slot);
7169 HInstruction* HOptimizedGraphBuilder::BuildKeyedGeneric(
7170 PropertyAccessType access_type, Expression* expr, FeedbackVectorICSlot slot,
7171 HValue* object, HValue* key, HValue* value) {
7172 if (access_type == LOAD) {
7173 InlineCacheState initial_state = expr->AsProperty()->GetInlineCacheState();
7174 HLoadKeyedGeneric* result = New<HLoadKeyedGeneric>(
7175 object, key, function_language_mode(), initial_state);
7176 // HLoadKeyedGeneric with vector ics benefits from being encoded as
7177 // MEGAMORPHIC because the vector/slot combo becomes unnecessary.
7178 if (initial_state != MEGAMORPHIC) {
7179 // We need to pass vector information.
7180 Handle<TypeFeedbackVector> vector =
7181 handle(current_feedback_vector(), isolate());
7182 result->SetVectorAndSlot(vector, slot);
7186 HStoreKeyedGeneric* result = New<HStoreKeyedGeneric>(
7187 object, key, value, function_language_mode(), PREMONOMORPHIC);
7188 if (FLAG_vector_stores) {
7189 Handle<TypeFeedbackVector> vector =
7190 handle(current_feedback_vector(), isolate());
7191 result->SetVectorAndSlot(vector, slot);
7198 LoadKeyedHoleMode HOptimizedGraphBuilder::BuildKeyedHoleMode(Handle<Map> map) {
7199 // Loads from a "stock" fast holey double arrays can elide the hole check.
7200 // Loads from a "stock" fast holey array can convert the hole to undefined
7202 LoadKeyedHoleMode load_mode = NEVER_RETURN_HOLE;
7203 bool holey_double_elements =
7204 *map == isolate()->get_initial_js_array_map(FAST_HOLEY_DOUBLE_ELEMENTS);
7205 bool holey_elements =
7206 *map == isolate()->get_initial_js_array_map(FAST_HOLEY_ELEMENTS);
7207 if ((holey_double_elements || holey_elements) &&
7208 isolate()->IsFastArrayConstructorPrototypeChainIntact()) {
7210 holey_double_elements ? ALLOW_RETURN_HOLE : CONVERT_HOLE_TO_UNDEFINED;
7212 Handle<JSObject> prototype(JSObject::cast(map->prototype()), isolate());
7213 Handle<JSObject> object_prototype = isolate()->initial_object_prototype();
7214 BuildCheckPrototypeMaps(prototype, object_prototype);
7215 graph()->MarkDependsOnEmptyArrayProtoElements();
7221 HInstruction* HOptimizedGraphBuilder::BuildMonomorphicElementAccess(
7227 PropertyAccessType access_type,
7228 KeyedAccessStoreMode store_mode) {
7229 HCheckMaps* checked_object = Add<HCheckMaps>(object, map, dependency);
7231 if (access_type == STORE && map->prototype()->IsJSObject()) {
7232 // monomorphic stores need a prototype chain check because shape
7233 // changes could allow callbacks on elements in the chain that
7234 // aren't compatible with monomorphic keyed stores.
7235 PrototypeIterator iter(map);
7236 JSObject* holder = NULL;
7237 while (!iter.IsAtEnd()) {
7238 holder = JSObject::cast(*PrototypeIterator::GetCurrent(iter));
7241 DCHECK(holder && holder->IsJSObject());
7243 BuildCheckPrototypeMaps(handle(JSObject::cast(map->prototype())),
7244 Handle<JSObject>(holder));
7247 LoadKeyedHoleMode load_mode = BuildKeyedHoleMode(map);
7248 return BuildUncheckedMonomorphicElementAccess(
7249 checked_object, key, val,
7250 map->instance_type() == JS_ARRAY_TYPE,
7251 map->elements_kind(), access_type,
7252 load_mode, store_mode);
7256 static bool CanInlineElementAccess(Handle<Map> map) {
7257 return map->IsJSObjectMap() && !map->has_dictionary_elements() &&
7258 !map->has_sloppy_arguments_elements() &&
7259 !map->has_indexed_interceptor() && !map->is_access_check_needed();
7263 HInstruction* HOptimizedGraphBuilder::TryBuildConsolidatedElementLoad(
7267 SmallMapList* maps) {
7268 // For polymorphic loads of similar elements kinds (i.e. all tagged or all
7269 // double), always use the "worst case" code without a transition. This is
7270 // much faster than transitioning the elements to the worst case, trading a
7271 // HTransitionElements for a HCheckMaps, and avoiding mutation of the array.
7272 bool has_double_maps = false;
7273 bool has_smi_or_object_maps = false;
7274 bool has_js_array_access = false;
7275 bool has_non_js_array_access = false;
7276 bool has_seen_holey_elements = false;
7277 Handle<Map> most_general_consolidated_map;
7278 for (int i = 0; i < maps->length(); ++i) {
7279 Handle<Map> map = maps->at(i);
7280 if (!CanInlineElementAccess(map)) return NULL;
7281 // Don't allow mixing of JSArrays with JSObjects.
7282 if (map->instance_type() == JS_ARRAY_TYPE) {
7283 if (has_non_js_array_access) return NULL;
7284 has_js_array_access = true;
7285 } else if (has_js_array_access) {
7288 has_non_js_array_access = true;
7290 // Don't allow mixed, incompatible elements kinds.
7291 if (map->has_fast_double_elements()) {
7292 if (has_smi_or_object_maps) return NULL;
7293 has_double_maps = true;
7294 } else if (map->has_fast_smi_or_object_elements()) {
7295 if (has_double_maps) return NULL;
7296 has_smi_or_object_maps = true;
7300 // Remember if we've ever seen holey elements.
7301 if (IsHoleyElementsKind(map->elements_kind())) {
7302 has_seen_holey_elements = true;
7304 // Remember the most general elements kind, the code for its load will
7305 // properly handle all of the more specific cases.
7306 if ((i == 0) || IsMoreGeneralElementsKindTransition(
7307 most_general_consolidated_map->elements_kind(),
7308 map->elements_kind())) {
7309 most_general_consolidated_map = map;
7312 if (!has_double_maps && !has_smi_or_object_maps) return NULL;
7314 HCheckMaps* checked_object = Add<HCheckMaps>(object, maps);
7315 // FAST_ELEMENTS is considered more general than FAST_HOLEY_SMI_ELEMENTS.
7316 // If we've seen both, the consolidated load must use FAST_HOLEY_ELEMENTS.
7317 ElementsKind consolidated_elements_kind = has_seen_holey_elements
7318 ? GetHoleyElementsKind(most_general_consolidated_map->elements_kind())
7319 : most_general_consolidated_map->elements_kind();
7320 HInstruction* instr = BuildUncheckedMonomorphicElementAccess(
7321 checked_object, key, val,
7322 most_general_consolidated_map->instance_type() == JS_ARRAY_TYPE,
7323 consolidated_elements_kind,
7324 LOAD, NEVER_RETURN_HOLE, STANDARD_STORE);
7329 HValue* HOptimizedGraphBuilder::HandlePolymorphicElementAccess(
7330 Expression* expr, FeedbackVectorICSlot slot, HValue* object, HValue* key,
7331 HValue* val, SmallMapList* maps, PropertyAccessType access_type,
7332 KeyedAccessStoreMode store_mode, bool* has_side_effects) {
7333 *has_side_effects = false;
7334 BuildCheckHeapObject(object);
7336 if (access_type == LOAD) {
7337 HInstruction* consolidated_load =
7338 TryBuildConsolidatedElementLoad(object, key, val, maps);
7339 if (consolidated_load != NULL) {
7340 *has_side_effects |= consolidated_load->HasObservableSideEffects();
7341 return consolidated_load;
7345 // Elements_kind transition support.
7346 MapHandleList transition_target(maps->length());
7347 // Collect possible transition targets.
7348 MapHandleList possible_transitioned_maps(maps->length());
7349 for (int i = 0; i < maps->length(); ++i) {
7350 Handle<Map> map = maps->at(i);
7351 // Loads from strings or loads with a mix of string and non-string maps
7352 // shouldn't be handled polymorphically.
7353 DCHECK(access_type != LOAD || !map->IsStringMap());
7354 ElementsKind elements_kind = map->elements_kind();
7355 if (CanInlineElementAccess(map) && IsFastElementsKind(elements_kind) &&
7356 elements_kind != GetInitialFastElementsKind()) {
7357 possible_transitioned_maps.Add(map);
7359 if (IsSloppyArgumentsElements(elements_kind)) {
7360 HInstruction* result =
7361 BuildKeyedGeneric(access_type, expr, slot, object, key, val);
7362 *has_side_effects = result->HasObservableSideEffects();
7363 return AddInstruction(result);
7366 // Get transition target for each map (NULL == no transition).
7367 for (int i = 0; i < maps->length(); ++i) {
7368 Handle<Map> map = maps->at(i);
7369 Handle<Map> transitioned_map =
7370 Map::FindTransitionedMap(map, &possible_transitioned_maps);
7371 transition_target.Add(transitioned_map);
7374 MapHandleList untransitionable_maps(maps->length());
7375 HTransitionElementsKind* transition = NULL;
7376 for (int i = 0; i < maps->length(); ++i) {
7377 Handle<Map> map = maps->at(i);
7378 DCHECK(map->IsMap());
7379 if (!transition_target.at(i).is_null()) {
7380 DCHECK(Map::IsValidElementsTransition(
7381 map->elements_kind(),
7382 transition_target.at(i)->elements_kind()));
7383 transition = Add<HTransitionElementsKind>(object, map,
7384 transition_target.at(i));
7386 untransitionable_maps.Add(map);
7390 // If only one map is left after transitioning, handle this case
7392 DCHECK(untransitionable_maps.length() >= 1);
7393 if (untransitionable_maps.length() == 1) {
7394 Handle<Map> untransitionable_map = untransitionable_maps[0];
7395 HInstruction* instr = NULL;
7396 if (!CanInlineElementAccess(untransitionable_map)) {
7397 instr = AddInstruction(
7398 BuildKeyedGeneric(access_type, expr, slot, object, key, val));
7400 instr = BuildMonomorphicElementAccess(
7401 object, key, val, transition, untransitionable_map, access_type,
7404 *has_side_effects |= instr->HasObservableSideEffects();
7405 return access_type == STORE ? val : instr;
7408 HBasicBlock* join = graph()->CreateBasicBlock();
7410 for (int i = 0; i < untransitionable_maps.length(); ++i) {
7411 Handle<Map> map = untransitionable_maps[i];
7412 ElementsKind elements_kind = map->elements_kind();
7413 HBasicBlock* this_map = graph()->CreateBasicBlock();
7414 HBasicBlock* other_map = graph()->CreateBasicBlock();
7415 HCompareMap* mapcompare =
7416 New<HCompareMap>(object, map, this_map, other_map);
7417 FinishCurrentBlock(mapcompare);
7419 set_current_block(this_map);
7420 HInstruction* access = NULL;
7421 if (!CanInlineElementAccess(map)) {
7422 access = AddInstruction(
7423 BuildKeyedGeneric(access_type, expr, slot, object, key, val));
7425 DCHECK(IsFastElementsKind(elements_kind) ||
7426 IsFixedTypedArrayElementsKind(elements_kind));
7427 LoadKeyedHoleMode load_mode = BuildKeyedHoleMode(map);
7428 // Happily, mapcompare is a checked object.
7429 access = BuildUncheckedMonomorphicElementAccess(
7430 mapcompare, key, val,
7431 map->instance_type() == JS_ARRAY_TYPE,
7432 elements_kind, access_type,
7436 *has_side_effects |= access->HasObservableSideEffects();
7437 // The caller will use has_side_effects and add a correct Simulate.
7438 access->SetFlag(HValue::kHasNoObservableSideEffects);
7439 if (access_type == LOAD) {
7442 NoObservableSideEffectsScope scope(this);
7443 GotoNoSimulate(join);
7444 set_current_block(other_map);
7447 // Ensure that we visited at least one map above that goes to join. This is
7448 // necessary because FinishExitWithHardDeoptimization does an AbnormalExit
7449 // rather than joining the join block. If this becomes an issue, insert a
7450 // generic access in the case length() == 0.
7451 DCHECK(join->predecessors()->length() > 0);
7452 // Deopt if none of the cases matched.
7453 NoObservableSideEffectsScope scope(this);
7454 FinishExitWithHardDeoptimization(
7455 Deoptimizer::kUnknownMapInPolymorphicElementAccess);
7456 set_current_block(join);
7457 return access_type == STORE ? val : Pop();
7461 HValue* HOptimizedGraphBuilder::HandleKeyedElementAccess(
7462 HValue* obj, HValue* key, HValue* val, Expression* expr,
7463 FeedbackVectorICSlot slot, BailoutId ast_id, BailoutId return_id,
7464 PropertyAccessType access_type, bool* has_side_effects) {
7465 if (key->ActualValue()->IsConstant()) {
7466 Handle<Object> constant =
7467 HConstant::cast(key->ActualValue())->handle(isolate());
7468 uint32_t array_index;
7469 if (constant->IsString() &&
7470 !Handle<String>::cast(constant)->AsArrayIndex(&array_index)) {
7471 if (!constant->IsUniqueName()) {
7472 constant = isolate()->factory()->InternalizeString(
7473 Handle<String>::cast(constant));
7476 BuildNamedAccess(access_type, ast_id, return_id, expr, slot, obj,
7477 Handle<String>::cast(constant), val, false);
7478 if (access == NULL || access->IsPhi() ||
7479 HInstruction::cast(access)->IsLinked()) {
7480 *has_side_effects = false;
7482 HInstruction* instr = HInstruction::cast(access);
7483 AddInstruction(instr);
7484 *has_side_effects = instr->HasObservableSideEffects();
7490 DCHECK(!expr->IsPropertyName());
7491 HInstruction* instr = NULL;
7494 bool monomorphic = ComputeReceiverTypes(expr, obj, &maps, zone());
7496 bool force_generic = false;
7497 if (expr->GetKeyType() == PROPERTY) {
7498 // Non-Generic accesses assume that elements are being accessed, and will
7499 // deopt for non-index keys, which the IC knows will occur.
7500 // TODO(jkummerow): Consider adding proper support for property accesses.
7501 force_generic = true;
7502 monomorphic = false;
7503 } else if (access_type == STORE &&
7504 (monomorphic || (maps != NULL && !maps->is_empty()))) {
7505 // Stores can't be mono/polymorphic if their prototype chain has dictionary
7506 // elements. However a receiver map that has dictionary elements itself
7507 // should be left to normal mono/poly behavior (the other maps may benefit
7508 // from highly optimized stores).
7509 for (int i = 0; i < maps->length(); i++) {
7510 Handle<Map> current_map = maps->at(i);
7511 if (current_map->DictionaryElementsInPrototypeChainOnly()) {
7512 force_generic = true;
7513 monomorphic = false;
7517 } else if (access_type == LOAD && !monomorphic &&
7518 (maps != NULL && !maps->is_empty())) {
7519 // Polymorphic loads have to go generic if any of the maps are strings.
7520 // If some, but not all of the maps are strings, we should go generic
7521 // because polymorphic access wants to key on ElementsKind and isn't
7522 // compatible with strings.
7523 for (int i = 0; i < maps->length(); i++) {
7524 Handle<Map> current_map = maps->at(i);
7525 if (current_map->IsStringMap()) {
7526 force_generic = true;
7533 Handle<Map> map = maps->first();
7534 if (!CanInlineElementAccess(map)) {
7535 instr = AddInstruction(
7536 BuildKeyedGeneric(access_type, expr, slot, obj, key, val));
7538 BuildCheckHeapObject(obj);
7539 instr = BuildMonomorphicElementAccess(
7540 obj, key, val, NULL, map, access_type, expr->GetStoreMode());
7542 } else if (!force_generic && (maps != NULL && !maps->is_empty())) {
7543 return HandlePolymorphicElementAccess(expr, slot, obj, key, val, maps,
7544 access_type, expr->GetStoreMode(),
7547 if (access_type == STORE) {
7548 if (expr->IsAssignment() &&
7549 expr->AsAssignment()->HasNoTypeInformation()) {
7550 Add<HDeoptimize>(Deoptimizer::kInsufficientTypeFeedbackForKeyedStore,
7554 if (expr->AsProperty()->HasNoTypeInformation()) {
7555 Add<HDeoptimize>(Deoptimizer::kInsufficientTypeFeedbackForKeyedLoad,
7559 instr = AddInstruction(
7560 BuildKeyedGeneric(access_type, expr, slot, obj, key, val));
7562 *has_side_effects = instr->HasObservableSideEffects();
7567 void HOptimizedGraphBuilder::EnsureArgumentsArePushedForAccess() {
7568 // Outermost function already has arguments on the stack.
7569 if (function_state()->outer() == NULL) return;
7571 if (function_state()->arguments_pushed()) return;
7573 // Push arguments when entering inlined function.
7574 HEnterInlined* entry = function_state()->entry();
7575 entry->set_arguments_pushed();
7577 HArgumentsObject* arguments = entry->arguments_object();
7578 const ZoneList<HValue*>* arguments_values = arguments->arguments_values();
7580 HInstruction* insert_after = entry;
7581 for (int i = 0; i < arguments_values->length(); i++) {
7582 HValue* argument = arguments_values->at(i);
7583 HInstruction* push_argument = New<HPushArguments>(argument);
7584 push_argument->InsertAfter(insert_after);
7585 insert_after = push_argument;
7588 HArgumentsElements* arguments_elements = New<HArgumentsElements>(true);
7589 arguments_elements->ClearFlag(HValue::kUseGVN);
7590 arguments_elements->InsertAfter(insert_after);
7591 function_state()->set_arguments_elements(arguments_elements);
7595 bool HOptimizedGraphBuilder::TryArgumentsAccess(Property* expr) {
7596 VariableProxy* proxy = expr->obj()->AsVariableProxy();
7597 if (proxy == NULL) return false;
7598 if (!proxy->var()->IsStackAllocated()) return false;
7599 if (!environment()->Lookup(proxy->var())->CheckFlag(HValue::kIsArguments)) {
7603 HInstruction* result = NULL;
7604 if (expr->key()->IsPropertyName()) {
7605 Handle<String> name = expr->key()->AsLiteral()->AsPropertyName();
7606 if (!String::Equals(name, isolate()->factory()->length_string())) {
7610 if (function_state()->outer() == NULL) {
7611 HInstruction* elements = Add<HArgumentsElements>(false);
7612 result = New<HArgumentsLength>(elements);
7614 // Number of arguments without receiver.
7615 int argument_count = environment()->
7616 arguments_environment()->parameter_count() - 1;
7617 result = New<HConstant>(argument_count);
7620 Push(graph()->GetArgumentsObject());
7621 CHECK_ALIVE_OR_RETURN(VisitForValue(expr->key()), true);
7622 HValue* key = Pop();
7623 Drop(1); // Arguments object.
7624 if (function_state()->outer() == NULL) {
7625 HInstruction* elements = Add<HArgumentsElements>(false);
7626 HInstruction* length = Add<HArgumentsLength>(elements);
7627 HInstruction* checked_key = Add<HBoundsCheck>(key, length);
7628 result = New<HAccessArgumentsAt>(elements, length, checked_key);
7630 EnsureArgumentsArePushedForAccess();
7632 // Number of arguments without receiver.
7633 HInstruction* elements = function_state()->arguments_elements();
7634 int argument_count = environment()->
7635 arguments_environment()->parameter_count() - 1;
7636 HInstruction* length = Add<HConstant>(argument_count);
7637 HInstruction* checked_key = Add<HBoundsCheck>(key, length);
7638 result = New<HAccessArgumentsAt>(elements, length, checked_key);
7641 ast_context()->ReturnInstruction(result, expr->id());
7646 HValue* HOptimizedGraphBuilder::BuildNamedAccess(
7647 PropertyAccessType access, BailoutId ast_id, BailoutId return_id,
7648 Expression* expr, FeedbackVectorICSlot slot, HValue* object,
7649 Handle<String> name, HValue* value, bool is_uninitialized) {
7651 ComputeReceiverTypes(expr, object, &maps, zone());
7652 DCHECK(maps != NULL);
7654 if (maps->length() > 0) {
7655 PropertyAccessInfo info(this, access, maps->first(), name);
7656 if (!info.CanAccessAsMonomorphic(maps)) {
7657 HandlePolymorphicNamedFieldAccess(access, expr, slot, ast_id, return_id,
7658 object, value, maps, name);
7662 HValue* checked_object;
7663 // Type::Number() is only supported by polymorphic load/call handling.
7664 DCHECK(!info.IsNumberType());
7665 BuildCheckHeapObject(object);
7666 if (AreStringTypes(maps)) {
7668 Add<HCheckInstanceType>(object, HCheckInstanceType::IS_STRING);
7670 checked_object = Add<HCheckMaps>(object, maps);
7672 return BuildMonomorphicAccess(
7673 &info, object, checked_object, value, ast_id, return_id);
7676 return BuildNamedGeneric(access, expr, slot, object, name, value,
7681 void HOptimizedGraphBuilder::PushLoad(Property* expr,
7684 ValueContext for_value(this, ARGUMENTS_NOT_ALLOWED);
7686 if (key != NULL) Push(key);
7687 BuildLoad(expr, expr->LoadId());
7691 void HOptimizedGraphBuilder::BuildLoad(Property* expr,
7693 HInstruction* instr = NULL;
7694 if (expr->IsStringAccess()) {
7695 HValue* index = Pop();
7696 HValue* string = Pop();
7697 HInstruction* char_code = BuildStringCharCodeAt(string, index);
7698 AddInstruction(char_code);
7699 instr = NewUncasted<HStringCharFromCode>(char_code);
7701 } else if (expr->key()->IsPropertyName()) {
7702 Handle<String> name = expr->key()->AsLiteral()->AsPropertyName();
7703 HValue* object = Pop();
7705 HValue* value = BuildNamedAccess(LOAD, ast_id, expr->LoadId(), expr,
7706 expr->PropertyFeedbackSlot(), object, name,
7707 NULL, expr->IsUninitialized());
7708 if (value == NULL) return;
7709 if (value->IsPhi()) return ast_context()->ReturnValue(value);
7710 instr = HInstruction::cast(value);
7711 if (instr->IsLinked()) return ast_context()->ReturnValue(instr);
7714 HValue* key = Pop();
7715 HValue* obj = Pop();
7717 bool has_side_effects = false;
7718 HValue* load = HandleKeyedElementAccess(
7719 obj, key, NULL, expr, expr->PropertyFeedbackSlot(), ast_id,
7720 expr->LoadId(), LOAD, &has_side_effects);
7721 if (has_side_effects) {
7722 if (ast_context()->IsEffect()) {
7723 Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
7726 Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
7730 if (load == NULL) return;
7731 return ast_context()->ReturnValue(load);
7733 return ast_context()->ReturnInstruction(instr, ast_id);
7737 void HOptimizedGraphBuilder::VisitProperty(Property* expr) {
7738 DCHECK(!HasStackOverflow());
7739 DCHECK(current_block() != NULL);
7740 DCHECK(current_block()->HasPredecessor());
7742 if (TryArgumentsAccess(expr)) return;
7744 CHECK_ALIVE(VisitForValue(expr->obj()));
7745 if (!expr->key()->IsPropertyName() || expr->IsStringAccess()) {
7746 CHECK_ALIVE(VisitForValue(expr->key()));
7749 BuildLoad(expr, expr->id());
7753 HInstruction* HGraphBuilder::BuildConstantMapCheck(Handle<JSObject> constant) {
7754 HCheckMaps* check = Add<HCheckMaps>(
7755 Add<HConstant>(constant), handle(constant->map()));
7756 check->ClearDependsOnFlag(kElementsKind);
7761 HInstruction* HGraphBuilder::BuildCheckPrototypeMaps(Handle<JSObject> prototype,
7762 Handle<JSObject> holder) {
7763 PrototypeIterator iter(isolate(), prototype,
7764 PrototypeIterator::START_AT_RECEIVER);
7765 while (holder.is_null() ||
7766 !PrototypeIterator::GetCurrent(iter).is_identical_to(holder)) {
7767 BuildConstantMapCheck(
7768 Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter)));
7770 if (iter.IsAtEnd()) {
7774 return BuildConstantMapCheck(
7775 Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter)));
7779 void HOptimizedGraphBuilder::AddCheckPrototypeMaps(Handle<JSObject> holder,
7780 Handle<Map> receiver_map) {
7781 if (!holder.is_null()) {
7782 Handle<JSObject> prototype(JSObject::cast(receiver_map->prototype()));
7783 BuildCheckPrototypeMaps(prototype, holder);
7788 HInstruction* HOptimizedGraphBuilder::NewPlainFunctionCall(
7789 HValue* fun, int argument_count, bool pass_argument_count) {
7790 return New<HCallJSFunction>(fun, argument_count, pass_argument_count);
7794 HInstruction* HOptimizedGraphBuilder::NewArgumentAdaptorCall(
7795 HValue* fun, HValue* context,
7796 int argument_count, HValue* expected_param_count) {
7797 ArgumentAdaptorDescriptor descriptor(isolate());
7798 HValue* arity = Add<HConstant>(argument_count - 1);
7800 HValue* op_vals[] = { context, fun, arity, expected_param_count };
7802 Handle<Code> adaptor =
7803 isolate()->builtins()->ArgumentsAdaptorTrampoline();
7804 HConstant* adaptor_value = Add<HConstant>(adaptor);
7806 return New<HCallWithDescriptor>(adaptor_value, argument_count, descriptor,
7807 Vector<HValue*>(op_vals, arraysize(op_vals)));
7811 HInstruction* HOptimizedGraphBuilder::BuildCallConstantFunction(
7812 Handle<JSFunction> jsfun, int argument_count) {
7813 HValue* target = Add<HConstant>(jsfun);
7814 // For constant functions, we try to avoid calling the
7815 // argument adaptor and instead call the function directly
7816 int formal_parameter_count =
7817 jsfun->shared()->internal_formal_parameter_count();
7818 bool dont_adapt_arguments =
7819 (formal_parameter_count ==
7820 SharedFunctionInfo::kDontAdaptArgumentsSentinel);
7821 int arity = argument_count - 1;
7822 bool can_invoke_directly =
7823 dont_adapt_arguments || formal_parameter_count == arity;
7824 if (can_invoke_directly) {
7825 if (jsfun.is_identical_to(current_info()->closure())) {
7826 graph()->MarkRecursive();
7828 return NewPlainFunctionCall(target, argument_count, dont_adapt_arguments);
7830 HValue* param_count_value = Add<HConstant>(formal_parameter_count);
7831 HValue* context = Add<HLoadNamedField>(
7832 target, nullptr, HObjectAccess::ForFunctionContextPointer());
7833 return NewArgumentAdaptorCall(target, context,
7834 argument_count, param_count_value);
7841 class FunctionSorter {
7843 explicit FunctionSorter(int index = 0, int ticks = 0, int size = 0)
7844 : index_(index), ticks_(ticks), size_(size) {}
7846 int index() const { return index_; }
7847 int ticks() const { return ticks_; }
7848 int size() const { return size_; }
7857 inline bool operator<(const FunctionSorter& lhs, const FunctionSorter& rhs) {
7858 int diff = lhs.ticks() - rhs.ticks();
7859 if (diff != 0) return diff > 0;
7860 return lhs.size() < rhs.size();
7864 void HOptimizedGraphBuilder::HandlePolymorphicCallNamed(Call* expr,
7867 Handle<String> name) {
7868 int argument_count = expr->arguments()->length() + 1; // Includes receiver.
7869 FunctionSorter order[kMaxCallPolymorphism];
7871 bool handle_smi = false;
7872 bool handled_string = false;
7873 int ordered_functions = 0;
7876 for (i = 0; i < maps->length() && ordered_functions < kMaxCallPolymorphism;
7878 PropertyAccessInfo info(this, LOAD, maps->at(i), name);
7879 if (info.CanAccessMonomorphic() && info.IsDataConstant() &&
7880 info.constant()->IsJSFunction()) {
7881 if (info.IsStringType()) {
7882 if (handled_string) continue;
7883 handled_string = true;
7885 Handle<JSFunction> target = Handle<JSFunction>::cast(info.constant());
7886 if (info.IsNumberType()) {
7889 expr->set_target(target);
7890 order[ordered_functions++] = FunctionSorter(
7891 i, target->shared()->profiler_ticks(), InliningAstSize(target));
7895 std::sort(order, order + ordered_functions);
7897 if (i < maps->length()) {
7899 ordered_functions = -1;
7902 HBasicBlock* number_block = NULL;
7903 HBasicBlock* join = NULL;
7904 handled_string = false;
7907 for (int fn = 0; fn < ordered_functions; ++fn) {
7908 int i = order[fn].index();
7909 PropertyAccessInfo info(this, LOAD, maps->at(i), name);
7910 if (info.IsStringType()) {
7911 if (handled_string) continue;
7912 handled_string = true;
7914 // Reloads the target.
7915 info.CanAccessMonomorphic();
7916 Handle<JSFunction> target = Handle<JSFunction>::cast(info.constant());
7918 expr->set_target(target);
7920 // Only needed once.
7921 join = graph()->CreateBasicBlock();
7923 HBasicBlock* empty_smi_block = graph()->CreateBasicBlock();
7924 HBasicBlock* not_smi_block = graph()->CreateBasicBlock();
7925 number_block = graph()->CreateBasicBlock();
7926 FinishCurrentBlock(New<HIsSmiAndBranch>(
7927 receiver, empty_smi_block, not_smi_block));
7928 GotoNoSimulate(empty_smi_block, number_block);
7929 set_current_block(not_smi_block);
7931 BuildCheckHeapObject(receiver);
7935 HBasicBlock* if_true = graph()->CreateBasicBlock();
7936 HBasicBlock* if_false = graph()->CreateBasicBlock();
7937 HUnaryControlInstruction* compare;
7939 Handle<Map> map = info.map();
7940 if (info.IsNumberType()) {
7941 Handle<Map> heap_number_map = isolate()->factory()->heap_number_map();
7942 compare = New<HCompareMap>(receiver, heap_number_map, if_true, if_false);
7943 } else if (info.IsStringType()) {
7944 compare = New<HIsStringAndBranch>(receiver, if_true, if_false);
7946 compare = New<HCompareMap>(receiver, map, if_true, if_false);
7948 FinishCurrentBlock(compare);
7950 if (info.IsNumberType()) {
7951 GotoNoSimulate(if_true, number_block);
7952 if_true = number_block;
7955 set_current_block(if_true);
7957 AddCheckPrototypeMaps(info.holder(), map);
7959 HValue* function = Add<HConstant>(expr->target());
7960 environment()->SetExpressionStackAt(0, function);
7962 CHECK_ALIVE(VisitExpressions(expr->arguments()));
7963 bool needs_wrapping = info.NeedsWrappingFor(target);
7964 bool try_inline = FLAG_polymorphic_inlining && !needs_wrapping;
7965 if (FLAG_trace_inlining && try_inline) {
7966 Handle<JSFunction> caller = current_info()->closure();
7967 base::SmartArrayPointer<char> caller_name =
7968 caller->shared()->DebugName()->ToCString();
7969 PrintF("Trying to inline the polymorphic call to %s from %s\n",
7970 name->ToCString().get(),
7973 if (try_inline && TryInlineCall(expr)) {
7974 // Trying to inline will signal that we should bailout from the
7975 // entire compilation by setting stack overflow on the visitor.
7976 if (HasStackOverflow()) return;
7978 // Since HWrapReceiver currently cannot actually wrap numbers and strings,
7979 // use the regular CallFunctionStub for method calls to wrap the receiver.
7980 // TODO(verwaest): Support creation of value wrappers directly in
7982 HInstruction* call = needs_wrapping
7983 ? NewUncasted<HCallFunction>(
7984 function, argument_count, WRAP_AND_CALL)
7985 : BuildCallConstantFunction(target, argument_count);
7986 PushArgumentsFromEnvironment(argument_count);
7987 AddInstruction(call);
7988 Drop(1); // Drop the function.
7989 if (!ast_context()->IsEffect()) Push(call);
7992 if (current_block() != NULL) Goto(join);
7993 set_current_block(if_false);
7996 // Finish up. Unconditionally deoptimize if we've handled all the maps we
7997 // know about and do not want to handle ones we've never seen. Otherwise
7998 // use a generic IC.
7999 if (ordered_functions == maps->length() && FLAG_deoptimize_uncommon_cases) {
8000 FinishExitWithHardDeoptimization(Deoptimizer::kUnknownMapInPolymorphicCall);
8002 Property* prop = expr->expression()->AsProperty();
8003 HInstruction* function =
8004 BuildNamedGeneric(LOAD, prop, prop->PropertyFeedbackSlot(), receiver,
8005 name, NULL, prop->IsUninitialized());
8006 AddInstruction(function);
8008 AddSimulate(prop->LoadId(), REMOVABLE_SIMULATE);
8010 environment()->SetExpressionStackAt(1, function);
8011 environment()->SetExpressionStackAt(0, receiver);
8012 CHECK_ALIVE(VisitExpressions(expr->arguments()));
8014 CallFunctionFlags flags = receiver->type().IsJSObject()
8015 ? NO_CALL_FUNCTION_FLAGS : CALL_AS_METHOD;
8016 HInstruction* call = New<HCallFunction>(
8017 function, argument_count, flags);
8019 PushArgumentsFromEnvironment(argument_count);
8021 Drop(1); // Function.
8024 AddInstruction(call);
8025 if (!ast_context()->IsEffect()) Push(call);
8028 return ast_context()->ReturnInstruction(call, expr->id());
8032 // We assume that control flow is always live after an expression. So
8033 // even without predecessors to the join block, we set it as the exit
8034 // block and continue by adding instructions there.
8035 DCHECK(join != NULL);
8036 if (join->HasPredecessor()) {
8037 set_current_block(join);
8038 join->SetJoinId(expr->id());
8039 if (!ast_context()->IsEffect()) return ast_context()->ReturnValue(Pop());
8041 set_current_block(NULL);
8046 void HOptimizedGraphBuilder::TraceInline(Handle<JSFunction> target,
8047 Handle<JSFunction> caller,
8048 const char* reason) {
8049 if (FLAG_trace_inlining) {
8050 base::SmartArrayPointer<char> target_name =
8051 target->shared()->DebugName()->ToCString();
8052 base::SmartArrayPointer<char> caller_name =
8053 caller->shared()->DebugName()->ToCString();
8054 if (reason == NULL) {
8055 PrintF("Inlined %s called from %s.\n", target_name.get(),
8058 PrintF("Did not inline %s called from %s (%s).\n",
8059 target_name.get(), caller_name.get(), reason);
8065 static const int kNotInlinable = 1000000000;
8068 int HOptimizedGraphBuilder::InliningAstSize(Handle<JSFunction> target) {
8069 if (!FLAG_use_inlining) return kNotInlinable;
8071 // Precondition: call is monomorphic and we have found a target with the
8072 // appropriate arity.
8073 Handle<JSFunction> caller = current_info()->closure();
8074 Handle<SharedFunctionInfo> target_shared(target->shared());
8076 // Always inline functions that force inlining.
8077 if (target_shared->force_inline()) {
8080 if (target->IsBuiltin()) {
8081 return kNotInlinable;
8084 if (target_shared->IsApiFunction()) {
8085 TraceInline(target, caller, "target is api function");
8086 return kNotInlinable;
8089 // Do a quick check on source code length to avoid parsing large
8090 // inlining candidates.
8091 if (target_shared->SourceSize() >
8092 Min(FLAG_max_inlined_source_size, kUnlimitedMaxInlinedSourceSize)) {
8093 TraceInline(target, caller, "target text too big");
8094 return kNotInlinable;
8097 // Target must be inlineable.
8098 if (!target_shared->IsInlineable()) {
8099 TraceInline(target, caller, "target not inlineable");
8100 return kNotInlinable;
8102 if (target_shared->disable_optimization_reason() != kNoReason) {
8103 TraceInline(target, caller, "target contains unsupported syntax [early]");
8104 return kNotInlinable;
8107 int nodes_added = target_shared->ast_node_count();
8112 bool HOptimizedGraphBuilder::TryInline(Handle<JSFunction> target,
8113 int arguments_count,
8114 HValue* implicit_return_value,
8115 BailoutId ast_id, BailoutId return_id,
8116 InliningKind inlining_kind) {
8117 if (target->context()->native_context() !=
8118 top_info()->closure()->context()->native_context()) {
8121 int nodes_added = InliningAstSize(target);
8122 if (nodes_added == kNotInlinable) return false;
8124 Handle<JSFunction> caller = current_info()->closure();
8126 if (nodes_added > Min(FLAG_max_inlined_nodes, kUnlimitedMaxInlinedNodes)) {
8127 TraceInline(target, caller, "target AST is too large [early]");
8131 // Don't inline deeper than the maximum number of inlining levels.
8132 HEnvironment* env = environment();
8133 int current_level = 1;
8134 while (env->outer() != NULL) {
8135 if (current_level == FLAG_max_inlining_levels) {
8136 TraceInline(target, caller, "inline depth limit reached");
8139 if (env->outer()->frame_type() == JS_FUNCTION) {
8145 // Don't inline recursive functions.
8146 for (FunctionState* state = function_state();
8148 state = state->outer()) {
8149 if (*state->compilation_info()->closure() == *target) {
8150 TraceInline(target, caller, "target is recursive");
8155 // We don't want to add more than a certain number of nodes from inlining.
8156 // Always inline small methods (<= 10 nodes).
8157 if (inlined_count_ > Min(FLAG_max_inlined_nodes_cumulative,
8158 kUnlimitedMaxInlinedNodesCumulative)) {
8159 TraceInline(target, caller, "cumulative AST node limit reached");
8163 // Parse and allocate variables.
8164 // Use the same AstValueFactory for creating strings in the sub-compilation
8165 // step, but don't transfer ownership to target_info.
8166 ParseInfo parse_info(zone(), target);
8167 parse_info.set_ast_value_factory(
8168 top_info()->parse_info()->ast_value_factory());
8169 parse_info.set_ast_value_factory_owned(false);
8171 CompilationInfo target_info(&parse_info);
8172 Handle<SharedFunctionInfo> target_shared(target->shared());
8173 if (target_shared->HasDebugInfo()) {
8174 TraceInline(target, caller, "target is being debugged");
8177 if (!Compiler::ParseAndAnalyze(target_info.parse_info())) {
8178 if (target_info.isolate()->has_pending_exception()) {
8179 // Parse or scope error, never optimize this function.
8181 target_shared->DisableOptimization(kParseScopeError);
8183 TraceInline(target, caller, "parse failure");
8187 if (target_info.scope()->num_heap_slots() > 0) {
8188 TraceInline(target, caller, "target has context-allocated variables");
8191 FunctionLiteral* function = target_info.function();
8193 // The following conditions must be checked again after re-parsing, because
8194 // earlier the information might not have been complete due to lazy parsing.
8195 nodes_added = function->ast_node_count();
8196 if (nodes_added > Min(FLAG_max_inlined_nodes, kUnlimitedMaxInlinedNodes)) {
8197 TraceInline(target, caller, "target AST is too large [late]");
8200 if (function->dont_optimize()) {
8201 TraceInline(target, caller, "target contains unsupported syntax [late]");
8205 // If the function uses the arguments object check that inlining of functions
8206 // with arguments object is enabled and the arguments-variable is
8208 if (function->scope()->arguments() != NULL) {
8209 if (!FLAG_inline_arguments) {
8210 TraceInline(target, caller, "target uses arguments object");
8215 // All declarations must be inlineable.
8216 ZoneList<Declaration*>* decls = target_info.scope()->declarations();
8217 int decl_count = decls->length();
8218 for (int i = 0; i < decl_count; ++i) {
8219 if (!decls->at(i)->IsInlineable()) {
8220 TraceInline(target, caller, "target has non-trivial declaration");
8225 // Generate the deoptimization data for the unoptimized version of
8226 // the target function if we don't already have it.
8227 if (!Compiler::EnsureDeoptimizationSupport(&target_info)) {
8228 TraceInline(target, caller, "could not generate deoptimization info");
8232 // In strong mode it is an error to call a function with too few arguments.
8233 // In that case do not inline because then the arity check would be skipped.
8234 if (is_strong(function->language_mode()) &&
8235 arguments_count < function->parameter_count()) {
8236 TraceInline(target, caller,
8237 "too few arguments passed to a strong function");
8241 // ----------------------------------------------------------------
8242 // After this point, we've made a decision to inline this function (so
8243 // TryInline should always return true).
8245 // Type-check the inlined function.
8246 DCHECK(target_shared->has_deoptimization_support());
8247 AstTyper::Run(&target_info);
8249 int inlining_id = 0;
8250 if (top_info()->is_tracking_positions()) {
8251 inlining_id = top_info()->TraceInlinedFunction(
8252 target_shared, source_position(), function_state()->inlining_id());
8255 // Save the pending call context. Set up new one for the inlined function.
8256 // The function state is new-allocated because we need to delete it
8257 // in two different places.
8258 FunctionState* target_state =
8259 new FunctionState(this, &target_info, inlining_kind, inlining_id);
8261 HConstant* undefined = graph()->GetConstantUndefined();
8263 HEnvironment* inner_env =
8264 environment()->CopyForInlining(target,
8268 function_state()->inlining_kind());
8270 HConstant* context = Add<HConstant>(Handle<Context>(target->context()));
8271 inner_env->BindContext(context);
8273 // Create a dematerialized arguments object for the function, also copy the
8274 // current arguments values to use them for materialization.
8275 HEnvironment* arguments_env = inner_env->arguments_environment();
8276 int parameter_count = arguments_env->parameter_count();
8277 HArgumentsObject* arguments_object = Add<HArgumentsObject>(parameter_count);
8278 for (int i = 0; i < parameter_count; i++) {
8279 arguments_object->AddArgument(arguments_env->Lookup(i), zone());
8282 // If the function uses arguments object then bind bind one.
8283 if (function->scope()->arguments() != NULL) {
8284 DCHECK(function->scope()->arguments()->IsStackAllocated());
8285 inner_env->Bind(function->scope()->arguments(), arguments_object);
8288 // Capture the state before invoking the inlined function for deopt in the
8289 // inlined function. This simulate has no bailout-id since it's not directly
8290 // reachable for deopt, and is only used to capture the state. If the simulate
8291 // becomes reachable by merging, the ast id of the simulate merged into it is
8293 Add<HSimulate>(BailoutId::None());
8295 current_block()->UpdateEnvironment(inner_env);
8296 Scope* saved_scope = scope();
8297 set_scope(target_info.scope());
8298 HEnterInlined* enter_inlined =
8299 Add<HEnterInlined>(return_id, target, context, arguments_count, function,
8300 function_state()->inlining_kind(),
8301 function->scope()->arguments(), arguments_object);
8302 if (top_info()->is_tracking_positions()) {
8303 enter_inlined->set_inlining_id(inlining_id);
8305 function_state()->set_entry(enter_inlined);
8307 VisitDeclarations(target_info.scope()->declarations());
8308 VisitStatements(function->body());
8309 set_scope(saved_scope);
8310 if (HasStackOverflow()) {
8311 // Bail out if the inline function did, as we cannot residualize a call
8312 // instead, but do not disable optimization for the outer function.
8313 TraceInline(target, caller, "inline graph construction failed");
8314 target_shared->DisableOptimization(kInliningBailedOut);
8315 current_info()->RetryOptimization(kInliningBailedOut);
8316 delete target_state;
8320 // Update inlined nodes count.
8321 inlined_count_ += nodes_added;
8323 Handle<Code> unoptimized_code(target_shared->code());
8324 DCHECK(unoptimized_code->kind() == Code::FUNCTION);
8325 Handle<TypeFeedbackInfo> type_info(
8326 TypeFeedbackInfo::cast(unoptimized_code->type_feedback_info()));
8327 graph()->update_type_change_checksum(type_info->own_type_change_checksum());
8329 TraceInline(target, caller, NULL);
8331 if (current_block() != NULL) {
8332 FunctionState* state = function_state();
8333 if (state->inlining_kind() == CONSTRUCT_CALL_RETURN) {
8334 // Falling off the end of an inlined construct call. In a test context the
8335 // return value will always evaluate to true, in a value context the
8336 // return value is the newly allocated receiver.
8337 if (call_context()->IsTest()) {
8338 Goto(inlined_test_context()->if_true(), state);
8339 } else if (call_context()->IsEffect()) {
8340 Goto(function_return(), state);
8342 DCHECK(call_context()->IsValue());
8343 AddLeaveInlined(implicit_return_value, state);
8345 } else if (state->inlining_kind() == SETTER_CALL_RETURN) {
8346 // Falling off the end of an inlined setter call. The returned value is
8347 // never used, the value of an assignment is always the value of the RHS
8348 // of the assignment.
8349 if (call_context()->IsTest()) {
8350 inlined_test_context()->ReturnValue(implicit_return_value);
8351 } else if (call_context()->IsEffect()) {
8352 Goto(function_return(), state);
8354 DCHECK(call_context()->IsValue());
8355 AddLeaveInlined(implicit_return_value, state);
8358 // Falling off the end of a normal inlined function. This basically means
8359 // returning undefined.
8360 if (call_context()->IsTest()) {
8361 Goto(inlined_test_context()->if_false(), state);
8362 } else if (call_context()->IsEffect()) {
8363 Goto(function_return(), state);
8365 DCHECK(call_context()->IsValue());
8366 AddLeaveInlined(undefined, state);
8371 // Fix up the function exits.
8372 if (inlined_test_context() != NULL) {
8373 HBasicBlock* if_true = inlined_test_context()->if_true();
8374 HBasicBlock* if_false = inlined_test_context()->if_false();
8376 HEnterInlined* entry = function_state()->entry();
8378 // Pop the return test context from the expression context stack.
8379 DCHECK(ast_context() == inlined_test_context());
8380 ClearInlinedTestContext();
8381 delete target_state;
8383 // Forward to the real test context.
8384 if (if_true->HasPredecessor()) {
8385 entry->RegisterReturnTarget(if_true, zone());
8386 if_true->SetJoinId(ast_id);
8387 HBasicBlock* true_target = TestContext::cast(ast_context())->if_true();
8388 Goto(if_true, true_target, function_state());
8390 if (if_false->HasPredecessor()) {
8391 entry->RegisterReturnTarget(if_false, zone());
8392 if_false->SetJoinId(ast_id);
8393 HBasicBlock* false_target = TestContext::cast(ast_context())->if_false();
8394 Goto(if_false, false_target, function_state());
8396 set_current_block(NULL);
8399 } else if (function_return()->HasPredecessor()) {
8400 function_state()->entry()->RegisterReturnTarget(function_return(), zone());
8401 function_return()->SetJoinId(ast_id);
8402 set_current_block(function_return());
8404 set_current_block(NULL);
8406 delete target_state;
8411 bool HOptimizedGraphBuilder::TryInlineCall(Call* expr) {
8412 return TryInline(expr->target(), expr->arguments()->length(), NULL,
8413 expr->id(), expr->ReturnId(), NORMAL_RETURN);
8417 bool HOptimizedGraphBuilder::TryInlineConstruct(CallNew* expr,
8418 HValue* implicit_return_value) {
8419 return TryInline(expr->target(), expr->arguments()->length(),
8420 implicit_return_value, expr->id(), expr->ReturnId(),
8421 CONSTRUCT_CALL_RETURN);
8425 bool HOptimizedGraphBuilder::TryInlineGetter(Handle<JSFunction> getter,
8426 Handle<Map> receiver_map,
8428 BailoutId return_id) {
8429 if (TryInlineApiGetter(getter, receiver_map, ast_id)) return true;
8430 return TryInline(getter, 0, NULL, ast_id, return_id, GETTER_CALL_RETURN);
8434 bool HOptimizedGraphBuilder::TryInlineSetter(Handle<JSFunction> setter,
8435 Handle<Map> receiver_map,
8437 BailoutId assignment_id,
8438 HValue* implicit_return_value) {
8439 if (TryInlineApiSetter(setter, receiver_map, id)) return true;
8440 return TryInline(setter, 1, implicit_return_value, id, assignment_id,
8441 SETTER_CALL_RETURN);
8445 bool HOptimizedGraphBuilder::TryInlineIndirectCall(Handle<JSFunction> function,
8447 int arguments_count) {
8448 return TryInline(function, arguments_count, NULL, expr->id(),
8449 expr->ReturnId(), NORMAL_RETURN);
8453 bool HOptimizedGraphBuilder::TryInlineBuiltinFunctionCall(Call* expr) {
8454 if (!expr->target()->shared()->HasBuiltinFunctionId()) return false;
8455 BuiltinFunctionId id = expr->target()->shared()->builtin_function_id();
8458 if (!FLAG_fast_math) break;
8459 // Fall through if FLAG_fast_math.
8467 if (expr->arguments()->length() == 1) {
8468 HValue* argument = Pop();
8469 Drop(2); // Receiver and function.
8470 HInstruction* op = NewUncasted<HUnaryMathOperation>(argument, id);
8471 ast_context()->ReturnInstruction(op, expr->id());
8476 if (expr->arguments()->length() == 2) {
8477 HValue* right = Pop();
8478 HValue* left = Pop();
8479 Drop(2); // Receiver and function.
8481 HMul::NewImul(isolate(), zone(), context(), left, right);
8482 ast_context()->ReturnInstruction(op, expr->id());
8487 // Not supported for inlining yet.
8495 bool HOptimizedGraphBuilder::IsReadOnlyLengthDescriptor(
8496 Handle<Map> jsarray_map) {
8497 DCHECK(!jsarray_map->is_dictionary_map());
8498 Isolate* isolate = jsarray_map->GetIsolate();
8499 Handle<Name> length_string = isolate->factory()->length_string();
8500 DescriptorArray* descriptors = jsarray_map->instance_descriptors();
8501 int number = descriptors->SearchWithCache(*length_string, *jsarray_map);
8502 DCHECK_NE(DescriptorArray::kNotFound, number);
8503 return descriptors->GetDetails(number).IsReadOnly();
8508 bool HOptimizedGraphBuilder::CanInlineArrayResizeOperation(
8509 Handle<Map> receiver_map) {
8510 return !receiver_map.is_null() &&
8511 receiver_map->instance_type() == JS_ARRAY_TYPE &&
8512 IsFastElementsKind(receiver_map->elements_kind()) &&
8513 !receiver_map->is_dictionary_map() &&
8514 !IsReadOnlyLengthDescriptor(receiver_map) &&
8515 !receiver_map->is_observed() && receiver_map->is_extensible();
8519 bool HOptimizedGraphBuilder::TryInlineBuiltinMethodCall(
8520 Call* expr, Handle<JSFunction> function, Handle<Map> receiver_map,
8521 int args_count_no_receiver) {
8522 if (!function->shared()->HasBuiltinFunctionId()) return false;
8523 BuiltinFunctionId id = function->shared()->builtin_function_id();
8524 int argument_count = args_count_no_receiver + 1; // Plus receiver.
8526 if (receiver_map.is_null()) {
8527 HValue* receiver = environment()->ExpressionStackAt(args_count_no_receiver);
8528 if (receiver->IsConstant() &&
8529 HConstant::cast(receiver)->handle(isolate())->IsHeapObject()) {
8531 handle(Handle<HeapObject>::cast(
8532 HConstant::cast(receiver)->handle(isolate()))->map());
8535 // Try to inline calls like Math.* as operations in the calling function.
8537 case kStringCharCodeAt:
8539 if (argument_count == 2) {
8540 HValue* index = Pop();
8541 HValue* string = Pop();
8542 Drop(1); // Function.
8543 HInstruction* char_code =
8544 BuildStringCharCodeAt(string, index);
8545 if (id == kStringCharCodeAt) {
8546 ast_context()->ReturnInstruction(char_code, expr->id());
8549 AddInstruction(char_code);
8550 HInstruction* result = NewUncasted<HStringCharFromCode>(char_code);
8551 ast_context()->ReturnInstruction(result, expr->id());
8555 case kStringFromCharCode:
8556 if (argument_count == 2) {
8557 HValue* argument = Pop();
8558 Drop(2); // Receiver and function.
8559 HInstruction* result = NewUncasted<HStringCharFromCode>(argument);
8560 ast_context()->ReturnInstruction(result, expr->id());
8565 if (!FLAG_fast_math) break;
8566 // Fall through if FLAG_fast_math.
8574 if (argument_count == 2) {
8575 HValue* argument = Pop();
8576 Drop(2); // Receiver and function.
8577 HInstruction* op = NewUncasted<HUnaryMathOperation>(argument, id);
8578 ast_context()->ReturnInstruction(op, expr->id());
8583 if (argument_count == 3) {
8584 HValue* right = Pop();
8585 HValue* left = Pop();
8586 Drop(2); // Receiver and function.
8587 HInstruction* result = NULL;
8588 // Use sqrt() if exponent is 0.5 or -0.5.
8589 if (right->IsConstant() && HConstant::cast(right)->HasDoubleValue()) {
8590 double exponent = HConstant::cast(right)->DoubleValue();
8591 if (exponent == 0.5) {
8592 result = NewUncasted<HUnaryMathOperation>(left, kMathPowHalf);
8593 } else if (exponent == -0.5) {
8594 HValue* one = graph()->GetConstant1();
8595 HInstruction* sqrt = AddUncasted<HUnaryMathOperation>(
8596 left, kMathPowHalf);
8597 // MathPowHalf doesn't have side effects so there's no need for
8598 // an environment simulation here.
8599 DCHECK(!sqrt->HasObservableSideEffects());
8600 result = NewUncasted<HDiv>(one, sqrt);
8601 } else if (exponent == 2.0) {
8602 result = NewUncasted<HMul>(left, left);
8606 if (result == NULL) {
8607 result = NewUncasted<HPower>(left, right);
8609 ast_context()->ReturnInstruction(result, expr->id());
8615 if (argument_count == 3) {
8616 HValue* right = Pop();
8617 HValue* left = Pop();
8618 Drop(2); // Receiver and function.
8619 HMathMinMax::Operation op = (id == kMathMin) ? HMathMinMax::kMathMin
8620 : HMathMinMax::kMathMax;
8621 HInstruction* result = NewUncasted<HMathMinMax>(left, right, op);
8622 ast_context()->ReturnInstruction(result, expr->id());
8627 if (argument_count == 3) {
8628 HValue* right = Pop();
8629 HValue* left = Pop();
8630 Drop(2); // Receiver and function.
8631 HInstruction* result =
8632 HMul::NewImul(isolate(), zone(), context(), left, right);
8633 ast_context()->ReturnInstruction(result, expr->id());
8638 if (!CanInlineArrayResizeOperation(receiver_map)) return false;
8639 ElementsKind elements_kind = receiver_map->elements_kind();
8641 Drop(args_count_no_receiver);
8643 HValue* reduced_length;
8644 HValue* receiver = Pop();
8646 HValue* checked_object = AddCheckMap(receiver, receiver_map);
8648 Add<HLoadNamedField>(checked_object, nullptr,
8649 HObjectAccess::ForArrayLength(elements_kind));
8651 Drop(1); // Function.
8653 { NoObservableSideEffectsScope scope(this);
8654 IfBuilder length_checker(this);
8656 HValue* bounds_check = length_checker.If<HCompareNumericAndBranch>(
8657 length, graph()->GetConstant0(), Token::EQ);
8658 length_checker.Then();
8660 if (!ast_context()->IsEffect()) Push(graph()->GetConstantUndefined());
8662 length_checker.Else();
8663 HValue* elements = AddLoadElements(checked_object);
8664 // Ensure that we aren't popping from a copy-on-write array.
8665 if (IsFastSmiOrObjectElementsKind(elements_kind)) {
8666 elements = BuildCopyElementsOnWrite(checked_object, elements,
8667 elements_kind, length);
8669 reduced_length = AddUncasted<HSub>(length, graph()->GetConstant1());
8670 result = AddElementAccess(elements, reduced_length, NULL,
8671 bounds_check, elements_kind, LOAD);
8672 HValue* hole = IsFastSmiOrObjectElementsKind(elements_kind)
8673 ? graph()->GetConstantHole()
8674 : Add<HConstant>(HConstant::kHoleNaN);
8675 if (IsFastSmiOrObjectElementsKind(elements_kind)) {
8676 elements_kind = FAST_HOLEY_ELEMENTS;
8679 elements, reduced_length, hole, bounds_check, elements_kind, STORE);
8680 Add<HStoreNamedField>(
8681 checked_object, HObjectAccess::ForArrayLength(elements_kind),
8682 reduced_length, STORE_TO_INITIALIZED_ENTRY);
8684 if (!ast_context()->IsEffect()) Push(result);
8686 length_checker.End();
8688 result = ast_context()->IsEffect() ? graph()->GetConstant0() : Top();
8689 Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
8690 if (!ast_context()->IsEffect()) Drop(1);
8692 ast_context()->ReturnValue(result);
8696 if (!CanInlineArrayResizeOperation(receiver_map)) return false;
8697 ElementsKind elements_kind = receiver_map->elements_kind();
8699 // If there may be elements accessors in the prototype chain, the fast
8700 // inlined version can't be used.
8701 if (receiver_map->DictionaryElementsInPrototypeChainOnly()) return false;
8702 // If there currently can be no elements accessors on the prototype chain,
8703 // it doesn't mean that there won't be any later. Install a full prototype
8704 // chain check to trap element accessors being installed on the prototype
8705 // chain, which would cause elements to go to dictionary mode and result
8707 Handle<JSObject> prototype(JSObject::cast(receiver_map->prototype()));
8708 BuildCheckPrototypeMaps(prototype, Handle<JSObject>());
8710 // Protect against adding elements to the Array prototype, which needs to
8711 // route through appropriate bottlenecks.
8712 if (isolate()->IsFastArrayConstructorPrototypeChainIntact() &&
8713 !prototype->IsJSArray()) {
8717 const int argc = args_count_no_receiver;
8718 if (argc != 1) return false;
8720 HValue* value_to_push = Pop();
8721 HValue* array = Pop();
8722 Drop(1); // Drop function.
8724 HInstruction* new_size = NULL;
8725 HValue* length = NULL;
8728 NoObservableSideEffectsScope scope(this);
8730 length = Add<HLoadNamedField>(
8731 array, nullptr, HObjectAccess::ForArrayLength(elements_kind));
8733 new_size = AddUncasted<HAdd>(length, graph()->GetConstant1());
8735 bool is_array = receiver_map->instance_type() == JS_ARRAY_TYPE;
8736 HValue* checked_array = Add<HCheckMaps>(array, receiver_map);
8737 BuildUncheckedMonomorphicElementAccess(
8738 checked_array, length, value_to_push, is_array, elements_kind,
8739 STORE, NEVER_RETURN_HOLE, STORE_AND_GROW_NO_TRANSITION);
8741 if (!ast_context()->IsEffect()) Push(new_size);
8742 Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
8743 if (!ast_context()->IsEffect()) Drop(1);
8746 ast_context()->ReturnValue(new_size);
8750 if (!CanInlineArrayResizeOperation(receiver_map)) return false;
8751 ElementsKind kind = receiver_map->elements_kind();
8753 // If there may be elements accessors in the prototype chain, the fast
8754 // inlined version can't be used.
8755 if (receiver_map->DictionaryElementsInPrototypeChainOnly()) return false;
8757 // If there currently can be no elements accessors on the prototype chain,
8758 // it doesn't mean that there won't be any later. Install a full prototype
8759 // chain check to trap element accessors being installed on the prototype
8760 // chain, which would cause elements to go to dictionary mode and result
8762 BuildCheckPrototypeMaps(
8763 handle(JSObject::cast(receiver_map->prototype()), isolate()),
8764 Handle<JSObject>::null());
8766 // Threshold for fast inlined Array.shift().
8767 HConstant* inline_threshold = Add<HConstant>(static_cast<int32_t>(16));
8769 Drop(args_count_no_receiver);
8770 HValue* receiver = Pop();
8771 HValue* function = Pop();
8775 NoObservableSideEffectsScope scope(this);
8777 HValue* length = Add<HLoadNamedField>(
8778 receiver, nullptr, HObjectAccess::ForArrayLength(kind));
8780 IfBuilder if_lengthiszero(this);
8781 HValue* lengthiszero = if_lengthiszero.If<HCompareNumericAndBranch>(
8782 length, graph()->GetConstant0(), Token::EQ);
8783 if_lengthiszero.Then();
8785 if (!ast_context()->IsEffect()) Push(graph()->GetConstantUndefined());
8787 if_lengthiszero.Else();
8789 HValue* elements = AddLoadElements(receiver);
8791 // Check if we can use the fast inlined Array.shift().
8792 IfBuilder if_inline(this);
8793 if_inline.If<HCompareNumericAndBranch>(
8794 length, inline_threshold, Token::LTE);
8795 if (IsFastSmiOrObjectElementsKind(kind)) {
8796 // We cannot handle copy-on-write backing stores here.
8797 if_inline.AndIf<HCompareMap>(
8798 elements, isolate()->factory()->fixed_array_map());
8802 // Remember the result.
8803 if (!ast_context()->IsEffect()) {
8804 Push(AddElementAccess(elements, graph()->GetConstant0(), NULL,
8805 lengthiszero, kind, LOAD));
8808 // Compute the new length.
8809 HValue* new_length = AddUncasted<HSub>(
8810 length, graph()->GetConstant1());
8811 new_length->ClearFlag(HValue::kCanOverflow);
8813 // Copy the remaining elements.
8814 LoopBuilder loop(this, context(), LoopBuilder::kPostIncrement);
8816 HValue* new_key = loop.BeginBody(
8817 graph()->GetConstant0(), new_length, Token::LT);
8818 HValue* key = AddUncasted<HAdd>(new_key, graph()->GetConstant1());
8819 key->ClearFlag(HValue::kCanOverflow);
8820 ElementsKind copy_kind =
8821 kind == FAST_HOLEY_SMI_ELEMENTS ? FAST_HOLEY_ELEMENTS : kind;
8822 HValue* element = AddUncasted<HLoadKeyed>(
8823 elements, key, lengthiszero, copy_kind, ALLOW_RETURN_HOLE);
8824 HStoreKeyed* store =
8825 Add<HStoreKeyed>(elements, new_key, element, copy_kind);
8826 store->SetFlag(HValue::kAllowUndefinedAsNaN);
8830 // Put a hole at the end.
8831 HValue* hole = IsFastSmiOrObjectElementsKind(kind)
8832 ? graph()->GetConstantHole()
8833 : Add<HConstant>(HConstant::kHoleNaN);
8834 if (IsFastSmiOrObjectElementsKind(kind)) kind = FAST_HOLEY_ELEMENTS;
8836 elements, new_length, hole, kind, INITIALIZING_STORE);
8838 // Remember new length.
8839 Add<HStoreNamedField>(
8840 receiver, HObjectAccess::ForArrayLength(kind),
8841 new_length, STORE_TO_INITIALIZED_ENTRY);
8845 Add<HPushArguments>(receiver);
8846 result = Add<HCallJSFunction>(function, 1, true);
8847 if (!ast_context()->IsEffect()) Push(result);
8851 if_lengthiszero.End();
8853 result = ast_context()->IsEffect() ? graph()->GetConstant0() : Top();
8854 Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
8855 if (!ast_context()->IsEffect()) Drop(1);
8856 ast_context()->ReturnValue(result);
8860 case kArrayLastIndexOf: {
8861 if (receiver_map.is_null()) return false;
8862 if (receiver_map->instance_type() != JS_ARRAY_TYPE) return false;
8863 ElementsKind kind = receiver_map->elements_kind();
8864 if (!IsFastElementsKind(kind)) return false;
8865 if (receiver_map->is_observed()) return false;
8866 if (argument_count != 2) return false;
8867 if (!receiver_map->is_extensible()) return false;
8869 // If there may be elements accessors in the prototype chain, the fast
8870 // inlined version can't be used.
8871 if (receiver_map->DictionaryElementsInPrototypeChainOnly()) return false;
8873 // If there currently can be no elements accessors on the prototype chain,
8874 // it doesn't mean that there won't be any later. Install a full prototype
8875 // chain check to trap element accessors being installed on the prototype
8876 // chain, which would cause elements to go to dictionary mode and result
8878 BuildCheckPrototypeMaps(
8879 handle(JSObject::cast(receiver_map->prototype()), isolate()),
8880 Handle<JSObject>::null());
8882 HValue* search_element = Pop();
8883 HValue* receiver = Pop();
8884 Drop(1); // Drop function.
8886 ArrayIndexOfMode mode = (id == kArrayIndexOf)
8887 ? kFirstIndexOf : kLastIndexOf;
8888 HValue* index = BuildArrayIndexOf(receiver, search_element, kind, mode);
8890 if (!ast_context()->IsEffect()) Push(index);
8891 Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
8892 if (!ast_context()->IsEffect()) Drop(1);
8893 ast_context()->ReturnValue(index);
8897 // Not yet supported for inlining.
8904 bool HOptimizedGraphBuilder::TryInlineApiFunctionCall(Call* expr,
8906 Handle<JSFunction> function = expr->target();
8907 int argc = expr->arguments()->length();
8908 SmallMapList receiver_maps;
8909 return TryInlineApiCall(function,
8918 bool HOptimizedGraphBuilder::TryInlineApiMethodCall(
8921 SmallMapList* receiver_maps) {
8922 Handle<JSFunction> function = expr->target();
8923 int argc = expr->arguments()->length();
8924 return TryInlineApiCall(function,
8933 bool HOptimizedGraphBuilder::TryInlineApiGetter(Handle<JSFunction> function,
8934 Handle<Map> receiver_map,
8936 SmallMapList receiver_maps(1, zone());
8937 receiver_maps.Add(receiver_map, zone());
8938 return TryInlineApiCall(function,
8939 NULL, // Receiver is on expression stack.
8947 bool HOptimizedGraphBuilder::TryInlineApiSetter(Handle<JSFunction> function,
8948 Handle<Map> receiver_map,
8950 SmallMapList receiver_maps(1, zone());
8951 receiver_maps.Add(receiver_map, zone());
8952 return TryInlineApiCall(function,
8953 NULL, // Receiver is on expression stack.
8961 bool HOptimizedGraphBuilder::TryInlineApiCall(Handle<JSFunction> function,
8963 SmallMapList* receiver_maps,
8966 ApiCallType call_type) {
8967 if (function->context()->native_context() !=
8968 top_info()->closure()->context()->native_context()) {
8971 CallOptimization optimization(function);
8972 if (!optimization.is_simple_api_call()) return false;
8973 Handle<Map> holder_map;
8974 for (int i = 0; i < receiver_maps->length(); ++i) {
8975 auto map = receiver_maps->at(i);
8976 // Don't inline calls to receivers requiring accesschecks.
8977 if (map->is_access_check_needed()) return false;
8979 if (call_type == kCallApiFunction) {
8980 // Cannot embed a direct reference to the global proxy map
8981 // as it maybe dropped on deserialization.
8982 CHECK(!isolate()->serializer_enabled());
8983 DCHECK_EQ(0, receiver_maps->length());
8984 receiver_maps->Add(handle(function->global_proxy()->map()), zone());
8986 CallOptimization::HolderLookup holder_lookup =
8987 CallOptimization::kHolderNotFound;
8988 Handle<JSObject> api_holder = optimization.LookupHolderOfExpectedType(
8989 receiver_maps->first(), &holder_lookup);
8990 if (holder_lookup == CallOptimization::kHolderNotFound) return false;
8992 if (FLAG_trace_inlining) {
8993 PrintF("Inlining api function ");
8994 function->ShortPrint();
8998 bool is_function = false;
8999 bool is_store = false;
9000 switch (call_type) {
9001 case kCallApiFunction:
9002 case kCallApiMethod:
9003 // Need to check that none of the receiver maps could have changed.
9004 Add<HCheckMaps>(receiver, receiver_maps);
9005 // Need to ensure the chain between receiver and api_holder is intact.
9006 if (holder_lookup == CallOptimization::kHolderFound) {
9007 AddCheckPrototypeMaps(api_holder, receiver_maps->first());
9009 DCHECK_EQ(holder_lookup, CallOptimization::kHolderIsReceiver);
9011 // Includes receiver.
9012 PushArgumentsFromEnvironment(argc + 1);
9015 case kCallApiGetter:
9016 // Receiver and prototype chain cannot have changed.
9018 DCHECK_NULL(receiver);
9019 // Receiver is on expression stack.
9021 Add<HPushArguments>(receiver);
9023 case kCallApiSetter:
9026 // Receiver and prototype chain cannot have changed.
9028 DCHECK_NULL(receiver);
9029 // Receiver and value are on expression stack.
9030 HValue* value = Pop();
9032 Add<HPushArguments>(receiver, value);
9037 HValue* holder = NULL;
9038 switch (holder_lookup) {
9039 case CallOptimization::kHolderFound:
9040 holder = Add<HConstant>(api_holder);
9042 case CallOptimization::kHolderIsReceiver:
9045 case CallOptimization::kHolderNotFound:
9049 Handle<CallHandlerInfo> api_call_info = optimization.api_call_info();
9050 Handle<Object> call_data_obj(api_call_info->data(), isolate());
9051 bool call_data_undefined = call_data_obj->IsUndefined();
9052 HValue* call_data = Add<HConstant>(call_data_obj);
9053 ApiFunction fun(v8::ToCData<Address>(api_call_info->callback()));
9054 ExternalReference ref = ExternalReference(&fun,
9055 ExternalReference::DIRECT_API_CALL,
9057 HValue* api_function_address = Add<HConstant>(ExternalReference(ref));
9059 HValue* op_vals[] = {context(), Add<HConstant>(function), call_data, holder,
9060 api_function_address, nullptr};
9062 HInstruction* call = nullptr;
9064 CallApiAccessorStub stub(isolate(), is_store, call_data_undefined);
9065 Handle<Code> code = stub.GetCode();
9066 HConstant* code_value = Add<HConstant>(code);
9067 ApiAccessorDescriptor descriptor(isolate());
9068 call = New<HCallWithDescriptor>(
9069 code_value, argc + 1, descriptor,
9070 Vector<HValue*>(op_vals, arraysize(op_vals) - 1));
9071 } else if (argc <= CallApiFunctionWithFixedArgsStub::kMaxFixedArgs) {
9072 CallApiFunctionWithFixedArgsStub stub(isolate(), argc, call_data_undefined);
9073 Handle<Code> code = stub.GetCode();
9074 HConstant* code_value = Add<HConstant>(code);
9075 ApiFunctionWithFixedArgsDescriptor descriptor(isolate());
9076 call = New<HCallWithDescriptor>(
9077 code_value, argc + 1, descriptor,
9078 Vector<HValue*>(op_vals, arraysize(op_vals) - 1));
9079 Drop(1); // Drop function.
9081 op_vals[arraysize(op_vals) - 1] = Add<HConstant>(argc);
9082 CallApiFunctionStub stub(isolate(), call_data_undefined);
9083 Handle<Code> code = stub.GetCode();
9084 HConstant* code_value = Add<HConstant>(code);
9085 ApiFunctionDescriptor descriptor(isolate());
9087 New<HCallWithDescriptor>(code_value, argc + 1, descriptor,
9088 Vector<HValue*>(op_vals, arraysize(op_vals)));
9089 Drop(1); // Drop function.
9092 ast_context()->ReturnInstruction(call, ast_id);
9097 void HOptimizedGraphBuilder::HandleIndirectCall(Call* expr, HValue* function,
9098 int arguments_count) {
9099 Handle<JSFunction> known_function;
9100 int args_count_no_receiver = arguments_count - 1;
9101 if (function->IsConstant() &&
9102 HConstant::cast(function)->handle(isolate())->IsJSFunction()) {
9104 Handle<JSFunction>::cast(HConstant::cast(function)->handle(isolate()));
9105 if (TryInlineBuiltinMethodCall(expr, known_function, Handle<Map>(),
9106 args_count_no_receiver)) {
9107 if (FLAG_trace_inlining) {
9108 PrintF("Inlining builtin ");
9109 known_function->ShortPrint();
9115 if (TryInlineIndirectCall(known_function, expr, args_count_no_receiver)) {
9120 PushArgumentsFromEnvironment(arguments_count);
9121 HInvokeFunction* call =
9122 New<HInvokeFunction>(function, known_function, arguments_count);
9123 Drop(1); // Function
9124 ast_context()->ReturnInstruction(call, expr->id());
9128 bool HOptimizedGraphBuilder::TryIndirectCall(Call* expr) {
9129 DCHECK(expr->expression()->IsProperty());
9131 if (!expr->IsMonomorphic()) {
9134 Handle<Map> function_map = expr->GetReceiverTypes()->first();
9135 if (function_map->instance_type() != JS_FUNCTION_TYPE ||
9136 !expr->target()->shared()->HasBuiltinFunctionId()) {
9140 switch (expr->target()->shared()->builtin_function_id()) {
9141 case kFunctionCall: {
9142 if (expr->arguments()->length() == 0) return false;
9143 BuildFunctionCall(expr);
9146 case kFunctionApply: {
9147 // For .apply, only the pattern f.apply(receiver, arguments)
9149 if (current_info()->scope()->arguments() == NULL) return false;
9151 if (!CanBeFunctionApplyArguments(expr)) return false;
9153 BuildFunctionApply(expr);
9156 default: { return false; }
9162 void HOptimizedGraphBuilder::BuildFunctionApply(Call* expr) {
9163 ZoneList<Expression*>* args = expr->arguments();
9164 CHECK_ALIVE(VisitForValue(args->at(0)));
9165 HValue* receiver = Pop(); // receiver
9166 HValue* function = Pop(); // f
9169 Handle<Map> function_map = expr->GetReceiverTypes()->first();
9170 HValue* checked_function = AddCheckMap(function, function_map);
9172 if (function_state()->outer() == NULL) {
9173 HInstruction* elements = Add<HArgumentsElements>(false);
9174 HInstruction* length = Add<HArgumentsLength>(elements);
9175 HValue* wrapped_receiver = BuildWrapReceiver(receiver, checked_function);
9176 HInstruction* result = New<HApplyArguments>(function,
9180 ast_context()->ReturnInstruction(result, expr->id());
9182 // We are inside inlined function and we know exactly what is inside
9183 // arguments object. But we need to be able to materialize at deopt.
9184 DCHECK_EQ(environment()->arguments_environment()->parameter_count(),
9185 function_state()->entry()->arguments_object()->arguments_count());
9186 HArgumentsObject* args = function_state()->entry()->arguments_object();
9187 const ZoneList<HValue*>* arguments_values = args->arguments_values();
9188 int arguments_count = arguments_values->length();
9190 Push(BuildWrapReceiver(receiver, checked_function));
9191 for (int i = 1; i < arguments_count; i++) {
9192 Push(arguments_values->at(i));
9194 HandleIndirectCall(expr, function, arguments_count);
9200 void HOptimizedGraphBuilder::BuildFunctionCall(Call* expr) {
9201 HValue* function = Top(); // f
9202 Handle<Map> function_map = expr->GetReceiverTypes()->first();
9203 HValue* checked_function = AddCheckMap(function, function_map);
9205 // f and call are on the stack in the unoptimized code
9206 // during evaluation of the arguments.
9207 CHECK_ALIVE(VisitExpressions(expr->arguments()));
9209 int args_length = expr->arguments()->length();
9210 int receiver_index = args_length - 1;
9211 // Patch the receiver.
9212 HValue* receiver = BuildWrapReceiver(
9213 environment()->ExpressionStackAt(receiver_index), checked_function);
9214 environment()->SetExpressionStackAt(receiver_index, receiver);
9216 // Call must not be on the stack from now on.
9217 int call_index = args_length + 1;
9218 environment()->RemoveExpressionStackAt(call_index);
9220 HandleIndirectCall(expr, function, args_length);
9224 HValue* HOptimizedGraphBuilder::ImplicitReceiverFor(HValue* function,
9225 Handle<JSFunction> target) {
9226 SharedFunctionInfo* shared = target->shared();
9227 if (is_sloppy(shared->language_mode()) && !shared->native()) {
9228 // Cannot embed a direct reference to the global proxy
9229 // as is it dropped on deserialization.
9230 CHECK(!isolate()->serializer_enabled());
9231 Handle<JSObject> global_proxy(target->context()->global_proxy());
9232 return Add<HConstant>(global_proxy);
9234 return graph()->GetConstantUndefined();
9238 void HOptimizedGraphBuilder::BuildArrayCall(Expression* expression,
9239 int arguments_count,
9241 Handle<AllocationSite> site) {
9242 Add<HCheckValue>(function, array_function());
9244 if (IsCallArrayInlineable(arguments_count, site)) {
9245 BuildInlinedCallArray(expression, arguments_count, site);
9249 HInstruction* call = PreProcessCall(New<HCallNewArray>(
9250 function, arguments_count + 1, site->GetElementsKind(), site));
9251 if (expression->IsCall()) {
9254 ast_context()->ReturnInstruction(call, expression->id());
9258 HValue* HOptimizedGraphBuilder::BuildArrayIndexOf(HValue* receiver,
9259 HValue* search_element,
9261 ArrayIndexOfMode mode) {
9262 DCHECK(IsFastElementsKind(kind));
9264 NoObservableSideEffectsScope no_effects(this);
9266 HValue* elements = AddLoadElements(receiver);
9267 HValue* length = AddLoadArrayLength(receiver, kind);
9270 HValue* terminating;
9272 LoopBuilder::Direction direction;
9273 if (mode == kFirstIndexOf) {
9274 initial = graph()->GetConstant0();
9275 terminating = length;
9277 direction = LoopBuilder::kPostIncrement;
9279 DCHECK_EQ(kLastIndexOf, mode);
9281 terminating = graph()->GetConstant0();
9283 direction = LoopBuilder::kPreDecrement;
9286 Push(graph()->GetConstantMinus1());
9287 if (IsFastDoubleElementsKind(kind) || IsFastSmiElementsKind(kind)) {
9288 // Make sure that we can actually compare numbers correctly below, see
9289 // https://code.google.com/p/chromium/issues/detail?id=407946 for details.
9290 search_element = AddUncasted<HForceRepresentation>(
9291 search_element, IsFastSmiElementsKind(kind) ? Representation::Smi()
9292 : Representation::Double());
9294 LoopBuilder loop(this, context(), direction);
9296 HValue* index = loop.BeginBody(initial, terminating, token);
9297 HValue* element = AddUncasted<HLoadKeyed>(elements, index, nullptr, kind,
9299 IfBuilder if_issame(this);
9300 if_issame.If<HCompareNumericAndBranch>(element, search_element,
9312 IfBuilder if_isstring(this);
9313 if_isstring.If<HIsStringAndBranch>(search_element);
9316 LoopBuilder loop(this, context(), direction);
9318 HValue* index = loop.BeginBody(initial, terminating, token);
9319 HValue* element = AddUncasted<HLoadKeyed>(elements, index, nullptr,
9320 kind, ALLOW_RETURN_HOLE);
9321 IfBuilder if_issame(this);
9322 if_issame.If<HIsStringAndBranch>(element);
9323 if_issame.AndIf<HStringCompareAndBranch>(
9324 element, search_element, Token::EQ_STRICT);
9337 IfBuilder if_isnumber(this);
9338 if_isnumber.If<HIsSmiAndBranch>(search_element);
9339 if_isnumber.OrIf<HCompareMap>(
9340 search_element, isolate()->factory()->heap_number_map());
9343 HValue* search_number =
9344 AddUncasted<HForceRepresentation>(search_element,
9345 Representation::Double());
9346 LoopBuilder loop(this, context(), direction);
9348 HValue* index = loop.BeginBody(initial, terminating, token);
9349 HValue* element = AddUncasted<HLoadKeyed>(elements, index, nullptr,
9350 kind, ALLOW_RETURN_HOLE);
9352 IfBuilder if_element_isnumber(this);
9353 if_element_isnumber.If<HIsSmiAndBranch>(element);
9354 if_element_isnumber.OrIf<HCompareMap>(
9355 element, isolate()->factory()->heap_number_map());
9356 if_element_isnumber.Then();
9359 AddUncasted<HForceRepresentation>(element,
9360 Representation::Double());
9361 IfBuilder if_issame(this);
9362 if_issame.If<HCompareNumericAndBranch>(
9363 number, search_number, Token::EQ_STRICT);
9372 if_element_isnumber.End();
9378 LoopBuilder loop(this, context(), direction);
9380 HValue* index = loop.BeginBody(initial, terminating, token);
9381 HValue* element = AddUncasted<HLoadKeyed>(elements, index, nullptr,
9382 kind, ALLOW_RETURN_HOLE);
9383 IfBuilder if_issame(this);
9384 if_issame.If<HCompareObjectEqAndBranch>(
9385 element, search_element);
9405 bool HOptimizedGraphBuilder::TryHandleArrayCall(Call* expr, HValue* function) {
9406 if (!array_function().is_identical_to(expr->target())) {
9410 Handle<AllocationSite> site = expr->allocation_site();
9411 if (site.is_null()) return false;
9413 BuildArrayCall(expr,
9414 expr->arguments()->length(),
9421 bool HOptimizedGraphBuilder::TryHandleArrayCallNew(CallNew* expr,
9423 if (!array_function().is_identical_to(expr->target())) {
9427 Handle<AllocationSite> site = expr->allocation_site();
9428 if (site.is_null()) return false;
9430 BuildArrayCall(expr, expr->arguments()->length(), function, site);
9435 bool HOptimizedGraphBuilder::CanBeFunctionApplyArguments(Call* expr) {
9436 ZoneList<Expression*>* args = expr->arguments();
9437 if (args->length() != 2) return false;
9438 VariableProxy* arg_two = args->at(1)->AsVariableProxy();
9439 if (arg_two == NULL || !arg_two->var()->IsStackAllocated()) return false;
9440 HValue* arg_two_value = LookupAndMakeLive(arg_two->var());
9441 if (!arg_two_value->CheckFlag(HValue::kIsArguments)) return false;
9446 void HOptimizedGraphBuilder::VisitCall(Call* expr) {
9447 DCHECK(!HasStackOverflow());
9448 DCHECK(current_block() != NULL);
9449 DCHECK(current_block()->HasPredecessor());
9450 if (!top_info()->is_tracking_positions()) SetSourcePosition(expr->position());
9451 Expression* callee = expr->expression();
9452 int argument_count = expr->arguments()->length() + 1; // Plus receiver.
9453 HInstruction* call = NULL;
9455 Property* prop = callee->AsProperty();
9457 CHECK_ALIVE(VisitForValue(prop->obj()));
9458 HValue* receiver = Top();
9461 ComputeReceiverTypes(expr, receiver, &maps, zone());
9463 if (prop->key()->IsPropertyName() && maps->length() > 0) {
9464 Handle<String> name = prop->key()->AsLiteral()->AsPropertyName();
9465 PropertyAccessInfo info(this, LOAD, maps->first(), name);
9466 if (!info.CanAccessAsMonomorphic(maps)) {
9467 HandlePolymorphicCallNamed(expr, receiver, maps, name);
9472 if (!prop->key()->IsPropertyName()) {
9473 CHECK_ALIVE(VisitForValue(prop->key()));
9477 CHECK_ALIVE(PushLoad(prop, receiver, key));
9478 HValue* function = Pop();
9480 if (function->IsConstant() &&
9481 HConstant::cast(function)->handle(isolate())->IsJSFunction()) {
9482 // Push the function under the receiver.
9483 environment()->SetExpressionStackAt(0, function);
9486 Handle<JSFunction> known_function = Handle<JSFunction>::cast(
9487 HConstant::cast(function)->handle(isolate()));
9488 expr->set_target(known_function);
9490 if (TryIndirectCall(expr)) return;
9491 CHECK_ALIVE(VisitExpressions(expr->arguments()));
9493 Handle<Map> map = maps->length() == 1 ? maps->first() : Handle<Map>();
9494 if (TryInlineBuiltinMethodCall(expr, known_function, map,
9495 expr->arguments()->length())) {
9496 if (FLAG_trace_inlining) {
9497 PrintF("Inlining builtin ");
9498 known_function->ShortPrint();
9503 if (TryInlineApiMethodCall(expr, receiver, maps)) return;
9505 // Wrap the receiver if necessary.
9506 if (NeedsWrapping(maps->first(), known_function)) {
9507 // Since HWrapReceiver currently cannot actually wrap numbers and
9508 // strings, use the regular CallFunctionStub for method calls to wrap
9510 // TODO(verwaest): Support creation of value wrappers directly in
9512 call = New<HCallFunction>(
9513 function, argument_count, WRAP_AND_CALL);
9514 } else if (TryInlineCall(expr)) {
9517 call = BuildCallConstantFunction(known_function, argument_count);
9521 ArgumentsAllowedFlag arguments_flag = ARGUMENTS_NOT_ALLOWED;
9522 if (CanBeFunctionApplyArguments(expr) && expr->is_uninitialized()) {
9523 // We have to use EAGER deoptimization here because Deoptimizer::SOFT
9524 // gets ignored by the always-opt flag, which leads to incorrect code.
9526 Deoptimizer::kInsufficientTypeFeedbackForCallWithArguments,
9527 Deoptimizer::EAGER);
9528 arguments_flag = ARGUMENTS_FAKED;
9531 // Push the function under the receiver.
9532 environment()->SetExpressionStackAt(0, function);
9535 CHECK_ALIVE(VisitExpressions(expr->arguments(), arguments_flag));
9536 CallFunctionFlags flags = receiver->type().IsJSObject()
9537 ? NO_CALL_FUNCTION_FLAGS : CALL_AS_METHOD;
9538 call = New<HCallFunction>(function, argument_count, flags);
9540 PushArgumentsFromEnvironment(argument_count);
9543 VariableProxy* proxy = expr->expression()->AsVariableProxy();
9544 if (proxy != NULL && proxy->var()->is_possibly_eval(isolate())) {
9545 return Bailout(kPossibleDirectCallToEval);
9548 // The function is on the stack in the unoptimized code during
9549 // evaluation of the arguments.
9550 CHECK_ALIVE(VisitForValue(expr->expression()));
9551 HValue* function = Top();
9552 if (function->IsConstant() &&
9553 HConstant::cast(function)->handle(isolate())->IsJSFunction()) {
9554 Handle<Object> constant = HConstant::cast(function)->handle(isolate());
9555 Handle<JSFunction> target = Handle<JSFunction>::cast(constant);
9556 expr->SetKnownGlobalTarget(target);
9559 // Placeholder for the receiver.
9560 Push(graph()->GetConstantUndefined());
9561 CHECK_ALIVE(VisitExpressions(expr->arguments()));
9563 if (expr->IsMonomorphic()) {
9564 Add<HCheckValue>(function, expr->target());
9566 // Patch the global object on the stack by the expected receiver.
9567 HValue* receiver = ImplicitReceiverFor(function, expr->target());
9568 const int receiver_index = argument_count - 1;
9569 environment()->SetExpressionStackAt(receiver_index, receiver);
9571 if (TryInlineBuiltinFunctionCall(expr)) {
9572 if (FLAG_trace_inlining) {
9573 PrintF("Inlining builtin ");
9574 expr->target()->ShortPrint();
9579 if (TryInlineApiFunctionCall(expr, receiver)) return;
9580 if (TryHandleArrayCall(expr, function)) return;
9581 if (TryInlineCall(expr)) return;
9583 PushArgumentsFromEnvironment(argument_count);
9584 call = BuildCallConstantFunction(expr->target(), argument_count);
9586 PushArgumentsFromEnvironment(argument_count);
9587 HCallFunction* call_function =
9588 New<HCallFunction>(function, argument_count);
9589 call = call_function;
9590 if (expr->is_uninitialized() &&
9591 expr->IsUsingCallFeedbackICSlot(isolate())) {
9592 // We've never seen this call before, so let's have Crankshaft learn
9593 // through the type vector.
9594 Handle<TypeFeedbackVector> vector =
9595 handle(current_feedback_vector(), isolate());
9596 FeedbackVectorICSlot slot = expr->CallFeedbackICSlot();
9597 call_function->SetVectorAndSlot(vector, slot);
9602 Drop(1); // Drop the function.
9603 return ast_context()->ReturnInstruction(call, expr->id());
9607 void HOptimizedGraphBuilder::BuildInlinedCallArray(
9608 Expression* expression,
9610 Handle<AllocationSite> site) {
9611 DCHECK(!site.is_null());
9612 DCHECK(argument_count >= 0 && argument_count <= 1);
9613 NoObservableSideEffectsScope no_effects(this);
9615 // We should at least have the constructor on the expression stack.
9616 HValue* constructor = environment()->ExpressionStackAt(argument_count);
9618 // Register on the site for deoptimization if the transition feedback changes.
9619 top_info()->dependencies()->AssumeTransitionStable(site);
9620 ElementsKind kind = site->GetElementsKind();
9621 HInstruction* site_instruction = Add<HConstant>(site);
9623 // In the single constant argument case, we may have to adjust elements kind
9624 // to avoid creating a packed non-empty array.
9625 if (argument_count == 1 && !IsHoleyElementsKind(kind)) {
9626 HValue* argument = environment()->Top();
9627 if (argument->IsConstant()) {
9628 HConstant* constant_argument = HConstant::cast(argument);
9629 DCHECK(constant_argument->HasSmiValue());
9630 int constant_array_size = constant_argument->Integer32Value();
9631 if (constant_array_size != 0) {
9632 kind = GetHoleyElementsKind(kind);
9638 JSArrayBuilder array_builder(this,
9642 DISABLE_ALLOCATION_SITES);
9643 HValue* new_object = argument_count == 0
9644 ? array_builder.AllocateEmptyArray()
9645 : BuildAllocateArrayFromLength(&array_builder, Top());
9647 int args_to_drop = argument_count + (expression->IsCall() ? 2 : 1);
9649 ast_context()->ReturnValue(new_object);
9653 // Checks whether allocation using the given constructor can be inlined.
9654 static bool IsAllocationInlineable(Handle<JSFunction> constructor) {
9655 return constructor->has_initial_map() &&
9656 constructor->initial_map()->instance_type() == JS_OBJECT_TYPE &&
9657 constructor->initial_map()->instance_size() <
9658 HAllocate::kMaxInlineSize;
9662 bool HOptimizedGraphBuilder::IsCallArrayInlineable(
9664 Handle<AllocationSite> site) {
9665 Handle<JSFunction> caller = current_info()->closure();
9666 Handle<JSFunction> target = array_function();
9667 // We should have the function plus array arguments on the environment stack.
9668 DCHECK(environment()->length() >= (argument_count + 1));
9669 DCHECK(!site.is_null());
9671 bool inline_ok = false;
9672 if (site->CanInlineCall()) {
9673 // We also want to avoid inlining in certain 1 argument scenarios.
9674 if (argument_count == 1) {
9675 HValue* argument = Top();
9676 if (argument->IsConstant()) {
9677 // Do not inline if the constant length argument is not a smi or
9678 // outside the valid range for unrolled loop initialization.
9679 HConstant* constant_argument = HConstant::cast(argument);
9680 if (constant_argument->HasSmiValue()) {
9681 int value = constant_argument->Integer32Value();
9682 inline_ok = value >= 0 && value <= kElementLoopUnrollThreshold;
9684 TraceInline(target, caller,
9685 "Constant length outside of valid inlining range.");
9689 TraceInline(target, caller,
9690 "Dont inline [new] Array(n) where n isn't constant.");
9692 } else if (argument_count == 0) {
9695 TraceInline(target, caller, "Too many arguments to inline.");
9698 TraceInline(target, caller, "AllocationSite requested no inlining.");
9702 TraceInline(target, caller, NULL);
9708 void HOptimizedGraphBuilder::VisitCallNew(CallNew* expr) {
9709 DCHECK(!HasStackOverflow());
9710 DCHECK(current_block() != NULL);
9711 DCHECK(current_block()->HasPredecessor());
9712 if (!top_info()->is_tracking_positions()) SetSourcePosition(expr->position());
9713 int argument_count = expr->arguments()->length() + 1; // Plus constructor.
9714 Factory* factory = isolate()->factory();
9716 // The constructor function is on the stack in the unoptimized code
9717 // during evaluation of the arguments.
9718 CHECK_ALIVE(VisitForValue(expr->expression()));
9719 HValue* function = Top();
9720 CHECK_ALIVE(VisitExpressions(expr->arguments()));
9722 if (function->IsConstant() &&
9723 HConstant::cast(function)->handle(isolate())->IsJSFunction()) {
9724 Handle<Object> constant = HConstant::cast(function)->handle(isolate());
9725 expr->SetKnownGlobalTarget(Handle<JSFunction>::cast(constant));
9728 if (FLAG_inline_construct &&
9729 expr->IsMonomorphic() &&
9730 IsAllocationInlineable(expr->target())) {
9731 Handle<JSFunction> constructor = expr->target();
9732 HValue* check = Add<HCheckValue>(function, constructor);
9734 // Force completion of inobject slack tracking before generating
9735 // allocation code to finalize instance size.
9736 if (constructor->IsInobjectSlackTrackingInProgress()) {
9737 constructor->CompleteInobjectSlackTracking();
9740 // Calculate instance size from initial map of constructor.
9741 DCHECK(constructor->has_initial_map());
9742 Handle<Map> initial_map(constructor->initial_map());
9743 int instance_size = initial_map->instance_size();
9745 // Allocate an instance of the implicit receiver object.
9746 HValue* size_in_bytes = Add<HConstant>(instance_size);
9747 HAllocationMode allocation_mode;
9748 if (FLAG_pretenuring_call_new) {
9749 if (FLAG_allocation_site_pretenuring) {
9750 // Try to use pretenuring feedback.
9751 Handle<AllocationSite> allocation_site = expr->allocation_site();
9752 allocation_mode = HAllocationMode(allocation_site);
9753 // Take a dependency on allocation site.
9754 top_info()->dependencies()->AssumeTenuringDecision(allocation_site);
9758 HAllocate* receiver = BuildAllocate(
9759 size_in_bytes, HType::JSObject(), JS_OBJECT_TYPE, allocation_mode);
9760 receiver->set_known_initial_map(initial_map);
9762 // Initialize map and fields of the newly allocated object.
9763 { NoObservableSideEffectsScope no_effects(this);
9764 DCHECK(initial_map->instance_type() == JS_OBJECT_TYPE);
9765 Add<HStoreNamedField>(receiver,
9766 HObjectAccess::ForMapAndOffset(initial_map, JSObject::kMapOffset),
9767 Add<HConstant>(initial_map));
9768 HValue* empty_fixed_array = Add<HConstant>(factory->empty_fixed_array());
9769 Add<HStoreNamedField>(receiver,
9770 HObjectAccess::ForMapAndOffset(initial_map,
9771 JSObject::kPropertiesOffset),
9773 Add<HStoreNamedField>(receiver,
9774 HObjectAccess::ForMapAndOffset(initial_map,
9775 JSObject::kElementsOffset),
9777 BuildInitializeInobjectProperties(receiver, initial_map);
9780 // Replace the constructor function with a newly allocated receiver using
9781 // the index of the receiver from the top of the expression stack.
9782 const int receiver_index = argument_count - 1;
9783 DCHECK(environment()->ExpressionStackAt(receiver_index) == function);
9784 environment()->SetExpressionStackAt(receiver_index, receiver);
9786 if (TryInlineConstruct(expr, receiver)) {
9787 // Inlining worked, add a dependency on the initial map to make sure that
9788 // this code is deoptimized whenever the initial map of the constructor
9790 top_info()->dependencies()->AssumeInitialMapCantChange(initial_map);
9794 // TODO(mstarzinger): For now we remove the previous HAllocate and all
9795 // corresponding instructions and instead add HPushArguments for the
9796 // arguments in case inlining failed. What we actually should do is for
9797 // inlining to try to build a subgraph without mutating the parent graph.
9798 HInstruction* instr = current_block()->last();
9800 HInstruction* prev_instr = instr->previous();
9801 instr->DeleteAndReplaceWith(NULL);
9803 } while (instr != check);
9804 environment()->SetExpressionStackAt(receiver_index, function);
9805 HInstruction* call =
9806 PreProcessCall(New<HCallNew>(function, argument_count));
9807 return ast_context()->ReturnInstruction(call, expr->id());
9809 // The constructor function is both an operand to the instruction and an
9810 // argument to the construct call.
9811 if (TryHandleArrayCallNew(expr, function)) return;
9813 HInstruction* call =
9814 PreProcessCall(New<HCallNew>(function, argument_count));
9815 return ast_context()->ReturnInstruction(call, expr->id());
9820 void HOptimizedGraphBuilder::BuildInitializeInobjectProperties(
9821 HValue* receiver, Handle<Map> initial_map) {
9822 if (initial_map->inobject_properties() != 0) {
9823 HConstant* undefined = graph()->GetConstantUndefined();
9824 for (int i = 0; i < initial_map->inobject_properties(); i++) {
9825 int property_offset = initial_map->GetInObjectPropertyOffset(i);
9826 Add<HStoreNamedField>(receiver, HObjectAccess::ForMapAndOffset(
9827 initial_map, property_offset),
9834 HValue* HGraphBuilder::BuildAllocateEmptyArrayBuffer(HValue* byte_length) {
9835 // We HForceRepresentation here to avoid allocations during an *-to-tagged
9836 // HChange that could cause GC while the array buffer object is not fully
9838 HObjectAccess byte_length_access(HObjectAccess::ForJSArrayBufferByteLength());
9839 byte_length = AddUncasted<HForceRepresentation>(
9840 byte_length, byte_length_access.representation());
9842 BuildAllocate(Add<HConstant>(JSArrayBuffer::kSizeWithInternalFields),
9843 HType::JSObject(), JS_ARRAY_BUFFER_TYPE, HAllocationMode());
9845 HValue* global_object = Add<HLoadNamedField>(
9847 HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
9848 HValue* native_context = Add<HLoadNamedField>(
9849 global_object, nullptr, HObjectAccess::ForGlobalObjectNativeContext());
9850 Add<HStoreNamedField>(
9851 result, HObjectAccess::ForMap(),
9852 Add<HLoadNamedField>(
9853 native_context, nullptr,
9854 HObjectAccess::ForContextSlot(Context::ARRAY_BUFFER_MAP_INDEX)));
9856 HConstant* empty_fixed_array =
9857 Add<HConstant>(isolate()->factory()->empty_fixed_array());
9858 Add<HStoreNamedField>(
9859 result, HObjectAccess::ForJSArrayOffset(JSArray::kPropertiesOffset),
9861 Add<HStoreNamedField>(
9862 result, HObjectAccess::ForJSArrayOffset(JSArray::kElementsOffset),
9864 Add<HStoreNamedField>(
9865 result, HObjectAccess::ForJSArrayBufferBackingStore().WithRepresentation(
9866 Representation::Smi()),
9867 graph()->GetConstant0());
9868 Add<HStoreNamedField>(result, byte_length_access, byte_length);
9869 Add<HStoreNamedField>(result, HObjectAccess::ForJSArrayBufferBitFieldSlot(),
9870 graph()->GetConstant0());
9871 Add<HStoreNamedField>(
9872 result, HObjectAccess::ForJSArrayBufferBitField(),
9873 Add<HConstant>((1 << JSArrayBuffer::IsExternal::kShift) |
9874 (1 << JSArrayBuffer::IsNeuterable::kShift)));
9876 for (int field = 0; field < v8::ArrayBuffer::kInternalFieldCount; ++field) {
9877 Add<HStoreNamedField>(
9879 HObjectAccess::ForObservableJSObjectOffset(
9880 JSArrayBuffer::kSize + field * kPointerSize, Representation::Smi()),
9881 graph()->GetConstant0());
9888 template <class ViewClass>
9889 void HGraphBuilder::BuildArrayBufferViewInitialization(
9892 HValue* byte_offset,
9893 HValue* byte_length) {
9895 for (int offset = ViewClass::kSize;
9896 offset < ViewClass::kSizeWithInternalFields;
9897 offset += kPointerSize) {
9898 Add<HStoreNamedField>(obj,
9899 HObjectAccess::ForObservableJSObjectOffset(offset),
9900 graph()->GetConstant0());
9903 Add<HStoreNamedField>(
9905 HObjectAccess::ForJSArrayBufferViewByteOffset(),
9907 Add<HStoreNamedField>(
9909 HObjectAccess::ForJSArrayBufferViewByteLength(),
9911 Add<HStoreNamedField>(obj, HObjectAccess::ForJSArrayBufferViewBuffer(),
9916 void HOptimizedGraphBuilder::GenerateDataViewInitialize(
9917 CallRuntime* expr) {
9918 ZoneList<Expression*>* arguments = expr->arguments();
9920 DCHECK(arguments->length()== 4);
9921 CHECK_ALIVE(VisitForValue(arguments->at(0)));
9922 HValue* obj = Pop();
9924 CHECK_ALIVE(VisitForValue(arguments->at(1)));
9925 HValue* buffer = Pop();
9927 CHECK_ALIVE(VisitForValue(arguments->at(2)));
9928 HValue* byte_offset = Pop();
9930 CHECK_ALIVE(VisitForValue(arguments->at(3)));
9931 HValue* byte_length = Pop();
9934 NoObservableSideEffectsScope scope(this);
9935 BuildArrayBufferViewInitialization<JSDataView>(
9936 obj, buffer, byte_offset, byte_length);
9941 static Handle<Map> TypedArrayMap(Isolate* isolate,
9942 ExternalArrayType array_type,
9943 ElementsKind target_kind) {
9944 Handle<Context> native_context = isolate->native_context();
9945 Handle<JSFunction> fun;
9946 switch (array_type) {
9947 #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
9948 case kExternal##Type##Array: \
9949 fun = Handle<JSFunction>(native_context->type##_array_fun()); \
9952 TYPED_ARRAYS(TYPED_ARRAY_CASE)
9953 #undef TYPED_ARRAY_CASE
9955 Handle<Map> map(fun->initial_map());
9956 return Map::AsElementsKind(map, target_kind);
9960 HValue* HOptimizedGraphBuilder::BuildAllocateExternalElements(
9961 ExternalArrayType array_type,
9962 bool is_zero_byte_offset,
9963 HValue* buffer, HValue* byte_offset, HValue* length) {
9964 Handle<Map> external_array_map(
9965 isolate()->heap()->MapForFixedTypedArray(array_type));
9967 // The HForceRepresentation is to prevent possible deopt on int-smi
9968 // conversion after allocation but before the new object fields are set.
9969 length = AddUncasted<HForceRepresentation>(length, Representation::Smi());
9970 HValue* elements = Add<HAllocate>(
9971 Add<HConstant>(FixedTypedArrayBase::kHeaderSize), HType::HeapObject(),
9972 NOT_TENURED, external_array_map->instance_type());
9974 AddStoreMapConstant(elements, external_array_map);
9975 Add<HStoreNamedField>(elements,
9976 HObjectAccess::ForFixedArrayLength(), length);
9978 HValue* backing_store = Add<HLoadNamedField>(
9979 buffer, nullptr, HObjectAccess::ForJSArrayBufferBackingStore());
9981 HValue* typed_array_start;
9982 if (is_zero_byte_offset) {
9983 typed_array_start = backing_store;
9985 HInstruction* external_pointer =
9986 AddUncasted<HAdd>(backing_store, byte_offset);
9987 // Arguments are checked prior to call to TypedArrayInitialize,
9988 // including byte_offset.
9989 external_pointer->ClearFlag(HValue::kCanOverflow);
9990 typed_array_start = external_pointer;
9993 Add<HStoreNamedField>(elements,
9994 HObjectAccess::ForFixedTypedArrayBaseBasePointer(),
9995 graph()->GetConstant0());
9996 Add<HStoreNamedField>(elements,
9997 HObjectAccess::ForFixedTypedArrayBaseExternalPointer(),
10004 HValue* HOptimizedGraphBuilder::BuildAllocateFixedTypedArray(
10005 ExternalArrayType array_type, size_t element_size,
10006 ElementsKind fixed_elements_kind, HValue* byte_length, HValue* length,
10009 (FixedTypedArrayBase::kHeaderSize & kObjectAlignmentMask) == 0);
10010 HValue* total_size;
10012 // if fixed array's elements are not aligned to object's alignment,
10013 // we need to align the whole array to object alignment.
10014 if (element_size % kObjectAlignment != 0) {
10015 total_size = BuildObjectSizeAlignment(
10016 byte_length, FixedTypedArrayBase::kHeaderSize);
10018 total_size = AddUncasted<HAdd>(byte_length,
10019 Add<HConstant>(FixedTypedArrayBase::kHeaderSize));
10020 total_size->ClearFlag(HValue::kCanOverflow);
10023 // The HForceRepresentation is to prevent possible deopt on int-smi
10024 // conversion after allocation but before the new object fields are set.
10025 length = AddUncasted<HForceRepresentation>(length, Representation::Smi());
10026 Handle<Map> fixed_typed_array_map(
10027 isolate()->heap()->MapForFixedTypedArray(array_type));
10028 HAllocate* elements =
10029 Add<HAllocate>(total_size, HType::HeapObject(), NOT_TENURED,
10030 fixed_typed_array_map->instance_type());
10032 #ifndef V8_HOST_ARCH_64_BIT
10033 if (array_type == kExternalFloat64Array) {
10034 elements->MakeDoubleAligned();
10038 AddStoreMapConstant(elements, fixed_typed_array_map);
10040 Add<HStoreNamedField>(elements,
10041 HObjectAccess::ForFixedArrayLength(),
10043 Add<HStoreNamedField>(
10044 elements, HObjectAccess::ForFixedTypedArrayBaseBasePointer(), elements);
10046 Add<HStoreNamedField>(
10047 elements, HObjectAccess::ForFixedTypedArrayBaseExternalPointer(),
10048 Add<HConstant>(ExternalReference::fixed_typed_array_base_data_offset()));
10050 HValue* filler = Add<HConstant>(static_cast<int32_t>(0));
10053 LoopBuilder builder(this, context(), LoopBuilder::kPostIncrement);
10055 HValue* backing_store = AddUncasted<HAdd>(
10056 Add<HConstant>(ExternalReference::fixed_typed_array_base_data_offset()),
10057 elements, Strength::WEAK, AddOfExternalAndTagged);
10059 HValue* key = builder.BeginBody(
10060 Add<HConstant>(static_cast<int32_t>(0)),
10061 length, Token::LT);
10062 Add<HStoreKeyed>(backing_store, key, filler, fixed_elements_kind);
10070 void HOptimizedGraphBuilder::GenerateTypedArrayInitialize(
10071 CallRuntime* expr) {
10072 ZoneList<Expression*>* arguments = expr->arguments();
10074 static const int kObjectArg = 0;
10075 static const int kArrayIdArg = 1;
10076 static const int kBufferArg = 2;
10077 static const int kByteOffsetArg = 3;
10078 static const int kByteLengthArg = 4;
10079 static const int kInitializeArg = 5;
10080 static const int kArgsLength = 6;
10081 DCHECK(arguments->length() == kArgsLength);
10084 CHECK_ALIVE(VisitForValue(arguments->at(kObjectArg)));
10085 HValue* obj = Pop();
10087 if (!arguments->at(kArrayIdArg)->IsLiteral()) {
10088 // This should never happen in real use, but can happen when fuzzing.
10090 Bailout(kNeedSmiLiteral);
10093 Handle<Object> value =
10094 static_cast<Literal*>(arguments->at(kArrayIdArg))->value();
10095 if (!value->IsSmi()) {
10096 // This should never happen in real use, but can happen when fuzzing.
10098 Bailout(kNeedSmiLiteral);
10101 int array_id = Smi::cast(*value)->value();
10104 if (!arguments->at(kBufferArg)->IsNullLiteral()) {
10105 CHECK_ALIVE(VisitForValue(arguments->at(kBufferArg)));
10111 HValue* byte_offset;
10112 bool is_zero_byte_offset;
10114 if (arguments->at(kByteOffsetArg)->IsLiteral()
10115 && Smi::FromInt(0) ==
10116 *static_cast<Literal*>(arguments->at(kByteOffsetArg))->value()) {
10117 byte_offset = Add<HConstant>(static_cast<int32_t>(0));
10118 is_zero_byte_offset = true;
10120 CHECK_ALIVE(VisitForValue(arguments->at(kByteOffsetArg)));
10121 byte_offset = Pop();
10122 is_zero_byte_offset = false;
10123 DCHECK(buffer != NULL);
10126 CHECK_ALIVE(VisitForValue(arguments->at(kByteLengthArg)));
10127 HValue* byte_length = Pop();
10129 CHECK(arguments->at(kInitializeArg)->IsLiteral());
10130 bool initialize = static_cast<Literal*>(arguments->at(kInitializeArg))
10134 NoObservableSideEffectsScope scope(this);
10135 IfBuilder byte_offset_smi(this);
10137 if (!is_zero_byte_offset) {
10138 byte_offset_smi.If<HIsSmiAndBranch>(byte_offset);
10139 byte_offset_smi.Then();
10142 ExternalArrayType array_type =
10143 kExternalInt8Array; // Bogus initialization.
10144 size_t element_size = 1; // Bogus initialization.
10145 ElementsKind fixed_elements_kind = // Bogus initialization.
10147 Runtime::ArrayIdToTypeAndSize(array_id,
10149 &fixed_elements_kind,
10153 { // byte_offset is Smi.
10154 HValue* allocated_buffer = buffer;
10155 if (buffer == NULL) {
10156 allocated_buffer = BuildAllocateEmptyArrayBuffer(byte_length);
10158 BuildArrayBufferViewInitialization<JSTypedArray>(obj, allocated_buffer,
10159 byte_offset, byte_length);
10162 HInstruction* length = AddUncasted<HDiv>(byte_length,
10163 Add<HConstant>(static_cast<int32_t>(element_size)));
10165 Add<HStoreNamedField>(obj,
10166 HObjectAccess::ForJSTypedArrayLength(),
10170 if (buffer != NULL) {
10171 elements = BuildAllocateExternalElements(
10172 array_type, is_zero_byte_offset, buffer, byte_offset, length);
10173 Handle<Map> obj_map =
10174 TypedArrayMap(isolate(), array_type, fixed_elements_kind);
10175 AddStoreMapConstant(obj, obj_map);
10177 DCHECK(is_zero_byte_offset);
10178 elements = BuildAllocateFixedTypedArray(array_type, element_size,
10179 fixed_elements_kind, byte_length,
10180 length, initialize);
10182 Add<HStoreNamedField>(
10183 obj, HObjectAccess::ForElementsPointer(), elements);
10186 if (!is_zero_byte_offset) {
10187 byte_offset_smi.Else();
10188 { // byte_offset is not Smi.
10190 CHECK_ALIVE(VisitForValue(arguments->at(kArrayIdArg)));
10194 CHECK_ALIVE(VisitForValue(arguments->at(kInitializeArg)));
10195 PushArgumentsFromEnvironment(kArgsLength);
10196 Add<HCallRuntime>(expr->name(), expr->function(), kArgsLength);
10199 byte_offset_smi.End();
10203 void HOptimizedGraphBuilder::GenerateMaxSmi(CallRuntime* expr) {
10204 DCHECK(expr->arguments()->length() == 0);
10205 HConstant* max_smi = New<HConstant>(static_cast<int32_t>(Smi::kMaxValue));
10206 return ast_context()->ReturnInstruction(max_smi, expr->id());
10210 void HOptimizedGraphBuilder::GenerateTypedArrayMaxSizeInHeap(
10211 CallRuntime* expr) {
10212 DCHECK(expr->arguments()->length() == 0);
10213 HConstant* result = New<HConstant>(static_cast<int32_t>(
10214 FLAG_typed_array_max_size_in_heap));
10215 return ast_context()->ReturnInstruction(result, expr->id());
10219 void HOptimizedGraphBuilder::GenerateArrayBufferGetByteLength(
10220 CallRuntime* expr) {
10221 DCHECK(expr->arguments()->length() == 1);
10222 CHECK_ALIVE(VisitForValue(expr->arguments()->at(0)));
10223 HValue* buffer = Pop();
10224 HInstruction* result = New<HLoadNamedField>(
10225 buffer, nullptr, HObjectAccess::ForJSArrayBufferByteLength());
10226 return ast_context()->ReturnInstruction(result, expr->id());
10230 void HOptimizedGraphBuilder::GenerateArrayBufferViewGetByteLength(
10231 CallRuntime* expr) {
10232 NoObservableSideEffectsScope scope(this);
10233 DCHECK(expr->arguments()->length() == 1);
10234 CHECK_ALIVE(VisitForValue(expr->arguments()->at(0)));
10235 HValue* view = Pop();
10237 return ast_context()->ReturnValue(BuildArrayBufferViewFieldAccessor(
10239 FieldIndex::ForInObjectOffset(JSArrayBufferView::kByteLengthOffset)));
10243 void HOptimizedGraphBuilder::GenerateArrayBufferViewGetByteOffset(
10244 CallRuntime* expr) {
10245 NoObservableSideEffectsScope scope(this);
10246 DCHECK(expr->arguments()->length() == 1);
10247 CHECK_ALIVE(VisitForValue(expr->arguments()->at(0)));
10248 HValue* view = Pop();
10250 return ast_context()->ReturnValue(BuildArrayBufferViewFieldAccessor(
10252 FieldIndex::ForInObjectOffset(JSArrayBufferView::kByteOffsetOffset)));
10256 void HOptimizedGraphBuilder::GenerateTypedArrayGetLength(
10257 CallRuntime* expr) {
10258 NoObservableSideEffectsScope scope(this);
10259 DCHECK(expr->arguments()->length() == 1);
10260 CHECK_ALIVE(VisitForValue(expr->arguments()->at(0)));
10261 HValue* view = Pop();
10263 return ast_context()->ReturnValue(BuildArrayBufferViewFieldAccessor(
10265 FieldIndex::ForInObjectOffset(JSTypedArray::kLengthOffset)));
10269 void HOptimizedGraphBuilder::VisitCallRuntime(CallRuntime* expr) {
10270 DCHECK(!HasStackOverflow());
10271 DCHECK(current_block() != NULL);
10272 DCHECK(current_block()->HasPredecessor());
10273 if (expr->is_jsruntime()) {
10274 return Bailout(kCallToAJavaScriptRuntimeFunction);
10277 const Runtime::Function* function = expr->function();
10278 DCHECK(function != NULL);
10279 switch (function->function_id) {
10280 #define CALL_INTRINSIC_GENERATOR(Name) \
10281 case Runtime::kInline##Name: \
10282 return Generate##Name(expr);
10284 FOR_EACH_HYDROGEN_INTRINSIC(CALL_INTRINSIC_GENERATOR)
10285 #undef CALL_INTRINSIC_GENERATOR
10287 Handle<String> name = expr->name();
10288 int argument_count = expr->arguments()->length();
10289 CHECK_ALIVE(VisitExpressions(expr->arguments()));
10290 PushArgumentsFromEnvironment(argument_count);
10291 HCallRuntime* call = New<HCallRuntime>(name, function, argument_count);
10292 return ast_context()->ReturnInstruction(call, expr->id());
10298 void HOptimizedGraphBuilder::VisitUnaryOperation(UnaryOperation* expr) {
10299 DCHECK(!HasStackOverflow());
10300 DCHECK(current_block() != NULL);
10301 DCHECK(current_block()->HasPredecessor());
10302 switch (expr->op()) {
10303 case Token::DELETE: return VisitDelete(expr);
10304 case Token::VOID: return VisitVoid(expr);
10305 case Token::TYPEOF: return VisitTypeof(expr);
10306 case Token::NOT: return VisitNot(expr);
10307 default: UNREACHABLE();
10312 void HOptimizedGraphBuilder::VisitDelete(UnaryOperation* expr) {
10313 Property* prop = expr->expression()->AsProperty();
10314 VariableProxy* proxy = expr->expression()->AsVariableProxy();
10315 if (prop != NULL) {
10316 CHECK_ALIVE(VisitForValue(prop->obj()));
10317 CHECK_ALIVE(VisitForValue(prop->key()));
10318 HValue* key = Pop();
10319 HValue* obj = Pop();
10320 HValue* function = AddLoadJSBuiltin(Builtins::DELETE);
10321 Add<HPushArguments>(obj, key, Add<HConstant>(function_language_mode()));
10322 // TODO(olivf) InvokeFunction produces a check for the parameter count,
10323 // even though we are certain to pass the correct number of arguments here.
10324 HInstruction* instr = New<HInvokeFunction>(function, 3);
10325 return ast_context()->ReturnInstruction(instr, expr->id());
10326 } else if (proxy != NULL) {
10327 Variable* var = proxy->var();
10328 if (var->IsUnallocatedOrGlobalSlot()) {
10329 Bailout(kDeleteWithGlobalVariable);
10330 } else if (var->IsStackAllocated() || var->IsContextSlot()) {
10331 // Result of deleting non-global variables is false. 'this' is not really
10332 // a variable, though we implement it as one. The subexpression does not
10333 // have side effects.
10334 HValue* value = var->HasThisName(isolate()) ? graph()->GetConstantTrue()
10335 : graph()->GetConstantFalse();
10336 return ast_context()->ReturnValue(value);
10338 Bailout(kDeleteWithNonGlobalVariable);
10341 // Result of deleting non-property, non-variable reference is true.
10342 // Evaluate the subexpression for side effects.
10343 CHECK_ALIVE(VisitForEffect(expr->expression()));
10344 return ast_context()->ReturnValue(graph()->GetConstantTrue());
10349 void HOptimizedGraphBuilder::VisitVoid(UnaryOperation* expr) {
10350 CHECK_ALIVE(VisitForEffect(expr->expression()));
10351 return ast_context()->ReturnValue(graph()->GetConstantUndefined());
10355 void HOptimizedGraphBuilder::VisitTypeof(UnaryOperation* expr) {
10356 CHECK_ALIVE(VisitForTypeOf(expr->expression()));
10357 HValue* value = Pop();
10358 HInstruction* instr = New<HTypeof>(value);
10359 return ast_context()->ReturnInstruction(instr, expr->id());
10363 void HOptimizedGraphBuilder::VisitNot(UnaryOperation* expr) {
10364 if (ast_context()->IsTest()) {
10365 TestContext* context = TestContext::cast(ast_context());
10366 VisitForControl(expr->expression(),
10367 context->if_false(),
10368 context->if_true());
10372 if (ast_context()->IsEffect()) {
10373 VisitForEffect(expr->expression());
10377 DCHECK(ast_context()->IsValue());
10378 HBasicBlock* materialize_false = graph()->CreateBasicBlock();
10379 HBasicBlock* materialize_true = graph()->CreateBasicBlock();
10380 CHECK_BAILOUT(VisitForControl(expr->expression(),
10382 materialize_true));
10384 if (materialize_false->HasPredecessor()) {
10385 materialize_false->SetJoinId(expr->MaterializeFalseId());
10386 set_current_block(materialize_false);
10387 Push(graph()->GetConstantFalse());
10389 materialize_false = NULL;
10392 if (materialize_true->HasPredecessor()) {
10393 materialize_true->SetJoinId(expr->MaterializeTrueId());
10394 set_current_block(materialize_true);
10395 Push(graph()->GetConstantTrue());
10397 materialize_true = NULL;
10400 HBasicBlock* join =
10401 CreateJoin(materialize_false, materialize_true, expr->id());
10402 set_current_block(join);
10403 if (join != NULL) return ast_context()->ReturnValue(Pop());
10407 static Representation RepresentationFor(Type* type) {
10408 DisallowHeapAllocation no_allocation;
10409 if (type->Is(Type::None())) return Representation::None();
10410 if (type->Is(Type::SignedSmall())) return Representation::Smi();
10411 if (type->Is(Type::Signed32())) return Representation::Integer32();
10412 if (type->Is(Type::Number())) return Representation::Double();
10413 return Representation::Tagged();
10417 HInstruction* HOptimizedGraphBuilder::BuildIncrement(
10418 bool returns_original_input,
10419 CountOperation* expr) {
10420 // The input to the count operation is on top of the expression stack.
10421 Representation rep = RepresentationFor(expr->type());
10422 if (rep.IsNone() || rep.IsTagged()) {
10423 rep = Representation::Smi();
10426 if (returns_original_input && !is_strong(function_language_mode())) {
10427 // We need an explicit HValue representing ToNumber(input). The
10428 // actual HChange instruction we need is (sometimes) added in a later
10429 // phase, so it is not available now to be used as an input to HAdd and
10430 // as the return value.
10431 HInstruction* number_input = AddUncasted<HForceRepresentation>(Pop(), rep);
10432 if (!rep.IsDouble()) {
10433 number_input->SetFlag(HInstruction::kFlexibleRepresentation);
10434 number_input->SetFlag(HInstruction::kCannotBeTagged);
10436 Push(number_input);
10439 // The addition has no side effects, so we do not need
10440 // to simulate the expression stack after this instruction.
10441 // Any later failures deopt to the load of the input or earlier.
10442 HConstant* delta = (expr->op() == Token::INC)
10443 ? graph()->GetConstant1()
10444 : graph()->GetConstantMinus1();
10445 HInstruction* instr =
10446 AddUncasted<HAdd>(Top(), delta, strength(function_language_mode()));
10447 if (instr->IsAdd()) {
10448 HAdd* add = HAdd::cast(instr);
10449 add->set_observed_input_representation(1, rep);
10450 add->set_observed_input_representation(2, Representation::Smi());
10452 if (!is_strong(function_language_mode())) {
10453 instr->ClearAllSideEffects();
10455 Add<HSimulate>(expr->ToNumberId(), REMOVABLE_SIMULATE);
10457 instr->SetFlag(HInstruction::kCannotBeTagged);
10462 void HOptimizedGraphBuilder::BuildStoreForEffect(
10463 Expression* expr, Property* prop, FeedbackVectorICSlot slot,
10464 BailoutId ast_id, BailoutId return_id, HValue* object, HValue* key,
10466 EffectContext for_effect(this);
10468 if (key != NULL) Push(key);
10470 BuildStore(expr, prop, slot, ast_id, return_id);
10474 void HOptimizedGraphBuilder::VisitCountOperation(CountOperation* expr) {
10475 DCHECK(!HasStackOverflow());
10476 DCHECK(current_block() != NULL);
10477 DCHECK(current_block()->HasPredecessor());
10478 if (!top_info()->is_tracking_positions()) SetSourcePosition(expr->position());
10479 Expression* target = expr->expression();
10480 VariableProxy* proxy = target->AsVariableProxy();
10481 Property* prop = target->AsProperty();
10482 if (proxy == NULL && prop == NULL) {
10483 return Bailout(kInvalidLhsInCountOperation);
10486 // Match the full code generator stack by simulating an extra stack
10487 // element for postfix operations in a non-effect context. The return
10488 // value is ToNumber(input).
10489 bool returns_original_input =
10490 expr->is_postfix() && !ast_context()->IsEffect();
10491 HValue* input = NULL; // ToNumber(original_input).
10492 HValue* after = NULL; // The result after incrementing or decrementing.
10494 if (proxy != NULL) {
10495 Variable* var = proxy->var();
10496 if (var->mode() == CONST_LEGACY) {
10497 return Bailout(kUnsupportedCountOperationWithConst);
10499 if (var->mode() == CONST) {
10500 return Bailout(kNonInitializerAssignmentToConst);
10502 // Argument of the count operation is a variable, not a property.
10503 DCHECK(prop == NULL);
10504 CHECK_ALIVE(VisitForValue(target));
10506 after = BuildIncrement(returns_original_input, expr);
10507 input = returns_original_input ? Top() : Pop();
10510 switch (var->location()) {
10511 case VariableLocation::GLOBAL:
10512 case VariableLocation::UNALLOCATED:
10513 HandleGlobalVariableAssignment(var, after, expr->CountSlot(),
10514 expr->AssignmentId());
10517 case VariableLocation::PARAMETER:
10518 case VariableLocation::LOCAL:
10519 BindIfLive(var, after);
10522 case VariableLocation::CONTEXT: {
10523 // Bail out if we try to mutate a parameter value in a function
10524 // using the arguments object. We do not (yet) correctly handle the
10525 // arguments property of the function.
10526 if (current_info()->scope()->arguments() != NULL) {
10527 // Parameters will rewrite to context slots. We have no direct
10528 // way to detect that the variable is a parameter so we use a
10529 // linear search of the parameter list.
10530 int count = current_info()->scope()->num_parameters();
10531 for (int i = 0; i < count; ++i) {
10532 if (var == current_info()->scope()->parameter(i)) {
10533 return Bailout(kAssignmentToParameterInArgumentsObject);
10538 HValue* context = BuildContextChainWalk(var);
10539 HStoreContextSlot::Mode mode = IsLexicalVariableMode(var->mode())
10540 ? HStoreContextSlot::kCheckDeoptimize : HStoreContextSlot::kNoCheck;
10541 HStoreContextSlot* instr = Add<HStoreContextSlot>(context, var->index(),
10543 if (instr->HasObservableSideEffects()) {
10544 Add<HSimulate>(expr->AssignmentId(), REMOVABLE_SIMULATE);
10549 case VariableLocation::LOOKUP:
10550 return Bailout(kLookupVariableInCountOperation);
10553 Drop(returns_original_input ? 2 : 1);
10554 return ast_context()->ReturnValue(expr->is_postfix() ? input : after);
10557 // Argument of the count operation is a property.
10558 DCHECK(prop != NULL);
10559 if (returns_original_input) Push(graph()->GetConstantUndefined());
10561 CHECK_ALIVE(VisitForValue(prop->obj()));
10562 HValue* object = Top();
10564 HValue* key = NULL;
10565 if (!prop->key()->IsPropertyName() || prop->IsStringAccess()) {
10566 CHECK_ALIVE(VisitForValue(prop->key()));
10570 CHECK_ALIVE(PushLoad(prop, object, key));
10572 after = BuildIncrement(returns_original_input, expr);
10574 if (returns_original_input) {
10576 // Drop object and key to push it again in the effect context below.
10577 Drop(key == NULL ? 1 : 2);
10578 environment()->SetExpressionStackAt(0, input);
10579 CHECK_ALIVE(BuildStoreForEffect(expr, prop, expr->CountSlot(), expr->id(),
10580 expr->AssignmentId(), object, key, after));
10581 return ast_context()->ReturnValue(Pop());
10584 environment()->SetExpressionStackAt(0, after);
10585 return BuildStore(expr, prop, expr->CountSlot(), expr->id(),
10586 expr->AssignmentId());
10590 HInstruction* HOptimizedGraphBuilder::BuildStringCharCodeAt(
10593 if (string->IsConstant() && index->IsConstant()) {
10594 HConstant* c_string = HConstant::cast(string);
10595 HConstant* c_index = HConstant::cast(index);
10596 if (c_string->HasStringValue() && c_index->HasNumberValue()) {
10597 int32_t i = c_index->NumberValueAsInteger32();
10598 Handle<String> s = c_string->StringValue();
10599 if (i < 0 || i >= s->length()) {
10600 return New<HConstant>(std::numeric_limits<double>::quiet_NaN());
10602 return New<HConstant>(s->Get(i));
10605 string = BuildCheckString(string);
10606 index = Add<HBoundsCheck>(index, AddLoadStringLength(string));
10607 return New<HStringCharCodeAt>(string, index);
10611 // Checks if the given shift amounts have following forms:
10612 // (N1) and (N2) with N1 + N2 = 32; (sa) and (32 - sa).
10613 static bool ShiftAmountsAllowReplaceByRotate(HValue* sa,
10614 HValue* const32_minus_sa) {
10615 if (sa->IsConstant() && const32_minus_sa->IsConstant()) {
10616 const HConstant* c1 = HConstant::cast(sa);
10617 const HConstant* c2 = HConstant::cast(const32_minus_sa);
10618 return c1->HasInteger32Value() && c2->HasInteger32Value() &&
10619 (c1->Integer32Value() + c2->Integer32Value() == 32);
10621 if (!const32_minus_sa->IsSub()) return false;
10622 HSub* sub = HSub::cast(const32_minus_sa);
10623 return sub->left()->EqualsInteger32Constant(32) && sub->right() == sa;
10627 // Checks if the left and the right are shift instructions with the oposite
10628 // directions that can be replaced by one rotate right instruction or not.
10629 // Returns the operand and the shift amount for the rotate instruction in the
10631 bool HGraphBuilder::MatchRotateRight(HValue* left,
10634 HValue** shift_amount) {
10637 if (left->IsShl() && right->IsShr()) {
10638 shl = HShl::cast(left);
10639 shr = HShr::cast(right);
10640 } else if (left->IsShr() && right->IsShl()) {
10641 shl = HShl::cast(right);
10642 shr = HShr::cast(left);
10646 if (shl->left() != shr->left()) return false;
10648 if (!ShiftAmountsAllowReplaceByRotate(shl->right(), shr->right()) &&
10649 !ShiftAmountsAllowReplaceByRotate(shr->right(), shl->right())) {
10652 *operand = shr->left();
10653 *shift_amount = shr->right();
10658 bool CanBeZero(HValue* right) {
10659 if (right->IsConstant()) {
10660 HConstant* right_const = HConstant::cast(right);
10661 if (right_const->HasInteger32Value() &&
10662 (right_const->Integer32Value() & 0x1f) != 0) {
10670 HValue* HGraphBuilder::EnforceNumberType(HValue* number,
10672 if (expected->Is(Type::SignedSmall())) {
10673 return AddUncasted<HForceRepresentation>(number, Representation::Smi());
10675 if (expected->Is(Type::Signed32())) {
10676 return AddUncasted<HForceRepresentation>(number,
10677 Representation::Integer32());
10683 HValue* HGraphBuilder::TruncateToNumber(HValue* value, Type** expected) {
10684 if (value->IsConstant()) {
10685 HConstant* constant = HConstant::cast(value);
10686 Maybe<HConstant*> number =
10687 constant->CopyToTruncatedNumber(isolate(), zone());
10688 if (number.IsJust()) {
10689 *expected = Type::Number(zone());
10690 return AddInstruction(number.FromJust());
10694 // We put temporary values on the stack, which don't correspond to anything
10695 // in baseline code. Since nothing is observable we avoid recording those
10696 // pushes with a NoObservableSideEffectsScope.
10697 NoObservableSideEffectsScope no_effects(this);
10699 Type* expected_type = *expected;
10701 // Separate the number type from the rest.
10702 Type* expected_obj =
10703 Type::Intersect(expected_type, Type::NonNumber(zone()), zone());
10704 Type* expected_number =
10705 Type::Intersect(expected_type, Type::Number(zone()), zone());
10707 // We expect to get a number.
10708 // (We need to check first, since Type::None->Is(Type::Any()) == true.
10709 if (expected_obj->Is(Type::None())) {
10710 DCHECK(!expected_number->Is(Type::None(zone())));
10714 if (expected_obj->Is(Type::Undefined(zone()))) {
10715 // This is already done by HChange.
10716 *expected = Type::Union(expected_number, Type::Number(zone()), zone());
10724 HValue* HOptimizedGraphBuilder::BuildBinaryOperation(
10725 BinaryOperation* expr,
10728 PushBeforeSimulateBehavior push_sim_result) {
10729 Type* left_type = expr->left()->bounds().lower;
10730 Type* right_type = expr->right()->bounds().lower;
10731 Type* result_type = expr->bounds().lower;
10732 Maybe<int> fixed_right_arg = expr->fixed_right_arg();
10733 Handle<AllocationSite> allocation_site = expr->allocation_site();
10735 HAllocationMode allocation_mode;
10736 if (FLAG_allocation_site_pretenuring && !allocation_site.is_null()) {
10737 allocation_mode = HAllocationMode(allocation_site);
10739 HValue* result = HGraphBuilder::BuildBinaryOperation(
10740 expr->op(), left, right, left_type, right_type, result_type,
10741 fixed_right_arg, allocation_mode, strength(function_language_mode()),
10743 // Add a simulate after instructions with observable side effects, and
10744 // after phis, which are the result of BuildBinaryOperation when we
10745 // inlined some complex subgraph.
10746 if (result->HasObservableSideEffects() || result->IsPhi()) {
10747 if (push_sim_result == PUSH_BEFORE_SIMULATE) {
10749 Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
10752 Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
10759 HValue* HGraphBuilder::BuildBinaryOperation(
10760 Token::Value op, HValue* left, HValue* right, Type* left_type,
10761 Type* right_type, Type* result_type, Maybe<int> fixed_right_arg,
10762 HAllocationMode allocation_mode, Strength strength, BailoutId opt_id) {
10763 bool maybe_string_add = false;
10764 if (op == Token::ADD) {
10765 // If we are adding constant string with something for which we don't have
10766 // a feedback yet, assume that it's also going to be a string and don't
10767 // generate deopt instructions.
10768 if (!left_type->IsInhabited() && right->IsConstant() &&
10769 HConstant::cast(right)->HasStringValue()) {
10770 left_type = Type::String();
10773 if (!right_type->IsInhabited() && left->IsConstant() &&
10774 HConstant::cast(left)->HasStringValue()) {
10775 right_type = Type::String();
10778 maybe_string_add = (left_type->Maybe(Type::String()) ||
10779 left_type->Maybe(Type::Receiver()) ||
10780 right_type->Maybe(Type::String()) ||
10781 right_type->Maybe(Type::Receiver()));
10784 Representation left_rep = RepresentationFor(left_type);
10785 Representation right_rep = RepresentationFor(right_type);
10787 if (!left_type->IsInhabited()) {
10789 Deoptimizer::kInsufficientTypeFeedbackForLHSOfBinaryOperation,
10790 Deoptimizer::SOFT);
10791 left_type = Type::Any(zone());
10792 left_rep = RepresentationFor(left_type);
10793 maybe_string_add = op == Token::ADD;
10796 if (!right_type->IsInhabited()) {
10798 Deoptimizer::kInsufficientTypeFeedbackForRHSOfBinaryOperation,
10799 Deoptimizer::SOFT);
10800 right_type = Type::Any(zone());
10801 right_rep = RepresentationFor(right_type);
10802 maybe_string_add = op == Token::ADD;
10805 if (!maybe_string_add && !is_strong(strength)) {
10806 left = TruncateToNumber(left, &left_type);
10807 right = TruncateToNumber(right, &right_type);
10810 // Special case for string addition here.
10811 if (op == Token::ADD &&
10812 (left_type->Is(Type::String()) || right_type->Is(Type::String()))) {
10813 // Validate type feedback for left argument.
10814 if (left_type->Is(Type::String())) {
10815 left = BuildCheckString(left);
10818 // Validate type feedback for right argument.
10819 if (right_type->Is(Type::String())) {
10820 right = BuildCheckString(right);
10823 // Convert left argument as necessary.
10824 if (left_type->Is(Type::Number()) && !is_strong(strength)) {
10825 DCHECK(right_type->Is(Type::String()));
10826 left = BuildNumberToString(left, left_type);
10827 } else if (!left_type->Is(Type::String())) {
10828 DCHECK(right_type->Is(Type::String()));
10829 HValue* function = AddLoadJSBuiltin(
10830 is_strong(strength) ? Builtins::STRING_ADD_RIGHT_STRONG
10831 : Builtins::STRING_ADD_RIGHT);
10832 Add<HPushArguments>(left, right);
10833 return AddUncasted<HInvokeFunction>(function, 2);
10836 // Convert right argument as necessary.
10837 if (right_type->Is(Type::Number()) && !is_strong(strength)) {
10838 DCHECK(left_type->Is(Type::String()));
10839 right = BuildNumberToString(right, right_type);
10840 } else if (!right_type->Is(Type::String())) {
10841 DCHECK(left_type->Is(Type::String()));
10842 HValue* function = AddLoadJSBuiltin(is_strong(strength)
10843 ? Builtins::STRING_ADD_LEFT_STRONG
10844 : Builtins::STRING_ADD_LEFT);
10845 Add<HPushArguments>(left, right);
10846 return AddUncasted<HInvokeFunction>(function, 2);
10849 // Fast paths for empty constant strings.
10850 Handle<String> left_string =
10851 left->IsConstant() && HConstant::cast(left)->HasStringValue()
10852 ? HConstant::cast(left)->StringValue()
10853 : Handle<String>();
10854 Handle<String> right_string =
10855 right->IsConstant() && HConstant::cast(right)->HasStringValue()
10856 ? HConstant::cast(right)->StringValue()
10857 : Handle<String>();
10858 if (!left_string.is_null() && left_string->length() == 0) return right;
10859 if (!right_string.is_null() && right_string->length() == 0) return left;
10860 if (!left_string.is_null() && !right_string.is_null()) {
10861 return AddUncasted<HStringAdd>(
10862 left, right, strength, allocation_mode.GetPretenureMode(),
10863 STRING_ADD_CHECK_NONE, allocation_mode.feedback_site());
10866 // Register the dependent code with the allocation site.
10867 if (!allocation_mode.feedback_site().is_null()) {
10868 DCHECK(!graph()->info()->IsStub());
10869 Handle<AllocationSite> site(allocation_mode.feedback_site());
10870 top_info()->dependencies()->AssumeTenuringDecision(site);
10873 // Inline the string addition into the stub when creating allocation
10874 // mementos to gather allocation site feedback, or if we can statically
10875 // infer that we're going to create a cons string.
10876 if ((graph()->info()->IsStub() &&
10877 allocation_mode.CreateAllocationMementos()) ||
10878 (left->IsConstant() &&
10879 HConstant::cast(left)->HasStringValue() &&
10880 HConstant::cast(left)->StringValue()->length() + 1 >=
10881 ConsString::kMinLength) ||
10882 (right->IsConstant() &&
10883 HConstant::cast(right)->HasStringValue() &&
10884 HConstant::cast(right)->StringValue()->length() + 1 >=
10885 ConsString::kMinLength)) {
10886 return BuildStringAdd(left, right, allocation_mode);
10889 // Fallback to using the string add stub.
10890 return AddUncasted<HStringAdd>(
10891 left, right, strength, allocation_mode.GetPretenureMode(),
10892 STRING_ADD_CHECK_NONE, allocation_mode.feedback_site());
10895 if (graph()->info()->IsStub()) {
10896 left = EnforceNumberType(left, left_type);
10897 right = EnforceNumberType(right, right_type);
10900 Representation result_rep = RepresentationFor(result_type);
10902 bool is_non_primitive = (left_rep.IsTagged() && !left_rep.IsSmi()) ||
10903 (right_rep.IsTagged() && !right_rep.IsSmi());
10905 HInstruction* instr = NULL;
10906 // Only the stub is allowed to call into the runtime, since otherwise we would
10907 // inline several instructions (including the two pushes) for every tagged
10908 // operation in optimized code, which is more expensive, than a stub call.
10909 if (graph()->info()->IsStub() && is_non_primitive) {
10911 AddLoadJSBuiltin(BinaryOpIC::TokenToJSBuiltin(op, strength));
10912 Add<HPushArguments>(left, right);
10913 instr = AddUncasted<HInvokeFunction>(function, 2);
10915 if (is_strong(strength) && Token::IsBitOp(op)) {
10916 // TODO(conradw): This is not efficient, but is necessary to prevent
10917 // conversion of oddball values to numbers in strong mode. It would be
10918 // better to prevent the conversion rather than adding a runtime check.
10919 IfBuilder if_builder(this);
10920 if_builder.If<HHasInstanceTypeAndBranch>(left, ODDBALL_TYPE);
10921 if_builder.OrIf<HHasInstanceTypeAndBranch>(right, ODDBALL_TYPE);
10924 isolate()->factory()->empty_string(),
10925 Runtime::FunctionForId(Runtime::kThrowStrongModeImplicitConversion),
10927 if (!graph()->info()->IsStub()) {
10928 Add<HSimulate>(opt_id, REMOVABLE_SIMULATE);
10934 instr = AddUncasted<HAdd>(left, right, strength);
10937 instr = AddUncasted<HSub>(left, right, strength);
10940 instr = AddUncasted<HMul>(left, right, strength);
10943 if (fixed_right_arg.IsJust() &&
10944 !right->EqualsInteger32Constant(fixed_right_arg.FromJust())) {
10945 HConstant* fixed_right =
10946 Add<HConstant>(static_cast<int>(fixed_right_arg.FromJust()));
10947 IfBuilder if_same(this);
10948 if_same.If<HCompareNumericAndBranch>(right, fixed_right, Token::EQ);
10950 if_same.ElseDeopt(Deoptimizer::kUnexpectedRHSOfBinaryOperation);
10951 right = fixed_right;
10953 instr = AddUncasted<HMod>(left, right, strength);
10957 instr = AddUncasted<HDiv>(left, right, strength);
10959 case Token::BIT_XOR:
10960 case Token::BIT_AND:
10961 instr = AddUncasted<HBitwise>(op, left, right, strength);
10963 case Token::BIT_OR: {
10964 HValue* operand, *shift_amount;
10965 if (left_type->Is(Type::Signed32()) &&
10966 right_type->Is(Type::Signed32()) &&
10967 MatchRotateRight(left, right, &operand, &shift_amount)) {
10968 instr = AddUncasted<HRor>(operand, shift_amount, strength);
10970 instr = AddUncasted<HBitwise>(op, left, right, strength);
10975 instr = AddUncasted<HSar>(left, right, strength);
10978 instr = AddUncasted<HShr>(left, right, strength);
10979 if (instr->IsShr() && CanBeZero(right)) {
10980 graph()->RecordUint32Instruction(instr);
10984 instr = AddUncasted<HShl>(left, right, strength);
10991 if (instr->IsBinaryOperation()) {
10992 HBinaryOperation* binop = HBinaryOperation::cast(instr);
10993 binop->set_observed_input_representation(1, left_rep);
10994 binop->set_observed_input_representation(2, right_rep);
10995 binop->initialize_output_representation(result_rep);
10996 if (graph()->info()->IsStub()) {
10997 // Stub should not call into stub.
10998 instr->SetFlag(HValue::kCannotBeTagged);
10999 // And should truncate on HForceRepresentation already.
11000 if (left->IsForceRepresentation()) {
11001 left->CopyFlag(HValue::kTruncatingToSmi, instr);
11002 left->CopyFlag(HValue::kTruncatingToInt32, instr);
11004 if (right->IsForceRepresentation()) {
11005 right->CopyFlag(HValue::kTruncatingToSmi, instr);
11006 right->CopyFlag(HValue::kTruncatingToInt32, instr);
11014 // Check for the form (%_ClassOf(foo) === 'BarClass').
11015 static bool IsClassOfTest(CompareOperation* expr) {
11016 if (expr->op() != Token::EQ_STRICT) return false;
11017 CallRuntime* call = expr->left()->AsCallRuntime();
11018 if (call == NULL) return false;
11019 Literal* literal = expr->right()->AsLiteral();
11020 if (literal == NULL) return false;
11021 if (!literal->value()->IsString()) return false;
11022 if (!call->name()->IsOneByteEqualTo(STATIC_CHAR_VECTOR("_ClassOf"))) {
11025 DCHECK(call->arguments()->length() == 1);
11030 void HOptimizedGraphBuilder::VisitBinaryOperation(BinaryOperation* expr) {
11031 DCHECK(!HasStackOverflow());
11032 DCHECK(current_block() != NULL);
11033 DCHECK(current_block()->HasPredecessor());
11034 switch (expr->op()) {
11036 return VisitComma(expr);
11039 return VisitLogicalExpression(expr);
11041 return VisitArithmeticExpression(expr);
11046 void HOptimizedGraphBuilder::VisitComma(BinaryOperation* expr) {
11047 CHECK_ALIVE(VisitForEffect(expr->left()));
11048 // Visit the right subexpression in the same AST context as the entire
11050 Visit(expr->right());
11054 void HOptimizedGraphBuilder::VisitLogicalExpression(BinaryOperation* expr) {
11055 bool is_logical_and = expr->op() == Token::AND;
11056 if (ast_context()->IsTest()) {
11057 TestContext* context = TestContext::cast(ast_context());
11058 // Translate left subexpression.
11059 HBasicBlock* eval_right = graph()->CreateBasicBlock();
11060 if (is_logical_and) {
11061 CHECK_BAILOUT(VisitForControl(expr->left(),
11063 context->if_false()));
11065 CHECK_BAILOUT(VisitForControl(expr->left(),
11066 context->if_true(),
11070 // Translate right subexpression by visiting it in the same AST
11071 // context as the entire expression.
11072 if (eval_right->HasPredecessor()) {
11073 eval_right->SetJoinId(expr->RightId());
11074 set_current_block(eval_right);
11075 Visit(expr->right());
11078 } else if (ast_context()->IsValue()) {
11079 CHECK_ALIVE(VisitForValue(expr->left()));
11080 DCHECK(current_block() != NULL);
11081 HValue* left_value = Top();
11083 // Short-circuit left values that always evaluate to the same boolean value.
11084 if (expr->left()->ToBooleanIsTrue() || expr->left()->ToBooleanIsFalse()) {
11085 // l (evals true) && r -> r
11086 // l (evals true) || r -> l
11087 // l (evals false) && r -> l
11088 // l (evals false) || r -> r
11089 if (is_logical_and == expr->left()->ToBooleanIsTrue()) {
11091 CHECK_ALIVE(VisitForValue(expr->right()));
11093 return ast_context()->ReturnValue(Pop());
11096 // We need an extra block to maintain edge-split form.
11097 HBasicBlock* empty_block = graph()->CreateBasicBlock();
11098 HBasicBlock* eval_right = graph()->CreateBasicBlock();
11099 ToBooleanStub::Types expected(expr->left()->to_boolean_types());
11100 HBranch* test = is_logical_and
11101 ? New<HBranch>(left_value, expected, eval_right, empty_block)
11102 : New<HBranch>(left_value, expected, empty_block, eval_right);
11103 FinishCurrentBlock(test);
11105 set_current_block(eval_right);
11106 Drop(1); // Value of the left subexpression.
11107 CHECK_BAILOUT(VisitForValue(expr->right()));
11109 HBasicBlock* join_block =
11110 CreateJoin(empty_block, current_block(), expr->id());
11111 set_current_block(join_block);
11112 return ast_context()->ReturnValue(Pop());
11115 DCHECK(ast_context()->IsEffect());
11116 // In an effect context, we don't need the value of the left subexpression,
11117 // only its control flow and side effects. We need an extra block to
11118 // maintain edge-split form.
11119 HBasicBlock* empty_block = graph()->CreateBasicBlock();
11120 HBasicBlock* right_block = graph()->CreateBasicBlock();
11121 if (is_logical_and) {
11122 CHECK_BAILOUT(VisitForControl(expr->left(), right_block, empty_block));
11124 CHECK_BAILOUT(VisitForControl(expr->left(), empty_block, right_block));
11127 // TODO(kmillikin): Find a way to fix this. It's ugly that there are
11128 // actually two empty blocks (one here and one inserted by
11129 // TestContext::BuildBranch, and that they both have an HSimulate though the
11130 // second one is not a merge node, and that we really have no good AST ID to
11131 // put on that first HSimulate.
11133 if (empty_block->HasPredecessor()) {
11134 empty_block->SetJoinId(expr->id());
11136 empty_block = NULL;
11139 if (right_block->HasPredecessor()) {
11140 right_block->SetJoinId(expr->RightId());
11141 set_current_block(right_block);
11142 CHECK_BAILOUT(VisitForEffect(expr->right()));
11143 right_block = current_block();
11145 right_block = NULL;
11148 HBasicBlock* join_block =
11149 CreateJoin(empty_block, right_block, expr->id());
11150 set_current_block(join_block);
11151 // We did not materialize any value in the predecessor environments,
11152 // so there is no need to handle it here.
11157 void HOptimizedGraphBuilder::VisitArithmeticExpression(BinaryOperation* expr) {
11158 CHECK_ALIVE(VisitForValue(expr->left()));
11159 CHECK_ALIVE(VisitForValue(expr->right()));
11160 SetSourcePosition(expr->position());
11161 HValue* right = Pop();
11162 HValue* left = Pop();
11164 BuildBinaryOperation(expr, left, right,
11165 ast_context()->IsEffect() ? NO_PUSH_BEFORE_SIMULATE
11166 : PUSH_BEFORE_SIMULATE);
11167 if (top_info()->is_tracking_positions() && result->IsBinaryOperation()) {
11168 HBinaryOperation::cast(result)->SetOperandPositions(
11170 ScriptPositionToSourcePosition(expr->left()->position()),
11171 ScriptPositionToSourcePosition(expr->right()->position()));
11173 return ast_context()->ReturnValue(result);
11177 void HOptimizedGraphBuilder::HandleLiteralCompareTypeof(CompareOperation* expr,
11178 Expression* sub_expr,
11179 Handle<String> check) {
11180 CHECK_ALIVE(VisitForTypeOf(sub_expr));
11181 SetSourcePosition(expr->position());
11182 HValue* value = Pop();
11183 HTypeofIsAndBranch* instr = New<HTypeofIsAndBranch>(value, check);
11184 return ast_context()->ReturnControl(instr, expr->id());
11188 static bool IsLiteralCompareBool(Isolate* isolate,
11192 return op == Token::EQ_STRICT &&
11193 ((left->IsConstant() &&
11194 HConstant::cast(left)->handle(isolate)->IsBoolean()) ||
11195 (right->IsConstant() &&
11196 HConstant::cast(right)->handle(isolate)->IsBoolean()));
11200 void HOptimizedGraphBuilder::VisitCompareOperation(CompareOperation* expr) {
11201 DCHECK(!HasStackOverflow());
11202 DCHECK(current_block() != NULL);
11203 DCHECK(current_block()->HasPredecessor());
11205 if (!top_info()->is_tracking_positions()) SetSourcePosition(expr->position());
11207 // Check for a few fast cases. The AST visiting behavior must be in sync
11208 // with the full codegen: We don't push both left and right values onto
11209 // the expression stack when one side is a special-case literal.
11210 Expression* sub_expr = NULL;
11211 Handle<String> check;
11212 if (expr->IsLiteralCompareTypeof(&sub_expr, &check)) {
11213 return HandleLiteralCompareTypeof(expr, sub_expr, check);
11215 if (expr->IsLiteralCompareUndefined(&sub_expr, isolate())) {
11216 return HandleLiteralCompareNil(expr, sub_expr, kUndefinedValue);
11218 if (expr->IsLiteralCompareNull(&sub_expr)) {
11219 return HandleLiteralCompareNil(expr, sub_expr, kNullValue);
11222 if (IsClassOfTest(expr)) {
11223 CallRuntime* call = expr->left()->AsCallRuntime();
11224 DCHECK(call->arguments()->length() == 1);
11225 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11226 HValue* value = Pop();
11227 Literal* literal = expr->right()->AsLiteral();
11228 Handle<String> rhs = Handle<String>::cast(literal->value());
11229 HClassOfTestAndBranch* instr = New<HClassOfTestAndBranch>(value, rhs);
11230 return ast_context()->ReturnControl(instr, expr->id());
11233 Type* left_type = expr->left()->bounds().lower;
11234 Type* right_type = expr->right()->bounds().lower;
11235 Type* combined_type = expr->combined_type();
11237 CHECK_ALIVE(VisitForValue(expr->left()));
11238 CHECK_ALIVE(VisitForValue(expr->right()));
11240 HValue* right = Pop();
11241 HValue* left = Pop();
11242 Token::Value op = expr->op();
11244 if (IsLiteralCompareBool(isolate(), left, op, right)) {
11245 HCompareObjectEqAndBranch* result =
11246 New<HCompareObjectEqAndBranch>(left, right);
11247 return ast_context()->ReturnControl(result, expr->id());
11250 if (op == Token::INSTANCEOF) {
11251 // Check to see if the rhs of the instanceof is a known function.
11252 if (right->IsConstant() &&
11253 HConstant::cast(right)->handle(isolate())->IsJSFunction()) {
11254 Handle<Object> function = HConstant::cast(right)->handle(isolate());
11255 Handle<JSFunction> target = Handle<JSFunction>::cast(function);
11256 HInstanceOfKnownGlobal* result =
11257 New<HInstanceOfKnownGlobal>(left, target);
11258 return ast_context()->ReturnInstruction(result, expr->id());
11261 HInstanceOf* result = New<HInstanceOf>(left, right);
11262 return ast_context()->ReturnInstruction(result, expr->id());
11264 } else if (op == Token::IN) {
11265 HValue* function = AddLoadJSBuiltin(Builtins::IN);
11266 Add<HPushArguments>(left, right);
11267 // TODO(olivf) InvokeFunction produces a check for the parameter count,
11268 // even though we are certain to pass the correct number of arguments here.
11269 HInstruction* result = New<HInvokeFunction>(function, 2);
11270 return ast_context()->ReturnInstruction(result, expr->id());
11273 PushBeforeSimulateBehavior push_behavior =
11274 ast_context()->IsEffect() ? NO_PUSH_BEFORE_SIMULATE
11275 : PUSH_BEFORE_SIMULATE;
11276 HControlInstruction* compare = BuildCompareInstruction(
11277 op, left, right, left_type, right_type, combined_type,
11278 ScriptPositionToSourcePosition(expr->left()->position()),
11279 ScriptPositionToSourcePosition(expr->right()->position()),
11280 push_behavior, expr->id());
11281 if (compare == NULL) return; // Bailed out.
11282 return ast_context()->ReturnControl(compare, expr->id());
11286 HControlInstruction* HOptimizedGraphBuilder::BuildCompareInstruction(
11287 Token::Value op, HValue* left, HValue* right, Type* left_type,
11288 Type* right_type, Type* combined_type, SourcePosition left_position,
11289 SourcePosition right_position, PushBeforeSimulateBehavior push_sim_result,
11290 BailoutId bailout_id) {
11291 // Cases handled below depend on collected type feedback. They should
11292 // soft deoptimize when there is no type feedback.
11293 if (!combined_type->IsInhabited()) {
11295 Deoptimizer::kInsufficientTypeFeedbackForCombinedTypeOfBinaryOperation,
11296 Deoptimizer::SOFT);
11297 combined_type = left_type = right_type = Type::Any(zone());
11300 Representation left_rep = RepresentationFor(left_type);
11301 Representation right_rep = RepresentationFor(right_type);
11302 Representation combined_rep = RepresentationFor(combined_type);
11304 if (combined_type->Is(Type::Receiver())) {
11305 if (Token::IsEqualityOp(op)) {
11306 // HCompareObjectEqAndBranch can only deal with object, so
11307 // exclude numbers.
11308 if ((left->IsConstant() &&
11309 HConstant::cast(left)->HasNumberValue()) ||
11310 (right->IsConstant() &&
11311 HConstant::cast(right)->HasNumberValue())) {
11312 Add<HDeoptimize>(Deoptimizer::kTypeMismatchBetweenFeedbackAndConstant,
11313 Deoptimizer::SOFT);
11314 // The caller expects a branch instruction, so make it happy.
11315 return New<HBranch>(graph()->GetConstantTrue());
11317 // Can we get away with map check and not instance type check?
11318 HValue* operand_to_check =
11319 left->block()->block_id() < right->block()->block_id() ? left : right;
11320 if (combined_type->IsClass()) {
11321 Handle<Map> map = combined_type->AsClass()->Map();
11322 AddCheckMap(operand_to_check, map);
11323 HCompareObjectEqAndBranch* result =
11324 New<HCompareObjectEqAndBranch>(left, right);
11325 if (top_info()->is_tracking_positions()) {
11326 result->set_operand_position(zone(), 0, left_position);
11327 result->set_operand_position(zone(), 1, right_position);
11331 BuildCheckHeapObject(operand_to_check);
11332 Add<HCheckInstanceType>(operand_to_check,
11333 HCheckInstanceType::IS_SPEC_OBJECT);
11334 HCompareObjectEqAndBranch* result =
11335 New<HCompareObjectEqAndBranch>(left, right);
11339 Bailout(kUnsupportedNonPrimitiveCompare);
11342 } else if (combined_type->Is(Type::InternalizedString()) &&
11343 Token::IsEqualityOp(op)) {
11344 // If we have a constant argument, it should be consistent with the type
11345 // feedback (otherwise we fail assertions in HCompareObjectEqAndBranch).
11346 if ((left->IsConstant() &&
11347 !HConstant::cast(left)->HasInternalizedStringValue()) ||
11348 (right->IsConstant() &&
11349 !HConstant::cast(right)->HasInternalizedStringValue())) {
11350 Add<HDeoptimize>(Deoptimizer::kTypeMismatchBetweenFeedbackAndConstant,
11351 Deoptimizer::SOFT);
11352 // The caller expects a branch instruction, so make it happy.
11353 return New<HBranch>(graph()->GetConstantTrue());
11355 BuildCheckHeapObject(left);
11356 Add<HCheckInstanceType>(left, HCheckInstanceType::IS_INTERNALIZED_STRING);
11357 BuildCheckHeapObject(right);
11358 Add<HCheckInstanceType>(right, HCheckInstanceType::IS_INTERNALIZED_STRING);
11359 HCompareObjectEqAndBranch* result =
11360 New<HCompareObjectEqAndBranch>(left, right);
11362 } else if (combined_type->Is(Type::String())) {
11363 BuildCheckHeapObject(left);
11364 Add<HCheckInstanceType>(left, HCheckInstanceType::IS_STRING);
11365 BuildCheckHeapObject(right);
11366 Add<HCheckInstanceType>(right, HCheckInstanceType::IS_STRING);
11367 HStringCompareAndBranch* result =
11368 New<HStringCompareAndBranch>(left, right, op);
11371 if (combined_rep.IsTagged() || combined_rep.IsNone()) {
11372 HCompareGeneric* result = Add<HCompareGeneric>(
11373 left, right, op, strength(function_language_mode()));
11374 result->set_observed_input_representation(1, left_rep);
11375 result->set_observed_input_representation(2, right_rep);
11376 if (result->HasObservableSideEffects()) {
11377 if (push_sim_result == PUSH_BEFORE_SIMULATE) {
11379 AddSimulate(bailout_id, REMOVABLE_SIMULATE);
11382 AddSimulate(bailout_id, REMOVABLE_SIMULATE);
11385 // TODO(jkummerow): Can we make this more efficient?
11386 HBranch* branch = New<HBranch>(result);
11389 HCompareNumericAndBranch* result = New<HCompareNumericAndBranch>(
11390 left, right, op, strength(function_language_mode()));
11391 result->set_observed_input_representation(left_rep, right_rep);
11392 if (top_info()->is_tracking_positions()) {
11393 result->SetOperandPositions(zone(), left_position, right_position);
11401 void HOptimizedGraphBuilder::HandleLiteralCompareNil(CompareOperation* expr,
11402 Expression* sub_expr,
11404 DCHECK(!HasStackOverflow());
11405 DCHECK(current_block() != NULL);
11406 DCHECK(current_block()->HasPredecessor());
11407 DCHECK(expr->op() == Token::EQ || expr->op() == Token::EQ_STRICT);
11408 if (!top_info()->is_tracking_positions()) SetSourcePosition(expr->position());
11409 CHECK_ALIVE(VisitForValue(sub_expr));
11410 HValue* value = Pop();
11411 if (expr->op() == Token::EQ_STRICT) {
11412 HConstant* nil_constant = nil == kNullValue
11413 ? graph()->GetConstantNull()
11414 : graph()->GetConstantUndefined();
11415 HCompareObjectEqAndBranch* instr =
11416 New<HCompareObjectEqAndBranch>(value, nil_constant);
11417 return ast_context()->ReturnControl(instr, expr->id());
11419 DCHECK_EQ(Token::EQ, expr->op());
11420 Type* type = expr->combined_type()->Is(Type::None())
11421 ? Type::Any(zone()) : expr->combined_type();
11422 HIfContinuation continuation;
11423 BuildCompareNil(value, type, &continuation);
11424 return ast_context()->ReturnContinuation(&continuation, expr->id());
11429 void HOptimizedGraphBuilder::VisitSpread(Spread* expr) { UNREACHABLE(); }
11432 HInstruction* HOptimizedGraphBuilder::BuildThisFunction() {
11433 // If we share optimized code between different closures, the
11434 // this-function is not a constant, except inside an inlined body.
11435 if (function_state()->outer() != NULL) {
11436 return New<HConstant>(
11437 function_state()->compilation_info()->closure());
11439 return New<HThisFunction>();
11444 HInstruction* HOptimizedGraphBuilder::BuildFastLiteral(
11445 Handle<JSObject> boilerplate_object,
11446 AllocationSiteUsageContext* site_context) {
11447 NoObservableSideEffectsScope no_effects(this);
11448 Handle<Map> initial_map(boilerplate_object->map());
11449 InstanceType instance_type = initial_map->instance_type();
11450 DCHECK(instance_type == JS_ARRAY_TYPE || instance_type == JS_OBJECT_TYPE);
11452 HType type = instance_type == JS_ARRAY_TYPE
11453 ? HType::JSArray() : HType::JSObject();
11454 HValue* object_size_constant = Add<HConstant>(initial_map->instance_size());
11456 PretenureFlag pretenure_flag = NOT_TENURED;
11457 Handle<AllocationSite> top_site(*site_context->top(), isolate());
11458 if (FLAG_allocation_site_pretenuring) {
11459 pretenure_flag = top_site->GetPretenureMode();
11462 Handle<AllocationSite> current_site(*site_context->current(), isolate());
11463 if (*top_site == *current_site) {
11464 // We install a dependency for pretenuring only on the outermost literal.
11465 top_info()->dependencies()->AssumeTenuringDecision(top_site);
11467 top_info()->dependencies()->AssumeTransitionStable(current_site);
11469 HInstruction* object = Add<HAllocate>(
11470 object_size_constant, type, pretenure_flag, instance_type, top_site);
11472 // If allocation folding reaches Page::kMaxRegularHeapObjectSize the
11473 // elements array may not get folded into the object. Hence, we set the
11474 // elements pointer to empty fixed array and let store elimination remove
11475 // this store in the folding case.
11476 HConstant* empty_fixed_array = Add<HConstant>(
11477 isolate()->factory()->empty_fixed_array());
11478 Add<HStoreNamedField>(object, HObjectAccess::ForElementsPointer(),
11479 empty_fixed_array);
11481 BuildEmitObjectHeader(boilerplate_object, object);
11483 // Similarly to the elements pointer, there is no guarantee that all
11484 // property allocations can get folded, so pre-initialize all in-object
11485 // properties to a safe value.
11486 BuildInitializeInobjectProperties(object, initial_map);
11488 Handle<FixedArrayBase> elements(boilerplate_object->elements());
11489 int elements_size = (elements->length() > 0 &&
11490 elements->map() != isolate()->heap()->fixed_cow_array_map()) ?
11491 elements->Size() : 0;
11493 if (pretenure_flag == TENURED &&
11494 elements->map() == isolate()->heap()->fixed_cow_array_map() &&
11495 isolate()->heap()->InNewSpace(*elements)) {
11496 // If we would like to pretenure a fixed cow array, we must ensure that the
11497 // array is already in old space, otherwise we'll create too many old-to-
11498 // new-space pointers (overflowing the store buffer).
11499 elements = Handle<FixedArrayBase>(
11500 isolate()->factory()->CopyAndTenureFixedCOWArray(
11501 Handle<FixedArray>::cast(elements)));
11502 boilerplate_object->set_elements(*elements);
11505 HInstruction* object_elements = NULL;
11506 if (elements_size > 0) {
11507 HValue* object_elements_size = Add<HConstant>(elements_size);
11508 InstanceType instance_type = boilerplate_object->HasFastDoubleElements()
11509 ? FIXED_DOUBLE_ARRAY_TYPE : FIXED_ARRAY_TYPE;
11510 object_elements = Add<HAllocate>(object_elements_size, HType::HeapObject(),
11511 pretenure_flag, instance_type, top_site);
11512 BuildEmitElements(boilerplate_object, elements, object_elements,
11514 Add<HStoreNamedField>(object, HObjectAccess::ForElementsPointer(),
11517 Handle<Object> elements_field =
11518 Handle<Object>(boilerplate_object->elements(), isolate());
11519 HInstruction* object_elements_cow = Add<HConstant>(elements_field);
11520 Add<HStoreNamedField>(object, HObjectAccess::ForElementsPointer(),
11521 object_elements_cow);
11524 // Copy in-object properties.
11525 if (initial_map->NumberOfFields() != 0 ||
11526 initial_map->unused_property_fields() > 0) {
11527 BuildEmitInObjectProperties(boilerplate_object, object, site_context,
11534 void HOptimizedGraphBuilder::BuildEmitObjectHeader(
11535 Handle<JSObject> boilerplate_object,
11536 HInstruction* object) {
11537 DCHECK(boilerplate_object->properties()->length() == 0);
11539 Handle<Map> boilerplate_object_map(boilerplate_object->map());
11540 AddStoreMapConstant(object, boilerplate_object_map);
11542 Handle<Object> properties_field =
11543 Handle<Object>(boilerplate_object->properties(), isolate());
11544 DCHECK(*properties_field == isolate()->heap()->empty_fixed_array());
11545 HInstruction* properties = Add<HConstant>(properties_field);
11546 HObjectAccess access = HObjectAccess::ForPropertiesPointer();
11547 Add<HStoreNamedField>(object, access, properties);
11549 if (boilerplate_object->IsJSArray()) {
11550 Handle<JSArray> boilerplate_array =
11551 Handle<JSArray>::cast(boilerplate_object);
11552 Handle<Object> length_field =
11553 Handle<Object>(boilerplate_array->length(), isolate());
11554 HInstruction* length = Add<HConstant>(length_field);
11556 DCHECK(boilerplate_array->length()->IsSmi());
11557 Add<HStoreNamedField>(object, HObjectAccess::ForArrayLength(
11558 boilerplate_array->GetElementsKind()), length);
11563 void HOptimizedGraphBuilder::BuildEmitInObjectProperties(
11564 Handle<JSObject> boilerplate_object,
11565 HInstruction* object,
11566 AllocationSiteUsageContext* site_context,
11567 PretenureFlag pretenure_flag) {
11568 Handle<Map> boilerplate_map(boilerplate_object->map());
11569 Handle<DescriptorArray> descriptors(boilerplate_map->instance_descriptors());
11570 int limit = boilerplate_map->NumberOfOwnDescriptors();
11572 int copied_fields = 0;
11573 for (int i = 0; i < limit; i++) {
11574 PropertyDetails details = descriptors->GetDetails(i);
11575 if (details.type() != DATA) continue;
11577 FieldIndex field_index = FieldIndex::ForDescriptor(*boilerplate_map, i);
11580 int property_offset = field_index.offset();
11581 Handle<Name> name(descriptors->GetKey(i));
11583 // The access for the store depends on the type of the boilerplate.
11584 HObjectAccess access = boilerplate_object->IsJSArray() ?
11585 HObjectAccess::ForJSArrayOffset(property_offset) :
11586 HObjectAccess::ForMapAndOffset(boilerplate_map, property_offset);
11588 if (boilerplate_object->IsUnboxedDoubleField(field_index)) {
11589 CHECK(!boilerplate_object->IsJSArray());
11590 double value = boilerplate_object->RawFastDoublePropertyAt(field_index);
11591 access = access.WithRepresentation(Representation::Double());
11592 Add<HStoreNamedField>(object, access, Add<HConstant>(value));
11595 Handle<Object> value(boilerplate_object->RawFastPropertyAt(field_index),
11598 if (value->IsJSObject()) {
11599 Handle<JSObject> value_object = Handle<JSObject>::cast(value);
11600 Handle<AllocationSite> current_site = site_context->EnterNewScope();
11601 HInstruction* result =
11602 BuildFastLiteral(value_object, site_context);
11603 site_context->ExitScope(current_site, value_object);
11604 Add<HStoreNamedField>(object, access, result);
11606 Representation representation = details.representation();
11607 HInstruction* value_instruction;
11609 if (representation.IsDouble()) {
11610 // Allocate a HeapNumber box and store the value into it.
11611 HValue* heap_number_constant = Add<HConstant>(HeapNumber::kSize);
11612 HInstruction* double_box =
11613 Add<HAllocate>(heap_number_constant, HType::HeapObject(),
11614 pretenure_flag, MUTABLE_HEAP_NUMBER_TYPE);
11615 AddStoreMapConstant(double_box,
11616 isolate()->factory()->mutable_heap_number_map());
11617 // Unwrap the mutable heap number from the boilerplate.
11618 HValue* double_value =
11619 Add<HConstant>(Handle<HeapNumber>::cast(value)->value());
11620 Add<HStoreNamedField>(
11621 double_box, HObjectAccess::ForHeapNumberValue(), double_value);
11622 value_instruction = double_box;
11623 } else if (representation.IsSmi()) {
11624 value_instruction = value->IsUninitialized()
11625 ? graph()->GetConstant0()
11626 : Add<HConstant>(value);
11627 // Ensure that value is stored as smi.
11628 access = access.WithRepresentation(representation);
11630 value_instruction = Add<HConstant>(value);
11633 Add<HStoreNamedField>(object, access, value_instruction);
11637 int inobject_properties = boilerplate_object->map()->inobject_properties();
11638 HInstruction* value_instruction =
11639 Add<HConstant>(isolate()->factory()->one_pointer_filler_map());
11640 for (int i = copied_fields; i < inobject_properties; i++) {
11641 DCHECK(boilerplate_object->IsJSObject());
11642 int property_offset = boilerplate_object->GetInObjectPropertyOffset(i);
11643 HObjectAccess access =
11644 HObjectAccess::ForMapAndOffset(boilerplate_map, property_offset);
11645 Add<HStoreNamedField>(object, access, value_instruction);
11650 void HOptimizedGraphBuilder::BuildEmitElements(
11651 Handle<JSObject> boilerplate_object,
11652 Handle<FixedArrayBase> elements,
11653 HValue* object_elements,
11654 AllocationSiteUsageContext* site_context) {
11655 ElementsKind kind = boilerplate_object->map()->elements_kind();
11656 int elements_length = elements->length();
11657 HValue* object_elements_length = Add<HConstant>(elements_length);
11658 BuildInitializeElementsHeader(object_elements, kind, object_elements_length);
11660 // Copy elements backing store content.
11661 if (elements->IsFixedDoubleArray()) {
11662 BuildEmitFixedDoubleArray(elements, kind, object_elements);
11663 } else if (elements->IsFixedArray()) {
11664 BuildEmitFixedArray(elements, kind, object_elements,
11672 void HOptimizedGraphBuilder::BuildEmitFixedDoubleArray(
11673 Handle<FixedArrayBase> elements,
11675 HValue* object_elements) {
11676 HInstruction* boilerplate_elements = Add<HConstant>(elements);
11677 int elements_length = elements->length();
11678 for (int i = 0; i < elements_length; i++) {
11679 HValue* key_constant = Add<HConstant>(i);
11680 HInstruction* value_instruction = Add<HLoadKeyed>(
11681 boilerplate_elements, key_constant, nullptr, kind, ALLOW_RETURN_HOLE);
11682 HInstruction* store = Add<HStoreKeyed>(object_elements, key_constant,
11683 value_instruction, kind);
11684 store->SetFlag(HValue::kAllowUndefinedAsNaN);
11689 void HOptimizedGraphBuilder::BuildEmitFixedArray(
11690 Handle<FixedArrayBase> elements,
11692 HValue* object_elements,
11693 AllocationSiteUsageContext* site_context) {
11694 HInstruction* boilerplate_elements = Add<HConstant>(elements);
11695 int elements_length = elements->length();
11696 Handle<FixedArray> fast_elements = Handle<FixedArray>::cast(elements);
11697 for (int i = 0; i < elements_length; i++) {
11698 Handle<Object> value(fast_elements->get(i), isolate());
11699 HValue* key_constant = Add<HConstant>(i);
11700 if (value->IsJSObject()) {
11701 Handle<JSObject> value_object = Handle<JSObject>::cast(value);
11702 Handle<AllocationSite> current_site = site_context->EnterNewScope();
11703 HInstruction* result =
11704 BuildFastLiteral(value_object, site_context);
11705 site_context->ExitScope(current_site, value_object);
11706 Add<HStoreKeyed>(object_elements, key_constant, result, kind);
11708 ElementsKind copy_kind =
11709 kind == FAST_HOLEY_SMI_ELEMENTS ? FAST_HOLEY_ELEMENTS : kind;
11710 HInstruction* value_instruction =
11711 Add<HLoadKeyed>(boilerplate_elements, key_constant, nullptr,
11712 copy_kind, ALLOW_RETURN_HOLE);
11713 Add<HStoreKeyed>(object_elements, key_constant, value_instruction,
11720 void HOptimizedGraphBuilder::VisitThisFunction(ThisFunction* expr) {
11721 DCHECK(!HasStackOverflow());
11722 DCHECK(current_block() != NULL);
11723 DCHECK(current_block()->HasPredecessor());
11724 HInstruction* instr = BuildThisFunction();
11725 return ast_context()->ReturnInstruction(instr, expr->id());
11729 void HOptimizedGraphBuilder::VisitSuperPropertyReference(
11730 SuperPropertyReference* expr) {
11731 DCHECK(!HasStackOverflow());
11732 DCHECK(current_block() != NULL);
11733 DCHECK(current_block()->HasPredecessor());
11734 return Bailout(kSuperReference);
11738 void HOptimizedGraphBuilder::VisitSuperCallReference(SuperCallReference* expr) {
11739 DCHECK(!HasStackOverflow());
11740 DCHECK(current_block() != NULL);
11741 DCHECK(current_block()->HasPredecessor());
11742 return Bailout(kSuperReference);
11746 void HOptimizedGraphBuilder::VisitDeclarations(
11747 ZoneList<Declaration*>* declarations) {
11748 DCHECK(globals_.is_empty());
11749 AstVisitor::VisitDeclarations(declarations);
11750 if (!globals_.is_empty()) {
11751 Handle<FixedArray> array =
11752 isolate()->factory()->NewFixedArray(globals_.length(), TENURED);
11753 for (int i = 0; i < globals_.length(); ++i) array->set(i, *globals_.at(i));
11755 DeclareGlobalsEvalFlag::encode(current_info()->is_eval()) |
11756 DeclareGlobalsNativeFlag::encode(current_info()->is_native()) |
11757 DeclareGlobalsLanguageMode::encode(current_info()->language_mode());
11758 Add<HDeclareGlobals>(array, flags);
11759 globals_.Rewind(0);
11764 void HOptimizedGraphBuilder::VisitVariableDeclaration(
11765 VariableDeclaration* declaration) {
11766 VariableProxy* proxy = declaration->proxy();
11767 VariableMode mode = declaration->mode();
11768 Variable* variable = proxy->var();
11769 bool hole_init = mode == LET || mode == CONST || mode == CONST_LEGACY;
11770 switch (variable->location()) {
11771 case VariableLocation::GLOBAL:
11772 case VariableLocation::UNALLOCATED:
11773 globals_.Add(variable->name(), zone());
11774 globals_.Add(variable->binding_needs_init()
11775 ? isolate()->factory()->the_hole_value()
11776 : isolate()->factory()->undefined_value(), zone());
11778 case VariableLocation::PARAMETER:
11779 case VariableLocation::LOCAL:
11781 HValue* value = graph()->GetConstantHole();
11782 environment()->Bind(variable, value);
11785 case VariableLocation::CONTEXT:
11787 HValue* value = graph()->GetConstantHole();
11788 HValue* context = environment()->context();
11789 HStoreContextSlot* store = Add<HStoreContextSlot>(
11790 context, variable->index(), HStoreContextSlot::kNoCheck, value);
11791 if (store->HasObservableSideEffects()) {
11792 Add<HSimulate>(proxy->id(), REMOVABLE_SIMULATE);
11796 case VariableLocation::LOOKUP:
11797 return Bailout(kUnsupportedLookupSlotInDeclaration);
11802 void HOptimizedGraphBuilder::VisitFunctionDeclaration(
11803 FunctionDeclaration* declaration) {
11804 VariableProxy* proxy = declaration->proxy();
11805 Variable* variable = proxy->var();
11806 switch (variable->location()) {
11807 case VariableLocation::GLOBAL:
11808 case VariableLocation::UNALLOCATED: {
11809 globals_.Add(variable->name(), zone());
11810 Handle<SharedFunctionInfo> function = Compiler::GetSharedFunctionInfo(
11811 declaration->fun(), current_info()->script(), top_info());
11812 // Check for stack-overflow exception.
11813 if (function.is_null()) return SetStackOverflow();
11814 globals_.Add(function, zone());
11817 case VariableLocation::PARAMETER:
11818 case VariableLocation::LOCAL: {
11819 CHECK_ALIVE(VisitForValue(declaration->fun()));
11820 HValue* value = Pop();
11821 BindIfLive(variable, value);
11824 case VariableLocation::CONTEXT: {
11825 CHECK_ALIVE(VisitForValue(declaration->fun()));
11826 HValue* value = Pop();
11827 HValue* context = environment()->context();
11828 HStoreContextSlot* store = Add<HStoreContextSlot>(
11829 context, variable->index(), HStoreContextSlot::kNoCheck, value);
11830 if (store->HasObservableSideEffects()) {
11831 Add<HSimulate>(proxy->id(), REMOVABLE_SIMULATE);
11835 case VariableLocation::LOOKUP:
11836 return Bailout(kUnsupportedLookupSlotInDeclaration);
11841 void HOptimizedGraphBuilder::VisitImportDeclaration(
11842 ImportDeclaration* declaration) {
11847 void HOptimizedGraphBuilder::VisitExportDeclaration(
11848 ExportDeclaration* declaration) {
11853 // Generators for inline runtime functions.
11854 // Support for types.
11855 void HOptimizedGraphBuilder::GenerateIsSmi(CallRuntime* call) {
11856 DCHECK(call->arguments()->length() == 1);
11857 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11858 HValue* value = Pop();
11859 HIsSmiAndBranch* result = New<HIsSmiAndBranch>(value);
11860 return ast_context()->ReturnControl(result, call->id());
11864 void HOptimizedGraphBuilder::GenerateIsSpecObject(CallRuntime* call) {
11865 DCHECK(call->arguments()->length() == 1);
11866 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11867 HValue* value = Pop();
11868 HHasInstanceTypeAndBranch* result =
11869 New<HHasInstanceTypeAndBranch>(value,
11870 FIRST_SPEC_OBJECT_TYPE,
11871 LAST_SPEC_OBJECT_TYPE);
11872 return ast_context()->ReturnControl(result, call->id());
11876 void HOptimizedGraphBuilder::GenerateIsFunction(CallRuntime* call) {
11877 DCHECK(call->arguments()->length() == 1);
11878 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11879 HValue* value = Pop();
11880 HHasInstanceTypeAndBranch* result =
11881 New<HHasInstanceTypeAndBranch>(value, JS_FUNCTION_TYPE);
11882 return ast_context()->ReturnControl(result, call->id());
11886 void HOptimizedGraphBuilder::GenerateIsMinusZero(CallRuntime* call) {
11887 DCHECK(call->arguments()->length() == 1);
11888 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11889 HValue* value = Pop();
11890 HCompareMinusZeroAndBranch* result = New<HCompareMinusZeroAndBranch>(value);
11891 return ast_context()->ReturnControl(result, call->id());
11895 void HOptimizedGraphBuilder::GenerateHasCachedArrayIndex(CallRuntime* call) {
11896 DCHECK(call->arguments()->length() == 1);
11897 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11898 HValue* value = Pop();
11899 HHasCachedArrayIndexAndBranch* result =
11900 New<HHasCachedArrayIndexAndBranch>(value);
11901 return ast_context()->ReturnControl(result, call->id());
11905 void HOptimizedGraphBuilder::GenerateIsArray(CallRuntime* call) {
11906 DCHECK(call->arguments()->length() == 1);
11907 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11908 HValue* value = Pop();
11909 HHasInstanceTypeAndBranch* result =
11910 New<HHasInstanceTypeAndBranch>(value, JS_ARRAY_TYPE);
11911 return ast_context()->ReturnControl(result, call->id());
11915 void HOptimizedGraphBuilder::GenerateIsTypedArray(CallRuntime* call) {
11916 DCHECK(call->arguments()->length() == 1);
11917 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11918 HValue* value = Pop();
11919 HHasInstanceTypeAndBranch* result =
11920 New<HHasInstanceTypeAndBranch>(value, JS_TYPED_ARRAY_TYPE);
11921 return ast_context()->ReturnControl(result, call->id());
11925 void HOptimizedGraphBuilder::GenerateIsRegExp(CallRuntime* call) {
11926 DCHECK(call->arguments()->length() == 1);
11927 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11928 HValue* value = Pop();
11929 HHasInstanceTypeAndBranch* result =
11930 New<HHasInstanceTypeAndBranch>(value, JS_REGEXP_TYPE);
11931 return ast_context()->ReturnControl(result, call->id());
11935 void HOptimizedGraphBuilder::GenerateIsObject(CallRuntime* call) {
11936 DCHECK(call->arguments()->length() == 1);
11937 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11938 HValue* value = Pop();
11939 HIsObjectAndBranch* result = New<HIsObjectAndBranch>(value);
11940 return ast_context()->ReturnControl(result, call->id());
11944 void HOptimizedGraphBuilder::GenerateIsJSProxy(CallRuntime* call) {
11945 DCHECK(call->arguments()->length() == 1);
11946 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11947 HValue* value = Pop();
11948 HIfContinuation continuation;
11949 IfBuilder if_proxy(this);
11951 HValue* smicheck = if_proxy.IfNot<HIsSmiAndBranch>(value);
11953 HValue* map = Add<HLoadNamedField>(value, smicheck, HObjectAccess::ForMap());
11954 HValue* instance_type =
11955 Add<HLoadNamedField>(map, nullptr, HObjectAccess::ForMapInstanceType());
11956 if_proxy.If<HCompareNumericAndBranch>(
11957 instance_type, Add<HConstant>(FIRST_JS_PROXY_TYPE), Token::GTE);
11959 if_proxy.If<HCompareNumericAndBranch>(
11960 instance_type, Add<HConstant>(LAST_JS_PROXY_TYPE), Token::LTE);
11962 if_proxy.CaptureContinuation(&continuation);
11963 return ast_context()->ReturnContinuation(&continuation, call->id());
11967 void HOptimizedGraphBuilder::GenerateHasFastPackedElements(CallRuntime* call) {
11968 DCHECK(call->arguments()->length() == 1);
11969 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11970 HValue* object = Pop();
11971 HIfContinuation continuation(graph()->CreateBasicBlock(),
11972 graph()->CreateBasicBlock());
11973 IfBuilder if_not_smi(this);
11974 if_not_smi.IfNot<HIsSmiAndBranch>(object);
11977 NoObservableSideEffectsScope no_effects(this);
11979 IfBuilder if_fast_packed(this);
11980 HValue* elements_kind = BuildGetElementsKind(object);
11981 if_fast_packed.If<HCompareNumericAndBranch>(
11982 elements_kind, Add<HConstant>(FAST_SMI_ELEMENTS), Token::EQ);
11983 if_fast_packed.Or();
11984 if_fast_packed.If<HCompareNumericAndBranch>(
11985 elements_kind, Add<HConstant>(FAST_ELEMENTS), Token::EQ);
11986 if_fast_packed.Or();
11987 if_fast_packed.If<HCompareNumericAndBranch>(
11988 elements_kind, Add<HConstant>(FAST_DOUBLE_ELEMENTS), Token::EQ);
11989 if_fast_packed.JoinContinuation(&continuation);
11991 if_not_smi.JoinContinuation(&continuation);
11992 return ast_context()->ReturnContinuation(&continuation, call->id());
11996 void HOptimizedGraphBuilder::GenerateIsUndetectableObject(CallRuntime* call) {
11997 DCHECK(call->arguments()->length() == 1);
11998 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11999 HValue* value = Pop();
12000 HIsUndetectableAndBranch* result = New<HIsUndetectableAndBranch>(value);
12001 return ast_context()->ReturnControl(result, call->id());
12005 // Support for construct call checks.
12006 void HOptimizedGraphBuilder::GenerateIsConstructCall(CallRuntime* call) {
12007 DCHECK(call->arguments()->length() == 0);
12008 if (function_state()->outer() != NULL) {
12009 // We are generating graph for inlined function.
12010 HValue* value = function_state()->inlining_kind() == CONSTRUCT_CALL_RETURN
12011 ? graph()->GetConstantTrue()
12012 : graph()->GetConstantFalse();
12013 return ast_context()->ReturnValue(value);
12015 return ast_context()->ReturnControl(New<HIsConstructCallAndBranch>(),
12021 // Support for arguments.length and arguments[?].
12022 void HOptimizedGraphBuilder::GenerateArgumentsLength(CallRuntime* call) {
12023 DCHECK(call->arguments()->length() == 0);
12024 HInstruction* result = NULL;
12025 if (function_state()->outer() == NULL) {
12026 HInstruction* elements = Add<HArgumentsElements>(false);
12027 result = New<HArgumentsLength>(elements);
12029 // Number of arguments without receiver.
12030 int argument_count = environment()->
12031 arguments_environment()->parameter_count() - 1;
12032 result = New<HConstant>(argument_count);
12034 return ast_context()->ReturnInstruction(result, call->id());
12038 void HOptimizedGraphBuilder::GenerateArguments(CallRuntime* call) {
12039 DCHECK(call->arguments()->length() == 1);
12040 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12041 HValue* index = Pop();
12042 HInstruction* result = NULL;
12043 if (function_state()->outer() == NULL) {
12044 HInstruction* elements = Add<HArgumentsElements>(false);
12045 HInstruction* length = Add<HArgumentsLength>(elements);
12046 HInstruction* checked_index = Add<HBoundsCheck>(index, length);
12047 result = New<HAccessArgumentsAt>(elements, length, checked_index);
12049 EnsureArgumentsArePushedForAccess();
12051 // Number of arguments without receiver.
12052 HInstruction* elements = function_state()->arguments_elements();
12053 int argument_count = environment()->
12054 arguments_environment()->parameter_count() - 1;
12055 HInstruction* length = Add<HConstant>(argument_count);
12056 HInstruction* checked_key = Add<HBoundsCheck>(index, length);
12057 result = New<HAccessArgumentsAt>(elements, length, checked_key);
12059 return ast_context()->ReturnInstruction(result, call->id());
12063 void HOptimizedGraphBuilder::GenerateValueOf(CallRuntime* call) {
12064 DCHECK(call->arguments()->length() == 1);
12065 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12066 HValue* object = Pop();
12068 IfBuilder if_objectisvalue(this);
12069 HValue* objectisvalue = if_objectisvalue.If<HHasInstanceTypeAndBranch>(
12070 object, JS_VALUE_TYPE);
12071 if_objectisvalue.Then();
12073 // Return the actual value.
12074 Push(Add<HLoadNamedField>(
12075 object, objectisvalue,
12076 HObjectAccess::ForObservableJSObjectOffset(
12077 JSValue::kValueOffset)));
12078 Add<HSimulate>(call->id(), FIXED_SIMULATE);
12080 if_objectisvalue.Else();
12082 // If the object is not a value return the object.
12084 Add<HSimulate>(call->id(), FIXED_SIMULATE);
12086 if_objectisvalue.End();
12087 return ast_context()->ReturnValue(Pop());
12091 void HOptimizedGraphBuilder::GenerateJSValueGetValue(CallRuntime* call) {
12092 DCHECK(call->arguments()->length() == 1);
12093 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12094 HValue* value = Pop();
12095 HInstruction* result = Add<HLoadNamedField>(
12097 HObjectAccess::ForObservableJSObjectOffset(JSValue::kValueOffset));
12098 return ast_context()->ReturnInstruction(result, call->id());
12102 void HOptimizedGraphBuilder::GenerateIsDate(CallRuntime* call) {
12103 DCHECK_EQ(1, call->arguments()->length());
12104 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12105 HValue* value = Pop();
12106 HHasInstanceTypeAndBranch* result =
12107 New<HHasInstanceTypeAndBranch>(value, JS_DATE_TYPE);
12108 return ast_context()->ReturnControl(result, call->id());
12112 void HOptimizedGraphBuilder::GenerateThrowNotDateError(CallRuntime* call) {
12113 DCHECK_EQ(0, call->arguments()->length());
12114 Add<HDeoptimize>(Deoptimizer::kNotADateObject, Deoptimizer::EAGER);
12115 Add<HSimulate>(call->id(), FIXED_SIMULATE);
12116 return ast_context()->ReturnValue(graph()->GetConstantUndefined());
12120 void HOptimizedGraphBuilder::GenerateDateField(CallRuntime* call) {
12121 DCHECK(call->arguments()->length() == 2);
12122 DCHECK_NOT_NULL(call->arguments()->at(1)->AsLiteral());
12123 Smi* index = Smi::cast(*(call->arguments()->at(1)->AsLiteral()->value()));
12124 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12125 HValue* date = Pop();
12126 HDateField* result = New<HDateField>(date, index);
12127 return ast_context()->ReturnInstruction(result, call->id());
12131 void HOptimizedGraphBuilder::GenerateOneByteSeqStringSetChar(
12132 CallRuntime* call) {
12133 DCHECK(call->arguments()->length() == 3);
12134 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12135 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12136 CHECK_ALIVE(VisitForValue(call->arguments()->at(2)));
12137 HValue* string = Pop();
12138 HValue* value = Pop();
12139 HValue* index = Pop();
12140 Add<HSeqStringSetChar>(String::ONE_BYTE_ENCODING, string,
12142 Add<HSimulate>(call->id(), FIXED_SIMULATE);
12143 return ast_context()->ReturnValue(graph()->GetConstantUndefined());
12147 void HOptimizedGraphBuilder::GenerateTwoByteSeqStringSetChar(
12148 CallRuntime* call) {
12149 DCHECK(call->arguments()->length() == 3);
12150 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12151 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12152 CHECK_ALIVE(VisitForValue(call->arguments()->at(2)));
12153 HValue* string = Pop();
12154 HValue* value = Pop();
12155 HValue* index = Pop();
12156 Add<HSeqStringSetChar>(String::TWO_BYTE_ENCODING, string,
12158 Add<HSimulate>(call->id(), FIXED_SIMULATE);
12159 return ast_context()->ReturnValue(graph()->GetConstantUndefined());
12163 void HOptimizedGraphBuilder::GenerateSetValueOf(CallRuntime* call) {
12164 DCHECK(call->arguments()->length() == 2);
12165 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12166 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12167 HValue* value = Pop();
12168 HValue* object = Pop();
12170 // Check if object is a JSValue.
12171 IfBuilder if_objectisvalue(this);
12172 if_objectisvalue.If<HHasInstanceTypeAndBranch>(object, JS_VALUE_TYPE);
12173 if_objectisvalue.Then();
12175 // Create in-object property store to kValueOffset.
12176 Add<HStoreNamedField>(object,
12177 HObjectAccess::ForObservableJSObjectOffset(JSValue::kValueOffset),
12179 if (!ast_context()->IsEffect()) {
12182 Add<HSimulate>(call->id(), FIXED_SIMULATE);
12184 if_objectisvalue.Else();
12186 // Nothing to do in this case.
12187 if (!ast_context()->IsEffect()) {
12190 Add<HSimulate>(call->id(), FIXED_SIMULATE);
12192 if_objectisvalue.End();
12193 if (!ast_context()->IsEffect()) {
12196 return ast_context()->ReturnValue(value);
12200 // Fast support for charCodeAt(n).
12201 void HOptimizedGraphBuilder::GenerateStringCharCodeAt(CallRuntime* call) {
12202 DCHECK(call->arguments()->length() == 2);
12203 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12204 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12205 HValue* index = Pop();
12206 HValue* string = Pop();
12207 HInstruction* result = BuildStringCharCodeAt(string, index);
12208 return ast_context()->ReturnInstruction(result, call->id());
12212 // Fast support for string.charAt(n) and string[n].
12213 void HOptimizedGraphBuilder::GenerateStringCharFromCode(CallRuntime* call) {
12214 DCHECK(call->arguments()->length() == 1);
12215 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12216 HValue* char_code = Pop();
12217 HInstruction* result = NewUncasted<HStringCharFromCode>(char_code);
12218 return ast_context()->ReturnInstruction(result, call->id());
12222 // Fast support for string.charAt(n) and string[n].
12223 void HOptimizedGraphBuilder::GenerateStringCharAt(CallRuntime* call) {
12224 DCHECK(call->arguments()->length() == 2);
12225 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12226 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12227 HValue* index = Pop();
12228 HValue* string = Pop();
12229 HInstruction* char_code = BuildStringCharCodeAt(string, index);
12230 AddInstruction(char_code);
12231 HInstruction* result = NewUncasted<HStringCharFromCode>(char_code);
12232 return ast_context()->ReturnInstruction(result, call->id());
12236 // Fast support for object equality testing.
12237 void HOptimizedGraphBuilder::GenerateObjectEquals(CallRuntime* call) {
12238 DCHECK(call->arguments()->length() == 2);
12239 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12240 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12241 HValue* right = Pop();
12242 HValue* left = Pop();
12243 HCompareObjectEqAndBranch* result =
12244 New<HCompareObjectEqAndBranch>(left, right);
12245 return ast_context()->ReturnControl(result, call->id());
12249 // Fast support for StringAdd.
12250 void HOptimizedGraphBuilder::GenerateStringAdd(CallRuntime* call) {
12251 DCHECK_EQ(2, call->arguments()->length());
12252 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12253 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12254 HValue* right = Pop();
12255 HValue* left = Pop();
12256 HInstruction* result =
12257 NewUncasted<HStringAdd>(left, right, strength(function_language_mode()));
12258 return ast_context()->ReturnInstruction(result, call->id());
12262 // Fast support for SubString.
12263 void HOptimizedGraphBuilder::GenerateSubString(CallRuntime* call) {
12264 DCHECK_EQ(3, call->arguments()->length());
12265 CHECK_ALIVE(VisitExpressions(call->arguments()));
12266 PushArgumentsFromEnvironment(call->arguments()->length());
12267 HCallStub* result = New<HCallStub>(CodeStub::SubString, 3);
12268 return ast_context()->ReturnInstruction(result, call->id());
12272 // Fast support for StringCompare.
12273 void HOptimizedGraphBuilder::GenerateStringCompare(CallRuntime* call) {
12274 DCHECK_EQ(2, call->arguments()->length());
12275 CHECK_ALIVE(VisitExpressions(call->arguments()));
12276 PushArgumentsFromEnvironment(call->arguments()->length());
12277 HCallStub* result = New<HCallStub>(CodeStub::StringCompare, 2);
12278 return ast_context()->ReturnInstruction(result, call->id());
12282 void HOptimizedGraphBuilder::GenerateStringGetLength(CallRuntime* call) {
12283 DCHECK(call->arguments()->length() == 1);
12284 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12285 HValue* string = Pop();
12286 HInstruction* result = BuildLoadStringLength(string);
12287 return ast_context()->ReturnInstruction(result, call->id());
12291 // Support for direct calls from JavaScript to native RegExp code.
12292 void HOptimizedGraphBuilder::GenerateRegExpExec(CallRuntime* call) {
12293 DCHECK_EQ(4, call->arguments()->length());
12294 CHECK_ALIVE(VisitExpressions(call->arguments()));
12295 PushArgumentsFromEnvironment(call->arguments()->length());
12296 HCallStub* result = New<HCallStub>(CodeStub::RegExpExec, 4);
12297 return ast_context()->ReturnInstruction(result, call->id());
12301 void HOptimizedGraphBuilder::GenerateDoubleLo(CallRuntime* call) {
12302 DCHECK_EQ(1, call->arguments()->length());
12303 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12304 HValue* value = Pop();
12305 HInstruction* result = NewUncasted<HDoubleBits>(value, HDoubleBits::LOW);
12306 return ast_context()->ReturnInstruction(result, call->id());
12310 void HOptimizedGraphBuilder::GenerateDoubleHi(CallRuntime* call) {
12311 DCHECK_EQ(1, call->arguments()->length());
12312 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12313 HValue* value = Pop();
12314 HInstruction* result = NewUncasted<HDoubleBits>(value, HDoubleBits::HIGH);
12315 return ast_context()->ReturnInstruction(result, call->id());
12319 void HOptimizedGraphBuilder::GenerateConstructDouble(CallRuntime* call) {
12320 DCHECK_EQ(2, call->arguments()->length());
12321 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12322 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12323 HValue* lo = Pop();
12324 HValue* hi = Pop();
12325 HInstruction* result = NewUncasted<HConstructDouble>(hi, lo);
12326 return ast_context()->ReturnInstruction(result, call->id());
12330 // Construct a RegExp exec result with two in-object properties.
12331 void HOptimizedGraphBuilder::GenerateRegExpConstructResult(CallRuntime* call) {
12332 DCHECK_EQ(3, call->arguments()->length());
12333 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12334 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12335 CHECK_ALIVE(VisitForValue(call->arguments()->at(2)));
12336 HValue* input = Pop();
12337 HValue* index = Pop();
12338 HValue* length = Pop();
12339 HValue* result = BuildRegExpConstructResult(length, index, input);
12340 return ast_context()->ReturnValue(result);
12344 // Support for fast native caches.
12345 void HOptimizedGraphBuilder::GenerateGetFromCache(CallRuntime* call) {
12346 return Bailout(kInlinedRuntimeFunctionGetFromCache);
12350 // Fast support for number to string.
12351 void HOptimizedGraphBuilder::GenerateNumberToString(CallRuntime* call) {
12352 DCHECK_EQ(1, call->arguments()->length());
12353 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12354 HValue* number = Pop();
12355 HValue* result = BuildNumberToString(number, Type::Any(zone()));
12356 return ast_context()->ReturnValue(result);
12360 // Fast call for custom callbacks.
12361 void HOptimizedGraphBuilder::GenerateCallFunction(CallRuntime* call) {
12362 // 1 ~ The function to call is not itself an argument to the call.
12363 int arg_count = call->arguments()->length() - 1;
12364 DCHECK(arg_count >= 1); // There's always at least a receiver.
12366 CHECK_ALIVE(VisitExpressions(call->arguments()));
12367 // The function is the last argument
12368 HValue* function = Pop();
12369 // Push the arguments to the stack
12370 PushArgumentsFromEnvironment(arg_count);
12372 IfBuilder if_is_jsfunction(this);
12373 if_is_jsfunction.If<HHasInstanceTypeAndBranch>(function, JS_FUNCTION_TYPE);
12375 if_is_jsfunction.Then();
12377 HInstruction* invoke_result =
12378 Add<HInvokeFunction>(function, arg_count);
12379 if (!ast_context()->IsEffect()) {
12380 Push(invoke_result);
12382 Add<HSimulate>(call->id(), FIXED_SIMULATE);
12385 if_is_jsfunction.Else();
12387 HInstruction* call_result =
12388 Add<HCallFunction>(function, arg_count);
12389 if (!ast_context()->IsEffect()) {
12392 Add<HSimulate>(call->id(), FIXED_SIMULATE);
12394 if_is_jsfunction.End();
12396 if (ast_context()->IsEffect()) {
12397 // EffectContext::ReturnValue ignores the value, so we can just pass
12398 // 'undefined' (as we do not have the call result anymore).
12399 return ast_context()->ReturnValue(graph()->GetConstantUndefined());
12401 return ast_context()->ReturnValue(Pop());
12406 // Fast call to math functions.
12407 void HOptimizedGraphBuilder::GenerateMathPow(CallRuntime* call) {
12408 DCHECK_EQ(2, call->arguments()->length());
12409 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12410 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12411 HValue* right = Pop();
12412 HValue* left = Pop();
12413 HInstruction* result = NewUncasted<HPower>(left, right);
12414 return ast_context()->ReturnInstruction(result, call->id());
12418 void HOptimizedGraphBuilder::GenerateMathClz32(CallRuntime* call) {
12419 DCHECK(call->arguments()->length() == 1);
12420 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12421 HValue* value = Pop();
12422 HInstruction* result = NewUncasted<HUnaryMathOperation>(value, kMathClz32);
12423 return ast_context()->ReturnInstruction(result, call->id());
12427 void HOptimizedGraphBuilder::GenerateMathFloor(CallRuntime* call) {
12428 DCHECK(call->arguments()->length() == 1);
12429 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12430 HValue* value = Pop();
12431 HInstruction* result = NewUncasted<HUnaryMathOperation>(value, kMathFloor);
12432 return ast_context()->ReturnInstruction(result, call->id());
12436 void HOptimizedGraphBuilder::GenerateMathLogRT(CallRuntime* call) {
12437 DCHECK(call->arguments()->length() == 1);
12438 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12439 HValue* value = Pop();
12440 HInstruction* result = NewUncasted<HUnaryMathOperation>(value, kMathLog);
12441 return ast_context()->ReturnInstruction(result, call->id());
12445 void HOptimizedGraphBuilder::GenerateMathSqrt(CallRuntime* call) {
12446 DCHECK(call->arguments()->length() == 1);
12447 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12448 HValue* value = Pop();
12449 HInstruction* result = NewUncasted<HUnaryMathOperation>(value, kMathSqrt);
12450 return ast_context()->ReturnInstruction(result, call->id());
12454 void HOptimizedGraphBuilder::GenerateLikely(CallRuntime* call) {
12455 DCHECK(call->arguments()->length() == 1);
12456 Visit(call->arguments()->at(0));
12460 void HOptimizedGraphBuilder::GenerateUnlikely(CallRuntime* call) {
12461 return GenerateLikely(call);
12465 void HOptimizedGraphBuilder::GenerateFixedArrayGet(CallRuntime* call) {
12466 DCHECK(call->arguments()->length() == 2);
12467 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12468 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12469 HValue* index = Pop();
12470 HValue* object = Pop();
12471 HInstruction* result = New<HLoadKeyed>(
12472 object, index, nullptr, FAST_HOLEY_ELEMENTS, ALLOW_RETURN_HOLE);
12473 return ast_context()->ReturnInstruction(result, call->id());
12477 void HOptimizedGraphBuilder::GenerateFixedArraySet(CallRuntime* call) {
12478 DCHECK(call->arguments()->length() == 3);
12479 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12480 CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12481 CHECK_ALIVE(VisitForValue(call->arguments()->at(2)));
12482 HValue* value = Pop();
12483 HValue* index = Pop();
12484 HValue* object = Pop();
12485 NoObservableSideEffectsScope no_effects(this);
12486 Add<HStoreKeyed>(object, index, value, FAST_HOLEY_ELEMENTS);
12487 return ast_context()->ReturnValue(graph()->GetConstantUndefined());
12491 void HOptimizedGraphBuilder::GenerateTheHole(CallRuntime* call) {
12492 DCHECK(call->arguments()->length() == 0);
12493 return ast_context()->ReturnValue(graph()->GetConstantHole());
12497 void HOptimizedGraphBuilder::GenerateJSCollectionGetTable(CallRuntime* call) {
12498 DCHECK(call->arguments()->length() == 1);
12499 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12500 HValue* receiver = Pop();
12501 HInstruction* result = New<HLoadNamedField>(
12502 receiver, nullptr, HObjectAccess::ForJSCollectionTable());
12503 return ast_context()->ReturnInstruction(result, call->id());
12507 void HOptimizedGraphBuilder::GenerateStringGetRawHashField(CallRuntime* call) {
12508 DCHECK(call->arguments()->length() == 1);
12509 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12510 HValue* object = Pop();
12511 HInstruction* result = New<HLoadNamedField>(
12512 object, nullptr, HObjectAccess::ForStringHashField());
12513 return ast_context()->ReturnInstruction(result, call->id());
12517 template <typename CollectionType>
12518 HValue* HOptimizedGraphBuilder::BuildAllocateOrderedHashTable() {
12519 static const int kCapacity = CollectionType::kMinCapacity;
12520 static const int kBucketCount = kCapacity / CollectionType::kLoadFactor;
12521 static const int kFixedArrayLength = CollectionType::kHashTableStartIndex +
12523 (kCapacity * CollectionType::kEntrySize);
12524 static const int kSizeInBytes =
12525 FixedArray::kHeaderSize + (kFixedArrayLength * kPointerSize);
12527 // Allocate the table and add the proper map.
12529 Add<HAllocate>(Add<HConstant>(kSizeInBytes), HType::HeapObject(),
12530 NOT_TENURED, FIXED_ARRAY_TYPE);
12531 AddStoreMapConstant(table, isolate()->factory()->ordered_hash_table_map());
12533 // Initialize the FixedArray...
12534 HValue* length = Add<HConstant>(kFixedArrayLength);
12535 Add<HStoreNamedField>(table, HObjectAccess::ForFixedArrayLength(), length);
12537 // ...and the OrderedHashTable fields.
12538 Add<HStoreNamedField>(
12540 HObjectAccess::ForOrderedHashTableNumberOfBuckets<CollectionType>(),
12541 Add<HConstant>(kBucketCount));
12542 Add<HStoreNamedField>(
12544 HObjectAccess::ForOrderedHashTableNumberOfElements<CollectionType>(),
12545 graph()->GetConstant0());
12546 Add<HStoreNamedField>(
12547 table, HObjectAccess::ForOrderedHashTableNumberOfDeletedElements<
12549 graph()->GetConstant0());
12551 // Fill the buckets with kNotFound.
12552 HValue* not_found = Add<HConstant>(CollectionType::kNotFound);
12553 for (int i = 0; i < kBucketCount; ++i) {
12554 Add<HStoreNamedField>(
12555 table, HObjectAccess::ForOrderedHashTableBucket<CollectionType>(i),
12559 // Fill the data table with undefined.
12560 HValue* undefined = graph()->GetConstantUndefined();
12561 for (int i = 0; i < (kCapacity * CollectionType::kEntrySize); ++i) {
12562 Add<HStoreNamedField>(table,
12563 HObjectAccess::ForOrderedHashTableDataTableIndex<
12564 CollectionType, kBucketCount>(i),
12572 void HOptimizedGraphBuilder::GenerateSetInitialize(CallRuntime* call) {
12573 DCHECK(call->arguments()->length() == 1);
12574 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12575 HValue* receiver = Pop();
12577 NoObservableSideEffectsScope no_effects(this);
12578 HValue* table = BuildAllocateOrderedHashTable<OrderedHashSet>();
12579 Add<HStoreNamedField>(receiver, HObjectAccess::ForJSCollectionTable(), table);
12580 return ast_context()->ReturnValue(receiver);
12584 void HOptimizedGraphBuilder::GenerateMapInitialize(CallRuntime* call) {
12585 DCHECK(call->arguments()->length() == 1);
12586 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12587 HValue* receiver = Pop();
12589 NoObservableSideEffectsScope no_effects(this);
12590 HValue* table = BuildAllocateOrderedHashTable<OrderedHashMap>();
12591 Add<HStoreNamedField>(receiver, HObjectAccess::ForJSCollectionTable(), table);
12592 return ast_context()->ReturnValue(receiver);
12596 template <typename CollectionType>
12597 void HOptimizedGraphBuilder::BuildOrderedHashTableClear(HValue* receiver) {
12598 HValue* old_table = Add<HLoadNamedField>(
12599 receiver, nullptr, HObjectAccess::ForJSCollectionTable());
12600 HValue* new_table = BuildAllocateOrderedHashTable<CollectionType>();
12601 Add<HStoreNamedField>(
12602 old_table, HObjectAccess::ForOrderedHashTableNextTable<CollectionType>(),
12604 Add<HStoreNamedField>(
12605 old_table, HObjectAccess::ForOrderedHashTableNumberOfDeletedElements<
12607 Add<HConstant>(CollectionType::kClearedTableSentinel));
12608 Add<HStoreNamedField>(receiver, HObjectAccess::ForJSCollectionTable(),
12613 void HOptimizedGraphBuilder::GenerateSetClear(CallRuntime* call) {
12614 DCHECK(call->arguments()->length() == 1);
12615 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12616 HValue* receiver = Pop();
12618 NoObservableSideEffectsScope no_effects(this);
12619 BuildOrderedHashTableClear<OrderedHashSet>(receiver);
12620 return ast_context()->ReturnValue(graph()->GetConstantUndefined());
12624 void HOptimizedGraphBuilder::GenerateMapClear(CallRuntime* call) {
12625 DCHECK(call->arguments()->length() == 1);
12626 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12627 HValue* receiver = Pop();
12629 NoObservableSideEffectsScope no_effects(this);
12630 BuildOrderedHashTableClear<OrderedHashMap>(receiver);
12631 return ast_context()->ReturnValue(graph()->GetConstantUndefined());
12635 void HOptimizedGraphBuilder::GenerateGetCachedArrayIndex(CallRuntime* call) {
12636 DCHECK(call->arguments()->length() == 1);
12637 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12638 HValue* value = Pop();
12639 HGetCachedArrayIndex* result = New<HGetCachedArrayIndex>(value);
12640 return ast_context()->ReturnInstruction(result, call->id());
12644 void HOptimizedGraphBuilder::GenerateFastOneByteArrayJoin(CallRuntime* call) {
12645 // Simply returning undefined here would be semantically correct and even
12646 // avoid the bailout. Nevertheless, some ancient benchmarks like SunSpider's
12647 // string-fasta would tank, because fullcode contains an optimized version.
12648 // Obviously the fullcode => Crankshaft => bailout => fullcode dance is
12649 // faster... *sigh*
12650 return Bailout(kInlinedRuntimeFunctionFastOneByteArrayJoin);
12654 void HOptimizedGraphBuilder::GenerateDebugBreakInOptimizedCode(
12655 CallRuntime* call) {
12656 Add<HDebugBreak>();
12657 return ast_context()->ReturnValue(graph()->GetConstant0());
12661 void HOptimizedGraphBuilder::GenerateDebugIsActive(CallRuntime* call) {
12662 DCHECK(call->arguments()->length() == 0);
12664 Add<HConstant>(ExternalReference::debug_is_active_address(isolate()));
12666 Add<HLoadNamedField>(ref, nullptr, HObjectAccess::ForExternalUInteger8());
12667 return ast_context()->ReturnValue(value);
12671 void HOptimizedGraphBuilder::GenerateGetPrototype(CallRuntime* call) {
12672 DCHECK(call->arguments()->length() == 1);
12673 CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12674 HValue* object = Pop();
12676 NoObservableSideEffectsScope no_effects(this);
12678 HValue* map = Add<HLoadNamedField>(object, nullptr, HObjectAccess::ForMap());
12679 HValue* bit_field =
12680 Add<HLoadNamedField>(map, nullptr, HObjectAccess::ForMapBitField());
12681 HValue* is_access_check_needed_mask =
12682 Add<HConstant>(1 << Map::kIsAccessCheckNeeded);
12683 HValue* is_access_check_needed_test = AddUncasted<HBitwise>(
12684 Token::BIT_AND, bit_field, is_access_check_needed_mask);
12687 Add<HLoadNamedField>(map, nullptr, HObjectAccess::ForPrototype());
12688 HValue* proto_map =
12689 Add<HLoadNamedField>(proto, nullptr, HObjectAccess::ForMap());
12690 HValue* proto_bit_field =
12691 Add<HLoadNamedField>(proto_map, nullptr, HObjectAccess::ForMapBitField());
12692 HValue* is_hidden_prototype_mask =
12693 Add<HConstant>(1 << Map::kIsHiddenPrototype);
12694 HValue* is_hidden_prototype_test = AddUncasted<HBitwise>(
12695 Token::BIT_AND, proto_bit_field, is_hidden_prototype_mask);
12698 IfBuilder needs_runtime(this);
12699 needs_runtime.If<HCompareNumericAndBranch>(
12700 is_access_check_needed_test, graph()->GetConstant0(), Token::NE);
12701 needs_runtime.OrIf<HCompareNumericAndBranch>(
12702 is_hidden_prototype_test, graph()->GetConstant0(), Token::NE);
12704 needs_runtime.Then();
12706 Add<HPushArguments>(object);
12707 Push(Add<HCallRuntime>(
12708 call->name(), Runtime::FunctionForId(Runtime::kGetPrototype), 1));
12711 needs_runtime.Else();
12714 return ast_context()->ReturnValue(Pop());
12718 #undef CHECK_BAILOUT
12722 HEnvironment::HEnvironment(HEnvironment* outer,
12724 Handle<JSFunction> closure,
12726 : closure_(closure),
12728 frame_type_(JS_FUNCTION),
12729 parameter_count_(0),
12730 specials_count_(1),
12736 ast_id_(BailoutId::None()),
12738 Scope* declaration_scope = scope->DeclarationScope();
12739 Initialize(declaration_scope->num_parameters() + 1,
12740 declaration_scope->num_stack_slots(), 0);
12744 HEnvironment::HEnvironment(Zone* zone, int parameter_count)
12745 : values_(0, zone),
12747 parameter_count_(parameter_count),
12748 specials_count_(1),
12754 ast_id_(BailoutId::None()),
12756 Initialize(parameter_count, 0, 0);
12760 HEnvironment::HEnvironment(const HEnvironment* other, Zone* zone)
12761 : values_(0, zone),
12762 frame_type_(JS_FUNCTION),
12763 parameter_count_(0),
12764 specials_count_(0),
12770 ast_id_(other->ast_id()),
12776 HEnvironment::HEnvironment(HEnvironment* outer,
12777 Handle<JSFunction> closure,
12778 FrameType frame_type,
12781 : closure_(closure),
12782 values_(arguments, zone),
12783 frame_type_(frame_type),
12784 parameter_count_(arguments),
12785 specials_count_(0),
12791 ast_id_(BailoutId::None()),
12796 void HEnvironment::Initialize(int parameter_count,
12798 int stack_height) {
12799 parameter_count_ = parameter_count;
12800 local_count_ = local_count;
12802 // Avoid reallocating the temporaries' backing store on the first Push.
12803 int total = parameter_count + specials_count_ + local_count + stack_height;
12804 values_.Initialize(total + 4, zone());
12805 for (int i = 0; i < total; ++i) values_.Add(NULL, zone());
12809 void HEnvironment::Initialize(const HEnvironment* other) {
12810 closure_ = other->closure();
12811 values_.AddAll(other->values_, zone());
12812 assigned_variables_.Union(other->assigned_variables_, zone());
12813 frame_type_ = other->frame_type_;
12814 parameter_count_ = other->parameter_count_;
12815 local_count_ = other->local_count_;
12816 if (other->outer_ != NULL) outer_ = other->outer_->Copy(); // Deep copy.
12817 entry_ = other->entry_;
12818 pop_count_ = other->pop_count_;
12819 push_count_ = other->push_count_;
12820 specials_count_ = other->specials_count_;
12821 ast_id_ = other->ast_id_;
12825 void HEnvironment::AddIncomingEdge(HBasicBlock* block, HEnvironment* other) {
12826 DCHECK(!block->IsLoopHeader());
12827 DCHECK(values_.length() == other->values_.length());
12829 int length = values_.length();
12830 for (int i = 0; i < length; ++i) {
12831 HValue* value = values_[i];
12832 if (value != NULL && value->IsPhi() && value->block() == block) {
12833 // There is already a phi for the i'th value.
12834 HPhi* phi = HPhi::cast(value);
12835 // Assert index is correct and that we haven't missed an incoming edge.
12836 DCHECK(phi->merged_index() == i || !phi->HasMergedIndex());
12837 DCHECK(phi->OperandCount() == block->predecessors()->length());
12838 phi->AddInput(other->values_[i]);
12839 } else if (values_[i] != other->values_[i]) {
12840 // There is a fresh value on the incoming edge, a phi is needed.
12841 DCHECK(values_[i] != NULL && other->values_[i] != NULL);
12842 HPhi* phi = block->AddNewPhi(i);
12843 HValue* old_value = values_[i];
12844 for (int j = 0; j < block->predecessors()->length(); j++) {
12845 phi->AddInput(old_value);
12847 phi->AddInput(other->values_[i]);
12848 this->values_[i] = phi;
12854 void HEnvironment::Bind(int index, HValue* value) {
12855 DCHECK(value != NULL);
12856 assigned_variables_.Add(index, zone());
12857 values_[index] = value;
12861 bool HEnvironment::HasExpressionAt(int index) const {
12862 return index >= parameter_count_ + specials_count_ + local_count_;
12866 bool HEnvironment::ExpressionStackIsEmpty() const {
12867 DCHECK(length() >= first_expression_index());
12868 return length() == first_expression_index();
12872 void HEnvironment::SetExpressionStackAt(int index_from_top, HValue* value) {
12873 int count = index_from_top + 1;
12874 int index = values_.length() - count;
12875 DCHECK(HasExpressionAt(index));
12876 // The push count must include at least the element in question or else
12877 // the new value will not be included in this environment's history.
12878 if (push_count_ < count) {
12879 // This is the same effect as popping then re-pushing 'count' elements.
12880 pop_count_ += (count - push_count_);
12881 push_count_ = count;
12883 values_[index] = value;
12887 HValue* HEnvironment::RemoveExpressionStackAt(int index_from_top) {
12888 int count = index_from_top + 1;
12889 int index = values_.length() - count;
12890 DCHECK(HasExpressionAt(index));
12891 // Simulate popping 'count' elements and then
12892 // pushing 'count - 1' elements back.
12893 pop_count_ += Max(count - push_count_, 0);
12894 push_count_ = Max(push_count_ - count, 0) + (count - 1);
12895 return values_.Remove(index);
12899 void HEnvironment::Drop(int count) {
12900 for (int i = 0; i < count; ++i) {
12906 HEnvironment* HEnvironment::Copy() const {
12907 return new(zone()) HEnvironment(this, zone());
12911 HEnvironment* HEnvironment::CopyWithoutHistory() const {
12912 HEnvironment* result = Copy();
12913 result->ClearHistory();
12918 HEnvironment* HEnvironment::CopyAsLoopHeader(HBasicBlock* loop_header) const {
12919 HEnvironment* new_env = Copy();
12920 for (int i = 0; i < values_.length(); ++i) {
12921 HPhi* phi = loop_header->AddNewPhi(i);
12922 phi->AddInput(values_[i]);
12923 new_env->values_[i] = phi;
12925 new_env->ClearHistory();
12930 HEnvironment* HEnvironment::CreateStubEnvironment(HEnvironment* outer,
12931 Handle<JSFunction> target,
12932 FrameType frame_type,
12933 int arguments) const {
12934 HEnvironment* new_env =
12935 new(zone()) HEnvironment(outer, target, frame_type,
12936 arguments + 1, zone());
12937 for (int i = 0; i <= arguments; ++i) { // Include receiver.
12938 new_env->Push(ExpressionStackAt(arguments - i));
12940 new_env->ClearHistory();
12945 HEnvironment* HEnvironment::CopyForInlining(
12946 Handle<JSFunction> target,
12948 FunctionLiteral* function,
12949 HConstant* undefined,
12950 InliningKind inlining_kind) const {
12951 DCHECK(frame_type() == JS_FUNCTION);
12953 // Outer environment is a copy of this one without the arguments.
12954 int arity = function->scope()->num_parameters();
12956 HEnvironment* outer = Copy();
12957 outer->Drop(arguments + 1); // Including receiver.
12958 outer->ClearHistory();
12960 if (inlining_kind == CONSTRUCT_CALL_RETURN) {
12961 // Create artificial constructor stub environment. The receiver should
12962 // actually be the constructor function, but we pass the newly allocated
12963 // object instead, DoComputeConstructStubFrame() relies on that.
12964 outer = CreateStubEnvironment(outer, target, JS_CONSTRUCT, arguments);
12965 } else if (inlining_kind == GETTER_CALL_RETURN) {
12966 // We need an additional StackFrame::INTERNAL frame for restoring the
12967 // correct context.
12968 outer = CreateStubEnvironment(outer, target, JS_GETTER, arguments);
12969 } else if (inlining_kind == SETTER_CALL_RETURN) {
12970 // We need an additional StackFrame::INTERNAL frame for temporarily saving
12971 // the argument of the setter, see StoreStubCompiler::CompileStoreViaSetter.
12972 outer = CreateStubEnvironment(outer, target, JS_SETTER, arguments);
12975 if (arity != arguments) {
12976 // Create artificial arguments adaptation environment.
12977 outer = CreateStubEnvironment(outer, target, ARGUMENTS_ADAPTOR, arguments);
12980 HEnvironment* inner =
12981 new(zone()) HEnvironment(outer, function->scope(), target, zone());
12982 // Get the argument values from the original environment.
12983 for (int i = 0; i <= arity; ++i) { // Include receiver.
12984 HValue* push = (i <= arguments) ?
12985 ExpressionStackAt(arguments - i) : undefined;
12986 inner->SetValueAt(i, push);
12988 inner->SetValueAt(arity + 1, context());
12989 for (int i = arity + 2; i < inner->length(); ++i) {
12990 inner->SetValueAt(i, undefined);
12993 inner->set_ast_id(BailoutId::FunctionEntry());
12998 std::ostream& operator<<(std::ostream& os, const HEnvironment& env) {
12999 for (int i = 0; i < env.length(); i++) {
13000 if (i == 0) os << "parameters\n";
13001 if (i == env.parameter_count()) os << "specials\n";
13002 if (i == env.parameter_count() + env.specials_count()) os << "locals\n";
13003 if (i == env.parameter_count() + env.specials_count() + env.local_count()) {
13004 os << "expressions\n";
13006 HValue* val = env.values()->at(i);
13019 void HTracer::TraceCompilation(CompilationInfo* info) {
13020 Tag tag(this, "compilation");
13021 if (info->IsOptimizing()) {
13022 Handle<String> name = info->function()->debug_name();
13023 PrintStringProperty("name", name->ToCString().get());
13025 trace_.Add("method \"%s:%d\"\n",
13026 name->ToCString().get(),
13027 info->optimization_id());
13029 CodeStub::Major major_key = info->code_stub()->MajorKey();
13030 PrintStringProperty("name", CodeStub::MajorName(major_key, false));
13031 PrintStringProperty("method", "stub");
13033 PrintLongProperty("date",
13034 static_cast<int64_t>(base::OS::TimeCurrentMillis()));
13038 void HTracer::TraceLithium(const char* name, LChunk* chunk) {
13039 DCHECK(!chunk->isolate()->concurrent_recompilation_enabled());
13040 AllowHandleDereference allow_deref;
13041 AllowDeferredHandleDereference allow_deferred_deref;
13042 Trace(name, chunk->graph(), chunk);
13046 void HTracer::TraceHydrogen(const char* name, HGraph* graph) {
13047 DCHECK(!graph->isolate()->concurrent_recompilation_enabled());
13048 AllowHandleDereference allow_deref;
13049 AllowDeferredHandleDereference allow_deferred_deref;
13050 Trace(name, graph, NULL);
13054 void HTracer::Trace(const char* name, HGraph* graph, LChunk* chunk) {
13055 Tag tag(this, "cfg");
13056 PrintStringProperty("name", name);
13057 const ZoneList<HBasicBlock*>* blocks = graph->blocks();
13058 for (int i = 0; i < blocks->length(); i++) {
13059 HBasicBlock* current = blocks->at(i);
13060 Tag block_tag(this, "block");
13061 PrintBlockProperty("name", current->block_id());
13062 PrintIntProperty("from_bci", -1);
13063 PrintIntProperty("to_bci", -1);
13065 if (!current->predecessors()->is_empty()) {
13067 trace_.Add("predecessors");
13068 for (int j = 0; j < current->predecessors()->length(); ++j) {
13069 trace_.Add(" \"B%d\"", current->predecessors()->at(j)->block_id());
13073 PrintEmptyProperty("predecessors");
13076 if (current->end()->SuccessorCount() == 0) {
13077 PrintEmptyProperty("successors");
13080 trace_.Add("successors");
13081 for (HSuccessorIterator it(current->end()); !it.Done(); it.Advance()) {
13082 trace_.Add(" \"B%d\"", it.Current()->block_id());
13087 PrintEmptyProperty("xhandlers");
13091 trace_.Add("flags");
13092 if (current->IsLoopSuccessorDominator()) {
13093 trace_.Add(" \"dom-loop-succ\"");
13095 if (current->IsUnreachable()) {
13096 trace_.Add(" \"dead\"");
13098 if (current->is_osr_entry()) {
13099 trace_.Add(" \"osr\"");
13104 if (current->dominator() != NULL) {
13105 PrintBlockProperty("dominator", current->dominator()->block_id());
13108 PrintIntProperty("loop_depth", current->LoopNestingDepth());
13110 if (chunk != NULL) {
13111 int first_index = current->first_instruction_index();
13112 int last_index = current->last_instruction_index();
13115 LifetimePosition::FromInstructionIndex(first_index).Value());
13118 LifetimePosition::FromInstructionIndex(last_index).Value());
13122 Tag states_tag(this, "states");
13123 Tag locals_tag(this, "locals");
13124 int total = current->phis()->length();
13125 PrintIntProperty("size", current->phis()->length());
13126 PrintStringProperty("method", "None");
13127 for (int j = 0; j < total; ++j) {
13128 HPhi* phi = current->phis()->at(j);
13130 std::ostringstream os;
13131 os << phi->merged_index() << " " << NameOf(phi) << " " << *phi << "\n";
13132 trace_.Add(os.str().c_str());
13137 Tag HIR_tag(this, "HIR");
13138 for (HInstructionIterator it(current); !it.Done(); it.Advance()) {
13139 HInstruction* instruction = it.Current();
13140 int uses = instruction->UseCount();
13142 std::ostringstream os;
13143 os << "0 " << uses << " " << NameOf(instruction) << " " << *instruction;
13144 if (graph->info()->is_tracking_positions() &&
13145 instruction->has_position() && instruction->position().raw() != 0) {
13146 const SourcePosition pos = instruction->position();
13148 if (pos.inlining_id() != 0) os << pos.inlining_id() << "_";
13149 os << pos.position();
13152 trace_.Add(os.str().c_str());
13157 if (chunk != NULL) {
13158 Tag LIR_tag(this, "LIR");
13159 int first_index = current->first_instruction_index();
13160 int last_index = current->last_instruction_index();
13161 if (first_index != -1 && last_index != -1) {
13162 const ZoneList<LInstruction*>* instructions = chunk->instructions();
13163 for (int i = first_index; i <= last_index; ++i) {
13164 LInstruction* linstr = instructions->at(i);
13165 if (linstr != NULL) {
13168 LifetimePosition::FromInstructionIndex(i).Value());
13169 linstr->PrintTo(&trace_);
13170 std::ostringstream os;
13171 os << " [hir:" << NameOf(linstr->hydrogen_value()) << "] <|@\n";
13172 trace_.Add(os.str().c_str());
13181 void HTracer::TraceLiveRanges(const char* name, LAllocator* allocator) {
13182 Tag tag(this, "intervals");
13183 PrintStringProperty("name", name);
13185 const Vector<LiveRange*>* fixed_d = allocator->fixed_double_live_ranges();
13186 for (int i = 0; i < fixed_d->length(); ++i) {
13187 TraceLiveRange(fixed_d->at(i), "fixed", allocator->zone());
13190 const Vector<LiveRange*>* fixed = allocator->fixed_live_ranges();
13191 for (int i = 0; i < fixed->length(); ++i) {
13192 TraceLiveRange(fixed->at(i), "fixed", allocator->zone());
13195 const ZoneList<LiveRange*>* live_ranges = allocator->live_ranges();
13196 for (int i = 0; i < live_ranges->length(); ++i) {
13197 TraceLiveRange(live_ranges->at(i), "object", allocator->zone());
13202 void HTracer::TraceLiveRange(LiveRange* range, const char* type,
13204 if (range != NULL && !range->IsEmpty()) {
13206 trace_.Add("%d %s", range->id(), type);
13207 if (range->HasRegisterAssigned()) {
13208 LOperand* op = range->CreateAssignedOperand(zone);
13209 int assigned_reg = op->index();
13210 if (op->IsDoubleRegister()) {
13211 trace_.Add(" \"%s\"",
13212 DoubleRegister::AllocationIndexToString(assigned_reg));
13214 DCHECK(op->IsRegister());
13215 trace_.Add(" \"%s\"", Register::AllocationIndexToString(assigned_reg));
13217 } else if (range->IsSpilled()) {
13218 LOperand* op = range->TopLevel()->GetSpillOperand();
13219 if (op->IsDoubleStackSlot()) {
13220 trace_.Add(" \"double_stack:%d\"", op->index());
13222 DCHECK(op->IsStackSlot());
13223 trace_.Add(" \"stack:%d\"", op->index());
13226 int parent_index = -1;
13227 if (range->IsChild()) {
13228 parent_index = range->parent()->id();
13230 parent_index = range->id();
13232 LOperand* op = range->FirstHint();
13233 int hint_index = -1;
13234 if (op != NULL && op->IsUnallocated()) {
13235 hint_index = LUnallocated::cast(op)->virtual_register();
13237 trace_.Add(" %d %d", parent_index, hint_index);
13238 UseInterval* cur_interval = range->first_interval();
13239 while (cur_interval != NULL && range->Covers(cur_interval->start())) {
13240 trace_.Add(" [%d, %d[",
13241 cur_interval->start().Value(),
13242 cur_interval->end().Value());
13243 cur_interval = cur_interval->next();
13246 UsePosition* current_pos = range->first_pos();
13247 while (current_pos != NULL) {
13248 if (current_pos->RegisterIsBeneficial() || FLAG_trace_all_uses) {
13249 trace_.Add(" %d M", current_pos->pos().Value());
13251 current_pos = current_pos->next();
13254 trace_.Add(" \"\"\n");
13259 void HTracer::FlushToFile() {
13260 AppendChars(filename_.start(), trace_.ToCString().get(), trace_.length(),
13266 void HStatistics::Initialize(CompilationInfo* info) {
13267 if (info->shared_info().is_null()) return;
13268 source_size_ += info->shared_info()->SourceSize();
13272 void HStatistics::Print() {
13275 "----------------------------------------"
13276 "----------------------------------------\n"
13277 "--- Hydrogen timing results:\n"
13278 "----------------------------------------"
13279 "----------------------------------------\n");
13280 base::TimeDelta sum;
13281 for (int i = 0; i < times_.length(); ++i) {
13285 for (int i = 0; i < names_.length(); ++i) {
13286 PrintF("%33s", names_[i]);
13287 double ms = times_[i].InMillisecondsF();
13288 double percent = times_[i].PercentOf(sum);
13289 PrintF(" %8.3f ms / %4.1f %% ", ms, percent);
13291 size_t size = sizes_[i];
13292 double size_percent = static_cast<double>(size) * 100 / total_size_;
13293 PrintF(" %9zu bytes / %4.1f %%\n", size, size_percent);
13297 "----------------------------------------"
13298 "----------------------------------------\n");
13299 base::TimeDelta total = create_graph_ + optimize_graph_ + generate_code_;
13300 PrintF("%33s %8.3f ms / %4.1f %% \n", "Create graph",
13301 create_graph_.InMillisecondsF(), create_graph_.PercentOf(total));
13302 PrintF("%33s %8.3f ms / %4.1f %% \n", "Optimize graph",
13303 optimize_graph_.InMillisecondsF(), optimize_graph_.PercentOf(total));
13304 PrintF("%33s %8.3f ms / %4.1f %% \n", "Generate and install code",
13305 generate_code_.InMillisecondsF(), generate_code_.PercentOf(total));
13307 "----------------------------------------"
13308 "----------------------------------------\n");
13309 PrintF("%33s %8.3f ms %9zu bytes\n", "Total",
13310 total.InMillisecondsF(), total_size_);
13311 PrintF("%33s (%.1f times slower than full code gen)\n", "",
13312 total.TimesOf(full_code_gen_));
13314 double source_size_in_kb = static_cast<double>(source_size_) / 1024;
13315 double normalized_time = source_size_in_kb > 0
13316 ? total.InMillisecondsF() / source_size_in_kb
13318 double normalized_size_in_kb =
13319 source_size_in_kb > 0
13320 ? static_cast<double>(total_size_) / 1024 / source_size_in_kb
13322 PrintF("%33s %8.3f ms %7.3f kB allocated\n",
13323 "Average per kB source", normalized_time, normalized_size_in_kb);
13327 void HStatistics::SaveTiming(const char* name, base::TimeDelta time,
13329 total_size_ += size;
13330 for (int i = 0; i < names_.length(); ++i) {
13331 if (strcmp(names_[i], name) == 0) {
13343 HPhase::~HPhase() {
13344 if (ShouldProduceTraceOutput()) {
13345 isolate()->GetHTracer()->TraceHydrogen(name(), graph_);
13349 graph_->Verify(false); // No full verify.
13353 } // namespace internal