2689e42d5c1d89e38bb3f698b6503be70e5bc965
[platform/upstream/v8.git] / src / hydrogen.cc
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.
4
5 #include "src/hydrogen.h"
6
7 #include <sstream>
8
9 #include "src/v8.h"
10
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"
38 // GetRootConstructor
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"
45
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
62 #else
63 #error Unsupported target architecture.
64 #endif
65
66 namespace v8 {
67 namespace internal {
68
69 HBasicBlock::HBasicBlock(HGraph* graph)
70     : block_id_(graph->GetNextBlockID()),
71       graph_(graph),
72       phis_(4, graph->zone()),
73       first_(NULL),
74       last_(NULL),
75       end_(NULL),
76       loop_information_(NULL),
77       predecessors_(2, graph->zone()),
78       dominator_(NULL),
79       dominated_blocks_(4, graph->zone()),
80       last_environment_(NULL),
81       argument_count_(-1),
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),
88       is_reachable_(true),
89       dominates_loop_successors_(false),
90       is_osr_entry_(false),
91       is_ordered_(false) { }
92
93
94 Isolate* HBasicBlock::isolate() const {
95   return graph_->isolate();
96 }
97
98
99 void HBasicBlock::MarkUnreachable() {
100   is_reachable_ = false;
101 }
102
103
104 void HBasicBlock::AttachLoopInformation() {
105   DCHECK(!IsLoopHeader());
106   loop_information_ = new(zone()) HLoopInformation(this, zone());
107 }
108
109
110 void HBasicBlock::DetachLoopInformation() {
111   DCHECK(IsLoopHeader());
112   loop_information_ = NULL;
113 }
114
115
116 void HBasicBlock::AddPhi(HPhi* phi) {
117   DCHECK(!IsStartBlock());
118   phis_.Add(phi, zone());
119   phi->SetBlock(this);
120 }
121
122
123 void HBasicBlock::RemovePhi(HPhi* phi) {
124   DCHECK(phi->block() == this);
125   DCHECK(phis_.Contains(phi));
126   phi->Kill();
127   phis_.RemoveElement(phi);
128   phi->SetBlock(NULL);
129 }
130
131
132 void HBasicBlock::AddInstruction(HInstruction* instr, SourcePosition position) {
133   DCHECK(!IsStartBlock() || !IsFinished());
134   DCHECK(!instr->IsLinked());
135   DCHECK(!IsFinished());
136
137   if (!position.IsUnknown()) {
138     instr->set_position(position);
139   }
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);
147     } else {
148       DCHECK(!FLAG_hydrogen_track_positions ||
149              !graph()->info()->IsOptimizing() || instr->IsAbnormalExit());
150     }
151     first_ = last_ = entry;
152   }
153   instr->InsertAfter(last_);
154 }
155
156
157 HPhi* HBasicBlock::AddNewPhi(int merged_index) {
158   if (graph()->IsInsideNoSideEffectsScope()) {
159     merged_index = HPhi::kInvalidMergedIndex;
160   }
161   HPhi* phi = new(zone()) HPhi(merged_index, zone());
162   AddPhi(phi);
163   return phi;
164 }
165
166
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));
174
175   int push_count = environment->push_count();
176   int pop_count = environment->pop_count();
177
178   HSimulate* instr =
179       new(zone()) HSimulate(ast_id, pop_count, zone(), removable);
180 #ifdef DEBUG
181   instr->set_closure(environment->closure());
182 #endif
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));
188   }
189   for (GrowableBitVector::Iterator it(environment->assigned_variables(),
190                                       zone());
191        !it.Done();
192        it.Advance()) {
193     int index = it.Current();
194     instr->AddAssignedValue(index, environment->Lookup(index));
195   }
196   environment->ClearHistory();
197   return instr;
198 }
199
200
201 void HBasicBlock::Finish(HControlInstruction* end, SourcePosition position) {
202   DCHECK(!IsFinished());
203   AddInstruction(end, position);
204   end_ = end;
205   for (HSuccessorIterator it(end); !it.Done(); it.Advance()) {
206     it.Current()->RegisterPredecessor(this);
207   }
208 }
209
210
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;
215
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),
221                    position);
222     UpdateEnvironment(last_environment()->DiscardInlined(drop_extra));
223   }
224
225   if (add_simulate) AddNewSimulate(BailoutId::None(), position);
226   HGoto* instr = new(zone()) HGoto(block);
227   Finish(instr, position);
228 }
229
230
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;
235
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),
241                  position);
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);
247 }
248
249
250 void HBasicBlock::SetInitialEnvironment(HEnvironment* env) {
251   DCHECK(!HasEnvironment());
252   DCHECK(first() == NULL);
253   UpdateEnvironment(env);
254 }
255
256
257 void HBasicBlock::UpdateEnvironment(HEnvironment* env) {
258   last_environment_ = env;
259   graph()->update_maximum_environment_size(env->first_expression_index());
260 }
261
262
263 void HBasicBlock::SetJoinId(BailoutId ast_id) {
264   int length = predecessors_.length();
265   DCHECK(length > 0);
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());
270     DCHECK(i != 0 ||
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);
276   }
277 }
278
279
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();
285   }
286   return false;
287 }
288
289
290 bool HBasicBlock::EqualToOrDominates(HBasicBlock* other) const {
291   if (this == other) return true;
292   return Dominates(other);
293 }
294
295
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();
301     result++;
302   }
303   return result;
304 }
305
306
307 void HBasicBlock::PostProcessLoopHeader(IterationStatement* stmt) {
308   DCHECK(IsLoopHeader());
309
310   SetJoinId(stmt->EntryId());
311   if (predecessors()->length() == 1) {
312     // This is a degenerated loop.
313     DetachLoopInformation();
314     return;
315   }
316
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));
321   }
322 }
323
324
325 void HBasicBlock::MarkSuccEdgeUnreachable(int succ) {
326   DCHECK(IsFinished());
327   HBasicBlock* succ_block = end()->SuccessorAt(succ);
328
329   DCHECK(succ_block->predecessors()->length() == 1);
330   succ_block->MarkUnreachable();
331 }
332
333
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));
345       }
346     } else {
347       last_environment()->AddIncomingEdge(this, pred->last_environment());
348     }
349   } else if (!HasEnvironment() && !IsFinished()) {
350     DCHECK(!IsLoopHeader());
351     SetInitialEnvironment(pred->last_environment()->Copy());
352   }
353
354   predecessors_.Add(pred, zone());
355 }
356
357
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.
362   int index = 0;
363   while (index < dominated_blocks_.length() &&
364          dominated_blocks_[index]->block_id() < block->block_id()) {
365     ++index;
366   }
367   dominated_blocks_.InsertAt(index, block, zone());
368 }
369
370
371 void HBasicBlock::AssignCommonDominator(HBasicBlock* other) {
372   if (dominator_ == NULL) {
373     dominator_ = other;
374     other->AddDominatedBlock(this);
375   } else if (other->dominator() != NULL) {
376     HBasicBlock* first = dominator_;
377     HBasicBlock* second = other;
378
379     while (first != second) {
380       if (first->block_id() > second->block_id()) {
381         first = first->dominator();
382       } else {
383         second = second->dominator();
384       }
385       DCHECK(first != NULL && second != NULL);
386     }
387
388     if (dominator_ != first) {
389       DCHECK(dominator_->dominated_blocks_.Contains(this));
390       dominator_->dominated_blocks_.RemoveElement(this);
391       dominator_ = first;
392       first->AddDominatedBlock(this);
393     }
394   }
395 }
396
397
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();
415          it.Advance()) {
416       HBasicBlock* predecessor = it.Current();
417       // Don't count back edges.
418       if (predecessor->block_id() < dominator_candidate->block_id()) {
419         outstanding_successors--;
420       }
421     }
422
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();
436     }
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
441       // to a loop header.
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++;
448       }
449     }
450   }
451 }
452
453
454 int HBasicBlock::PredecessorIndexOf(HBasicBlock* predecessor) const {
455   for (int i = 0; i < predecessors_.length(); ++i) {
456     if (predecessors_[i] == predecessor) return i;
457   }
458   UNREACHABLE();
459   return -1;
460 }
461
462
463 #ifdef DEBUG
464 void HBasicBlock::Verify() {
465   // Check that every block is finished.
466   DCHECK(IsFinished());
467   DCHECK(block_id() >= 0);
468
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);
473     }
474   }
475 }
476 #endif
477
478
479 void HLoopInformation::RegisterBackEdge(HBasicBlock* block) {
480   this->back_edges_.Add(block, block->zone());
481   AddBlock(block);
482 }
483
484
485 HBasicBlock* HLoopInformation::GetLastBackEdge() const {
486   int max_id = -1;
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();
492       result = cur;
493     }
494   }
495   return result;
496 }
497
498
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());
504   } else {
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));
509     }
510   }
511 }
512
513
514 #ifdef DEBUG
515
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 {
522  public:
523   ReachabilityAnalyzer(HBasicBlock* entry_block,
524                        int block_count,
525                        HBasicBlock* dont_visit)
526       : visited_count_(0),
527         stack_(16, entry_block->zone()),
528         reachable_(block_count, entry_block->zone()),
529         dont_visit_(dont_visit) {
530     PushBlock(entry_block);
531     Analyze();
532   }
533
534   int visited_count() const { return visited_count_; }
535   const BitVector* reachable() const { return &reachable_; }
536
537  private:
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());
543       visited_count_++;
544     }
545   }
546
547   void Analyze() {
548     while (!stack_.is_empty()) {
549       HControlInstruction* end = stack_.RemoveLast()->end();
550       for (HSuccessorIterator it(end); !it.Done(); it.Advance()) {
551         PushBlock(it.Current());
552       }
553     }
554   }
555
556   int visited_count_;
557   ZoneList<HBasicBlock*> stack_;
558   BitVector reachable_;
559   HBasicBlock* dont_visit_;
560 };
561
562
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);
569
570     block->Verify();
571
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);
579       current->Verify();
580       current = current->next();
581     }
582
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);
587
588     // Check that the predecessor array is correct.
589     if (first != NULL) {
590       DCHECK(first->predecessors()->Contains(block));
591       if (second != NULL) {
592         DCHECK(second->predecessors()->Contains(block));
593       }
594     }
595
596     // Check that phis have correct arguments.
597     for (int j = 0; j < block->phis()->length(); j++) {
598       HPhi* phi = block->phis()->at(j);
599       phi->Verify();
600     }
601
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) {
605       BailoutId id =
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);
612       }
613     }
614   }
615
616   // Check special property of first block to have no predecessors.
617   DCHECK(blocks_.at(0)->predecessors()->is_empty());
618
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());
623
624     // Check that entry block dominator is NULL.
625     DCHECK(entry_block_->dominator() == NULL);
626
627     // Check dominators.
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.
632         DCHECK(i == 0);
633       } else {
634         // Assert that block is unreachable if dominator must not be visited.
635         ReachabilityAnalyzer dominator_analyzer(entry_block_,
636                                                 blocks_.length(),
637                                                 block->dominator());
638         DCHECK(!dominator_analyzer.reachable()->Contains(block->block_id()));
639       }
640     }
641   }
642 }
643
644 #endif
645
646
647 HConstant* HGraph::GetConstant(SetOncePointer<HConstant>* pointer,
648                                int32_t value) {
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);
655     return constant;
656   }
657   return ReinsertConstantIfNecessary(pointer->get());
658 }
659
660
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());
666   }
667   return constant;
668 }
669
670
671 HConstant* HGraph::GetConstant0() {
672   return GetConstant(&constant_0_, 0);
673 }
674
675
676 HConstant* HGraph::GetConstant1() {
677   return GetConstant(&constant_1_, 1);
678 }
679
680
681 HConstant* HGraph::GetConstantMinus1() {
682   return GetConstant(&constant_minus1_, -1);
683 }
684
685
686 HConstant* HGraph::GetConstantBool(bool value) {
687   return value ? GetConstantTrue() : GetConstantFalse();
688 }
689
690
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()),      \
697         false,                                                                 \
698         Representation::Tagged(),                                              \
699         htype,                                                                 \
700         true,                                                                  \
701         boolean_value,                                                         \
702         false,                                                                 \
703         ODDBALL_TYPE);                                                         \
704     constant->InsertAfter(entry_block()->first());                             \
705     constant_##name##_.set(constant);                                          \
706   }                                                                            \
707   return ReinsertConstantIfNecessary(constant_##name##_.get());                \
708 }
709
710
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)
716
717
718 #undef DEFINE_GET_CONSTANT
719
720 #define DEFINE_IS_CONSTANT(Name, name)                                         \
721 bool HGraph::IsConstant##Name(HConstant* constant) {                           \
722   return constant_##name##_.is_set() && constant == constant_##name##_.get();  \
723 }
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)
732
733 #undef DEFINE_IS_CONSTANT
734
735
736 HConstant* HGraph::GetInvalidContext() {
737   return GetConstant(&constant_invalid_context_, 0xFFFFC0C7);
738 }
739
740
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;
750   return false;
751 }
752
753
754 HGraphBuilder::IfBuilder::IfBuilder() : builder_(NULL), needs_compare_(true) {}
755
756
757 HGraphBuilder::IfBuilder::IfBuilder(HGraphBuilder* builder)
758     : needs_compare_(true) {
759   Initialize(builder);
760 }
761
762
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_);
768 }
769
770
771 void HGraphBuilder::IfBuilder::InitializeDontCreateBlocks(
772     HGraphBuilder* builder) {
773   builder_ = builder;
774   finished_ = false;
775   did_then_ = false;
776   did_else_ = false;
777   did_else_if_ = false;
778   did_and_ = false;
779   did_or_ = false;
780   captured_ = 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;
786 }
787
788
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());
794 }
795
796
797 HControlInstruction* HGraphBuilder::IfBuilder::AddCompare(
798     HControlInstruction* compare) {
799   DCHECK(did_then_ == did_else_);
800   if (did_else_) {
801     // Handle if-then-elseif
802     did_else_if_ = true;
803     did_else_ = false;
804     did_then_ = false;
805     did_and_ = false;
806     did_or_ = false;
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());
812   }
813   if (split_edge_merge_block_ != NULL) {
814     HEnvironment* env = first_false_block_->last_environment();
815     HBasicBlock* split_edge = builder()->CreateBasicBlock(env->Copy());
816     if (did_or_) {
817       compare->SetSuccessorAt(0, split_edge);
818       compare->SetSuccessorAt(1, first_false_block_);
819     } else {
820       compare->SetSuccessorAt(0, first_true_block_);
821       compare->SetSuccessorAt(1, split_edge);
822     }
823     builder()->GotoNoSimulate(split_edge, split_edge_merge_block_);
824   } else {
825     compare->SetSuccessorAt(0, first_true_block_);
826     compare->SetSuccessorAt(1, first_false_block_);
827   }
828   builder()->FinishCurrentBlock(compare);
829   needs_compare_ = false;
830   return compare;
831 }
832
833
834 void HGraphBuilder::IfBuilder::Or() {
835   DCHECK(!needs_compare_);
836   DCHECK(!did_and_);
837   did_or_ = true;
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_;
843   }
844   builder()->set_current_block(first_false_block_);
845   first_false_block_ = builder()->CreateBasicBlock(env->Copy());
846 }
847
848
849 void HGraphBuilder::IfBuilder::And() {
850   DCHECK(!needs_compare_);
851   DCHECK(!did_or_);
852   did_and_ = true;
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_;
858   }
859   builder()->set_current_block(first_true_block_);
860   first_true_block_ = builder()->CreateBasicBlock(env->Copy());
861 }
862
863
864 void HGraphBuilder::IfBuilder::CaptureContinuation(
865     HIfContinuation* continuation) {
866   DCHECK(!did_else_if_);
867   DCHECK(!finished_);
868   DCHECK(!captured_);
869
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);
876   captured_ = true;
877   builder()->set_current_block(NULL);
878   End();
879 }
880
881
882 void HGraphBuilder::IfBuilder::JoinContinuation(HIfContinuation* continuation) {
883   DCHECK(!did_else_if_);
884   DCHECK(!finished_);
885   DCHECK(!captured_);
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());
893   }
894   if (false_block != NULL && !false_block->IsFinished()) {
895     DCHECK(continuation->IsFalseReachable());
896     builder()->GotoNoSimulate(false_block, continuation->false_branch());
897   }
898   captured_ = true;
899   End();
900 }
901
902
903 void HGraphBuilder::IfBuilder::Then() {
904   DCHECK(!captured_);
905   DCHECK(!finished_);
906   did_then_ = true;
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);
918   }
919   builder()->set_current_block(first_true_block_);
920   pending_merge_block_ = true;
921 }
922
923
924 void HGraphBuilder::IfBuilder::Else() {
925   DCHECK(did_then_);
926   DCHECK(!captured_);
927   DCHECK(!finished_);
928   AddMergeAtJoinBlock(false);
929   builder()->set_current_block(first_false_block_);
930   pending_merge_block_ = true;
931   did_else_ = true;
932 }
933
934
935 void HGraphBuilder::IfBuilder::Deopt(Deoptimizer::DeoptReason reason) {
936   DCHECK(did_then_);
937   builder()->Add<HDeoptimize>(reason, Deoptimizer::EAGER);
938   AddMergeAtJoinBlock(true);
939 }
940
941
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);
947 }
948
949
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;
957   if (block != NULL) {
958     DCHECK(block->end() == NULL);
959     if (deopt) {
960       normal_merge_at_join_block_count_++;
961     } else {
962       deopt_merge_at_join_block_count_++;
963     }
964   }
965   builder()->set_current_block(NULL);
966   pending_merge_block_ = false;
967 }
968
969
970 void HGraphBuilder::IfBuilder::Finish() {
971   DCHECK(!finished_);
972   if (!did_then_) {
973     Then();
974   }
975   AddMergeAtJoinBlock(false);
976   if (!did_else_) {
977     Else();
978     AddMergeAtJoinBlock(false);
979   }
980   finished_ = true;
981 }
982
983
984 void HGraphBuilder::IfBuilder::Finish(HBasicBlock** then_continuation,
985                                       HBasicBlock** else_continuation) {
986   Finish();
987
988   MergeAtJoinBlock* else_record = merge_at_join_blocks_;
989   if (else_continuation != NULL) {
990     *else_continuation = else_record->block_;
991   }
992   MergeAtJoinBlock* then_record = else_record->next_;
993   if (then_continuation != NULL) {
994     *then_continuation = then_record->block_;
995   }
996   DCHECK(then_record->next_ == NULL);
997 }
998
999
1000 void HGraphBuilder::IfBuilder::EndUnreachable() {
1001   if (captured_) return;
1002   Finish();
1003   builder()->set_current_block(nullptr);
1004 }
1005
1006
1007 void HGraphBuilder::IfBuilder::End() {
1008   if (captured_) return;
1009   Finish();
1010
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();
1016
1017   // Merge non-deopt blocks first to ensure environment has right size for
1018   // padding.
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_);
1027         return;
1028       }
1029       builder()->GotoNoSimulate(current->block_, merge_block);
1030     }
1031     current = current->next_;
1032   }
1033
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());
1041     }
1042     current = current->next_;
1043   }
1044   builder()->set_current_block(merge_block);
1045 }
1046
1047
1048 HGraphBuilder::LoopBuilder::LoopBuilder(HGraphBuilder* builder) {
1049   Initialize(builder, NULL, kWhileTrue, NULL);
1050 }
1051
1052
1053 HGraphBuilder::LoopBuilder::LoopBuilder(HGraphBuilder* builder, HValue* context,
1054                                         LoopBuilder::Direction direction) {
1055   Initialize(builder, context, direction, builder->graph()->GetConstant1());
1056 }
1057
1058
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;
1064 }
1065
1066
1067 void HGraphBuilder::LoopBuilder::Initialize(HGraphBuilder* builder,
1068                                             HValue* context,
1069                                             Direction direction,
1070                                             HValue* increment_amount) {
1071   builder_ = builder;
1072   context_ = context;
1073   direction_ = direction;
1074   increment_amount_ = increment_amount;
1075
1076   finished_ = false;
1077   header_block_ = builder->CreateLoopHeaderBlock();
1078   body_block_ = NULL;
1079   exit_block_ = NULL;
1080   exit_trampoline_block_ = NULL;
1081 }
1082
1083
1084 HValue* HGraphBuilder::LoopBuilder::BeginBody(
1085     HValue* initial,
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);
1092   env->Push(initial);
1093   builder_->GotoNoSimulate(header_block_);
1094
1095   HEnvironment* body_env = env->Copy();
1096   HEnvironment* exit_env = env->Copy();
1097   // Remove the phi from the expression stack
1098   body_env->Pop();
1099   exit_env->Pop();
1100   body_block_ = builder_->CreateBasicBlock(body_env);
1101   exit_block_ = builder_->CreateBasicBlock(exit_env);
1102
1103   builder_->set_current_block(header_block_);
1104   env->Pop();
1105   builder_->FinishCurrentBlock(builder_->New<HCompareNumericAndBranch>(
1106           phi_, terminating, token, body_block_, exit_block_));
1107
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);
1114     } else {
1115       increment_ = HSub::New(isolate, zone(), context_, phi_, one);
1116     }
1117     increment_->ClearFlag(HValue::kCanOverflow);
1118     builder_->AddInstruction(increment_);
1119     return increment_;
1120   } else {
1121     return phi_;
1122   }
1123 }
1124
1125
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);
1132 }
1133
1134
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);
1141     } else {
1142       HEnvironment* env = exit_block_->last_environment()->Copy();
1143       exit_trampoline_block_ = builder_->CreateBasicBlock(env);
1144       builder_->GotoNoSimulate(exit_block_, exit_trampoline_block_);
1145     }
1146   }
1147
1148   builder_->GotoNoSimulate(exit_trampoline_block_);
1149   builder_->set_current_block(NULL);
1150 }
1151
1152
1153 void HGraphBuilder::LoopBuilder::EndBody() {
1154   DCHECK(!finished_);
1155
1156   if (direction_ == kPostIncrement || direction_ == kPostDecrement) {
1157     Isolate* isolate = builder_->isolate();
1158     if (direction_ == kPostIncrement) {
1159       increment_ =
1160           HAdd::New(isolate, zone(), context_, phi_, increment_amount_);
1161     } else {
1162       increment_ =
1163           HSub::New(isolate, zone(), context_, phi_, increment_amount_);
1164     }
1165     increment_->ClearFlag(HValue::kCanOverflow);
1166     builder_->AddInstruction(increment_);
1167   }
1168
1169   if (direction_ != kWhileTrue) {
1170     // Push the new increment value on the expression stack to merge into
1171     // the phi.
1172     builder_->environment()->Push(increment_);
1173   }
1174   HBasicBlock* last_block = builder_->current_block();
1175   builder_->GotoNoSimulate(last_block, header_block_);
1176   header_block_->loop_information()->RegisterBackEdge(last_block);
1177
1178   if (exit_trampoline_block_ != NULL) {
1179     builder_->set_current_block(exit_trampoline_block_);
1180   } else {
1181     builder_->set_current_block(exit_block_);
1182   }
1183   finished_ = true;
1184 }
1185
1186
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();
1194   return graph_;
1195 }
1196
1197
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);
1206   }
1207   return instr;
1208 }
1209
1210
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);
1218   }
1219 }
1220
1221
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);
1228   }
1229 }
1230
1231
1232 void HGraphBuilder::AddIncrementCounter(StatsCounter* counter) {
1233   if (FLAG_native_code_counters && counter->Enabled()) {
1234     HValue* reference = Add<HConstant>(ExternalReference(counter));
1235     HValue* old_value =
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);
1241   }
1242 }
1243
1244
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);
1250 }
1251
1252
1253 HBasicBlock* HGraphBuilder::CreateBasicBlock(HEnvironment* env) {
1254   HBasicBlock* b = graph()->CreateBasicBlock();
1255   b->SetInitialEnvironment(env);
1256   return b;
1257 }
1258
1259
1260 HBasicBlock* HGraphBuilder::CreateLoopHeaderBlock() {
1261   HBasicBlock* header = graph()->CreateBasicBlock();
1262   HEnvironment* entry_env = environment()->CopyAsLoopHeader(header);
1263   header->SetInitialEnvironment(entry_env);
1264   header->AttachLoopInformation();
1265   return header;
1266 }
1267
1268
1269 HValue* HGraphBuilder::BuildGetElementsKind(HValue* object) {
1270   HValue* map = Add<HLoadNamedField>(object, nullptr, HObjectAccess::ForMap());
1271
1272   HValue* bit_field2 =
1273       Add<HLoadNamedField>(map, nullptr, HObjectAccess::ForMapBitField2());
1274   return BuildDecodeField<Map::ElementsKindBits>(bit_field2);
1275 }
1276
1277
1278 HValue* HGraphBuilder::BuildCheckHeapObject(HValue* obj) {
1279   if (obj->type().IsHeapObject()) return obj;
1280   return Add<HCheckHeapObject>(obj);
1281 }
1282
1283
1284 void HGraphBuilder::FinishExitWithHardDeoptimization(
1285     Deoptimizer::DeoptReason reason) {
1286   Add<HDeoptimize>(reason, Deoptimizer::EAGER);
1287   FinishExitCurrentBlock(New<HAbnormalExit>());
1288 }
1289
1290
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);
1297   }
1298   return string;
1299 }
1300
1301
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;
1310   }
1311   return Add<HWrapReceiver>(object, function);
1312 }
1313
1314
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);
1321
1322   HValue* new_capacity = BuildNewElementsCapacity(key);
1323   HValue* new_elements = BuildGrowElementsCapacity(object, elements, kind, kind,
1324                                                    length, new_capacity);
1325   return new_elements;
1326 }
1327
1328
1329 HValue* HGraphBuilder::BuildCheckForCapacityGrow(
1330     HValue* object,
1331     HValue* elements,
1332     ElementsKind kind,
1333     HValue* length,
1334     HValue* key,
1335     bool is_js_array,
1336     PropertyAccessType access_type) {
1337   IfBuilder length_checker(this);
1338
1339   Token::Value token = IsHoleyElementsKind(kind) ? Token::GTE : Token::EQ;
1340   length_checker.If<HCompareNumericAndBranch>(key, length, token);
1341
1342   length_checker.Then();
1343
1344   HValue* current_capacity = AddLoadFixedArrayLength(elements);
1345
1346   if (top_info()->IsStub()) {
1347     IfBuilder capacity_checker(this);
1348     capacity_checker.If<HCompareNumericAndBranch>(key, current_capacity,
1349                                                   Token::GTE);
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();
1357   } else {
1358     HValue* result = Add<HMaybeGrowElements>(
1359         object, elements, key, current_capacity, is_js_array, kind);
1360     environment()->Push(result);
1361   }
1362
1363   if (is_js_array) {
1364     HValue* new_length = AddUncasted<HAdd>(key, graph_->GetConstant1());
1365     new_length->ClearFlag(HValue::kCanOverflow);
1366
1367     Add<HStoreNamedField>(object, HObjectAccess::ForArrayLength(kind),
1368                           new_length);
1369   }
1370
1371   if (access_type == STORE && kind == FAST_SMI_ELEMENTS) {
1372     HValue* checked_elements = environment()->Top();
1373
1374     // Write zero to ensure that the new element is initialized with some smi.
1375     Add<HStoreKeyed>(checked_elements, key, graph()->GetConstant0(), kind);
1376   }
1377
1378   length_checker.Else();
1379   Add<HBoundsCheck>(key, length);
1380
1381   environment()->Push(elements);
1382   length_checker.End();
1383
1384   return environment()->Pop();
1385 }
1386
1387
1388 HValue* HGraphBuilder::BuildCopyElementsOnWrite(HValue* object,
1389                                                 HValue* elements,
1390                                                 ElementsKind kind,
1391                                                 HValue* length) {
1392   Factory* factory = isolate()->factory();
1393
1394   IfBuilder cow_checker(this);
1395
1396   cow_checker.If<HCompareMap>(elements, factory->fixed_cow_array_map());
1397   cow_checker.Then();
1398
1399   HValue* capacity = AddLoadFixedArrayLength(elements);
1400
1401   HValue* new_elements = BuildGrowElementsCapacity(object, elements, kind,
1402                                                    kind, length, capacity);
1403
1404   environment()->Push(new_elements);
1405
1406   cow_checker.Else();
1407
1408   environment()->Push(elements);
1409
1410   cow_checker.End();
1411
1412   return environment()->Pop();
1413 }
1414
1415
1416 void HGraphBuilder::BuildTransitionElementsKind(HValue* object,
1417                                                 HValue* map,
1418                                                 ElementsKind from_kind,
1419                                                 ElementsKind to_kind,
1420                                                 bool is_jsarray) {
1421   DCHECK(!IsFastHoleyElementsKind(from_kind) ||
1422          IsFastHoleyElementsKind(to_kind));
1423
1424   if (AllocationSite::GetMode(from_kind, to_kind) == TRACK_ALLOCATION_SITE) {
1425     Add<HTrapAllocationMemento>(object);
1426   }
1427
1428   if (!IsSimpleMapChangeTransition(from_kind, to_kind)) {
1429     HInstruction* elements = AddLoadElements(object);
1430
1431     HInstruction* empty_fixed_array = Add<HConstant>(
1432         isolate()->factory()->empty_fixed_array());
1433
1434     IfBuilder if_builder(this);
1435
1436     if_builder.IfNot<HCompareObjectEqAndBranch>(elements, empty_fixed_array);
1437
1438     if_builder.Then();
1439
1440     HInstruction* elements_length = AddLoadFixedArrayLength(elements);
1441
1442     HInstruction* array_length =
1443         is_jsarray
1444             ? Add<HLoadNamedField>(object, nullptr,
1445                                    HObjectAccess::ForArrayLength(from_kind))
1446             : elements_length;
1447
1448     BuildGrowElementsCapacity(object, elements, from_kind, to_kind,
1449                               array_length, elements_length);
1450
1451     if_builder.End();
1452   }
1453
1454   Add<HStoreNamedField>(object, HObjectAccess::ForMap(), map);
1455 }
1456
1457
1458 void HGraphBuilder::BuildJSObjectCheck(HValue* receiver,
1459                                        int bit_field_mask) {
1460   // Check that the object isn't a smi.
1461   Add<HCheckHeapObject>(receiver);
1462
1463   // Get the map of the receiver.
1464   HValue* map =
1465       Add<HLoadNamedField>(receiver, nullptr, HObjectAccess::ForMap());
1466
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);
1472
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,
1476                                              mask);
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));
1481 }
1482
1483
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.
1491
1492   IfBuilder key_smi_if(this);
1493   key_smi_if.If<HIsSmiAndBranch>(key);
1494   key_smi_if.Then();
1495   {
1496     Push(key);  // Nothing to do, just continue to true of continuation.
1497   }
1498   key_smi_if.Else();
1499   {
1500     HValue* map = Add<HLoadNamedField>(key, nullptr, HObjectAccess::ForMap());
1501     HValue* instance_type =
1502         Add<HLoadNamedField>(map, nullptr, HObjectAccess::ForMapInstanceType());
1503
1504     // Non-unique string, check for a string with a hash code that is actually
1505     // an index.
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>(
1509         instance_type,
1510         Add<HConstant>(LAST_UNIQUE_NAME_TYPE),
1511         Token::GT);
1512
1513     not_string_or_name_if.Then();
1514     {
1515       // Non-smi, non-Name, non-String: Try to convert to smi in case of
1516       // HeapNumber.
1517       // TODO(danno): This could call some variant of ToString
1518       Push(AddUncasted<HForceRepresentation>(key, Representation::Smi()));
1519     }
1520     not_string_or_name_if.Else();
1521     {
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>(
1526           instance_type,
1527           Add<HConstant>(SYMBOL_TYPE),
1528           Token::NE);
1529
1530       not_symbol_if.Then();
1531       {
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));
1538
1539         HValue* not_index_test = AddUncasted<HBitwise>(
1540             Token::BIT_AND, hash, not_index_mask);
1541
1542         IfBuilder string_index_if(this);
1543         string_index_if.If<HCompareNumericAndBranch>(not_index_test,
1544                                                      graph()->GetConstant0(),
1545                                                      Token::EQ);
1546         string_index_if.Then();
1547         {
1548           // String with index in hash: extract string and merge to index path.
1549           Push(BuildDecodeField<String::ArrayIndexValueBits>(hash));
1550         }
1551         string_index_if.Else();
1552         {
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>(
1556               Token::BIT_AND,
1557               instance_type,
1558               Add<HConstant>(static_cast<int>(kIsNotInternalizedMask)));
1559
1560           IfBuilder internalized(this);
1561           internalized.If<HCompareNumericAndBranch>(not_internalized_bit,
1562                                                     graph()->GetConstant0(),
1563                                                     Token::EQ);
1564           internalized.Then();
1565           Push(key);
1566
1567           internalized.Else();
1568           Add<HPushArguments>(key);
1569           HValue* intern_key = Add<HCallRuntime>(
1570               isolate()->factory()->empty_string(),
1571               Runtime::FunctionForId(Runtime::kInternalizeString), 1);
1572           Push(intern_key);
1573
1574           internalized.End();
1575           // Key guaranteed to be a unique string
1576         }
1577         string_index_if.JoinContinuation(join_continuation);
1578       }
1579       not_symbol_if.Else();
1580       {
1581         Push(key);  // Key is symbol
1582       }
1583       not_symbol_if.JoinContinuation(join_continuation);
1584     }
1585     not_string_or_name_if.JoinContinuation(join_continuation);
1586   }
1587   key_smi_if.JoinContinuation(join_continuation);
1588 }
1589
1590
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.
1594   HValue* map =
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);
1601
1602   IfBuilder if_global_object(this);
1603   if_global_object.If<HCompareNumericAndBranch>(instance_type,
1604                                                 max_global_type,
1605                                                 Token::LTE);
1606   if_global_object.And();
1607   if_global_object.If<HCompareNumericAndBranch>(instance_type,
1608                                                 min_global_type,
1609                                                 Token::GTE);
1610   if_global_object.ThenDeopt(Deoptimizer::kReceiverWasAGlobalObject);
1611   if_global_object.End();
1612 }
1613
1614
1615 void HGraphBuilder::BuildTestForDictionaryProperties(
1616     HValue* object,
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);
1626 }
1627
1628
1629 HValue* HGraphBuilder::BuildKeyedLookupCacheHash(HValue* object,
1630                                                  HValue* key) {
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,
1642                                              shifted_hash);
1643   int mask = (KeyedLookupCache::kCapacityMask & KeyedLookupCache::kHashMask);
1644   return AddUncasted<HBitwise>(Token::BIT_AND, xor_result,
1645                                Add<HConstant>(mask));
1646 }
1647
1648
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);
1653
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);
1659
1660   // hash = hash ^ (hash >> 12);
1661   shifted_hash = AddUncasted<HShr>(hash, Add<HConstant>(12));
1662   hash = AddUncasted<HBitwise>(Token::BIT_XOR, hash, shifted_hash);
1663
1664   // hash = hash + (hash << 2);
1665   shifted_hash = AddUncasted<HShl>(hash, Add<HConstant>(2));
1666   hash = AddUncasted<HAdd>(hash, shifted_hash);
1667
1668   // hash = hash ^ (hash >> 4);
1669   shifted_hash = AddUncasted<HShr>(hash, Add<HConstant>(4));
1670   hash = AddUncasted<HBitwise>(Token::BIT_XOR, hash, shifted_hash);
1671
1672   // hash = hash * 2057;
1673   hash = AddUncasted<HMul>(hash, Add<HConstant>(2057));
1674   hash->ClearFlag(HValue::kCanOverflow);
1675
1676   // hash = hash ^ (hash >> 16);
1677   shifted_hash = AddUncasted<HShr>(hash, Add<HConstant>(16));
1678   return AddUncasted<HBitwise>(Token::BIT_XOR, hash, shifted_hash);
1679 }
1680
1681
1682 HValue* HGraphBuilder::BuildUncheckedDictionaryElementLoad(
1683     HValue* receiver, HValue* elements, HValue* key, HValue* hash,
1684     LanguageMode language_mode) {
1685   HValue* capacity =
1686       Add<HLoadKeyed>(elements, Add<HConstant>(NameDictionary::kCapacityIndex),
1687                       nullptr, FAST_ELEMENTS);
1688
1689   HValue* mask = AddUncasted<HSub>(capacity, graph()->GetConstant1());
1690   mask->ChangeRepresentation(Representation::Integer32());
1691   mask->ClearFlag(HValue::kCanOverflow);
1692
1693   HValue* entry = hash;
1694   HValue* count = graph()->GetConstant1();
1695   Push(entry);
1696   Push(count);
1697
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.
1705
1706   count = Pop();
1707   entry = Pop();
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;
1713   HValue* key_index =
1714       AddUncasted<HAdd>(base_index, Add<HConstant>(start_offset));
1715   key_index->ClearFlag(HValue::kCanOverflow);
1716
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();
1723   {
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),
1732         2));
1733   }
1734   if_undefined.Else();
1735   {
1736     IfBuilder if_match(this);
1737     if_match.If<HCompareObjectEqAndBranch>(candidate_key, key);
1738     if_match.Then();
1739     if_match.Else();
1740
1741     // Update non-internalized string in the dictionary with internalized key?
1742     IfBuilder if_update_with_internalized(this);
1743     HValue* smi_check =
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,
1758                                                                key, Token::EQ);
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();
1764
1765     if_update_with_internalized.JoinContinuation(&found_key_match_continuation);
1766     if_match.JoinContinuation(&found_key_match_continuation);
1767
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);
1775     HValue* details =
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),
1795         2));
1796     details_compare.End();
1797
1798     found_key_match.Else();
1799     found_key_match.JoinContinuation(&return_or_loop_continuation);
1800   }
1801   if_undefined.JoinContinuation(&return_or_loop_continuation);
1802
1803   IfBuilder return_or_loop(this, &return_or_loop_continuation);
1804   return_or_loop.Then();
1805   probe_loop.Break();
1806
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);
1812   Push(entry);
1813   Push(count);
1814
1815   probe_loop.EndBody();
1816
1817   return_or_loop.End();
1818
1819   return Pop();
1820 }
1821
1822
1823 HValue* HGraphBuilder::BuildRegExpConstructResult(HValue* length,
1824                                                   HValue* index,
1825                                                   HValue* input) {
1826   NoObservableSideEffectsScope scope(this);
1827   HConstant* max_length = Add<HConstant>(JSObject::kInitialMaxFastElementArray);
1828   Add<HBoundsCheck>(length, max_length);
1829
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);
1834
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);
1839
1840   // Initialize the JSRegExpResult header.
1841   HValue* global_object = Add<HLoadNamedField>(
1842       context(), nullptr,
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),
1855       empty_fixed_array);
1856   Add<HStoreNamedField>(
1857       result, HObjectAccess::ForJSArrayOffset(JSArray::kElementsOffset),
1858       empty_fixed_array);
1859   Add<HStoreNamedField>(
1860       result, HObjectAccess::ForJSArrayOffset(JSArray::kLengthOffset), length);
1861
1862   // Initialize the additional fields.
1863   Add<HStoreNamedField>(
1864       result, HObjectAccess::ForJSArrayOffset(JSRegExpResult::kIndexOffset),
1865       index);
1866   Add<HStoreNamedField>(
1867       result, HObjectAccess::ForJSArrayOffset(JSRegExpResult::kInputOffset),
1868       input);
1869
1870   // Allocate and initialize the elements header.
1871   HAllocate* elements = BuildAllocateElements(elements_kind, size);
1872   BuildInitializeElementsHeader(elements, elements_kind, length);
1873
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);
1878   }
1879
1880   Add<HStoreNamedField>(
1881       result, HObjectAccess::ForJSArrayOffset(JSArray::kElementsOffset),
1882       elements);
1883
1884   // Initialize the elements contents with undefined.
1885   BuildFillElementsWithValue(
1886       elements, elements_kind, graph()->GetConstant0(), length,
1887       graph()->GetConstantUndefined());
1888
1889   return result;
1890 }
1891
1892
1893 HValue* HGraphBuilder::BuildNumberToString(HValue* object, Type* type) {
1894   NoObservableSideEffectsScope scope(this);
1895
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);
1901   }
1902
1903   // Create a joinable continuation.
1904   HIfContinuation found(graph()->CreateBasicBlock(),
1905                         graph()->CreateBasicBlock());
1906
1907   // Load the number string cache.
1908   HValue* number_string_cache =
1909       Add<HLoadRoot>(Heap::kNumberStringCacheRootIndex);
1910
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());
1917
1918   // Check whether object is a smi.
1919   IfBuilder if_objectissmi(this);
1920   if_objectissmi.If<HIsSmiAndBranch>(object);
1921   if_objectissmi.Then();
1922   {
1923     // Compute hash for smi similar to smi_get_hash().
1924     HValue* hash = AddUncasted<HBitwise>(Token::BIT_AND, object, mask);
1925
1926     // Load the key.
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);
1930
1931     // Check if object == key.
1932     IfBuilder if_objectiskey(this);
1933     if_objectiskey.If<HCompareObjectEqAndBranch>(object, key);
1934     if_objectiskey.Then();
1935     {
1936       // Make the key_index available.
1937       Push(key_index);
1938     }
1939     if_objectiskey.JoinContinuation(&found);
1940   }
1941   if_objectissmi.Else();
1942   {
1943     if (type->Is(Type::SignedSmall())) {
1944       if_objectissmi.Deopt(Deoptimizer::kExpectedSmi);
1945     } else {
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();
1951       {
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);
1961
1962         // Load the key.
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);
1966
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();
1971         {
1972           IfBuilder if_keyisheapnumber(this);
1973           if_keyisheapnumber.If<HCompareMap>(
1974               key, isolate()->factory()->heap_number_map());
1975           if_keyisheapnumber.Then();
1976           {
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()),
1984                 Token::EQ);
1985             if_keyeqobject.Then();
1986             {
1987               // Make the key_index available.
1988               Push(key_index);
1989             }
1990             if_keyeqobject.JoinContinuation(&found);
1991           }
1992           if_keyisheapnumber.JoinContinuation(&found);
1993         }
1994         if_keyisnotsmi.JoinContinuation(&found);
1995       }
1996       if_objectisnumber.Else();
1997       {
1998         if (type->Is(Type::Number())) {
1999           if_objectisnumber.Deopt(Deoptimizer::kExpectedHeapNumber);
2000         }
2001       }
2002       if_objectisnumber.JoinContinuation(&found);
2003     }
2004   }
2005   if_objectissmi.JoinContinuation(&found);
2006
2007   // Check for cache hit.
2008   IfBuilder if_found(this, &found);
2009   if_found.Then();
2010   {
2011     // Count number to string operation in native code.
2012     AddIncrementCounter(isolate()->counters()->number_to_string_native());
2013
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));
2019   }
2020   if_found.Else();
2021   {
2022     // Cache miss, fallback to runtime.
2023     Add<HPushArguments>(object);
2024     Push(Add<HCallRuntime>(
2025             isolate()->factory()->empty_string(),
2026             Runtime::FunctionForId(Runtime::kNumberToStringSkipCache),
2027             1));
2028   }
2029   if_found.End();
2030
2031   return Pop();
2032 }
2033
2034
2035 HAllocate* HGraphBuilder::BuildAllocate(
2036     HValue* object_size,
2037     HType type,
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);
2045   }
2046
2047   // Perform the actual allocation.
2048   HAllocate* object = Add<HAllocate>(
2049       size, type, allocation_mode.GetPretenureMode(),
2050       instance_type, allocation_mode.feedback_site());
2051
2052   // Setup the allocation memento.
2053   if (allocation_mode.CreateAllocationMementos()) {
2054     BuildCreateAllocationMemento(
2055         object, object_size, allocation_mode.current_site());
2056   }
2057
2058   return object;
2059 }
2060
2061
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);
2069   return length;
2070 }
2071
2072
2073 HValue* HGraphBuilder::BuildCreateConsString(
2074     HValue* length,
2075     HValue* left,
2076     HValue* right,
2077     HAllocationMode allocation_mode) {
2078   // Determine the string instance types.
2079   HInstruction* left_instance_type = AddLoadStringInstanceType(left);
2080   HInstruction* right_instance_type = AddLoadStringInstanceType(right);
2081
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,
2090                                     allocation_mode);
2091
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);
2097
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
2104   //    both strings, or
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);
2116   if_onebyte.Or();
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);
2127   if_onebyte.Then();
2128   {
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()));
2133   }
2134   if_onebyte.Else();
2135   {
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()));
2140   }
2141   if_onebyte.End();
2142
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);
2149
2150   // Count the native string addition.
2151   AddIncrementCounter(isolate()->counters()->string_add_native());
2152
2153   return result;
2154 }
2155
2156
2157 void HGraphBuilder::BuildCopySeqStringChars(HValue* src,
2158                                             HValue* src_offset,
2159                                             String::Encoding src_encoding,
2160                                             HValue* dst,
2161                                             HValue* dst_offset,
2162                                             String::Encoding dst_encoding,
2163                                             HValue* length) {
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);
2168   {
2169     HValue* src_index = AddUncasted<HAdd>(src_offset, index);
2170     HValue* value =
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);
2174   }
2175   loop.EndBody();
2176 }
2177
2178
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)));
2189 }
2190
2191
2192 HValue* HGraphBuilder::BuildUncheckedStringAdd(
2193     HValue* left,
2194     HValue* right,
2195     HAllocationMode allocation_mode) {
2196   // Determine the string lengths.
2197   HValue* left_length = AddLoadStringLength(left);
2198   HValue* right_length = AddLoadStringLength(right);
2199
2200   // Compute the combined string length.
2201   HValue* length = BuildAddStringLengths(left_length, right_length);
2202
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);
2210     }
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);
2217     }
2218   }
2219
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();
2225   {
2226     // Create a cons string.
2227     Push(BuildCreateConsString(length, left, right, allocation_mode));
2228   }
2229   if_createcons.Else();
2230   {
2231     // Determine the string instance types.
2232     HValue* left_instance_type = AddLoadStringInstanceType(left);
2233     HValue* right_instance_type = AddLoadStringInstanceType(right);
2234
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);
2240
2241     // Check if both strings have the same encoding and both are
2242     // sequential.
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();
2257     {
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());
2262
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);
2271       if_onebyte.Then();
2272       {
2273         // Allocate sequential one-byte string object.
2274         Push(length);
2275         Push(one_byte_string_map);
2276       }
2277       if_onebyte.Else();
2278       {
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);
2283         Push(size);
2284         Push(string_map);
2285       }
2286       if_onebyte.End();
2287       HValue* map = Pop();
2288
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);
2293
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);
2299
2300       // Initialize the string fields.
2301       Add<HStoreNamedField>(result, HObjectAccess::ForStringHashField(),
2302                             Add<HConstant>(String::kEmptyHashField));
2303       Add<HStoreNamedField>(result, HObjectAccess::ForStringLength(), length);
2304
2305       // Copy characters to the result string.
2306       IfBuilder if_twobyte(this);
2307       if_twobyte.If<HCompareObjectEqAndBranch>(map, string_map);
2308       if_twobyte.Then();
2309       {
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,
2314             left_length);
2315
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,
2320             right_length);
2321       }
2322       if_twobyte.Else();
2323       {
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,
2328             left_length);
2329
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,
2334             right_length);
2335       }
2336       if_twobyte.End();
2337
2338       // Count the native string addition.
2339       AddIncrementCounter(isolate()->counters()->string_add_native());
2340
2341       // Return the sequential string.
2342       Push(result);
2343     }
2344     if_sameencodingandsequential.Else();
2345     {
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));
2350     }
2351     if_sameencodingandsequential.End();
2352   }
2353   if_createcons.End();
2354
2355   return Pop();
2356 }
2357
2358
2359 HValue* HGraphBuilder::BuildStringAdd(
2360     HValue* left,
2361     HValue* right,
2362     HAllocationMode allocation_mode) {
2363   NoObservableSideEffectsScope no_effects(this);
2364
2365   // Determine string lengths.
2366   HValue* left_length = AddLoadStringLength(left);
2367   HValue* right_length = AddLoadStringLength(right);
2368
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();
2374   {
2375     // Count the native string addition.
2376     AddIncrementCounter(isolate()->counters()->string_add_native());
2377
2378     // Just return the right string.
2379     Push(right);
2380   }
2381   if_leftempty.Else();
2382   {
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();
2388     {
2389       // Count the native string addition.
2390       AddIncrementCounter(isolate()->counters()->string_add_native());
2391
2392       // Just return the left string.
2393       Push(left);
2394     }
2395     if_rightempty.Else();
2396     {
2397       // Add the two non-empty strings.
2398       Push(BuildUncheckedStringAdd(left, right, allocation_mode));
2399     }
2400     if_rightempty.End();
2401   }
2402   if_leftempty.End();
2403
2404   return Pop();
2405 }
2406
2407
2408 HInstruction* HGraphBuilder::BuildUncheckedMonomorphicElementAccess(
2409     HValue* checked_object,
2410     HValue* key,
2411     HValue* val,
2412     bool is_js_array,
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((!IsExternalArrayElementsKind(elements_kind) &&
2420               !IsFixedTypedArrayElementsKind(elements_kind)) ||
2421          !is_js_array);
2422   // No GVNFlag is necessary for ElementsKind if there is an explicit dependency
2423   // on a HElementsTransition instruction. The flag can also be removed if the
2424   // map to check has FAST_HOLEY_ELEMENTS, since there can be no further
2425   // ElementsKind transitions. Finally, the dependency can be removed for stores
2426   // for FAST_ELEMENTS, since a transition to HOLEY elements won't change the
2427   // generated store code.
2428   if ((elements_kind == FAST_HOLEY_ELEMENTS) ||
2429       (elements_kind == FAST_ELEMENTS && access_type == STORE)) {
2430     checked_object->ClearDependsOnFlag(kElementsKind);
2431   }
2432
2433   bool fast_smi_only_elements = IsFastSmiElementsKind(elements_kind);
2434   bool fast_elements = IsFastObjectElementsKind(elements_kind);
2435   HValue* elements = AddLoadElements(checked_object);
2436   if (access_type == STORE && (fast_elements || fast_smi_only_elements) &&
2437       store_mode != STORE_NO_TRANSITION_HANDLE_COW) {
2438     HCheckMaps* check_cow_map = Add<HCheckMaps>(
2439         elements, isolate()->factory()->fixed_array_map());
2440     check_cow_map->ClearDependsOnFlag(kElementsKind);
2441   }
2442   HInstruction* length = NULL;
2443   if (is_js_array) {
2444     length = Add<HLoadNamedField>(
2445         checked_object->ActualValue(), checked_object,
2446         HObjectAccess::ForArrayLength(elements_kind));
2447   } else {
2448     length = AddLoadFixedArrayLength(elements);
2449   }
2450   length->set_type(HType::Smi());
2451   HValue* checked_key = NULL;
2452   if (IsExternalArrayElementsKind(elements_kind) ||
2453       IsFixedTypedArrayElementsKind(elements_kind)) {
2454     checked_object = Add<HCheckArrayBufferNotNeutered>(checked_object);
2455
2456     HValue* backing_store;
2457     if (IsExternalArrayElementsKind(elements_kind)) {
2458       backing_store = Add<HLoadNamedField>(
2459           elements, nullptr, HObjectAccess::ForExternalArrayExternalPointer());
2460     } else {
2461       HValue* external_pointer = Add<HLoadNamedField>(
2462           elements, nullptr,
2463           HObjectAccess::ForFixedTypedArrayBaseExternalPointer());
2464       HValue* base_pointer = Add<HLoadNamedField>(
2465           elements, nullptr,
2466           HObjectAccess::ForFixedTypedArrayBaseBasePointer());
2467       backing_store = AddUncasted<HAdd>(external_pointer, base_pointer,
2468                                         Strength::WEAK, AddOfExternalAndTagged);
2469     }
2470     if (store_mode == STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
2471       NoObservableSideEffectsScope no_effects(this);
2472       IfBuilder length_checker(this);
2473       length_checker.If<HCompareNumericAndBranch>(key, length, Token::LT);
2474       length_checker.Then();
2475       IfBuilder negative_checker(this);
2476       HValue* bounds_check = negative_checker.If<HCompareNumericAndBranch>(
2477           key, graph()->GetConstant0(), Token::GTE);
2478       negative_checker.Then();
2479       HInstruction* result = AddElementAccess(
2480           backing_store, key, val, bounds_check, elements_kind, access_type);
2481       negative_checker.ElseDeopt(Deoptimizer::kNegativeKeyEncountered);
2482       negative_checker.End();
2483       length_checker.End();
2484       return result;
2485     } else {
2486       DCHECK(store_mode == STANDARD_STORE);
2487       checked_key = Add<HBoundsCheck>(key, length);
2488       return AddElementAccess(
2489           backing_store, checked_key, val,
2490           checked_object, elements_kind, access_type);
2491     }
2492   }
2493   DCHECK(fast_smi_only_elements ||
2494          fast_elements ||
2495          IsFastDoubleElementsKind(elements_kind));
2496
2497   // In case val is stored into a fast smi array, assure that the value is a smi
2498   // before manipulating the backing store. Otherwise the actual store may
2499   // deopt, leaving the backing store in an invalid state.
2500   if (access_type == STORE && IsFastSmiElementsKind(elements_kind) &&
2501       !val->type().IsSmi()) {
2502     val = AddUncasted<HForceRepresentation>(val, Representation::Smi());
2503   }
2504
2505   if (IsGrowStoreMode(store_mode)) {
2506     NoObservableSideEffectsScope no_effects(this);
2507     Representation representation = HStoreKeyed::RequiredValueRepresentation(
2508         elements_kind, STORE_TO_INITIALIZED_ENTRY);
2509     val = AddUncasted<HForceRepresentation>(val, representation);
2510     elements = BuildCheckForCapacityGrow(checked_object, elements,
2511                                          elements_kind, length, key,
2512                                          is_js_array, access_type);
2513     checked_key = key;
2514   } else {
2515     checked_key = Add<HBoundsCheck>(key, length);
2516
2517     if (access_type == STORE && (fast_elements || fast_smi_only_elements)) {
2518       if (store_mode == STORE_NO_TRANSITION_HANDLE_COW) {
2519         NoObservableSideEffectsScope no_effects(this);
2520         elements = BuildCopyElementsOnWrite(checked_object, elements,
2521                                             elements_kind, length);
2522       } else {
2523         HCheckMaps* check_cow_map = Add<HCheckMaps>(
2524             elements, isolate()->factory()->fixed_array_map());
2525         check_cow_map->ClearDependsOnFlag(kElementsKind);
2526       }
2527     }
2528   }
2529   return AddElementAccess(elements, checked_key, val, checked_object,
2530                           elements_kind, access_type, load_mode);
2531 }
2532
2533
2534 HValue* HGraphBuilder::BuildAllocateArrayFromLength(
2535     JSArrayBuilder* array_builder,
2536     HValue* length_argument) {
2537   if (length_argument->IsConstant() &&
2538       HConstant::cast(length_argument)->HasSmiValue()) {
2539     int array_length = HConstant::cast(length_argument)->Integer32Value();
2540     if (array_length == 0) {
2541       return array_builder->AllocateEmptyArray();
2542     } else {
2543       return array_builder->AllocateArray(length_argument,
2544                                           array_length,
2545                                           length_argument);
2546     }
2547   }
2548
2549   HValue* constant_zero = graph()->GetConstant0();
2550   HConstant* max_alloc_length =
2551       Add<HConstant>(JSObject::kInitialMaxFastElementArray);
2552   HInstruction* checked_length = Add<HBoundsCheck>(length_argument,
2553                                                    max_alloc_length);
2554   IfBuilder if_builder(this);
2555   if_builder.If<HCompareNumericAndBranch>(checked_length, constant_zero,
2556                                           Token::EQ);
2557   if_builder.Then();
2558   const int initial_capacity = JSArray::kPreallocatedArrayElements;
2559   HConstant* initial_capacity_node = Add<HConstant>(initial_capacity);
2560   Push(initial_capacity_node);  // capacity
2561   Push(constant_zero);          // length
2562   if_builder.Else();
2563   if (!(top_info()->IsStub()) &&
2564       IsFastPackedElementsKind(array_builder->kind())) {
2565     // We'll come back later with better (holey) feedback.
2566     if_builder.Deopt(
2567         Deoptimizer::kHoleyArrayDespitePackedElements_kindFeedback);
2568   } else {
2569     Push(checked_length);         // capacity
2570     Push(checked_length);         // length
2571   }
2572   if_builder.End();
2573
2574   // Figure out total size
2575   HValue* length = Pop();
2576   HValue* capacity = Pop();
2577   return array_builder->AllocateArray(capacity, max_alloc_length, length);
2578 }
2579
2580
2581 HValue* HGraphBuilder::BuildCalculateElementsSize(ElementsKind kind,
2582                                                   HValue* capacity) {
2583   int elements_size = IsFastDoubleElementsKind(kind)
2584       ? kDoubleSize
2585       : kPointerSize;
2586
2587   HConstant* elements_size_value = Add<HConstant>(elements_size);
2588   HInstruction* mul =
2589       HMul::NewImul(isolate(), zone(), context(), capacity->ActualValue(),
2590                     elements_size_value);
2591   AddInstruction(mul);
2592   mul->ClearFlag(HValue::kCanOverflow);
2593
2594   STATIC_ASSERT(FixedDoubleArray::kHeaderSize == FixedArray::kHeaderSize);
2595
2596   HConstant* header_size = Add<HConstant>(FixedArray::kHeaderSize);
2597   HValue* total_size = AddUncasted<HAdd>(mul, header_size);
2598   total_size->ClearFlag(HValue::kCanOverflow);
2599   return total_size;
2600 }
2601
2602
2603 HAllocate* HGraphBuilder::AllocateJSArrayObject(AllocationSiteMode mode) {
2604   int base_size = JSArray::kSize;
2605   if (mode == TRACK_ALLOCATION_SITE) {
2606     base_size += AllocationMemento::kSize;
2607   }
2608   HConstant* size_in_bytes = Add<HConstant>(base_size);
2609   return Add<HAllocate>(
2610       size_in_bytes, HType::JSArray(), NOT_TENURED, JS_OBJECT_TYPE);
2611 }
2612
2613
2614 HConstant* HGraphBuilder::EstablishElementsAllocationSize(
2615     ElementsKind kind,
2616     int capacity) {
2617   int base_size = IsFastDoubleElementsKind(kind)
2618       ? FixedDoubleArray::SizeFor(capacity)
2619       : FixedArray::SizeFor(capacity);
2620
2621   return Add<HConstant>(base_size);
2622 }
2623
2624
2625 HAllocate* HGraphBuilder::BuildAllocateElements(ElementsKind kind,
2626                                                 HValue* size_in_bytes) {
2627   InstanceType instance_type = IsFastDoubleElementsKind(kind)
2628       ? FIXED_DOUBLE_ARRAY_TYPE
2629       : FIXED_ARRAY_TYPE;
2630
2631   return Add<HAllocate>(size_in_bytes, HType::HeapObject(), NOT_TENURED,
2632                         instance_type);
2633 }
2634
2635
2636 void HGraphBuilder::BuildInitializeElementsHeader(HValue* elements,
2637                                                   ElementsKind kind,
2638                                                   HValue* capacity) {
2639   Factory* factory = isolate()->factory();
2640   Handle<Map> map = IsFastDoubleElementsKind(kind)
2641       ? factory->fixed_double_array_map()
2642       : factory->fixed_array_map();
2643
2644   Add<HStoreNamedField>(elements, HObjectAccess::ForMap(), Add<HConstant>(map));
2645   Add<HStoreNamedField>(elements, HObjectAccess::ForFixedArrayLength(),
2646                         capacity);
2647 }
2648
2649
2650 HValue* HGraphBuilder::BuildAllocateAndInitializeArray(ElementsKind kind,
2651                                                        HValue* capacity) {
2652   // The HForceRepresentation is to prevent possible deopt on int-smi
2653   // conversion after allocation but before the new object fields are set.
2654   capacity = AddUncasted<HForceRepresentation>(capacity, Representation::Smi());
2655   HValue* size_in_bytes = BuildCalculateElementsSize(kind, capacity);
2656   HValue* new_array = BuildAllocateElements(kind, size_in_bytes);
2657   BuildInitializeElementsHeader(new_array, kind, capacity);
2658   return new_array;
2659 }
2660
2661
2662 void HGraphBuilder::BuildJSArrayHeader(HValue* array,
2663                                        HValue* array_map,
2664                                        HValue* elements,
2665                                        AllocationSiteMode mode,
2666                                        ElementsKind elements_kind,
2667                                        HValue* allocation_site_payload,
2668                                        HValue* length_field) {
2669   Add<HStoreNamedField>(array, HObjectAccess::ForMap(), array_map);
2670
2671   HConstant* empty_fixed_array =
2672     Add<HConstant>(isolate()->factory()->empty_fixed_array());
2673
2674   Add<HStoreNamedField>(
2675       array, HObjectAccess::ForPropertiesPointer(), empty_fixed_array);
2676
2677   Add<HStoreNamedField>(
2678       array, HObjectAccess::ForElementsPointer(),
2679       elements != NULL ? elements : empty_fixed_array);
2680
2681   Add<HStoreNamedField>(
2682       array, HObjectAccess::ForArrayLength(elements_kind), length_field);
2683
2684   if (mode == TRACK_ALLOCATION_SITE) {
2685     BuildCreateAllocationMemento(
2686         array, Add<HConstant>(JSArray::kSize), allocation_site_payload);
2687   }
2688 }
2689
2690
2691 HInstruction* HGraphBuilder::AddElementAccess(
2692     HValue* elements,
2693     HValue* checked_key,
2694     HValue* val,
2695     HValue* dependency,
2696     ElementsKind elements_kind,
2697     PropertyAccessType access_type,
2698     LoadKeyedHoleMode load_mode) {
2699   if (access_type == STORE) {
2700     DCHECK(val != NULL);
2701     if (elements_kind == EXTERNAL_UINT8_CLAMPED_ELEMENTS ||
2702         elements_kind == UINT8_CLAMPED_ELEMENTS) {
2703       val = Add<HClampToUint8>(val);
2704     }
2705     return Add<HStoreKeyed>(elements, checked_key, val, elements_kind,
2706                             STORE_TO_INITIALIZED_ENTRY);
2707   }
2708
2709   DCHECK(access_type == LOAD);
2710   DCHECK(val == NULL);
2711   HLoadKeyed* load = Add<HLoadKeyed>(
2712       elements, checked_key, dependency, elements_kind, load_mode);
2713   if (elements_kind == EXTERNAL_UINT32_ELEMENTS ||
2714       elements_kind == UINT32_ELEMENTS) {
2715     graph()->RecordUint32Instruction(load);
2716   }
2717   return load;
2718 }
2719
2720
2721 HLoadNamedField* HGraphBuilder::AddLoadMap(HValue* object,
2722                                            HValue* dependency) {
2723   return Add<HLoadNamedField>(object, dependency, HObjectAccess::ForMap());
2724 }
2725
2726
2727 HLoadNamedField* HGraphBuilder::AddLoadElements(HValue* object,
2728                                                 HValue* dependency) {
2729   return Add<HLoadNamedField>(
2730       object, dependency, HObjectAccess::ForElementsPointer());
2731 }
2732
2733
2734 HLoadNamedField* HGraphBuilder::AddLoadFixedArrayLength(
2735     HValue* array,
2736     HValue* dependency) {
2737   return Add<HLoadNamedField>(
2738       array, dependency, HObjectAccess::ForFixedArrayLength());
2739 }
2740
2741
2742 HLoadNamedField* HGraphBuilder::AddLoadArrayLength(HValue* array,
2743                                                    ElementsKind kind,
2744                                                    HValue* dependency) {
2745   return Add<HLoadNamedField>(
2746       array, dependency, HObjectAccess::ForArrayLength(kind));
2747 }
2748
2749
2750 HValue* HGraphBuilder::BuildNewElementsCapacity(HValue* old_capacity) {
2751   HValue* half_old_capacity = AddUncasted<HShr>(old_capacity,
2752                                                 graph_->GetConstant1());
2753
2754   HValue* new_capacity = AddUncasted<HAdd>(half_old_capacity, old_capacity);
2755   new_capacity->ClearFlag(HValue::kCanOverflow);
2756
2757   HValue* min_growth = Add<HConstant>(16);
2758
2759   new_capacity = AddUncasted<HAdd>(new_capacity, min_growth);
2760   new_capacity->ClearFlag(HValue::kCanOverflow);
2761
2762   return new_capacity;
2763 }
2764
2765
2766 HValue* HGraphBuilder::BuildGrowElementsCapacity(HValue* object,
2767                                                  HValue* elements,
2768                                                  ElementsKind kind,
2769                                                  ElementsKind new_kind,
2770                                                  HValue* length,
2771                                                  HValue* new_capacity) {
2772   Add<HBoundsCheck>(new_capacity, Add<HConstant>(
2773           (Page::kMaxRegularHeapObjectSize - FixedArray::kHeaderSize) >>
2774           ElementsKindToShiftSize(new_kind)));
2775
2776   HValue* new_elements =
2777       BuildAllocateAndInitializeArray(new_kind, new_capacity);
2778
2779   BuildCopyElements(elements, kind, new_elements,
2780                     new_kind, length, new_capacity);
2781
2782   Add<HStoreNamedField>(object, HObjectAccess::ForElementsPointer(),
2783                         new_elements);
2784
2785   return new_elements;
2786 }
2787
2788
2789 void HGraphBuilder::BuildFillElementsWithValue(HValue* elements,
2790                                                ElementsKind elements_kind,
2791                                                HValue* from,
2792                                                HValue* to,
2793                                                HValue* value) {
2794   if (to == NULL) {
2795     to = AddLoadFixedArrayLength(elements);
2796   }
2797
2798   // Special loop unfolding case
2799   STATIC_ASSERT(JSArray::kPreallocatedArrayElements <=
2800                 kElementLoopUnrollThreshold);
2801   int initial_capacity = -1;
2802   if (from->IsInteger32Constant() && to->IsInteger32Constant()) {
2803     int constant_from = from->GetInteger32Constant();
2804     int constant_to = to->GetInteger32Constant();
2805
2806     if (constant_from == 0 && constant_to <= kElementLoopUnrollThreshold) {
2807       initial_capacity = constant_to;
2808     }
2809   }
2810
2811   if (initial_capacity >= 0) {
2812     for (int i = 0; i < initial_capacity; i++) {
2813       HInstruction* key = Add<HConstant>(i);
2814       Add<HStoreKeyed>(elements, key, value, elements_kind);
2815     }
2816   } else {
2817     // Carefully loop backwards so that the "from" remains live through the loop
2818     // rather than the to. This often corresponds to keeping length live rather
2819     // then capacity, which helps register allocation, since length is used more
2820     // other than capacity after filling with holes.
2821     LoopBuilder builder(this, context(), LoopBuilder::kPostDecrement);
2822
2823     HValue* key = builder.BeginBody(to, from, Token::GT);
2824
2825     HValue* adjusted_key = AddUncasted<HSub>(key, graph()->GetConstant1());
2826     adjusted_key->ClearFlag(HValue::kCanOverflow);
2827
2828     Add<HStoreKeyed>(elements, adjusted_key, value, elements_kind);
2829
2830     builder.EndBody();
2831   }
2832 }
2833
2834
2835 void HGraphBuilder::BuildFillElementsWithHole(HValue* elements,
2836                                               ElementsKind elements_kind,
2837                                               HValue* from,
2838                                               HValue* to) {
2839   // Fast elements kinds need to be initialized in case statements below cause a
2840   // garbage collection.
2841
2842   HValue* hole = IsFastSmiOrObjectElementsKind(elements_kind)
2843                      ? graph()->GetConstantHole()
2844                      : Add<HConstant>(HConstant::kHoleNaN);
2845
2846   // Since we're about to store a hole value, the store instruction below must
2847   // assume an elements kind that supports heap object values.
2848   if (IsFastSmiOrObjectElementsKind(elements_kind)) {
2849     elements_kind = FAST_HOLEY_ELEMENTS;
2850   }
2851
2852   BuildFillElementsWithValue(elements, elements_kind, from, to, hole);
2853 }
2854
2855
2856 void HGraphBuilder::BuildCopyProperties(HValue* from_properties,
2857                                         HValue* to_properties, HValue* length,
2858                                         HValue* capacity) {
2859   ElementsKind kind = FAST_ELEMENTS;
2860
2861   BuildFillElementsWithValue(to_properties, kind, length, capacity,
2862                              graph()->GetConstantUndefined());
2863
2864   LoopBuilder builder(this, context(), LoopBuilder::kPostDecrement);
2865
2866   HValue* key = builder.BeginBody(length, graph()->GetConstant0(), Token::GT);
2867
2868   key = AddUncasted<HSub>(key, graph()->GetConstant1());
2869   key->ClearFlag(HValue::kCanOverflow);
2870
2871   HValue* element = Add<HLoadKeyed>(from_properties, key, nullptr, kind);
2872
2873   Add<HStoreKeyed>(to_properties, key, element, kind);
2874
2875   builder.EndBody();
2876 }
2877
2878
2879 void HGraphBuilder::BuildCopyElements(HValue* from_elements,
2880                                       ElementsKind from_elements_kind,
2881                                       HValue* to_elements,
2882                                       ElementsKind to_elements_kind,
2883                                       HValue* length,
2884                                       HValue* capacity) {
2885   int constant_capacity = -1;
2886   if (capacity != NULL &&
2887       capacity->IsConstant() &&
2888       HConstant::cast(capacity)->HasInteger32Value()) {
2889     int constant_candidate = HConstant::cast(capacity)->Integer32Value();
2890     if (constant_candidate <= kElementLoopUnrollThreshold) {
2891       constant_capacity = constant_candidate;
2892     }
2893   }
2894
2895   bool pre_fill_with_holes =
2896     IsFastDoubleElementsKind(from_elements_kind) &&
2897     IsFastObjectElementsKind(to_elements_kind);
2898   if (pre_fill_with_holes) {
2899     // If the copy might trigger a GC, make sure that the FixedArray is
2900     // pre-initialized with holes to make sure that it's always in a
2901     // consistent state.
2902     BuildFillElementsWithHole(to_elements, to_elements_kind,
2903                               graph()->GetConstant0(), NULL);
2904   }
2905
2906   if (constant_capacity != -1) {
2907     // Unroll the loop for small elements kinds.
2908     for (int i = 0; i < constant_capacity; i++) {
2909       HValue* key_constant = Add<HConstant>(i);
2910       HInstruction* value = Add<HLoadKeyed>(from_elements, key_constant,
2911                                             nullptr, from_elements_kind);
2912       Add<HStoreKeyed>(to_elements, key_constant, value, to_elements_kind);
2913     }
2914   } else {
2915     if (!pre_fill_with_holes &&
2916         (capacity == NULL || !length->Equals(capacity))) {
2917       BuildFillElementsWithHole(to_elements, to_elements_kind,
2918                                 length, NULL);
2919     }
2920
2921     LoopBuilder builder(this, context(), LoopBuilder::kPostDecrement);
2922
2923     HValue* key = builder.BeginBody(length, graph()->GetConstant0(),
2924                                     Token::GT);
2925
2926     key = AddUncasted<HSub>(key, graph()->GetConstant1());
2927     key->ClearFlag(HValue::kCanOverflow);
2928
2929     HValue* element = Add<HLoadKeyed>(from_elements, key, nullptr,
2930                                       from_elements_kind, ALLOW_RETURN_HOLE);
2931
2932     ElementsKind kind = (IsHoleyElementsKind(from_elements_kind) &&
2933                          IsFastSmiElementsKind(to_elements_kind))
2934       ? FAST_HOLEY_ELEMENTS : to_elements_kind;
2935
2936     if (IsHoleyElementsKind(from_elements_kind) &&
2937         from_elements_kind != to_elements_kind) {
2938       IfBuilder if_hole(this);
2939       if_hole.If<HCompareHoleAndBranch>(element);
2940       if_hole.Then();
2941       HConstant* hole_constant = IsFastDoubleElementsKind(to_elements_kind)
2942                                      ? Add<HConstant>(HConstant::kHoleNaN)
2943                                      : graph()->GetConstantHole();
2944       Add<HStoreKeyed>(to_elements, key, hole_constant, kind);
2945       if_hole.Else();
2946       HStoreKeyed* store = Add<HStoreKeyed>(to_elements, key, element, kind);
2947       store->SetFlag(HValue::kAllowUndefinedAsNaN);
2948       if_hole.End();
2949     } else {
2950       HStoreKeyed* store = Add<HStoreKeyed>(to_elements, key, element, kind);
2951       store->SetFlag(HValue::kAllowUndefinedAsNaN);
2952     }
2953
2954     builder.EndBody();
2955   }
2956
2957   Counters* counters = isolate()->counters();
2958   AddIncrementCounter(counters->inlined_copied_elements());
2959 }
2960
2961
2962 HValue* HGraphBuilder::BuildCloneShallowArrayCow(HValue* boilerplate,
2963                                                  HValue* allocation_site,
2964                                                  AllocationSiteMode mode,
2965                                                  ElementsKind kind) {
2966   HAllocate* array = AllocateJSArrayObject(mode);
2967
2968   HValue* map = AddLoadMap(boilerplate);
2969   HValue* elements = AddLoadElements(boilerplate);
2970   HValue* length = AddLoadArrayLength(boilerplate, kind);
2971
2972   BuildJSArrayHeader(array,
2973                      map,
2974                      elements,
2975                      mode,
2976                      FAST_ELEMENTS,
2977                      allocation_site,
2978                      length);
2979   return array;
2980 }
2981
2982
2983 HValue* HGraphBuilder::BuildCloneShallowArrayEmpty(HValue* boilerplate,
2984                                                    HValue* allocation_site,
2985                                                    AllocationSiteMode mode) {
2986   HAllocate* array = AllocateJSArrayObject(mode);
2987
2988   HValue* map = AddLoadMap(boilerplate);
2989
2990   BuildJSArrayHeader(array,
2991                      map,
2992                      NULL,  // set elements to empty fixed array
2993                      mode,
2994                      FAST_ELEMENTS,
2995                      allocation_site,
2996                      graph()->GetConstant0());
2997   return array;
2998 }
2999
3000
3001 HValue* HGraphBuilder::BuildCloneShallowArrayNonEmpty(HValue* boilerplate,
3002                                                       HValue* allocation_site,
3003                                                       AllocationSiteMode mode,
3004                                                       ElementsKind kind) {
3005   HValue* boilerplate_elements = AddLoadElements(boilerplate);
3006   HValue* capacity = AddLoadFixedArrayLength(boilerplate_elements);
3007
3008   // Generate size calculation code here in order to make it dominate
3009   // the JSArray allocation.
3010   HValue* elements_size = BuildCalculateElementsSize(kind, capacity);
3011
3012   // Create empty JSArray object for now, store elimination should remove
3013   // redundant initialization of elements and length fields and at the same
3014   // time the object will be fully prepared for GC if it happens during
3015   // elements allocation.
3016   HValue* result = BuildCloneShallowArrayEmpty(
3017       boilerplate, allocation_site, mode);
3018
3019   HAllocate* elements = BuildAllocateElements(kind, elements_size);
3020
3021   // This function implicitly relies on the fact that the
3022   // FastCloneShallowArrayStub is called only for literals shorter than
3023   // JSObject::kInitialMaxFastElementArray.
3024   // Can't add HBoundsCheck here because otherwise the stub will eager a frame.
3025   HConstant* size_upper_bound = EstablishElementsAllocationSize(
3026       kind, JSObject::kInitialMaxFastElementArray);
3027   elements->set_size_upper_bound(size_upper_bound);
3028
3029   Add<HStoreNamedField>(result, HObjectAccess::ForElementsPointer(), elements);
3030
3031   // The allocation for the cloned array above causes register pressure on
3032   // machines with low register counts. Force a reload of the boilerplate
3033   // elements here to free up a register for the allocation to avoid unnecessary
3034   // spillage.
3035   boilerplate_elements = AddLoadElements(boilerplate);
3036   boilerplate_elements->SetFlag(HValue::kCantBeReplaced);
3037
3038   // Copy the elements array header.
3039   for (int i = 0; i < FixedArrayBase::kHeaderSize; i += kPointerSize) {
3040     HObjectAccess access = HObjectAccess::ForFixedArrayHeader(i);
3041     Add<HStoreNamedField>(
3042         elements, access,
3043         Add<HLoadNamedField>(boilerplate_elements, nullptr, access));
3044   }
3045
3046   // And the result of the length
3047   HValue* length = AddLoadArrayLength(boilerplate, kind);
3048   Add<HStoreNamedField>(result, HObjectAccess::ForArrayLength(kind), length);
3049
3050   BuildCopyElements(boilerplate_elements, kind, elements,
3051                     kind, length, NULL);
3052   return result;
3053 }
3054
3055
3056 void HGraphBuilder::BuildCompareNil(HValue* value, Type* type,
3057                                     HIfContinuation* continuation,
3058                                     MapEmbedding map_embedding) {
3059   IfBuilder if_nil(this);
3060   bool some_case_handled = false;
3061   bool some_case_missing = false;
3062
3063   if (type->Maybe(Type::Null())) {
3064     if (some_case_handled) if_nil.Or();
3065     if_nil.If<HCompareObjectEqAndBranch>(value, graph()->GetConstantNull());
3066     some_case_handled = true;
3067   } else {
3068     some_case_missing = true;
3069   }
3070
3071   if (type->Maybe(Type::Undefined())) {
3072     if (some_case_handled) if_nil.Or();
3073     if_nil.If<HCompareObjectEqAndBranch>(value,
3074                                          graph()->GetConstantUndefined());
3075     some_case_handled = true;
3076   } else {
3077     some_case_missing = true;
3078   }
3079
3080   if (type->Maybe(Type::Undetectable())) {
3081     if (some_case_handled) if_nil.Or();
3082     if_nil.If<HIsUndetectableAndBranch>(value);
3083     some_case_handled = true;
3084   } else {
3085     some_case_missing = true;
3086   }
3087
3088   if (some_case_missing) {
3089     if_nil.Then();
3090     if_nil.Else();
3091     if (type->NumClasses() == 1) {
3092       BuildCheckHeapObject(value);
3093       // For ICs, the map checked below is a sentinel map that gets replaced by
3094       // the monomorphic map when the code is used as a template to generate a
3095       // new IC. For optimized functions, there is no sentinel map, the map
3096       // emitted below is the actual monomorphic map.
3097       if (map_embedding == kEmbedMapsViaWeakCells) {
3098         HValue* cell =
3099             Add<HConstant>(Map::WeakCellForMap(type->Classes().Current()));
3100         HValue* expected_map = Add<HLoadNamedField>(
3101             cell, nullptr, HObjectAccess::ForWeakCellValue());
3102         HValue* map =
3103             Add<HLoadNamedField>(value, nullptr, HObjectAccess::ForMap());
3104         IfBuilder map_check(this);
3105         map_check.IfNot<HCompareObjectEqAndBranch>(expected_map, map);
3106         map_check.ThenDeopt(Deoptimizer::kUnknownMap);
3107         map_check.End();
3108       } else {
3109         DCHECK(map_embedding == kEmbedMapsDirectly);
3110         Add<HCheckMaps>(value, type->Classes().Current());
3111       }
3112     } else {
3113       if_nil.Deopt(Deoptimizer::kTooManyUndetectableTypes);
3114     }
3115   }
3116
3117   if_nil.CaptureContinuation(continuation);
3118 }
3119
3120
3121 void HGraphBuilder::BuildCreateAllocationMemento(
3122     HValue* previous_object,
3123     HValue* previous_object_size,
3124     HValue* allocation_site) {
3125   DCHECK(allocation_site != NULL);
3126   HInnerAllocatedObject* allocation_memento = Add<HInnerAllocatedObject>(
3127       previous_object, previous_object_size, HType::HeapObject());
3128   AddStoreMapConstant(
3129       allocation_memento, isolate()->factory()->allocation_memento_map());
3130   Add<HStoreNamedField>(
3131       allocation_memento,
3132       HObjectAccess::ForAllocationMementoSite(),
3133       allocation_site);
3134   if (FLAG_allocation_site_pretenuring) {
3135     HValue* memento_create_count =
3136         Add<HLoadNamedField>(allocation_site, nullptr,
3137                              HObjectAccess::ForAllocationSiteOffset(
3138                                  AllocationSite::kPretenureCreateCountOffset));
3139     memento_create_count = AddUncasted<HAdd>(
3140         memento_create_count, graph()->GetConstant1());
3141     // This smi value is reset to zero after every gc, overflow isn't a problem
3142     // since the counter is bounded by the new space size.
3143     memento_create_count->ClearFlag(HValue::kCanOverflow);
3144     Add<HStoreNamedField>(
3145         allocation_site, HObjectAccess::ForAllocationSiteOffset(
3146             AllocationSite::kPretenureCreateCountOffset), memento_create_count);
3147   }
3148 }
3149
3150
3151 HInstruction* HGraphBuilder::BuildGetNativeContext() {
3152   // Get the global object, then the native context
3153   HValue* global_object = Add<HLoadNamedField>(
3154       context(), nullptr,
3155       HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
3156   return Add<HLoadNamedField>(global_object, nullptr,
3157                               HObjectAccess::ForObservableJSObjectOffset(
3158                                   GlobalObject::kNativeContextOffset));
3159 }
3160
3161
3162 HInstruction* HGraphBuilder::BuildGetNativeContext(HValue* closure) {
3163   // Get the global object, then the native context
3164   HInstruction* context = Add<HLoadNamedField>(
3165       closure, nullptr, HObjectAccess::ForFunctionContextPointer());
3166   HInstruction* global_object = Add<HLoadNamedField>(
3167       context, nullptr,
3168       HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
3169   HObjectAccess access = HObjectAccess::ForObservableJSObjectOffset(
3170       GlobalObject::kNativeContextOffset);
3171   return Add<HLoadNamedField>(global_object, nullptr, access);
3172 }
3173
3174
3175 HInstruction* HGraphBuilder::BuildGetScriptContext(int context_index) {
3176   HValue* native_context = BuildGetNativeContext();
3177   HValue* script_context_table = Add<HLoadNamedField>(
3178       native_context, nullptr,
3179       HObjectAccess::ForContextSlot(Context::SCRIPT_CONTEXT_TABLE_INDEX));
3180   return Add<HLoadNamedField>(script_context_table, nullptr,
3181                               HObjectAccess::ForScriptContext(context_index));
3182 }
3183
3184
3185 HValue* HGraphBuilder::BuildGetParentContext(HValue* depth, int depth_value) {
3186   HValue* script_context = context();
3187   if (depth != NULL) {
3188     HValue* zero = graph()->GetConstant0();
3189
3190     Push(script_context);
3191     Push(depth);
3192
3193     LoopBuilder loop(this);
3194     loop.BeginBody(2);  // Drop script_context and depth from last environment
3195                         // to appease live range building without simulates.
3196     depth = Pop();
3197     script_context = Pop();
3198
3199     script_context = Add<HLoadNamedField>(
3200         script_context, nullptr,
3201         HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX));
3202     depth = AddUncasted<HSub>(depth, graph()->GetConstant1());
3203     depth->ClearFlag(HValue::kCanOverflow);
3204
3205     IfBuilder if_break(this);
3206     if_break.If<HCompareNumericAndBranch, HValue*>(depth, zero, Token::EQ);
3207     if_break.Then();
3208     {
3209       Push(script_context);  // The result.
3210       loop.Break();
3211     }
3212     if_break.Else();
3213     {
3214       Push(script_context);
3215       Push(depth);
3216     }
3217     loop.EndBody();
3218     if_break.End();
3219
3220     script_context = Pop();
3221   } else if (depth_value > 0) {
3222     // Unroll the above loop.
3223     for (int i = 0; i < depth_value; i++) {
3224       script_context = Add<HLoadNamedField>(
3225           script_context, nullptr,
3226           HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX));
3227     }
3228   }
3229   return script_context;
3230 }
3231
3232
3233 HInstruction* HGraphBuilder::BuildGetArrayFunction() {
3234   HInstruction* native_context = BuildGetNativeContext();
3235   HInstruction* index =
3236       Add<HConstant>(static_cast<int32_t>(Context::ARRAY_FUNCTION_INDEX));
3237   return Add<HLoadKeyed>(native_context, index, nullptr, FAST_ELEMENTS);
3238 }
3239
3240
3241 HValue* HGraphBuilder::BuildArrayBufferViewFieldAccessor(HValue* object,
3242                                                          HValue* checked_object,
3243                                                          FieldIndex index) {
3244   NoObservableSideEffectsScope scope(this);
3245   HObjectAccess access = HObjectAccess::ForObservableJSObjectOffset(
3246       index.offset(), Representation::Tagged());
3247   HInstruction* buffer = Add<HLoadNamedField>(
3248       object, checked_object, HObjectAccess::ForJSArrayBufferViewBuffer());
3249   HInstruction* field = Add<HLoadNamedField>(object, checked_object, access);
3250
3251   HInstruction* flags = Add<HLoadNamedField>(
3252       buffer, nullptr, HObjectAccess::ForJSArrayBufferBitField());
3253   HValue* was_neutered_mask =
3254       Add<HConstant>(1 << JSArrayBuffer::WasNeutered::kShift);
3255   HValue* was_neutered_test =
3256       AddUncasted<HBitwise>(Token::BIT_AND, flags, was_neutered_mask);
3257
3258   IfBuilder if_was_neutered(this);
3259   if_was_neutered.If<HCompareNumericAndBranch>(
3260       was_neutered_test, graph()->GetConstant0(), Token::NE);
3261   if_was_neutered.Then();
3262   Push(graph()->GetConstant0());
3263   if_was_neutered.Else();
3264   Push(field);
3265   if_was_neutered.End();
3266
3267   return Pop();
3268 }
3269
3270
3271 HGraphBuilder::JSArrayBuilder::JSArrayBuilder(HGraphBuilder* builder,
3272     ElementsKind kind,
3273     HValue* allocation_site_payload,
3274     HValue* constructor_function,
3275     AllocationSiteOverrideMode override_mode) :
3276         builder_(builder),
3277         kind_(kind),
3278         allocation_site_payload_(allocation_site_payload),
3279         constructor_function_(constructor_function) {
3280   DCHECK(!allocation_site_payload->IsConstant() ||
3281          HConstant::cast(allocation_site_payload)->handle(
3282              builder_->isolate())->IsAllocationSite());
3283   mode_ = override_mode == DISABLE_ALLOCATION_SITES
3284       ? DONT_TRACK_ALLOCATION_SITE
3285       : AllocationSite::GetMode(kind);
3286 }
3287
3288
3289 HGraphBuilder::JSArrayBuilder::JSArrayBuilder(HGraphBuilder* builder,
3290                                               ElementsKind kind,
3291                                               HValue* constructor_function) :
3292     builder_(builder),
3293     kind_(kind),
3294     mode_(DONT_TRACK_ALLOCATION_SITE),
3295     allocation_site_payload_(NULL),
3296     constructor_function_(constructor_function) {
3297 }
3298
3299
3300 HValue* HGraphBuilder::JSArrayBuilder::EmitMapCode() {
3301   if (!builder()->top_info()->IsStub()) {
3302     // A constant map is fine.
3303     Handle<Map> map(builder()->isolate()->get_initial_js_array_map(kind_),
3304                     builder()->isolate());
3305     return builder()->Add<HConstant>(map);
3306   }
3307
3308   if (constructor_function_ != NULL && kind_ == GetInitialFastElementsKind()) {
3309     // No need for a context lookup if the kind_ matches the initial
3310     // map, because we can just load the map in that case.
3311     HObjectAccess access = HObjectAccess::ForPrototypeOrInitialMap();
3312     return builder()->Add<HLoadNamedField>(constructor_function_, nullptr,
3313                                            access);
3314   }
3315
3316   // TODO(mvstanton): we should always have a constructor function if we
3317   // are creating a stub.
3318   HInstruction* native_context = constructor_function_ != NULL
3319       ? builder()->BuildGetNativeContext(constructor_function_)
3320       : builder()->BuildGetNativeContext();
3321
3322   HInstruction* index = builder()->Add<HConstant>(
3323       static_cast<int32_t>(Context::JS_ARRAY_MAPS_INDEX));
3324
3325   HInstruction* map_array =
3326       builder()->Add<HLoadKeyed>(native_context, index, nullptr, FAST_ELEMENTS);
3327
3328   HInstruction* kind_index = builder()->Add<HConstant>(kind_);
3329
3330   return builder()->Add<HLoadKeyed>(map_array, kind_index, nullptr,
3331                                     FAST_ELEMENTS);
3332 }
3333
3334
3335 HValue* HGraphBuilder::JSArrayBuilder::EmitInternalMapCode() {
3336   // Find the map near the constructor function
3337   HObjectAccess access = HObjectAccess::ForPrototypeOrInitialMap();
3338   return builder()->Add<HLoadNamedField>(constructor_function_, nullptr,
3339                                          access);
3340 }
3341
3342
3343 HAllocate* HGraphBuilder::JSArrayBuilder::AllocateEmptyArray() {
3344   HConstant* capacity = builder()->Add<HConstant>(initial_capacity());
3345   return AllocateArray(capacity,
3346                        capacity,
3347                        builder()->graph()->GetConstant0());
3348 }
3349
3350
3351 HAllocate* HGraphBuilder::JSArrayBuilder::AllocateArray(
3352     HValue* capacity,
3353     HConstant* capacity_upper_bound,
3354     HValue* length_field,
3355     FillMode fill_mode) {
3356   return AllocateArray(capacity,
3357                        capacity_upper_bound->GetInteger32Constant(),
3358                        length_field,
3359                        fill_mode);
3360 }
3361
3362
3363 HAllocate* HGraphBuilder::JSArrayBuilder::AllocateArray(
3364     HValue* capacity,
3365     int capacity_upper_bound,
3366     HValue* length_field,
3367     FillMode fill_mode) {
3368   HConstant* elememts_size_upper_bound = capacity->IsInteger32Constant()
3369       ? HConstant::cast(capacity)
3370       : builder()->EstablishElementsAllocationSize(kind_, capacity_upper_bound);
3371
3372   HAllocate* array = AllocateArray(capacity, length_field, fill_mode);
3373   if (!elements_location_->has_size_upper_bound()) {
3374     elements_location_->set_size_upper_bound(elememts_size_upper_bound);
3375   }
3376   return array;
3377 }
3378
3379
3380 HAllocate* HGraphBuilder::JSArrayBuilder::AllocateArray(
3381     HValue* capacity,
3382     HValue* length_field,
3383     FillMode fill_mode) {
3384   // These HForceRepresentations are because we store these as fields in the
3385   // objects we construct, and an int32-to-smi HChange could deopt. Accept
3386   // the deopt possibility now, before allocation occurs.
3387   capacity =
3388       builder()->AddUncasted<HForceRepresentation>(capacity,
3389                                                    Representation::Smi());
3390   length_field =
3391       builder()->AddUncasted<HForceRepresentation>(length_field,
3392                                                    Representation::Smi());
3393
3394   // Generate size calculation code here in order to make it dominate
3395   // the JSArray allocation.
3396   HValue* elements_size =
3397       builder()->BuildCalculateElementsSize(kind_, capacity);
3398
3399   // Allocate (dealing with failure appropriately)
3400   HAllocate* array_object = builder()->AllocateJSArrayObject(mode_);
3401
3402   // Fill in the fields: map, properties, length
3403   HValue* map;
3404   if (allocation_site_payload_ == NULL) {
3405     map = EmitInternalMapCode();
3406   } else {
3407     map = EmitMapCode();
3408   }
3409
3410   builder()->BuildJSArrayHeader(array_object,
3411                                 map,
3412                                 NULL,  // set elements to empty fixed array
3413                                 mode_,
3414                                 kind_,
3415                                 allocation_site_payload_,
3416                                 length_field);
3417
3418   // Allocate and initialize the elements
3419   elements_location_ = builder()->BuildAllocateElements(kind_, elements_size);
3420
3421   builder()->BuildInitializeElementsHeader(elements_location_, kind_, capacity);
3422
3423   // Set the elements
3424   builder()->Add<HStoreNamedField>(
3425       array_object, HObjectAccess::ForElementsPointer(), elements_location_);
3426
3427   if (fill_mode == FILL_WITH_HOLE) {
3428     builder()->BuildFillElementsWithHole(elements_location_, kind_,
3429                                          graph()->GetConstant0(), capacity);
3430   }
3431
3432   return array_object;
3433 }
3434
3435
3436 HValue* HGraphBuilder::AddLoadJSBuiltin(Builtins::JavaScript builtin) {
3437   HValue* global_object = Add<HLoadNamedField>(
3438       context(), nullptr,
3439       HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
3440   HObjectAccess access = HObjectAccess::ForObservableJSObjectOffset(
3441       GlobalObject::kBuiltinsOffset);
3442   HValue* builtins = Add<HLoadNamedField>(global_object, nullptr, access);
3443   HObjectAccess function_access = HObjectAccess::ForObservableJSObjectOffset(
3444           JSBuiltinsObject::OffsetOfFunctionWithId(builtin));
3445   return Add<HLoadNamedField>(builtins, nullptr, function_access);
3446 }
3447
3448
3449 HOptimizedGraphBuilder::HOptimizedGraphBuilder(CompilationInfo* info)
3450     : HGraphBuilder(info),
3451       function_state_(NULL),
3452       initial_function_state_(this, info, NORMAL_RETURN, 0),
3453       ast_context_(NULL),
3454       break_scope_(NULL),
3455       inlined_count_(0),
3456       globals_(10, info->zone()),
3457       osr_(new(info->zone()) HOsrBuilder(this)) {
3458   // This is not initialized in the initializer list because the
3459   // constructor for the initial state relies on function_state_ == NULL
3460   // to know it's the initial state.
3461   function_state_ = &initial_function_state_;
3462   InitializeAstVisitor(info->isolate(), info->zone());
3463   if (top_info()->is_tracking_positions()) {
3464     SetSourcePosition(info->shared_info()->start_position());
3465   }
3466 }
3467
3468
3469 HBasicBlock* HOptimizedGraphBuilder::CreateJoin(HBasicBlock* first,
3470                                                 HBasicBlock* second,
3471                                                 BailoutId join_id) {
3472   if (first == NULL) {
3473     return second;
3474   } else if (second == NULL) {
3475     return first;
3476   } else {
3477     HBasicBlock* join_block = graph()->CreateBasicBlock();
3478     Goto(first, join_block);
3479     Goto(second, join_block);
3480     join_block->SetJoinId(join_id);
3481     return join_block;
3482   }
3483 }
3484
3485
3486 HBasicBlock* HOptimizedGraphBuilder::JoinContinue(IterationStatement* statement,
3487                                                   HBasicBlock* exit_block,
3488                                                   HBasicBlock* continue_block) {
3489   if (continue_block != NULL) {
3490     if (exit_block != NULL) Goto(exit_block, continue_block);
3491     continue_block->SetJoinId(statement->ContinueId());
3492     return continue_block;
3493   }
3494   return exit_block;
3495 }
3496
3497
3498 HBasicBlock* HOptimizedGraphBuilder::CreateLoop(IterationStatement* statement,
3499                                                 HBasicBlock* loop_entry,
3500                                                 HBasicBlock* body_exit,
3501                                                 HBasicBlock* loop_successor,
3502                                                 HBasicBlock* break_block) {
3503   if (body_exit != NULL) Goto(body_exit, loop_entry);
3504   loop_entry->PostProcessLoopHeader(statement);
3505   if (break_block != NULL) {
3506     if (loop_successor != NULL) Goto(loop_successor, break_block);
3507     break_block->SetJoinId(statement->ExitId());
3508     return break_block;
3509   }
3510   return loop_successor;
3511 }
3512
3513
3514 // Build a new loop header block and set it as the current block.
3515 HBasicBlock* HOptimizedGraphBuilder::BuildLoopEntry() {
3516   HBasicBlock* loop_entry = CreateLoopHeaderBlock();
3517   Goto(loop_entry);
3518   set_current_block(loop_entry);
3519   return loop_entry;
3520 }
3521
3522
3523 HBasicBlock* HOptimizedGraphBuilder::BuildLoopEntry(
3524     IterationStatement* statement) {
3525   HBasicBlock* loop_entry = osr()->HasOsrEntryAt(statement)
3526       ? osr()->BuildOsrLoopEntry(statement)
3527       : BuildLoopEntry();
3528   return loop_entry;
3529 }
3530
3531
3532 void HBasicBlock::FinishExit(HControlInstruction* instruction,
3533                              SourcePosition position) {
3534   Finish(instruction, position);
3535   ClearEnvironment();
3536 }
3537
3538
3539 std::ostream& operator<<(std::ostream& os, const HBasicBlock& b) {
3540   return os << "B" << b.block_id();
3541 }
3542
3543
3544 HGraph::HGraph(CompilationInfo* info)
3545     : isolate_(info->isolate()),
3546       next_block_id_(0),
3547       entry_block_(NULL),
3548       blocks_(8, info->zone()),
3549       values_(16, info->zone()),
3550       phi_list_(NULL),
3551       uint32_instructions_(NULL),
3552       osr_(NULL),
3553       info_(info),
3554       zone_(info->zone()),
3555       is_recursive_(false),
3556       use_optimistic_licm_(false),
3557       depends_on_empty_array_proto_elements_(false),
3558       type_change_checksum_(0),
3559       maximum_environment_size_(0),
3560       no_side_effects_scope_count_(0),
3561       disallow_adding_new_values_(false) {
3562   if (info->IsStub()) {
3563     CallInterfaceDescriptor descriptor =
3564         info->code_stub()->GetCallInterfaceDescriptor();
3565     start_environment_ =
3566         new (zone_) HEnvironment(zone_, descriptor.GetRegisterParameterCount());
3567   } else {
3568     if (info->is_tracking_positions()) {
3569       info->TraceInlinedFunction(info->shared_info(), SourcePosition::Unknown(),
3570                                  InlinedFunctionInfo::kNoParentId);
3571     }
3572     start_environment_ =
3573         new(zone_) HEnvironment(NULL, info->scope(), info->closure(), zone_);
3574   }
3575   start_environment_->set_ast_id(BailoutId::FunctionEntry());
3576   entry_block_ = CreateBasicBlock();
3577   entry_block_->SetInitialEnvironment(start_environment_);
3578 }
3579
3580
3581 HBasicBlock* HGraph::CreateBasicBlock() {
3582   HBasicBlock* result = new(zone()) HBasicBlock(this);
3583   blocks_.Add(result, zone());
3584   return result;
3585 }
3586
3587
3588 void HGraph::FinalizeUniqueness() {
3589   DisallowHeapAllocation no_gc;
3590   for (int i = 0; i < blocks()->length(); ++i) {
3591     for (HInstructionIterator it(blocks()->at(i)); !it.Done(); it.Advance()) {
3592       it.Current()->FinalizeUniqueness();
3593     }
3594   }
3595 }
3596
3597
3598 int HGraph::SourcePositionToScriptPosition(SourcePosition pos) {
3599   return (FLAG_hydrogen_track_positions && !pos.IsUnknown())
3600              ? info()->start_position_for(pos.inlining_id()) + pos.position()
3601              : pos.raw();
3602 }
3603
3604
3605 // Block ordering was implemented with two mutually recursive methods,
3606 // HGraph::Postorder and HGraph::PostorderLoopBlocks.
3607 // The recursion could lead to stack overflow so the algorithm has been
3608 // implemented iteratively.
3609 // At a high level the algorithm looks like this:
3610 //
3611 // Postorder(block, loop_header) : {
3612 //   if (block has already been visited or is of another loop) return;
3613 //   mark block as visited;
3614 //   if (block is a loop header) {
3615 //     VisitLoopMembers(block, loop_header);
3616 //     VisitSuccessorsOfLoopHeader(block);
3617 //   } else {
3618 //     VisitSuccessors(block)
3619 //   }
3620 //   put block in result list;
3621 // }
3622 //
3623 // VisitLoopMembers(block, outer_loop_header) {
3624 //   foreach (block b in block loop members) {
3625 //     VisitSuccessorsOfLoopMember(b, outer_loop_header);
3626 //     if (b is loop header) VisitLoopMembers(b);
3627 //   }
3628 // }
3629 //
3630 // VisitSuccessorsOfLoopMember(block, outer_loop_header) {
3631 //   foreach (block b in block successors) Postorder(b, outer_loop_header)
3632 // }
3633 //
3634 // VisitSuccessorsOfLoopHeader(block) {
3635 //   foreach (block b in block successors) Postorder(b, block)
3636 // }
3637 //
3638 // VisitSuccessors(block, loop_header) {
3639 //   foreach (block b in block successors) Postorder(b, loop_header)
3640 // }
3641 //
3642 // The ordering is started calling Postorder(entry, NULL).
3643 //
3644 // Each instance of PostorderProcessor represents the "stack frame" of the
3645 // recursion, and particularly keeps the state of the loop (iteration) of the
3646 // "Visit..." function it represents.
3647 // To recycle memory we keep all the frames in a double linked list but
3648 // this means that we cannot use constructors to initialize the frames.
3649 //
3650 class PostorderProcessor : public ZoneObject {
3651  public:
3652   // Back link (towards the stack bottom).
3653   PostorderProcessor* parent() {return father_; }
3654   // Forward link (towards the stack top).
3655   PostorderProcessor* child() {return child_; }
3656   HBasicBlock* block() { return block_; }
3657   HLoopInformation* loop() { return loop_; }
3658   HBasicBlock* loop_header() { return loop_header_; }
3659
3660   static PostorderProcessor* CreateEntryProcessor(Zone* zone,
3661                                                   HBasicBlock* block) {
3662     PostorderProcessor* result = new(zone) PostorderProcessor(NULL);
3663     return result->SetupSuccessors(zone, block, NULL);
3664   }
3665
3666   PostorderProcessor* PerformStep(Zone* zone,
3667                                   ZoneList<HBasicBlock*>* order) {
3668     PostorderProcessor* next =
3669         PerformNonBacktrackingStep(zone, order);
3670     if (next != NULL) {
3671       return next;
3672     } else {
3673       return Backtrack(zone, order);
3674     }
3675   }
3676
3677  private:
3678   explicit PostorderProcessor(PostorderProcessor* father)
3679       : father_(father), child_(NULL), successor_iterator(NULL) { }
3680
3681   // Each enum value states the cycle whose state is kept by this instance.
3682   enum LoopKind {
3683     NONE,
3684     SUCCESSORS,
3685     SUCCESSORS_OF_LOOP_HEADER,
3686     LOOP_MEMBERS,
3687     SUCCESSORS_OF_LOOP_MEMBER
3688   };
3689
3690   // Each "Setup..." method is like a constructor for a cycle state.
3691   PostorderProcessor* SetupSuccessors(Zone* zone,
3692                                       HBasicBlock* block,
3693                                       HBasicBlock* loop_header) {
3694     if (block == NULL || block->IsOrdered() ||
3695         block->parent_loop_header() != loop_header) {
3696       kind_ = NONE;
3697       block_ = NULL;
3698       loop_ = NULL;
3699       loop_header_ = NULL;
3700       return this;
3701     } else {
3702       block_ = block;
3703       loop_ = NULL;
3704       block->MarkAsOrdered();
3705
3706       if (block->IsLoopHeader()) {
3707         kind_ = SUCCESSORS_OF_LOOP_HEADER;
3708         loop_header_ = block;
3709         InitializeSuccessors();
3710         PostorderProcessor* result = Push(zone);
3711         return result->SetupLoopMembers(zone, block, block->loop_information(),
3712                                         loop_header);
3713       } else {
3714         DCHECK(block->IsFinished());
3715         kind_ = SUCCESSORS;
3716         loop_header_ = loop_header;
3717         InitializeSuccessors();
3718         return this;
3719       }
3720     }
3721   }
3722
3723   PostorderProcessor* SetupLoopMembers(Zone* zone,
3724                                        HBasicBlock* block,
3725                                        HLoopInformation* loop,
3726                                        HBasicBlock* loop_header) {
3727     kind_ = LOOP_MEMBERS;
3728     block_ = block;
3729     loop_ = loop;
3730     loop_header_ = loop_header;
3731     InitializeLoopMembers();
3732     return this;
3733   }
3734
3735   PostorderProcessor* SetupSuccessorsOfLoopMember(
3736       HBasicBlock* block,
3737       HLoopInformation* loop,
3738       HBasicBlock* loop_header) {
3739     kind_ = SUCCESSORS_OF_LOOP_MEMBER;
3740     block_ = block;
3741     loop_ = loop;
3742     loop_header_ = loop_header;
3743     InitializeSuccessors();
3744     return this;
3745   }
3746
3747   // This method "allocates" a new stack frame.
3748   PostorderProcessor* Push(Zone* zone) {
3749     if (child_ == NULL) {
3750       child_ = new(zone) PostorderProcessor(this);
3751     }
3752     return child_;
3753   }
3754
3755   void ClosePostorder(ZoneList<HBasicBlock*>* order, Zone* zone) {
3756     DCHECK(block_->end()->FirstSuccessor() == NULL ||
3757            order->Contains(block_->end()->FirstSuccessor()) ||
3758            block_->end()->FirstSuccessor()->IsLoopHeader());
3759     DCHECK(block_->end()->SecondSuccessor() == NULL ||
3760            order->Contains(block_->end()->SecondSuccessor()) ||
3761            block_->end()->SecondSuccessor()->IsLoopHeader());
3762     order->Add(block_, zone);
3763   }
3764
3765   // This method is the basic block to walk up the stack.
3766   PostorderProcessor* Pop(Zone* zone,
3767                           ZoneList<HBasicBlock*>* order) {
3768     switch (kind_) {
3769       case SUCCESSORS:
3770       case SUCCESSORS_OF_LOOP_HEADER:
3771         ClosePostorder(order, zone);
3772         return father_;
3773       case LOOP_MEMBERS:
3774         return father_;
3775       case SUCCESSORS_OF_LOOP_MEMBER:
3776         if (block()->IsLoopHeader() && block() != loop_->loop_header()) {
3777           // In this case we need to perform a LOOP_MEMBERS cycle so we
3778           // initialize it and return this instead of father.
3779           return SetupLoopMembers(zone, block(),
3780                                   block()->loop_information(), loop_header_);
3781         } else {
3782           return father_;
3783         }
3784       case NONE:
3785         return father_;
3786     }
3787     UNREACHABLE();
3788     return NULL;
3789   }
3790
3791   // Walks up the stack.
3792   PostorderProcessor* Backtrack(Zone* zone,
3793                                 ZoneList<HBasicBlock*>* order) {
3794     PostorderProcessor* parent = Pop(zone, order);
3795     while (parent != NULL) {
3796       PostorderProcessor* next =
3797           parent->PerformNonBacktrackingStep(zone, order);
3798       if (next != NULL) {
3799         return next;
3800       } else {
3801         parent = parent->Pop(zone, order);
3802       }
3803     }
3804     return NULL;
3805   }
3806
3807   PostorderProcessor* PerformNonBacktrackingStep(
3808       Zone* zone,
3809       ZoneList<HBasicBlock*>* order) {
3810     HBasicBlock* next_block;
3811     switch (kind_) {
3812       case SUCCESSORS:
3813         next_block = AdvanceSuccessors();
3814         if (next_block != NULL) {
3815           PostorderProcessor* result = Push(zone);
3816           return result->SetupSuccessors(zone, next_block, loop_header_);
3817         }
3818         break;
3819       case SUCCESSORS_OF_LOOP_HEADER:
3820         next_block = AdvanceSuccessors();
3821         if (next_block != NULL) {
3822           PostorderProcessor* result = Push(zone);
3823           return result->SetupSuccessors(zone, next_block, block());
3824         }
3825         break;
3826       case LOOP_MEMBERS:
3827         next_block = AdvanceLoopMembers();
3828         if (next_block != NULL) {
3829           PostorderProcessor* result = Push(zone);
3830           return result->SetupSuccessorsOfLoopMember(next_block,
3831                                                      loop_, loop_header_);
3832         }
3833         break;
3834       case SUCCESSORS_OF_LOOP_MEMBER:
3835         next_block = AdvanceSuccessors();
3836         if (next_block != NULL) {
3837           PostorderProcessor* result = Push(zone);
3838           return result->SetupSuccessors(zone, next_block, loop_header_);
3839         }
3840         break;
3841       case NONE:
3842         return NULL;
3843     }
3844     return NULL;
3845   }
3846
3847   // The following two methods implement a "foreach b in successors" cycle.
3848   void InitializeSuccessors() {
3849     loop_index = 0;
3850     loop_length = 0;
3851     successor_iterator = HSuccessorIterator(block_->end());
3852   }
3853
3854   HBasicBlock* AdvanceSuccessors() {
3855     if (!successor_iterator.Done()) {
3856       HBasicBlock* result = successor_iterator.Current();
3857       successor_iterator.Advance();
3858       return result;
3859     }
3860     return NULL;
3861   }
3862
3863   // The following two methods implement a "foreach b in loop members" cycle.
3864   void InitializeLoopMembers() {
3865     loop_index = 0;
3866     loop_length = loop_->blocks()->length();
3867   }
3868
3869   HBasicBlock* AdvanceLoopMembers() {
3870     if (loop_index < loop_length) {
3871       HBasicBlock* result = loop_->blocks()->at(loop_index);
3872       loop_index++;
3873       return result;
3874     } else {
3875       return NULL;
3876     }
3877   }
3878
3879   LoopKind kind_;
3880   PostorderProcessor* father_;
3881   PostorderProcessor* child_;
3882   HLoopInformation* loop_;
3883   HBasicBlock* block_;
3884   HBasicBlock* loop_header_;
3885   int loop_index;
3886   int loop_length;
3887   HSuccessorIterator successor_iterator;
3888 };
3889
3890
3891 void HGraph::OrderBlocks() {
3892   CompilationPhase phase("H_Block ordering", info());
3893
3894 #ifdef DEBUG
3895   // Initially the blocks must not be ordered.
3896   for (int i = 0; i < blocks_.length(); ++i) {
3897     DCHECK(!blocks_[i]->IsOrdered());
3898   }
3899 #endif
3900
3901   PostorderProcessor* postorder =
3902       PostorderProcessor::CreateEntryProcessor(zone(), blocks_[0]);
3903   blocks_.Rewind(0);
3904   while (postorder) {
3905     postorder = postorder->PerformStep(zone(), &blocks_);
3906   }
3907
3908 #ifdef DEBUG
3909   // Now all blocks must be marked as ordered.
3910   for (int i = 0; i < blocks_.length(); ++i) {
3911     DCHECK(blocks_[i]->IsOrdered());
3912   }
3913 #endif
3914
3915   // Reverse block list and assign block IDs.
3916   for (int i = 0, j = blocks_.length(); --j >= i; ++i) {
3917     HBasicBlock* bi = blocks_[i];
3918     HBasicBlock* bj = blocks_[j];
3919     bi->set_block_id(j);
3920     bj->set_block_id(i);
3921     blocks_[i] = bj;
3922     blocks_[j] = bi;
3923   }
3924 }
3925
3926
3927 void HGraph::AssignDominators() {
3928   HPhase phase("H_Assign dominators", this);
3929   for (int i = 0; i < blocks_.length(); ++i) {
3930     HBasicBlock* block = blocks_[i];
3931     if (block->IsLoopHeader()) {
3932       // Only the first predecessor of a loop header is from outside the loop.
3933       // All others are back edges, and thus cannot dominate the loop header.
3934       block->AssignCommonDominator(block->predecessors()->first());
3935       block->AssignLoopSuccessorDominators();
3936     } else {
3937       for (int j = blocks_[i]->predecessors()->length() - 1; j >= 0; --j) {
3938         blocks_[i]->AssignCommonDominator(blocks_[i]->predecessors()->at(j));
3939       }
3940     }
3941   }
3942 }
3943
3944
3945 bool HGraph::CheckArgumentsPhiUses() {
3946   int block_count = blocks_.length();
3947   for (int i = 0; i < block_count; ++i) {
3948     for (int j = 0; j < blocks_[i]->phis()->length(); ++j) {
3949       HPhi* phi = blocks_[i]->phis()->at(j);
3950       // We don't support phi uses of arguments for now.
3951       if (phi->CheckFlag(HValue::kIsArguments)) return false;
3952     }
3953   }
3954   return true;
3955 }
3956
3957
3958 bool HGraph::CheckConstPhiUses() {
3959   int block_count = blocks_.length();
3960   for (int i = 0; i < block_count; ++i) {
3961     for (int j = 0; j < blocks_[i]->phis()->length(); ++j) {
3962       HPhi* phi = blocks_[i]->phis()->at(j);
3963       // Check for the hole value (from an uninitialized const).
3964       for (int k = 0; k < phi->OperandCount(); k++) {
3965         if (phi->OperandAt(k) == GetConstantHole()) return false;
3966       }
3967     }
3968   }
3969   return true;
3970 }
3971
3972
3973 void HGraph::CollectPhis() {
3974   int block_count = blocks_.length();
3975   phi_list_ = new(zone()) ZoneList<HPhi*>(block_count, zone());
3976   for (int i = 0; i < block_count; ++i) {
3977     for (int j = 0; j < blocks_[i]->phis()->length(); ++j) {
3978       HPhi* phi = blocks_[i]->phis()->at(j);
3979       phi_list_->Add(phi, zone());
3980     }
3981   }
3982 }
3983
3984
3985 // Implementation of utility class to encapsulate the translation state for
3986 // a (possibly inlined) function.
3987 FunctionState::FunctionState(HOptimizedGraphBuilder* owner,
3988                              CompilationInfo* info, InliningKind inlining_kind,
3989                              int inlining_id)
3990     : owner_(owner),
3991       compilation_info_(info),
3992       call_context_(NULL),
3993       inlining_kind_(inlining_kind),
3994       function_return_(NULL),
3995       test_context_(NULL),
3996       entry_(NULL),
3997       arguments_object_(NULL),
3998       arguments_elements_(NULL),
3999       inlining_id_(inlining_id),
4000       outer_source_position_(SourcePosition::Unknown()),
4001       outer_(owner->function_state()) {
4002   if (outer_ != NULL) {
4003     // State for an inline function.
4004     if (owner->ast_context()->IsTest()) {
4005       HBasicBlock* if_true = owner->graph()->CreateBasicBlock();
4006       HBasicBlock* if_false = owner->graph()->CreateBasicBlock();
4007       if_true->MarkAsInlineReturnTarget(owner->current_block());
4008       if_false->MarkAsInlineReturnTarget(owner->current_block());
4009       TestContext* outer_test_context = TestContext::cast(owner->ast_context());
4010       Expression* cond = outer_test_context->condition();
4011       // The AstContext constructor pushed on the context stack.  This newed
4012       // instance is the reason that AstContext can't be BASE_EMBEDDED.
4013       test_context_ = new TestContext(owner, cond, if_true, if_false);
4014     } else {
4015       function_return_ = owner->graph()->CreateBasicBlock();
4016       function_return()->MarkAsInlineReturnTarget(owner->current_block());
4017     }
4018     // Set this after possibly allocating a new TestContext above.
4019     call_context_ = owner->ast_context();
4020   }
4021
4022   // Push on the state stack.
4023   owner->set_function_state(this);
4024
4025   if (compilation_info_->is_tracking_positions()) {
4026     outer_source_position_ = owner->source_position();
4027     owner->EnterInlinedSource(
4028       info->shared_info()->start_position(),
4029       inlining_id);
4030     owner->SetSourcePosition(info->shared_info()->start_position());
4031   }
4032 }
4033
4034
4035 FunctionState::~FunctionState() {
4036   delete test_context_;
4037   owner_->set_function_state(outer_);
4038
4039   if (compilation_info_->is_tracking_positions()) {
4040     owner_->set_source_position(outer_source_position_);
4041     owner_->EnterInlinedSource(
4042       outer_->compilation_info()->shared_info()->start_position(),
4043       outer_->inlining_id());
4044   }
4045 }
4046
4047
4048 // Implementation of utility classes to represent an expression's context in
4049 // the AST.
4050 AstContext::AstContext(HOptimizedGraphBuilder* owner, Expression::Context kind)
4051     : owner_(owner),
4052       kind_(kind),
4053       outer_(owner->ast_context()),
4054       typeof_mode_(NOT_INSIDE_TYPEOF) {
4055   owner->set_ast_context(this);  // Push.
4056 #ifdef DEBUG
4057   DCHECK(owner->environment()->frame_type() == JS_FUNCTION);
4058   original_length_ = owner->environment()->length();
4059 #endif
4060 }
4061
4062
4063 AstContext::~AstContext() {
4064   owner_->set_ast_context(outer_);  // Pop.
4065 }
4066
4067
4068 EffectContext::~EffectContext() {
4069   DCHECK(owner()->HasStackOverflow() ||
4070          owner()->current_block() == NULL ||
4071          (owner()->environment()->length() == original_length_ &&
4072           owner()->environment()->frame_type() == JS_FUNCTION));
4073 }
4074
4075
4076 ValueContext::~ValueContext() {
4077   DCHECK(owner()->HasStackOverflow() ||
4078          owner()->current_block() == NULL ||
4079          (owner()->environment()->length() == original_length_ + 1 &&
4080           owner()->environment()->frame_type() == JS_FUNCTION));
4081 }
4082
4083
4084 void EffectContext::ReturnValue(HValue* value) {
4085   // The value is simply ignored.
4086 }
4087
4088
4089 void ValueContext::ReturnValue(HValue* value) {
4090   // The value is tracked in the bailout environment, and communicated
4091   // through the environment as the result of the expression.
4092   if (value->CheckFlag(HValue::kIsArguments)) {
4093     if (flag_ == ARGUMENTS_FAKED) {
4094       value = owner()->graph()->GetConstantUndefined();
4095     } else if (!arguments_allowed()) {
4096       owner()->Bailout(kBadValueContextForArgumentsValue);
4097     }
4098   }
4099   owner()->Push(value);
4100 }
4101
4102
4103 void TestContext::ReturnValue(HValue* value) {
4104   BuildBranch(value);
4105 }
4106
4107
4108 void EffectContext::ReturnInstruction(HInstruction* instr, BailoutId ast_id) {
4109   DCHECK(!instr->IsControlInstruction());
4110   owner()->AddInstruction(instr);
4111   if (instr->HasObservableSideEffects()) {
4112     owner()->Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
4113   }
4114 }
4115
4116
4117 void EffectContext::ReturnControl(HControlInstruction* instr,
4118                                   BailoutId ast_id) {
4119   DCHECK(!instr->HasObservableSideEffects());
4120   HBasicBlock* empty_true = owner()->graph()->CreateBasicBlock();
4121   HBasicBlock* empty_false = owner()->graph()->CreateBasicBlock();
4122   instr->SetSuccessorAt(0, empty_true);
4123   instr->SetSuccessorAt(1, empty_false);
4124   owner()->FinishCurrentBlock(instr);
4125   HBasicBlock* join = owner()->CreateJoin(empty_true, empty_false, ast_id);
4126   owner()->set_current_block(join);
4127 }
4128
4129
4130 void EffectContext::ReturnContinuation(HIfContinuation* continuation,
4131                                        BailoutId ast_id) {
4132   HBasicBlock* true_branch = NULL;
4133   HBasicBlock* false_branch = NULL;
4134   continuation->Continue(&true_branch, &false_branch);
4135   if (!continuation->IsTrueReachable()) {
4136     owner()->set_current_block(false_branch);
4137   } else if (!continuation->IsFalseReachable()) {
4138     owner()->set_current_block(true_branch);
4139   } else {
4140     HBasicBlock* join = owner()->CreateJoin(true_branch, false_branch, ast_id);
4141     owner()->set_current_block(join);
4142   }
4143 }
4144
4145
4146 void ValueContext::ReturnInstruction(HInstruction* instr, BailoutId ast_id) {
4147   DCHECK(!instr->IsControlInstruction());
4148   if (!arguments_allowed() && instr->CheckFlag(HValue::kIsArguments)) {
4149     return owner()->Bailout(kBadValueContextForArgumentsObjectValue);
4150   }
4151   owner()->AddInstruction(instr);
4152   owner()->Push(instr);
4153   if (instr->HasObservableSideEffects()) {
4154     owner()->Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
4155   }
4156 }
4157
4158
4159 void ValueContext::ReturnControl(HControlInstruction* instr, BailoutId ast_id) {
4160   DCHECK(!instr->HasObservableSideEffects());
4161   if (!arguments_allowed() && instr->CheckFlag(HValue::kIsArguments)) {
4162     return owner()->Bailout(kBadValueContextForArgumentsObjectValue);
4163   }
4164   HBasicBlock* materialize_false = owner()->graph()->CreateBasicBlock();
4165   HBasicBlock* materialize_true = owner()->graph()->CreateBasicBlock();
4166   instr->SetSuccessorAt(0, materialize_true);
4167   instr->SetSuccessorAt(1, materialize_false);
4168   owner()->FinishCurrentBlock(instr);
4169   owner()->set_current_block(materialize_true);
4170   owner()->Push(owner()->graph()->GetConstantTrue());
4171   owner()->set_current_block(materialize_false);
4172   owner()->Push(owner()->graph()->GetConstantFalse());
4173   HBasicBlock* join =
4174     owner()->CreateJoin(materialize_true, materialize_false, ast_id);
4175   owner()->set_current_block(join);
4176 }
4177
4178
4179 void ValueContext::ReturnContinuation(HIfContinuation* continuation,
4180                                       BailoutId ast_id) {
4181   HBasicBlock* materialize_true = NULL;
4182   HBasicBlock* materialize_false = NULL;
4183   continuation->Continue(&materialize_true, &materialize_false);
4184   if (continuation->IsTrueReachable()) {
4185     owner()->set_current_block(materialize_true);
4186     owner()->Push(owner()->graph()->GetConstantTrue());
4187     owner()->set_current_block(materialize_true);
4188   }
4189   if (continuation->IsFalseReachable()) {
4190     owner()->set_current_block(materialize_false);
4191     owner()->Push(owner()->graph()->GetConstantFalse());
4192     owner()->set_current_block(materialize_false);
4193   }
4194   if (continuation->TrueAndFalseReachable()) {
4195     HBasicBlock* join =
4196         owner()->CreateJoin(materialize_true, materialize_false, ast_id);
4197     owner()->set_current_block(join);
4198   }
4199 }
4200
4201
4202 void TestContext::ReturnInstruction(HInstruction* instr, BailoutId ast_id) {
4203   DCHECK(!instr->IsControlInstruction());
4204   HOptimizedGraphBuilder* builder = owner();
4205   builder->AddInstruction(instr);
4206   // We expect a simulate after every expression with side effects, though
4207   // this one isn't actually needed (and wouldn't work if it were targeted).
4208   if (instr->HasObservableSideEffects()) {
4209     builder->Push(instr);
4210     builder->Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
4211     builder->Pop();
4212   }
4213   BuildBranch(instr);
4214 }
4215
4216
4217 void TestContext::ReturnControl(HControlInstruction* instr, BailoutId ast_id) {
4218   DCHECK(!instr->HasObservableSideEffects());
4219   HBasicBlock* empty_true = owner()->graph()->CreateBasicBlock();
4220   HBasicBlock* empty_false = owner()->graph()->CreateBasicBlock();
4221   instr->SetSuccessorAt(0, empty_true);
4222   instr->SetSuccessorAt(1, empty_false);
4223   owner()->FinishCurrentBlock(instr);
4224   owner()->Goto(empty_true, if_true(), owner()->function_state());
4225   owner()->Goto(empty_false, if_false(), owner()->function_state());
4226   owner()->set_current_block(NULL);
4227 }
4228
4229
4230 void TestContext::ReturnContinuation(HIfContinuation* continuation,
4231                                      BailoutId ast_id) {
4232   HBasicBlock* true_branch = NULL;
4233   HBasicBlock* false_branch = NULL;
4234   continuation->Continue(&true_branch, &false_branch);
4235   if (continuation->IsTrueReachable()) {
4236     owner()->Goto(true_branch, if_true(), owner()->function_state());
4237   }
4238   if (continuation->IsFalseReachable()) {
4239     owner()->Goto(false_branch, if_false(), owner()->function_state());
4240   }
4241   owner()->set_current_block(NULL);
4242 }
4243
4244
4245 void TestContext::BuildBranch(HValue* value) {
4246   // We expect the graph to be in edge-split form: there is no edge that
4247   // connects a branch node to a join node.  We conservatively ensure that
4248   // property by always adding an empty block on the outgoing edges of this
4249   // branch.
4250   HOptimizedGraphBuilder* builder = owner();
4251   if (value != NULL && value->CheckFlag(HValue::kIsArguments)) {
4252     builder->Bailout(kArgumentsObjectValueInATestContext);
4253   }
4254   ToBooleanStub::Types expected(condition()->to_boolean_types());
4255   ReturnControl(owner()->New<HBranch>(value, expected), BailoutId::None());
4256 }
4257
4258
4259 // HOptimizedGraphBuilder infrastructure for bailing out and checking bailouts.
4260 #define CHECK_BAILOUT(call)                     \
4261   do {                                          \
4262     call;                                       \
4263     if (HasStackOverflow()) return;             \
4264   } while (false)
4265
4266
4267 #define CHECK_ALIVE(call)                                       \
4268   do {                                                          \
4269     call;                                                       \
4270     if (HasStackOverflow() || current_block() == NULL) return;  \
4271   } while (false)
4272
4273
4274 #define CHECK_ALIVE_OR_RETURN(call, value)                            \
4275   do {                                                                \
4276     call;                                                             \
4277     if (HasStackOverflow() || current_block() == NULL) return value;  \
4278   } while (false)
4279
4280
4281 void HOptimizedGraphBuilder::Bailout(BailoutReason reason) {
4282   current_info()->AbortOptimization(reason);
4283   SetStackOverflow();
4284 }
4285
4286
4287 void HOptimizedGraphBuilder::VisitForEffect(Expression* expr) {
4288   EffectContext for_effect(this);
4289   Visit(expr);
4290 }
4291
4292
4293 void HOptimizedGraphBuilder::VisitForValue(Expression* expr,
4294                                            ArgumentsAllowedFlag flag) {
4295   ValueContext for_value(this, flag);
4296   Visit(expr);
4297 }
4298
4299
4300 void HOptimizedGraphBuilder::VisitForTypeOf(Expression* expr) {
4301   ValueContext for_value(this, ARGUMENTS_NOT_ALLOWED);
4302   for_value.set_typeof_mode(INSIDE_TYPEOF);
4303   Visit(expr);
4304 }
4305
4306
4307 void HOptimizedGraphBuilder::VisitForControl(Expression* expr,
4308                                              HBasicBlock* true_block,
4309                                              HBasicBlock* false_block) {
4310   TestContext for_test(this, expr, true_block, false_block);
4311   Visit(expr);
4312 }
4313
4314
4315 void HOptimizedGraphBuilder::VisitExpressions(
4316     ZoneList<Expression*>* exprs) {
4317   for (int i = 0; i < exprs->length(); ++i) {
4318     CHECK_ALIVE(VisitForValue(exprs->at(i)));
4319   }
4320 }
4321
4322
4323 void HOptimizedGraphBuilder::VisitExpressions(ZoneList<Expression*>* exprs,
4324                                               ArgumentsAllowedFlag flag) {
4325   for (int i = 0; i < exprs->length(); ++i) {
4326     CHECK_ALIVE(VisitForValue(exprs->at(i), flag));
4327   }
4328 }
4329
4330
4331 bool HOptimizedGraphBuilder::BuildGraph() {
4332   if (IsSubclassConstructor(current_info()->function()->kind())) {
4333     Bailout(kSuperReference);
4334     return false;
4335   }
4336
4337   int slots = current_info()->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
4338   if (current_info()->scope()->is_script_scope() && slots > 0) {
4339     Bailout(kScriptContext);
4340     return false;
4341   }
4342
4343   Scope* scope = current_info()->scope();
4344   SetUpScope(scope);
4345
4346   // Add an edge to the body entry.  This is warty: the graph's start
4347   // environment will be used by the Lithium translation as the initial
4348   // environment on graph entry, but it has now been mutated by the
4349   // Hydrogen translation of the instructions in the start block.  This
4350   // environment uses values which have not been defined yet.  These
4351   // Hydrogen instructions will then be replayed by the Lithium
4352   // translation, so they cannot have an environment effect.  The edge to
4353   // the body's entry block (along with some special logic for the start
4354   // block in HInstruction::InsertAfter) seals the start block from
4355   // getting unwanted instructions inserted.
4356   //
4357   // TODO(kmillikin): Fix this.  Stop mutating the initial environment.
4358   // Make the Hydrogen instructions in the initial block into Hydrogen
4359   // values (but not instructions), present in the initial environment and
4360   // not replayed by the Lithium translation.
4361   HEnvironment* initial_env = environment()->CopyWithoutHistory();
4362   HBasicBlock* body_entry = CreateBasicBlock(initial_env);
4363   Goto(body_entry);
4364   body_entry->SetJoinId(BailoutId::FunctionEntry());
4365   set_current_block(body_entry);
4366
4367   VisitDeclarations(scope->declarations());
4368   Add<HSimulate>(BailoutId::Declarations());
4369
4370   Add<HStackCheck>(HStackCheck::kFunctionEntry);
4371
4372   VisitStatements(current_info()->function()->body());
4373   if (HasStackOverflow()) return false;
4374
4375   if (current_block() != NULL) {
4376     Add<HReturn>(graph()->GetConstantUndefined());
4377     set_current_block(NULL);
4378   }
4379
4380   // If the checksum of the number of type info changes is the same as the
4381   // last time this function was compiled, then this recompile is likely not
4382   // due to missing/inadequate type feedback, but rather too aggressive
4383   // optimization. Disable optimistic LICM in that case.
4384   Handle<Code> unoptimized_code(current_info()->shared_info()->code());
4385   DCHECK(unoptimized_code->kind() == Code::FUNCTION);
4386   Handle<TypeFeedbackInfo> type_info(
4387       TypeFeedbackInfo::cast(unoptimized_code->type_feedback_info()));
4388   int checksum = type_info->own_type_change_checksum();
4389   int composite_checksum = graph()->update_type_change_checksum(checksum);
4390   graph()->set_use_optimistic_licm(
4391       !type_info->matches_inlined_type_change_checksum(composite_checksum));
4392   type_info->set_inlined_type_change_checksum(composite_checksum);
4393
4394   // Perform any necessary OSR-specific cleanups or changes to the graph.
4395   osr()->FinishGraph();
4396
4397   return true;
4398 }
4399
4400
4401 bool HGraph::Optimize(BailoutReason* bailout_reason) {
4402   OrderBlocks();
4403   AssignDominators();
4404
4405   // We need to create a HConstant "zero" now so that GVN will fold every
4406   // zero-valued constant in the graph together.
4407   // The constant is needed to make idef-based bounds check work: the pass
4408   // evaluates relations with "zero" and that zero cannot be created after GVN.
4409   GetConstant0();
4410
4411 #ifdef DEBUG
4412   // Do a full verify after building the graph and computing dominators.
4413   Verify(true);
4414 #endif
4415
4416   if (FLAG_analyze_environment_liveness && maximum_environment_size() != 0) {
4417     Run<HEnvironmentLivenessAnalysisPhase>();
4418   }
4419
4420   if (!CheckConstPhiUses()) {
4421     *bailout_reason = kUnsupportedPhiUseOfConstVariable;
4422     return false;
4423   }
4424   Run<HRedundantPhiEliminationPhase>();
4425   if (!CheckArgumentsPhiUses()) {
4426     *bailout_reason = kUnsupportedPhiUseOfArguments;
4427     return false;
4428   }
4429
4430   // Find and mark unreachable code to simplify optimizations, especially gvn,
4431   // where unreachable code could unnecessarily defeat LICM.
4432   Run<HMarkUnreachableBlocksPhase>();
4433
4434   if (FLAG_dead_code_elimination) Run<HDeadCodeEliminationPhase>();
4435   if (FLAG_use_escape_analysis) Run<HEscapeAnalysisPhase>();
4436
4437   if (FLAG_load_elimination) Run<HLoadEliminationPhase>();
4438
4439   CollectPhis();
4440
4441   if (has_osr()) osr()->FinishOsrValues();
4442
4443   Run<HInferRepresentationPhase>();
4444
4445   // Remove HSimulate instructions that have turned out not to be needed
4446   // after all by folding them into the following HSimulate.
4447   // This must happen after inferring representations.
4448   Run<HMergeRemovableSimulatesPhase>();
4449
4450   Run<HMarkDeoptimizeOnUndefinedPhase>();
4451   Run<HRepresentationChangesPhase>();
4452
4453   Run<HInferTypesPhase>();
4454
4455   // Must be performed before canonicalization to ensure that Canonicalize
4456   // will not remove semantically meaningful ToInt32 operations e.g. BIT_OR with
4457   // zero.
4458   Run<HUint32AnalysisPhase>();
4459
4460   if (FLAG_use_canonicalizing) Run<HCanonicalizePhase>();
4461
4462   if (FLAG_use_gvn) Run<HGlobalValueNumberingPhase>();
4463
4464   if (FLAG_check_elimination) Run<HCheckEliminationPhase>();
4465
4466   if (FLAG_store_elimination) Run<HStoreEliminationPhase>();
4467
4468   Run<HRangeAnalysisPhase>();
4469
4470   Run<HComputeChangeUndefinedToNaN>();
4471
4472   // Eliminate redundant stack checks on backwards branches.
4473   Run<HStackCheckEliminationPhase>();
4474
4475   if (FLAG_array_bounds_checks_elimination) Run<HBoundsCheckEliminationPhase>();
4476   if (FLAG_array_bounds_checks_hoisting) Run<HBoundsCheckHoistingPhase>();
4477   if (FLAG_array_index_dehoisting) Run<HDehoistIndexComputationsPhase>();
4478   if (FLAG_dead_code_elimination) Run<HDeadCodeEliminationPhase>();
4479
4480   RestoreActualValues();
4481
4482   // Find unreachable code a second time, GVN and other optimizations may have
4483   // made blocks unreachable that were previously reachable.
4484   Run<HMarkUnreachableBlocksPhase>();
4485
4486   return true;
4487 }
4488
4489
4490 void HGraph::RestoreActualValues() {
4491   HPhase phase("H_Restore actual values", this);
4492
4493   for (int block_index = 0; block_index < blocks()->length(); block_index++) {
4494     HBasicBlock* block = blocks()->at(block_index);
4495
4496 #ifdef DEBUG
4497     for (int i = 0; i < block->phis()->length(); i++) {
4498       HPhi* phi = block->phis()->at(i);
4499       DCHECK(phi->ActualValue() == phi);
4500     }
4501 #endif
4502
4503     for (HInstructionIterator it(block); !it.Done(); it.Advance()) {
4504       HInstruction* instruction = it.Current();
4505       if (instruction->ActualValue() == instruction) continue;
4506       if (instruction->CheckFlag(HValue::kIsDead)) {
4507         // The instruction was marked as deleted but left in the graph
4508         // as a control flow dependency point for subsequent
4509         // instructions.
4510         instruction->DeleteAndReplaceWith(instruction->ActualValue());
4511       } else {
4512         DCHECK(instruction->IsInformativeDefinition());
4513         if (instruction->IsPurelyInformativeDefinition()) {
4514           instruction->DeleteAndReplaceWith(instruction->RedefinedOperand());
4515         } else {
4516           instruction->ReplaceAllUsesWith(instruction->ActualValue());
4517         }
4518       }
4519     }
4520   }
4521 }
4522
4523
4524 void HOptimizedGraphBuilder::PushArgumentsFromEnvironment(int count) {
4525   ZoneList<HValue*> arguments(count, zone());
4526   for (int i = 0; i < count; ++i) {
4527     arguments.Add(Pop(), zone());
4528   }
4529
4530   HPushArguments* push_args = New<HPushArguments>();
4531   while (!arguments.is_empty()) {
4532     push_args->AddInput(arguments.RemoveLast());
4533   }
4534   AddInstruction(push_args);
4535 }
4536
4537
4538 template <class Instruction>
4539 HInstruction* HOptimizedGraphBuilder::PreProcessCall(Instruction* call) {
4540   PushArgumentsFromEnvironment(call->argument_count());
4541   return call;
4542 }
4543
4544
4545 void HOptimizedGraphBuilder::SetUpScope(Scope* scope) {
4546   // First special is HContext.
4547   HInstruction* context = Add<HContext>();
4548   environment()->BindContext(context);
4549
4550   // Create an arguments object containing the initial parameters.  Set the
4551   // initial values of parameters including "this" having parameter index 0.
4552   DCHECK_EQ(scope->num_parameters() + 1, environment()->parameter_count());
4553   HArgumentsObject* arguments_object =
4554       New<HArgumentsObject>(environment()->parameter_count());
4555   for (int i = 0; i < environment()->parameter_count(); ++i) {
4556     HInstruction* parameter = Add<HParameter>(i);
4557     arguments_object->AddArgument(parameter, zone());
4558     environment()->Bind(i, parameter);
4559   }
4560   AddInstruction(arguments_object);
4561   graph()->SetArgumentsObject(arguments_object);
4562
4563   HConstant* undefined_constant = graph()->GetConstantUndefined();
4564   // Initialize specials and locals to undefined.
4565   for (int i = environment()->parameter_count() + 1;
4566        i < environment()->length();
4567        ++i) {
4568     environment()->Bind(i, undefined_constant);
4569   }
4570
4571   // Handle the arguments and arguments shadow variables specially (they do
4572   // not have declarations).
4573   if (scope->arguments() != NULL) {
4574     environment()->Bind(scope->arguments(),
4575                         graph()->GetArgumentsObject());
4576   }
4577
4578   int rest_index;
4579   Variable* rest = scope->rest_parameter(&rest_index);
4580   if (rest) {
4581     return Bailout(kRestParameter);
4582   }
4583
4584   if (scope->this_function_var() != nullptr ||
4585       scope->new_target_var() != nullptr) {
4586     return Bailout(kSuperReference);
4587   }
4588 }
4589
4590
4591 void HOptimizedGraphBuilder::VisitStatements(ZoneList<Statement*>* statements) {
4592   for (int i = 0; i < statements->length(); i++) {
4593     Statement* stmt = statements->at(i);
4594     CHECK_ALIVE(Visit(stmt));
4595     if (stmt->IsJump()) break;
4596   }
4597 }
4598
4599
4600 void HOptimizedGraphBuilder::VisitBlock(Block* stmt) {
4601   DCHECK(!HasStackOverflow());
4602   DCHECK(current_block() != NULL);
4603   DCHECK(current_block()->HasPredecessor());
4604
4605   Scope* outer_scope = scope();
4606   Scope* scope = stmt->scope();
4607   BreakAndContinueInfo break_info(stmt, outer_scope);
4608
4609   { BreakAndContinueScope push(&break_info, this);
4610     if (scope != NULL) {
4611       if (scope->ContextLocalCount() > 0) {
4612         // Load the function object.
4613         Scope* declaration_scope = scope->DeclarationScope();
4614         HInstruction* function;
4615         HValue* outer_context = environment()->context();
4616         if (declaration_scope->is_script_scope() ||
4617             declaration_scope->is_eval_scope()) {
4618           function = new (zone())
4619               HLoadContextSlot(outer_context, Context::CLOSURE_INDEX,
4620                                HLoadContextSlot::kNoCheck);
4621         } else {
4622           function = New<HThisFunction>();
4623         }
4624         AddInstruction(function);
4625         // Allocate a block context and store it to the stack frame.
4626         HInstruction* inner_context = Add<HAllocateBlockContext>(
4627             outer_context, function, scope->GetScopeInfo(isolate()));
4628         HInstruction* instr = Add<HStoreFrameContext>(inner_context);
4629         set_scope(scope);
4630         environment()->BindContext(inner_context);
4631         if (instr->HasObservableSideEffects()) {
4632           AddSimulate(stmt->EntryId(), REMOVABLE_SIMULATE);
4633         }
4634       }
4635       VisitDeclarations(scope->declarations());
4636       AddSimulate(stmt->DeclsId(), REMOVABLE_SIMULATE);
4637     }
4638     CHECK_BAILOUT(VisitStatements(stmt->statements()));
4639   }
4640   set_scope(outer_scope);
4641   if (scope != NULL && current_block() != NULL &&
4642       scope->ContextLocalCount() > 0) {
4643     HValue* inner_context = environment()->context();
4644     HValue* outer_context = Add<HLoadNamedField>(
4645         inner_context, nullptr,
4646         HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX));
4647
4648     HInstruction* instr = Add<HStoreFrameContext>(outer_context);
4649     environment()->BindContext(outer_context);
4650     if (instr->HasObservableSideEffects()) {
4651       AddSimulate(stmt->ExitId(), REMOVABLE_SIMULATE);
4652     }
4653   }
4654   HBasicBlock* break_block = break_info.break_block();
4655   if (break_block != NULL) {
4656     if (current_block() != NULL) Goto(break_block);
4657     break_block->SetJoinId(stmt->ExitId());
4658     set_current_block(break_block);
4659   }
4660 }
4661
4662
4663 void HOptimizedGraphBuilder::VisitExpressionStatement(
4664     ExpressionStatement* stmt) {
4665   DCHECK(!HasStackOverflow());
4666   DCHECK(current_block() != NULL);
4667   DCHECK(current_block()->HasPredecessor());
4668   VisitForEffect(stmt->expression());
4669 }
4670
4671
4672 void HOptimizedGraphBuilder::VisitEmptyStatement(EmptyStatement* stmt) {
4673   DCHECK(!HasStackOverflow());
4674   DCHECK(current_block() != NULL);
4675   DCHECK(current_block()->HasPredecessor());
4676 }
4677
4678
4679 void HOptimizedGraphBuilder::VisitIfStatement(IfStatement* stmt) {
4680   DCHECK(!HasStackOverflow());
4681   DCHECK(current_block() != NULL);
4682   DCHECK(current_block()->HasPredecessor());
4683   if (stmt->condition()->ToBooleanIsTrue()) {
4684     Add<HSimulate>(stmt->ThenId());
4685     Visit(stmt->then_statement());
4686   } else if (stmt->condition()->ToBooleanIsFalse()) {
4687     Add<HSimulate>(stmt->ElseId());
4688     Visit(stmt->else_statement());
4689   } else {
4690     HBasicBlock* cond_true = graph()->CreateBasicBlock();
4691     HBasicBlock* cond_false = graph()->CreateBasicBlock();
4692     CHECK_BAILOUT(VisitForControl(stmt->condition(), cond_true, cond_false));
4693
4694     if (cond_true->HasPredecessor()) {
4695       cond_true->SetJoinId(stmt->ThenId());
4696       set_current_block(cond_true);
4697       CHECK_BAILOUT(Visit(stmt->then_statement()));
4698       cond_true = current_block();
4699     } else {
4700       cond_true = NULL;
4701     }
4702
4703     if (cond_false->HasPredecessor()) {
4704       cond_false->SetJoinId(stmt->ElseId());
4705       set_current_block(cond_false);
4706       CHECK_BAILOUT(Visit(stmt->else_statement()));
4707       cond_false = current_block();
4708     } else {
4709       cond_false = NULL;
4710     }
4711
4712     HBasicBlock* join = CreateJoin(cond_true, cond_false, stmt->IfId());
4713     set_current_block(join);
4714   }
4715 }
4716
4717
4718 HBasicBlock* HOptimizedGraphBuilder::BreakAndContinueScope::Get(
4719     BreakableStatement* stmt,
4720     BreakType type,
4721     Scope** scope,
4722     int* drop_extra) {
4723   *drop_extra = 0;
4724   BreakAndContinueScope* current = this;
4725   while (current != NULL && current->info()->target() != stmt) {
4726     *drop_extra += current->info()->drop_extra();
4727     current = current->next();
4728   }
4729   DCHECK(current != NULL);  // Always found (unless stack is malformed).
4730   *scope = current->info()->scope();
4731
4732   if (type == BREAK) {
4733     *drop_extra += current->info()->drop_extra();
4734   }
4735
4736   HBasicBlock* block = NULL;
4737   switch (type) {
4738     case BREAK:
4739       block = current->info()->break_block();
4740       if (block == NULL) {
4741         block = current->owner()->graph()->CreateBasicBlock();
4742         current->info()->set_break_block(block);
4743       }
4744       break;
4745
4746     case CONTINUE:
4747       block = current->info()->continue_block();
4748       if (block == NULL) {
4749         block = current->owner()->graph()->CreateBasicBlock();
4750         current->info()->set_continue_block(block);
4751       }
4752       break;
4753   }
4754
4755   return block;
4756 }
4757
4758
4759 void HOptimizedGraphBuilder::VisitContinueStatement(
4760     ContinueStatement* stmt) {
4761   DCHECK(!HasStackOverflow());
4762   DCHECK(current_block() != NULL);
4763   DCHECK(current_block()->HasPredecessor());
4764   Scope* outer_scope = NULL;
4765   Scope* inner_scope = scope();
4766   int drop_extra = 0;
4767   HBasicBlock* continue_block = break_scope()->Get(
4768       stmt->target(), BreakAndContinueScope::CONTINUE,
4769       &outer_scope, &drop_extra);
4770   HValue* context = environment()->context();
4771   Drop(drop_extra);
4772   int context_pop_count = inner_scope->ContextChainLength(outer_scope);
4773   if (context_pop_count > 0) {
4774     while (context_pop_count-- > 0) {
4775       HInstruction* context_instruction = Add<HLoadNamedField>(
4776           context, nullptr,
4777           HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX));
4778       context = context_instruction;
4779     }
4780     HInstruction* instr = Add<HStoreFrameContext>(context);
4781     if (instr->HasObservableSideEffects()) {
4782       AddSimulate(stmt->target()->EntryId(), REMOVABLE_SIMULATE);
4783     }
4784     environment()->BindContext(context);
4785   }
4786
4787   Goto(continue_block);
4788   set_current_block(NULL);
4789 }
4790
4791
4792 void HOptimizedGraphBuilder::VisitBreakStatement(BreakStatement* stmt) {
4793   DCHECK(!HasStackOverflow());
4794   DCHECK(current_block() != NULL);
4795   DCHECK(current_block()->HasPredecessor());
4796   Scope* outer_scope = NULL;
4797   Scope* inner_scope = scope();
4798   int drop_extra = 0;
4799   HBasicBlock* break_block = break_scope()->Get(
4800       stmt->target(), BreakAndContinueScope::BREAK,
4801       &outer_scope, &drop_extra);
4802   HValue* context = environment()->context();
4803   Drop(drop_extra);
4804   int context_pop_count = inner_scope->ContextChainLength(outer_scope);
4805   if (context_pop_count > 0) {
4806     while (context_pop_count-- > 0) {
4807       HInstruction* context_instruction = Add<HLoadNamedField>(
4808           context, nullptr,
4809           HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX));
4810       context = context_instruction;
4811     }
4812     HInstruction* instr = Add<HStoreFrameContext>(context);
4813     if (instr->HasObservableSideEffects()) {
4814       AddSimulate(stmt->target()->ExitId(), REMOVABLE_SIMULATE);
4815     }
4816     environment()->BindContext(context);
4817   }
4818   Goto(break_block);
4819   set_current_block(NULL);
4820 }
4821
4822
4823 void HOptimizedGraphBuilder::VisitReturnStatement(ReturnStatement* stmt) {
4824   DCHECK(!HasStackOverflow());
4825   DCHECK(current_block() != NULL);
4826   DCHECK(current_block()->HasPredecessor());
4827   FunctionState* state = function_state();
4828   AstContext* context = call_context();
4829   if (context == NULL) {
4830     // Not an inlined return, so an actual one.
4831     CHECK_ALIVE(VisitForValue(stmt->expression()));
4832     HValue* result = environment()->Pop();
4833     Add<HReturn>(result);
4834   } else if (state->inlining_kind() == CONSTRUCT_CALL_RETURN) {
4835     // Return from an inlined construct call. In a test context the return value
4836     // will always evaluate to true, in a value context the return value needs
4837     // to be a JSObject.
4838     if (context->IsTest()) {
4839       TestContext* test = TestContext::cast(context);
4840       CHECK_ALIVE(VisitForEffect(stmt->expression()));
4841       Goto(test->if_true(), state);
4842     } else if (context->IsEffect()) {
4843       CHECK_ALIVE(VisitForEffect(stmt->expression()));
4844       Goto(function_return(), state);
4845     } else {
4846       DCHECK(context->IsValue());
4847       CHECK_ALIVE(VisitForValue(stmt->expression()));
4848       HValue* return_value = Pop();
4849       HValue* receiver = environment()->arguments_environment()->Lookup(0);
4850       HHasInstanceTypeAndBranch* typecheck =
4851           New<HHasInstanceTypeAndBranch>(return_value,
4852                                          FIRST_SPEC_OBJECT_TYPE,
4853                                          LAST_SPEC_OBJECT_TYPE);
4854       HBasicBlock* if_spec_object = graph()->CreateBasicBlock();
4855       HBasicBlock* not_spec_object = graph()->CreateBasicBlock();
4856       typecheck->SetSuccessorAt(0, if_spec_object);
4857       typecheck->SetSuccessorAt(1, not_spec_object);
4858       FinishCurrentBlock(typecheck);
4859       AddLeaveInlined(if_spec_object, return_value, state);
4860       AddLeaveInlined(not_spec_object, receiver, state);
4861     }
4862   } else if (state->inlining_kind() == SETTER_CALL_RETURN) {
4863     // Return from an inlined setter call. The returned value is never used, the
4864     // value of an assignment is always the value of the RHS of the assignment.
4865     CHECK_ALIVE(VisitForEffect(stmt->expression()));
4866     if (context->IsTest()) {
4867       HValue* rhs = environment()->arguments_environment()->Lookup(1);
4868       context->ReturnValue(rhs);
4869     } else if (context->IsEffect()) {
4870       Goto(function_return(), state);
4871     } else {
4872       DCHECK(context->IsValue());
4873       HValue* rhs = environment()->arguments_environment()->Lookup(1);
4874       AddLeaveInlined(rhs, state);
4875     }
4876   } else {
4877     // Return from a normal inlined function. Visit the subexpression in the
4878     // expression context of the call.
4879     if (context->IsTest()) {
4880       TestContext* test = TestContext::cast(context);
4881       VisitForControl(stmt->expression(), test->if_true(), test->if_false());
4882     } else if (context->IsEffect()) {
4883       // Visit in value context and ignore the result. This is needed to keep
4884       // environment in sync with full-codegen since some visitors (e.g.
4885       // VisitCountOperation) use the operand stack differently depending on
4886       // context.
4887       CHECK_ALIVE(VisitForValue(stmt->expression()));
4888       Pop();
4889       Goto(function_return(), state);
4890     } else {
4891       DCHECK(context->IsValue());
4892       CHECK_ALIVE(VisitForValue(stmt->expression()));
4893       AddLeaveInlined(Pop(), state);
4894     }
4895   }
4896   set_current_block(NULL);
4897 }
4898
4899
4900 void HOptimizedGraphBuilder::VisitWithStatement(WithStatement* stmt) {
4901   DCHECK(!HasStackOverflow());
4902   DCHECK(current_block() != NULL);
4903   DCHECK(current_block()->HasPredecessor());
4904   return Bailout(kWithStatement);
4905 }
4906
4907
4908 void HOptimizedGraphBuilder::VisitSwitchStatement(SwitchStatement* stmt) {
4909   DCHECK(!HasStackOverflow());
4910   DCHECK(current_block() != NULL);
4911   DCHECK(current_block()->HasPredecessor());
4912
4913   ZoneList<CaseClause*>* clauses = stmt->cases();
4914   int clause_count = clauses->length();
4915   ZoneList<HBasicBlock*> body_blocks(clause_count, zone());
4916
4917   CHECK_ALIVE(VisitForValue(stmt->tag()));
4918   Add<HSimulate>(stmt->EntryId());
4919   HValue* tag_value = Top();
4920   Type* tag_type = stmt->tag()->bounds().lower;
4921
4922   // 1. Build all the tests, with dangling true branches
4923   BailoutId default_id = BailoutId::None();
4924   for (int i = 0; i < clause_count; ++i) {
4925     CaseClause* clause = clauses->at(i);
4926     if (clause->is_default()) {
4927       body_blocks.Add(NULL, zone());
4928       if (default_id.IsNone()) default_id = clause->EntryId();
4929       continue;
4930     }
4931
4932     // Generate a compare and branch.
4933     CHECK_ALIVE(VisitForValue(clause->label()));
4934     HValue* label_value = Pop();
4935
4936     Type* label_type = clause->label()->bounds().lower;
4937     Type* combined_type = clause->compare_type();
4938     HControlInstruction* compare = BuildCompareInstruction(
4939         Token::EQ_STRICT, tag_value, label_value, tag_type, label_type,
4940         combined_type,
4941         ScriptPositionToSourcePosition(stmt->tag()->position()),
4942         ScriptPositionToSourcePosition(clause->label()->position()),
4943         PUSH_BEFORE_SIMULATE, clause->id());
4944
4945     HBasicBlock* next_test_block = graph()->CreateBasicBlock();
4946     HBasicBlock* body_block = graph()->CreateBasicBlock();
4947     body_blocks.Add(body_block, zone());
4948     compare->SetSuccessorAt(0, body_block);
4949     compare->SetSuccessorAt(1, next_test_block);
4950     FinishCurrentBlock(compare);
4951
4952     set_current_block(body_block);
4953     Drop(1);  // tag_value
4954
4955     set_current_block(next_test_block);
4956   }
4957
4958   // Save the current block to use for the default or to join with the
4959   // exit.
4960   HBasicBlock* last_block = current_block();
4961   Drop(1);  // tag_value
4962
4963   // 2. Loop over the clauses and the linked list of tests in lockstep,
4964   // translating the clause bodies.
4965   HBasicBlock* fall_through_block = NULL;
4966
4967   BreakAndContinueInfo break_info(stmt, scope());
4968   { BreakAndContinueScope push(&break_info, this);
4969     for (int i = 0; i < clause_count; ++i) {
4970       CaseClause* clause = clauses->at(i);
4971
4972       // Identify the block where normal (non-fall-through) control flow
4973       // goes to.
4974       HBasicBlock* normal_block = NULL;
4975       if (clause->is_default()) {
4976         if (last_block == NULL) continue;
4977         normal_block = last_block;
4978         last_block = NULL;  // Cleared to indicate we've handled it.
4979       } else {
4980         normal_block = body_blocks[i];
4981       }
4982
4983       if (fall_through_block == NULL) {
4984         set_current_block(normal_block);
4985       } else {
4986         HBasicBlock* join = CreateJoin(fall_through_block,
4987                                        normal_block,
4988                                        clause->EntryId());
4989         set_current_block(join);
4990       }
4991
4992       CHECK_BAILOUT(VisitStatements(clause->statements()));
4993       fall_through_block = current_block();
4994     }
4995   }
4996
4997   // Create an up-to-3-way join.  Use the break block if it exists since
4998   // it's already a join block.
4999   HBasicBlock* break_block = break_info.break_block();
5000   if (break_block == NULL) {
5001     set_current_block(CreateJoin(fall_through_block,
5002                                  last_block,
5003                                  stmt->ExitId()));
5004   } else {
5005     if (fall_through_block != NULL) Goto(fall_through_block, break_block);
5006     if (last_block != NULL) Goto(last_block, break_block);
5007     break_block->SetJoinId(stmt->ExitId());
5008     set_current_block(break_block);
5009   }
5010 }
5011
5012
5013 void HOptimizedGraphBuilder::VisitLoopBody(IterationStatement* stmt,
5014                                            HBasicBlock* loop_entry) {
5015   Add<HSimulate>(stmt->StackCheckId());
5016   HStackCheck* stack_check =
5017       HStackCheck::cast(Add<HStackCheck>(HStackCheck::kBackwardsBranch));
5018   DCHECK(loop_entry->IsLoopHeader());
5019   loop_entry->loop_information()->set_stack_check(stack_check);
5020   CHECK_BAILOUT(Visit(stmt->body()));
5021 }
5022
5023
5024 void HOptimizedGraphBuilder::VisitDoWhileStatement(DoWhileStatement* stmt) {
5025   DCHECK(!HasStackOverflow());
5026   DCHECK(current_block() != NULL);
5027   DCHECK(current_block()->HasPredecessor());
5028   DCHECK(current_block() != NULL);
5029   HBasicBlock* loop_entry = BuildLoopEntry(stmt);
5030
5031   BreakAndContinueInfo break_info(stmt, scope());
5032   {
5033     BreakAndContinueScope push(&break_info, this);
5034     CHECK_BAILOUT(VisitLoopBody(stmt, loop_entry));
5035   }
5036   HBasicBlock* body_exit =
5037       JoinContinue(stmt, current_block(), break_info.continue_block());
5038   HBasicBlock* loop_successor = NULL;
5039   if (body_exit != NULL && !stmt->cond()->ToBooleanIsTrue()) {
5040     set_current_block(body_exit);
5041     loop_successor = graph()->CreateBasicBlock();
5042     if (stmt->cond()->ToBooleanIsFalse()) {
5043       loop_entry->loop_information()->stack_check()->Eliminate();
5044       Goto(loop_successor);
5045       body_exit = NULL;
5046     } else {
5047       // The block for a true condition, the actual predecessor block of the
5048       // back edge.
5049       body_exit = graph()->CreateBasicBlock();
5050       CHECK_BAILOUT(VisitForControl(stmt->cond(), body_exit, loop_successor));
5051     }
5052     if (body_exit != NULL && body_exit->HasPredecessor()) {
5053       body_exit->SetJoinId(stmt->BackEdgeId());
5054     } else {
5055       body_exit = NULL;
5056     }
5057     if (loop_successor->HasPredecessor()) {
5058       loop_successor->SetJoinId(stmt->ExitId());
5059     } else {
5060       loop_successor = NULL;
5061     }
5062   }
5063   HBasicBlock* loop_exit = CreateLoop(stmt,
5064                                       loop_entry,
5065                                       body_exit,
5066                                       loop_successor,
5067                                       break_info.break_block());
5068   set_current_block(loop_exit);
5069 }
5070
5071
5072 void HOptimizedGraphBuilder::VisitWhileStatement(WhileStatement* stmt) {
5073   DCHECK(!HasStackOverflow());
5074   DCHECK(current_block() != NULL);
5075   DCHECK(current_block()->HasPredecessor());
5076   DCHECK(current_block() != NULL);
5077   HBasicBlock* loop_entry = BuildLoopEntry(stmt);
5078
5079   // If the condition is constant true, do not generate a branch.
5080   HBasicBlock* loop_successor = NULL;
5081   if (!stmt->cond()->ToBooleanIsTrue()) {
5082     HBasicBlock* body_entry = graph()->CreateBasicBlock();
5083     loop_successor = graph()->CreateBasicBlock();
5084     CHECK_BAILOUT(VisitForControl(stmt->cond(), body_entry, loop_successor));
5085     if (body_entry->HasPredecessor()) {
5086       body_entry->SetJoinId(stmt->BodyId());
5087       set_current_block(body_entry);
5088     }
5089     if (loop_successor->HasPredecessor()) {
5090       loop_successor->SetJoinId(stmt->ExitId());
5091     } else {
5092       loop_successor = NULL;
5093     }
5094   }
5095
5096   BreakAndContinueInfo break_info(stmt, scope());
5097   if (current_block() != NULL) {
5098     BreakAndContinueScope push(&break_info, this);
5099     CHECK_BAILOUT(VisitLoopBody(stmt, loop_entry));
5100   }
5101   HBasicBlock* body_exit =
5102       JoinContinue(stmt, current_block(), break_info.continue_block());
5103   HBasicBlock* loop_exit = CreateLoop(stmt,
5104                                       loop_entry,
5105                                       body_exit,
5106                                       loop_successor,
5107                                       break_info.break_block());
5108   set_current_block(loop_exit);
5109 }
5110
5111
5112 void HOptimizedGraphBuilder::VisitForStatement(ForStatement* stmt) {
5113   DCHECK(!HasStackOverflow());
5114   DCHECK(current_block() != NULL);
5115   DCHECK(current_block()->HasPredecessor());
5116   if (stmt->init() != NULL) {
5117     CHECK_ALIVE(Visit(stmt->init()));
5118   }
5119   DCHECK(current_block() != NULL);
5120   HBasicBlock* loop_entry = BuildLoopEntry(stmt);
5121
5122   HBasicBlock* loop_successor = NULL;
5123   if (stmt->cond() != NULL) {
5124     HBasicBlock* body_entry = graph()->CreateBasicBlock();
5125     loop_successor = graph()->CreateBasicBlock();
5126     CHECK_BAILOUT(VisitForControl(stmt->cond(), body_entry, loop_successor));
5127     if (body_entry->HasPredecessor()) {
5128       body_entry->SetJoinId(stmt->BodyId());
5129       set_current_block(body_entry);
5130     }
5131     if (loop_successor->HasPredecessor()) {
5132       loop_successor->SetJoinId(stmt->ExitId());
5133     } else {
5134       loop_successor = NULL;
5135     }
5136   }
5137
5138   BreakAndContinueInfo break_info(stmt, scope());
5139   if (current_block() != NULL) {
5140     BreakAndContinueScope push(&break_info, this);
5141     CHECK_BAILOUT(VisitLoopBody(stmt, loop_entry));
5142   }
5143   HBasicBlock* body_exit =
5144       JoinContinue(stmt, current_block(), break_info.continue_block());
5145
5146   if (stmt->next() != NULL && body_exit != NULL) {
5147     set_current_block(body_exit);
5148     CHECK_BAILOUT(Visit(stmt->next()));
5149     body_exit = current_block();
5150   }
5151
5152   HBasicBlock* loop_exit = CreateLoop(stmt,
5153                                       loop_entry,
5154                                       body_exit,
5155                                       loop_successor,
5156                                       break_info.break_block());
5157   set_current_block(loop_exit);
5158 }
5159
5160
5161 void HOptimizedGraphBuilder::VisitForInStatement(ForInStatement* stmt) {
5162   DCHECK(!HasStackOverflow());
5163   DCHECK(current_block() != NULL);
5164   DCHECK(current_block()->HasPredecessor());
5165
5166   if (!FLAG_optimize_for_in) {
5167     return Bailout(kForInStatementOptimizationIsDisabled);
5168   }
5169
5170   if (!stmt->each()->IsVariableProxy() ||
5171       !stmt->each()->AsVariableProxy()->var()->IsStackLocal()) {
5172     return Bailout(kForInStatementWithNonLocalEachVariable);
5173   }
5174
5175   Variable* each_var = stmt->each()->AsVariableProxy()->var();
5176
5177   CHECK_ALIVE(VisitForValue(stmt->enumerable()));
5178   HValue* enumerable = Top();  // Leave enumerable at the top.
5179
5180   IfBuilder if_undefined_or_null(this);
5181   if_undefined_or_null.If<HCompareObjectEqAndBranch>(
5182       enumerable, graph()->GetConstantUndefined());
5183   if_undefined_or_null.Or();
5184   if_undefined_or_null.If<HCompareObjectEqAndBranch>(
5185       enumerable, graph()->GetConstantNull());
5186   if_undefined_or_null.ThenDeopt(Deoptimizer::kUndefinedOrNullInForIn);
5187   if_undefined_or_null.End();
5188   BuildForInBody(stmt, each_var, enumerable);
5189 }
5190
5191
5192 void HOptimizedGraphBuilder::BuildForInBody(ForInStatement* stmt,
5193                                             Variable* each_var,
5194                                             HValue* enumerable) {
5195   HInstruction* map;
5196   HInstruction* array;
5197   HInstruction* enum_length;
5198   bool fast = stmt->for_in_type() == ForInStatement::FAST_FOR_IN;
5199   if (fast) {
5200     map = Add<HForInPrepareMap>(enumerable);
5201     Add<HSimulate>(stmt->PrepareId());
5202
5203     array = Add<HForInCacheArray>(enumerable, map,
5204                                   DescriptorArray::kEnumCacheBridgeCacheIndex);
5205     enum_length = Add<HMapEnumLength>(map);
5206
5207     HInstruction* index_cache = Add<HForInCacheArray>(
5208         enumerable, map, DescriptorArray::kEnumCacheBridgeIndicesCacheIndex);
5209     HForInCacheArray::cast(array)
5210         ->set_index_cache(HForInCacheArray::cast(index_cache));
5211   } else {
5212     Add<HSimulate>(stmt->PrepareId());
5213     {
5214       NoObservableSideEffectsScope no_effects(this);
5215       BuildJSObjectCheck(enumerable, 0);
5216     }
5217     Add<HSimulate>(stmt->ToObjectId());
5218
5219     map = graph()->GetConstant1();
5220     Runtime::FunctionId function_id = Runtime::kGetPropertyNamesFast;
5221     Add<HPushArguments>(enumerable);
5222     array = Add<HCallRuntime>(isolate()->factory()->empty_string(),
5223                               Runtime::FunctionForId(function_id), 1);
5224     Push(array);
5225     Add<HSimulate>(stmt->EnumId());
5226     Drop(1);
5227     Handle<Map> array_map = isolate()->factory()->fixed_array_map();
5228     HValue* check = Add<HCheckMaps>(array, array_map);
5229     enum_length = AddLoadFixedArrayLength(array, check);
5230   }
5231
5232   HInstruction* start_index = Add<HConstant>(0);
5233
5234   Push(map);
5235   Push(array);
5236   Push(enum_length);
5237   Push(start_index);
5238
5239   HBasicBlock* loop_entry = BuildLoopEntry(stmt);
5240
5241   // Reload the values to ensure we have up-to-date values inside of the loop.
5242   // This is relevant especially for OSR where the values don't come from the
5243   // computation above, but from the OSR entry block.
5244   enumerable = environment()->ExpressionStackAt(4);
5245   HValue* index = environment()->ExpressionStackAt(0);
5246   HValue* limit = environment()->ExpressionStackAt(1);
5247
5248   // Check that we still have more keys.
5249   HCompareNumericAndBranch* compare_index =
5250       New<HCompareNumericAndBranch>(index, limit, Token::LT);
5251   compare_index->set_observed_input_representation(
5252       Representation::Smi(), Representation::Smi());
5253
5254   HBasicBlock* loop_body = graph()->CreateBasicBlock();
5255   HBasicBlock* loop_successor = graph()->CreateBasicBlock();
5256
5257   compare_index->SetSuccessorAt(0, loop_body);
5258   compare_index->SetSuccessorAt(1, loop_successor);
5259   FinishCurrentBlock(compare_index);
5260
5261   set_current_block(loop_successor);
5262   Drop(5);
5263
5264   set_current_block(loop_body);
5265
5266   HValue* key =
5267       Add<HLoadKeyed>(environment()->ExpressionStackAt(2),  // Enum cache.
5268                       index, index, FAST_ELEMENTS);
5269
5270   if (fast) {
5271     // Check if the expected map still matches that of the enumerable.
5272     // If not just deoptimize.
5273     Add<HCheckMapValue>(enumerable, environment()->ExpressionStackAt(3));
5274     Bind(each_var, key);
5275   } else {
5276     Add<HPushArguments>(enumerable, key);
5277     Runtime::FunctionId function_id = Runtime::kForInFilter;
5278     key = Add<HCallRuntime>(isolate()->factory()->empty_string(),
5279                             Runtime::FunctionForId(function_id), 2);
5280     Push(key);
5281     Add<HSimulate>(stmt->FilterId());
5282     key = Pop();
5283     Bind(each_var, key);
5284     IfBuilder if_undefined(this);
5285     if_undefined.If<HCompareObjectEqAndBranch>(key,
5286                                                graph()->GetConstantUndefined());
5287     if_undefined.ThenDeopt(Deoptimizer::kUndefined);
5288     if_undefined.End();
5289     Add<HSimulate>(stmt->AssignmentId());
5290   }
5291
5292   BreakAndContinueInfo break_info(stmt, scope(), 5);
5293   {
5294     BreakAndContinueScope push(&break_info, this);
5295     CHECK_BAILOUT(VisitLoopBody(stmt, loop_entry));
5296   }
5297
5298   HBasicBlock* body_exit =
5299       JoinContinue(stmt, current_block(), break_info.continue_block());
5300
5301   if (body_exit != NULL) {
5302     set_current_block(body_exit);
5303
5304     HValue* current_index = Pop();
5305     Push(AddUncasted<HAdd>(current_index, graph()->GetConstant1()));
5306     body_exit = current_block();
5307   }
5308
5309   HBasicBlock* loop_exit = CreateLoop(stmt,
5310                                       loop_entry,
5311                                       body_exit,
5312                                       loop_successor,
5313                                       break_info.break_block());
5314
5315   set_current_block(loop_exit);
5316 }
5317
5318
5319 void HOptimizedGraphBuilder::VisitForOfStatement(ForOfStatement* stmt) {
5320   DCHECK(!HasStackOverflow());
5321   DCHECK(current_block() != NULL);
5322   DCHECK(current_block()->HasPredecessor());
5323   return Bailout(kForOfStatement);
5324 }
5325
5326
5327 void HOptimizedGraphBuilder::VisitTryCatchStatement(TryCatchStatement* stmt) {
5328   DCHECK(!HasStackOverflow());
5329   DCHECK(current_block() != NULL);
5330   DCHECK(current_block()->HasPredecessor());
5331   return Bailout(kTryCatchStatement);
5332 }
5333
5334
5335 void HOptimizedGraphBuilder::VisitTryFinallyStatement(
5336     TryFinallyStatement* stmt) {
5337   DCHECK(!HasStackOverflow());
5338   DCHECK(current_block() != NULL);
5339   DCHECK(current_block()->HasPredecessor());
5340   return Bailout(kTryFinallyStatement);
5341 }
5342
5343
5344 void HOptimizedGraphBuilder::VisitDebuggerStatement(DebuggerStatement* stmt) {
5345   DCHECK(!HasStackOverflow());
5346   DCHECK(current_block() != NULL);
5347   DCHECK(current_block()->HasPredecessor());
5348   return Bailout(kDebuggerStatement);
5349 }
5350
5351
5352 void HOptimizedGraphBuilder::VisitCaseClause(CaseClause* clause) {
5353   UNREACHABLE();
5354 }
5355
5356
5357 void HOptimizedGraphBuilder::VisitFunctionLiteral(FunctionLiteral* expr) {
5358   DCHECK(!HasStackOverflow());
5359   DCHECK(current_block() != NULL);
5360   DCHECK(current_block()->HasPredecessor());
5361   Handle<SharedFunctionInfo> shared_info = Compiler::GetSharedFunctionInfo(
5362       expr, current_info()->script(), top_info());
5363   // We also have a stack overflow if the recursive compilation did.
5364   if (HasStackOverflow()) return;
5365   HFunctionLiteral* instr =
5366       New<HFunctionLiteral>(shared_info, expr->pretenure());
5367   return ast_context()->ReturnInstruction(instr, expr->id());
5368 }
5369
5370
5371 void HOptimizedGraphBuilder::VisitClassLiteral(ClassLiteral* lit) {
5372   DCHECK(!HasStackOverflow());
5373   DCHECK(current_block() != NULL);
5374   DCHECK(current_block()->HasPredecessor());
5375   return Bailout(kClassLiteral);
5376 }
5377
5378
5379 void HOptimizedGraphBuilder::VisitNativeFunctionLiteral(
5380     NativeFunctionLiteral* expr) {
5381   DCHECK(!HasStackOverflow());
5382   DCHECK(current_block() != NULL);
5383   DCHECK(current_block()->HasPredecessor());
5384   return Bailout(kNativeFunctionLiteral);
5385 }
5386
5387
5388 void HOptimizedGraphBuilder::VisitConditional(Conditional* expr) {
5389   DCHECK(!HasStackOverflow());
5390   DCHECK(current_block() != NULL);
5391   DCHECK(current_block()->HasPredecessor());
5392   HBasicBlock* cond_true = graph()->CreateBasicBlock();
5393   HBasicBlock* cond_false = graph()->CreateBasicBlock();
5394   CHECK_BAILOUT(VisitForControl(expr->condition(), cond_true, cond_false));
5395
5396   // Visit the true and false subexpressions in the same AST context as the
5397   // whole expression.
5398   if (cond_true->HasPredecessor()) {
5399     cond_true->SetJoinId(expr->ThenId());
5400     set_current_block(cond_true);
5401     CHECK_BAILOUT(Visit(expr->then_expression()));
5402     cond_true = current_block();
5403   } else {
5404     cond_true = NULL;
5405   }
5406
5407   if (cond_false->HasPredecessor()) {
5408     cond_false->SetJoinId(expr->ElseId());
5409     set_current_block(cond_false);
5410     CHECK_BAILOUT(Visit(expr->else_expression()));
5411     cond_false = current_block();
5412   } else {
5413     cond_false = NULL;
5414   }
5415
5416   if (!ast_context()->IsTest()) {
5417     HBasicBlock* join = CreateJoin(cond_true, cond_false, expr->id());
5418     set_current_block(join);
5419     if (join != NULL && !ast_context()->IsEffect()) {
5420       return ast_context()->ReturnValue(Pop());
5421     }
5422   }
5423 }
5424
5425
5426 HOptimizedGraphBuilder::GlobalPropertyAccess
5427 HOptimizedGraphBuilder::LookupGlobalProperty(Variable* var, LookupIterator* it,
5428                                              PropertyAccessType access_type) {
5429   if (var->is_this() || !current_info()->has_global_object()) {
5430     return kUseGeneric;
5431   }
5432
5433   switch (it->state()) {
5434     case LookupIterator::ACCESSOR:
5435     case LookupIterator::ACCESS_CHECK:
5436     case LookupIterator::INTERCEPTOR:
5437     case LookupIterator::INTEGER_INDEXED_EXOTIC:
5438     case LookupIterator::NOT_FOUND:
5439       return kUseGeneric;
5440     case LookupIterator::DATA:
5441       if (access_type == STORE && it->IsReadOnly()) return kUseGeneric;
5442       return kUseCell;
5443     case LookupIterator::JSPROXY:
5444     case LookupIterator::TRANSITION:
5445       UNREACHABLE();
5446   }
5447   UNREACHABLE();
5448   return kUseGeneric;
5449 }
5450
5451
5452 HValue* HOptimizedGraphBuilder::BuildContextChainWalk(Variable* var) {
5453   DCHECK(var->IsContextSlot());
5454   HValue* context = environment()->context();
5455   int length = scope()->ContextChainLength(var->scope());
5456   while (length-- > 0) {
5457     context = Add<HLoadNamedField>(
5458         context, nullptr,
5459         HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX));
5460   }
5461   return context;
5462 }
5463
5464
5465 void HOptimizedGraphBuilder::VisitVariableProxy(VariableProxy* expr) {
5466   DCHECK(!HasStackOverflow());
5467   DCHECK(current_block() != NULL);
5468   DCHECK(current_block()->HasPredecessor());
5469   Variable* variable = expr->var();
5470   switch (variable->location()) {
5471     case VariableLocation::GLOBAL:
5472     case VariableLocation::UNALLOCATED: {
5473       if (IsLexicalVariableMode(variable->mode())) {
5474         // TODO(rossberg): should this be an DCHECK?
5475         return Bailout(kReferenceToGlobalLexicalVariable);
5476       }
5477       // Handle known global constants like 'undefined' specially to avoid a
5478       // load from a global cell for them.
5479       Handle<Object> constant_value =
5480           isolate()->factory()->GlobalConstantFor(variable->name());
5481       if (!constant_value.is_null()) {
5482         HConstant* instr = New<HConstant>(constant_value);
5483         return ast_context()->ReturnInstruction(instr, expr->id());
5484       }
5485
5486       Handle<GlobalObject> global(current_info()->global_object());
5487
5488       // Lookup in script contexts.
5489       {
5490         Handle<ScriptContextTable> script_contexts(
5491             global->native_context()->script_context_table());
5492         ScriptContextTable::LookupResult lookup;
5493         if (ScriptContextTable::Lookup(script_contexts, variable->name(),
5494                                        &lookup)) {
5495           Handle<Context> script_context = ScriptContextTable::GetContext(
5496               script_contexts, lookup.context_index);
5497           Handle<Object> current_value =
5498               FixedArray::get(script_context, lookup.slot_index);
5499
5500           // If the values is not the hole, it will stay initialized,
5501           // so no need to generate a check.
5502           if (*current_value == *isolate()->factory()->the_hole_value()) {
5503             return Bailout(kReferenceToUninitializedVariable);
5504           }
5505           HInstruction* result = New<HLoadNamedField>(
5506               Add<HConstant>(script_context), nullptr,
5507               HObjectAccess::ForContextSlot(lookup.slot_index));
5508           return ast_context()->ReturnInstruction(result, expr->id());
5509         }
5510       }
5511
5512       LookupIterator it(global, variable->name(), LookupIterator::OWN);
5513       GlobalPropertyAccess type = LookupGlobalProperty(variable, &it, LOAD);
5514
5515       if (type == kUseCell) {
5516         Handle<PropertyCell> cell = it.GetPropertyCell();
5517         top_info()->dependencies()->AssumePropertyCell(cell);
5518         auto cell_type = it.property_details().cell_type();
5519         if (cell_type == PropertyCellType::kConstant ||
5520             cell_type == PropertyCellType::kUndefined) {
5521           Handle<Object> constant_object(cell->value(), isolate());
5522           if (constant_object->IsConsString()) {
5523             constant_object =
5524                 String::Flatten(Handle<String>::cast(constant_object));
5525           }
5526           HConstant* constant = New<HConstant>(constant_object);
5527           return ast_context()->ReturnInstruction(constant, expr->id());
5528         } else {
5529           auto access = HObjectAccess::ForPropertyCellValue();
5530           UniqueSet<Map>* field_maps = nullptr;
5531           if (cell_type == PropertyCellType::kConstantType) {
5532             switch (cell->GetConstantType()) {
5533               case PropertyCellConstantType::kSmi:
5534                 access = access.WithRepresentation(Representation::Smi());
5535                 break;
5536               case PropertyCellConstantType::kStableMap: {
5537                 // Check that the map really is stable. The heap object could
5538                 // have mutated without the cell updating state. In that case,
5539                 // make no promises about the loaded value except that it's a
5540                 // heap object.
5541                 access =
5542                     access.WithRepresentation(Representation::HeapObject());
5543                 Handle<Map> map(HeapObject::cast(cell->value())->map());
5544                 if (map->is_stable()) {
5545                   field_maps = new (zone())
5546                       UniqueSet<Map>(Unique<Map>::CreateImmovable(map), zone());
5547                 }
5548                 break;
5549               }
5550             }
5551           }
5552           HConstant* cell_constant = Add<HConstant>(cell);
5553           HLoadNamedField* instr;
5554           if (field_maps == nullptr) {
5555             instr = New<HLoadNamedField>(cell_constant, nullptr, access);
5556           } else {
5557             instr = New<HLoadNamedField>(cell_constant, nullptr, access,
5558                                          field_maps, HType::HeapObject());
5559           }
5560           instr->ClearDependsOnFlag(kInobjectFields);
5561           instr->SetDependsOnFlag(kGlobalVars);
5562           return ast_context()->ReturnInstruction(instr, expr->id());
5563         }
5564       } else if (variable->IsGlobalSlot()) {
5565         DCHECK(variable->index() > 0);
5566         DCHECK(variable->IsStaticGlobalObjectProperty());
5567         int slot_index = variable->index();
5568         int depth = scope()->ContextChainLength(variable->scope());
5569
5570         HLoadGlobalViaContext* instr =
5571             New<HLoadGlobalViaContext>(depth, slot_index);
5572         return ast_context()->ReturnInstruction(instr, expr->id());
5573
5574       } else {
5575         HValue* global_object = Add<HLoadNamedField>(
5576             context(), nullptr,
5577             HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
5578         HLoadGlobalGeneric* instr = New<HLoadGlobalGeneric>(
5579             global_object, variable->name(), ast_context()->typeof_mode());
5580         instr->SetVectorAndSlot(handle(current_feedback_vector(), isolate()),
5581                                 expr->VariableFeedbackSlot());
5582         return ast_context()->ReturnInstruction(instr, expr->id());
5583       }
5584     }
5585
5586     case VariableLocation::PARAMETER:
5587     case VariableLocation::LOCAL: {
5588       HValue* value = LookupAndMakeLive(variable);
5589       if (value == graph()->GetConstantHole()) {
5590         DCHECK(IsDeclaredVariableMode(variable->mode()) &&
5591                variable->mode() != VAR);
5592         return Bailout(kReferenceToUninitializedVariable);
5593       }
5594       return ast_context()->ReturnValue(value);
5595     }
5596
5597     case VariableLocation::CONTEXT: {
5598       HValue* context = BuildContextChainWalk(variable);
5599       HLoadContextSlot::Mode mode;
5600       switch (variable->mode()) {
5601         case LET:
5602         case CONST:
5603           mode = HLoadContextSlot::kCheckDeoptimize;
5604           break;
5605         case CONST_LEGACY:
5606           mode = HLoadContextSlot::kCheckReturnUndefined;
5607           break;
5608         default:
5609           mode = HLoadContextSlot::kNoCheck;
5610           break;
5611       }
5612       HLoadContextSlot* instr =
5613           new(zone()) HLoadContextSlot(context, variable->index(), mode);
5614       return ast_context()->ReturnInstruction(instr, expr->id());
5615     }
5616
5617     case VariableLocation::LOOKUP:
5618       return Bailout(kReferenceToAVariableWhichRequiresDynamicLookup);
5619   }
5620 }
5621
5622
5623 void HOptimizedGraphBuilder::VisitLiteral(Literal* expr) {
5624   DCHECK(!HasStackOverflow());
5625   DCHECK(current_block() != NULL);
5626   DCHECK(current_block()->HasPredecessor());
5627   HConstant* instr = New<HConstant>(expr->value());
5628   return ast_context()->ReturnInstruction(instr, expr->id());
5629 }
5630
5631
5632 void HOptimizedGraphBuilder::VisitRegExpLiteral(RegExpLiteral* expr) {
5633   DCHECK(!HasStackOverflow());
5634   DCHECK(current_block() != NULL);
5635   DCHECK(current_block()->HasPredecessor());
5636   Handle<JSFunction> closure = function_state()->compilation_info()->closure();
5637   Handle<FixedArray> literals(closure->literals());
5638   HRegExpLiteral* instr = New<HRegExpLiteral>(literals,
5639                                               expr->pattern(),
5640                                               expr->flags(),
5641                                               expr->literal_index());
5642   return ast_context()->ReturnInstruction(instr, expr->id());
5643 }
5644
5645
5646 static bool CanInlinePropertyAccess(Handle<Map> map) {
5647   if (map->instance_type() == HEAP_NUMBER_TYPE) return true;
5648   if (map->instance_type() < FIRST_NONSTRING_TYPE) return true;
5649   return map->IsJSObjectMap() && !map->is_dictionary_map() &&
5650          !map->has_named_interceptor() &&
5651          // TODO(verwaest): Whitelist contexts to which we have access.
5652          !map->is_access_check_needed();
5653 }
5654
5655
5656 // Determines whether the given array or object literal boilerplate satisfies
5657 // all limits to be considered for fast deep-copying and computes the total
5658 // size of all objects that are part of the graph.
5659 static bool IsFastLiteral(Handle<JSObject> boilerplate,
5660                           int max_depth,
5661                           int* max_properties) {
5662   if (boilerplate->map()->is_deprecated() &&
5663       !JSObject::TryMigrateInstance(boilerplate)) {
5664     return false;
5665   }
5666
5667   DCHECK(max_depth >= 0 && *max_properties >= 0);
5668   if (max_depth == 0) return false;
5669
5670   Isolate* isolate = boilerplate->GetIsolate();
5671   Handle<FixedArrayBase> elements(boilerplate->elements());
5672   if (elements->length() > 0 &&
5673       elements->map() != isolate->heap()->fixed_cow_array_map()) {
5674     if (boilerplate->HasFastSmiOrObjectElements()) {
5675       Handle<FixedArray> fast_elements = Handle<FixedArray>::cast(elements);
5676       int length = elements->length();
5677       for (int i = 0; i < length; i++) {
5678         if ((*max_properties)-- == 0) return false;
5679         Handle<Object> value(fast_elements->get(i), isolate);
5680         if (value->IsJSObject()) {
5681           Handle<JSObject> value_object = Handle<JSObject>::cast(value);
5682           if (!IsFastLiteral(value_object,
5683                              max_depth - 1,
5684                              max_properties)) {
5685             return false;
5686           }
5687         }
5688       }
5689     } else if (!boilerplate->HasFastDoubleElements()) {
5690       return false;
5691     }
5692   }
5693
5694   Handle<FixedArray> properties(boilerplate->properties());
5695   if (properties->length() > 0) {
5696     return false;
5697   } else {
5698     Handle<DescriptorArray> descriptors(
5699         boilerplate->map()->instance_descriptors());
5700     int limit = boilerplate->map()->NumberOfOwnDescriptors();
5701     for (int i = 0; i < limit; i++) {
5702       PropertyDetails details = descriptors->GetDetails(i);
5703       if (details.type() != DATA) continue;
5704       if ((*max_properties)-- == 0) return false;
5705       FieldIndex field_index = FieldIndex::ForDescriptor(boilerplate->map(), i);
5706       if (boilerplate->IsUnboxedDoubleField(field_index)) continue;
5707       Handle<Object> value(boilerplate->RawFastPropertyAt(field_index),
5708                            isolate);
5709       if (value->IsJSObject()) {
5710         Handle<JSObject> value_object = Handle<JSObject>::cast(value);
5711         if (!IsFastLiteral(value_object,
5712                            max_depth - 1,
5713                            max_properties)) {
5714           return false;
5715         }
5716       }
5717     }
5718   }
5719   return true;
5720 }
5721
5722
5723 void HOptimizedGraphBuilder::VisitObjectLiteral(ObjectLiteral* expr) {
5724   DCHECK(!HasStackOverflow());
5725   DCHECK(current_block() != NULL);
5726   DCHECK(current_block()->HasPredecessor());
5727
5728   Handle<JSFunction> closure = function_state()->compilation_info()->closure();
5729   HInstruction* literal;
5730
5731   // Check whether to use fast or slow deep-copying for boilerplate.
5732   int max_properties = kMaxFastLiteralProperties;
5733   Handle<Object> literals_cell(closure->literals()->get(expr->literal_index()),
5734                                isolate());
5735   Handle<AllocationSite> site;
5736   Handle<JSObject> boilerplate;
5737   if (!literals_cell->IsUndefined()) {
5738     // Retrieve the boilerplate
5739     site = Handle<AllocationSite>::cast(literals_cell);
5740     boilerplate = Handle<JSObject>(JSObject::cast(site->transition_info()),
5741                                    isolate());
5742   }
5743
5744   if (!boilerplate.is_null() &&
5745       IsFastLiteral(boilerplate, kMaxFastLiteralDepth, &max_properties)) {
5746     AllocationSiteUsageContext site_context(isolate(), site, false);
5747     site_context.EnterNewScope();
5748     literal = BuildFastLiteral(boilerplate, &site_context);
5749     site_context.ExitScope(site, boilerplate);
5750   } else {
5751     NoObservableSideEffectsScope no_effects(this);
5752     Handle<FixedArray> closure_literals(closure->literals(), isolate());
5753     Handle<FixedArray> constant_properties = expr->constant_properties();
5754     int literal_index = expr->literal_index();
5755     int flags = expr->ComputeFlags(true);
5756
5757     Add<HPushArguments>(Add<HConstant>(closure_literals),
5758                         Add<HConstant>(literal_index),
5759                         Add<HConstant>(constant_properties),
5760                         Add<HConstant>(flags));
5761
5762     Runtime::FunctionId function_id = Runtime::kCreateObjectLiteral;
5763     literal = Add<HCallRuntime>(isolate()->factory()->empty_string(),
5764                                 Runtime::FunctionForId(function_id),
5765                                 4);
5766   }
5767
5768   // The object is expected in the bailout environment during computation
5769   // of the property values and is the value of the entire expression.
5770   Push(literal);
5771
5772   for (int i = 0; i < expr->properties()->length(); i++) {
5773     ObjectLiteral::Property* property = expr->properties()->at(i);
5774     if (property->is_computed_name()) return Bailout(kComputedPropertyName);
5775     if (property->IsCompileTimeValue()) continue;
5776
5777     Literal* key = property->key()->AsLiteral();
5778     Expression* value = property->value();
5779
5780     switch (property->kind()) {
5781       case ObjectLiteral::Property::MATERIALIZED_LITERAL:
5782         DCHECK(!CompileTimeValue::IsCompileTimeValue(value));
5783         // Fall through.
5784       case ObjectLiteral::Property::COMPUTED:
5785         // It is safe to use [[Put]] here because the boilerplate already
5786         // contains computed properties with an uninitialized value.
5787         if (key->value()->IsInternalizedString()) {
5788           if (property->emit_store()) {
5789             CHECK_ALIVE(VisitForValue(value));
5790             HValue* value = Pop();
5791
5792             // Add [[HomeObject]] to function literals.
5793             if (FunctionLiteral::NeedsHomeObject(property->value())) {
5794               Handle<Symbol> sym = isolate()->factory()->home_object_symbol();
5795               HInstruction* store_home = BuildKeyedGeneric(
5796                   STORE, NULL, value, Add<HConstant>(sym), literal);
5797               AddInstruction(store_home);
5798               DCHECK(store_home->HasObservableSideEffects());
5799               Add<HSimulate>(property->value()->id(), REMOVABLE_SIMULATE);
5800             }
5801
5802             Handle<Map> map = property->GetReceiverType();
5803             Handle<String> name = key->AsPropertyName();
5804             HValue* store;
5805             if (map.is_null()) {
5806               // If we don't know the monomorphic type, do a generic store.
5807               CHECK_ALIVE(store = BuildNamedGeneric(
5808                   STORE, NULL, literal, name, value));
5809             } else {
5810               PropertyAccessInfo info(this, STORE, map, name);
5811               if (info.CanAccessMonomorphic()) {
5812                 HValue* checked_literal = Add<HCheckMaps>(literal, map);
5813                 DCHECK(!info.IsAccessorConstant());
5814                 store = BuildMonomorphicAccess(
5815                     &info, literal, checked_literal, value,
5816                     BailoutId::None(), BailoutId::None());
5817               } else {
5818                 CHECK_ALIVE(store = BuildNamedGeneric(
5819                     STORE, NULL, literal, name, value));
5820               }
5821             }
5822             if (store->IsInstruction()) {
5823               AddInstruction(HInstruction::cast(store));
5824             }
5825             DCHECK(store->HasObservableSideEffects());
5826             Add<HSimulate>(key->id(), REMOVABLE_SIMULATE);
5827           } else {
5828             CHECK_ALIVE(VisitForEffect(value));
5829           }
5830           break;
5831         }
5832         // Fall through.
5833       case ObjectLiteral::Property::PROTOTYPE:
5834       case ObjectLiteral::Property::SETTER:
5835       case ObjectLiteral::Property::GETTER:
5836         return Bailout(kObjectLiteralWithComplexProperty);
5837       default: UNREACHABLE();
5838     }
5839   }
5840
5841   if (expr->has_function()) {
5842     // Return the result of the transformation to fast properties
5843     // instead of the original since this operation changes the map
5844     // of the object. This makes sure that the original object won't
5845     // be used by other optimized code before it is transformed
5846     // (e.g. because of code motion).
5847     HToFastProperties* result = Add<HToFastProperties>(Pop());
5848     return ast_context()->ReturnValue(result);
5849   } else {
5850     return ast_context()->ReturnValue(Pop());
5851   }
5852 }
5853
5854
5855 void HOptimizedGraphBuilder::VisitArrayLiteral(ArrayLiteral* expr) {
5856   DCHECK(!HasStackOverflow());
5857   DCHECK(current_block() != NULL);
5858   DCHECK(current_block()->HasPredecessor());
5859   expr->BuildConstantElements(isolate());
5860   ZoneList<Expression*>* subexprs = expr->values();
5861   int length = subexprs->length();
5862   HInstruction* literal;
5863
5864   Handle<AllocationSite> site;
5865   Handle<FixedArray> literals(environment()->closure()->literals(), isolate());
5866   bool uninitialized = false;
5867   Handle<Object> literals_cell(literals->get(expr->literal_index()),
5868                                isolate());
5869   Handle<JSObject> boilerplate_object;
5870   if (literals_cell->IsUndefined()) {
5871     uninitialized = true;
5872     Handle<Object> raw_boilerplate;
5873     ASSIGN_RETURN_ON_EXCEPTION_VALUE(
5874         isolate(), raw_boilerplate,
5875         Runtime::CreateArrayLiteralBoilerplate(
5876             isolate(), literals, expr->constant_elements(),
5877             is_strong(function_language_mode())),
5878         Bailout(kArrayBoilerplateCreationFailed));
5879
5880     boilerplate_object = Handle<JSObject>::cast(raw_boilerplate);
5881     AllocationSiteCreationContext creation_context(isolate());
5882     site = creation_context.EnterNewScope();
5883     if (JSObject::DeepWalk(boilerplate_object, &creation_context).is_null()) {
5884       return Bailout(kArrayBoilerplateCreationFailed);
5885     }
5886     creation_context.ExitScope(site, boilerplate_object);
5887     literals->set(expr->literal_index(), *site);
5888
5889     if (boilerplate_object->elements()->map() ==
5890         isolate()->heap()->fixed_cow_array_map()) {
5891       isolate()->counters()->cow_arrays_created_runtime()->Increment();
5892     }
5893   } else {
5894     DCHECK(literals_cell->IsAllocationSite());
5895     site = Handle<AllocationSite>::cast(literals_cell);
5896     boilerplate_object = Handle<JSObject>(
5897         JSObject::cast(site->transition_info()), isolate());
5898   }
5899
5900   DCHECK(!boilerplate_object.is_null());
5901   DCHECK(site->SitePointsToLiteral());
5902
5903   ElementsKind boilerplate_elements_kind =
5904       boilerplate_object->GetElementsKind();
5905
5906   // Check whether to use fast or slow deep-copying for boilerplate.
5907   int max_properties = kMaxFastLiteralProperties;
5908   if (IsFastLiteral(boilerplate_object,
5909                     kMaxFastLiteralDepth,
5910                     &max_properties)) {
5911     AllocationSiteUsageContext site_context(isolate(), site, false);
5912     site_context.EnterNewScope();
5913     literal = BuildFastLiteral(boilerplate_object, &site_context);
5914     site_context.ExitScope(site, boilerplate_object);
5915   } else {
5916     NoObservableSideEffectsScope no_effects(this);
5917     // Boilerplate already exists and constant elements are never accessed,
5918     // pass an empty fixed array to the runtime function instead.
5919     Handle<FixedArray> constants = isolate()->factory()->empty_fixed_array();
5920     int literal_index = expr->literal_index();
5921     int flags = expr->ComputeFlags(true);
5922
5923     Add<HPushArguments>(Add<HConstant>(literals),
5924                         Add<HConstant>(literal_index),
5925                         Add<HConstant>(constants),
5926                         Add<HConstant>(flags));
5927
5928     Runtime::FunctionId function_id = Runtime::kCreateArrayLiteral;
5929     literal = Add<HCallRuntime>(isolate()->factory()->empty_string(),
5930                                 Runtime::FunctionForId(function_id),
5931                                 4);
5932
5933     // Register to deopt if the boilerplate ElementsKind changes.
5934     top_info()->dependencies()->AssumeTransitionStable(site);
5935   }
5936
5937   // The array is expected in the bailout environment during computation
5938   // of the property values and is the value of the entire expression.
5939   Push(literal);
5940   // The literal index is on the stack, too.
5941   Push(Add<HConstant>(expr->literal_index()));
5942
5943   HInstruction* elements = NULL;
5944
5945   for (int i = 0; i < length; i++) {
5946     Expression* subexpr = subexprs->at(i);
5947     if (subexpr->IsSpread()) {
5948       return Bailout(kSpread);
5949     }
5950
5951     // If the subexpression is a literal or a simple materialized literal it
5952     // is already set in the cloned array.
5953     if (CompileTimeValue::IsCompileTimeValue(subexpr)) continue;
5954
5955     CHECK_ALIVE(VisitForValue(subexpr));
5956     HValue* value = Pop();
5957     if (!Smi::IsValid(i)) return Bailout(kNonSmiKeyInArrayLiteral);
5958
5959     elements = AddLoadElements(literal);
5960
5961     HValue* key = Add<HConstant>(i);
5962
5963     switch (boilerplate_elements_kind) {
5964       case FAST_SMI_ELEMENTS:
5965       case FAST_HOLEY_SMI_ELEMENTS:
5966       case FAST_ELEMENTS:
5967       case FAST_HOLEY_ELEMENTS:
5968       case FAST_DOUBLE_ELEMENTS:
5969       case FAST_HOLEY_DOUBLE_ELEMENTS: {
5970         HStoreKeyed* instr = Add<HStoreKeyed>(elements, key, value,
5971                                               boilerplate_elements_kind);
5972         instr->SetUninitialized(uninitialized);
5973         break;
5974       }
5975       default:
5976         UNREACHABLE();
5977         break;
5978     }
5979
5980     Add<HSimulate>(expr->GetIdForElement(i));
5981   }
5982
5983   Drop(1);  // array literal index
5984   return ast_context()->ReturnValue(Pop());
5985 }
5986
5987
5988 HCheckMaps* HOptimizedGraphBuilder::AddCheckMap(HValue* object,
5989                                                 Handle<Map> map) {
5990   BuildCheckHeapObject(object);
5991   return Add<HCheckMaps>(object, map);
5992 }
5993
5994
5995 HInstruction* HOptimizedGraphBuilder::BuildLoadNamedField(
5996     PropertyAccessInfo* info,
5997     HValue* checked_object) {
5998   // See if this is a load for an immutable property
5999   if (checked_object->ActualValue()->IsConstant()) {
6000     Handle<Object> object(
6001         HConstant::cast(checked_object->ActualValue())->handle(isolate()));
6002
6003     if (object->IsJSObject()) {
6004       LookupIterator it(object, info->name(),
6005                         LookupIterator::OWN_SKIP_INTERCEPTOR);
6006       Handle<Object> value = JSReceiver::GetDataProperty(&it);
6007       if (it.IsFound() && it.IsReadOnly() && !it.IsConfigurable()) {
6008         return New<HConstant>(value);
6009       }
6010     }
6011   }
6012
6013   HObjectAccess access = info->access();
6014   if (access.representation().IsDouble() &&
6015       (!FLAG_unbox_double_fields || !access.IsInobject())) {
6016     // Load the heap number.
6017     checked_object = Add<HLoadNamedField>(
6018         checked_object, nullptr,
6019         access.WithRepresentation(Representation::Tagged()));
6020     // Load the double value from it.
6021     access = HObjectAccess::ForHeapNumberValue();
6022   }
6023
6024   SmallMapList* map_list = info->field_maps();
6025   if (map_list->length() == 0) {
6026     return New<HLoadNamedField>(checked_object, checked_object, access);
6027   }
6028
6029   UniqueSet<Map>* maps = new(zone()) UniqueSet<Map>(map_list->length(), zone());
6030   for (int i = 0; i < map_list->length(); ++i) {
6031     maps->Add(Unique<Map>::CreateImmovable(map_list->at(i)), zone());
6032   }
6033   return New<HLoadNamedField>(
6034       checked_object, checked_object, access, maps, info->field_type());
6035 }
6036
6037
6038 HInstruction* HOptimizedGraphBuilder::BuildStoreNamedField(
6039     PropertyAccessInfo* info,
6040     HValue* checked_object,
6041     HValue* value) {
6042   bool transition_to_field = info->IsTransition();
6043   // TODO(verwaest): Move this logic into PropertyAccessInfo.
6044   HObjectAccess field_access = info->access();
6045
6046   HStoreNamedField *instr;
6047   if (field_access.representation().IsDouble() &&
6048       (!FLAG_unbox_double_fields || !field_access.IsInobject())) {
6049     HObjectAccess heap_number_access =
6050         field_access.WithRepresentation(Representation::Tagged());
6051     if (transition_to_field) {
6052       // The store requires a mutable HeapNumber to be allocated.
6053       NoObservableSideEffectsScope no_side_effects(this);
6054       HInstruction* heap_number_size = Add<HConstant>(HeapNumber::kSize);
6055
6056       // TODO(hpayer): Allocation site pretenuring support.
6057       HInstruction* heap_number = Add<HAllocate>(heap_number_size,
6058           HType::HeapObject(),
6059           NOT_TENURED,
6060           MUTABLE_HEAP_NUMBER_TYPE);
6061       AddStoreMapConstant(
6062           heap_number, isolate()->factory()->mutable_heap_number_map());
6063       Add<HStoreNamedField>(heap_number, HObjectAccess::ForHeapNumberValue(),
6064                             value);
6065       instr = New<HStoreNamedField>(checked_object->ActualValue(),
6066                                     heap_number_access,
6067                                     heap_number);
6068     } else {
6069       // Already holds a HeapNumber; load the box and write its value field.
6070       HInstruction* heap_number =
6071           Add<HLoadNamedField>(checked_object, nullptr, heap_number_access);
6072       instr = New<HStoreNamedField>(heap_number,
6073                                     HObjectAccess::ForHeapNumberValue(),
6074                                     value, STORE_TO_INITIALIZED_ENTRY);
6075     }
6076   } else {
6077     if (field_access.representation().IsHeapObject()) {
6078       BuildCheckHeapObject(value);
6079     }
6080
6081     if (!info->field_maps()->is_empty()) {
6082       DCHECK(field_access.representation().IsHeapObject());
6083       value = Add<HCheckMaps>(value, info->field_maps());
6084     }
6085
6086     // This is a normal store.
6087     instr = New<HStoreNamedField>(
6088         checked_object->ActualValue(), field_access, value,
6089         transition_to_field ? INITIALIZING_STORE : STORE_TO_INITIALIZED_ENTRY);
6090   }
6091
6092   if (transition_to_field) {
6093     Handle<Map> transition(info->transition());
6094     DCHECK(!transition->is_deprecated());
6095     instr->SetTransition(Add<HConstant>(transition));
6096   }
6097   return instr;
6098 }
6099
6100
6101 bool HOptimizedGraphBuilder::PropertyAccessInfo::IsCompatible(
6102     PropertyAccessInfo* info) {
6103   if (!CanInlinePropertyAccess(map_)) return false;
6104
6105   // Currently only handle Type::Number as a polymorphic case.
6106   // TODO(verwaest): Support monomorphic handling of numbers with a HCheckNumber
6107   // instruction.
6108   if (IsNumberType()) return false;
6109
6110   // Values are only compatible for monomorphic load if they all behave the same
6111   // regarding value wrappers.
6112   if (IsValueWrapped() != info->IsValueWrapped()) return false;
6113
6114   if (!LookupDescriptor()) return false;
6115
6116   if (!IsFound()) {
6117     return (!info->IsFound() || info->has_holder()) &&
6118            map()->prototype() == info->map()->prototype();
6119   }
6120
6121   // Mismatch if the other access info found the property in the prototype
6122   // chain.
6123   if (info->has_holder()) return false;
6124
6125   if (IsAccessorConstant()) {
6126     return accessor_.is_identical_to(info->accessor_) &&
6127         api_holder_.is_identical_to(info->api_holder_);
6128   }
6129
6130   if (IsDataConstant()) {
6131     return constant_.is_identical_to(info->constant_);
6132   }
6133
6134   DCHECK(IsData());
6135   if (!info->IsData()) return false;
6136
6137   Representation r = access_.representation();
6138   if (IsLoad()) {
6139     if (!info->access_.representation().IsCompatibleForLoad(r)) return false;
6140   } else {
6141     if (!info->access_.representation().IsCompatibleForStore(r)) return false;
6142   }
6143   if (info->access_.offset() != access_.offset()) return false;
6144   if (info->access_.IsInobject() != access_.IsInobject()) return false;
6145   if (IsLoad()) {
6146     if (field_maps_.is_empty()) {
6147       info->field_maps_.Clear();
6148     } else if (!info->field_maps_.is_empty()) {
6149       for (int i = 0; i < field_maps_.length(); ++i) {
6150         info->field_maps_.AddMapIfMissing(field_maps_.at(i), info->zone());
6151       }
6152       info->field_maps_.Sort();
6153     }
6154   } else {
6155     // We can only merge stores that agree on their field maps. The comparison
6156     // below is safe, since we keep the field maps sorted.
6157     if (field_maps_.length() != info->field_maps_.length()) return false;
6158     for (int i = 0; i < field_maps_.length(); ++i) {
6159       if (!field_maps_.at(i).is_identical_to(info->field_maps_.at(i))) {
6160         return false;
6161       }
6162     }
6163   }
6164   info->GeneralizeRepresentation(r);
6165   info->field_type_ = info->field_type_.Combine(field_type_);
6166   return true;
6167 }
6168
6169
6170 bool HOptimizedGraphBuilder::PropertyAccessInfo::LookupDescriptor() {
6171   if (!map_->IsJSObjectMap()) return true;
6172   LookupDescriptor(*map_, *name_);
6173   return LoadResult(map_);
6174 }
6175
6176
6177 bool HOptimizedGraphBuilder::PropertyAccessInfo::LoadResult(Handle<Map> map) {
6178   if (!IsLoad() && IsProperty() && IsReadOnly()) {
6179     return false;
6180   }
6181
6182   if (IsData()) {
6183     // Construct the object field access.
6184     int index = GetLocalFieldIndexFromMap(map);
6185     access_ = HObjectAccess::ForField(map, index, representation(), name_);
6186
6187     // Load field map for heap objects.
6188     return LoadFieldMaps(map);
6189   } else if (IsAccessorConstant()) {
6190     Handle<Object> accessors = GetAccessorsFromMap(map);
6191     if (!accessors->IsAccessorPair()) return false;
6192     Object* raw_accessor =
6193         IsLoad() ? Handle<AccessorPair>::cast(accessors)->getter()
6194                  : Handle<AccessorPair>::cast(accessors)->setter();
6195     if (!raw_accessor->IsJSFunction()) return false;
6196     Handle<JSFunction> accessor = handle(JSFunction::cast(raw_accessor));
6197     if (accessor->shared()->IsApiFunction()) {
6198       CallOptimization call_optimization(accessor);
6199       if (call_optimization.is_simple_api_call()) {
6200         CallOptimization::HolderLookup holder_lookup;
6201         api_holder_ =
6202             call_optimization.LookupHolderOfExpectedType(map_, &holder_lookup);
6203       }
6204     }
6205     accessor_ = accessor;
6206   } else if (IsDataConstant()) {
6207     constant_ = GetConstantFromMap(map);
6208   }
6209
6210   return true;
6211 }
6212
6213
6214 bool HOptimizedGraphBuilder::PropertyAccessInfo::LoadFieldMaps(
6215     Handle<Map> map) {
6216   // Clear any previously collected field maps/type.
6217   field_maps_.Clear();
6218   field_type_ = HType::Tagged();
6219
6220   // Figure out the field type from the accessor map.
6221   Handle<HeapType> field_type = GetFieldTypeFromMap(map);
6222
6223   // Collect the (stable) maps from the field type.
6224   int num_field_maps = field_type->NumClasses();
6225   if (num_field_maps > 0) {
6226     DCHECK(access_.representation().IsHeapObject());
6227     field_maps_.Reserve(num_field_maps, zone());
6228     HeapType::Iterator<Map> it = field_type->Classes();
6229     while (!it.Done()) {
6230       Handle<Map> field_map = it.Current();
6231       if (!field_map->is_stable()) {
6232         field_maps_.Clear();
6233         break;
6234       }
6235       field_maps_.Add(field_map, zone());
6236       it.Advance();
6237     }
6238   }
6239
6240   if (field_maps_.is_empty()) {
6241     // Store is not safe if the field map was cleared.
6242     return IsLoad() || !field_type->Is(HeapType::None());
6243   }
6244
6245   field_maps_.Sort();
6246   DCHECK_EQ(num_field_maps, field_maps_.length());
6247
6248   // Determine field HType from field HeapType.
6249   field_type_ = HType::FromType<HeapType>(field_type);
6250   DCHECK(field_type_.IsHeapObject());
6251
6252   // Add dependency on the map that introduced the field.
6253   top_info()->dependencies()->AssumeFieldType(GetFieldOwnerFromMap(map));
6254   return true;
6255 }
6256
6257
6258 bool HOptimizedGraphBuilder::PropertyAccessInfo::LookupInPrototypes() {
6259   Handle<Map> map = this->map();
6260
6261   while (map->prototype()->IsJSObject()) {
6262     holder_ = handle(JSObject::cast(map->prototype()));
6263     if (holder_->map()->is_deprecated()) {
6264       JSObject::TryMigrateInstance(holder_);
6265     }
6266     map = Handle<Map>(holder_->map());
6267     if (!CanInlinePropertyAccess(map)) {
6268       NotFound();
6269       return false;
6270     }
6271     LookupDescriptor(*map, *name_);
6272     if (IsFound()) return LoadResult(map);
6273   }
6274
6275   NotFound();
6276   return !map->prototype()->IsJSReceiver();
6277 }
6278
6279
6280 bool HOptimizedGraphBuilder::PropertyAccessInfo::IsIntegerIndexedExotic() {
6281   InstanceType instance_type = map_->instance_type();
6282   return instance_type == JS_TYPED_ARRAY_TYPE &&
6283          IsSpecialIndex(isolate()->unicode_cache(), *name_);
6284 }
6285
6286
6287 bool HOptimizedGraphBuilder::PropertyAccessInfo::CanAccessMonomorphic() {
6288   if (!CanInlinePropertyAccess(map_)) return false;
6289   if (IsJSObjectFieldAccessor()) return IsLoad();
6290   if (IsJSArrayBufferViewFieldAccessor()) return IsLoad();
6291   if (map_->function_with_prototype() && !map_->has_non_instance_prototype() &&
6292       name_.is_identical_to(isolate()->factory()->prototype_string())) {
6293     return IsLoad();
6294   }
6295   if (!LookupDescriptor()) return false;
6296   if (IsFound()) return IsLoad() || !IsReadOnly();
6297   if (IsIntegerIndexedExotic()) return false;
6298   if (!LookupInPrototypes()) return false;
6299   if (IsLoad()) return true;
6300
6301   if (IsAccessorConstant()) return true;
6302   LookupTransition(*map_, *name_, NONE);
6303   if (IsTransitionToData() && map_->unused_property_fields() > 0) {
6304     // Construct the object field access.
6305     int descriptor = transition()->LastAdded();
6306     int index =
6307         transition()->instance_descriptors()->GetFieldIndex(descriptor) -
6308         map_->inobject_properties();
6309     PropertyDetails details =
6310         transition()->instance_descriptors()->GetDetails(descriptor);
6311     Representation representation = details.representation();
6312     access_ = HObjectAccess::ForField(map_, index, representation, name_);
6313
6314     // Load field map for heap objects.
6315     return LoadFieldMaps(transition());
6316   }
6317   return false;
6318 }
6319
6320
6321 bool HOptimizedGraphBuilder::PropertyAccessInfo::CanAccessAsMonomorphic(
6322     SmallMapList* maps) {
6323   DCHECK(map_.is_identical_to(maps->first()));
6324   if (!CanAccessMonomorphic()) return false;
6325   STATIC_ASSERT(kMaxLoadPolymorphism == kMaxStorePolymorphism);
6326   if (maps->length() > kMaxLoadPolymorphism) return false;
6327   HObjectAccess access = HObjectAccess::ForMap();  // bogus default
6328   if (GetJSObjectFieldAccess(&access)) {
6329     for (int i = 1; i < maps->length(); ++i) {
6330       PropertyAccessInfo test_info(builder_, access_type_, maps->at(i), name_);
6331       HObjectAccess test_access = HObjectAccess::ForMap();  // bogus default
6332       if (!test_info.GetJSObjectFieldAccess(&test_access)) return false;
6333       if (!access.Equals(test_access)) return false;
6334     }
6335     return true;
6336   }
6337   if (GetJSArrayBufferViewFieldAccess(&access)) {
6338     for (int i = 1; i < maps->length(); ++i) {
6339       PropertyAccessInfo test_info(builder_, access_type_, maps->at(i), name_);
6340       HObjectAccess test_access = HObjectAccess::ForMap();  // bogus default
6341       if (!test_info.GetJSArrayBufferViewFieldAccess(&test_access)) {
6342         return false;
6343       }
6344       if (!access.Equals(test_access)) return false;
6345     }
6346     return true;
6347   }
6348
6349   // Currently only handle numbers as a polymorphic case.
6350   // TODO(verwaest): Support monomorphic handling of numbers with a HCheckNumber
6351   // instruction.
6352   if (IsNumberType()) return false;
6353
6354   // Multiple maps cannot transition to the same target map.
6355   DCHECK(!IsLoad() || !IsTransition());
6356   if (IsTransition() && maps->length() > 1) return false;
6357
6358   for (int i = 1; i < maps->length(); ++i) {
6359     PropertyAccessInfo test_info(builder_, access_type_, maps->at(i), name_);
6360     if (!test_info.IsCompatible(this)) return false;
6361   }
6362
6363   return true;
6364 }
6365
6366
6367 Handle<Map> HOptimizedGraphBuilder::PropertyAccessInfo::map() {
6368   JSFunction* ctor = IC::GetRootConstructor(
6369       *map_, current_info()->closure()->context()->native_context());
6370   if (ctor != NULL) return handle(ctor->initial_map());
6371   return map_;
6372 }
6373
6374
6375 static bool NeedsWrapping(Handle<Map> map, Handle<JSFunction> target) {
6376   return !map->IsJSObjectMap() &&
6377          is_sloppy(target->shared()->language_mode()) &&
6378          !target->shared()->native();
6379 }
6380
6381
6382 bool HOptimizedGraphBuilder::PropertyAccessInfo::NeedsWrappingFor(
6383     Handle<JSFunction> target) const {
6384   return NeedsWrapping(map_, target);
6385 }
6386
6387
6388 HValue* HOptimizedGraphBuilder::BuildMonomorphicAccess(
6389     PropertyAccessInfo* info, HValue* object, HValue* checked_object,
6390     HValue* value, BailoutId ast_id, BailoutId return_id,
6391     bool can_inline_accessor) {
6392   HObjectAccess access = HObjectAccess::ForMap();  // bogus default
6393   if (info->GetJSObjectFieldAccess(&access)) {
6394     DCHECK(info->IsLoad());
6395     return New<HLoadNamedField>(object, checked_object, access);
6396   }
6397
6398   if (info->GetJSArrayBufferViewFieldAccess(&access)) {
6399     DCHECK(info->IsLoad());
6400     checked_object = Add<HCheckArrayBufferNotNeutered>(checked_object);
6401     return New<HLoadNamedField>(object, checked_object, access);
6402   }
6403
6404   if (info->name().is_identical_to(isolate()->factory()->prototype_string()) &&
6405       info->map()->function_with_prototype()) {
6406     DCHECK(!info->map()->has_non_instance_prototype());
6407     return New<HLoadFunctionPrototype>(checked_object);
6408   }
6409
6410   HValue* checked_holder = checked_object;
6411   if (info->has_holder()) {
6412     Handle<JSObject> prototype(JSObject::cast(info->map()->prototype()));
6413     checked_holder = BuildCheckPrototypeMaps(prototype, info->holder());
6414   }
6415
6416   if (!info->IsFound()) {
6417     DCHECK(info->IsLoad());
6418     if (is_strong(function_language_mode())) {
6419       return New<HCallRuntime>(
6420           isolate()->factory()->empty_string(),
6421           Runtime::FunctionForId(Runtime::kThrowStrongModeImplicitConversion),
6422           0);
6423     } else {
6424       return graph()->GetConstantUndefined();
6425     }
6426   }
6427
6428   if (info->IsData()) {
6429     if (info->IsLoad()) {
6430       return BuildLoadNamedField(info, checked_holder);
6431     } else {
6432       return BuildStoreNamedField(info, checked_object, value);
6433     }
6434   }
6435
6436   if (info->IsTransition()) {
6437     DCHECK(!info->IsLoad());
6438     return BuildStoreNamedField(info, checked_object, value);
6439   }
6440
6441   if (info->IsAccessorConstant()) {
6442     Push(checked_object);
6443     int argument_count = 1;
6444     if (!info->IsLoad()) {
6445       argument_count = 2;
6446       Push(value);
6447     }
6448
6449     if (info->NeedsWrappingFor(info->accessor())) {
6450       HValue* function = Add<HConstant>(info->accessor());
6451       PushArgumentsFromEnvironment(argument_count);
6452       return New<HCallFunction>(function, argument_count, WRAP_AND_CALL);
6453     } else if (FLAG_inline_accessors && can_inline_accessor) {
6454       bool success = info->IsLoad()
6455           ? TryInlineGetter(info->accessor(), info->map(), ast_id, return_id)
6456           : TryInlineSetter(
6457               info->accessor(), info->map(), ast_id, return_id, value);
6458       if (success || HasStackOverflow()) return NULL;
6459     }
6460
6461     PushArgumentsFromEnvironment(argument_count);
6462     return BuildCallConstantFunction(info->accessor(), argument_count);
6463   }
6464
6465   DCHECK(info->IsDataConstant());
6466   if (info->IsLoad()) {
6467     return New<HConstant>(info->constant());
6468   } else {
6469     return New<HCheckValue>(value, Handle<JSFunction>::cast(info->constant()));
6470   }
6471 }
6472
6473
6474 void HOptimizedGraphBuilder::HandlePolymorphicNamedFieldAccess(
6475     PropertyAccessType access_type, Expression* expr, BailoutId ast_id,
6476     BailoutId return_id, HValue* object, HValue* value, SmallMapList* maps,
6477     Handle<String> name) {
6478   // Something did not match; must use a polymorphic load.
6479   int count = 0;
6480   HBasicBlock* join = NULL;
6481   HBasicBlock* number_block = NULL;
6482   bool handled_string = false;
6483
6484   bool handle_smi = false;
6485   STATIC_ASSERT(kMaxLoadPolymorphism == kMaxStorePolymorphism);
6486   int i;
6487   for (i = 0; i < maps->length() && count < kMaxLoadPolymorphism; ++i) {
6488     PropertyAccessInfo info(this, access_type, maps->at(i), name);
6489     if (info.IsStringType()) {
6490       if (handled_string) continue;
6491       handled_string = true;
6492     }
6493     if (info.CanAccessMonomorphic()) {
6494       count++;
6495       if (info.IsNumberType()) {
6496         handle_smi = true;
6497         break;
6498       }
6499     }
6500   }
6501
6502   if (i < maps->length()) {
6503     count = -1;
6504     maps->Clear();
6505   } else {
6506     count = 0;
6507   }
6508   HControlInstruction* smi_check = NULL;
6509   handled_string = false;
6510
6511   for (i = 0; i < maps->length() && count < kMaxLoadPolymorphism; ++i) {
6512     PropertyAccessInfo info(this, access_type, maps->at(i), name);
6513     if (info.IsStringType()) {
6514       if (handled_string) continue;
6515       handled_string = true;
6516     }
6517     if (!info.CanAccessMonomorphic()) continue;
6518
6519     if (count == 0) {
6520       join = graph()->CreateBasicBlock();
6521       if (handle_smi) {
6522         HBasicBlock* empty_smi_block = graph()->CreateBasicBlock();
6523         HBasicBlock* not_smi_block = graph()->CreateBasicBlock();
6524         number_block = graph()->CreateBasicBlock();
6525         smi_check = New<HIsSmiAndBranch>(
6526             object, empty_smi_block, not_smi_block);
6527         FinishCurrentBlock(smi_check);
6528         GotoNoSimulate(empty_smi_block, number_block);
6529         set_current_block(not_smi_block);
6530       } else {
6531         BuildCheckHeapObject(object);
6532       }
6533     }
6534     ++count;
6535     HBasicBlock* if_true = graph()->CreateBasicBlock();
6536     HBasicBlock* if_false = graph()->CreateBasicBlock();
6537     HUnaryControlInstruction* compare;
6538
6539     HValue* dependency;
6540     if (info.IsNumberType()) {
6541       Handle<Map> heap_number_map = isolate()->factory()->heap_number_map();
6542       compare = New<HCompareMap>(object, heap_number_map, if_true, if_false);
6543       dependency = smi_check;
6544     } else if (info.IsStringType()) {
6545       compare = New<HIsStringAndBranch>(object, if_true, if_false);
6546       dependency = compare;
6547     } else {
6548       compare = New<HCompareMap>(object, info.map(), if_true, if_false);
6549       dependency = compare;
6550     }
6551     FinishCurrentBlock(compare);
6552
6553     if (info.IsNumberType()) {
6554       GotoNoSimulate(if_true, number_block);
6555       if_true = number_block;
6556     }
6557
6558     set_current_block(if_true);
6559
6560     HValue* access =
6561         BuildMonomorphicAccess(&info, object, dependency, value, ast_id,
6562                                return_id, FLAG_polymorphic_inlining);
6563
6564     HValue* result = NULL;
6565     switch (access_type) {
6566       case LOAD:
6567         result = access;
6568         break;
6569       case STORE:
6570         result = value;
6571         break;
6572     }
6573
6574     if (access == NULL) {
6575       if (HasStackOverflow()) return;
6576     } else {
6577       if (access->IsInstruction()) {
6578         HInstruction* instr = HInstruction::cast(access);
6579         if (!instr->IsLinked()) AddInstruction(instr);
6580       }
6581       if (!ast_context()->IsEffect()) Push(result);
6582     }
6583
6584     if (current_block() != NULL) Goto(join);
6585     set_current_block(if_false);
6586   }
6587
6588   // Finish up.  Unconditionally deoptimize if we've handled all the maps we
6589   // know about and do not want to handle ones we've never seen.  Otherwise
6590   // use a generic IC.
6591   if (count == maps->length() && FLAG_deoptimize_uncommon_cases) {
6592     FinishExitWithHardDeoptimization(
6593         Deoptimizer::kUnknownMapInPolymorphicAccess);
6594   } else {
6595     HInstruction* instr = BuildNamedGeneric(access_type, expr, object, name,
6596                                             value);
6597     AddInstruction(instr);
6598     if (!ast_context()->IsEffect()) Push(access_type == LOAD ? instr : value);
6599
6600     if (join != NULL) {
6601       Goto(join);
6602     } else {
6603       Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6604       if (!ast_context()->IsEffect()) ast_context()->ReturnValue(Pop());
6605       return;
6606     }
6607   }
6608
6609   DCHECK(join != NULL);
6610   if (join->HasPredecessor()) {
6611     join->SetJoinId(ast_id);
6612     set_current_block(join);
6613     if (!ast_context()->IsEffect()) ast_context()->ReturnValue(Pop());
6614   } else {
6615     set_current_block(NULL);
6616   }
6617 }
6618
6619
6620 static bool ComputeReceiverTypes(Expression* expr,
6621                                  HValue* receiver,
6622                                  SmallMapList** t,
6623                                  Zone* zone) {
6624   SmallMapList* maps = expr->GetReceiverTypes();
6625   *t = maps;
6626   bool monomorphic = expr->IsMonomorphic();
6627   if (maps != NULL && receiver->HasMonomorphicJSObjectType()) {
6628     Map* root_map = receiver->GetMonomorphicJSObjectMap()->FindRootMap();
6629     maps->FilterForPossibleTransitions(root_map);
6630     monomorphic = maps->length() == 1;
6631   }
6632   return monomorphic && CanInlinePropertyAccess(maps->first());
6633 }
6634
6635
6636 static bool AreStringTypes(SmallMapList* maps) {
6637   for (int i = 0; i < maps->length(); i++) {
6638     if (maps->at(i)->instance_type() >= FIRST_NONSTRING_TYPE) return false;
6639   }
6640   return true;
6641 }
6642
6643
6644 void HOptimizedGraphBuilder::BuildStore(Expression* expr,
6645                                         Property* prop,
6646                                         BailoutId ast_id,
6647                                         BailoutId return_id,
6648                                         bool is_uninitialized) {
6649   if (!prop->key()->IsPropertyName()) {
6650     // Keyed store.
6651     HValue* value = Pop();
6652     HValue* key = Pop();
6653     HValue* object = Pop();
6654     bool has_side_effects = false;
6655     HValue* result = HandleKeyedElementAccess(
6656         object, key, value, expr, ast_id, return_id, STORE, &has_side_effects);
6657     if (has_side_effects) {
6658       if (!ast_context()->IsEffect()) Push(value);
6659       Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6660       if (!ast_context()->IsEffect()) Drop(1);
6661     }
6662     if (result == NULL) return;
6663     return ast_context()->ReturnValue(value);
6664   }
6665
6666   // Named store.
6667   HValue* value = Pop();
6668   HValue* object = Pop();
6669
6670   Literal* key = prop->key()->AsLiteral();
6671   Handle<String> name = Handle<String>::cast(key->value());
6672   DCHECK(!name.is_null());
6673
6674   HValue* access = BuildNamedAccess(STORE, ast_id, return_id, expr, object,
6675                                     name, value, is_uninitialized);
6676   if (access == NULL) return;
6677
6678   if (!ast_context()->IsEffect()) Push(value);
6679   if (access->IsInstruction()) AddInstruction(HInstruction::cast(access));
6680   if (access->HasObservableSideEffects()) {
6681     Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6682   }
6683   if (!ast_context()->IsEffect()) Drop(1);
6684   return ast_context()->ReturnValue(value);
6685 }
6686
6687
6688 void HOptimizedGraphBuilder::HandlePropertyAssignment(Assignment* expr) {
6689   Property* prop = expr->target()->AsProperty();
6690   DCHECK(prop != NULL);
6691   CHECK_ALIVE(VisitForValue(prop->obj()));
6692   if (!prop->key()->IsPropertyName()) {
6693     CHECK_ALIVE(VisitForValue(prop->key()));
6694   }
6695   CHECK_ALIVE(VisitForValue(expr->value()));
6696   BuildStore(expr, prop, expr->id(),
6697              expr->AssignmentId(), expr->IsUninitialized());
6698 }
6699
6700
6701 // Because not every expression has a position and there is not common
6702 // superclass of Assignment and CountOperation, we cannot just pass the
6703 // owning expression instead of position and ast_id separately.
6704 void HOptimizedGraphBuilder::HandleGlobalVariableAssignment(
6705     Variable* var,
6706     HValue* value,
6707     BailoutId ast_id) {
6708   Handle<GlobalObject> global(current_info()->global_object());
6709
6710   // Lookup in script contexts.
6711   {
6712     Handle<ScriptContextTable> script_contexts(
6713         global->native_context()->script_context_table());
6714     ScriptContextTable::LookupResult lookup;
6715     if (ScriptContextTable::Lookup(script_contexts, var->name(), &lookup)) {
6716       if (lookup.mode == CONST) {
6717         return Bailout(kNonInitializerAssignmentToConst);
6718       }
6719       Handle<Context> script_context =
6720           ScriptContextTable::GetContext(script_contexts, lookup.context_index);
6721
6722       Handle<Object> current_value =
6723           FixedArray::get(script_context, lookup.slot_index);
6724
6725       // If the values is not the hole, it will stay initialized,
6726       // so no need to generate a check.
6727       if (*current_value == *isolate()->factory()->the_hole_value()) {
6728         return Bailout(kReferenceToUninitializedVariable);
6729       }
6730
6731       HStoreNamedField* instr = Add<HStoreNamedField>(
6732           Add<HConstant>(script_context),
6733           HObjectAccess::ForContextSlot(lookup.slot_index), value);
6734       USE(instr);
6735       DCHECK(instr->HasObservableSideEffects());
6736       Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6737       return;
6738     }
6739   }
6740
6741   LookupIterator it(global, var->name(), LookupIterator::OWN);
6742   GlobalPropertyAccess type = LookupGlobalProperty(var, &it, STORE);
6743   if (type == kUseCell) {
6744     Handle<PropertyCell> cell = it.GetPropertyCell();
6745     top_info()->dependencies()->AssumePropertyCell(cell);
6746     auto cell_type = it.property_details().cell_type();
6747     if (cell_type == PropertyCellType::kConstant ||
6748         cell_type == PropertyCellType::kUndefined) {
6749       Handle<Object> constant(cell->value(), isolate());
6750       if (value->IsConstant()) {
6751         HConstant* c_value = HConstant::cast(value);
6752         if (!constant.is_identical_to(c_value->handle(isolate()))) {
6753           Add<HDeoptimize>(Deoptimizer::kConstantGlobalVariableAssignment,
6754                            Deoptimizer::EAGER);
6755         }
6756       } else {
6757         HValue* c_constant = Add<HConstant>(constant);
6758         IfBuilder builder(this);
6759         if (constant->IsNumber()) {
6760           builder.If<HCompareNumericAndBranch>(value, c_constant, Token::EQ);
6761         } else {
6762           builder.If<HCompareObjectEqAndBranch>(value, c_constant);
6763         }
6764         builder.Then();
6765         builder.Else();
6766         Add<HDeoptimize>(Deoptimizer::kConstantGlobalVariableAssignment,
6767                          Deoptimizer::EAGER);
6768         builder.End();
6769       }
6770     }
6771     HConstant* cell_constant = Add<HConstant>(cell);
6772     auto access = HObjectAccess::ForPropertyCellValue();
6773     if (cell_type == PropertyCellType::kConstantType) {
6774       switch (cell->GetConstantType()) {
6775         case PropertyCellConstantType::kSmi:
6776           access = access.WithRepresentation(Representation::Smi());
6777           break;
6778         case PropertyCellConstantType::kStableMap: {
6779           // The map may no longer be stable, deopt if it's ever different from
6780           // what is currently there, which will allow for restablization.
6781           Handle<Map> map(HeapObject::cast(cell->value())->map());
6782           Add<HCheckHeapObject>(value);
6783           value = Add<HCheckMaps>(value, map);
6784           access = access.WithRepresentation(Representation::HeapObject());
6785           break;
6786         }
6787       }
6788     }
6789     HInstruction* instr = Add<HStoreNamedField>(cell_constant, access, value);
6790     instr->ClearChangesFlag(kInobjectFields);
6791     instr->SetChangesFlag(kGlobalVars);
6792     if (instr->HasObservableSideEffects()) {
6793       Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6794     }
6795   } else if (var->IsGlobalSlot()) {
6796     DCHECK(var->index() > 0);
6797     DCHECK(var->IsStaticGlobalObjectProperty());
6798     int slot_index = var->index();
6799     int depth = scope()->ContextChainLength(var->scope());
6800
6801     HStoreGlobalViaContext* instr = Add<HStoreGlobalViaContext>(
6802         value, depth, slot_index, function_language_mode());
6803     USE(instr);
6804     DCHECK(instr->HasObservableSideEffects());
6805     Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6806
6807   } else {
6808     HValue* global_object = Add<HLoadNamedField>(
6809         context(), nullptr,
6810         HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
6811     HStoreNamedGeneric* instr =
6812         Add<HStoreNamedGeneric>(global_object, var->name(), value,
6813                                 function_language_mode(), PREMONOMORPHIC);
6814     USE(instr);
6815     DCHECK(instr->HasObservableSideEffects());
6816     Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6817   }
6818 }
6819
6820
6821 void HOptimizedGraphBuilder::HandleCompoundAssignment(Assignment* expr) {
6822   Expression* target = expr->target();
6823   VariableProxy* proxy = target->AsVariableProxy();
6824   Property* prop = target->AsProperty();
6825   DCHECK(proxy == NULL || prop == NULL);
6826
6827   // We have a second position recorded in the FullCodeGenerator to have
6828   // type feedback for the binary operation.
6829   BinaryOperation* operation = expr->binary_operation();
6830
6831   if (proxy != NULL) {
6832     Variable* var = proxy->var();
6833     if (var->mode() == LET)  {
6834       return Bailout(kUnsupportedLetCompoundAssignment);
6835     }
6836
6837     CHECK_ALIVE(VisitForValue(operation));
6838
6839     switch (var->location()) {
6840       case VariableLocation::GLOBAL:
6841       case VariableLocation::UNALLOCATED:
6842         HandleGlobalVariableAssignment(var,
6843                                        Top(),
6844                                        expr->AssignmentId());
6845         break;
6846
6847       case VariableLocation::PARAMETER:
6848       case VariableLocation::LOCAL:
6849         if (var->mode() == CONST_LEGACY)  {
6850           return Bailout(kUnsupportedConstCompoundAssignment);
6851         }
6852         if (var->mode() == CONST) {
6853           return Bailout(kNonInitializerAssignmentToConst);
6854         }
6855         BindIfLive(var, Top());
6856         break;
6857
6858       case VariableLocation::CONTEXT: {
6859         // Bail out if we try to mutate a parameter value in a function
6860         // using the arguments object.  We do not (yet) correctly handle the
6861         // arguments property of the function.
6862         if (current_info()->scope()->arguments() != NULL) {
6863           // Parameters will be allocated to context slots.  We have no
6864           // direct way to detect that the variable is a parameter so we do
6865           // a linear search of the parameter variables.
6866           int count = current_info()->scope()->num_parameters();
6867           for (int i = 0; i < count; ++i) {
6868             if (var == current_info()->scope()->parameter(i)) {
6869               Bailout(kAssignmentToParameterFunctionUsesArgumentsObject);
6870             }
6871           }
6872         }
6873
6874         HStoreContextSlot::Mode mode;
6875
6876         switch (var->mode()) {
6877           case LET:
6878             mode = HStoreContextSlot::kCheckDeoptimize;
6879             break;
6880           case CONST:
6881             return Bailout(kNonInitializerAssignmentToConst);
6882           case CONST_LEGACY:
6883             return ast_context()->ReturnValue(Pop());
6884           default:
6885             mode = HStoreContextSlot::kNoCheck;
6886         }
6887
6888         HValue* context = BuildContextChainWalk(var);
6889         HStoreContextSlot* instr = Add<HStoreContextSlot>(
6890             context, var->index(), mode, Top());
6891         if (instr->HasObservableSideEffects()) {
6892           Add<HSimulate>(expr->AssignmentId(), REMOVABLE_SIMULATE);
6893         }
6894         break;
6895       }
6896
6897       case VariableLocation::LOOKUP:
6898         return Bailout(kCompoundAssignmentToLookupSlot);
6899     }
6900     return ast_context()->ReturnValue(Pop());
6901
6902   } else if (prop != NULL) {
6903     CHECK_ALIVE(VisitForValue(prop->obj()));
6904     HValue* object = Top();
6905     HValue* key = NULL;
6906     if (!prop->key()->IsPropertyName() || prop->IsStringAccess()) {
6907       CHECK_ALIVE(VisitForValue(prop->key()));
6908       key = Top();
6909     }
6910
6911     CHECK_ALIVE(PushLoad(prop, object, key));
6912
6913     CHECK_ALIVE(VisitForValue(expr->value()));
6914     HValue* right = Pop();
6915     HValue* left = Pop();
6916
6917     Push(BuildBinaryOperation(operation, left, right, PUSH_BEFORE_SIMULATE));
6918
6919     BuildStore(expr, prop, expr->id(),
6920                expr->AssignmentId(), expr->IsUninitialized());
6921   } else {
6922     return Bailout(kInvalidLhsInCompoundAssignment);
6923   }
6924 }
6925
6926
6927 void HOptimizedGraphBuilder::VisitAssignment(Assignment* expr) {
6928   DCHECK(!HasStackOverflow());
6929   DCHECK(current_block() != NULL);
6930   DCHECK(current_block()->HasPredecessor());
6931   VariableProxy* proxy = expr->target()->AsVariableProxy();
6932   Property* prop = expr->target()->AsProperty();
6933   DCHECK(proxy == NULL || prop == NULL);
6934
6935   if (expr->is_compound()) {
6936     HandleCompoundAssignment(expr);
6937     return;
6938   }
6939
6940   if (prop != NULL) {
6941     HandlePropertyAssignment(expr);
6942   } else if (proxy != NULL) {
6943     Variable* var = proxy->var();
6944
6945     if (var->mode() == CONST) {
6946       if (expr->op() != Token::INIT_CONST) {
6947         return Bailout(kNonInitializerAssignmentToConst);
6948       }
6949     } else if (var->mode() == CONST_LEGACY) {
6950       if (expr->op() != Token::INIT_CONST_LEGACY) {
6951         CHECK_ALIVE(VisitForValue(expr->value()));
6952         return ast_context()->ReturnValue(Pop());
6953       }
6954
6955       if (var->IsStackAllocated()) {
6956         // We insert a use of the old value to detect unsupported uses of const
6957         // variables (e.g. initialization inside a loop).
6958         HValue* old_value = environment()->Lookup(var);
6959         Add<HUseConst>(old_value);
6960       }
6961     }
6962
6963     if (proxy->IsArguments()) return Bailout(kAssignmentToArguments);
6964
6965     // Handle the assignment.
6966     switch (var->location()) {
6967       case VariableLocation::GLOBAL:
6968       case VariableLocation::UNALLOCATED:
6969         CHECK_ALIVE(VisitForValue(expr->value()));
6970         HandleGlobalVariableAssignment(var,
6971                                        Top(),
6972                                        expr->AssignmentId());
6973         return ast_context()->ReturnValue(Pop());
6974
6975       case VariableLocation::PARAMETER:
6976       case VariableLocation::LOCAL: {
6977         // Perform an initialization check for let declared variables
6978         // or parameters.
6979         if (var->mode() == LET && expr->op() == Token::ASSIGN) {
6980           HValue* env_value = environment()->Lookup(var);
6981           if (env_value == graph()->GetConstantHole()) {
6982             return Bailout(kAssignmentToLetVariableBeforeInitialization);
6983           }
6984         }
6985         // We do not allow the arguments object to occur in a context where it
6986         // may escape, but assignments to stack-allocated locals are
6987         // permitted.
6988         CHECK_ALIVE(VisitForValue(expr->value(), ARGUMENTS_ALLOWED));
6989         HValue* value = Pop();
6990         BindIfLive(var, value);
6991         return ast_context()->ReturnValue(value);
6992       }
6993
6994       case VariableLocation::CONTEXT: {
6995         // Bail out if we try to mutate a parameter value in a function using
6996         // the arguments object.  We do not (yet) correctly handle the
6997         // arguments property of the function.
6998         if (current_info()->scope()->arguments() != NULL) {
6999           // Parameters will rewrite to context slots.  We have no direct way
7000           // to detect that the variable is a parameter.
7001           int count = current_info()->scope()->num_parameters();
7002           for (int i = 0; i < count; ++i) {
7003             if (var == current_info()->scope()->parameter(i)) {
7004               return Bailout(kAssignmentToParameterInArgumentsObject);
7005             }
7006           }
7007         }
7008
7009         CHECK_ALIVE(VisitForValue(expr->value()));
7010         HStoreContextSlot::Mode mode;
7011         if (expr->op() == Token::ASSIGN) {
7012           switch (var->mode()) {
7013             case LET:
7014               mode = HStoreContextSlot::kCheckDeoptimize;
7015               break;
7016             case CONST:
7017               // This case is checked statically so no need to
7018               // perform checks here
7019               UNREACHABLE();
7020             case CONST_LEGACY:
7021               return ast_context()->ReturnValue(Pop());
7022             default:
7023               mode = HStoreContextSlot::kNoCheck;
7024           }
7025         } else if (expr->op() == Token::INIT_VAR ||
7026                    expr->op() == Token::INIT_LET ||
7027                    expr->op() == Token::INIT_CONST) {
7028           mode = HStoreContextSlot::kNoCheck;
7029         } else {
7030           DCHECK(expr->op() == Token::INIT_CONST_LEGACY);
7031
7032           mode = HStoreContextSlot::kCheckIgnoreAssignment;
7033         }
7034
7035         HValue* context = BuildContextChainWalk(var);
7036         HStoreContextSlot* instr = Add<HStoreContextSlot>(
7037             context, var->index(), mode, Top());
7038         if (instr->HasObservableSideEffects()) {
7039           Add<HSimulate>(expr->AssignmentId(), REMOVABLE_SIMULATE);
7040         }
7041         return ast_context()->ReturnValue(Pop());
7042       }
7043
7044       case VariableLocation::LOOKUP:
7045         return Bailout(kAssignmentToLOOKUPVariable);
7046     }
7047   } else {
7048     return Bailout(kInvalidLeftHandSideInAssignment);
7049   }
7050 }
7051
7052
7053 void HOptimizedGraphBuilder::VisitYield(Yield* expr) {
7054   // Generators are not optimized, so we should never get here.
7055   UNREACHABLE();
7056 }
7057
7058
7059 void HOptimizedGraphBuilder::VisitThrow(Throw* expr) {
7060   DCHECK(!HasStackOverflow());
7061   DCHECK(current_block() != NULL);
7062   DCHECK(current_block()->HasPredecessor());
7063   if (!ast_context()->IsEffect()) {
7064     // The parser turns invalid left-hand sides in assignments into throw
7065     // statements, which may not be in effect contexts. We might still try
7066     // to optimize such functions; bail out now if we do.
7067     return Bailout(kInvalidLeftHandSideInAssignment);
7068   }
7069   CHECK_ALIVE(VisitForValue(expr->exception()));
7070
7071   HValue* value = environment()->Pop();
7072   if (!top_info()->is_tracking_positions()) SetSourcePosition(expr->position());
7073   Add<HPushArguments>(value);
7074   Add<HCallRuntime>(isolate()->factory()->empty_string(),
7075                     Runtime::FunctionForId(Runtime::kThrow), 1);
7076   Add<HSimulate>(expr->id());
7077
7078   // If the throw definitely exits the function, we can finish with a dummy
7079   // control flow at this point.  This is not the case if the throw is inside
7080   // an inlined function which may be replaced.
7081   if (call_context() == NULL) {
7082     FinishExitCurrentBlock(New<HAbnormalExit>());
7083   }
7084 }
7085
7086
7087 HInstruction* HGraphBuilder::AddLoadStringInstanceType(HValue* string) {
7088   if (string->IsConstant()) {
7089     HConstant* c_string = HConstant::cast(string);
7090     if (c_string->HasStringValue()) {
7091       return Add<HConstant>(c_string->StringValue()->map()->instance_type());
7092     }
7093   }
7094   return Add<HLoadNamedField>(
7095       Add<HLoadNamedField>(string, nullptr, HObjectAccess::ForMap()), nullptr,
7096       HObjectAccess::ForMapInstanceType());
7097 }
7098
7099
7100 HInstruction* HGraphBuilder::AddLoadStringLength(HValue* string) {
7101   return AddInstruction(BuildLoadStringLength(string));
7102 }
7103
7104
7105 HInstruction* HGraphBuilder::BuildLoadStringLength(HValue* string) {
7106   if (string->IsConstant()) {
7107     HConstant* c_string = HConstant::cast(string);
7108     if (c_string->HasStringValue()) {
7109       return New<HConstant>(c_string->StringValue()->length());
7110     }
7111   }
7112   return New<HLoadNamedField>(string, nullptr,
7113                               HObjectAccess::ForStringLength());
7114 }
7115
7116
7117 HInstruction* HOptimizedGraphBuilder::BuildNamedGeneric(
7118     PropertyAccessType access_type, Expression* expr, HValue* object,
7119     Handle<String> name, HValue* value, bool is_uninitialized) {
7120   if (is_uninitialized) {
7121     Add<HDeoptimize>(
7122         Deoptimizer::kInsufficientTypeFeedbackForGenericNamedAccess,
7123         Deoptimizer::SOFT);
7124   }
7125   if (access_type == LOAD) {
7126     Handle<TypeFeedbackVector> vector =
7127         handle(current_feedback_vector(), isolate());
7128     FeedbackVectorICSlot slot = expr->AsProperty()->PropertyFeedbackSlot();
7129
7130     if (!expr->AsProperty()->key()->IsPropertyName()) {
7131       // It's possible that a keyed load of a constant string was converted
7132       // to a named load. Here, at the last minute, we need to make sure to
7133       // use a generic Keyed Load if we are using the type vector, because
7134       // it has to share information with full code.
7135       HConstant* key = Add<HConstant>(name);
7136       HLoadKeyedGeneric* result = New<HLoadKeyedGeneric>(
7137           object, key, function_language_mode(), PREMONOMORPHIC);
7138       result->SetVectorAndSlot(vector, slot);
7139       return result;
7140     }
7141
7142     HLoadNamedGeneric* result = New<HLoadNamedGeneric>(
7143         object, name, function_language_mode(), PREMONOMORPHIC);
7144     result->SetVectorAndSlot(vector, slot);
7145     return result;
7146   } else {
7147     return New<HStoreNamedGeneric>(object, name, value,
7148                                    function_language_mode(), PREMONOMORPHIC);
7149   }
7150 }
7151
7152
7153
7154 HInstruction* HOptimizedGraphBuilder::BuildKeyedGeneric(
7155     PropertyAccessType access_type,
7156     Expression* expr,
7157     HValue* object,
7158     HValue* key,
7159     HValue* value) {
7160   if (access_type == LOAD) {
7161     InlineCacheState initial_state = expr->AsProperty()->GetInlineCacheState();
7162     HLoadKeyedGeneric* result = New<HLoadKeyedGeneric>(
7163         object, key, function_language_mode(), initial_state);
7164     // HLoadKeyedGeneric with vector ics benefits from being encoded as
7165     // MEGAMORPHIC because the vector/slot combo becomes unnecessary.
7166     if (initial_state != MEGAMORPHIC) {
7167       // We need to pass vector information.
7168       Handle<TypeFeedbackVector> vector =
7169           handle(current_feedback_vector(), isolate());
7170       FeedbackVectorICSlot slot = expr->AsProperty()->PropertyFeedbackSlot();
7171       result->SetVectorAndSlot(vector, slot);
7172     }
7173     return result;
7174   } else {
7175     return New<HStoreKeyedGeneric>(object, key, value, function_language_mode(),
7176                                    PREMONOMORPHIC);
7177   }
7178 }
7179
7180
7181 LoadKeyedHoleMode HOptimizedGraphBuilder::BuildKeyedHoleMode(Handle<Map> map) {
7182   // Loads from a "stock" fast holey double arrays can elide the hole check.
7183   // Loads from a "stock" fast holey array can convert the hole to undefined
7184   // with impunity.
7185   LoadKeyedHoleMode load_mode = NEVER_RETURN_HOLE;
7186   bool holey_double_elements =
7187       *map == isolate()->get_initial_js_array_map(FAST_HOLEY_DOUBLE_ELEMENTS);
7188   bool holey_elements =
7189       *map == isolate()->get_initial_js_array_map(FAST_HOLEY_ELEMENTS);
7190   if ((holey_double_elements || holey_elements) &&
7191       isolate()->IsFastArrayConstructorPrototypeChainIntact()) {
7192     load_mode =
7193         holey_double_elements ? ALLOW_RETURN_HOLE : CONVERT_HOLE_TO_UNDEFINED;
7194
7195     Handle<JSObject> prototype(JSObject::cast(map->prototype()), isolate());
7196     Handle<JSObject> object_prototype = isolate()->initial_object_prototype();
7197     BuildCheckPrototypeMaps(prototype, object_prototype);
7198     graph()->MarkDependsOnEmptyArrayProtoElements();
7199   }
7200   return load_mode;
7201 }
7202
7203
7204 HInstruction* HOptimizedGraphBuilder::BuildMonomorphicElementAccess(
7205     HValue* object,
7206     HValue* key,
7207     HValue* val,
7208     HValue* dependency,
7209     Handle<Map> map,
7210     PropertyAccessType access_type,
7211     KeyedAccessStoreMode store_mode) {
7212   HCheckMaps* checked_object = Add<HCheckMaps>(object, map, dependency);
7213
7214   if (access_type == STORE && map->prototype()->IsJSObject()) {
7215     // monomorphic stores need a prototype chain check because shape
7216     // changes could allow callbacks on elements in the chain that
7217     // aren't compatible with monomorphic keyed stores.
7218     PrototypeIterator iter(map);
7219     JSObject* holder = NULL;
7220     while (!iter.IsAtEnd()) {
7221       holder = JSObject::cast(*PrototypeIterator::GetCurrent(iter));
7222       iter.Advance();
7223     }
7224     DCHECK(holder && holder->IsJSObject());
7225
7226     BuildCheckPrototypeMaps(handle(JSObject::cast(map->prototype())),
7227                             Handle<JSObject>(holder));
7228   }
7229
7230   LoadKeyedHoleMode load_mode = BuildKeyedHoleMode(map);
7231   return BuildUncheckedMonomorphicElementAccess(
7232       checked_object, key, val,
7233       map->instance_type() == JS_ARRAY_TYPE,
7234       map->elements_kind(), access_type,
7235       load_mode, store_mode);
7236 }
7237
7238
7239 static bool CanInlineElementAccess(Handle<Map> map) {
7240   return map->IsJSObjectMap() && !map->has_dictionary_elements() &&
7241          !map->has_sloppy_arguments_elements() &&
7242          !map->has_indexed_interceptor() && !map->is_access_check_needed();
7243 }
7244
7245
7246 HInstruction* HOptimizedGraphBuilder::TryBuildConsolidatedElementLoad(
7247     HValue* object,
7248     HValue* key,
7249     HValue* val,
7250     SmallMapList* maps) {
7251   // For polymorphic loads of similar elements kinds (i.e. all tagged or all
7252   // double), always use the "worst case" code without a transition.  This is
7253   // much faster than transitioning the elements to the worst case, trading a
7254   // HTransitionElements for a HCheckMaps, and avoiding mutation of the array.
7255   bool has_double_maps = false;
7256   bool has_smi_or_object_maps = false;
7257   bool has_js_array_access = false;
7258   bool has_non_js_array_access = false;
7259   bool has_seen_holey_elements = false;
7260   Handle<Map> most_general_consolidated_map;
7261   for (int i = 0; i < maps->length(); ++i) {
7262     Handle<Map> map = maps->at(i);
7263     if (!CanInlineElementAccess(map)) return NULL;
7264     // Don't allow mixing of JSArrays with JSObjects.
7265     if (map->instance_type() == JS_ARRAY_TYPE) {
7266       if (has_non_js_array_access) return NULL;
7267       has_js_array_access = true;
7268     } else if (has_js_array_access) {
7269       return NULL;
7270     } else {
7271       has_non_js_array_access = true;
7272     }
7273     // Don't allow mixed, incompatible elements kinds.
7274     if (map->has_fast_double_elements()) {
7275       if (has_smi_or_object_maps) return NULL;
7276       has_double_maps = true;
7277     } else if (map->has_fast_smi_or_object_elements()) {
7278       if (has_double_maps) return NULL;
7279       has_smi_or_object_maps = true;
7280     } else {
7281       return NULL;
7282     }
7283     // Remember if we've ever seen holey elements.
7284     if (IsHoleyElementsKind(map->elements_kind())) {
7285       has_seen_holey_elements = true;
7286     }
7287     // Remember the most general elements kind, the code for its load will
7288     // properly handle all of the more specific cases.
7289     if ((i == 0) || IsMoreGeneralElementsKindTransition(
7290             most_general_consolidated_map->elements_kind(),
7291             map->elements_kind())) {
7292       most_general_consolidated_map = map;
7293     }
7294   }
7295   if (!has_double_maps && !has_smi_or_object_maps) return NULL;
7296
7297   HCheckMaps* checked_object = Add<HCheckMaps>(object, maps);
7298   // FAST_ELEMENTS is considered more general than FAST_HOLEY_SMI_ELEMENTS.
7299   // If we've seen both, the consolidated load must use FAST_HOLEY_ELEMENTS.
7300   ElementsKind consolidated_elements_kind = has_seen_holey_elements
7301       ? GetHoleyElementsKind(most_general_consolidated_map->elements_kind())
7302       : most_general_consolidated_map->elements_kind();
7303   HInstruction* instr = BuildUncheckedMonomorphicElementAccess(
7304       checked_object, key, val,
7305       most_general_consolidated_map->instance_type() == JS_ARRAY_TYPE,
7306       consolidated_elements_kind,
7307       LOAD, NEVER_RETURN_HOLE, STANDARD_STORE);
7308   return instr;
7309 }
7310
7311
7312 HValue* HOptimizedGraphBuilder::HandlePolymorphicElementAccess(
7313     Expression* expr,
7314     HValue* object,
7315     HValue* key,
7316     HValue* val,
7317     SmallMapList* maps,
7318     PropertyAccessType access_type,
7319     KeyedAccessStoreMode store_mode,
7320     bool* has_side_effects) {
7321   *has_side_effects = false;
7322   BuildCheckHeapObject(object);
7323
7324   if (access_type == LOAD) {
7325     HInstruction* consolidated_load =
7326         TryBuildConsolidatedElementLoad(object, key, val, maps);
7327     if (consolidated_load != NULL) {
7328       *has_side_effects |= consolidated_load->HasObservableSideEffects();
7329       return consolidated_load;
7330     }
7331   }
7332
7333   // Elements_kind transition support.
7334   MapHandleList transition_target(maps->length());
7335   // Collect possible transition targets.
7336   MapHandleList possible_transitioned_maps(maps->length());
7337   for (int i = 0; i < maps->length(); ++i) {
7338     Handle<Map> map = maps->at(i);
7339     // Loads from strings or loads with a mix of string and non-string maps
7340     // shouldn't be handled polymorphically.
7341     DCHECK(access_type != LOAD || !map->IsStringMap());
7342     ElementsKind elements_kind = map->elements_kind();
7343     if (CanInlineElementAccess(map) && IsFastElementsKind(elements_kind) &&
7344         elements_kind != GetInitialFastElementsKind()) {
7345       possible_transitioned_maps.Add(map);
7346     }
7347     if (IsSloppyArgumentsElements(elements_kind)) {
7348       HInstruction* result = BuildKeyedGeneric(access_type, expr, object, key,
7349                                                val);
7350       *has_side_effects = result->HasObservableSideEffects();
7351       return AddInstruction(result);
7352     }
7353   }
7354   // Get transition target for each map (NULL == no transition).
7355   for (int i = 0; i < maps->length(); ++i) {
7356     Handle<Map> map = maps->at(i);
7357     Handle<Map> transitioned_map =
7358         Map::FindTransitionedMap(map, &possible_transitioned_maps);
7359     transition_target.Add(transitioned_map);
7360   }
7361
7362   MapHandleList untransitionable_maps(maps->length());
7363   HTransitionElementsKind* transition = NULL;
7364   for (int i = 0; i < maps->length(); ++i) {
7365     Handle<Map> map = maps->at(i);
7366     DCHECK(map->IsMap());
7367     if (!transition_target.at(i).is_null()) {
7368       DCHECK(Map::IsValidElementsTransition(
7369           map->elements_kind(),
7370           transition_target.at(i)->elements_kind()));
7371       transition = Add<HTransitionElementsKind>(object, map,
7372                                                 transition_target.at(i));
7373     } else {
7374       untransitionable_maps.Add(map);
7375     }
7376   }
7377
7378   // If only one map is left after transitioning, handle this case
7379   // monomorphically.
7380   DCHECK(untransitionable_maps.length() >= 1);
7381   if (untransitionable_maps.length() == 1) {
7382     Handle<Map> untransitionable_map = untransitionable_maps[0];
7383     HInstruction* instr = NULL;
7384     if (!CanInlineElementAccess(untransitionable_map)) {
7385       instr = AddInstruction(BuildKeyedGeneric(access_type, expr, object, key,
7386                                                val));
7387     } else {
7388       instr = BuildMonomorphicElementAccess(
7389           object, key, val, transition, untransitionable_map, access_type,
7390           store_mode);
7391     }
7392     *has_side_effects |= instr->HasObservableSideEffects();
7393     return access_type == STORE ? val : instr;
7394   }
7395
7396   HBasicBlock* join = graph()->CreateBasicBlock();
7397
7398   for (int i = 0; i < untransitionable_maps.length(); ++i) {
7399     Handle<Map> map = untransitionable_maps[i];
7400     ElementsKind elements_kind = map->elements_kind();
7401     HBasicBlock* this_map = graph()->CreateBasicBlock();
7402     HBasicBlock* other_map = graph()->CreateBasicBlock();
7403     HCompareMap* mapcompare =
7404         New<HCompareMap>(object, map, this_map, other_map);
7405     FinishCurrentBlock(mapcompare);
7406
7407     set_current_block(this_map);
7408     HInstruction* access = NULL;
7409     if (!CanInlineElementAccess(map)) {
7410       access = AddInstruction(BuildKeyedGeneric(access_type, expr, object, key,
7411                                                 val));
7412     } else {
7413       DCHECK(IsFastElementsKind(elements_kind) ||
7414              IsExternalArrayElementsKind(elements_kind) ||
7415              IsFixedTypedArrayElementsKind(elements_kind));
7416       LoadKeyedHoleMode load_mode = BuildKeyedHoleMode(map);
7417       // Happily, mapcompare is a checked object.
7418       access = BuildUncheckedMonomorphicElementAccess(
7419           mapcompare, key, val,
7420           map->instance_type() == JS_ARRAY_TYPE,
7421           elements_kind, access_type,
7422           load_mode,
7423           store_mode);
7424     }
7425     *has_side_effects |= access->HasObservableSideEffects();
7426     // The caller will use has_side_effects and add a correct Simulate.
7427     access->SetFlag(HValue::kHasNoObservableSideEffects);
7428     if (access_type == LOAD) {
7429       Push(access);
7430     }
7431     NoObservableSideEffectsScope scope(this);
7432     GotoNoSimulate(join);
7433     set_current_block(other_map);
7434   }
7435
7436   // Ensure that we visited at least one map above that goes to join. This is
7437   // necessary because FinishExitWithHardDeoptimization does an AbnormalExit
7438   // rather than joining the join block. If this becomes an issue, insert a
7439   // generic access in the case length() == 0.
7440   DCHECK(join->predecessors()->length() > 0);
7441   // Deopt if none of the cases matched.
7442   NoObservableSideEffectsScope scope(this);
7443   FinishExitWithHardDeoptimization(
7444       Deoptimizer::kUnknownMapInPolymorphicElementAccess);
7445   set_current_block(join);
7446   return access_type == STORE ? val : Pop();
7447 }
7448
7449
7450 HValue* HOptimizedGraphBuilder::HandleKeyedElementAccess(
7451     HValue* obj, HValue* key, HValue* val, Expression* expr, BailoutId ast_id,
7452     BailoutId return_id, PropertyAccessType access_type,
7453     bool* has_side_effects) {
7454   if (key->ActualValue()->IsConstant()) {
7455     Handle<Object> constant =
7456         HConstant::cast(key->ActualValue())->handle(isolate());
7457     uint32_t array_index;
7458     if (constant->IsString() &&
7459         !Handle<String>::cast(constant)->AsArrayIndex(&array_index)) {
7460       if (!constant->IsUniqueName()) {
7461         constant = isolate()->factory()->InternalizeString(
7462             Handle<String>::cast(constant));
7463       }
7464       HValue* access =
7465           BuildNamedAccess(access_type, ast_id, return_id, expr, obj,
7466                            Handle<String>::cast(constant), val, false);
7467       if (access == NULL || access->IsPhi() ||
7468           HInstruction::cast(access)->IsLinked()) {
7469         *has_side_effects = false;
7470       } else {
7471         HInstruction* instr = HInstruction::cast(access);
7472         AddInstruction(instr);
7473         *has_side_effects = instr->HasObservableSideEffects();
7474       }
7475       return access;
7476     }
7477   }
7478
7479   DCHECK(!expr->IsPropertyName());
7480   HInstruction* instr = NULL;
7481
7482   SmallMapList* maps;
7483   bool monomorphic = ComputeReceiverTypes(expr, obj, &maps, zone());
7484
7485   bool force_generic = false;
7486   if (expr->GetKeyType() == PROPERTY) {
7487     // Non-Generic accesses assume that elements are being accessed, and will
7488     // deopt for non-index keys, which the IC knows will occur.
7489     // TODO(jkummerow): Consider adding proper support for property accesses.
7490     force_generic = true;
7491     monomorphic = false;
7492   } else if (access_type == STORE &&
7493              (monomorphic || (maps != NULL && !maps->is_empty()))) {
7494     // Stores can't be mono/polymorphic if their prototype chain has dictionary
7495     // elements. However a receiver map that has dictionary elements itself
7496     // should be left to normal mono/poly behavior (the other maps may benefit
7497     // from highly optimized stores).
7498     for (int i = 0; i < maps->length(); i++) {
7499       Handle<Map> current_map = maps->at(i);
7500       if (current_map->DictionaryElementsInPrototypeChainOnly()) {
7501         force_generic = true;
7502         monomorphic = false;
7503         break;
7504       }
7505     }
7506   } else if (access_type == LOAD && !monomorphic &&
7507              (maps != NULL && !maps->is_empty())) {
7508     // Polymorphic loads have to go generic if any of the maps are strings.
7509     // If some, but not all of the maps are strings, we should go generic
7510     // because polymorphic access wants to key on ElementsKind and isn't
7511     // compatible with strings.
7512     for (int i = 0; i < maps->length(); i++) {
7513       Handle<Map> current_map = maps->at(i);
7514       if (current_map->IsStringMap()) {
7515         force_generic = true;
7516         break;
7517       }
7518     }
7519   }
7520
7521   if (monomorphic) {
7522     Handle<Map> map = maps->first();
7523     if (!CanInlineElementAccess(map)) {
7524       instr = AddInstruction(BuildKeyedGeneric(access_type, expr, obj, key,
7525                                                val));
7526     } else {
7527       BuildCheckHeapObject(obj);
7528       instr = BuildMonomorphicElementAccess(
7529           obj, key, val, NULL, map, access_type, expr->GetStoreMode());
7530     }
7531   } else if (!force_generic && (maps != NULL && !maps->is_empty())) {
7532     return HandlePolymorphicElementAccess(expr, obj, key, val, maps,
7533                                           access_type, expr->GetStoreMode(),
7534                                           has_side_effects);
7535   } else {
7536     if (access_type == STORE) {
7537       if (expr->IsAssignment() &&
7538           expr->AsAssignment()->HasNoTypeInformation()) {
7539         Add<HDeoptimize>(Deoptimizer::kInsufficientTypeFeedbackForKeyedStore,
7540                          Deoptimizer::SOFT);
7541       }
7542     } else {
7543       if (expr->AsProperty()->HasNoTypeInformation()) {
7544         Add<HDeoptimize>(Deoptimizer::kInsufficientTypeFeedbackForKeyedLoad,
7545                          Deoptimizer::SOFT);
7546       }
7547     }
7548     instr = AddInstruction(BuildKeyedGeneric(access_type, expr, obj, key, val));
7549   }
7550   *has_side_effects = instr->HasObservableSideEffects();
7551   return instr;
7552 }
7553
7554
7555 void HOptimizedGraphBuilder::EnsureArgumentsArePushedForAccess() {
7556   // Outermost function already has arguments on the stack.
7557   if (function_state()->outer() == NULL) return;
7558
7559   if (function_state()->arguments_pushed()) return;
7560
7561   // Push arguments when entering inlined function.
7562   HEnterInlined* entry = function_state()->entry();
7563   entry->set_arguments_pushed();
7564
7565   HArgumentsObject* arguments = entry->arguments_object();
7566   const ZoneList<HValue*>* arguments_values = arguments->arguments_values();
7567
7568   HInstruction* insert_after = entry;
7569   for (int i = 0; i < arguments_values->length(); i++) {
7570     HValue* argument = arguments_values->at(i);
7571     HInstruction* push_argument = New<HPushArguments>(argument);
7572     push_argument->InsertAfter(insert_after);
7573     insert_after = push_argument;
7574   }
7575
7576   HArgumentsElements* arguments_elements = New<HArgumentsElements>(true);
7577   arguments_elements->ClearFlag(HValue::kUseGVN);
7578   arguments_elements->InsertAfter(insert_after);
7579   function_state()->set_arguments_elements(arguments_elements);
7580 }
7581
7582
7583 bool HOptimizedGraphBuilder::TryArgumentsAccess(Property* expr) {
7584   VariableProxy* proxy = expr->obj()->AsVariableProxy();
7585   if (proxy == NULL) return false;
7586   if (!proxy->var()->IsStackAllocated()) return false;
7587   if (!environment()->Lookup(proxy->var())->CheckFlag(HValue::kIsArguments)) {
7588     return false;
7589   }
7590
7591   HInstruction* result = NULL;
7592   if (expr->key()->IsPropertyName()) {
7593     Handle<String> name = expr->key()->AsLiteral()->AsPropertyName();
7594     if (!String::Equals(name, isolate()->factory()->length_string())) {
7595       return false;
7596     }
7597
7598     if (function_state()->outer() == NULL) {
7599       HInstruction* elements = Add<HArgumentsElements>(false);
7600       result = New<HArgumentsLength>(elements);
7601     } else {
7602       // Number of arguments without receiver.
7603       int argument_count = environment()->
7604           arguments_environment()->parameter_count() - 1;
7605       result = New<HConstant>(argument_count);
7606     }
7607   } else {
7608     Push(graph()->GetArgumentsObject());
7609     CHECK_ALIVE_OR_RETURN(VisitForValue(expr->key()), true);
7610     HValue* key = Pop();
7611     Drop(1);  // Arguments object.
7612     if (function_state()->outer() == NULL) {
7613       HInstruction* elements = Add<HArgumentsElements>(false);
7614       HInstruction* length = Add<HArgumentsLength>(elements);
7615       HInstruction* checked_key = Add<HBoundsCheck>(key, length);
7616       result = New<HAccessArgumentsAt>(elements, length, checked_key);
7617     } else {
7618       EnsureArgumentsArePushedForAccess();
7619
7620       // Number of arguments without receiver.
7621       HInstruction* elements = function_state()->arguments_elements();
7622       int argument_count = environment()->
7623           arguments_environment()->parameter_count() - 1;
7624       HInstruction* length = Add<HConstant>(argument_count);
7625       HInstruction* checked_key = Add<HBoundsCheck>(key, length);
7626       result = New<HAccessArgumentsAt>(elements, length, checked_key);
7627     }
7628   }
7629   ast_context()->ReturnInstruction(result, expr->id());
7630   return true;
7631 }
7632
7633
7634 HValue* HOptimizedGraphBuilder::BuildNamedAccess(
7635     PropertyAccessType access, BailoutId ast_id, BailoutId return_id,
7636     Expression* expr, HValue* object, Handle<String> name, HValue* value,
7637     bool is_uninitialized) {
7638   SmallMapList* maps;
7639   ComputeReceiverTypes(expr, object, &maps, zone());
7640   DCHECK(maps != NULL);
7641
7642   if (maps->length() > 0) {
7643     PropertyAccessInfo info(this, access, maps->first(), name);
7644     if (!info.CanAccessAsMonomorphic(maps)) {
7645       HandlePolymorphicNamedFieldAccess(access, expr, ast_id, return_id, object,
7646                                         value, maps, name);
7647       return NULL;
7648     }
7649
7650     HValue* checked_object;
7651     // Type::Number() is only supported by polymorphic load/call handling.
7652     DCHECK(!info.IsNumberType());
7653     BuildCheckHeapObject(object);
7654     if (AreStringTypes(maps)) {
7655       checked_object =
7656           Add<HCheckInstanceType>(object, HCheckInstanceType::IS_STRING);
7657     } else {
7658       checked_object = Add<HCheckMaps>(object, maps);
7659     }
7660     return BuildMonomorphicAccess(
7661         &info, object, checked_object, value, ast_id, return_id);
7662   }
7663
7664   return BuildNamedGeneric(access, expr, object, name, value, is_uninitialized);
7665 }
7666
7667
7668 void HOptimizedGraphBuilder::PushLoad(Property* expr,
7669                                       HValue* object,
7670                                       HValue* key) {
7671   ValueContext for_value(this, ARGUMENTS_NOT_ALLOWED);
7672   Push(object);
7673   if (key != NULL) Push(key);
7674   BuildLoad(expr, expr->LoadId());
7675 }
7676
7677
7678 void HOptimizedGraphBuilder::BuildLoad(Property* expr,
7679                                        BailoutId ast_id) {
7680   HInstruction* instr = NULL;
7681   if (expr->IsStringAccess()) {
7682     HValue* index = Pop();
7683     HValue* string = Pop();
7684     HInstruction* char_code = BuildStringCharCodeAt(string, index);
7685     AddInstruction(char_code);
7686     instr = NewUncasted<HStringCharFromCode>(char_code);
7687
7688   } else if (expr->key()->IsPropertyName()) {
7689     Handle<String> name = expr->key()->AsLiteral()->AsPropertyName();
7690     HValue* object = Pop();
7691
7692     HValue* value = BuildNamedAccess(LOAD, ast_id, expr->LoadId(), expr, object,
7693                                      name, NULL, expr->IsUninitialized());
7694     if (value == NULL) return;
7695     if (value->IsPhi()) return ast_context()->ReturnValue(value);
7696     instr = HInstruction::cast(value);
7697     if (instr->IsLinked()) return ast_context()->ReturnValue(instr);
7698
7699   } else {
7700     HValue* key = Pop();
7701     HValue* obj = Pop();
7702
7703     bool has_side_effects = false;
7704     HValue* load = HandleKeyedElementAccess(
7705         obj, key, NULL, expr, ast_id, expr->LoadId(), LOAD, &has_side_effects);
7706     if (has_side_effects) {
7707       if (ast_context()->IsEffect()) {
7708         Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
7709       } else {
7710         Push(load);
7711         Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
7712         Drop(1);
7713       }
7714     }
7715     if (load == NULL) return;
7716     return ast_context()->ReturnValue(load);
7717   }
7718   return ast_context()->ReturnInstruction(instr, ast_id);
7719 }
7720
7721
7722 void HOptimizedGraphBuilder::VisitProperty(Property* expr) {
7723   DCHECK(!HasStackOverflow());
7724   DCHECK(current_block() != NULL);
7725   DCHECK(current_block()->HasPredecessor());
7726
7727   if (TryArgumentsAccess(expr)) return;
7728
7729   CHECK_ALIVE(VisitForValue(expr->obj()));
7730   if (!expr->key()->IsPropertyName() || expr->IsStringAccess()) {
7731     CHECK_ALIVE(VisitForValue(expr->key()));
7732   }
7733
7734   BuildLoad(expr, expr->id());
7735 }
7736
7737
7738 HInstruction* HGraphBuilder::BuildConstantMapCheck(Handle<JSObject> constant) {
7739   HCheckMaps* check = Add<HCheckMaps>(
7740       Add<HConstant>(constant), handle(constant->map()));
7741   check->ClearDependsOnFlag(kElementsKind);
7742   return check;
7743 }
7744
7745
7746 HInstruction* HGraphBuilder::BuildCheckPrototypeMaps(Handle<JSObject> prototype,
7747                                                      Handle<JSObject> holder) {
7748   PrototypeIterator iter(isolate(), prototype,
7749                          PrototypeIterator::START_AT_RECEIVER);
7750   while (holder.is_null() ||
7751          !PrototypeIterator::GetCurrent(iter).is_identical_to(holder)) {
7752     BuildConstantMapCheck(
7753         Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter)));
7754     iter.Advance();
7755     if (iter.IsAtEnd()) {
7756       return NULL;
7757     }
7758   }
7759   return BuildConstantMapCheck(
7760       Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter)));
7761 }
7762
7763
7764 void HOptimizedGraphBuilder::AddCheckPrototypeMaps(Handle<JSObject> holder,
7765                                                    Handle<Map> receiver_map) {
7766   if (!holder.is_null()) {
7767     Handle<JSObject> prototype(JSObject::cast(receiver_map->prototype()));
7768     BuildCheckPrototypeMaps(prototype, holder);
7769   }
7770 }
7771
7772
7773 HInstruction* HOptimizedGraphBuilder::NewPlainFunctionCall(
7774     HValue* fun, int argument_count, bool pass_argument_count) {
7775   return New<HCallJSFunction>(fun, argument_count, pass_argument_count);
7776 }
7777
7778
7779 HInstruction* HOptimizedGraphBuilder::NewArgumentAdaptorCall(
7780     HValue* fun, HValue* context,
7781     int argument_count, HValue* expected_param_count) {
7782   ArgumentAdaptorDescriptor descriptor(isolate());
7783   HValue* arity = Add<HConstant>(argument_count - 1);
7784
7785   HValue* op_vals[] = { context, fun, arity, expected_param_count };
7786
7787   Handle<Code> adaptor =
7788       isolate()->builtins()->ArgumentsAdaptorTrampoline();
7789   HConstant* adaptor_value = Add<HConstant>(adaptor);
7790
7791   return New<HCallWithDescriptor>(adaptor_value, argument_count, descriptor,
7792                                   Vector<HValue*>(op_vals, arraysize(op_vals)));
7793 }
7794
7795
7796 HInstruction* HOptimizedGraphBuilder::BuildCallConstantFunction(
7797     Handle<JSFunction> jsfun, int argument_count) {
7798   HValue* target = Add<HConstant>(jsfun);
7799   // For constant functions, we try to avoid calling the
7800   // argument adaptor and instead call the function directly
7801   int formal_parameter_count =
7802       jsfun->shared()->internal_formal_parameter_count();
7803   bool dont_adapt_arguments =
7804       (formal_parameter_count ==
7805        SharedFunctionInfo::kDontAdaptArgumentsSentinel);
7806   int arity = argument_count - 1;
7807   bool can_invoke_directly =
7808       dont_adapt_arguments || formal_parameter_count == arity;
7809   if (can_invoke_directly) {
7810     if (jsfun.is_identical_to(current_info()->closure())) {
7811       graph()->MarkRecursive();
7812     }
7813     return NewPlainFunctionCall(target, argument_count, dont_adapt_arguments);
7814   } else {
7815     HValue* param_count_value = Add<HConstant>(formal_parameter_count);
7816     HValue* context = Add<HLoadNamedField>(
7817         target, nullptr, HObjectAccess::ForFunctionContextPointer());
7818     return NewArgumentAdaptorCall(target, context,
7819         argument_count, param_count_value);
7820   }
7821   UNREACHABLE();
7822   return NULL;
7823 }
7824
7825
7826 class FunctionSorter {
7827  public:
7828   explicit FunctionSorter(int index = 0, int ticks = 0, int size = 0)
7829       : index_(index), ticks_(ticks), size_(size) {}
7830
7831   int index() const { return index_; }
7832   int ticks() const { return ticks_; }
7833   int size() const { return size_; }
7834
7835  private:
7836   int index_;
7837   int ticks_;
7838   int size_;
7839 };
7840
7841
7842 inline bool operator<(const FunctionSorter& lhs, const FunctionSorter& rhs) {
7843   int diff = lhs.ticks() - rhs.ticks();
7844   if (diff != 0) return diff > 0;
7845   return lhs.size() < rhs.size();
7846 }
7847
7848
7849 void HOptimizedGraphBuilder::HandlePolymorphicCallNamed(Call* expr,
7850                                                         HValue* receiver,
7851                                                         SmallMapList* maps,
7852                                                         Handle<String> name) {
7853   int argument_count = expr->arguments()->length() + 1;  // Includes receiver.
7854   FunctionSorter order[kMaxCallPolymorphism];
7855
7856   bool handle_smi = false;
7857   bool handled_string = false;
7858   int ordered_functions = 0;
7859
7860   int i;
7861   for (i = 0; i < maps->length() && ordered_functions < kMaxCallPolymorphism;
7862        ++i) {
7863     PropertyAccessInfo info(this, LOAD, maps->at(i), name);
7864     if (info.CanAccessMonomorphic() && info.IsDataConstant() &&
7865         info.constant()->IsJSFunction()) {
7866       if (info.IsStringType()) {
7867         if (handled_string) continue;
7868         handled_string = true;
7869       }
7870       Handle<JSFunction> target = Handle<JSFunction>::cast(info.constant());
7871       if (info.IsNumberType()) {
7872         handle_smi = true;
7873       }
7874       expr->set_target(target);
7875       order[ordered_functions++] = FunctionSorter(
7876           i, target->shared()->profiler_ticks(), InliningAstSize(target));
7877     }
7878   }
7879
7880   std::sort(order, order + ordered_functions);
7881
7882   if (i < maps->length()) {
7883     maps->Clear();
7884     ordered_functions = -1;
7885   }
7886
7887   HBasicBlock* number_block = NULL;
7888   HBasicBlock* join = NULL;
7889   handled_string = false;
7890   int count = 0;
7891
7892   for (int fn = 0; fn < ordered_functions; ++fn) {
7893     int i = order[fn].index();
7894     PropertyAccessInfo info(this, LOAD, maps->at(i), name);
7895     if (info.IsStringType()) {
7896       if (handled_string) continue;
7897       handled_string = true;
7898     }
7899     // Reloads the target.
7900     info.CanAccessMonomorphic();
7901     Handle<JSFunction> target = Handle<JSFunction>::cast(info.constant());
7902
7903     expr->set_target(target);
7904     if (count == 0) {
7905       // Only needed once.
7906       join = graph()->CreateBasicBlock();
7907       if (handle_smi) {
7908         HBasicBlock* empty_smi_block = graph()->CreateBasicBlock();
7909         HBasicBlock* not_smi_block = graph()->CreateBasicBlock();
7910         number_block = graph()->CreateBasicBlock();
7911         FinishCurrentBlock(New<HIsSmiAndBranch>(
7912                 receiver, empty_smi_block, not_smi_block));
7913         GotoNoSimulate(empty_smi_block, number_block);
7914         set_current_block(not_smi_block);
7915       } else {
7916         BuildCheckHeapObject(receiver);
7917       }
7918     }
7919     ++count;
7920     HBasicBlock* if_true = graph()->CreateBasicBlock();
7921     HBasicBlock* if_false = graph()->CreateBasicBlock();
7922     HUnaryControlInstruction* compare;
7923
7924     Handle<Map> map = info.map();
7925     if (info.IsNumberType()) {
7926       Handle<Map> heap_number_map = isolate()->factory()->heap_number_map();
7927       compare = New<HCompareMap>(receiver, heap_number_map, if_true, if_false);
7928     } else if (info.IsStringType()) {
7929       compare = New<HIsStringAndBranch>(receiver, if_true, if_false);
7930     } else {
7931       compare = New<HCompareMap>(receiver, map, if_true, if_false);
7932     }
7933     FinishCurrentBlock(compare);
7934
7935     if (info.IsNumberType()) {
7936       GotoNoSimulate(if_true, number_block);
7937       if_true = number_block;
7938     }
7939
7940     set_current_block(if_true);
7941
7942     AddCheckPrototypeMaps(info.holder(), map);
7943
7944     HValue* function = Add<HConstant>(expr->target());
7945     environment()->SetExpressionStackAt(0, function);
7946     Push(receiver);
7947     CHECK_ALIVE(VisitExpressions(expr->arguments()));
7948     bool needs_wrapping = info.NeedsWrappingFor(target);
7949     bool try_inline = FLAG_polymorphic_inlining && !needs_wrapping;
7950     if (FLAG_trace_inlining && try_inline) {
7951       Handle<JSFunction> caller = current_info()->closure();
7952       base::SmartArrayPointer<char> caller_name =
7953           caller->shared()->DebugName()->ToCString();
7954       PrintF("Trying to inline the polymorphic call to %s from %s\n",
7955              name->ToCString().get(),
7956              caller_name.get());
7957     }
7958     if (try_inline && TryInlineCall(expr)) {
7959       // Trying to inline will signal that we should bailout from the
7960       // entire compilation by setting stack overflow on the visitor.
7961       if (HasStackOverflow()) return;
7962     } else {
7963       // Since HWrapReceiver currently cannot actually wrap numbers and strings,
7964       // use the regular CallFunctionStub for method calls to wrap the receiver.
7965       // TODO(verwaest): Support creation of value wrappers directly in
7966       // HWrapReceiver.
7967       HInstruction* call = needs_wrapping
7968           ? NewUncasted<HCallFunction>(
7969               function, argument_count, WRAP_AND_CALL)
7970           : BuildCallConstantFunction(target, argument_count);
7971       PushArgumentsFromEnvironment(argument_count);
7972       AddInstruction(call);
7973       Drop(1);  // Drop the function.
7974       if (!ast_context()->IsEffect()) Push(call);
7975     }
7976
7977     if (current_block() != NULL) Goto(join);
7978     set_current_block(if_false);
7979   }
7980
7981   // Finish up.  Unconditionally deoptimize if we've handled all the maps we
7982   // know about and do not want to handle ones we've never seen.  Otherwise
7983   // use a generic IC.
7984   if (ordered_functions == maps->length() && FLAG_deoptimize_uncommon_cases) {
7985     FinishExitWithHardDeoptimization(Deoptimizer::kUnknownMapInPolymorphicCall);
7986   } else {
7987     Property* prop = expr->expression()->AsProperty();
7988     HInstruction* function = BuildNamedGeneric(
7989         LOAD, prop, receiver, name, NULL, prop->IsUninitialized());
7990     AddInstruction(function);
7991     Push(function);
7992     AddSimulate(prop->LoadId(), REMOVABLE_SIMULATE);
7993
7994     environment()->SetExpressionStackAt(1, function);
7995     environment()->SetExpressionStackAt(0, receiver);
7996     CHECK_ALIVE(VisitExpressions(expr->arguments()));
7997
7998     CallFunctionFlags flags = receiver->type().IsJSObject()
7999         ? NO_CALL_FUNCTION_FLAGS : CALL_AS_METHOD;
8000     HInstruction* call = New<HCallFunction>(
8001         function, argument_count, flags);
8002
8003     PushArgumentsFromEnvironment(argument_count);
8004
8005     Drop(1);  // Function.
8006
8007     if (join != NULL) {
8008       AddInstruction(call);
8009       if (!ast_context()->IsEffect()) Push(call);
8010       Goto(join);
8011     } else {
8012       return ast_context()->ReturnInstruction(call, expr->id());
8013     }
8014   }
8015
8016   // We assume that control flow is always live after an expression.  So
8017   // even without predecessors to the join block, we set it as the exit
8018   // block and continue by adding instructions there.
8019   DCHECK(join != NULL);
8020   if (join->HasPredecessor()) {
8021     set_current_block(join);
8022     join->SetJoinId(expr->id());
8023     if (!ast_context()->IsEffect()) return ast_context()->ReturnValue(Pop());
8024   } else {
8025     set_current_block(NULL);
8026   }
8027 }
8028
8029
8030 void HOptimizedGraphBuilder::TraceInline(Handle<JSFunction> target,
8031                                          Handle<JSFunction> caller,
8032                                          const char* reason) {
8033   if (FLAG_trace_inlining) {
8034     base::SmartArrayPointer<char> target_name =
8035         target->shared()->DebugName()->ToCString();
8036     base::SmartArrayPointer<char> caller_name =
8037         caller->shared()->DebugName()->ToCString();
8038     if (reason == NULL) {
8039       PrintF("Inlined %s called from %s.\n", target_name.get(),
8040              caller_name.get());
8041     } else {
8042       PrintF("Did not inline %s called from %s (%s).\n",
8043              target_name.get(), caller_name.get(), reason);
8044     }
8045   }
8046 }
8047
8048
8049 static const int kNotInlinable = 1000000000;
8050
8051
8052 int HOptimizedGraphBuilder::InliningAstSize(Handle<JSFunction> target) {
8053   if (!FLAG_use_inlining) return kNotInlinable;
8054
8055   // Precondition: call is monomorphic and we have found a target with the
8056   // appropriate arity.
8057   Handle<JSFunction> caller = current_info()->closure();
8058   Handle<SharedFunctionInfo> target_shared(target->shared());
8059
8060   // Always inline functions that force inlining.
8061   if (target_shared->force_inline()) {
8062     return 0;
8063   }
8064   if (target->IsBuiltin()) {
8065     return kNotInlinable;
8066   }
8067
8068   if (target_shared->IsApiFunction()) {
8069     TraceInline(target, caller, "target is api function");
8070     return kNotInlinable;
8071   }
8072
8073   // Do a quick check on source code length to avoid parsing large
8074   // inlining candidates.
8075   if (target_shared->SourceSize() >
8076       Min(FLAG_max_inlined_source_size, kUnlimitedMaxInlinedSourceSize)) {
8077     TraceInline(target, caller, "target text too big");
8078     return kNotInlinable;
8079   }
8080
8081   // Target must be inlineable.
8082   if (!target_shared->IsInlineable()) {
8083     TraceInline(target, caller, "target not inlineable");
8084     return kNotInlinable;
8085   }
8086   if (target_shared->disable_optimization_reason() != kNoReason) {
8087     TraceInline(target, caller, "target contains unsupported syntax [early]");
8088     return kNotInlinable;
8089   }
8090
8091   int nodes_added = target_shared->ast_node_count();
8092   return nodes_added;
8093 }
8094
8095
8096 bool HOptimizedGraphBuilder::TryInline(Handle<JSFunction> target,
8097                                        int arguments_count,
8098                                        HValue* implicit_return_value,
8099                                        BailoutId ast_id, BailoutId return_id,
8100                                        InliningKind inlining_kind) {
8101   if (target->context()->native_context() !=
8102       top_info()->closure()->context()->native_context()) {
8103     return false;
8104   }
8105   int nodes_added = InliningAstSize(target);
8106   if (nodes_added == kNotInlinable) return false;
8107
8108   Handle<JSFunction> caller = current_info()->closure();
8109
8110   if (nodes_added > Min(FLAG_max_inlined_nodes, kUnlimitedMaxInlinedNodes)) {
8111     TraceInline(target, caller, "target AST is too large [early]");
8112     return false;
8113   }
8114
8115   // Don't inline deeper than the maximum number of inlining levels.
8116   HEnvironment* env = environment();
8117   int current_level = 1;
8118   while (env->outer() != NULL) {
8119     if (current_level == FLAG_max_inlining_levels) {
8120       TraceInline(target, caller, "inline depth limit reached");
8121       return false;
8122     }
8123     if (env->outer()->frame_type() == JS_FUNCTION) {
8124       current_level++;
8125     }
8126     env = env->outer();
8127   }
8128
8129   // Don't inline recursive functions.
8130   for (FunctionState* state = function_state();
8131        state != NULL;
8132        state = state->outer()) {
8133     if (*state->compilation_info()->closure() == *target) {
8134       TraceInline(target, caller, "target is recursive");
8135       return false;
8136     }
8137   }
8138
8139   // We don't want to add more than a certain number of nodes from inlining.
8140   // Always inline small methods (<= 10 nodes).
8141   if (inlined_count_ > Min(FLAG_max_inlined_nodes_cumulative,
8142                            kUnlimitedMaxInlinedNodesCumulative)) {
8143     TraceInline(target, caller, "cumulative AST node limit reached");
8144     return false;
8145   }
8146
8147   // Parse and allocate variables.
8148   // Use the same AstValueFactory for creating strings in the sub-compilation
8149   // step, but don't transfer ownership to target_info.
8150   ParseInfo parse_info(zone(), target);
8151   parse_info.set_ast_value_factory(
8152       top_info()->parse_info()->ast_value_factory());
8153   parse_info.set_ast_value_factory_owned(false);
8154
8155   CompilationInfo target_info(&parse_info);
8156   Handle<SharedFunctionInfo> target_shared(target->shared());
8157   if (target_shared->HasDebugInfo()) {
8158     TraceInline(target, caller, "target is being debugged");
8159     return false;
8160   }
8161   if (!Compiler::ParseAndAnalyze(target_info.parse_info())) {
8162     if (target_info.isolate()->has_pending_exception()) {
8163       // Parse or scope error, never optimize this function.
8164       SetStackOverflow();
8165       target_shared->DisableOptimization(kParseScopeError);
8166     }
8167     TraceInline(target, caller, "parse failure");
8168     return false;
8169   }
8170
8171   if (target_info.scope()->num_heap_slots() > 0) {
8172     TraceInline(target, caller, "target has context-allocated variables");
8173     return false;
8174   }
8175   FunctionLiteral* function = target_info.function();
8176
8177   // The following conditions must be checked again after re-parsing, because
8178   // earlier the information might not have been complete due to lazy parsing.
8179   nodes_added = function->ast_node_count();
8180   if (nodes_added > Min(FLAG_max_inlined_nodes, kUnlimitedMaxInlinedNodes)) {
8181     TraceInline(target, caller, "target AST is too large [late]");
8182     return false;
8183   }
8184   if (function->dont_optimize()) {
8185     TraceInline(target, caller, "target contains unsupported syntax [late]");
8186     return false;
8187   }
8188
8189   // If the function uses the arguments object check that inlining of functions
8190   // with arguments object is enabled and the arguments-variable is
8191   // stack allocated.
8192   if (function->scope()->arguments() != NULL) {
8193     if (!FLAG_inline_arguments) {
8194       TraceInline(target, caller, "target uses arguments object");
8195       return false;
8196     }
8197   }
8198
8199   // All declarations must be inlineable.
8200   ZoneList<Declaration*>* decls = target_info.scope()->declarations();
8201   int decl_count = decls->length();
8202   for (int i = 0; i < decl_count; ++i) {
8203     if (!decls->at(i)->IsInlineable()) {
8204       TraceInline(target, caller, "target has non-trivial declaration");
8205       return false;
8206     }
8207   }
8208
8209   // Generate the deoptimization data for the unoptimized version of
8210   // the target function if we don't already have it.
8211   if (!Compiler::EnsureDeoptimizationSupport(&target_info)) {
8212     TraceInline(target, caller, "could not generate deoptimization info");
8213     return false;
8214   }
8215
8216   // In strong mode it is an error to call a function with too few arguments.
8217   // In that case do not inline because then the arity check would be skipped.
8218   if (is_strong(function->language_mode()) &&
8219       arguments_count < function->parameter_count()) {
8220     TraceInline(target, caller,
8221                 "too few arguments passed to a strong function");
8222     return false;
8223   }
8224
8225   // ----------------------------------------------------------------
8226   // After this point, we've made a decision to inline this function (so
8227   // TryInline should always return true).
8228
8229   // Type-check the inlined function.
8230   DCHECK(target_shared->has_deoptimization_support());
8231   AstTyper::Run(&target_info);
8232
8233   int inlining_id = 0;
8234   if (top_info()->is_tracking_positions()) {
8235     inlining_id = top_info()->TraceInlinedFunction(
8236         target_shared, source_position(), function_state()->inlining_id());
8237   }
8238
8239   // Save the pending call context. Set up new one for the inlined function.
8240   // The function state is new-allocated because we need to delete it
8241   // in two different places.
8242   FunctionState* target_state =
8243       new FunctionState(this, &target_info, inlining_kind, inlining_id);
8244
8245   HConstant* undefined = graph()->GetConstantUndefined();
8246
8247   HEnvironment* inner_env =
8248       environment()->CopyForInlining(target,
8249                                      arguments_count,
8250                                      function,
8251                                      undefined,
8252                                      function_state()->inlining_kind());
8253
8254   HConstant* context = Add<HConstant>(Handle<Context>(target->context()));
8255   inner_env->BindContext(context);
8256
8257   // Create a dematerialized arguments object for the function, also copy the
8258   // current arguments values to use them for materialization.
8259   HEnvironment* arguments_env = inner_env->arguments_environment();
8260   int parameter_count = arguments_env->parameter_count();
8261   HArgumentsObject* arguments_object = Add<HArgumentsObject>(parameter_count);
8262   for (int i = 0; i < parameter_count; i++) {
8263     arguments_object->AddArgument(arguments_env->Lookup(i), zone());
8264   }
8265
8266   // If the function uses arguments object then bind bind one.
8267   if (function->scope()->arguments() != NULL) {
8268     DCHECK(function->scope()->arguments()->IsStackAllocated());
8269     inner_env->Bind(function->scope()->arguments(), arguments_object);
8270   }
8271
8272   // Capture the state before invoking the inlined function for deopt in the
8273   // inlined function. This simulate has no bailout-id since it's not directly
8274   // reachable for deopt, and is only used to capture the state. If the simulate
8275   // becomes reachable by merging, the ast id of the simulate merged into it is
8276   // adopted.
8277   Add<HSimulate>(BailoutId::None());
8278
8279   current_block()->UpdateEnvironment(inner_env);
8280   Scope* saved_scope = scope();
8281   set_scope(target_info.scope());
8282   HEnterInlined* enter_inlined =
8283       Add<HEnterInlined>(return_id, target, context, arguments_count, function,
8284                          function_state()->inlining_kind(),
8285                          function->scope()->arguments(), arguments_object);
8286   if (top_info()->is_tracking_positions()) {
8287     enter_inlined->set_inlining_id(inlining_id);
8288   }
8289   function_state()->set_entry(enter_inlined);
8290
8291   VisitDeclarations(target_info.scope()->declarations());
8292   VisitStatements(function->body());
8293   set_scope(saved_scope);
8294   if (HasStackOverflow()) {
8295     // Bail out if the inline function did, as we cannot residualize a call
8296     // instead, but do not disable optimization for the outer function.
8297     TraceInline(target, caller, "inline graph construction failed");
8298     target_shared->DisableOptimization(kInliningBailedOut);
8299     current_info()->RetryOptimization(kInliningBailedOut);
8300     delete target_state;
8301     return true;
8302   }
8303
8304   // Update inlined nodes count.
8305   inlined_count_ += nodes_added;
8306
8307   Handle<Code> unoptimized_code(target_shared->code());
8308   DCHECK(unoptimized_code->kind() == Code::FUNCTION);
8309   Handle<TypeFeedbackInfo> type_info(
8310       TypeFeedbackInfo::cast(unoptimized_code->type_feedback_info()));
8311   graph()->update_type_change_checksum(type_info->own_type_change_checksum());
8312
8313   TraceInline(target, caller, NULL);
8314
8315   if (current_block() != NULL) {
8316     FunctionState* state = function_state();
8317     if (state->inlining_kind() == CONSTRUCT_CALL_RETURN) {
8318       // Falling off the end of an inlined construct call. In a test context the
8319       // return value will always evaluate to true, in a value context the
8320       // return value is the newly allocated receiver.
8321       if (call_context()->IsTest()) {
8322         Goto(inlined_test_context()->if_true(), state);
8323       } else if (call_context()->IsEffect()) {
8324         Goto(function_return(), state);
8325       } else {
8326         DCHECK(call_context()->IsValue());
8327         AddLeaveInlined(implicit_return_value, state);
8328       }
8329     } else if (state->inlining_kind() == SETTER_CALL_RETURN) {
8330       // Falling off the end of an inlined setter call. The returned value is
8331       // never used, the value of an assignment is always the value of the RHS
8332       // of the assignment.
8333       if (call_context()->IsTest()) {
8334         inlined_test_context()->ReturnValue(implicit_return_value);
8335       } else if (call_context()->IsEffect()) {
8336         Goto(function_return(), state);
8337       } else {
8338         DCHECK(call_context()->IsValue());
8339         AddLeaveInlined(implicit_return_value, state);
8340       }
8341     } else {
8342       // Falling off the end of a normal inlined function. This basically means
8343       // returning undefined.
8344       if (call_context()->IsTest()) {
8345         Goto(inlined_test_context()->if_false(), state);
8346       } else if (call_context()->IsEffect()) {
8347         Goto(function_return(), state);
8348       } else {
8349         DCHECK(call_context()->IsValue());
8350         AddLeaveInlined(undefined, state);
8351       }
8352     }
8353   }
8354
8355   // Fix up the function exits.
8356   if (inlined_test_context() != NULL) {
8357     HBasicBlock* if_true = inlined_test_context()->if_true();
8358     HBasicBlock* if_false = inlined_test_context()->if_false();
8359
8360     HEnterInlined* entry = function_state()->entry();
8361
8362     // Pop the return test context from the expression context stack.
8363     DCHECK(ast_context() == inlined_test_context());
8364     ClearInlinedTestContext();
8365     delete target_state;
8366
8367     // Forward to the real test context.
8368     if (if_true->HasPredecessor()) {
8369       entry->RegisterReturnTarget(if_true, zone());
8370       if_true->SetJoinId(ast_id);
8371       HBasicBlock* true_target = TestContext::cast(ast_context())->if_true();
8372       Goto(if_true, true_target, function_state());
8373     }
8374     if (if_false->HasPredecessor()) {
8375       entry->RegisterReturnTarget(if_false, zone());
8376       if_false->SetJoinId(ast_id);
8377       HBasicBlock* false_target = TestContext::cast(ast_context())->if_false();
8378       Goto(if_false, false_target, function_state());
8379     }
8380     set_current_block(NULL);
8381     return true;
8382
8383   } else if (function_return()->HasPredecessor()) {
8384     function_state()->entry()->RegisterReturnTarget(function_return(), zone());
8385     function_return()->SetJoinId(ast_id);
8386     set_current_block(function_return());
8387   } else {
8388     set_current_block(NULL);
8389   }
8390   delete target_state;
8391   return true;
8392 }
8393
8394
8395 bool HOptimizedGraphBuilder::TryInlineCall(Call* expr) {
8396   return TryInline(expr->target(), expr->arguments()->length(), NULL,
8397                    expr->id(), expr->ReturnId(), NORMAL_RETURN);
8398 }
8399
8400
8401 bool HOptimizedGraphBuilder::TryInlineConstruct(CallNew* expr,
8402                                                 HValue* implicit_return_value) {
8403   return TryInline(expr->target(), expr->arguments()->length(),
8404                    implicit_return_value, expr->id(), expr->ReturnId(),
8405                    CONSTRUCT_CALL_RETURN);
8406 }
8407
8408
8409 bool HOptimizedGraphBuilder::TryInlineGetter(Handle<JSFunction> getter,
8410                                              Handle<Map> receiver_map,
8411                                              BailoutId ast_id,
8412                                              BailoutId return_id) {
8413   if (TryInlineApiGetter(getter, receiver_map, ast_id)) return true;
8414   return TryInline(getter, 0, NULL, ast_id, return_id, GETTER_CALL_RETURN);
8415 }
8416
8417
8418 bool HOptimizedGraphBuilder::TryInlineSetter(Handle<JSFunction> setter,
8419                                              Handle<Map> receiver_map,
8420                                              BailoutId id,
8421                                              BailoutId assignment_id,
8422                                              HValue* implicit_return_value) {
8423   if (TryInlineApiSetter(setter, receiver_map, id)) return true;
8424   return TryInline(setter, 1, implicit_return_value, id, assignment_id,
8425                    SETTER_CALL_RETURN);
8426 }
8427
8428
8429 bool HOptimizedGraphBuilder::TryInlineIndirectCall(Handle<JSFunction> function,
8430                                                    Call* expr,
8431                                                    int arguments_count) {
8432   return TryInline(function, arguments_count, NULL, expr->id(),
8433                    expr->ReturnId(), NORMAL_RETURN);
8434 }
8435
8436
8437 bool HOptimizedGraphBuilder::TryInlineBuiltinFunctionCall(Call* expr) {
8438   if (!expr->target()->shared()->HasBuiltinFunctionId()) return false;
8439   BuiltinFunctionId id = expr->target()->shared()->builtin_function_id();
8440   switch (id) {
8441     case kMathExp:
8442       if (!FLAG_fast_math) break;
8443       // Fall through if FLAG_fast_math.
8444     case kMathRound:
8445     case kMathFround:
8446     case kMathFloor:
8447     case kMathAbs:
8448     case kMathSqrt:
8449     case kMathLog:
8450     case kMathClz32:
8451       if (expr->arguments()->length() == 1) {
8452         HValue* argument = Pop();
8453         Drop(2);  // Receiver and function.
8454         HInstruction* op = NewUncasted<HUnaryMathOperation>(argument, id);
8455         ast_context()->ReturnInstruction(op, expr->id());
8456         return true;
8457       }
8458       break;
8459     case kMathImul:
8460       if (expr->arguments()->length() == 2) {
8461         HValue* right = Pop();
8462         HValue* left = Pop();
8463         Drop(2);  // Receiver and function.
8464         HInstruction* op =
8465             HMul::NewImul(isolate(), zone(), context(), left, right);
8466         ast_context()->ReturnInstruction(op, expr->id());
8467         return true;
8468       }
8469       break;
8470     default:
8471       // Not supported for inlining yet.
8472       break;
8473   }
8474   return false;
8475 }
8476
8477
8478 // static
8479 bool HOptimizedGraphBuilder::IsReadOnlyLengthDescriptor(
8480     Handle<Map> jsarray_map) {
8481   DCHECK(!jsarray_map->is_dictionary_map());
8482   Isolate* isolate = jsarray_map->GetIsolate();
8483   Handle<Name> length_string = isolate->factory()->length_string();
8484   DescriptorArray* descriptors = jsarray_map->instance_descriptors();
8485   int number = descriptors->SearchWithCache(*length_string, *jsarray_map);
8486   DCHECK_NE(DescriptorArray::kNotFound, number);
8487   return descriptors->GetDetails(number).IsReadOnly();
8488 }
8489
8490
8491 // static
8492 bool HOptimizedGraphBuilder::CanInlineArrayResizeOperation(
8493     Handle<Map> receiver_map) {
8494   return !receiver_map.is_null() &&
8495          receiver_map->instance_type() == JS_ARRAY_TYPE &&
8496          IsFastElementsKind(receiver_map->elements_kind()) &&
8497          !receiver_map->is_dictionary_map() &&
8498          !IsReadOnlyLengthDescriptor(receiver_map) &&
8499          !receiver_map->is_observed() && receiver_map->is_extensible();
8500 }
8501
8502
8503 bool HOptimizedGraphBuilder::TryInlineBuiltinMethodCall(
8504     Call* expr, Handle<JSFunction> function, Handle<Map> receiver_map,
8505     int args_count_no_receiver) {
8506   if (!function->shared()->HasBuiltinFunctionId()) return false;
8507   BuiltinFunctionId id = function->shared()->builtin_function_id();
8508   int argument_count = args_count_no_receiver + 1;  // Plus receiver.
8509
8510   if (receiver_map.is_null()) {
8511     HValue* receiver = environment()->ExpressionStackAt(args_count_no_receiver);
8512     if (receiver->IsConstant() &&
8513         HConstant::cast(receiver)->handle(isolate())->IsHeapObject()) {
8514       receiver_map =
8515           handle(Handle<HeapObject>::cast(
8516                      HConstant::cast(receiver)->handle(isolate()))->map());
8517     }
8518   }
8519   // Try to inline calls like Math.* as operations in the calling function.
8520   switch (id) {
8521     case kStringCharCodeAt:
8522     case kStringCharAt:
8523       if (argument_count == 2) {
8524         HValue* index = Pop();
8525         HValue* string = Pop();
8526         Drop(1);  // Function.
8527         HInstruction* char_code =
8528             BuildStringCharCodeAt(string, index);
8529         if (id == kStringCharCodeAt) {
8530           ast_context()->ReturnInstruction(char_code, expr->id());
8531           return true;
8532         }
8533         AddInstruction(char_code);
8534         HInstruction* result = NewUncasted<HStringCharFromCode>(char_code);
8535         ast_context()->ReturnInstruction(result, expr->id());
8536         return true;
8537       }
8538       break;
8539     case kStringFromCharCode:
8540       if (argument_count == 2) {
8541         HValue* argument = Pop();
8542         Drop(2);  // Receiver and function.
8543         HInstruction* result = NewUncasted<HStringCharFromCode>(argument);
8544         ast_context()->ReturnInstruction(result, expr->id());
8545         return true;
8546       }
8547       break;
8548     case kMathExp:
8549       if (!FLAG_fast_math) break;
8550       // Fall through if FLAG_fast_math.
8551     case kMathRound:
8552     case kMathFround:
8553     case kMathFloor:
8554     case kMathAbs:
8555     case kMathSqrt:
8556     case kMathLog:
8557     case kMathClz32:
8558       if (argument_count == 2) {
8559         HValue* argument = Pop();
8560         Drop(2);  // Receiver and function.
8561         HInstruction* op = NewUncasted<HUnaryMathOperation>(argument, id);
8562         ast_context()->ReturnInstruction(op, expr->id());
8563         return true;
8564       }
8565       break;
8566     case kMathPow:
8567       if (argument_count == 3) {
8568         HValue* right = Pop();
8569         HValue* left = Pop();
8570         Drop(2);  // Receiver and function.
8571         HInstruction* result = NULL;
8572         // Use sqrt() if exponent is 0.5 or -0.5.
8573         if (right->IsConstant() && HConstant::cast(right)->HasDoubleValue()) {
8574           double exponent = HConstant::cast(right)->DoubleValue();
8575           if (exponent == 0.5) {
8576             result = NewUncasted<HUnaryMathOperation>(left, kMathPowHalf);
8577           } else if (exponent == -0.5) {
8578             HValue* one = graph()->GetConstant1();
8579             HInstruction* sqrt = AddUncasted<HUnaryMathOperation>(
8580                 left, kMathPowHalf);
8581             // MathPowHalf doesn't have side effects so there's no need for
8582             // an environment simulation here.
8583             DCHECK(!sqrt->HasObservableSideEffects());
8584             result = NewUncasted<HDiv>(one, sqrt);
8585           } else if (exponent == 2.0) {
8586             result = NewUncasted<HMul>(left, left);
8587           }
8588         }
8589
8590         if (result == NULL) {
8591           result = NewUncasted<HPower>(left, right);
8592         }
8593         ast_context()->ReturnInstruction(result, expr->id());
8594         return true;
8595       }
8596       break;
8597     case kMathMax:
8598     case kMathMin:
8599       if (argument_count == 3) {
8600         HValue* right = Pop();
8601         HValue* left = Pop();
8602         Drop(2);  // Receiver and function.
8603         HMathMinMax::Operation op = (id == kMathMin) ? HMathMinMax::kMathMin
8604                                                      : HMathMinMax::kMathMax;
8605         HInstruction* result = NewUncasted<HMathMinMax>(left, right, op);
8606         ast_context()->ReturnInstruction(result, expr->id());
8607         return true;
8608       }
8609       break;
8610     case kMathImul:
8611       if (argument_count == 3) {
8612         HValue* right = Pop();
8613         HValue* left = Pop();
8614         Drop(2);  // Receiver and function.
8615         HInstruction* result =
8616             HMul::NewImul(isolate(), zone(), context(), left, right);
8617         ast_context()->ReturnInstruction(result, expr->id());
8618         return true;
8619       }
8620       break;
8621     case kArrayPop: {
8622       if (!CanInlineArrayResizeOperation(receiver_map)) return false;
8623       ElementsKind elements_kind = receiver_map->elements_kind();
8624
8625       Drop(args_count_no_receiver);
8626       HValue* result;
8627       HValue* reduced_length;
8628       HValue* receiver = Pop();
8629
8630       HValue* checked_object = AddCheckMap(receiver, receiver_map);
8631       HValue* length =
8632           Add<HLoadNamedField>(checked_object, nullptr,
8633                                HObjectAccess::ForArrayLength(elements_kind));
8634
8635       Drop(1);  // Function.
8636
8637       { NoObservableSideEffectsScope scope(this);
8638         IfBuilder length_checker(this);
8639
8640         HValue* bounds_check = length_checker.If<HCompareNumericAndBranch>(
8641             length, graph()->GetConstant0(), Token::EQ);
8642         length_checker.Then();
8643
8644         if (!ast_context()->IsEffect()) Push(graph()->GetConstantUndefined());
8645
8646         length_checker.Else();
8647         HValue* elements = AddLoadElements(checked_object);
8648         // Ensure that we aren't popping from a copy-on-write array.
8649         if (IsFastSmiOrObjectElementsKind(elements_kind)) {
8650           elements = BuildCopyElementsOnWrite(checked_object, elements,
8651                                               elements_kind, length);
8652         }
8653         reduced_length = AddUncasted<HSub>(length, graph()->GetConstant1());
8654         result = AddElementAccess(elements, reduced_length, NULL,
8655                                   bounds_check, elements_kind, LOAD);
8656         HValue* hole = IsFastSmiOrObjectElementsKind(elements_kind)
8657                            ? graph()->GetConstantHole()
8658                            : Add<HConstant>(HConstant::kHoleNaN);
8659         if (IsFastSmiOrObjectElementsKind(elements_kind)) {
8660           elements_kind = FAST_HOLEY_ELEMENTS;
8661         }
8662         AddElementAccess(
8663             elements, reduced_length, hole, bounds_check, elements_kind, STORE);
8664         Add<HStoreNamedField>(
8665             checked_object, HObjectAccess::ForArrayLength(elements_kind),
8666             reduced_length, STORE_TO_INITIALIZED_ENTRY);
8667
8668         if (!ast_context()->IsEffect()) Push(result);
8669
8670         length_checker.End();
8671       }
8672       result = ast_context()->IsEffect() ? graph()->GetConstant0() : Top();
8673       Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
8674       if (!ast_context()->IsEffect()) Drop(1);
8675
8676       ast_context()->ReturnValue(result);
8677       return true;
8678     }
8679     case kArrayPush: {
8680       if (!CanInlineArrayResizeOperation(receiver_map)) return false;
8681       ElementsKind elements_kind = receiver_map->elements_kind();
8682
8683       // If there may be elements accessors in the prototype chain, the fast
8684       // inlined version can't be used.
8685       if (receiver_map->DictionaryElementsInPrototypeChainOnly()) return false;
8686       // If there currently can be no elements accessors on the prototype chain,
8687       // it doesn't mean that there won't be any later. Install a full prototype
8688       // chain check to trap element accessors being installed on the prototype
8689       // chain, which would cause elements to go to dictionary mode and result
8690       // in a map change.
8691       Handle<JSObject> prototype(JSObject::cast(receiver_map->prototype()));
8692       BuildCheckPrototypeMaps(prototype, Handle<JSObject>());
8693
8694       // Protect against adding elements to the Array prototype, which needs to
8695       // route through appropriate bottlenecks.
8696       if (isolate()->IsFastArrayConstructorPrototypeChainIntact() &&
8697           !prototype->IsJSArray()) {
8698         return false;
8699       }
8700
8701       const int argc = args_count_no_receiver;
8702       if (argc != 1) return false;
8703
8704       HValue* value_to_push = Pop();
8705       HValue* array = Pop();
8706       Drop(1);  // Drop function.
8707
8708       HInstruction* new_size = NULL;
8709       HValue* length = NULL;
8710
8711       {
8712         NoObservableSideEffectsScope scope(this);
8713
8714         length = Add<HLoadNamedField>(
8715             array, nullptr, HObjectAccess::ForArrayLength(elements_kind));
8716
8717         new_size = AddUncasted<HAdd>(length, graph()->GetConstant1());
8718
8719         bool is_array = receiver_map->instance_type() == JS_ARRAY_TYPE;
8720         HValue* checked_array = Add<HCheckMaps>(array, receiver_map);
8721         BuildUncheckedMonomorphicElementAccess(
8722             checked_array, length, value_to_push, is_array, elements_kind,
8723             STORE, NEVER_RETURN_HOLE, STORE_AND_GROW_NO_TRANSITION);
8724
8725         if (!ast_context()->IsEffect()) Push(new_size);
8726         Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
8727         if (!ast_context()->IsEffect()) Drop(1);
8728       }
8729
8730       ast_context()->ReturnValue(new_size);
8731       return true;
8732     }
8733     case kArrayShift: {
8734       if (!CanInlineArrayResizeOperation(receiver_map)) return false;
8735       ElementsKind kind = receiver_map->elements_kind();
8736
8737       // If there may be elements accessors in the prototype chain, the fast
8738       // inlined version can't be used.
8739       if (receiver_map->DictionaryElementsInPrototypeChainOnly()) return false;
8740
8741       // If there currently can be no elements accessors on the prototype chain,
8742       // it doesn't mean that there won't be any later. Install a full prototype
8743       // chain check to trap element accessors being installed on the prototype
8744       // chain, which would cause elements to go to dictionary mode and result
8745       // in a map change.
8746       BuildCheckPrototypeMaps(
8747           handle(JSObject::cast(receiver_map->prototype()), isolate()),
8748           Handle<JSObject>::null());
8749
8750       // Threshold for fast inlined Array.shift().
8751       HConstant* inline_threshold = Add<HConstant>(static_cast<int32_t>(16));
8752
8753       Drop(args_count_no_receiver);
8754       HValue* receiver = Pop();
8755       HValue* function = Pop();
8756       HValue* result;
8757
8758       {
8759         NoObservableSideEffectsScope scope(this);
8760
8761         HValue* length = Add<HLoadNamedField>(
8762             receiver, nullptr, HObjectAccess::ForArrayLength(kind));
8763
8764         IfBuilder if_lengthiszero(this);
8765         HValue* lengthiszero = if_lengthiszero.If<HCompareNumericAndBranch>(
8766             length, graph()->GetConstant0(), Token::EQ);
8767         if_lengthiszero.Then();
8768         {
8769           if (!ast_context()->IsEffect()) Push(graph()->GetConstantUndefined());
8770         }
8771         if_lengthiszero.Else();
8772         {
8773           HValue* elements = AddLoadElements(receiver);
8774
8775           // Check if we can use the fast inlined Array.shift().
8776           IfBuilder if_inline(this);
8777           if_inline.If<HCompareNumericAndBranch>(
8778               length, inline_threshold, Token::LTE);
8779           if (IsFastSmiOrObjectElementsKind(kind)) {
8780             // We cannot handle copy-on-write backing stores here.
8781             if_inline.AndIf<HCompareMap>(
8782                 elements, isolate()->factory()->fixed_array_map());
8783           }
8784           if_inline.Then();
8785           {
8786             // Remember the result.
8787             if (!ast_context()->IsEffect()) {
8788               Push(AddElementAccess(elements, graph()->GetConstant0(), NULL,
8789                                     lengthiszero, kind, LOAD));
8790             }
8791
8792             // Compute the new length.
8793             HValue* new_length = AddUncasted<HSub>(
8794                 length, graph()->GetConstant1());
8795             new_length->ClearFlag(HValue::kCanOverflow);
8796
8797             // Copy the remaining elements.
8798             LoopBuilder loop(this, context(), LoopBuilder::kPostIncrement);
8799             {
8800               HValue* new_key = loop.BeginBody(
8801                   graph()->GetConstant0(), new_length, Token::LT);
8802               HValue* key = AddUncasted<HAdd>(new_key, graph()->GetConstant1());
8803               key->ClearFlag(HValue::kCanOverflow);
8804               ElementsKind copy_kind =
8805                   kind == FAST_HOLEY_SMI_ELEMENTS ? FAST_HOLEY_ELEMENTS : kind;
8806               HValue* element = AddUncasted<HLoadKeyed>(
8807                   elements, key, lengthiszero, copy_kind, ALLOW_RETURN_HOLE);
8808               HStoreKeyed* store =
8809                   Add<HStoreKeyed>(elements, new_key, element, copy_kind);
8810               store->SetFlag(HValue::kAllowUndefinedAsNaN);
8811             }
8812             loop.EndBody();
8813
8814             // Put a hole at the end.
8815             HValue* hole = IsFastSmiOrObjectElementsKind(kind)
8816                                ? graph()->GetConstantHole()
8817                                : Add<HConstant>(HConstant::kHoleNaN);
8818             if (IsFastSmiOrObjectElementsKind(kind)) kind = FAST_HOLEY_ELEMENTS;
8819             Add<HStoreKeyed>(
8820                 elements, new_length, hole, kind, INITIALIZING_STORE);
8821
8822             // Remember new length.
8823             Add<HStoreNamedField>(
8824                 receiver, HObjectAccess::ForArrayLength(kind),
8825                 new_length, STORE_TO_INITIALIZED_ENTRY);
8826           }
8827           if_inline.Else();
8828           {
8829             Add<HPushArguments>(receiver);
8830             result = Add<HCallJSFunction>(function, 1, true);
8831             if (!ast_context()->IsEffect()) Push(result);
8832           }
8833           if_inline.End();
8834         }
8835         if_lengthiszero.End();
8836       }
8837       result = ast_context()->IsEffect() ? graph()->GetConstant0() : Top();
8838       Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
8839       if (!ast_context()->IsEffect()) Drop(1);
8840       ast_context()->ReturnValue(result);
8841       return true;
8842     }
8843     case kArrayIndexOf:
8844     case kArrayLastIndexOf: {
8845       if (receiver_map.is_null()) return false;
8846       if (receiver_map->instance_type() != JS_ARRAY_TYPE) return false;
8847       ElementsKind kind = receiver_map->elements_kind();
8848       if (!IsFastElementsKind(kind)) return false;
8849       if (receiver_map->is_observed()) return false;
8850       if (argument_count != 2) return false;
8851       if (!receiver_map->is_extensible()) return false;
8852
8853       // If there may be elements accessors in the prototype chain, the fast
8854       // inlined version can't be used.
8855       if (receiver_map->DictionaryElementsInPrototypeChainOnly()) return false;
8856
8857       // If there currently can be no elements accessors on the prototype chain,
8858       // it doesn't mean that there won't be any later. Install a full prototype
8859       // chain check to trap element accessors being installed on the prototype
8860       // chain, which would cause elements to go to dictionary mode and result
8861       // in a map change.
8862       BuildCheckPrototypeMaps(
8863           handle(JSObject::cast(receiver_map->prototype()), isolate()),
8864           Handle<JSObject>::null());
8865
8866       HValue* search_element = Pop();
8867       HValue* receiver = Pop();
8868       Drop(1);  // Drop function.
8869
8870       ArrayIndexOfMode mode = (id == kArrayIndexOf)
8871           ? kFirstIndexOf : kLastIndexOf;
8872       HValue* index = BuildArrayIndexOf(receiver, search_element, kind, mode);
8873
8874       if (!ast_context()->IsEffect()) Push(index);
8875       Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
8876       if (!ast_context()->IsEffect()) Drop(1);
8877       ast_context()->ReturnValue(index);
8878       return true;
8879     }
8880     default:
8881       // Not yet supported for inlining.
8882       break;
8883   }
8884   return false;
8885 }
8886
8887
8888 bool HOptimizedGraphBuilder::TryInlineApiFunctionCall(Call* expr,
8889                                                       HValue* receiver) {
8890   Handle<JSFunction> function = expr->target();
8891   int argc = expr->arguments()->length();
8892   SmallMapList receiver_maps;
8893   return TryInlineApiCall(function,
8894                           receiver,
8895                           &receiver_maps,
8896                           argc,
8897                           expr->id(),
8898                           kCallApiFunction);
8899 }
8900
8901
8902 bool HOptimizedGraphBuilder::TryInlineApiMethodCall(
8903     Call* expr,
8904     HValue* receiver,
8905     SmallMapList* receiver_maps) {
8906   Handle<JSFunction> function = expr->target();
8907   int argc = expr->arguments()->length();
8908   return TryInlineApiCall(function,
8909                           receiver,
8910                           receiver_maps,
8911                           argc,
8912                           expr->id(),
8913                           kCallApiMethod);
8914 }
8915
8916
8917 bool HOptimizedGraphBuilder::TryInlineApiGetter(Handle<JSFunction> function,
8918                                                 Handle<Map> receiver_map,
8919                                                 BailoutId ast_id) {
8920   SmallMapList receiver_maps(1, zone());
8921   receiver_maps.Add(receiver_map, zone());
8922   return TryInlineApiCall(function,
8923                           NULL,  // Receiver is on expression stack.
8924                           &receiver_maps,
8925                           0,
8926                           ast_id,
8927                           kCallApiGetter);
8928 }
8929
8930
8931 bool HOptimizedGraphBuilder::TryInlineApiSetter(Handle<JSFunction> function,
8932                                                 Handle<Map> receiver_map,
8933                                                 BailoutId ast_id) {
8934   SmallMapList receiver_maps(1, zone());
8935   receiver_maps.Add(receiver_map, zone());
8936   return TryInlineApiCall(function,
8937                           NULL,  // Receiver is on expression stack.
8938                           &receiver_maps,
8939                           1,
8940                           ast_id,
8941                           kCallApiSetter);
8942 }
8943
8944
8945 bool HOptimizedGraphBuilder::TryInlineApiCall(Handle<JSFunction> function,
8946                                                HValue* receiver,
8947                                                SmallMapList* receiver_maps,
8948                                                int argc,
8949                                                BailoutId ast_id,
8950                                                ApiCallType call_type) {
8951   if (function->context()->native_context() !=
8952       top_info()->closure()->context()->native_context()) {
8953     return false;
8954   }
8955   CallOptimization optimization(function);
8956   if (!optimization.is_simple_api_call()) return false;
8957   Handle<Map> holder_map;
8958   for (int i = 0; i < receiver_maps->length(); ++i) {
8959     auto map = receiver_maps->at(i);
8960     // Don't inline calls to receivers requiring accesschecks.
8961     if (map->is_access_check_needed()) return false;
8962   }
8963   if (call_type == kCallApiFunction) {
8964     // Cannot embed a direct reference to the global proxy map
8965     // as it maybe dropped on deserialization.
8966     CHECK(!isolate()->serializer_enabled());
8967     DCHECK_EQ(0, receiver_maps->length());
8968     receiver_maps->Add(handle(function->global_proxy()->map()), zone());
8969   }
8970   CallOptimization::HolderLookup holder_lookup =
8971       CallOptimization::kHolderNotFound;
8972   Handle<JSObject> api_holder = optimization.LookupHolderOfExpectedType(
8973       receiver_maps->first(), &holder_lookup);
8974   if (holder_lookup == CallOptimization::kHolderNotFound) return false;
8975
8976   if (FLAG_trace_inlining) {
8977     PrintF("Inlining api function ");
8978     function->ShortPrint();
8979     PrintF("\n");
8980   }
8981
8982   bool is_function = false;
8983   bool is_store = false;
8984   switch (call_type) {
8985     case kCallApiFunction:
8986     case kCallApiMethod:
8987       // Need to check that none of the receiver maps could have changed.
8988       Add<HCheckMaps>(receiver, receiver_maps);
8989       // Need to ensure the chain between receiver and api_holder is intact.
8990       if (holder_lookup == CallOptimization::kHolderFound) {
8991         AddCheckPrototypeMaps(api_holder, receiver_maps->first());
8992       } else {
8993         DCHECK_EQ(holder_lookup, CallOptimization::kHolderIsReceiver);
8994       }
8995       // Includes receiver.
8996       PushArgumentsFromEnvironment(argc + 1);
8997       is_function = true;
8998       break;
8999     case kCallApiGetter:
9000       // Receiver and prototype chain cannot have changed.
9001       DCHECK_EQ(0, argc);
9002       DCHECK_NULL(receiver);
9003       // Receiver is on expression stack.
9004       receiver = Pop();
9005       Add<HPushArguments>(receiver);
9006       break;
9007     case kCallApiSetter:
9008       {
9009         is_store = true;
9010         // Receiver and prototype chain cannot have changed.
9011         DCHECK_EQ(1, argc);
9012         DCHECK_NULL(receiver);
9013         // Receiver and value are on expression stack.
9014         HValue* value = Pop();
9015         receiver = Pop();
9016         Add<HPushArguments>(receiver, value);
9017         break;
9018      }
9019   }
9020
9021   HValue* holder = NULL;
9022   switch (holder_lookup) {
9023     case CallOptimization::kHolderFound:
9024       holder = Add<HConstant>(api_holder);
9025       break;
9026     case CallOptimization::kHolderIsReceiver:
9027       holder = receiver;
9028       break;
9029     case CallOptimization::kHolderNotFound:
9030       UNREACHABLE();
9031       break;
9032   }
9033   Handle<CallHandlerInfo> api_call_info = optimization.api_call_info();
9034   Handle<Object> call_data_obj(api_call_info->data(), isolate());
9035   bool call_data_undefined = call_data_obj->IsUndefined();
9036   HValue* call_data = Add<HConstant>(call_data_obj);
9037   ApiFunction fun(v8::ToCData<Address>(api_call_info->callback()));
9038   ExternalReference ref = ExternalReference(&fun,
9039                                             ExternalReference::DIRECT_API_CALL,
9040                                             isolate());
9041   HValue* api_function_address = Add<HConstant>(ExternalReference(ref));
9042
9043   HValue* op_vals[] = {context(), Add<HConstant>(function), call_data, holder,
9044                        api_function_address, nullptr};
9045
9046   HInstruction* call = nullptr;
9047   if (!is_function) {
9048     CallApiAccessorStub stub(isolate(), is_store, call_data_undefined);
9049     Handle<Code> code = stub.GetCode();
9050     HConstant* code_value = Add<HConstant>(code);
9051     ApiAccessorDescriptor descriptor(isolate());
9052     call = New<HCallWithDescriptor>(
9053         code_value, argc + 1, descriptor,
9054         Vector<HValue*>(op_vals, arraysize(op_vals) - 1));
9055   } else if (argc <= CallApiFunctionWithFixedArgsStub::kMaxFixedArgs) {
9056     CallApiFunctionWithFixedArgsStub stub(isolate(), argc, call_data_undefined);
9057     Handle<Code> code = stub.GetCode();
9058     HConstant* code_value = Add<HConstant>(code);
9059     ApiFunctionWithFixedArgsDescriptor descriptor(isolate());
9060     call = New<HCallWithDescriptor>(
9061         code_value, argc + 1, descriptor,
9062         Vector<HValue*>(op_vals, arraysize(op_vals) - 1));
9063     Drop(1);  // Drop function.
9064   } else {
9065     op_vals[arraysize(op_vals) - 1] = Add<HConstant>(argc);
9066     CallApiFunctionStub stub(isolate(), call_data_undefined);
9067     Handle<Code> code = stub.GetCode();
9068     HConstant* code_value = Add<HConstant>(code);
9069     ApiFunctionDescriptor descriptor(isolate());
9070     call =
9071         New<HCallWithDescriptor>(code_value, argc + 1, descriptor,
9072                                  Vector<HValue*>(op_vals, arraysize(op_vals)));
9073     Drop(1);  // Drop function.
9074   }
9075
9076   ast_context()->ReturnInstruction(call, ast_id);
9077   return true;
9078 }
9079
9080
9081 void HOptimizedGraphBuilder::HandleIndirectCall(Call* expr, HValue* function,
9082                                                 int arguments_count) {
9083   Handle<JSFunction> known_function;
9084   int args_count_no_receiver = arguments_count - 1;
9085   if (function->IsConstant() &&
9086       HConstant::cast(function)->handle(isolate())->IsJSFunction()) {
9087     known_function =
9088         Handle<JSFunction>::cast(HConstant::cast(function)->handle(isolate()));
9089     if (TryInlineBuiltinMethodCall(expr, known_function, Handle<Map>(),
9090                                    args_count_no_receiver)) {
9091       if (FLAG_trace_inlining) {
9092         PrintF("Inlining builtin ");
9093         known_function->ShortPrint();
9094         PrintF("\n");
9095       }
9096       return;
9097     }
9098
9099     if (TryInlineIndirectCall(known_function, expr, args_count_no_receiver)) {
9100       return;
9101     }
9102   }
9103
9104   PushArgumentsFromEnvironment(arguments_count);
9105   HInvokeFunction* call =
9106       New<HInvokeFunction>(function, known_function, arguments_count);
9107   Drop(1);  // Function
9108   ast_context()->ReturnInstruction(call, expr->id());
9109 }
9110
9111
9112 bool HOptimizedGraphBuilder::TryIndirectCall(Call* expr) {
9113   DCHECK(expr->expression()->IsProperty());
9114
9115   if (!expr->IsMonomorphic()) {
9116     return false;
9117   }
9118   Handle<Map> function_map = expr->GetReceiverTypes()->first();
9119   if (function_map->instance_type() != JS_FUNCTION_TYPE ||
9120       !expr->target()->shared()->HasBuiltinFunctionId()) {
9121     return false;
9122   }
9123
9124   switch (expr->target()->shared()->builtin_function_id()) {
9125     case kFunctionCall: {
9126       if (expr->arguments()->length() == 0) return false;
9127       BuildFunctionCall(expr);
9128       return true;
9129     }
9130     case kFunctionApply: {
9131       // For .apply, only the pattern f.apply(receiver, arguments)
9132       // is supported.
9133       if (current_info()->scope()->arguments() == NULL) return false;
9134
9135       if (!CanBeFunctionApplyArguments(expr)) return false;
9136
9137       BuildFunctionApply(expr);
9138       return true;
9139     }
9140     default: { return false; }
9141   }
9142   UNREACHABLE();
9143 }
9144
9145
9146 void HOptimizedGraphBuilder::BuildFunctionApply(Call* expr) {
9147   ZoneList<Expression*>* args = expr->arguments();
9148   CHECK_ALIVE(VisitForValue(args->at(0)));
9149   HValue* receiver = Pop();  // receiver
9150   HValue* function = Pop();  // f
9151   Drop(1);  // apply
9152
9153   Handle<Map> function_map = expr->GetReceiverTypes()->first();
9154   HValue* checked_function = AddCheckMap(function, function_map);
9155
9156   if (function_state()->outer() == NULL) {
9157     HInstruction* elements = Add<HArgumentsElements>(false);
9158     HInstruction* length = Add<HArgumentsLength>(elements);
9159     HValue* wrapped_receiver = BuildWrapReceiver(receiver, checked_function);
9160     HInstruction* result = New<HApplyArguments>(function,
9161                                                 wrapped_receiver,
9162                                                 length,
9163                                                 elements);
9164     ast_context()->ReturnInstruction(result, expr->id());
9165   } else {
9166     // We are inside inlined function and we know exactly what is inside
9167     // arguments object. But we need to be able to materialize at deopt.
9168     DCHECK_EQ(environment()->arguments_environment()->parameter_count(),
9169               function_state()->entry()->arguments_object()->arguments_count());
9170     HArgumentsObject* args = function_state()->entry()->arguments_object();
9171     const ZoneList<HValue*>* arguments_values = args->arguments_values();
9172     int arguments_count = arguments_values->length();
9173     Push(function);
9174     Push(BuildWrapReceiver(receiver, checked_function));
9175     for (int i = 1; i < arguments_count; i++) {
9176       Push(arguments_values->at(i));
9177     }
9178     HandleIndirectCall(expr, function, arguments_count);
9179   }
9180 }
9181
9182
9183 // f.call(...)
9184 void HOptimizedGraphBuilder::BuildFunctionCall(Call* expr) {
9185   HValue* function = Top();  // f
9186   Handle<Map> function_map = expr->GetReceiverTypes()->first();
9187   HValue* checked_function = AddCheckMap(function, function_map);
9188
9189   // f and call are on the stack in the unoptimized code
9190   // during evaluation of the arguments.
9191   CHECK_ALIVE(VisitExpressions(expr->arguments()));
9192
9193   int args_length = expr->arguments()->length();
9194   int receiver_index = args_length - 1;
9195   // Patch the receiver.
9196   HValue* receiver = BuildWrapReceiver(
9197       environment()->ExpressionStackAt(receiver_index), checked_function);
9198   environment()->SetExpressionStackAt(receiver_index, receiver);
9199
9200   // Call must not be on the stack from now on.
9201   int call_index = args_length + 1;
9202   environment()->RemoveExpressionStackAt(call_index);
9203
9204   HandleIndirectCall(expr, function, args_length);
9205 }
9206
9207
9208 HValue* HOptimizedGraphBuilder::ImplicitReceiverFor(HValue* function,
9209                                                     Handle<JSFunction> target) {
9210   SharedFunctionInfo* shared = target->shared();
9211   if (is_sloppy(shared->language_mode()) && !shared->native()) {
9212     // Cannot embed a direct reference to the global proxy
9213     // as is it dropped on deserialization.
9214     CHECK(!isolate()->serializer_enabled());
9215     Handle<JSObject> global_proxy(target->context()->global_proxy());
9216     return Add<HConstant>(global_proxy);
9217   }
9218   return graph()->GetConstantUndefined();
9219 }
9220
9221
9222 void HOptimizedGraphBuilder::BuildArrayCall(Expression* expression,
9223                                             int arguments_count,
9224                                             HValue* function,
9225                                             Handle<AllocationSite> site) {
9226   Add<HCheckValue>(function, array_function());
9227
9228   if (IsCallArrayInlineable(arguments_count, site)) {
9229     BuildInlinedCallArray(expression, arguments_count, site);
9230     return;
9231   }
9232
9233   HInstruction* call = PreProcessCall(New<HCallNewArray>(
9234       function, arguments_count + 1, site->GetElementsKind(), site));
9235   if (expression->IsCall()) {
9236     Drop(1);
9237   }
9238   ast_context()->ReturnInstruction(call, expression->id());
9239 }
9240
9241
9242 HValue* HOptimizedGraphBuilder::BuildArrayIndexOf(HValue* receiver,
9243                                                   HValue* search_element,
9244                                                   ElementsKind kind,
9245                                                   ArrayIndexOfMode mode) {
9246   DCHECK(IsFastElementsKind(kind));
9247
9248   NoObservableSideEffectsScope no_effects(this);
9249
9250   HValue* elements = AddLoadElements(receiver);
9251   HValue* length = AddLoadArrayLength(receiver, kind);
9252
9253   HValue* initial;
9254   HValue* terminating;
9255   Token::Value token;
9256   LoopBuilder::Direction direction;
9257   if (mode == kFirstIndexOf) {
9258     initial = graph()->GetConstant0();
9259     terminating = length;
9260     token = Token::LT;
9261     direction = LoopBuilder::kPostIncrement;
9262   } else {
9263     DCHECK_EQ(kLastIndexOf, mode);
9264     initial = length;
9265     terminating = graph()->GetConstant0();
9266     token = Token::GT;
9267     direction = LoopBuilder::kPreDecrement;
9268   }
9269
9270   Push(graph()->GetConstantMinus1());
9271   if (IsFastDoubleElementsKind(kind) || IsFastSmiElementsKind(kind)) {
9272     // Make sure that we can actually compare numbers correctly below, see
9273     // https://code.google.com/p/chromium/issues/detail?id=407946 for details.
9274     search_element = AddUncasted<HForceRepresentation>(
9275         search_element, IsFastSmiElementsKind(kind) ? Representation::Smi()
9276                                                     : Representation::Double());
9277
9278     LoopBuilder loop(this, context(), direction);
9279     {
9280       HValue* index = loop.BeginBody(initial, terminating, token);
9281       HValue* element = AddUncasted<HLoadKeyed>(elements, index, nullptr, kind,
9282                                                 ALLOW_RETURN_HOLE);
9283       IfBuilder if_issame(this);
9284       if_issame.If<HCompareNumericAndBranch>(element, search_element,
9285                                              Token::EQ_STRICT);
9286       if_issame.Then();
9287       {
9288         Drop(1);
9289         Push(index);
9290         loop.Break();
9291       }
9292       if_issame.End();
9293     }
9294     loop.EndBody();
9295   } else {
9296     IfBuilder if_isstring(this);
9297     if_isstring.If<HIsStringAndBranch>(search_element);
9298     if_isstring.Then();
9299     {
9300       LoopBuilder loop(this, context(), direction);
9301       {
9302         HValue* index = loop.BeginBody(initial, terminating, token);
9303         HValue* element = AddUncasted<HLoadKeyed>(elements, index, nullptr,
9304                                                   kind, ALLOW_RETURN_HOLE);
9305         IfBuilder if_issame(this);
9306         if_issame.If<HIsStringAndBranch>(element);
9307         if_issame.AndIf<HStringCompareAndBranch>(
9308             element, search_element, Token::EQ_STRICT);
9309         if_issame.Then();
9310         {
9311           Drop(1);
9312           Push(index);
9313           loop.Break();
9314         }
9315         if_issame.End();
9316       }
9317       loop.EndBody();
9318     }
9319     if_isstring.Else();
9320     {
9321       IfBuilder if_isnumber(this);
9322       if_isnumber.If<HIsSmiAndBranch>(search_element);
9323       if_isnumber.OrIf<HCompareMap>(
9324           search_element, isolate()->factory()->heap_number_map());
9325       if_isnumber.Then();
9326       {
9327         HValue* search_number =
9328             AddUncasted<HForceRepresentation>(search_element,
9329                                               Representation::Double());
9330         LoopBuilder loop(this, context(), direction);
9331         {
9332           HValue* index = loop.BeginBody(initial, terminating, token);
9333           HValue* element = AddUncasted<HLoadKeyed>(elements, index, nullptr,
9334                                                     kind, ALLOW_RETURN_HOLE);
9335
9336           IfBuilder if_element_isnumber(this);
9337           if_element_isnumber.If<HIsSmiAndBranch>(element);
9338           if_element_isnumber.OrIf<HCompareMap>(
9339               element, isolate()->factory()->heap_number_map());
9340           if_element_isnumber.Then();
9341           {
9342             HValue* number =
9343                 AddUncasted<HForceRepresentation>(element,
9344                                                   Representation::Double());
9345             IfBuilder if_issame(this);
9346             if_issame.If<HCompareNumericAndBranch>(
9347                 number, search_number, Token::EQ_STRICT);
9348             if_issame.Then();
9349             {
9350               Drop(1);
9351               Push(index);
9352               loop.Break();
9353             }
9354             if_issame.End();
9355           }
9356           if_element_isnumber.End();
9357         }
9358         loop.EndBody();
9359       }
9360       if_isnumber.Else();
9361       {
9362         LoopBuilder loop(this, context(), direction);
9363         {
9364           HValue* index = loop.BeginBody(initial, terminating, token);
9365           HValue* element = AddUncasted<HLoadKeyed>(elements, index, nullptr,
9366                                                     kind, ALLOW_RETURN_HOLE);
9367           IfBuilder if_issame(this);
9368           if_issame.If<HCompareObjectEqAndBranch>(
9369               element, search_element);
9370           if_issame.Then();
9371           {
9372             Drop(1);
9373             Push(index);
9374             loop.Break();
9375           }
9376           if_issame.End();
9377         }
9378         loop.EndBody();
9379       }
9380       if_isnumber.End();
9381     }
9382     if_isstring.End();
9383   }
9384
9385   return Pop();
9386 }
9387
9388
9389 bool HOptimizedGraphBuilder::TryHandleArrayCall(Call* expr, HValue* function) {
9390   if (!array_function().is_identical_to(expr->target())) {
9391     return false;
9392   }
9393
9394   Handle<AllocationSite> site = expr->allocation_site();
9395   if (site.is_null()) return false;
9396
9397   BuildArrayCall(expr,
9398                  expr->arguments()->length(),
9399                  function,
9400                  site);
9401   return true;
9402 }
9403
9404
9405 bool HOptimizedGraphBuilder::TryHandleArrayCallNew(CallNew* expr,
9406                                                    HValue* function) {
9407   if (!array_function().is_identical_to(expr->target())) {
9408     return false;
9409   }
9410
9411   Handle<AllocationSite> site = expr->allocation_site();
9412   if (site.is_null()) return false;
9413
9414   BuildArrayCall(expr, expr->arguments()->length(), function, site);
9415   return true;
9416 }
9417
9418
9419 bool HOptimizedGraphBuilder::CanBeFunctionApplyArguments(Call* expr) {
9420   ZoneList<Expression*>* args = expr->arguments();
9421   if (args->length() != 2) return false;
9422   VariableProxy* arg_two = args->at(1)->AsVariableProxy();
9423   if (arg_two == NULL || !arg_two->var()->IsStackAllocated()) return false;
9424   HValue* arg_two_value = LookupAndMakeLive(arg_two->var());
9425   if (!arg_two_value->CheckFlag(HValue::kIsArguments)) return false;
9426   return true;
9427 }
9428
9429
9430 void HOptimizedGraphBuilder::VisitCall(Call* expr) {
9431   DCHECK(!HasStackOverflow());
9432   DCHECK(current_block() != NULL);
9433   DCHECK(current_block()->HasPredecessor());
9434   if (!top_info()->is_tracking_positions()) SetSourcePosition(expr->position());
9435   Expression* callee = expr->expression();
9436   int argument_count = expr->arguments()->length() + 1;  // Plus receiver.
9437   HInstruction* call = NULL;
9438
9439   Property* prop = callee->AsProperty();
9440   if (prop != NULL) {
9441     CHECK_ALIVE(VisitForValue(prop->obj()));
9442     HValue* receiver = Top();
9443
9444     SmallMapList* maps;
9445     ComputeReceiverTypes(expr, receiver, &maps, zone());
9446
9447     if (prop->key()->IsPropertyName() && maps->length() > 0) {
9448       Handle<String> name = prop->key()->AsLiteral()->AsPropertyName();
9449       PropertyAccessInfo info(this, LOAD, maps->first(), name);
9450       if (!info.CanAccessAsMonomorphic(maps)) {
9451         HandlePolymorphicCallNamed(expr, receiver, maps, name);
9452         return;
9453       }
9454     }
9455     HValue* key = NULL;
9456     if (!prop->key()->IsPropertyName()) {
9457       CHECK_ALIVE(VisitForValue(prop->key()));
9458       key = Pop();
9459     }
9460
9461     CHECK_ALIVE(PushLoad(prop, receiver, key));
9462     HValue* function = Pop();
9463
9464     if (function->IsConstant() &&
9465         HConstant::cast(function)->handle(isolate())->IsJSFunction()) {
9466       // Push the function under the receiver.
9467       environment()->SetExpressionStackAt(0, function);
9468       Push(receiver);
9469
9470       Handle<JSFunction> known_function = Handle<JSFunction>::cast(
9471           HConstant::cast(function)->handle(isolate()));
9472       expr->set_target(known_function);
9473
9474       if (TryIndirectCall(expr)) return;
9475       CHECK_ALIVE(VisitExpressions(expr->arguments()));
9476
9477       Handle<Map> map = maps->length() == 1 ? maps->first() : Handle<Map>();
9478       if (TryInlineBuiltinMethodCall(expr, known_function, map,
9479                                      expr->arguments()->length())) {
9480         if (FLAG_trace_inlining) {
9481           PrintF("Inlining builtin ");
9482           known_function->ShortPrint();
9483           PrintF("\n");
9484         }
9485         return;
9486       }
9487       if (TryInlineApiMethodCall(expr, receiver, maps)) return;
9488
9489       // Wrap the receiver if necessary.
9490       if (NeedsWrapping(maps->first(), known_function)) {
9491         // Since HWrapReceiver currently cannot actually wrap numbers and
9492         // strings, use the regular CallFunctionStub for method calls to wrap
9493         // the receiver.
9494         // TODO(verwaest): Support creation of value wrappers directly in
9495         // HWrapReceiver.
9496         call = New<HCallFunction>(
9497             function, argument_count, WRAP_AND_CALL);
9498       } else if (TryInlineCall(expr)) {
9499         return;
9500       } else {
9501         call = BuildCallConstantFunction(known_function, argument_count);
9502       }
9503
9504     } else {
9505       ArgumentsAllowedFlag arguments_flag = ARGUMENTS_NOT_ALLOWED;
9506       if (CanBeFunctionApplyArguments(expr) && expr->is_uninitialized()) {
9507         // We have to use EAGER deoptimization here because Deoptimizer::SOFT
9508         // gets ignored by the always-opt flag, which leads to incorrect code.
9509         Add<HDeoptimize>(
9510             Deoptimizer::kInsufficientTypeFeedbackForCallWithArguments,
9511             Deoptimizer::EAGER);
9512         arguments_flag = ARGUMENTS_FAKED;
9513       }
9514
9515       // Push the function under the receiver.
9516       environment()->SetExpressionStackAt(0, function);
9517       Push(receiver);
9518
9519       CHECK_ALIVE(VisitExpressions(expr->arguments(), arguments_flag));
9520       CallFunctionFlags flags = receiver->type().IsJSObject()
9521           ? NO_CALL_FUNCTION_FLAGS : CALL_AS_METHOD;
9522       call = New<HCallFunction>(function, argument_count, flags);
9523     }
9524     PushArgumentsFromEnvironment(argument_count);
9525
9526   } else {
9527     VariableProxy* proxy = expr->expression()->AsVariableProxy();
9528     if (proxy != NULL && proxy->var()->is_possibly_eval(isolate())) {
9529       return Bailout(kPossibleDirectCallToEval);
9530     }
9531
9532     // The function is on the stack in the unoptimized code during
9533     // evaluation of the arguments.
9534     CHECK_ALIVE(VisitForValue(expr->expression()));
9535     HValue* function = Top();
9536     if (function->IsConstant() &&
9537         HConstant::cast(function)->handle(isolate())->IsJSFunction()) {
9538       Handle<Object> constant = HConstant::cast(function)->handle(isolate());
9539       Handle<JSFunction> target = Handle<JSFunction>::cast(constant);
9540       expr->SetKnownGlobalTarget(target);
9541     }
9542
9543     // Placeholder for the receiver.
9544     Push(graph()->GetConstantUndefined());
9545     CHECK_ALIVE(VisitExpressions(expr->arguments()));
9546
9547     if (expr->IsMonomorphic()) {
9548       Add<HCheckValue>(function, expr->target());
9549
9550       // Patch the global object on the stack by the expected receiver.
9551       HValue* receiver = ImplicitReceiverFor(function, expr->target());
9552       const int receiver_index = argument_count - 1;
9553       environment()->SetExpressionStackAt(receiver_index, receiver);
9554
9555       if (TryInlineBuiltinFunctionCall(expr)) {
9556         if (FLAG_trace_inlining) {
9557           PrintF("Inlining builtin ");
9558           expr->target()->ShortPrint();
9559           PrintF("\n");
9560         }
9561         return;
9562       }
9563       if (TryInlineApiFunctionCall(expr, receiver)) return;
9564       if (TryHandleArrayCall(expr, function)) return;
9565       if (TryInlineCall(expr)) return;
9566
9567       PushArgumentsFromEnvironment(argument_count);
9568       call = BuildCallConstantFunction(expr->target(), argument_count);
9569     } else {
9570       PushArgumentsFromEnvironment(argument_count);
9571       HCallFunction* call_function =
9572           New<HCallFunction>(function, argument_count);
9573       call = call_function;
9574       if (expr->is_uninitialized() &&
9575           expr->IsUsingCallFeedbackICSlot(isolate())) {
9576         // We've never seen this call before, so let's have Crankshaft learn
9577         // through the type vector.
9578         Handle<TypeFeedbackVector> vector =
9579             handle(current_feedback_vector(), isolate());
9580         FeedbackVectorICSlot slot = expr->CallFeedbackICSlot();
9581         call_function->SetVectorAndSlot(vector, slot);
9582       }
9583     }
9584   }
9585
9586   Drop(1);  // Drop the function.
9587   return ast_context()->ReturnInstruction(call, expr->id());
9588 }
9589
9590
9591 void HOptimizedGraphBuilder::BuildInlinedCallArray(
9592     Expression* expression,
9593     int argument_count,
9594     Handle<AllocationSite> site) {
9595   DCHECK(!site.is_null());
9596   DCHECK(argument_count >= 0 && argument_count <= 1);
9597   NoObservableSideEffectsScope no_effects(this);
9598
9599   // We should at least have the constructor on the expression stack.
9600   HValue* constructor = environment()->ExpressionStackAt(argument_count);
9601
9602   // Register on the site for deoptimization if the transition feedback changes.
9603   top_info()->dependencies()->AssumeTransitionStable(site);
9604   ElementsKind kind = site->GetElementsKind();
9605   HInstruction* site_instruction = Add<HConstant>(site);
9606
9607   // In the single constant argument case, we may have to adjust elements kind
9608   // to avoid creating a packed non-empty array.
9609   if (argument_count == 1 && !IsHoleyElementsKind(kind)) {
9610     HValue* argument = environment()->Top();
9611     if (argument->IsConstant()) {
9612       HConstant* constant_argument = HConstant::cast(argument);
9613       DCHECK(constant_argument->HasSmiValue());
9614       int constant_array_size = constant_argument->Integer32Value();
9615       if (constant_array_size != 0) {
9616         kind = GetHoleyElementsKind(kind);
9617       }
9618     }
9619   }
9620
9621   // Build the array.
9622   JSArrayBuilder array_builder(this,
9623                                kind,
9624                                site_instruction,
9625                                constructor,
9626                                DISABLE_ALLOCATION_SITES);
9627   HValue* new_object = argument_count == 0
9628       ? array_builder.AllocateEmptyArray()
9629       : BuildAllocateArrayFromLength(&array_builder, Top());
9630
9631   int args_to_drop = argument_count + (expression->IsCall() ? 2 : 1);
9632   Drop(args_to_drop);
9633   ast_context()->ReturnValue(new_object);
9634 }
9635
9636
9637 // Checks whether allocation using the given constructor can be inlined.
9638 static bool IsAllocationInlineable(Handle<JSFunction> constructor) {
9639   return constructor->has_initial_map() &&
9640          constructor->initial_map()->instance_type() == JS_OBJECT_TYPE &&
9641          constructor->initial_map()->instance_size() <
9642              HAllocate::kMaxInlineSize;
9643 }
9644
9645
9646 bool HOptimizedGraphBuilder::IsCallArrayInlineable(
9647     int argument_count,
9648     Handle<AllocationSite> site) {
9649   Handle<JSFunction> caller = current_info()->closure();
9650   Handle<JSFunction> target = array_function();
9651   // We should have the function plus array arguments on the environment stack.
9652   DCHECK(environment()->length() >= (argument_count + 1));
9653   DCHECK(!site.is_null());
9654
9655   bool inline_ok = false;
9656   if (site->CanInlineCall()) {
9657     // We also want to avoid inlining in certain 1 argument scenarios.
9658     if (argument_count == 1) {
9659       HValue* argument = Top();
9660       if (argument->IsConstant()) {
9661         // Do not inline if the constant length argument is not a smi or
9662         // outside the valid range for unrolled loop initialization.
9663         HConstant* constant_argument = HConstant::cast(argument);
9664         if (constant_argument->HasSmiValue()) {
9665           int value = constant_argument->Integer32Value();
9666           inline_ok = value >= 0 && value <= kElementLoopUnrollThreshold;
9667           if (!inline_ok) {
9668             TraceInline(target, caller,
9669                         "Constant length outside of valid inlining range.");
9670           }
9671         }
9672       } else {
9673         TraceInline(target, caller,
9674                     "Dont inline [new] Array(n) where n isn't constant.");
9675       }
9676     } else if (argument_count == 0) {
9677       inline_ok = true;
9678     } else {
9679       TraceInline(target, caller, "Too many arguments to inline.");
9680     }
9681   } else {
9682     TraceInline(target, caller, "AllocationSite requested no inlining.");
9683   }
9684
9685   if (inline_ok) {
9686     TraceInline(target, caller, NULL);
9687   }
9688   return inline_ok;
9689 }
9690
9691
9692 void HOptimizedGraphBuilder::VisitCallNew(CallNew* expr) {
9693   DCHECK(!HasStackOverflow());
9694   DCHECK(current_block() != NULL);
9695   DCHECK(current_block()->HasPredecessor());
9696   if (!top_info()->is_tracking_positions()) SetSourcePosition(expr->position());
9697   int argument_count = expr->arguments()->length() + 1;  // Plus constructor.
9698   Factory* factory = isolate()->factory();
9699
9700   // The constructor function is on the stack in the unoptimized code
9701   // during evaluation of the arguments.
9702   CHECK_ALIVE(VisitForValue(expr->expression()));
9703   HValue* function = Top();
9704   CHECK_ALIVE(VisitExpressions(expr->arguments()));
9705
9706   if (function->IsConstant() &&
9707       HConstant::cast(function)->handle(isolate())->IsJSFunction()) {
9708     Handle<Object> constant = HConstant::cast(function)->handle(isolate());
9709     expr->SetKnownGlobalTarget(Handle<JSFunction>::cast(constant));
9710   }
9711
9712   if (FLAG_inline_construct &&
9713       expr->IsMonomorphic() &&
9714       IsAllocationInlineable(expr->target())) {
9715     Handle<JSFunction> constructor = expr->target();
9716     HValue* check = Add<HCheckValue>(function, constructor);
9717
9718     // Force completion of inobject slack tracking before generating
9719     // allocation code to finalize instance size.
9720     if (constructor->IsInobjectSlackTrackingInProgress()) {
9721       constructor->CompleteInobjectSlackTracking();
9722     }
9723
9724     // Calculate instance size from initial map of constructor.
9725     DCHECK(constructor->has_initial_map());
9726     Handle<Map> initial_map(constructor->initial_map());
9727     int instance_size = initial_map->instance_size();
9728
9729     // Allocate an instance of the implicit receiver object.
9730     HValue* size_in_bytes = Add<HConstant>(instance_size);
9731     HAllocationMode allocation_mode;
9732     if (FLAG_pretenuring_call_new) {
9733       if (FLAG_allocation_site_pretenuring) {
9734         // Try to use pretenuring feedback.
9735         Handle<AllocationSite> allocation_site = expr->allocation_site();
9736         allocation_mode = HAllocationMode(allocation_site);
9737         // Take a dependency on allocation site.
9738         top_info()->dependencies()->AssumeTenuringDecision(allocation_site);
9739       }
9740     }
9741
9742     HAllocate* receiver = BuildAllocate(
9743         size_in_bytes, HType::JSObject(), JS_OBJECT_TYPE, allocation_mode);
9744     receiver->set_known_initial_map(initial_map);
9745
9746     // Initialize map and fields of the newly allocated object.
9747     { NoObservableSideEffectsScope no_effects(this);
9748       DCHECK(initial_map->instance_type() == JS_OBJECT_TYPE);
9749       Add<HStoreNamedField>(receiver,
9750           HObjectAccess::ForMapAndOffset(initial_map, JSObject::kMapOffset),
9751           Add<HConstant>(initial_map));
9752       HValue* empty_fixed_array = Add<HConstant>(factory->empty_fixed_array());
9753       Add<HStoreNamedField>(receiver,
9754           HObjectAccess::ForMapAndOffset(initial_map,
9755                                          JSObject::kPropertiesOffset),
9756           empty_fixed_array);
9757       Add<HStoreNamedField>(receiver,
9758           HObjectAccess::ForMapAndOffset(initial_map,
9759                                          JSObject::kElementsOffset),
9760           empty_fixed_array);
9761       BuildInitializeInobjectProperties(receiver, initial_map);
9762     }
9763
9764     // Replace the constructor function with a newly allocated receiver using
9765     // the index of the receiver from the top of the expression stack.
9766     const int receiver_index = argument_count - 1;
9767     DCHECK(environment()->ExpressionStackAt(receiver_index) == function);
9768     environment()->SetExpressionStackAt(receiver_index, receiver);
9769
9770     if (TryInlineConstruct(expr, receiver)) {
9771       // Inlining worked, add a dependency on the initial map to make sure that
9772       // this code is deoptimized whenever the initial map of the constructor
9773       // changes.
9774       top_info()->dependencies()->AssumeInitialMapCantChange(initial_map);
9775       return;
9776     }
9777
9778     // TODO(mstarzinger): For now we remove the previous HAllocate and all
9779     // corresponding instructions and instead add HPushArguments for the
9780     // arguments in case inlining failed.  What we actually should do is for
9781     // inlining to try to build a subgraph without mutating the parent graph.
9782     HInstruction* instr = current_block()->last();
9783     do {
9784       HInstruction* prev_instr = instr->previous();
9785       instr->DeleteAndReplaceWith(NULL);
9786       instr = prev_instr;
9787     } while (instr != check);
9788     environment()->SetExpressionStackAt(receiver_index, function);
9789     HInstruction* call =
9790       PreProcessCall(New<HCallNew>(function, argument_count));
9791     return ast_context()->ReturnInstruction(call, expr->id());
9792   } else {
9793     // The constructor function is both an operand to the instruction and an
9794     // argument to the construct call.
9795     if (TryHandleArrayCallNew(expr, function)) return;
9796
9797     HInstruction* call =
9798         PreProcessCall(New<HCallNew>(function, argument_count));
9799     return ast_context()->ReturnInstruction(call, expr->id());
9800   }
9801 }
9802
9803
9804 void HOptimizedGraphBuilder::BuildInitializeInobjectProperties(
9805     HValue* receiver, Handle<Map> initial_map) {
9806   if (initial_map->inobject_properties() != 0) {
9807     HConstant* undefined = graph()->GetConstantUndefined();
9808     for (int i = 0; i < initial_map->inobject_properties(); i++) {
9809       int property_offset = initial_map->GetInObjectPropertyOffset(i);
9810       Add<HStoreNamedField>(receiver, HObjectAccess::ForMapAndOffset(
9811                                           initial_map, property_offset),
9812                             undefined);
9813     }
9814   }
9815 }
9816
9817
9818 HValue* HGraphBuilder::BuildAllocateEmptyArrayBuffer(HValue* byte_length) {
9819   // We HForceRepresentation here to avoid allocations during an *-to-tagged
9820   // HChange that could cause GC while the array buffer object is not fully
9821   // initialized.
9822   HObjectAccess byte_length_access(HObjectAccess::ForJSArrayBufferByteLength());
9823   byte_length = AddUncasted<HForceRepresentation>(
9824       byte_length, byte_length_access.representation());
9825   HAllocate* result =
9826       BuildAllocate(Add<HConstant>(JSArrayBuffer::kSizeWithInternalFields),
9827                     HType::JSObject(), JS_ARRAY_BUFFER_TYPE, HAllocationMode());
9828
9829   HValue* global_object = Add<HLoadNamedField>(
9830       context(), nullptr,
9831       HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
9832   HValue* native_context = Add<HLoadNamedField>(
9833       global_object, nullptr, HObjectAccess::ForGlobalObjectNativeContext());
9834   Add<HStoreNamedField>(
9835       result, HObjectAccess::ForMap(),
9836       Add<HLoadNamedField>(
9837           native_context, nullptr,
9838           HObjectAccess::ForContextSlot(Context::ARRAY_BUFFER_MAP_INDEX)));
9839
9840   HConstant* empty_fixed_array =
9841       Add<HConstant>(isolate()->factory()->empty_fixed_array());
9842   Add<HStoreNamedField>(
9843       result, HObjectAccess::ForJSArrayOffset(JSArray::kPropertiesOffset),
9844       empty_fixed_array);
9845   Add<HStoreNamedField>(
9846       result, HObjectAccess::ForJSArrayOffset(JSArray::kElementsOffset),
9847       empty_fixed_array);
9848   Add<HStoreNamedField>(
9849       result, HObjectAccess::ForJSArrayBufferBackingStore().WithRepresentation(
9850                   Representation::Smi()),
9851       graph()->GetConstant0());
9852   Add<HStoreNamedField>(result, byte_length_access, byte_length);
9853   Add<HStoreNamedField>(result, HObjectAccess::ForJSArrayBufferBitFieldSlot(),
9854                         graph()->GetConstant0());
9855   Add<HStoreNamedField>(
9856       result, HObjectAccess::ForJSArrayBufferBitField(),
9857       Add<HConstant>((1 << JSArrayBuffer::IsExternal::kShift) |
9858                      (1 << JSArrayBuffer::IsNeuterable::kShift)));
9859
9860   for (int field = 0; field < v8::ArrayBuffer::kInternalFieldCount; ++field) {
9861     Add<HStoreNamedField>(
9862         result,
9863         HObjectAccess::ForObservableJSObjectOffset(
9864             JSArrayBuffer::kSize + field * kPointerSize, Representation::Smi()),
9865         graph()->GetConstant0());
9866   }
9867
9868   return result;
9869 }
9870
9871
9872 template <class ViewClass>
9873 void HGraphBuilder::BuildArrayBufferViewInitialization(
9874     HValue* obj,
9875     HValue* buffer,
9876     HValue* byte_offset,
9877     HValue* byte_length) {
9878
9879   for (int offset = ViewClass::kSize;
9880        offset < ViewClass::kSizeWithInternalFields;
9881        offset += kPointerSize) {
9882     Add<HStoreNamedField>(obj,
9883         HObjectAccess::ForObservableJSObjectOffset(offset),
9884         graph()->GetConstant0());
9885   }
9886
9887   Add<HStoreNamedField>(
9888       obj,
9889       HObjectAccess::ForJSArrayBufferViewByteOffset(),
9890       byte_offset);
9891   Add<HStoreNamedField>(
9892       obj,
9893       HObjectAccess::ForJSArrayBufferViewByteLength(),
9894       byte_length);
9895   Add<HStoreNamedField>(obj, HObjectAccess::ForJSArrayBufferViewBuffer(),
9896                         buffer);
9897 }
9898
9899
9900 void HOptimizedGraphBuilder::GenerateDataViewInitialize(
9901     CallRuntime* expr) {
9902   ZoneList<Expression*>* arguments = expr->arguments();
9903
9904   DCHECK(arguments->length()== 4);
9905   CHECK_ALIVE(VisitForValue(arguments->at(0)));
9906   HValue* obj = Pop();
9907
9908   CHECK_ALIVE(VisitForValue(arguments->at(1)));
9909   HValue* buffer = Pop();
9910
9911   CHECK_ALIVE(VisitForValue(arguments->at(2)));
9912   HValue* byte_offset = Pop();
9913
9914   CHECK_ALIVE(VisitForValue(arguments->at(3)));
9915   HValue* byte_length = Pop();
9916
9917   {
9918     NoObservableSideEffectsScope scope(this);
9919     BuildArrayBufferViewInitialization<JSDataView>(
9920         obj, buffer, byte_offset, byte_length);
9921   }
9922 }
9923
9924
9925 static Handle<Map> TypedArrayMap(Isolate* isolate,
9926                                  ExternalArrayType array_type,
9927                                  ElementsKind target_kind) {
9928   Handle<Context> native_context = isolate->native_context();
9929   Handle<JSFunction> fun;
9930   switch (array_type) {
9931 #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size)                       \
9932     case kExternal##Type##Array:                                              \
9933       fun = Handle<JSFunction>(native_context->type##_array_fun());           \
9934       break;
9935
9936     TYPED_ARRAYS(TYPED_ARRAY_CASE)
9937 #undef TYPED_ARRAY_CASE
9938   }
9939   Handle<Map> map(fun->initial_map());
9940   return Map::AsElementsKind(map, target_kind);
9941 }
9942
9943
9944 HValue* HOptimizedGraphBuilder::BuildAllocateExternalElements(
9945     ExternalArrayType array_type,
9946     bool is_zero_byte_offset,
9947     HValue* buffer, HValue* byte_offset, HValue* length) {
9948   Handle<Map> external_array_map(
9949       isolate()->heap()->MapForExternalArrayType(array_type));
9950
9951   // The HForceRepresentation is to prevent possible deopt on int-smi
9952   // conversion after allocation but before the new object fields are set.
9953   length = AddUncasted<HForceRepresentation>(length, Representation::Smi());
9954   HValue* elements =
9955       Add<HAllocate>(Add<HConstant>(ExternalArray::kSize), HType::HeapObject(),
9956                      NOT_TENURED, external_array_map->instance_type());
9957
9958   AddStoreMapConstant(elements, external_array_map);
9959   Add<HStoreNamedField>(elements,
9960       HObjectAccess::ForFixedArrayLength(), length);
9961
9962   HValue* backing_store = Add<HLoadNamedField>(
9963       buffer, nullptr, HObjectAccess::ForJSArrayBufferBackingStore());
9964
9965   HValue* typed_array_start;
9966   if (is_zero_byte_offset) {
9967     typed_array_start = backing_store;
9968   } else {
9969     HInstruction* external_pointer =
9970         AddUncasted<HAdd>(backing_store, byte_offset);
9971     // Arguments are checked prior to call to TypedArrayInitialize,
9972     // including byte_offset.
9973     external_pointer->ClearFlag(HValue::kCanOverflow);
9974     typed_array_start = external_pointer;
9975   }
9976
9977   Add<HStoreNamedField>(elements,
9978       HObjectAccess::ForExternalArrayExternalPointer(),
9979       typed_array_start);
9980
9981   return elements;
9982 }
9983
9984
9985 HValue* HOptimizedGraphBuilder::BuildAllocateFixedTypedArray(
9986     ExternalArrayType array_type, size_t element_size,
9987     ElementsKind fixed_elements_kind, HValue* byte_length, HValue* length,
9988     bool initialize) {
9989   STATIC_ASSERT(
9990       (FixedTypedArrayBase::kHeaderSize & kObjectAlignmentMask) == 0);
9991   HValue* total_size;
9992
9993   // if fixed array's elements are not aligned to object's alignment,
9994   // we need to align the whole array to object alignment.
9995   if (element_size % kObjectAlignment != 0) {
9996     total_size = BuildObjectSizeAlignment(
9997         byte_length, FixedTypedArrayBase::kHeaderSize);
9998   } else {
9999     total_size = AddUncasted<HAdd>(byte_length,
10000         Add<HConstant>(FixedTypedArrayBase::kHeaderSize));
10001     total_size->ClearFlag(HValue::kCanOverflow);
10002   }
10003
10004   // The HForceRepresentation is to prevent possible deopt on int-smi
10005   // conversion after allocation but before the new object fields are set.
10006   length = AddUncasted<HForceRepresentation>(length, Representation::Smi());
10007   Handle<Map> fixed_typed_array_map(
10008       isolate()->heap()->MapForFixedTypedArray(array_type));
10009   HAllocate* elements =
10010       Add<HAllocate>(total_size, HType::HeapObject(), NOT_TENURED,
10011                      fixed_typed_array_map->instance_type());
10012
10013 #ifndef V8_HOST_ARCH_64_BIT
10014   if (array_type == kExternalFloat64Array) {
10015     elements->MakeDoubleAligned();
10016   }
10017 #endif
10018
10019   AddStoreMapConstant(elements, fixed_typed_array_map);
10020
10021   Add<HStoreNamedField>(elements,
10022       HObjectAccess::ForFixedArrayLength(),
10023       length);
10024   Add<HStoreNamedField>(
10025       elements, HObjectAccess::ForFixedTypedArrayBaseBasePointer(), elements);
10026
10027   Add<HStoreNamedField>(
10028       elements, HObjectAccess::ForFixedTypedArrayBaseExternalPointer(),
10029       Add<HConstant>(ExternalReference::fixed_typed_array_base_data_offset()));
10030
10031   HValue* filler = Add<HConstant>(static_cast<int32_t>(0));
10032
10033   if (initialize) {
10034     LoopBuilder builder(this, context(), LoopBuilder::kPostIncrement);
10035
10036     HValue* backing_store = AddUncasted<HAdd>(
10037         Add<HConstant>(ExternalReference::fixed_typed_array_base_data_offset()),
10038         elements, Strength::WEAK, AddOfExternalAndTagged);
10039
10040     HValue* key = builder.BeginBody(
10041         Add<HConstant>(static_cast<int32_t>(0)),
10042         length, Token::LT);
10043     Add<HStoreKeyed>(backing_store, key, filler, fixed_elements_kind);
10044
10045     builder.EndBody();
10046   }
10047   return elements;
10048 }
10049
10050
10051 void HOptimizedGraphBuilder::GenerateTypedArrayInitialize(
10052     CallRuntime* expr) {
10053   ZoneList<Expression*>* arguments = expr->arguments();
10054
10055   static const int kObjectArg = 0;
10056   static const int kArrayIdArg = 1;
10057   static const int kBufferArg = 2;
10058   static const int kByteOffsetArg = 3;
10059   static const int kByteLengthArg = 4;
10060   static const int kInitializeArg = 5;
10061   static const int kArgsLength = 6;
10062   DCHECK(arguments->length() == kArgsLength);
10063
10064
10065   CHECK_ALIVE(VisitForValue(arguments->at(kObjectArg)));
10066   HValue* obj = Pop();
10067
10068   if (!arguments->at(kArrayIdArg)->IsLiteral()) {
10069     // This should never happen in real use, but can happen when fuzzing.
10070     // Just bail out.
10071     Bailout(kNeedSmiLiteral);
10072     return;
10073   }
10074   Handle<Object> value =
10075       static_cast<Literal*>(arguments->at(kArrayIdArg))->value();
10076   if (!value->IsSmi()) {
10077     // This should never happen in real use, but can happen when fuzzing.
10078     // Just bail out.
10079     Bailout(kNeedSmiLiteral);
10080     return;
10081   }
10082   int array_id = Smi::cast(*value)->value();
10083
10084   HValue* buffer;
10085   if (!arguments->at(kBufferArg)->IsNullLiteral()) {
10086     CHECK_ALIVE(VisitForValue(arguments->at(kBufferArg)));
10087     buffer = Pop();
10088   } else {
10089     buffer = NULL;
10090   }
10091
10092   HValue* byte_offset;
10093   bool is_zero_byte_offset;
10094
10095   if (arguments->at(kByteOffsetArg)->IsLiteral()
10096       && Smi::FromInt(0) ==
10097       *static_cast<Literal*>(arguments->at(kByteOffsetArg))->value()) {
10098     byte_offset = Add<HConstant>(static_cast<int32_t>(0));
10099     is_zero_byte_offset = true;
10100   } else {
10101     CHECK_ALIVE(VisitForValue(arguments->at(kByteOffsetArg)));
10102     byte_offset = Pop();
10103     is_zero_byte_offset = false;
10104     DCHECK(buffer != NULL);
10105   }
10106
10107   CHECK_ALIVE(VisitForValue(arguments->at(kByteLengthArg)));
10108   HValue* byte_length = Pop();
10109
10110   CHECK(arguments->at(kInitializeArg)->IsLiteral());
10111   bool initialize = static_cast<Literal*>(arguments->at(kInitializeArg))
10112                         ->value()
10113                         ->BooleanValue();
10114
10115   NoObservableSideEffectsScope scope(this);
10116   IfBuilder byte_offset_smi(this);
10117
10118   if (!is_zero_byte_offset) {
10119     byte_offset_smi.If<HIsSmiAndBranch>(byte_offset);
10120     byte_offset_smi.Then();
10121   }
10122
10123   ExternalArrayType array_type =
10124       kExternalInt8Array;  // Bogus initialization.
10125   size_t element_size = 1;  // Bogus initialization.
10126   ElementsKind external_elements_kind =  // Bogus initialization.
10127       EXTERNAL_INT8_ELEMENTS;
10128   ElementsKind fixed_elements_kind =  // Bogus initialization.
10129       INT8_ELEMENTS;
10130   Runtime::ArrayIdToTypeAndSize(array_id,
10131       &array_type,
10132       &external_elements_kind,
10133       &fixed_elements_kind,
10134       &element_size);
10135
10136
10137   { //  byte_offset is Smi.
10138     HValue* allocated_buffer = buffer;
10139     if (buffer == NULL) {
10140       allocated_buffer = BuildAllocateEmptyArrayBuffer(byte_length);
10141     }
10142     BuildArrayBufferViewInitialization<JSTypedArray>(obj, allocated_buffer,
10143                                                      byte_offset, byte_length);
10144
10145
10146     HInstruction* length = AddUncasted<HDiv>(byte_length,
10147         Add<HConstant>(static_cast<int32_t>(element_size)));
10148
10149     Add<HStoreNamedField>(obj,
10150         HObjectAccess::ForJSTypedArrayLength(),
10151         length);
10152
10153     HValue* elements;
10154     if (buffer != NULL) {
10155       elements = BuildAllocateExternalElements(
10156           array_type, is_zero_byte_offset, buffer, byte_offset, length);
10157       Handle<Map> obj_map = TypedArrayMap(
10158           isolate(), array_type, external_elements_kind);
10159       AddStoreMapConstant(obj, obj_map);
10160     } else {
10161       DCHECK(is_zero_byte_offset);
10162       elements = BuildAllocateFixedTypedArray(array_type, element_size,
10163                                               fixed_elements_kind, byte_length,
10164                                               length, initialize);
10165     }
10166     Add<HStoreNamedField>(
10167         obj, HObjectAccess::ForElementsPointer(), elements);
10168   }
10169
10170   if (!is_zero_byte_offset) {
10171     byte_offset_smi.Else();
10172     { //  byte_offset is not Smi.
10173       Push(obj);
10174       CHECK_ALIVE(VisitForValue(arguments->at(kArrayIdArg)));
10175       Push(buffer);
10176       Push(byte_offset);
10177       Push(byte_length);
10178       CHECK_ALIVE(VisitForValue(arguments->at(kInitializeArg)));
10179       PushArgumentsFromEnvironment(kArgsLength);
10180       Add<HCallRuntime>(expr->name(), expr->function(), kArgsLength);
10181     }
10182   }
10183   byte_offset_smi.End();
10184 }
10185
10186
10187 void HOptimizedGraphBuilder::GenerateMaxSmi(CallRuntime* expr) {
10188   DCHECK(expr->arguments()->length() == 0);
10189   HConstant* max_smi = New<HConstant>(static_cast<int32_t>(Smi::kMaxValue));
10190   return ast_context()->ReturnInstruction(max_smi, expr->id());
10191 }
10192
10193
10194 void HOptimizedGraphBuilder::GenerateTypedArrayMaxSizeInHeap(
10195     CallRuntime* expr) {
10196   DCHECK(expr->arguments()->length() == 0);
10197   HConstant* result = New<HConstant>(static_cast<int32_t>(
10198         FLAG_typed_array_max_size_in_heap));
10199   return ast_context()->ReturnInstruction(result, expr->id());
10200 }
10201
10202
10203 void HOptimizedGraphBuilder::GenerateArrayBufferGetByteLength(
10204     CallRuntime* expr) {
10205   DCHECK(expr->arguments()->length() == 1);
10206   CHECK_ALIVE(VisitForValue(expr->arguments()->at(0)));
10207   HValue* buffer = Pop();
10208   HInstruction* result = New<HLoadNamedField>(
10209       buffer, nullptr, HObjectAccess::ForJSArrayBufferByteLength());
10210   return ast_context()->ReturnInstruction(result, expr->id());
10211 }
10212
10213
10214 void HOptimizedGraphBuilder::GenerateArrayBufferViewGetByteLength(
10215     CallRuntime* expr) {
10216   NoObservableSideEffectsScope scope(this);
10217   DCHECK(expr->arguments()->length() == 1);
10218   CHECK_ALIVE(VisitForValue(expr->arguments()->at(0)));
10219   HValue* view = Pop();
10220
10221   return ast_context()->ReturnValue(BuildArrayBufferViewFieldAccessor(
10222       view, nullptr,
10223       FieldIndex::ForInObjectOffset(JSArrayBufferView::kByteLengthOffset)));
10224 }
10225
10226
10227 void HOptimizedGraphBuilder::GenerateArrayBufferViewGetByteOffset(
10228     CallRuntime* expr) {
10229   NoObservableSideEffectsScope scope(this);
10230   DCHECK(expr->arguments()->length() == 1);
10231   CHECK_ALIVE(VisitForValue(expr->arguments()->at(0)));
10232   HValue* view = Pop();
10233
10234   return ast_context()->ReturnValue(BuildArrayBufferViewFieldAccessor(
10235       view, nullptr,
10236       FieldIndex::ForInObjectOffset(JSArrayBufferView::kByteOffsetOffset)));
10237 }
10238
10239
10240 void HOptimizedGraphBuilder::GenerateTypedArrayGetLength(
10241     CallRuntime* expr) {
10242   NoObservableSideEffectsScope scope(this);
10243   DCHECK(expr->arguments()->length() == 1);
10244   CHECK_ALIVE(VisitForValue(expr->arguments()->at(0)));
10245   HValue* view = Pop();
10246
10247   return ast_context()->ReturnValue(BuildArrayBufferViewFieldAccessor(
10248       view, nullptr,
10249       FieldIndex::ForInObjectOffset(JSTypedArray::kLengthOffset)));
10250 }
10251
10252
10253 void HOptimizedGraphBuilder::VisitCallRuntime(CallRuntime* expr) {
10254   DCHECK(!HasStackOverflow());
10255   DCHECK(current_block() != NULL);
10256   DCHECK(current_block()->HasPredecessor());
10257   if (expr->is_jsruntime()) {
10258     return Bailout(kCallToAJavaScriptRuntimeFunction);
10259   }
10260
10261   const Runtime::Function* function = expr->function();
10262   DCHECK(function != NULL);
10263   switch (function->function_id) {
10264 #define CALL_INTRINSIC_GENERATOR(Name) \
10265   case Runtime::kInline##Name:         \
10266     return Generate##Name(expr);
10267
10268     FOR_EACH_HYDROGEN_INTRINSIC(CALL_INTRINSIC_GENERATOR)
10269 #undef CALL_INTRINSIC_GENERATOR
10270     default: {
10271       Handle<String> name = expr->name();
10272       int argument_count = expr->arguments()->length();
10273       CHECK_ALIVE(VisitExpressions(expr->arguments()));
10274       PushArgumentsFromEnvironment(argument_count);
10275       HCallRuntime* call = New<HCallRuntime>(name, function, argument_count);
10276       return ast_context()->ReturnInstruction(call, expr->id());
10277     }
10278   }
10279 }
10280
10281
10282 void HOptimizedGraphBuilder::VisitUnaryOperation(UnaryOperation* expr) {
10283   DCHECK(!HasStackOverflow());
10284   DCHECK(current_block() != NULL);
10285   DCHECK(current_block()->HasPredecessor());
10286   switch (expr->op()) {
10287     case Token::DELETE: return VisitDelete(expr);
10288     case Token::VOID: return VisitVoid(expr);
10289     case Token::TYPEOF: return VisitTypeof(expr);
10290     case Token::NOT: return VisitNot(expr);
10291     default: UNREACHABLE();
10292   }
10293 }
10294
10295
10296 void HOptimizedGraphBuilder::VisitDelete(UnaryOperation* expr) {
10297   Property* prop = expr->expression()->AsProperty();
10298   VariableProxy* proxy = expr->expression()->AsVariableProxy();
10299   if (prop != NULL) {
10300     CHECK_ALIVE(VisitForValue(prop->obj()));
10301     CHECK_ALIVE(VisitForValue(prop->key()));
10302     HValue* key = Pop();
10303     HValue* obj = Pop();
10304     HValue* function = AddLoadJSBuiltin(Builtins::DELETE);
10305     Add<HPushArguments>(obj, key, Add<HConstant>(function_language_mode()));
10306     // TODO(olivf) InvokeFunction produces a check for the parameter count,
10307     // even though we are certain to pass the correct number of arguments here.
10308     HInstruction* instr = New<HInvokeFunction>(function, 3);
10309     return ast_context()->ReturnInstruction(instr, expr->id());
10310   } else if (proxy != NULL) {
10311     Variable* var = proxy->var();
10312     if (var->IsUnallocatedOrGlobalSlot()) {
10313       Bailout(kDeleteWithGlobalVariable);
10314     } else if (var->IsStackAllocated() || var->IsContextSlot()) {
10315       // Result of deleting non-global variables is false.  'this' is not really
10316       // a variable, though we implement it as one.  The subexpression does not
10317       // have side effects.
10318       HValue* value = var->HasThisName(isolate()) ? graph()->GetConstantTrue()
10319                                                   : graph()->GetConstantFalse();
10320       return ast_context()->ReturnValue(value);
10321     } else {
10322       Bailout(kDeleteWithNonGlobalVariable);
10323     }
10324   } else {
10325     // Result of deleting non-property, non-variable reference is true.
10326     // Evaluate the subexpression for side effects.
10327     CHECK_ALIVE(VisitForEffect(expr->expression()));
10328     return ast_context()->ReturnValue(graph()->GetConstantTrue());
10329   }
10330 }
10331
10332
10333 void HOptimizedGraphBuilder::VisitVoid(UnaryOperation* expr) {
10334   CHECK_ALIVE(VisitForEffect(expr->expression()));
10335   return ast_context()->ReturnValue(graph()->GetConstantUndefined());
10336 }
10337
10338
10339 void HOptimizedGraphBuilder::VisitTypeof(UnaryOperation* expr) {
10340   CHECK_ALIVE(VisitForTypeOf(expr->expression()));
10341   HValue* value = Pop();
10342   HInstruction* instr = New<HTypeof>(value);
10343   return ast_context()->ReturnInstruction(instr, expr->id());
10344 }
10345
10346
10347 void HOptimizedGraphBuilder::VisitNot(UnaryOperation* expr) {
10348   if (ast_context()->IsTest()) {
10349     TestContext* context = TestContext::cast(ast_context());
10350     VisitForControl(expr->expression(),
10351                     context->if_false(),
10352                     context->if_true());
10353     return;
10354   }
10355
10356   if (ast_context()->IsEffect()) {
10357     VisitForEffect(expr->expression());
10358     return;
10359   }
10360
10361   DCHECK(ast_context()->IsValue());
10362   HBasicBlock* materialize_false = graph()->CreateBasicBlock();
10363   HBasicBlock* materialize_true = graph()->CreateBasicBlock();
10364   CHECK_BAILOUT(VisitForControl(expr->expression(),
10365                                 materialize_false,
10366                                 materialize_true));
10367
10368   if (materialize_false->HasPredecessor()) {
10369     materialize_false->SetJoinId(expr->MaterializeFalseId());
10370     set_current_block(materialize_false);
10371     Push(graph()->GetConstantFalse());
10372   } else {
10373     materialize_false = NULL;
10374   }
10375
10376   if (materialize_true->HasPredecessor()) {
10377     materialize_true->SetJoinId(expr->MaterializeTrueId());
10378     set_current_block(materialize_true);
10379     Push(graph()->GetConstantTrue());
10380   } else {
10381     materialize_true = NULL;
10382   }
10383
10384   HBasicBlock* join =
10385     CreateJoin(materialize_false, materialize_true, expr->id());
10386   set_current_block(join);
10387   if (join != NULL) return ast_context()->ReturnValue(Pop());
10388 }
10389
10390
10391 static Representation RepresentationFor(Type* type) {
10392   DisallowHeapAllocation no_allocation;
10393   if (type->Is(Type::None())) return Representation::None();
10394   if (type->Is(Type::SignedSmall())) return Representation::Smi();
10395   if (type->Is(Type::Signed32())) return Representation::Integer32();
10396   if (type->Is(Type::Number())) return Representation::Double();
10397   return Representation::Tagged();
10398 }
10399
10400
10401 HInstruction* HOptimizedGraphBuilder::BuildIncrement(
10402     bool returns_original_input,
10403     CountOperation* expr) {
10404   // The input to the count operation is on top of the expression stack.
10405   Representation rep = RepresentationFor(expr->type());
10406   if (rep.IsNone() || rep.IsTagged()) {
10407     rep = Representation::Smi();
10408   }
10409
10410   if (returns_original_input && !is_strong(function_language_mode())) {
10411     // We need an explicit HValue representing ToNumber(input).  The
10412     // actual HChange instruction we need is (sometimes) added in a later
10413     // phase, so it is not available now to be used as an input to HAdd and
10414     // as the return value.
10415     HInstruction* number_input = AddUncasted<HForceRepresentation>(Pop(), rep);
10416     if (!rep.IsDouble()) {
10417       number_input->SetFlag(HInstruction::kFlexibleRepresentation);
10418       number_input->SetFlag(HInstruction::kCannotBeTagged);
10419     }
10420     Push(number_input);
10421   }
10422
10423   // The addition has no side effects, so we do not need
10424   // to simulate the expression stack after this instruction.
10425   // Any later failures deopt to the load of the input or earlier.
10426   HConstant* delta = (expr->op() == Token::INC)
10427       ? graph()->GetConstant1()
10428       : graph()->GetConstantMinus1();
10429   HInstruction* instr =
10430       AddUncasted<HAdd>(Top(), delta, strength(function_language_mode()));
10431   if (instr->IsAdd()) {
10432     HAdd* add = HAdd::cast(instr);
10433     add->set_observed_input_representation(1, rep);
10434     add->set_observed_input_representation(2, Representation::Smi());
10435   }
10436   if (!is_strong(function_language_mode())) {
10437     instr->ClearAllSideEffects();
10438   } else {
10439     Add<HSimulate>(expr->ToNumberId(), REMOVABLE_SIMULATE);
10440   }
10441   instr->SetFlag(HInstruction::kCannotBeTagged);
10442   return instr;
10443 }
10444
10445
10446 void HOptimizedGraphBuilder::BuildStoreForEffect(Expression* expr,
10447                                                  Property* prop,
10448                                                  BailoutId ast_id,
10449                                                  BailoutId return_id,
10450                                                  HValue* object,
10451                                                  HValue* key,
10452                                                  HValue* value) {
10453   EffectContext for_effect(this);
10454   Push(object);
10455   if (key != NULL) Push(key);
10456   Push(value);
10457   BuildStore(expr, prop, ast_id, return_id);
10458 }
10459
10460
10461 void HOptimizedGraphBuilder::VisitCountOperation(CountOperation* expr) {
10462   DCHECK(!HasStackOverflow());
10463   DCHECK(current_block() != NULL);
10464   DCHECK(current_block()->HasPredecessor());
10465   if (!top_info()->is_tracking_positions()) SetSourcePosition(expr->position());
10466   Expression* target = expr->expression();
10467   VariableProxy* proxy = target->AsVariableProxy();
10468   Property* prop = target->AsProperty();
10469   if (proxy == NULL && prop == NULL) {
10470     return Bailout(kInvalidLhsInCountOperation);
10471   }
10472
10473   // Match the full code generator stack by simulating an extra stack
10474   // element for postfix operations in a non-effect context.  The return
10475   // value is ToNumber(input).
10476   bool returns_original_input =
10477       expr->is_postfix() && !ast_context()->IsEffect();
10478   HValue* input = NULL;  // ToNumber(original_input).
10479   HValue* after = NULL;  // The result after incrementing or decrementing.
10480
10481   if (proxy != NULL) {
10482     Variable* var = proxy->var();
10483     if (var->mode() == CONST_LEGACY)  {
10484       return Bailout(kUnsupportedCountOperationWithConst);
10485     }
10486     if (var->mode() == CONST) {
10487       return Bailout(kNonInitializerAssignmentToConst);
10488     }
10489     // Argument of the count operation is a variable, not a property.
10490     DCHECK(prop == NULL);
10491     CHECK_ALIVE(VisitForValue(target));
10492
10493     after = BuildIncrement(returns_original_input, expr);
10494     input = returns_original_input ? Top() : Pop();
10495     Push(after);
10496
10497     switch (var->location()) {
10498       case VariableLocation::GLOBAL:
10499       case VariableLocation::UNALLOCATED:
10500         HandleGlobalVariableAssignment(var,
10501                                        after,
10502                                        expr->AssignmentId());
10503         break;
10504
10505       case VariableLocation::PARAMETER:
10506       case VariableLocation::LOCAL:
10507         BindIfLive(var, after);
10508         break;
10509
10510       case VariableLocation::CONTEXT: {
10511         // Bail out if we try to mutate a parameter value in a function
10512         // using the arguments object.  We do not (yet) correctly handle the
10513         // arguments property of the function.
10514         if (current_info()->scope()->arguments() != NULL) {
10515           // Parameters will rewrite to context slots.  We have no direct
10516           // way to detect that the variable is a parameter so we use a
10517           // linear search of the parameter list.
10518           int count = current_info()->scope()->num_parameters();
10519           for (int i = 0; i < count; ++i) {
10520             if (var == current_info()->scope()->parameter(i)) {
10521               return Bailout(kAssignmentToParameterInArgumentsObject);
10522             }
10523           }
10524         }
10525
10526         HValue* context = BuildContextChainWalk(var);
10527         HStoreContextSlot::Mode mode = IsLexicalVariableMode(var->mode())
10528             ? HStoreContextSlot::kCheckDeoptimize : HStoreContextSlot::kNoCheck;
10529         HStoreContextSlot* instr = Add<HStoreContextSlot>(context, var->index(),
10530                                                           mode, after);
10531         if (instr->HasObservableSideEffects()) {
10532           Add<HSimulate>(expr->AssignmentId(), REMOVABLE_SIMULATE);
10533         }
10534         break;
10535       }
10536
10537       case VariableLocation::LOOKUP:
10538         return Bailout(kLookupVariableInCountOperation);
10539     }
10540
10541     Drop(returns_original_input ? 2 : 1);
10542     return ast_context()->ReturnValue(expr->is_postfix() ? input : after);
10543   }
10544
10545   // Argument of the count operation is a property.
10546   DCHECK(prop != NULL);
10547   if (returns_original_input) Push(graph()->GetConstantUndefined());
10548
10549   CHECK_ALIVE(VisitForValue(prop->obj()));
10550   HValue* object = Top();
10551
10552   HValue* key = NULL;
10553   if (!prop->key()->IsPropertyName() || prop->IsStringAccess()) {
10554     CHECK_ALIVE(VisitForValue(prop->key()));
10555     key = Top();
10556   }
10557
10558   CHECK_ALIVE(PushLoad(prop, object, key));
10559
10560   after = BuildIncrement(returns_original_input, expr);
10561
10562   if (returns_original_input) {
10563     input = Pop();
10564     // Drop object and key to push it again in the effect context below.
10565     Drop(key == NULL ? 1 : 2);
10566     environment()->SetExpressionStackAt(0, input);
10567     CHECK_ALIVE(BuildStoreForEffect(
10568         expr, prop, expr->id(), expr->AssignmentId(), object, key, after));
10569     return ast_context()->ReturnValue(Pop());
10570   }
10571
10572   environment()->SetExpressionStackAt(0, after);
10573   return BuildStore(expr, prop, expr->id(), expr->AssignmentId());
10574 }
10575
10576
10577 HInstruction* HOptimizedGraphBuilder::BuildStringCharCodeAt(
10578     HValue* string,
10579     HValue* index) {
10580   if (string->IsConstant() && index->IsConstant()) {
10581     HConstant* c_string = HConstant::cast(string);
10582     HConstant* c_index = HConstant::cast(index);
10583     if (c_string->HasStringValue() && c_index->HasNumberValue()) {
10584       int32_t i = c_index->NumberValueAsInteger32();
10585       Handle<String> s = c_string->StringValue();
10586       if (i < 0 || i >= s->length()) {
10587         return New<HConstant>(std::numeric_limits<double>::quiet_NaN());
10588       }
10589       return New<HConstant>(s->Get(i));
10590     }
10591   }
10592   string = BuildCheckString(string);
10593   index = Add<HBoundsCheck>(index, AddLoadStringLength(string));
10594   return New<HStringCharCodeAt>(string, index);
10595 }
10596
10597
10598 // Checks if the given shift amounts have following forms:
10599 // (N1) and (N2) with N1 + N2 = 32; (sa) and (32 - sa).
10600 static bool ShiftAmountsAllowReplaceByRotate(HValue* sa,
10601                                              HValue* const32_minus_sa) {
10602   if (sa->IsConstant() && const32_minus_sa->IsConstant()) {
10603     const HConstant* c1 = HConstant::cast(sa);
10604     const HConstant* c2 = HConstant::cast(const32_minus_sa);
10605     return c1->HasInteger32Value() && c2->HasInteger32Value() &&
10606         (c1->Integer32Value() + c2->Integer32Value() == 32);
10607   }
10608   if (!const32_minus_sa->IsSub()) return false;
10609   HSub* sub = HSub::cast(const32_minus_sa);
10610   return sub->left()->EqualsInteger32Constant(32) && sub->right() == sa;
10611 }
10612
10613
10614 // Checks if the left and the right are shift instructions with the oposite
10615 // directions that can be replaced by one rotate right instruction or not.
10616 // Returns the operand and the shift amount for the rotate instruction in the
10617 // former case.
10618 bool HGraphBuilder::MatchRotateRight(HValue* left,
10619                                      HValue* right,
10620                                      HValue** operand,
10621                                      HValue** shift_amount) {
10622   HShl* shl;
10623   HShr* shr;
10624   if (left->IsShl() && right->IsShr()) {
10625     shl = HShl::cast(left);
10626     shr = HShr::cast(right);
10627   } else if (left->IsShr() && right->IsShl()) {
10628     shl = HShl::cast(right);
10629     shr = HShr::cast(left);
10630   } else {
10631     return false;
10632   }
10633   if (shl->left() != shr->left()) return false;
10634
10635   if (!ShiftAmountsAllowReplaceByRotate(shl->right(), shr->right()) &&
10636       !ShiftAmountsAllowReplaceByRotate(shr->right(), shl->right())) {
10637     return false;
10638   }
10639   *operand = shr->left();
10640   *shift_amount = shr->right();
10641   return true;
10642 }
10643
10644
10645 bool CanBeZero(HValue* right) {
10646   if (right->IsConstant()) {
10647     HConstant* right_const = HConstant::cast(right);
10648     if (right_const->HasInteger32Value() &&
10649        (right_const->Integer32Value() & 0x1f) != 0) {
10650       return false;
10651     }
10652   }
10653   return true;
10654 }
10655
10656
10657 HValue* HGraphBuilder::EnforceNumberType(HValue* number,
10658                                          Type* expected) {
10659   if (expected->Is(Type::SignedSmall())) {
10660     return AddUncasted<HForceRepresentation>(number, Representation::Smi());
10661   }
10662   if (expected->Is(Type::Signed32())) {
10663     return AddUncasted<HForceRepresentation>(number,
10664                                              Representation::Integer32());
10665   }
10666   return number;
10667 }
10668
10669
10670 HValue* HGraphBuilder::TruncateToNumber(HValue* value, Type** expected) {
10671   if (value->IsConstant()) {
10672     HConstant* constant = HConstant::cast(value);
10673     Maybe<HConstant*> number =
10674         constant->CopyToTruncatedNumber(isolate(), zone());
10675     if (number.IsJust()) {
10676       *expected = Type::Number(zone());
10677       return AddInstruction(number.FromJust());
10678     }
10679   }
10680
10681   // We put temporary values on the stack, which don't correspond to anything
10682   // in baseline code. Since nothing is observable we avoid recording those
10683   // pushes with a NoObservableSideEffectsScope.
10684   NoObservableSideEffectsScope no_effects(this);
10685
10686   Type* expected_type = *expected;
10687
10688   // Separate the number type from the rest.
10689   Type* expected_obj =
10690       Type::Intersect(expected_type, Type::NonNumber(zone()), zone());
10691   Type* expected_number =
10692       Type::Intersect(expected_type, Type::Number(zone()), zone());
10693
10694   // We expect to get a number.
10695   // (We need to check first, since Type::None->Is(Type::Any()) == true.
10696   if (expected_obj->Is(Type::None())) {
10697     DCHECK(!expected_number->Is(Type::None(zone())));
10698     return value;
10699   }
10700
10701   if (expected_obj->Is(Type::Undefined(zone()))) {
10702     // This is already done by HChange.
10703     *expected = Type::Union(expected_number, Type::Number(zone()), zone());
10704     return value;
10705   }
10706
10707   return value;
10708 }
10709
10710
10711 HValue* HOptimizedGraphBuilder::BuildBinaryOperation(
10712     BinaryOperation* expr,
10713     HValue* left,
10714     HValue* right,
10715     PushBeforeSimulateBehavior push_sim_result) {
10716   Type* left_type = expr->left()->bounds().lower;
10717   Type* right_type = expr->right()->bounds().lower;
10718   Type* result_type = expr->bounds().lower;
10719   Maybe<int> fixed_right_arg = expr->fixed_right_arg();
10720   Handle<AllocationSite> allocation_site = expr->allocation_site();
10721
10722   HAllocationMode allocation_mode;
10723   if (FLAG_allocation_site_pretenuring && !allocation_site.is_null()) {
10724     allocation_mode = HAllocationMode(allocation_site);
10725   }
10726   HValue* result = HGraphBuilder::BuildBinaryOperation(
10727       expr->op(), left, right, left_type, right_type, result_type,
10728       fixed_right_arg, allocation_mode, strength(function_language_mode()),
10729       expr->id());
10730   // Add a simulate after instructions with observable side effects, and
10731   // after phis, which are the result of BuildBinaryOperation when we
10732   // inlined some complex subgraph.
10733   if (result->HasObservableSideEffects() || result->IsPhi()) {
10734     if (push_sim_result == PUSH_BEFORE_SIMULATE) {
10735       Push(result);
10736       Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
10737       Drop(1);
10738     } else {
10739       Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
10740     }
10741   }
10742   return result;
10743 }
10744
10745
10746 HValue* HGraphBuilder::BuildBinaryOperation(
10747     Token::Value op, HValue* left, HValue* right, Type* left_type,
10748     Type* right_type, Type* result_type, Maybe<int> fixed_right_arg,
10749     HAllocationMode allocation_mode, Strength strength, BailoutId opt_id) {
10750   bool maybe_string_add = false;
10751   if (op == Token::ADD) {
10752     // If we are adding constant string with something for which we don't have
10753     // a feedback yet, assume that it's also going to be a string and don't
10754     // generate deopt instructions.
10755     if (!left_type->IsInhabited() && right->IsConstant() &&
10756         HConstant::cast(right)->HasStringValue()) {
10757       left_type = Type::String();
10758     }
10759
10760     if (!right_type->IsInhabited() && left->IsConstant() &&
10761         HConstant::cast(left)->HasStringValue()) {
10762       right_type = Type::String();
10763     }
10764
10765     maybe_string_add = (left_type->Maybe(Type::String()) ||
10766                         left_type->Maybe(Type::Receiver()) ||
10767                         right_type->Maybe(Type::String()) ||
10768                         right_type->Maybe(Type::Receiver()));
10769   }
10770
10771   Representation left_rep = RepresentationFor(left_type);
10772   Representation right_rep = RepresentationFor(right_type);
10773
10774   if (!left_type->IsInhabited()) {
10775     Add<HDeoptimize>(
10776         Deoptimizer::kInsufficientTypeFeedbackForLHSOfBinaryOperation,
10777         Deoptimizer::SOFT);
10778     left_type = Type::Any(zone());
10779     left_rep = RepresentationFor(left_type);
10780     maybe_string_add = op == Token::ADD;
10781   }
10782
10783   if (!right_type->IsInhabited()) {
10784     Add<HDeoptimize>(
10785         Deoptimizer::kInsufficientTypeFeedbackForRHSOfBinaryOperation,
10786         Deoptimizer::SOFT);
10787     right_type = Type::Any(zone());
10788     right_rep = RepresentationFor(right_type);
10789     maybe_string_add = op == Token::ADD;
10790   }
10791
10792   if (!maybe_string_add && !is_strong(strength)) {
10793     left = TruncateToNumber(left, &left_type);
10794     right = TruncateToNumber(right, &right_type);
10795   }
10796
10797   // Special case for string addition here.
10798   if (op == Token::ADD &&
10799       (left_type->Is(Type::String()) || right_type->Is(Type::String()))) {
10800     // Validate type feedback for left argument.
10801     if (left_type->Is(Type::String())) {
10802       left = BuildCheckString(left);
10803     }
10804
10805     // Validate type feedback for right argument.
10806     if (right_type->Is(Type::String())) {
10807       right = BuildCheckString(right);
10808     }
10809
10810     // Convert left argument as necessary.
10811     if (left_type->Is(Type::Number()) && !is_strong(strength)) {
10812       DCHECK(right_type->Is(Type::String()));
10813       left = BuildNumberToString(left, left_type);
10814     } else if (!left_type->Is(Type::String())) {
10815       DCHECK(right_type->Is(Type::String()));
10816       HValue* function = AddLoadJSBuiltin(
10817           is_strong(strength) ? Builtins::STRING_ADD_RIGHT_STRONG
10818                               : Builtins::STRING_ADD_RIGHT);
10819       Add<HPushArguments>(left, right);
10820       return AddUncasted<HInvokeFunction>(function, 2);
10821     }
10822
10823     // Convert right argument as necessary.
10824     if (right_type->Is(Type::Number()) && !is_strong(strength)) {
10825       DCHECK(left_type->Is(Type::String()));
10826       right = BuildNumberToString(right, right_type);
10827     } else if (!right_type->Is(Type::String())) {
10828       DCHECK(left_type->Is(Type::String()));
10829       HValue* function = AddLoadJSBuiltin(is_strong(strength)
10830                                               ? Builtins::STRING_ADD_LEFT_STRONG
10831                                               : Builtins::STRING_ADD_LEFT);
10832       Add<HPushArguments>(left, right);
10833       return AddUncasted<HInvokeFunction>(function, 2);
10834     }
10835
10836     // Fast paths for empty constant strings.
10837     Handle<String> left_string =
10838         left->IsConstant() && HConstant::cast(left)->HasStringValue()
10839             ? HConstant::cast(left)->StringValue()
10840             : Handle<String>();
10841     Handle<String> right_string =
10842         right->IsConstant() && HConstant::cast(right)->HasStringValue()
10843             ? HConstant::cast(right)->StringValue()
10844             : Handle<String>();
10845     if (!left_string.is_null() && left_string->length() == 0) return right;
10846     if (!right_string.is_null() && right_string->length() == 0) return left;
10847     if (!left_string.is_null() && !right_string.is_null()) {
10848       return AddUncasted<HStringAdd>(
10849           left, right, strength, allocation_mode.GetPretenureMode(),
10850           STRING_ADD_CHECK_NONE, allocation_mode.feedback_site());
10851     }
10852
10853     // Register the dependent code with the allocation site.
10854     if (!allocation_mode.feedback_site().is_null()) {
10855       DCHECK(!graph()->info()->IsStub());
10856       Handle<AllocationSite> site(allocation_mode.feedback_site());
10857       top_info()->dependencies()->AssumeTenuringDecision(site);
10858     }
10859
10860     // Inline the string addition into the stub when creating allocation
10861     // mementos to gather allocation site feedback, or if we can statically
10862     // infer that we're going to create a cons string.
10863     if ((graph()->info()->IsStub() &&
10864          allocation_mode.CreateAllocationMementos()) ||
10865         (left->IsConstant() &&
10866          HConstant::cast(left)->HasStringValue() &&
10867          HConstant::cast(left)->StringValue()->length() + 1 >=
10868            ConsString::kMinLength) ||
10869         (right->IsConstant() &&
10870          HConstant::cast(right)->HasStringValue() &&
10871          HConstant::cast(right)->StringValue()->length() + 1 >=
10872            ConsString::kMinLength)) {
10873       return BuildStringAdd(left, right, allocation_mode);
10874     }
10875
10876     // Fallback to using the string add stub.
10877     return AddUncasted<HStringAdd>(
10878         left, right, strength, allocation_mode.GetPretenureMode(),
10879         STRING_ADD_CHECK_NONE, allocation_mode.feedback_site());
10880   }
10881
10882   if (graph()->info()->IsStub()) {
10883     left = EnforceNumberType(left, left_type);
10884     right = EnforceNumberType(right, right_type);
10885   }
10886
10887   Representation result_rep = RepresentationFor(result_type);
10888
10889   bool is_non_primitive = (left_rep.IsTagged() && !left_rep.IsSmi()) ||
10890                           (right_rep.IsTagged() && !right_rep.IsSmi());
10891
10892   HInstruction* instr = NULL;
10893   // Only the stub is allowed to call into the runtime, since otherwise we would
10894   // inline several instructions (including the two pushes) for every tagged
10895   // operation in optimized code, which is more expensive, than a stub call.
10896   if (graph()->info()->IsStub() && is_non_primitive) {
10897     HValue* function =
10898         AddLoadJSBuiltin(BinaryOpIC::TokenToJSBuiltin(op, strength));
10899     Add<HPushArguments>(left, right);
10900     instr = AddUncasted<HInvokeFunction>(function, 2);
10901   } else {
10902     if (is_strong(strength) && Token::IsBitOp(op)) {
10903       // TODO(conradw): This is not efficient, but is necessary to prevent
10904       // conversion of oddball values to numbers in strong mode. It would be
10905       // better to prevent the conversion rather than adding a runtime check.
10906       IfBuilder if_builder(this);
10907       if_builder.If<HHasInstanceTypeAndBranch>(left, ODDBALL_TYPE);
10908       if_builder.OrIf<HHasInstanceTypeAndBranch>(right, ODDBALL_TYPE);
10909       if_builder.Then();
10910       Add<HCallRuntime>(
10911           isolate()->factory()->empty_string(),
10912           Runtime::FunctionForId(Runtime::kThrowStrongModeImplicitConversion),
10913           0);
10914       if (!graph()->info()->IsStub()) {
10915         Add<HSimulate>(opt_id, REMOVABLE_SIMULATE);
10916       }
10917       if_builder.End();
10918     }
10919     switch (op) {
10920       case Token::ADD:
10921         instr = AddUncasted<HAdd>(left, right, strength);
10922         break;
10923       case Token::SUB:
10924         instr = AddUncasted<HSub>(left, right, strength);
10925         break;
10926       case Token::MUL:
10927         instr = AddUncasted<HMul>(left, right, strength);
10928         break;
10929       case Token::MOD: {
10930         if (fixed_right_arg.IsJust() &&
10931             !right->EqualsInteger32Constant(fixed_right_arg.FromJust())) {
10932           HConstant* fixed_right =
10933               Add<HConstant>(static_cast<int>(fixed_right_arg.FromJust()));
10934           IfBuilder if_same(this);
10935           if_same.If<HCompareNumericAndBranch>(right, fixed_right, Token::EQ);
10936           if_same.Then();
10937           if_same.ElseDeopt(Deoptimizer::kUnexpectedRHSOfBinaryOperation);
10938           right = fixed_right;
10939         }
10940         instr = AddUncasted<HMod>(left, right, strength);
10941         break;
10942       }
10943       case Token::DIV:
10944         instr = AddUncasted<HDiv>(left, right, strength);
10945         break;
10946       case Token::BIT_XOR:
10947       case Token::BIT_AND:
10948         instr = AddUncasted<HBitwise>(op, left, right, strength);
10949         break;
10950       case Token::BIT_OR: {
10951         HValue* operand, *shift_amount;
10952         if (left_type->Is(Type::Signed32()) &&
10953             right_type->Is(Type::Signed32()) &&
10954             MatchRotateRight(left, right, &operand, &shift_amount)) {
10955           instr = AddUncasted<HRor>(operand, shift_amount, strength);
10956         } else {
10957           instr = AddUncasted<HBitwise>(op, left, right, strength);
10958         }
10959         break;
10960       }
10961       case Token::SAR:
10962         instr = AddUncasted<HSar>(left, right, strength);
10963         break;
10964       case Token::SHR:
10965         instr = AddUncasted<HShr>(left, right, strength);
10966         if (instr->IsShr() && CanBeZero(right)) {
10967           graph()->RecordUint32Instruction(instr);
10968         }
10969         break;
10970       case Token::SHL:
10971         instr = AddUncasted<HShl>(left, right, strength);
10972         break;
10973       default:
10974         UNREACHABLE();
10975     }
10976   }
10977
10978   if (instr->IsBinaryOperation()) {
10979     HBinaryOperation* binop = HBinaryOperation::cast(instr);
10980     binop->set_observed_input_representation(1, left_rep);
10981     binop->set_observed_input_representation(2, right_rep);
10982     binop->initialize_output_representation(result_rep);
10983     if (graph()->info()->IsStub()) {
10984       // Stub should not call into stub.
10985       instr->SetFlag(HValue::kCannotBeTagged);
10986       // And should truncate on HForceRepresentation already.
10987       if (left->IsForceRepresentation()) {
10988         left->CopyFlag(HValue::kTruncatingToSmi, instr);
10989         left->CopyFlag(HValue::kTruncatingToInt32, instr);
10990       }
10991       if (right->IsForceRepresentation()) {
10992         right->CopyFlag(HValue::kTruncatingToSmi, instr);
10993         right->CopyFlag(HValue::kTruncatingToInt32, instr);
10994       }
10995     }
10996   }
10997   return instr;
10998 }
10999
11000
11001 // Check for the form (%_ClassOf(foo) === 'BarClass').
11002 static bool IsClassOfTest(CompareOperation* expr) {
11003   if (expr->op() != Token::EQ_STRICT) return false;
11004   CallRuntime* call = expr->left()->AsCallRuntime();
11005   if (call == NULL) return false;
11006   Literal* literal = expr->right()->AsLiteral();
11007   if (literal == NULL) return false;
11008   if (!literal->value()->IsString()) return false;
11009   if (!call->name()->IsOneByteEqualTo(STATIC_CHAR_VECTOR("_ClassOf"))) {
11010     return false;
11011   }
11012   DCHECK(call->arguments()->length() == 1);
11013   return true;
11014 }
11015
11016
11017 void HOptimizedGraphBuilder::VisitBinaryOperation(BinaryOperation* expr) {
11018   DCHECK(!HasStackOverflow());
11019   DCHECK(current_block() != NULL);
11020   DCHECK(current_block()->HasPredecessor());
11021   switch (expr->op()) {
11022     case Token::COMMA:
11023       return VisitComma(expr);
11024     case Token::OR:
11025     case Token::AND:
11026       return VisitLogicalExpression(expr);
11027     default:
11028       return VisitArithmeticExpression(expr);
11029   }
11030 }
11031
11032
11033 void HOptimizedGraphBuilder::VisitComma(BinaryOperation* expr) {
11034   CHECK_ALIVE(VisitForEffect(expr->left()));
11035   // Visit the right subexpression in the same AST context as the entire
11036   // expression.
11037   Visit(expr->right());
11038 }
11039
11040
11041 void HOptimizedGraphBuilder::VisitLogicalExpression(BinaryOperation* expr) {
11042   bool is_logical_and = expr->op() == Token::AND;
11043   if (ast_context()->IsTest()) {
11044     TestContext* context = TestContext::cast(ast_context());
11045     // Translate left subexpression.
11046     HBasicBlock* eval_right = graph()->CreateBasicBlock();
11047     if (is_logical_and) {
11048       CHECK_BAILOUT(VisitForControl(expr->left(),
11049                                     eval_right,
11050                                     context->if_false()));
11051     } else {
11052       CHECK_BAILOUT(VisitForControl(expr->left(),
11053                                     context->if_true(),
11054                                     eval_right));
11055     }
11056
11057     // Translate right subexpression by visiting it in the same AST
11058     // context as the entire expression.
11059     if (eval_right->HasPredecessor()) {
11060       eval_right->SetJoinId(expr->RightId());
11061       set_current_block(eval_right);
11062       Visit(expr->right());
11063     }
11064
11065   } else if (ast_context()->IsValue()) {
11066     CHECK_ALIVE(VisitForValue(expr->left()));
11067     DCHECK(current_block() != NULL);
11068     HValue* left_value = Top();
11069
11070     // Short-circuit left values that always evaluate to the same boolean value.
11071     if (expr->left()->ToBooleanIsTrue() || expr->left()->ToBooleanIsFalse()) {
11072       // l (evals true)  && r -> r
11073       // l (evals true)  || r -> l
11074       // l (evals false) && r -> l
11075       // l (evals false) || r -> r
11076       if (is_logical_and == expr->left()->ToBooleanIsTrue()) {
11077         Drop(1);
11078         CHECK_ALIVE(VisitForValue(expr->right()));
11079       }
11080       return ast_context()->ReturnValue(Pop());
11081     }
11082
11083     // We need an extra block to maintain edge-split form.
11084     HBasicBlock* empty_block = graph()->CreateBasicBlock();
11085     HBasicBlock* eval_right = graph()->CreateBasicBlock();
11086     ToBooleanStub::Types expected(expr->left()->to_boolean_types());
11087     HBranch* test = is_logical_and
11088         ? New<HBranch>(left_value, expected, eval_right, empty_block)
11089         : New<HBranch>(left_value, expected, empty_block, eval_right);
11090     FinishCurrentBlock(test);
11091
11092     set_current_block(eval_right);
11093     Drop(1);  // Value of the left subexpression.
11094     CHECK_BAILOUT(VisitForValue(expr->right()));
11095
11096     HBasicBlock* join_block =
11097       CreateJoin(empty_block, current_block(), expr->id());
11098     set_current_block(join_block);
11099     return ast_context()->ReturnValue(Pop());
11100
11101   } else {
11102     DCHECK(ast_context()->IsEffect());
11103     // In an effect context, we don't need the value of the left subexpression,
11104     // only its control flow and side effects.  We need an extra block to
11105     // maintain edge-split form.
11106     HBasicBlock* empty_block = graph()->CreateBasicBlock();
11107     HBasicBlock* right_block = graph()->CreateBasicBlock();
11108     if (is_logical_and) {
11109       CHECK_BAILOUT(VisitForControl(expr->left(), right_block, empty_block));
11110     } else {
11111       CHECK_BAILOUT(VisitForControl(expr->left(), empty_block, right_block));
11112     }
11113
11114     // TODO(kmillikin): Find a way to fix this.  It's ugly that there are
11115     // actually two empty blocks (one here and one inserted by
11116     // TestContext::BuildBranch, and that they both have an HSimulate though the
11117     // second one is not a merge node, and that we really have no good AST ID to
11118     // put on that first HSimulate.
11119
11120     if (empty_block->HasPredecessor()) {
11121       empty_block->SetJoinId(expr->id());
11122     } else {
11123       empty_block = NULL;
11124     }
11125
11126     if (right_block->HasPredecessor()) {
11127       right_block->SetJoinId(expr->RightId());
11128       set_current_block(right_block);
11129       CHECK_BAILOUT(VisitForEffect(expr->right()));
11130       right_block = current_block();
11131     } else {
11132       right_block = NULL;
11133     }
11134
11135     HBasicBlock* join_block =
11136       CreateJoin(empty_block, right_block, expr->id());
11137     set_current_block(join_block);
11138     // We did not materialize any value in the predecessor environments,
11139     // so there is no need to handle it here.
11140   }
11141 }
11142
11143
11144 void HOptimizedGraphBuilder::VisitArithmeticExpression(BinaryOperation* expr) {
11145   CHECK_ALIVE(VisitForValue(expr->left()));
11146   CHECK_ALIVE(VisitForValue(expr->right()));
11147   SetSourcePosition(expr->position());
11148   HValue* right = Pop();
11149   HValue* left = Pop();
11150   HValue* result =
11151       BuildBinaryOperation(expr, left, right,
11152           ast_context()->IsEffect() ? NO_PUSH_BEFORE_SIMULATE
11153                                     : PUSH_BEFORE_SIMULATE);
11154   if (top_info()->is_tracking_positions() && result->IsBinaryOperation()) {
11155     HBinaryOperation::cast(result)->SetOperandPositions(
11156         zone(),
11157         ScriptPositionToSourcePosition(expr->left()->position()),
11158         ScriptPositionToSourcePosition(expr->right()->position()));
11159   }
11160   return ast_context()->ReturnValue(result);
11161 }
11162
11163
11164 void HOptimizedGraphBuilder::HandleLiteralCompareTypeof(CompareOperation* expr,
11165                                                         Expression* sub_expr,
11166                                                         Handle<String> check) {
11167   CHECK_ALIVE(VisitForTypeOf(sub_expr));
11168   SetSourcePosition(expr->position());
11169   HValue* value = Pop();
11170   HTypeofIsAndBranch* instr = New<HTypeofIsAndBranch>(value, check);
11171   return ast_context()->ReturnControl(instr, expr->id());
11172 }
11173
11174
11175 static bool IsLiteralCompareBool(Isolate* isolate,
11176                                  HValue* left,
11177                                  Token::Value op,
11178                                  HValue* right) {
11179   return op == Token::EQ_STRICT &&
11180       ((left->IsConstant() &&
11181           HConstant::cast(left)->handle(isolate)->IsBoolean()) ||
11182        (right->IsConstant() &&
11183            HConstant::cast(right)->handle(isolate)->IsBoolean()));
11184 }
11185
11186
11187 void HOptimizedGraphBuilder::VisitCompareOperation(CompareOperation* expr) {
11188   DCHECK(!HasStackOverflow());
11189   DCHECK(current_block() != NULL);
11190   DCHECK(current_block()->HasPredecessor());
11191
11192   if (!top_info()->is_tracking_positions()) SetSourcePosition(expr->position());
11193
11194   // Check for a few fast cases. The AST visiting behavior must be in sync
11195   // with the full codegen: We don't push both left and right values onto
11196   // the expression stack when one side is a special-case literal.
11197   Expression* sub_expr = NULL;
11198   Handle<String> check;
11199   if (expr->IsLiteralCompareTypeof(&sub_expr, &check)) {
11200     return HandleLiteralCompareTypeof(expr, sub_expr, check);
11201   }
11202   if (expr->IsLiteralCompareUndefined(&sub_expr, isolate())) {
11203     return HandleLiteralCompareNil(expr, sub_expr, kUndefinedValue);
11204   }
11205   if (expr->IsLiteralCompareNull(&sub_expr)) {
11206     return HandleLiteralCompareNil(expr, sub_expr, kNullValue);
11207   }
11208
11209   if (IsClassOfTest(expr)) {
11210     CallRuntime* call = expr->left()->AsCallRuntime();
11211     DCHECK(call->arguments()->length() == 1);
11212     CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11213     HValue* value = Pop();
11214     Literal* literal = expr->right()->AsLiteral();
11215     Handle<String> rhs = Handle<String>::cast(literal->value());
11216     HClassOfTestAndBranch* instr = New<HClassOfTestAndBranch>(value, rhs);
11217     return ast_context()->ReturnControl(instr, expr->id());
11218   }
11219
11220   Type* left_type = expr->left()->bounds().lower;
11221   Type* right_type = expr->right()->bounds().lower;
11222   Type* combined_type = expr->combined_type();
11223
11224   CHECK_ALIVE(VisitForValue(expr->left()));
11225   CHECK_ALIVE(VisitForValue(expr->right()));
11226
11227   HValue* right = Pop();
11228   HValue* left = Pop();
11229   Token::Value op = expr->op();
11230
11231   if (IsLiteralCompareBool(isolate(), left, op, right)) {
11232     HCompareObjectEqAndBranch* result =
11233         New<HCompareObjectEqAndBranch>(left, right);
11234     return ast_context()->ReturnControl(result, expr->id());
11235   }
11236
11237   if (op == Token::INSTANCEOF) {
11238     // Check to see if the rhs of the instanceof is a known function.
11239     if (right->IsConstant() &&
11240         HConstant::cast(right)->handle(isolate())->IsJSFunction()) {
11241       Handle<Object> function = HConstant::cast(right)->handle(isolate());
11242       Handle<JSFunction> target = Handle<JSFunction>::cast(function);
11243       HInstanceOfKnownGlobal* result =
11244           New<HInstanceOfKnownGlobal>(left, target);
11245       return ast_context()->ReturnInstruction(result, expr->id());
11246     }
11247
11248     HInstanceOf* result = New<HInstanceOf>(left, right);
11249     return ast_context()->ReturnInstruction(result, expr->id());
11250
11251   } else if (op == Token::IN) {
11252     HValue* function = AddLoadJSBuiltin(Builtins::IN);
11253     Add<HPushArguments>(left, right);
11254     // TODO(olivf) InvokeFunction produces a check for the parameter count,
11255     // even though we are certain to pass the correct number of arguments here.
11256     HInstruction* result = New<HInvokeFunction>(function, 2);
11257     return ast_context()->ReturnInstruction(result, expr->id());
11258   }
11259
11260   PushBeforeSimulateBehavior push_behavior =
11261     ast_context()->IsEffect() ? NO_PUSH_BEFORE_SIMULATE
11262                               : PUSH_BEFORE_SIMULATE;
11263   HControlInstruction* compare = BuildCompareInstruction(
11264       op, left, right, left_type, right_type, combined_type,
11265       ScriptPositionToSourcePosition(expr->left()->position()),
11266       ScriptPositionToSourcePosition(expr->right()->position()),
11267       push_behavior, expr->id());
11268   if (compare == NULL) return;  // Bailed out.
11269   return ast_context()->ReturnControl(compare, expr->id());
11270 }
11271
11272
11273 HControlInstruction* HOptimizedGraphBuilder::BuildCompareInstruction(
11274     Token::Value op, HValue* left, HValue* right, Type* left_type,
11275     Type* right_type, Type* combined_type, SourcePosition left_position,
11276     SourcePosition right_position, PushBeforeSimulateBehavior push_sim_result,
11277     BailoutId bailout_id) {
11278   // Cases handled below depend on collected type feedback. They should
11279   // soft deoptimize when there is no type feedback.
11280   if (!combined_type->IsInhabited()) {
11281     Add<HDeoptimize>(
11282         Deoptimizer::kInsufficientTypeFeedbackForCombinedTypeOfBinaryOperation,
11283         Deoptimizer::SOFT);
11284     combined_type = left_type = right_type = Type::Any(zone());
11285   }
11286
11287   Representation left_rep = RepresentationFor(left_type);
11288   Representation right_rep = RepresentationFor(right_type);
11289   Representation combined_rep = RepresentationFor(combined_type);
11290
11291   if (combined_type->Is(Type::Receiver())) {
11292     if (Token::IsEqualityOp(op)) {
11293       // HCompareObjectEqAndBranch can only deal with object, so
11294       // exclude numbers.
11295       if ((left->IsConstant() &&
11296            HConstant::cast(left)->HasNumberValue()) ||
11297           (right->IsConstant() &&
11298            HConstant::cast(right)->HasNumberValue())) {
11299         Add<HDeoptimize>(Deoptimizer::kTypeMismatchBetweenFeedbackAndConstant,
11300                          Deoptimizer::SOFT);
11301         // The caller expects a branch instruction, so make it happy.
11302         return New<HBranch>(graph()->GetConstantTrue());
11303       }
11304       // Can we get away with map check and not instance type check?
11305       HValue* operand_to_check =
11306           left->block()->block_id() < right->block()->block_id() ? left : right;
11307       if (combined_type->IsClass()) {
11308         Handle<Map> map = combined_type->AsClass()->Map();
11309         AddCheckMap(operand_to_check, map);
11310         HCompareObjectEqAndBranch* result =
11311             New<HCompareObjectEqAndBranch>(left, right);
11312         if (top_info()->is_tracking_positions()) {
11313           result->set_operand_position(zone(), 0, left_position);
11314           result->set_operand_position(zone(), 1, right_position);
11315         }
11316         return result;
11317       } else {
11318         BuildCheckHeapObject(operand_to_check);
11319         Add<HCheckInstanceType>(operand_to_check,
11320                                 HCheckInstanceType::IS_SPEC_OBJECT);
11321         HCompareObjectEqAndBranch* result =
11322             New<HCompareObjectEqAndBranch>(left, right);
11323         return result;
11324       }
11325     } else {
11326       Bailout(kUnsupportedNonPrimitiveCompare);
11327       return NULL;
11328     }
11329   } else if (combined_type->Is(Type::InternalizedString()) &&
11330              Token::IsEqualityOp(op)) {
11331     // If we have a constant argument, it should be consistent with the type
11332     // feedback (otherwise we fail assertions in HCompareObjectEqAndBranch).
11333     if ((left->IsConstant() &&
11334          !HConstant::cast(left)->HasInternalizedStringValue()) ||
11335         (right->IsConstant() &&
11336          !HConstant::cast(right)->HasInternalizedStringValue())) {
11337       Add<HDeoptimize>(Deoptimizer::kTypeMismatchBetweenFeedbackAndConstant,
11338                        Deoptimizer::SOFT);
11339       // The caller expects a branch instruction, so make it happy.
11340       return New<HBranch>(graph()->GetConstantTrue());
11341     }
11342     BuildCheckHeapObject(left);
11343     Add<HCheckInstanceType>(left, HCheckInstanceType::IS_INTERNALIZED_STRING);
11344     BuildCheckHeapObject(right);
11345     Add<HCheckInstanceType>(right, HCheckInstanceType::IS_INTERNALIZED_STRING);
11346     HCompareObjectEqAndBranch* result =
11347         New<HCompareObjectEqAndBranch>(left, right);
11348     return result;
11349   } else if (combined_type->Is(Type::String())) {
11350     BuildCheckHeapObject(left);
11351     Add<HCheckInstanceType>(left, HCheckInstanceType::IS_STRING);
11352     BuildCheckHeapObject(right);
11353     Add<HCheckInstanceType>(right, HCheckInstanceType::IS_STRING);
11354     HStringCompareAndBranch* result =
11355         New<HStringCompareAndBranch>(left, right, op);
11356     return result;
11357   } else {
11358     if (combined_rep.IsTagged() || combined_rep.IsNone()) {
11359       HCompareGeneric* result = Add<HCompareGeneric>(
11360           left, right, op, strength(function_language_mode()));
11361       result->set_observed_input_representation(1, left_rep);
11362       result->set_observed_input_representation(2, right_rep);
11363       if (result->HasObservableSideEffects()) {
11364         if (push_sim_result == PUSH_BEFORE_SIMULATE) {
11365           Push(result);
11366           AddSimulate(bailout_id, REMOVABLE_SIMULATE);
11367           Drop(1);
11368         } else {
11369           AddSimulate(bailout_id, REMOVABLE_SIMULATE);
11370         }
11371       }
11372       // TODO(jkummerow): Can we make this more efficient?
11373       HBranch* branch = New<HBranch>(result);
11374       return branch;
11375     } else {
11376       HCompareNumericAndBranch* result = New<HCompareNumericAndBranch>(
11377           left, right, op, strength(function_language_mode()));
11378       result->set_observed_input_representation(left_rep, right_rep);
11379       if (top_info()->is_tracking_positions()) {
11380         result->SetOperandPositions(zone(), left_position, right_position);
11381       }
11382       return result;
11383     }
11384   }
11385 }
11386
11387
11388 void HOptimizedGraphBuilder::HandleLiteralCompareNil(CompareOperation* expr,
11389                                                      Expression* sub_expr,
11390                                                      NilValue nil) {
11391   DCHECK(!HasStackOverflow());
11392   DCHECK(current_block() != NULL);
11393   DCHECK(current_block()->HasPredecessor());
11394   DCHECK(expr->op() == Token::EQ || expr->op() == Token::EQ_STRICT);
11395   if (!top_info()->is_tracking_positions()) SetSourcePosition(expr->position());
11396   CHECK_ALIVE(VisitForValue(sub_expr));
11397   HValue* value = Pop();
11398   if (expr->op() == Token::EQ_STRICT) {
11399     HConstant* nil_constant = nil == kNullValue
11400         ? graph()->GetConstantNull()
11401         : graph()->GetConstantUndefined();
11402     HCompareObjectEqAndBranch* instr =
11403         New<HCompareObjectEqAndBranch>(value, nil_constant);
11404     return ast_context()->ReturnControl(instr, expr->id());
11405   } else {
11406     DCHECK_EQ(Token::EQ, expr->op());
11407     Type* type = expr->combined_type()->Is(Type::None())
11408         ? Type::Any(zone()) : expr->combined_type();
11409     HIfContinuation continuation;
11410     BuildCompareNil(value, type, &continuation);
11411     return ast_context()->ReturnContinuation(&continuation, expr->id());
11412   }
11413 }
11414
11415
11416 void HOptimizedGraphBuilder::VisitSpread(Spread* expr) { UNREACHABLE(); }
11417
11418
11419 HInstruction* HOptimizedGraphBuilder::BuildThisFunction() {
11420   // If we share optimized code between different closures, the
11421   // this-function is not a constant, except inside an inlined body.
11422   if (function_state()->outer() != NULL) {
11423       return New<HConstant>(
11424           function_state()->compilation_info()->closure());
11425   } else {
11426       return New<HThisFunction>();
11427   }
11428 }
11429
11430
11431 HInstruction* HOptimizedGraphBuilder::BuildFastLiteral(
11432     Handle<JSObject> boilerplate_object,
11433     AllocationSiteUsageContext* site_context) {
11434   NoObservableSideEffectsScope no_effects(this);
11435   Handle<Map> initial_map(boilerplate_object->map());
11436   InstanceType instance_type = initial_map->instance_type();
11437   DCHECK(instance_type == JS_ARRAY_TYPE || instance_type == JS_OBJECT_TYPE);
11438
11439   HType type = instance_type == JS_ARRAY_TYPE
11440       ? HType::JSArray() : HType::JSObject();
11441   HValue* object_size_constant = Add<HConstant>(initial_map->instance_size());
11442
11443   PretenureFlag pretenure_flag = NOT_TENURED;
11444   Handle<AllocationSite> current_site(*site_context->current(), isolate());
11445   if (FLAG_allocation_site_pretenuring) {
11446     pretenure_flag = current_site->GetPretenureMode();
11447     top_info()->dependencies()->AssumeTenuringDecision(current_site);
11448   }
11449
11450   top_info()->dependencies()->AssumeTransitionStable(current_site);
11451
11452   HInstruction* object = Add<HAllocate>(
11453       object_size_constant, type, pretenure_flag, instance_type, current_site);
11454
11455   // If allocation folding reaches Page::kMaxRegularHeapObjectSize the
11456   // elements array may not get folded into the object. Hence, we set the
11457   // elements pointer to empty fixed array and let store elimination remove
11458   // this store in the folding case.
11459   HConstant* empty_fixed_array = Add<HConstant>(
11460       isolate()->factory()->empty_fixed_array());
11461   Add<HStoreNamedField>(object, HObjectAccess::ForElementsPointer(),
11462       empty_fixed_array);
11463
11464   BuildEmitObjectHeader(boilerplate_object, object);
11465
11466   // Similarly to the elements pointer, there is no guarantee that all
11467   // property allocations can get folded, so pre-initialize all in-object
11468   // properties to a safe value.
11469   BuildInitializeInobjectProperties(object, initial_map);
11470
11471   Handle<FixedArrayBase> elements(boilerplate_object->elements());
11472   int elements_size = (elements->length() > 0 &&
11473       elements->map() != isolate()->heap()->fixed_cow_array_map()) ?
11474           elements->Size() : 0;
11475
11476   if (pretenure_flag == TENURED &&
11477       elements->map() == isolate()->heap()->fixed_cow_array_map() &&
11478       isolate()->heap()->InNewSpace(*elements)) {
11479     // If we would like to pretenure a fixed cow array, we must ensure that the
11480     // array is already in old space, otherwise we'll create too many old-to-
11481     // new-space pointers (overflowing the store buffer).
11482     elements = Handle<FixedArrayBase>(
11483         isolate()->factory()->CopyAndTenureFixedCOWArray(
11484             Handle<FixedArray>::cast(elements)));
11485     boilerplate_object->set_elements(*elements);
11486   }
11487
11488   HInstruction* object_elements = NULL;
11489   if (elements_size > 0) {
11490     HValue* object_elements_size = Add<HConstant>(elements_size);
11491     InstanceType instance_type = boilerplate_object->HasFastDoubleElements()
11492         ? FIXED_DOUBLE_ARRAY_TYPE : FIXED_ARRAY_TYPE;
11493     object_elements =
11494         Add<HAllocate>(object_elements_size, HType::HeapObject(),
11495                        pretenure_flag, instance_type, current_site);
11496     BuildEmitElements(boilerplate_object, elements, object_elements,
11497                       site_context);
11498     Add<HStoreNamedField>(object, HObjectAccess::ForElementsPointer(),
11499                           object_elements);
11500   } else {
11501     Handle<Object> elements_field =
11502         Handle<Object>(boilerplate_object->elements(), isolate());
11503     HInstruction* object_elements_cow = Add<HConstant>(elements_field);
11504     Add<HStoreNamedField>(object, HObjectAccess::ForElementsPointer(),
11505                           object_elements_cow);
11506   }
11507
11508   // Copy in-object properties.
11509   if (initial_map->NumberOfFields() != 0 ||
11510       initial_map->unused_property_fields() > 0) {
11511     BuildEmitInObjectProperties(boilerplate_object, object, site_context,
11512                                 pretenure_flag);
11513   }
11514   return object;
11515 }
11516
11517
11518 void HOptimizedGraphBuilder::BuildEmitObjectHeader(
11519     Handle<JSObject> boilerplate_object,
11520     HInstruction* object) {
11521   DCHECK(boilerplate_object->properties()->length() == 0);
11522
11523   Handle<Map> boilerplate_object_map(boilerplate_object->map());
11524   AddStoreMapConstant(object, boilerplate_object_map);
11525
11526   Handle<Object> properties_field =
11527       Handle<Object>(boilerplate_object->properties(), isolate());
11528   DCHECK(*properties_field == isolate()->heap()->empty_fixed_array());
11529   HInstruction* properties = Add<HConstant>(properties_field);
11530   HObjectAccess access = HObjectAccess::ForPropertiesPointer();
11531   Add<HStoreNamedField>(object, access, properties);
11532
11533   if (boilerplate_object->IsJSArray()) {
11534     Handle<JSArray> boilerplate_array =
11535         Handle<JSArray>::cast(boilerplate_object);
11536     Handle<Object> length_field =
11537         Handle<Object>(boilerplate_array->length(), isolate());
11538     HInstruction* length = Add<HConstant>(length_field);
11539
11540     DCHECK(boilerplate_array->length()->IsSmi());
11541     Add<HStoreNamedField>(object, HObjectAccess::ForArrayLength(
11542         boilerplate_array->GetElementsKind()), length);
11543   }
11544 }
11545
11546
11547 void HOptimizedGraphBuilder::BuildEmitInObjectProperties(
11548     Handle<JSObject> boilerplate_object,
11549     HInstruction* object,
11550     AllocationSiteUsageContext* site_context,
11551     PretenureFlag pretenure_flag) {
11552   Handle<Map> boilerplate_map(boilerplate_object->map());
11553   Handle<DescriptorArray> descriptors(boilerplate_map->instance_descriptors());
11554   int limit = boilerplate_map->NumberOfOwnDescriptors();
11555
11556   int copied_fields = 0;
11557   for (int i = 0; i < limit; i++) {
11558     PropertyDetails details = descriptors->GetDetails(i);
11559     if (details.type() != DATA) continue;
11560     copied_fields++;
11561     FieldIndex field_index = FieldIndex::ForDescriptor(*boilerplate_map, i);
11562
11563
11564     int property_offset = field_index.offset();
11565     Handle<Name> name(descriptors->GetKey(i));
11566
11567     // The access for the store depends on the type of the boilerplate.
11568     HObjectAccess access = boilerplate_object->IsJSArray() ?
11569         HObjectAccess::ForJSArrayOffset(property_offset) :
11570         HObjectAccess::ForMapAndOffset(boilerplate_map, property_offset);
11571
11572     if (boilerplate_object->IsUnboxedDoubleField(field_index)) {
11573       CHECK(!boilerplate_object->IsJSArray());
11574       double value = boilerplate_object->RawFastDoublePropertyAt(field_index);
11575       access = access.WithRepresentation(Representation::Double());
11576       Add<HStoreNamedField>(object, access, Add<HConstant>(value));
11577       continue;
11578     }
11579     Handle<Object> value(boilerplate_object->RawFastPropertyAt(field_index),
11580                          isolate());
11581
11582     if (value->IsJSObject()) {
11583       Handle<JSObject> value_object = Handle<JSObject>::cast(value);
11584       Handle<AllocationSite> current_site = site_context->EnterNewScope();
11585       HInstruction* result =
11586           BuildFastLiteral(value_object, site_context);
11587       site_context->ExitScope(current_site, value_object);
11588       Add<HStoreNamedField>(object, access, result);
11589     } else {
11590       Representation representation = details.representation();
11591       HInstruction* value_instruction;
11592
11593       if (representation.IsDouble()) {
11594         // Allocate a HeapNumber box and store the value into it.
11595         HValue* heap_number_constant = Add<HConstant>(HeapNumber::kSize);
11596         // This heap number alloc does not have a corresponding
11597         // AllocationSite. That is okay because
11598         // 1) it's a child object of another object with a valid allocation site
11599         // 2) we can just use the mode of the parent object for pretenuring
11600         HInstruction* double_box =
11601             Add<HAllocate>(heap_number_constant, HType::HeapObject(),
11602                 pretenure_flag, MUTABLE_HEAP_NUMBER_TYPE);
11603         AddStoreMapConstant(double_box,
11604             isolate()->factory()->mutable_heap_number_map());
11605         // Unwrap the mutable heap number from the boilerplate.
11606         HValue* double_value =
11607             Add<HConstant>(Handle<HeapNumber>::cast(value)->value());
11608         Add<HStoreNamedField>(
11609             double_box, HObjectAccess::ForHeapNumberValue(), double_value);
11610         value_instruction = double_box;
11611       } else if (representation.IsSmi()) {
11612         value_instruction = value->IsUninitialized()
11613             ? graph()->GetConstant0()
11614             : Add<HConstant>(value);
11615         // Ensure that value is stored as smi.
11616         access = access.WithRepresentation(representation);
11617       } else {
11618         value_instruction = Add<HConstant>(value);
11619       }
11620
11621       Add<HStoreNamedField>(object, access, value_instruction);
11622     }
11623   }
11624
11625   int inobject_properties = boilerplate_object->map()->inobject_properties();
11626   HInstruction* value_instruction =
11627       Add<HConstant>(isolate()->factory()->one_pointer_filler_map());
11628   for (int i = copied_fields; i < inobject_properties; i++) {
11629     DCHECK(boilerplate_object->IsJSObject());
11630     int property_offset = boilerplate_object->GetInObjectPropertyOffset(i);
11631     HObjectAccess access =
11632         HObjectAccess::ForMapAndOffset(boilerplate_map, property_offset);
11633     Add<HStoreNamedField>(object, access, value_instruction);
11634   }
11635 }
11636
11637
11638 void HOptimizedGraphBuilder::BuildEmitElements(
11639     Handle<JSObject> boilerplate_object,
11640     Handle<FixedArrayBase> elements,
11641     HValue* object_elements,
11642     AllocationSiteUsageContext* site_context) {
11643   ElementsKind kind = boilerplate_object->map()->elements_kind();
11644   int elements_length = elements->length();
11645   HValue* object_elements_length = Add<HConstant>(elements_length);
11646   BuildInitializeElementsHeader(object_elements, kind, object_elements_length);
11647
11648   // Copy elements backing store content.
11649   if (elements->IsFixedDoubleArray()) {
11650     BuildEmitFixedDoubleArray(elements, kind, object_elements);
11651   } else if (elements->IsFixedArray()) {
11652     BuildEmitFixedArray(elements, kind, object_elements,
11653                         site_context);
11654   } else {
11655     UNREACHABLE();
11656   }
11657 }
11658
11659
11660 void HOptimizedGraphBuilder::BuildEmitFixedDoubleArray(
11661     Handle<FixedArrayBase> elements,
11662     ElementsKind kind,
11663     HValue* object_elements) {
11664   HInstruction* boilerplate_elements = Add<HConstant>(elements);
11665   int elements_length = elements->length();
11666   for (int i = 0; i < elements_length; i++) {
11667     HValue* key_constant = Add<HConstant>(i);
11668     HInstruction* value_instruction = Add<HLoadKeyed>(
11669         boilerplate_elements, key_constant, nullptr, kind, ALLOW_RETURN_HOLE);
11670     HInstruction* store = Add<HStoreKeyed>(object_elements, key_constant,
11671                                            value_instruction, kind);
11672     store->SetFlag(HValue::kAllowUndefinedAsNaN);
11673   }
11674 }
11675
11676
11677 void HOptimizedGraphBuilder::BuildEmitFixedArray(
11678     Handle<FixedArrayBase> elements,
11679     ElementsKind kind,
11680     HValue* object_elements,
11681     AllocationSiteUsageContext* site_context) {
11682   HInstruction* boilerplate_elements = Add<HConstant>(elements);
11683   int elements_length = elements->length();
11684   Handle<FixedArray> fast_elements = Handle<FixedArray>::cast(elements);
11685   for (int i = 0; i < elements_length; i++) {
11686     Handle<Object> value(fast_elements->get(i), isolate());
11687     HValue* key_constant = Add<HConstant>(i);
11688     if (value->IsJSObject()) {
11689       Handle<JSObject> value_object = Handle<JSObject>::cast(value);
11690       Handle<AllocationSite> current_site = site_context->EnterNewScope();
11691       HInstruction* result =
11692           BuildFastLiteral(value_object, site_context);
11693       site_context->ExitScope(current_site, value_object);
11694       Add<HStoreKeyed>(object_elements, key_constant, result, kind);
11695     } else {
11696       ElementsKind copy_kind =
11697           kind == FAST_HOLEY_SMI_ELEMENTS ? FAST_HOLEY_ELEMENTS : kind;
11698       HInstruction* value_instruction =
11699           Add<HLoadKeyed>(boilerplate_elements, key_constant, nullptr,
11700                           copy_kind, ALLOW_RETURN_HOLE);
11701       Add<HStoreKeyed>(object_elements, key_constant, value_instruction,
11702                        copy_kind);
11703     }
11704   }
11705 }
11706
11707
11708 void HOptimizedGraphBuilder::VisitThisFunction(ThisFunction* expr) {
11709   DCHECK(!HasStackOverflow());
11710   DCHECK(current_block() != NULL);
11711   DCHECK(current_block()->HasPredecessor());
11712   HInstruction* instr = BuildThisFunction();
11713   return ast_context()->ReturnInstruction(instr, expr->id());
11714 }
11715
11716
11717 void HOptimizedGraphBuilder::VisitSuperPropertyReference(
11718     SuperPropertyReference* expr) {
11719   DCHECK(!HasStackOverflow());
11720   DCHECK(current_block() != NULL);
11721   DCHECK(current_block()->HasPredecessor());
11722   return Bailout(kSuperReference);
11723 }
11724
11725
11726 void HOptimizedGraphBuilder::VisitSuperCallReference(SuperCallReference* expr) {
11727   DCHECK(!HasStackOverflow());
11728   DCHECK(current_block() != NULL);
11729   DCHECK(current_block()->HasPredecessor());
11730   return Bailout(kSuperReference);
11731 }
11732
11733
11734 void HOptimizedGraphBuilder::VisitDeclarations(
11735     ZoneList<Declaration*>* declarations) {
11736   DCHECK(globals_.is_empty());
11737   AstVisitor::VisitDeclarations(declarations);
11738   if (!globals_.is_empty()) {
11739     Handle<FixedArray> array =
11740        isolate()->factory()->NewFixedArray(globals_.length(), TENURED);
11741     for (int i = 0; i < globals_.length(); ++i) array->set(i, *globals_.at(i));
11742     int flags =
11743         DeclareGlobalsEvalFlag::encode(current_info()->is_eval()) |
11744         DeclareGlobalsNativeFlag::encode(current_info()->is_native()) |
11745         DeclareGlobalsLanguageMode::encode(current_info()->language_mode());
11746     Add<HDeclareGlobals>(array, flags);
11747     globals_.Rewind(0);
11748   }
11749 }
11750
11751
11752 void HOptimizedGraphBuilder::VisitVariableDeclaration(
11753     VariableDeclaration* declaration) {
11754   VariableProxy* proxy = declaration->proxy();
11755   VariableMode mode = declaration->mode();
11756   Variable* variable = proxy->var();
11757   bool hole_init = mode == LET || mode == CONST || mode == CONST_LEGACY;
11758   switch (variable->location()) {
11759     case VariableLocation::GLOBAL:
11760     case VariableLocation::UNALLOCATED:
11761       globals_.Add(variable->name(), zone());
11762       globals_.Add(variable->binding_needs_init()
11763                        ? isolate()->factory()->the_hole_value()
11764                        : isolate()->factory()->undefined_value(), zone());
11765       return;
11766     case VariableLocation::PARAMETER:
11767     case VariableLocation::LOCAL:
11768       if (hole_init) {
11769         HValue* value = graph()->GetConstantHole();
11770         environment()->Bind(variable, value);
11771       }
11772       break;
11773     case VariableLocation::CONTEXT:
11774       if (hole_init) {
11775         HValue* value = graph()->GetConstantHole();
11776         HValue* context = environment()->context();
11777         HStoreContextSlot* store = Add<HStoreContextSlot>(
11778             context, variable->index(), HStoreContextSlot::kNoCheck, value);
11779         if (store->HasObservableSideEffects()) {
11780           Add<HSimulate>(proxy->id(), REMOVABLE_SIMULATE);
11781         }
11782       }
11783       break;
11784     case VariableLocation::LOOKUP:
11785       return Bailout(kUnsupportedLookupSlotInDeclaration);
11786   }
11787 }
11788
11789
11790 void HOptimizedGraphBuilder::VisitFunctionDeclaration(
11791     FunctionDeclaration* declaration) {
11792   VariableProxy* proxy = declaration->proxy();
11793   Variable* variable = proxy->var();
11794   switch (variable->location()) {
11795     case VariableLocation::GLOBAL:
11796     case VariableLocation::UNALLOCATED: {
11797       globals_.Add(variable->name(), zone());
11798       Handle<SharedFunctionInfo> function = Compiler::GetSharedFunctionInfo(
11799           declaration->fun(), current_info()->script(), top_info());
11800       // Check for stack-overflow exception.
11801       if (function.is_null()) return SetStackOverflow();
11802       globals_.Add(function, zone());
11803       return;
11804     }
11805     case VariableLocation::PARAMETER:
11806     case VariableLocation::LOCAL: {
11807       CHECK_ALIVE(VisitForValue(declaration->fun()));
11808       HValue* value = Pop();
11809       BindIfLive(variable, value);
11810       break;
11811     }
11812     case VariableLocation::CONTEXT: {
11813       CHECK_ALIVE(VisitForValue(declaration->fun()));
11814       HValue* value = Pop();
11815       HValue* context = environment()->context();
11816       HStoreContextSlot* store = Add<HStoreContextSlot>(
11817           context, variable->index(), HStoreContextSlot::kNoCheck, value);
11818       if (store->HasObservableSideEffects()) {
11819         Add<HSimulate>(proxy->id(), REMOVABLE_SIMULATE);
11820       }
11821       break;
11822     }
11823     case VariableLocation::LOOKUP:
11824       return Bailout(kUnsupportedLookupSlotInDeclaration);
11825   }
11826 }
11827
11828
11829 void HOptimizedGraphBuilder::VisitImportDeclaration(
11830     ImportDeclaration* declaration) {
11831   UNREACHABLE();
11832 }
11833
11834
11835 void HOptimizedGraphBuilder::VisitExportDeclaration(
11836     ExportDeclaration* declaration) {
11837   UNREACHABLE();
11838 }
11839
11840
11841 // Generators for inline runtime functions.
11842 // Support for types.
11843 void HOptimizedGraphBuilder::GenerateIsSmi(CallRuntime* call) {
11844   DCHECK(call->arguments()->length() == 1);
11845   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11846   HValue* value = Pop();
11847   HIsSmiAndBranch* result = New<HIsSmiAndBranch>(value);
11848   return ast_context()->ReturnControl(result, call->id());
11849 }
11850
11851
11852 void HOptimizedGraphBuilder::GenerateIsSpecObject(CallRuntime* call) {
11853   DCHECK(call->arguments()->length() == 1);
11854   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11855   HValue* value = Pop();
11856   HHasInstanceTypeAndBranch* result =
11857       New<HHasInstanceTypeAndBranch>(value,
11858                                      FIRST_SPEC_OBJECT_TYPE,
11859                                      LAST_SPEC_OBJECT_TYPE);
11860   return ast_context()->ReturnControl(result, call->id());
11861 }
11862
11863
11864 void HOptimizedGraphBuilder::GenerateIsFunction(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, JS_FUNCTION_TYPE);
11870   return ast_context()->ReturnControl(result, call->id());
11871 }
11872
11873
11874 void HOptimizedGraphBuilder::GenerateIsMinusZero(CallRuntime* call) {
11875   DCHECK(call->arguments()->length() == 1);
11876   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11877   HValue* value = Pop();
11878   HCompareMinusZeroAndBranch* result = New<HCompareMinusZeroAndBranch>(value);
11879   return ast_context()->ReturnControl(result, call->id());
11880 }
11881
11882
11883 void HOptimizedGraphBuilder::GenerateHasCachedArrayIndex(CallRuntime* call) {
11884   DCHECK(call->arguments()->length() == 1);
11885   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11886   HValue* value = Pop();
11887   HHasCachedArrayIndexAndBranch* result =
11888       New<HHasCachedArrayIndexAndBranch>(value);
11889   return ast_context()->ReturnControl(result, call->id());
11890 }
11891
11892
11893 void HOptimizedGraphBuilder::GenerateIsArray(CallRuntime* call) {
11894   DCHECK(call->arguments()->length() == 1);
11895   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11896   HValue* value = Pop();
11897   HHasInstanceTypeAndBranch* result =
11898       New<HHasInstanceTypeAndBranch>(value, JS_ARRAY_TYPE);
11899   return ast_context()->ReturnControl(result, call->id());
11900 }
11901
11902
11903 void HOptimizedGraphBuilder::GenerateIsTypedArray(CallRuntime* call) {
11904   DCHECK(call->arguments()->length() == 1);
11905   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11906   HValue* value = Pop();
11907   HHasInstanceTypeAndBranch* result =
11908       New<HHasInstanceTypeAndBranch>(value, JS_TYPED_ARRAY_TYPE);
11909   return ast_context()->ReturnControl(result, call->id());
11910 }
11911
11912
11913 void HOptimizedGraphBuilder::GenerateIsRegExp(CallRuntime* call) {
11914   DCHECK(call->arguments()->length() == 1);
11915   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11916   HValue* value = Pop();
11917   HHasInstanceTypeAndBranch* result =
11918       New<HHasInstanceTypeAndBranch>(value, JS_REGEXP_TYPE);
11919   return ast_context()->ReturnControl(result, call->id());
11920 }
11921
11922
11923 void HOptimizedGraphBuilder::GenerateIsObject(CallRuntime* call) {
11924   DCHECK(call->arguments()->length() == 1);
11925   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11926   HValue* value = Pop();
11927   HIsObjectAndBranch* result = New<HIsObjectAndBranch>(value);
11928   return ast_context()->ReturnControl(result, call->id());
11929 }
11930
11931
11932 void HOptimizedGraphBuilder::GenerateIsJSProxy(CallRuntime* call) {
11933   DCHECK(call->arguments()->length() == 1);
11934   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11935   HValue* value = Pop();
11936   HIfContinuation continuation;
11937   IfBuilder if_proxy(this);
11938
11939   HValue* smicheck = if_proxy.IfNot<HIsSmiAndBranch>(value);
11940   if_proxy.And();
11941   HValue* map = Add<HLoadNamedField>(value, smicheck, HObjectAccess::ForMap());
11942   HValue* instance_type =
11943       Add<HLoadNamedField>(map, nullptr, HObjectAccess::ForMapInstanceType());
11944   if_proxy.If<HCompareNumericAndBranch>(
11945       instance_type, Add<HConstant>(FIRST_JS_PROXY_TYPE), Token::GTE);
11946   if_proxy.And();
11947   if_proxy.If<HCompareNumericAndBranch>(
11948       instance_type, Add<HConstant>(LAST_JS_PROXY_TYPE), Token::LTE);
11949
11950   if_proxy.CaptureContinuation(&continuation);
11951   return ast_context()->ReturnContinuation(&continuation, call->id());
11952 }
11953
11954
11955 void HOptimizedGraphBuilder::GenerateHasFastPackedElements(CallRuntime* call) {
11956   DCHECK(call->arguments()->length() == 1);
11957   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11958   HValue* object = Pop();
11959   HIfContinuation continuation(graph()->CreateBasicBlock(),
11960                                graph()->CreateBasicBlock());
11961   IfBuilder if_not_smi(this);
11962   if_not_smi.IfNot<HIsSmiAndBranch>(object);
11963   if_not_smi.Then();
11964   {
11965     NoObservableSideEffectsScope no_effects(this);
11966
11967     IfBuilder if_fast_packed(this);
11968     HValue* elements_kind = BuildGetElementsKind(object);
11969     if_fast_packed.If<HCompareNumericAndBranch>(
11970         elements_kind, Add<HConstant>(FAST_SMI_ELEMENTS), Token::EQ);
11971     if_fast_packed.Or();
11972     if_fast_packed.If<HCompareNumericAndBranch>(
11973         elements_kind, Add<HConstant>(FAST_ELEMENTS), Token::EQ);
11974     if_fast_packed.Or();
11975     if_fast_packed.If<HCompareNumericAndBranch>(
11976         elements_kind, Add<HConstant>(FAST_DOUBLE_ELEMENTS), Token::EQ);
11977     if_fast_packed.JoinContinuation(&continuation);
11978   }
11979   if_not_smi.JoinContinuation(&continuation);
11980   return ast_context()->ReturnContinuation(&continuation, call->id());
11981 }
11982
11983
11984 void HOptimizedGraphBuilder::GenerateIsUndetectableObject(CallRuntime* call) {
11985   DCHECK(call->arguments()->length() == 1);
11986   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11987   HValue* value = Pop();
11988   HIsUndetectableAndBranch* result = New<HIsUndetectableAndBranch>(value);
11989   return ast_context()->ReturnControl(result, call->id());
11990 }
11991
11992
11993 // Support for construct call checks.
11994 void HOptimizedGraphBuilder::GenerateIsConstructCall(CallRuntime* call) {
11995   DCHECK(call->arguments()->length() == 0);
11996   if (function_state()->outer() != NULL) {
11997     // We are generating graph for inlined function.
11998     HValue* value = function_state()->inlining_kind() == CONSTRUCT_CALL_RETURN
11999         ? graph()->GetConstantTrue()
12000         : graph()->GetConstantFalse();
12001     return ast_context()->ReturnValue(value);
12002   } else {
12003     return ast_context()->ReturnControl(New<HIsConstructCallAndBranch>(),
12004                                         call->id());
12005   }
12006 }
12007
12008
12009 // Support for arguments.length and arguments[?].
12010 void HOptimizedGraphBuilder::GenerateArgumentsLength(CallRuntime* call) {
12011   DCHECK(call->arguments()->length() == 0);
12012   HInstruction* result = NULL;
12013   if (function_state()->outer() == NULL) {
12014     HInstruction* elements = Add<HArgumentsElements>(false);
12015     result = New<HArgumentsLength>(elements);
12016   } else {
12017     // Number of arguments without receiver.
12018     int argument_count = environment()->
12019         arguments_environment()->parameter_count() - 1;
12020     result = New<HConstant>(argument_count);
12021   }
12022   return ast_context()->ReturnInstruction(result, call->id());
12023 }
12024
12025
12026 void HOptimizedGraphBuilder::GenerateArguments(CallRuntime* call) {
12027   DCHECK(call->arguments()->length() == 1);
12028   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12029   HValue* index = Pop();
12030   HInstruction* result = NULL;
12031   if (function_state()->outer() == NULL) {
12032     HInstruction* elements = Add<HArgumentsElements>(false);
12033     HInstruction* length = Add<HArgumentsLength>(elements);
12034     HInstruction* checked_index = Add<HBoundsCheck>(index, length);
12035     result = New<HAccessArgumentsAt>(elements, length, checked_index);
12036   } else {
12037     EnsureArgumentsArePushedForAccess();
12038
12039     // Number of arguments without receiver.
12040     HInstruction* elements = function_state()->arguments_elements();
12041     int argument_count = environment()->
12042         arguments_environment()->parameter_count() - 1;
12043     HInstruction* length = Add<HConstant>(argument_count);
12044     HInstruction* checked_key = Add<HBoundsCheck>(index, length);
12045     result = New<HAccessArgumentsAt>(elements, length, checked_key);
12046   }
12047   return ast_context()->ReturnInstruction(result, call->id());
12048 }
12049
12050
12051 void HOptimizedGraphBuilder::GenerateValueOf(CallRuntime* call) {
12052   DCHECK(call->arguments()->length() == 1);
12053   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12054   HValue* object = Pop();
12055
12056   IfBuilder if_objectisvalue(this);
12057   HValue* objectisvalue = if_objectisvalue.If<HHasInstanceTypeAndBranch>(
12058       object, JS_VALUE_TYPE);
12059   if_objectisvalue.Then();
12060   {
12061     // Return the actual value.
12062     Push(Add<HLoadNamedField>(
12063             object, objectisvalue,
12064             HObjectAccess::ForObservableJSObjectOffset(
12065                 JSValue::kValueOffset)));
12066     Add<HSimulate>(call->id(), FIXED_SIMULATE);
12067   }
12068   if_objectisvalue.Else();
12069   {
12070     // If the object is not a value return the object.
12071     Push(object);
12072     Add<HSimulate>(call->id(), FIXED_SIMULATE);
12073   }
12074   if_objectisvalue.End();
12075   return ast_context()->ReturnValue(Pop());
12076 }
12077
12078
12079 void HOptimizedGraphBuilder::GenerateJSValueGetValue(CallRuntime* call) {
12080   DCHECK(call->arguments()->length() == 1);
12081   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12082   HValue* value = Pop();
12083   HInstruction* result = Add<HLoadNamedField>(
12084       value, nullptr,
12085       HObjectAccess::ForObservableJSObjectOffset(JSValue::kValueOffset));
12086   return ast_context()->ReturnInstruction(result, call->id());
12087 }
12088
12089
12090 void HOptimizedGraphBuilder::GenerateIsDate(CallRuntime* call) {
12091   DCHECK_EQ(1, call->arguments()->length());
12092   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12093   HValue* value = Pop();
12094   HHasInstanceTypeAndBranch* result =
12095       New<HHasInstanceTypeAndBranch>(value, JS_DATE_TYPE);
12096   return ast_context()->ReturnControl(result, call->id());
12097 }
12098
12099
12100 void HOptimizedGraphBuilder::GenerateThrowNotDateError(CallRuntime* call) {
12101   DCHECK_EQ(0, call->arguments()->length());
12102   Add<HDeoptimize>(Deoptimizer::kNotADateObject, Deoptimizer::EAGER);
12103   Add<HSimulate>(call->id(), FIXED_SIMULATE);
12104   return ast_context()->ReturnValue(graph()->GetConstantUndefined());
12105 }
12106
12107
12108 void HOptimizedGraphBuilder::GenerateDateField(CallRuntime* call) {
12109   DCHECK(call->arguments()->length() == 2);
12110   DCHECK_NOT_NULL(call->arguments()->at(1)->AsLiteral());
12111   Smi* index = Smi::cast(*(call->arguments()->at(1)->AsLiteral()->value()));
12112   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12113   HValue* date = Pop();
12114   HDateField* result = New<HDateField>(date, index);
12115   return ast_context()->ReturnInstruction(result, call->id());
12116 }
12117
12118
12119 void HOptimizedGraphBuilder::GenerateOneByteSeqStringSetChar(
12120     CallRuntime* call) {
12121   DCHECK(call->arguments()->length() == 3);
12122   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12123   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12124   CHECK_ALIVE(VisitForValue(call->arguments()->at(2)));
12125   HValue* string = Pop();
12126   HValue* value = Pop();
12127   HValue* index = Pop();
12128   Add<HSeqStringSetChar>(String::ONE_BYTE_ENCODING, string,
12129                          index, value);
12130   Add<HSimulate>(call->id(), FIXED_SIMULATE);
12131   return ast_context()->ReturnValue(graph()->GetConstantUndefined());
12132 }
12133
12134
12135 void HOptimizedGraphBuilder::GenerateTwoByteSeqStringSetChar(
12136     CallRuntime* call) {
12137   DCHECK(call->arguments()->length() == 3);
12138   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12139   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12140   CHECK_ALIVE(VisitForValue(call->arguments()->at(2)));
12141   HValue* string = Pop();
12142   HValue* value = Pop();
12143   HValue* index = Pop();
12144   Add<HSeqStringSetChar>(String::TWO_BYTE_ENCODING, string,
12145                          index, value);
12146   Add<HSimulate>(call->id(), FIXED_SIMULATE);
12147   return ast_context()->ReturnValue(graph()->GetConstantUndefined());
12148 }
12149
12150
12151 void HOptimizedGraphBuilder::GenerateSetValueOf(CallRuntime* call) {
12152   DCHECK(call->arguments()->length() == 2);
12153   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12154   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12155   HValue* value = Pop();
12156   HValue* object = Pop();
12157
12158   // Check if object is a JSValue.
12159   IfBuilder if_objectisvalue(this);
12160   if_objectisvalue.If<HHasInstanceTypeAndBranch>(object, JS_VALUE_TYPE);
12161   if_objectisvalue.Then();
12162   {
12163     // Create in-object property store to kValueOffset.
12164     Add<HStoreNamedField>(object,
12165         HObjectAccess::ForObservableJSObjectOffset(JSValue::kValueOffset),
12166         value);
12167     if (!ast_context()->IsEffect()) {
12168       Push(value);
12169     }
12170     Add<HSimulate>(call->id(), FIXED_SIMULATE);
12171   }
12172   if_objectisvalue.Else();
12173   {
12174     // Nothing to do in this case.
12175     if (!ast_context()->IsEffect()) {
12176       Push(value);
12177     }
12178     Add<HSimulate>(call->id(), FIXED_SIMULATE);
12179   }
12180   if_objectisvalue.End();
12181   if (!ast_context()->IsEffect()) {
12182     Drop(1);
12183   }
12184   return ast_context()->ReturnValue(value);
12185 }
12186
12187
12188 // Fast support for charCodeAt(n).
12189 void HOptimizedGraphBuilder::GenerateStringCharCodeAt(CallRuntime* call) {
12190   DCHECK(call->arguments()->length() == 2);
12191   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12192   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12193   HValue* index = Pop();
12194   HValue* string = Pop();
12195   HInstruction* result = BuildStringCharCodeAt(string, index);
12196   return ast_context()->ReturnInstruction(result, call->id());
12197 }
12198
12199
12200 // Fast support for string.charAt(n) and string[n].
12201 void HOptimizedGraphBuilder::GenerateStringCharFromCode(CallRuntime* call) {
12202   DCHECK(call->arguments()->length() == 1);
12203   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12204   HValue* char_code = Pop();
12205   HInstruction* result = NewUncasted<HStringCharFromCode>(char_code);
12206   return ast_context()->ReturnInstruction(result, call->id());
12207 }
12208
12209
12210 // Fast support for string.charAt(n) and string[n].
12211 void HOptimizedGraphBuilder::GenerateStringCharAt(CallRuntime* call) {
12212   DCHECK(call->arguments()->length() == 2);
12213   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12214   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12215   HValue* index = Pop();
12216   HValue* string = Pop();
12217   HInstruction* char_code = BuildStringCharCodeAt(string, index);
12218   AddInstruction(char_code);
12219   HInstruction* result = NewUncasted<HStringCharFromCode>(char_code);
12220   return ast_context()->ReturnInstruction(result, call->id());
12221 }
12222
12223
12224 // Fast support for object equality testing.
12225 void HOptimizedGraphBuilder::GenerateObjectEquals(CallRuntime* call) {
12226   DCHECK(call->arguments()->length() == 2);
12227   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12228   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12229   HValue* right = Pop();
12230   HValue* left = Pop();
12231   HCompareObjectEqAndBranch* result =
12232       New<HCompareObjectEqAndBranch>(left, right);
12233   return ast_context()->ReturnControl(result, call->id());
12234 }
12235
12236
12237 // Fast support for StringAdd.
12238 void HOptimizedGraphBuilder::GenerateStringAdd(CallRuntime* call) {
12239   DCHECK_EQ(2, call->arguments()->length());
12240   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12241   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12242   HValue* right = Pop();
12243   HValue* left = Pop();
12244   HInstruction* result =
12245       NewUncasted<HStringAdd>(left, right, strength(function_language_mode()));
12246   return ast_context()->ReturnInstruction(result, call->id());
12247 }
12248
12249
12250 // Fast support for SubString.
12251 void HOptimizedGraphBuilder::GenerateSubString(CallRuntime* call) {
12252   DCHECK_EQ(3, call->arguments()->length());
12253   CHECK_ALIVE(VisitExpressions(call->arguments()));
12254   PushArgumentsFromEnvironment(call->arguments()->length());
12255   HCallStub* result = New<HCallStub>(CodeStub::SubString, 3);
12256   return ast_context()->ReturnInstruction(result, call->id());
12257 }
12258
12259
12260 // Fast support for StringCompare.
12261 void HOptimizedGraphBuilder::GenerateStringCompare(CallRuntime* call) {
12262   DCHECK_EQ(2, call->arguments()->length());
12263   CHECK_ALIVE(VisitExpressions(call->arguments()));
12264   PushArgumentsFromEnvironment(call->arguments()->length());
12265   HCallStub* result = New<HCallStub>(CodeStub::StringCompare, 2);
12266   return ast_context()->ReturnInstruction(result, call->id());
12267 }
12268
12269
12270 void HOptimizedGraphBuilder::GenerateStringGetLength(CallRuntime* call) {
12271   DCHECK(call->arguments()->length() == 1);
12272   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12273   HValue* string = Pop();
12274   HInstruction* result = BuildLoadStringLength(string);
12275   return ast_context()->ReturnInstruction(result, call->id());
12276 }
12277
12278
12279 // Support for direct calls from JavaScript to native RegExp code.
12280 void HOptimizedGraphBuilder::GenerateRegExpExec(CallRuntime* call) {
12281   DCHECK_EQ(4, call->arguments()->length());
12282   CHECK_ALIVE(VisitExpressions(call->arguments()));
12283   PushArgumentsFromEnvironment(call->arguments()->length());
12284   HCallStub* result = New<HCallStub>(CodeStub::RegExpExec, 4);
12285   return ast_context()->ReturnInstruction(result, call->id());
12286 }
12287
12288
12289 void HOptimizedGraphBuilder::GenerateDoubleLo(CallRuntime* call) {
12290   DCHECK_EQ(1, call->arguments()->length());
12291   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12292   HValue* value = Pop();
12293   HInstruction* result = NewUncasted<HDoubleBits>(value, HDoubleBits::LOW);
12294   return ast_context()->ReturnInstruction(result, call->id());
12295 }
12296
12297
12298 void HOptimizedGraphBuilder::GenerateDoubleHi(CallRuntime* call) {
12299   DCHECK_EQ(1, call->arguments()->length());
12300   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12301   HValue* value = Pop();
12302   HInstruction* result = NewUncasted<HDoubleBits>(value, HDoubleBits::HIGH);
12303   return ast_context()->ReturnInstruction(result, call->id());
12304 }
12305
12306
12307 void HOptimizedGraphBuilder::GenerateConstructDouble(CallRuntime* call) {
12308   DCHECK_EQ(2, call->arguments()->length());
12309   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12310   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12311   HValue* lo = Pop();
12312   HValue* hi = Pop();
12313   HInstruction* result = NewUncasted<HConstructDouble>(hi, lo);
12314   return ast_context()->ReturnInstruction(result, call->id());
12315 }
12316
12317
12318 // Construct a RegExp exec result with two in-object properties.
12319 void HOptimizedGraphBuilder::GenerateRegExpConstructResult(CallRuntime* call) {
12320   DCHECK_EQ(3, call->arguments()->length());
12321   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12322   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12323   CHECK_ALIVE(VisitForValue(call->arguments()->at(2)));
12324   HValue* input = Pop();
12325   HValue* index = Pop();
12326   HValue* length = Pop();
12327   HValue* result = BuildRegExpConstructResult(length, index, input);
12328   return ast_context()->ReturnValue(result);
12329 }
12330
12331
12332 // Support for fast native caches.
12333 void HOptimizedGraphBuilder::GenerateGetFromCache(CallRuntime* call) {
12334   return Bailout(kInlinedRuntimeFunctionGetFromCache);
12335 }
12336
12337
12338 // Fast support for number to string.
12339 void HOptimizedGraphBuilder::GenerateNumberToString(CallRuntime* call) {
12340   DCHECK_EQ(1, call->arguments()->length());
12341   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12342   HValue* number = Pop();
12343   HValue* result = BuildNumberToString(number, Type::Any(zone()));
12344   return ast_context()->ReturnValue(result);
12345 }
12346
12347
12348 // Fast call for custom callbacks.
12349 void HOptimizedGraphBuilder::GenerateCallFunction(CallRuntime* call) {
12350   // 1 ~ The function to call is not itself an argument to the call.
12351   int arg_count = call->arguments()->length() - 1;
12352   DCHECK(arg_count >= 1);  // There's always at least a receiver.
12353
12354   CHECK_ALIVE(VisitExpressions(call->arguments()));
12355   // The function is the last argument
12356   HValue* function = Pop();
12357   // Push the arguments to the stack
12358   PushArgumentsFromEnvironment(arg_count);
12359
12360   IfBuilder if_is_jsfunction(this);
12361   if_is_jsfunction.If<HHasInstanceTypeAndBranch>(function, JS_FUNCTION_TYPE);
12362
12363   if_is_jsfunction.Then();
12364   {
12365     HInstruction* invoke_result =
12366         Add<HInvokeFunction>(function, arg_count);
12367     if (!ast_context()->IsEffect()) {
12368       Push(invoke_result);
12369     }
12370     Add<HSimulate>(call->id(), FIXED_SIMULATE);
12371   }
12372
12373   if_is_jsfunction.Else();
12374   {
12375     HInstruction* call_result =
12376         Add<HCallFunction>(function, arg_count);
12377     if (!ast_context()->IsEffect()) {
12378       Push(call_result);
12379     }
12380     Add<HSimulate>(call->id(), FIXED_SIMULATE);
12381   }
12382   if_is_jsfunction.End();
12383
12384   if (ast_context()->IsEffect()) {
12385     // EffectContext::ReturnValue ignores the value, so we can just pass
12386     // 'undefined' (as we do not have the call result anymore).
12387     return ast_context()->ReturnValue(graph()->GetConstantUndefined());
12388   } else {
12389     return ast_context()->ReturnValue(Pop());
12390   }
12391 }
12392
12393
12394 // Fast call to math functions.
12395 void HOptimizedGraphBuilder::GenerateMathPow(CallRuntime* call) {
12396   DCHECK_EQ(2, call->arguments()->length());
12397   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12398   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12399   HValue* right = Pop();
12400   HValue* left = Pop();
12401   HInstruction* result = NewUncasted<HPower>(left, right);
12402   return ast_context()->ReturnInstruction(result, call->id());
12403 }
12404
12405
12406 void HOptimizedGraphBuilder::GenerateMathClz32(CallRuntime* call) {
12407   DCHECK(call->arguments()->length() == 1);
12408   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12409   HValue* value = Pop();
12410   HInstruction* result = NewUncasted<HUnaryMathOperation>(value, kMathClz32);
12411   return ast_context()->ReturnInstruction(result, call->id());
12412 }
12413
12414
12415 void HOptimizedGraphBuilder::GenerateMathFloor(CallRuntime* call) {
12416   DCHECK(call->arguments()->length() == 1);
12417   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12418   HValue* value = Pop();
12419   HInstruction* result = NewUncasted<HUnaryMathOperation>(value, kMathFloor);
12420   return ast_context()->ReturnInstruction(result, call->id());
12421 }
12422
12423
12424 void HOptimizedGraphBuilder::GenerateMathLogRT(CallRuntime* call) {
12425   DCHECK(call->arguments()->length() == 1);
12426   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12427   HValue* value = Pop();
12428   HInstruction* result = NewUncasted<HUnaryMathOperation>(value, kMathLog);
12429   return ast_context()->ReturnInstruction(result, call->id());
12430 }
12431
12432
12433 void HOptimizedGraphBuilder::GenerateMathSqrt(CallRuntime* call) {
12434   DCHECK(call->arguments()->length() == 1);
12435   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12436   HValue* value = Pop();
12437   HInstruction* result = NewUncasted<HUnaryMathOperation>(value, kMathSqrt);
12438   return ast_context()->ReturnInstruction(result, call->id());
12439 }
12440
12441
12442 void HOptimizedGraphBuilder::GenerateLikely(CallRuntime* call) {
12443   DCHECK(call->arguments()->length() == 1);
12444   Visit(call->arguments()->at(0));
12445 }
12446
12447
12448 void HOptimizedGraphBuilder::GenerateUnlikely(CallRuntime* call) {
12449   return GenerateLikely(call);
12450 }
12451
12452
12453 void HOptimizedGraphBuilder::GenerateFixedArrayGet(CallRuntime* call) {
12454   DCHECK(call->arguments()->length() == 2);
12455   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12456   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12457   HValue* index = Pop();
12458   HValue* object = Pop();
12459   HInstruction* result = New<HLoadKeyed>(
12460       object, index, nullptr, FAST_HOLEY_ELEMENTS, ALLOW_RETURN_HOLE);
12461   return ast_context()->ReturnInstruction(result, call->id());
12462 }
12463
12464
12465 void HOptimizedGraphBuilder::GenerateFixedArraySet(CallRuntime* call) {
12466   DCHECK(call->arguments()->length() == 3);
12467   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12468   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12469   CHECK_ALIVE(VisitForValue(call->arguments()->at(2)));
12470   HValue* value = Pop();
12471   HValue* index = Pop();
12472   HValue* object = Pop();
12473   NoObservableSideEffectsScope no_effects(this);
12474   Add<HStoreKeyed>(object, index, value, FAST_HOLEY_ELEMENTS);
12475   return ast_context()->ReturnValue(graph()->GetConstantUndefined());
12476 }
12477
12478
12479 void HOptimizedGraphBuilder::GenerateTheHole(CallRuntime* call) {
12480   DCHECK(call->arguments()->length() == 0);
12481   return ast_context()->ReturnValue(graph()->GetConstantHole());
12482 }
12483
12484
12485 void HOptimizedGraphBuilder::GenerateJSCollectionGetTable(CallRuntime* call) {
12486   DCHECK(call->arguments()->length() == 1);
12487   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12488   HValue* receiver = Pop();
12489   HInstruction* result = New<HLoadNamedField>(
12490       receiver, nullptr, HObjectAccess::ForJSCollectionTable());
12491   return ast_context()->ReturnInstruction(result, call->id());
12492 }
12493
12494
12495 void HOptimizedGraphBuilder::GenerateStringGetRawHashField(CallRuntime* call) {
12496   DCHECK(call->arguments()->length() == 1);
12497   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12498   HValue* object = Pop();
12499   HInstruction* result = New<HLoadNamedField>(
12500       object, nullptr, HObjectAccess::ForStringHashField());
12501   return ast_context()->ReturnInstruction(result, call->id());
12502 }
12503
12504
12505 template <typename CollectionType>
12506 HValue* HOptimizedGraphBuilder::BuildAllocateOrderedHashTable() {
12507   static const int kCapacity = CollectionType::kMinCapacity;
12508   static const int kBucketCount = kCapacity / CollectionType::kLoadFactor;
12509   static const int kFixedArrayLength = CollectionType::kHashTableStartIndex +
12510                                        kBucketCount +
12511                                        (kCapacity * CollectionType::kEntrySize);
12512   static const int kSizeInBytes =
12513       FixedArray::kHeaderSize + (kFixedArrayLength * kPointerSize);
12514
12515   // Allocate the table and add the proper map.
12516   HValue* table =
12517       Add<HAllocate>(Add<HConstant>(kSizeInBytes), HType::HeapObject(),
12518                      NOT_TENURED, FIXED_ARRAY_TYPE);
12519   AddStoreMapConstant(table, isolate()->factory()->ordered_hash_table_map());
12520
12521   // Initialize the FixedArray...
12522   HValue* length = Add<HConstant>(kFixedArrayLength);
12523   Add<HStoreNamedField>(table, HObjectAccess::ForFixedArrayLength(), length);
12524
12525   // ...and the OrderedHashTable fields.
12526   Add<HStoreNamedField>(
12527       table,
12528       HObjectAccess::ForOrderedHashTableNumberOfBuckets<CollectionType>(),
12529       Add<HConstant>(kBucketCount));
12530   Add<HStoreNamedField>(
12531       table,
12532       HObjectAccess::ForOrderedHashTableNumberOfElements<CollectionType>(),
12533       graph()->GetConstant0());
12534   Add<HStoreNamedField>(
12535       table, HObjectAccess::ForOrderedHashTableNumberOfDeletedElements<
12536                  CollectionType>(),
12537       graph()->GetConstant0());
12538
12539   // Fill the buckets with kNotFound.
12540   HValue* not_found = Add<HConstant>(CollectionType::kNotFound);
12541   for (int i = 0; i < kBucketCount; ++i) {
12542     Add<HStoreNamedField>(
12543         table, HObjectAccess::ForOrderedHashTableBucket<CollectionType>(i),
12544         not_found);
12545   }
12546
12547   // Fill the data table with undefined.
12548   HValue* undefined = graph()->GetConstantUndefined();
12549   for (int i = 0; i < (kCapacity * CollectionType::kEntrySize); ++i) {
12550     Add<HStoreNamedField>(table,
12551                           HObjectAccess::ForOrderedHashTableDataTableIndex<
12552                               CollectionType, kBucketCount>(i),
12553                           undefined);
12554   }
12555
12556   return table;
12557 }
12558
12559
12560 void HOptimizedGraphBuilder::GenerateSetInitialize(CallRuntime* call) {
12561   DCHECK(call->arguments()->length() == 1);
12562   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12563   HValue* receiver = Pop();
12564
12565   NoObservableSideEffectsScope no_effects(this);
12566   HValue* table = BuildAllocateOrderedHashTable<OrderedHashSet>();
12567   Add<HStoreNamedField>(receiver, HObjectAccess::ForJSCollectionTable(), table);
12568   return ast_context()->ReturnValue(receiver);
12569 }
12570
12571
12572 void HOptimizedGraphBuilder::GenerateMapInitialize(CallRuntime* call) {
12573   DCHECK(call->arguments()->length() == 1);
12574   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12575   HValue* receiver = Pop();
12576
12577   NoObservableSideEffectsScope no_effects(this);
12578   HValue* table = BuildAllocateOrderedHashTable<OrderedHashMap>();
12579   Add<HStoreNamedField>(receiver, HObjectAccess::ForJSCollectionTable(), table);
12580   return ast_context()->ReturnValue(receiver);
12581 }
12582
12583
12584 template <typename CollectionType>
12585 void HOptimizedGraphBuilder::BuildOrderedHashTableClear(HValue* receiver) {
12586   HValue* old_table = Add<HLoadNamedField>(
12587       receiver, nullptr, HObjectAccess::ForJSCollectionTable());
12588   HValue* new_table = BuildAllocateOrderedHashTable<CollectionType>();
12589   Add<HStoreNamedField>(
12590       old_table, HObjectAccess::ForOrderedHashTableNextTable<CollectionType>(),
12591       new_table);
12592   Add<HStoreNamedField>(
12593       old_table, HObjectAccess::ForOrderedHashTableNumberOfDeletedElements<
12594                      CollectionType>(),
12595       Add<HConstant>(CollectionType::kClearedTableSentinel));
12596   Add<HStoreNamedField>(receiver, HObjectAccess::ForJSCollectionTable(),
12597                         new_table);
12598 }
12599
12600
12601 void HOptimizedGraphBuilder::GenerateSetClear(CallRuntime* call) {
12602   DCHECK(call->arguments()->length() == 1);
12603   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12604   HValue* receiver = Pop();
12605
12606   NoObservableSideEffectsScope no_effects(this);
12607   BuildOrderedHashTableClear<OrderedHashSet>(receiver);
12608   return ast_context()->ReturnValue(graph()->GetConstantUndefined());
12609 }
12610
12611
12612 void HOptimizedGraphBuilder::GenerateMapClear(CallRuntime* call) {
12613   DCHECK(call->arguments()->length() == 1);
12614   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12615   HValue* receiver = Pop();
12616
12617   NoObservableSideEffectsScope no_effects(this);
12618   BuildOrderedHashTableClear<OrderedHashMap>(receiver);
12619   return ast_context()->ReturnValue(graph()->GetConstantUndefined());
12620 }
12621
12622
12623 void HOptimizedGraphBuilder::GenerateGetCachedArrayIndex(CallRuntime* call) {
12624   DCHECK(call->arguments()->length() == 1);
12625   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12626   HValue* value = Pop();
12627   HGetCachedArrayIndex* result = New<HGetCachedArrayIndex>(value);
12628   return ast_context()->ReturnInstruction(result, call->id());
12629 }
12630
12631
12632 void HOptimizedGraphBuilder::GenerateFastOneByteArrayJoin(CallRuntime* call) {
12633   // Simply returning undefined here would be semantically correct and even
12634   // avoid the bailout. Nevertheless, some ancient benchmarks like SunSpider's
12635   // string-fasta would tank, because fullcode contains an optimized version.
12636   // Obviously the fullcode => Crankshaft => bailout => fullcode dance is
12637   // faster... *sigh*
12638   return Bailout(kInlinedRuntimeFunctionFastOneByteArrayJoin);
12639 }
12640
12641
12642 void HOptimizedGraphBuilder::GenerateDebugBreakInOptimizedCode(
12643     CallRuntime* call) {
12644   Add<HDebugBreak>();
12645   return ast_context()->ReturnValue(graph()->GetConstant0());
12646 }
12647
12648
12649 void HOptimizedGraphBuilder::GenerateDebugIsActive(CallRuntime* call) {
12650   DCHECK(call->arguments()->length() == 0);
12651   HValue* ref =
12652       Add<HConstant>(ExternalReference::debug_is_active_address(isolate()));
12653   HValue* value =
12654       Add<HLoadNamedField>(ref, nullptr, HObjectAccess::ForExternalUInteger8());
12655   return ast_context()->ReturnValue(value);
12656 }
12657
12658
12659 void HOptimizedGraphBuilder::GenerateGetPrototype(CallRuntime* call) {
12660   DCHECK(call->arguments()->length() == 1);
12661   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12662   HValue* object = Pop();
12663
12664   NoObservableSideEffectsScope no_effects(this);
12665
12666   HValue* map = Add<HLoadNamedField>(object, nullptr, HObjectAccess::ForMap());
12667   HValue* bit_field =
12668       Add<HLoadNamedField>(map, nullptr, HObjectAccess::ForMapBitField());
12669   HValue* is_access_check_needed_mask =
12670       Add<HConstant>(1 << Map::kIsAccessCheckNeeded);
12671   HValue* is_access_check_needed_test = AddUncasted<HBitwise>(
12672       Token::BIT_AND, bit_field, is_access_check_needed_mask);
12673
12674   HValue* proto =
12675       Add<HLoadNamedField>(map, nullptr, HObjectAccess::ForPrototype());
12676   HValue* proto_map =
12677       Add<HLoadNamedField>(proto, nullptr, HObjectAccess::ForMap());
12678   HValue* proto_bit_field =
12679       Add<HLoadNamedField>(proto_map, nullptr, HObjectAccess::ForMapBitField());
12680   HValue* is_hidden_prototype_mask =
12681       Add<HConstant>(1 << Map::kIsHiddenPrototype);
12682   HValue* is_hidden_prototype_test = AddUncasted<HBitwise>(
12683       Token::BIT_AND, proto_bit_field, is_hidden_prototype_mask);
12684
12685   {
12686     IfBuilder needs_runtime(this);
12687     needs_runtime.If<HCompareNumericAndBranch>(
12688         is_access_check_needed_test, graph()->GetConstant0(), Token::NE);
12689     needs_runtime.OrIf<HCompareNumericAndBranch>(
12690         is_hidden_prototype_test, graph()->GetConstant0(), Token::NE);
12691
12692     needs_runtime.Then();
12693     {
12694       Add<HPushArguments>(object);
12695       Push(Add<HCallRuntime>(
12696           call->name(), Runtime::FunctionForId(Runtime::kGetPrototype), 1));
12697     }
12698
12699     needs_runtime.Else();
12700     Push(proto);
12701   }
12702   return ast_context()->ReturnValue(Pop());
12703 }
12704
12705
12706 #undef CHECK_BAILOUT
12707 #undef CHECK_ALIVE
12708
12709
12710 HEnvironment::HEnvironment(HEnvironment* outer,
12711                            Scope* scope,
12712                            Handle<JSFunction> closure,
12713                            Zone* zone)
12714     : closure_(closure),
12715       values_(0, zone),
12716       frame_type_(JS_FUNCTION),
12717       parameter_count_(0),
12718       specials_count_(1),
12719       local_count_(0),
12720       outer_(outer),
12721       entry_(NULL),
12722       pop_count_(0),
12723       push_count_(0),
12724       ast_id_(BailoutId::None()),
12725       zone_(zone) {
12726   Scope* declaration_scope = scope->DeclarationScope();
12727   Initialize(declaration_scope->num_parameters() + 1,
12728              declaration_scope->num_stack_slots(), 0);
12729 }
12730
12731
12732 HEnvironment::HEnvironment(Zone* zone, int parameter_count)
12733     : values_(0, zone),
12734       frame_type_(STUB),
12735       parameter_count_(parameter_count),
12736       specials_count_(1),
12737       local_count_(0),
12738       outer_(NULL),
12739       entry_(NULL),
12740       pop_count_(0),
12741       push_count_(0),
12742       ast_id_(BailoutId::None()),
12743       zone_(zone) {
12744   Initialize(parameter_count, 0, 0);
12745 }
12746
12747
12748 HEnvironment::HEnvironment(const HEnvironment* other, Zone* zone)
12749     : values_(0, zone),
12750       frame_type_(JS_FUNCTION),
12751       parameter_count_(0),
12752       specials_count_(0),
12753       local_count_(0),
12754       outer_(NULL),
12755       entry_(NULL),
12756       pop_count_(0),
12757       push_count_(0),
12758       ast_id_(other->ast_id()),
12759       zone_(zone) {
12760   Initialize(other);
12761 }
12762
12763
12764 HEnvironment::HEnvironment(HEnvironment* outer,
12765                            Handle<JSFunction> closure,
12766                            FrameType frame_type,
12767                            int arguments,
12768                            Zone* zone)
12769     : closure_(closure),
12770       values_(arguments, zone),
12771       frame_type_(frame_type),
12772       parameter_count_(arguments),
12773       specials_count_(0),
12774       local_count_(0),
12775       outer_(outer),
12776       entry_(NULL),
12777       pop_count_(0),
12778       push_count_(0),
12779       ast_id_(BailoutId::None()),
12780       zone_(zone) {
12781 }
12782
12783
12784 void HEnvironment::Initialize(int parameter_count,
12785                               int local_count,
12786                               int stack_height) {
12787   parameter_count_ = parameter_count;
12788   local_count_ = local_count;
12789
12790   // Avoid reallocating the temporaries' backing store on the first Push.
12791   int total = parameter_count + specials_count_ + local_count + stack_height;
12792   values_.Initialize(total + 4, zone());
12793   for (int i = 0; i < total; ++i) values_.Add(NULL, zone());
12794 }
12795
12796
12797 void HEnvironment::Initialize(const HEnvironment* other) {
12798   closure_ = other->closure();
12799   values_.AddAll(other->values_, zone());
12800   assigned_variables_.Union(other->assigned_variables_, zone());
12801   frame_type_ = other->frame_type_;
12802   parameter_count_ = other->parameter_count_;
12803   local_count_ = other->local_count_;
12804   if (other->outer_ != NULL) outer_ = other->outer_->Copy();  // Deep copy.
12805   entry_ = other->entry_;
12806   pop_count_ = other->pop_count_;
12807   push_count_ = other->push_count_;
12808   specials_count_ = other->specials_count_;
12809   ast_id_ = other->ast_id_;
12810 }
12811
12812
12813 void HEnvironment::AddIncomingEdge(HBasicBlock* block, HEnvironment* other) {
12814   DCHECK(!block->IsLoopHeader());
12815   DCHECK(values_.length() == other->values_.length());
12816
12817   int length = values_.length();
12818   for (int i = 0; i < length; ++i) {
12819     HValue* value = values_[i];
12820     if (value != NULL && value->IsPhi() && value->block() == block) {
12821       // There is already a phi for the i'th value.
12822       HPhi* phi = HPhi::cast(value);
12823       // Assert index is correct and that we haven't missed an incoming edge.
12824       DCHECK(phi->merged_index() == i || !phi->HasMergedIndex());
12825       DCHECK(phi->OperandCount() == block->predecessors()->length());
12826       phi->AddInput(other->values_[i]);
12827     } else if (values_[i] != other->values_[i]) {
12828       // There is a fresh value on the incoming edge, a phi is needed.
12829       DCHECK(values_[i] != NULL && other->values_[i] != NULL);
12830       HPhi* phi = block->AddNewPhi(i);
12831       HValue* old_value = values_[i];
12832       for (int j = 0; j < block->predecessors()->length(); j++) {
12833         phi->AddInput(old_value);
12834       }
12835       phi->AddInput(other->values_[i]);
12836       this->values_[i] = phi;
12837     }
12838   }
12839 }
12840
12841
12842 void HEnvironment::Bind(int index, HValue* value) {
12843   DCHECK(value != NULL);
12844   assigned_variables_.Add(index, zone());
12845   values_[index] = value;
12846 }
12847
12848
12849 bool HEnvironment::HasExpressionAt(int index) const {
12850   return index >= parameter_count_ + specials_count_ + local_count_;
12851 }
12852
12853
12854 bool HEnvironment::ExpressionStackIsEmpty() const {
12855   DCHECK(length() >= first_expression_index());
12856   return length() == first_expression_index();
12857 }
12858
12859
12860 void HEnvironment::SetExpressionStackAt(int index_from_top, HValue* value) {
12861   int count = index_from_top + 1;
12862   int index = values_.length() - count;
12863   DCHECK(HasExpressionAt(index));
12864   // The push count must include at least the element in question or else
12865   // the new value will not be included in this environment's history.
12866   if (push_count_ < count) {
12867     // This is the same effect as popping then re-pushing 'count' elements.
12868     pop_count_ += (count - push_count_);
12869     push_count_ = count;
12870   }
12871   values_[index] = value;
12872 }
12873
12874
12875 HValue* HEnvironment::RemoveExpressionStackAt(int index_from_top) {
12876   int count = index_from_top + 1;
12877   int index = values_.length() - count;
12878   DCHECK(HasExpressionAt(index));
12879   // Simulate popping 'count' elements and then
12880   // pushing 'count - 1' elements back.
12881   pop_count_ += Max(count - push_count_, 0);
12882   push_count_ = Max(push_count_ - count, 0) + (count - 1);
12883   return values_.Remove(index);
12884 }
12885
12886
12887 void HEnvironment::Drop(int count) {
12888   for (int i = 0; i < count; ++i) {
12889     Pop();
12890   }
12891 }
12892
12893
12894 HEnvironment* HEnvironment::Copy() const {
12895   return new(zone()) HEnvironment(this, zone());
12896 }
12897
12898
12899 HEnvironment* HEnvironment::CopyWithoutHistory() const {
12900   HEnvironment* result = Copy();
12901   result->ClearHistory();
12902   return result;
12903 }
12904
12905
12906 HEnvironment* HEnvironment::CopyAsLoopHeader(HBasicBlock* loop_header) const {
12907   HEnvironment* new_env = Copy();
12908   for (int i = 0; i < values_.length(); ++i) {
12909     HPhi* phi = loop_header->AddNewPhi(i);
12910     phi->AddInput(values_[i]);
12911     new_env->values_[i] = phi;
12912   }
12913   new_env->ClearHistory();
12914   return new_env;
12915 }
12916
12917
12918 HEnvironment* HEnvironment::CreateStubEnvironment(HEnvironment* outer,
12919                                                   Handle<JSFunction> target,
12920                                                   FrameType frame_type,
12921                                                   int arguments) const {
12922   HEnvironment* new_env =
12923       new(zone()) HEnvironment(outer, target, frame_type,
12924                                arguments + 1, zone());
12925   for (int i = 0; i <= arguments; ++i) {  // Include receiver.
12926     new_env->Push(ExpressionStackAt(arguments - i));
12927   }
12928   new_env->ClearHistory();
12929   return new_env;
12930 }
12931
12932
12933 HEnvironment* HEnvironment::CopyForInlining(
12934     Handle<JSFunction> target,
12935     int arguments,
12936     FunctionLiteral* function,
12937     HConstant* undefined,
12938     InliningKind inlining_kind) const {
12939   DCHECK(frame_type() == JS_FUNCTION);
12940
12941   // Outer environment is a copy of this one without the arguments.
12942   int arity = function->scope()->num_parameters();
12943
12944   HEnvironment* outer = Copy();
12945   outer->Drop(arguments + 1);  // Including receiver.
12946   outer->ClearHistory();
12947
12948   if (inlining_kind == CONSTRUCT_CALL_RETURN) {
12949     // Create artificial constructor stub environment.  The receiver should
12950     // actually be the constructor function, but we pass the newly allocated
12951     // object instead, DoComputeConstructStubFrame() relies on that.
12952     outer = CreateStubEnvironment(outer, target, JS_CONSTRUCT, arguments);
12953   } else if (inlining_kind == GETTER_CALL_RETURN) {
12954     // We need an additional StackFrame::INTERNAL frame for restoring the
12955     // correct context.
12956     outer = CreateStubEnvironment(outer, target, JS_GETTER, arguments);
12957   } else if (inlining_kind == SETTER_CALL_RETURN) {
12958     // We need an additional StackFrame::INTERNAL frame for temporarily saving
12959     // the argument of the setter, see StoreStubCompiler::CompileStoreViaSetter.
12960     outer = CreateStubEnvironment(outer, target, JS_SETTER, arguments);
12961   }
12962
12963   if (arity != arguments) {
12964     // Create artificial arguments adaptation environment.
12965     outer = CreateStubEnvironment(outer, target, ARGUMENTS_ADAPTOR, arguments);
12966   }
12967
12968   HEnvironment* inner =
12969       new(zone()) HEnvironment(outer, function->scope(), target, zone());
12970   // Get the argument values from the original environment.
12971   for (int i = 0; i <= arity; ++i) {  // Include receiver.
12972     HValue* push = (i <= arguments) ?
12973         ExpressionStackAt(arguments - i) : undefined;
12974     inner->SetValueAt(i, push);
12975   }
12976   inner->SetValueAt(arity + 1, context());
12977   for (int i = arity + 2; i < inner->length(); ++i) {
12978     inner->SetValueAt(i, undefined);
12979   }
12980
12981   inner->set_ast_id(BailoutId::FunctionEntry());
12982   return inner;
12983 }
12984
12985
12986 std::ostream& operator<<(std::ostream& os, const HEnvironment& env) {
12987   for (int i = 0; i < env.length(); i++) {
12988     if (i == 0) os << "parameters\n";
12989     if (i == env.parameter_count()) os << "specials\n";
12990     if (i == env.parameter_count() + env.specials_count()) os << "locals\n";
12991     if (i == env.parameter_count() + env.specials_count() + env.local_count()) {
12992       os << "expressions\n";
12993     }
12994     HValue* val = env.values()->at(i);
12995     os << i << ": ";
12996     if (val != NULL) {
12997       os << val;
12998     } else {
12999       os << "NULL";
13000     }
13001     os << "\n";
13002   }
13003   return os << "\n";
13004 }
13005
13006
13007 void HTracer::TraceCompilation(CompilationInfo* info) {
13008   Tag tag(this, "compilation");
13009   if (info->IsOptimizing()) {
13010     Handle<String> name = info->function()->debug_name();
13011     PrintStringProperty("name", name->ToCString().get());
13012     PrintIndent();
13013     trace_.Add("method \"%s:%d\"\n",
13014                name->ToCString().get(),
13015                info->optimization_id());
13016   } else {
13017     CodeStub::Major major_key = info->code_stub()->MajorKey();
13018     PrintStringProperty("name", CodeStub::MajorName(major_key, false));
13019     PrintStringProperty("method", "stub");
13020   }
13021   PrintLongProperty("date",
13022                     static_cast<int64_t>(base::OS::TimeCurrentMillis()));
13023 }
13024
13025
13026 void HTracer::TraceLithium(const char* name, LChunk* chunk) {
13027   DCHECK(!chunk->isolate()->concurrent_recompilation_enabled());
13028   AllowHandleDereference allow_deref;
13029   AllowDeferredHandleDereference allow_deferred_deref;
13030   Trace(name, chunk->graph(), chunk);
13031 }
13032
13033
13034 void HTracer::TraceHydrogen(const char* name, HGraph* graph) {
13035   DCHECK(!graph->isolate()->concurrent_recompilation_enabled());
13036   AllowHandleDereference allow_deref;
13037   AllowDeferredHandleDereference allow_deferred_deref;
13038   Trace(name, graph, NULL);
13039 }
13040
13041
13042 void HTracer::Trace(const char* name, HGraph* graph, LChunk* chunk) {
13043   Tag tag(this, "cfg");
13044   PrintStringProperty("name", name);
13045   const ZoneList<HBasicBlock*>* blocks = graph->blocks();
13046   for (int i = 0; i < blocks->length(); i++) {
13047     HBasicBlock* current = blocks->at(i);
13048     Tag block_tag(this, "block");
13049     PrintBlockProperty("name", current->block_id());
13050     PrintIntProperty("from_bci", -1);
13051     PrintIntProperty("to_bci", -1);
13052
13053     if (!current->predecessors()->is_empty()) {
13054       PrintIndent();
13055       trace_.Add("predecessors");
13056       for (int j = 0; j < current->predecessors()->length(); ++j) {
13057         trace_.Add(" \"B%d\"", current->predecessors()->at(j)->block_id());
13058       }
13059       trace_.Add("\n");
13060     } else {
13061       PrintEmptyProperty("predecessors");
13062     }
13063
13064     if (current->end()->SuccessorCount() == 0) {
13065       PrintEmptyProperty("successors");
13066     } else  {
13067       PrintIndent();
13068       trace_.Add("successors");
13069       for (HSuccessorIterator it(current->end()); !it.Done(); it.Advance()) {
13070         trace_.Add(" \"B%d\"", it.Current()->block_id());
13071       }
13072       trace_.Add("\n");
13073     }
13074
13075     PrintEmptyProperty("xhandlers");
13076
13077     {
13078       PrintIndent();
13079       trace_.Add("flags");
13080       if (current->IsLoopSuccessorDominator()) {
13081         trace_.Add(" \"dom-loop-succ\"");
13082       }
13083       if (current->IsUnreachable()) {
13084         trace_.Add(" \"dead\"");
13085       }
13086       if (current->is_osr_entry()) {
13087         trace_.Add(" \"osr\"");
13088       }
13089       trace_.Add("\n");
13090     }
13091
13092     if (current->dominator() != NULL) {
13093       PrintBlockProperty("dominator", current->dominator()->block_id());
13094     }
13095
13096     PrintIntProperty("loop_depth", current->LoopNestingDepth());
13097
13098     if (chunk != NULL) {
13099       int first_index = current->first_instruction_index();
13100       int last_index = current->last_instruction_index();
13101       PrintIntProperty(
13102           "first_lir_id",
13103           LifetimePosition::FromInstructionIndex(first_index).Value());
13104       PrintIntProperty(
13105           "last_lir_id",
13106           LifetimePosition::FromInstructionIndex(last_index).Value());
13107     }
13108
13109     {
13110       Tag states_tag(this, "states");
13111       Tag locals_tag(this, "locals");
13112       int total = current->phis()->length();
13113       PrintIntProperty("size", current->phis()->length());
13114       PrintStringProperty("method", "None");
13115       for (int j = 0; j < total; ++j) {
13116         HPhi* phi = current->phis()->at(j);
13117         PrintIndent();
13118         std::ostringstream os;
13119         os << phi->merged_index() << " " << NameOf(phi) << " " << *phi << "\n";
13120         trace_.Add(os.str().c_str());
13121       }
13122     }
13123
13124     {
13125       Tag HIR_tag(this, "HIR");
13126       for (HInstructionIterator it(current); !it.Done(); it.Advance()) {
13127         HInstruction* instruction = it.Current();
13128         int uses = instruction->UseCount();
13129         PrintIndent();
13130         std::ostringstream os;
13131         os << "0 " << uses << " " << NameOf(instruction) << " " << *instruction;
13132         if (graph->info()->is_tracking_positions() &&
13133             instruction->has_position() && instruction->position().raw() != 0) {
13134           const SourcePosition pos = instruction->position();
13135           os << " pos:";
13136           if (pos.inlining_id() != 0) os << pos.inlining_id() << "_";
13137           os << pos.position();
13138         }
13139         os << " <|@\n";
13140         trace_.Add(os.str().c_str());
13141       }
13142     }
13143
13144
13145     if (chunk != NULL) {
13146       Tag LIR_tag(this, "LIR");
13147       int first_index = current->first_instruction_index();
13148       int last_index = current->last_instruction_index();
13149       if (first_index != -1 && last_index != -1) {
13150         const ZoneList<LInstruction*>* instructions = chunk->instructions();
13151         for (int i = first_index; i <= last_index; ++i) {
13152           LInstruction* linstr = instructions->at(i);
13153           if (linstr != NULL) {
13154             PrintIndent();
13155             trace_.Add("%d ",
13156                        LifetimePosition::FromInstructionIndex(i).Value());
13157             linstr->PrintTo(&trace_);
13158             std::ostringstream os;
13159             os << " [hir:" << NameOf(linstr->hydrogen_value()) << "] <|@\n";
13160             trace_.Add(os.str().c_str());
13161           }
13162         }
13163       }
13164     }
13165   }
13166 }
13167
13168
13169 void HTracer::TraceLiveRanges(const char* name, LAllocator* allocator) {
13170   Tag tag(this, "intervals");
13171   PrintStringProperty("name", name);
13172
13173   const Vector<LiveRange*>* fixed_d = allocator->fixed_double_live_ranges();
13174   for (int i = 0; i < fixed_d->length(); ++i) {
13175     TraceLiveRange(fixed_d->at(i), "fixed", allocator->zone());
13176   }
13177
13178   const Vector<LiveRange*>* fixed = allocator->fixed_live_ranges();
13179   for (int i = 0; i < fixed->length(); ++i) {
13180     TraceLiveRange(fixed->at(i), "fixed", allocator->zone());
13181   }
13182
13183   const ZoneList<LiveRange*>* live_ranges = allocator->live_ranges();
13184   for (int i = 0; i < live_ranges->length(); ++i) {
13185     TraceLiveRange(live_ranges->at(i), "object", allocator->zone());
13186   }
13187 }
13188
13189
13190 void HTracer::TraceLiveRange(LiveRange* range, const char* type,
13191                              Zone* zone) {
13192   if (range != NULL && !range->IsEmpty()) {
13193     PrintIndent();
13194     trace_.Add("%d %s", range->id(), type);
13195     if (range->HasRegisterAssigned()) {
13196       LOperand* op = range->CreateAssignedOperand(zone);
13197       int assigned_reg = op->index();
13198       if (op->IsDoubleRegister()) {
13199         trace_.Add(" \"%s\"",
13200                    DoubleRegister::AllocationIndexToString(assigned_reg));
13201       } else {
13202         DCHECK(op->IsRegister());
13203         trace_.Add(" \"%s\"", Register::AllocationIndexToString(assigned_reg));
13204       }
13205     } else if (range->IsSpilled()) {
13206       LOperand* op = range->TopLevel()->GetSpillOperand();
13207       if (op->IsDoubleStackSlot()) {
13208         trace_.Add(" \"double_stack:%d\"", op->index());
13209       } else {
13210         DCHECK(op->IsStackSlot());
13211         trace_.Add(" \"stack:%d\"", op->index());
13212       }
13213     }
13214     int parent_index = -1;
13215     if (range->IsChild()) {
13216       parent_index = range->parent()->id();
13217     } else {
13218       parent_index = range->id();
13219     }
13220     LOperand* op = range->FirstHint();
13221     int hint_index = -1;
13222     if (op != NULL && op->IsUnallocated()) {
13223       hint_index = LUnallocated::cast(op)->virtual_register();
13224     }
13225     trace_.Add(" %d %d", parent_index, hint_index);
13226     UseInterval* cur_interval = range->first_interval();
13227     while (cur_interval != NULL && range->Covers(cur_interval->start())) {
13228       trace_.Add(" [%d, %d[",
13229                  cur_interval->start().Value(),
13230                  cur_interval->end().Value());
13231       cur_interval = cur_interval->next();
13232     }
13233
13234     UsePosition* current_pos = range->first_pos();
13235     while (current_pos != NULL) {
13236       if (current_pos->RegisterIsBeneficial() || FLAG_trace_all_uses) {
13237         trace_.Add(" %d M", current_pos->pos().Value());
13238       }
13239       current_pos = current_pos->next();
13240     }
13241
13242     trace_.Add(" \"\"\n");
13243   }
13244 }
13245
13246
13247 void HTracer::FlushToFile() {
13248   AppendChars(filename_.start(), trace_.ToCString().get(), trace_.length(),
13249               false);
13250   trace_.Reset();
13251 }
13252
13253
13254 void HStatistics::Initialize(CompilationInfo* info) {
13255   if (info->shared_info().is_null()) return;
13256   source_size_ += info->shared_info()->SourceSize();
13257 }
13258
13259
13260 void HStatistics::Print() {
13261   PrintF(
13262       "\n"
13263       "----------------------------------------"
13264       "----------------------------------------\n"
13265       "--- Hydrogen timing results:\n"
13266       "----------------------------------------"
13267       "----------------------------------------\n");
13268   base::TimeDelta sum;
13269   for (int i = 0; i < times_.length(); ++i) {
13270     sum += times_[i];
13271   }
13272
13273   for (int i = 0; i < names_.length(); ++i) {
13274     PrintF("%33s", names_[i]);
13275     double ms = times_[i].InMillisecondsF();
13276     double percent = times_[i].PercentOf(sum);
13277     PrintF(" %8.3f ms / %4.1f %% ", ms, percent);
13278
13279     size_t size = sizes_[i];
13280     double size_percent = static_cast<double>(size) * 100 / total_size_;
13281     PrintF(" %9zu bytes / %4.1f %%\n", size, size_percent);
13282   }
13283
13284   PrintF(
13285       "----------------------------------------"
13286       "----------------------------------------\n");
13287   base::TimeDelta total = create_graph_ + optimize_graph_ + generate_code_;
13288   PrintF("%33s %8.3f ms / %4.1f %% \n", "Create graph",
13289          create_graph_.InMillisecondsF(), create_graph_.PercentOf(total));
13290   PrintF("%33s %8.3f ms / %4.1f %% \n", "Optimize graph",
13291          optimize_graph_.InMillisecondsF(), optimize_graph_.PercentOf(total));
13292   PrintF("%33s %8.3f ms / %4.1f %% \n", "Generate and install code",
13293          generate_code_.InMillisecondsF(), generate_code_.PercentOf(total));
13294   PrintF(
13295       "----------------------------------------"
13296       "----------------------------------------\n");
13297   PrintF("%33s %8.3f ms           %9zu bytes\n", "Total",
13298          total.InMillisecondsF(), total_size_);
13299   PrintF("%33s     (%.1f times slower than full code gen)\n", "",
13300          total.TimesOf(full_code_gen_));
13301
13302   double source_size_in_kb = static_cast<double>(source_size_) / 1024;
13303   double normalized_time =  source_size_in_kb > 0
13304       ? total.InMillisecondsF() / source_size_in_kb
13305       : 0;
13306   double normalized_size_in_kb =
13307       source_size_in_kb > 0
13308           ? static_cast<double>(total_size_) / 1024 / source_size_in_kb
13309           : 0;
13310   PrintF("%33s %8.3f ms           %7.3f kB allocated\n",
13311          "Average per kB source", normalized_time, normalized_size_in_kb);
13312 }
13313
13314
13315 void HStatistics::SaveTiming(const char* name, base::TimeDelta time,
13316                              size_t size) {
13317   total_size_ += size;
13318   for (int i = 0; i < names_.length(); ++i) {
13319     if (strcmp(names_[i], name) == 0) {
13320       times_[i] += time;
13321       sizes_[i] += size;
13322       return;
13323     }
13324   }
13325   names_.Add(name);
13326   times_.Add(time);
13327   sizes_.Add(size);
13328 }
13329
13330
13331 HPhase::~HPhase() {
13332   if (ShouldProduceTraceOutput()) {
13333     isolate()->GetHTracer()->TraceHydrogen(name(), graph_);
13334   }
13335
13336 #ifdef DEBUG
13337   graph_->Verify(false);  // No full verify.
13338 #endif
13339 }
13340
13341 }  // namespace internal
13342 }  // namespace v8