Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / v8 / 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 <algorithm>
8
9 #include "src/v8.h"
10
11 #include "src/allocation-site-scopes.h"
12 #include "src/codegen.h"
13 #include "src/full-codegen.h"
14 #include "src/hashmap.h"
15 #include "src/hydrogen-bce.h"
16 #include "src/hydrogen-bch.h"
17 #include "src/hydrogen-canonicalize.h"
18 #include "src/hydrogen-check-elimination.h"
19 #include "src/hydrogen-dce.h"
20 #include "src/hydrogen-dehoist.h"
21 #include "src/hydrogen-environment-liveness.h"
22 #include "src/hydrogen-escape-analysis.h"
23 #include "src/hydrogen-gvn.h"
24 #include "src/hydrogen-infer-representation.h"
25 #include "src/hydrogen-infer-types.h"
26 #include "src/hydrogen-load-elimination.h"
27 #include "src/hydrogen-mark-deoptimize.h"
28 #include "src/hydrogen-mark-unreachable.h"
29 #include "src/hydrogen-osr.h"
30 #include "src/hydrogen-range-analysis.h"
31 #include "src/hydrogen-redundant-phi.h"
32 #include "src/hydrogen-removable-simulates.h"
33 #include "src/hydrogen-representation-changes.h"
34 #include "src/hydrogen-sce.h"
35 #include "src/hydrogen-store-elimination.h"
36 #include "src/hydrogen-uint32-analysis.h"
37 #include "src/lithium-allocator.h"
38 #include "src/parser.h"
39 #include "src/runtime.h"
40 #include "src/scopeinfo.h"
41 #include "src/scopes.h"
42 #include "src/stub-cache.h"
43 #include "src/typing.h"
44
45 #if V8_TARGET_ARCH_IA32
46 #include "src/ia32/lithium-codegen-ia32.h"  // NOLINT
47 #elif V8_TARGET_ARCH_X64
48 #include "src/x64/lithium-codegen-x64.h"  // NOLINT
49 #elif V8_TARGET_ARCH_ARM64
50 #include "src/arm64/lithium-codegen-arm64.h"  // NOLINT
51 #elif V8_TARGET_ARCH_ARM
52 #include "src/arm/lithium-codegen-arm.h"  // NOLINT
53 #elif V8_TARGET_ARCH_MIPS
54 #include "src/mips/lithium-codegen-mips.h"  // NOLINT
55 #elif V8_TARGET_ARCH_MIPS64
56 #include "src/mips64/lithium-codegen-mips64.h"  // NOLINT
57 #elif V8_TARGET_ARCH_X87
58 #include "src/x87/lithium-codegen-x87.h"  // NOLINT
59 #else
60 #error Unsupported target architecture.
61 #endif
62
63 namespace v8 {
64 namespace internal {
65
66 HBasicBlock::HBasicBlock(HGraph* graph)
67     : block_id_(graph->GetNextBlockID()),
68       graph_(graph),
69       phis_(4, graph->zone()),
70       first_(NULL),
71       last_(NULL),
72       end_(NULL),
73       loop_information_(NULL),
74       predecessors_(2, graph->zone()),
75       dominator_(NULL),
76       dominated_blocks_(4, graph->zone()),
77       last_environment_(NULL),
78       argument_count_(-1),
79       first_instruction_index_(-1),
80       last_instruction_index_(-1),
81       deleted_phis_(4, graph->zone()),
82       parent_loop_header_(NULL),
83       inlined_entry_block_(NULL),
84       is_inline_return_target_(false),
85       is_reachable_(true),
86       dominates_loop_successors_(false),
87       is_osr_entry_(false),
88       is_ordered_(false) { }
89
90
91 Isolate* HBasicBlock::isolate() const {
92   return graph_->isolate();
93 }
94
95
96 void HBasicBlock::MarkUnreachable() {
97   is_reachable_ = false;
98 }
99
100
101 void HBasicBlock::AttachLoopInformation() {
102   DCHECK(!IsLoopHeader());
103   loop_information_ = new(zone()) HLoopInformation(this, zone());
104 }
105
106
107 void HBasicBlock::DetachLoopInformation() {
108   DCHECK(IsLoopHeader());
109   loop_information_ = NULL;
110 }
111
112
113 void HBasicBlock::AddPhi(HPhi* phi) {
114   DCHECK(!IsStartBlock());
115   phis_.Add(phi, zone());
116   phi->SetBlock(this);
117 }
118
119
120 void HBasicBlock::RemovePhi(HPhi* phi) {
121   DCHECK(phi->block() == this);
122   DCHECK(phis_.Contains(phi));
123   phi->Kill();
124   phis_.RemoveElement(phi);
125   phi->SetBlock(NULL);
126 }
127
128
129 void HBasicBlock::AddInstruction(HInstruction* instr,
130                                  HSourcePosition position) {
131   DCHECK(!IsStartBlock() || !IsFinished());
132   DCHECK(!instr->IsLinked());
133   DCHECK(!IsFinished());
134
135   if (!position.IsUnknown()) {
136     instr->set_position(position);
137   }
138   if (first_ == NULL) {
139     DCHECK(last_environment() != NULL);
140     DCHECK(!last_environment()->ast_id().IsNone());
141     HBlockEntry* entry = new(zone()) HBlockEntry();
142     entry->InitializeAsFirst(this);
143     if (!position.IsUnknown()) {
144       entry->set_position(position);
145     } else {
146       DCHECK(!FLAG_hydrogen_track_positions ||
147              !graph()->info()->IsOptimizing());
148     }
149     first_ = last_ = entry;
150   }
151   instr->InsertAfter(last_);
152 }
153
154
155 HPhi* HBasicBlock::AddNewPhi(int merged_index) {
156   if (graph()->IsInsideNoSideEffectsScope()) {
157     merged_index = HPhi::kInvalidMergedIndex;
158   }
159   HPhi* phi = new(zone()) HPhi(merged_index, zone());
160   AddPhi(phi);
161   return phi;
162 }
163
164
165 HSimulate* HBasicBlock::CreateSimulate(BailoutId ast_id,
166                                        RemovableSimulate removable) {
167   DCHECK(HasEnvironment());
168   HEnvironment* environment = last_environment();
169   DCHECK(ast_id.IsNone() ||
170          ast_id == BailoutId::StubEntry() ||
171          environment->closure()->shared()->VerifyBailoutId(ast_id));
172
173   int push_count = environment->push_count();
174   int pop_count = environment->pop_count();
175
176   HSimulate* instr =
177       new(zone()) HSimulate(ast_id, pop_count, zone(), removable);
178 #ifdef DEBUG
179   instr->set_closure(environment->closure());
180 #endif
181   // Order of pushed values: newest (top of stack) first. This allows
182   // HSimulate::MergeWith() to easily append additional pushed values
183   // that are older (from further down the stack).
184   for (int i = 0; i < push_count; ++i) {
185     instr->AddPushedValue(environment->ExpressionStackAt(i));
186   }
187   for (GrowableBitVector::Iterator it(environment->assigned_variables(),
188                                       zone());
189        !it.Done();
190        it.Advance()) {
191     int index = it.Current();
192     instr->AddAssignedValue(index, environment->Lookup(index));
193   }
194   environment->ClearHistory();
195   return instr;
196 }
197
198
199 void HBasicBlock::Finish(HControlInstruction* end, HSourcePosition position) {
200   DCHECK(!IsFinished());
201   AddInstruction(end, position);
202   end_ = end;
203   for (HSuccessorIterator it(end); !it.Done(); it.Advance()) {
204     it.Current()->RegisterPredecessor(this);
205   }
206 }
207
208
209 void HBasicBlock::Goto(HBasicBlock* block,
210                        HSourcePosition position,
211                        FunctionState* state,
212                        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,
232                                   FunctionState* state,
233                                   HSourcePosition position) {
234   HBasicBlock* target = state->function_return();
235   bool drop_extra = state->inlining_kind() == NORMAL_RETURN;
236
237   DCHECK(target->IsInlineReturnTarget());
238   DCHECK(return_value != NULL);
239   HEnvironment* env = last_environment();
240   int argument_count = env->arguments_environment()->parameter_count();
241   AddInstruction(new(zone()) HLeaveInlined(state->entry(), argument_count),
242                  position);
243   UpdateEnvironment(last_environment()->DiscardInlined(drop_extra));
244   last_environment()->Push(return_value);
245   AddNewSimulate(BailoutId::None(), position);
246   HGoto* instr = new(zone()) HGoto(target);
247   Finish(instr, position);
248 }
249
250
251 void HBasicBlock::SetInitialEnvironment(HEnvironment* env) {
252   DCHECK(!HasEnvironment());
253   DCHECK(first() == NULL);
254   UpdateEnvironment(env);
255 }
256
257
258 void HBasicBlock::UpdateEnvironment(HEnvironment* env) {
259   last_environment_ = env;
260   graph()->update_maximum_environment_size(env->first_expression_index());
261 }
262
263
264 void HBasicBlock::SetJoinId(BailoutId ast_id) {
265   int length = predecessors_.length();
266   DCHECK(length > 0);
267   for (int i = 0; i < length; i++) {
268     HBasicBlock* predecessor = predecessors_[i];
269     DCHECK(predecessor->end()->IsGoto());
270     HSimulate* simulate = HSimulate::cast(predecessor->end()->previous());
271     DCHECK(i != 0 ||
272            (predecessor->last_environment()->closure().is_null() ||
273             predecessor->last_environment()->closure()->shared()
274               ->VerifyBailoutId(ast_id)));
275     simulate->set_ast_id(ast_id);
276     predecessor->last_environment()->set_ast_id(ast_id);
277   }
278 }
279
280
281 bool HBasicBlock::Dominates(HBasicBlock* other) const {
282   HBasicBlock* current = other->dominator();
283   while (current != NULL) {
284     if (current == this) return true;
285     current = current->dominator();
286   }
287   return false;
288 }
289
290
291 bool HBasicBlock::EqualToOrDominates(HBasicBlock* other) const {
292   if (this == other) return true;
293   return Dominates(other);
294 }
295
296
297 int HBasicBlock::LoopNestingDepth() const {
298   const HBasicBlock* current = this;
299   int result  = (current->IsLoopHeader()) ? 1 : 0;
300   while (current->parent_loop_header() != NULL) {
301     current = current->parent_loop_header();
302     result++;
303   }
304   return result;
305 }
306
307
308 void HBasicBlock::PostProcessLoopHeader(IterationStatement* stmt) {
309   DCHECK(IsLoopHeader());
310
311   SetJoinId(stmt->EntryId());
312   if (predecessors()->length() == 1) {
313     // This is a degenerated loop.
314     DetachLoopInformation();
315     return;
316   }
317
318   // Only the first entry into the loop is from outside the loop. All other
319   // entries must be back edges.
320   for (int i = 1; i < predecessors()->length(); ++i) {
321     loop_information()->RegisterBackEdge(predecessors()->at(i));
322   }
323 }
324
325
326 void HBasicBlock::MarkSuccEdgeUnreachable(int succ) {
327   DCHECK(IsFinished());
328   HBasicBlock* succ_block = end()->SuccessorAt(succ);
329
330   DCHECK(succ_block->predecessors()->length() == 1);
331   succ_block->MarkUnreachable();
332 }
333
334
335 void HBasicBlock::RegisterPredecessor(HBasicBlock* pred) {
336   if (HasPredecessor()) {
337     // Only loop header blocks can have a predecessor added after
338     // instructions have been added to the block (they have phis for all
339     // values in the environment, these phis may be eliminated later).
340     DCHECK(IsLoopHeader() || first_ == NULL);
341     HEnvironment* incoming_env = pred->last_environment();
342     if (IsLoopHeader()) {
343       DCHECK(phis()->length() == incoming_env->length());
344       for (int i = 0; i < phis_.length(); ++i) {
345         phis_[i]->AddInput(incoming_env->values()->at(i));
346       }
347     } else {
348       last_environment()->AddIncomingEdge(this, pred->last_environment());
349     }
350   } else if (!HasEnvironment() && !IsFinished()) {
351     DCHECK(!IsLoopHeader());
352     SetInitialEnvironment(pred->last_environment()->Copy());
353   }
354
355   predecessors_.Add(pred, zone());
356 }
357
358
359 void HBasicBlock::AddDominatedBlock(HBasicBlock* block) {
360   DCHECK(!dominated_blocks_.Contains(block));
361   // Keep the list of dominated blocks sorted such that if there is two
362   // succeeding block in this list, the predecessor is before the successor.
363   int index = 0;
364   while (index < dominated_blocks_.length() &&
365          dominated_blocks_[index]->block_id() < block->block_id()) {
366     ++index;
367   }
368   dominated_blocks_.InsertAt(index, block, zone());
369 }
370
371
372 void HBasicBlock::AssignCommonDominator(HBasicBlock* other) {
373   if (dominator_ == NULL) {
374     dominator_ = other;
375     other->AddDominatedBlock(this);
376   } else if (other->dominator() != NULL) {
377     HBasicBlock* first = dominator_;
378     HBasicBlock* second = other;
379
380     while (first != second) {
381       if (first->block_id() > second->block_id()) {
382         first = first->dominator();
383       } else {
384         second = second->dominator();
385       }
386       DCHECK(first != NULL && second != NULL);
387     }
388
389     if (dominator_ != first) {
390       DCHECK(dominator_->dominated_blocks_.Contains(this));
391       dominator_->dominated_blocks_.RemoveElement(this);
392       dominator_ = first;
393       first->AddDominatedBlock(this);
394     }
395   }
396 }
397
398
399 void HBasicBlock::AssignLoopSuccessorDominators() {
400   // Mark blocks that dominate all subsequent reachable blocks inside their
401   // loop. Exploit the fact that blocks are sorted in reverse post order. When
402   // the loop is visited in increasing block id order, if the number of
403   // non-loop-exiting successor edges at the dominator_candidate block doesn't
404   // exceed the number of previously encountered predecessor edges, there is no
405   // path from the loop header to any block with higher id that doesn't go
406   // through the dominator_candidate block. In this case, the
407   // dominator_candidate block is guaranteed to dominate all blocks reachable
408   // from it with higher ids.
409   HBasicBlock* last = loop_information()->GetLastBackEdge();
410   int outstanding_successors = 1;  // one edge from the pre-header
411   // Header always dominates everything.
412   MarkAsLoopSuccessorDominator();
413   for (int j = block_id(); j <= last->block_id(); ++j) {
414     HBasicBlock* dominator_candidate = graph_->blocks()->at(j);
415     for (HPredecessorIterator it(dominator_candidate); !it.Done();
416          it.Advance()) {
417       HBasicBlock* predecessor = it.Current();
418       // Don't count back edges.
419       if (predecessor->block_id() < dominator_candidate->block_id()) {
420         outstanding_successors--;
421       }
422     }
423
424     // If more successors than predecessors have been seen in the loop up to
425     // now, it's not possible to guarantee that the current block dominates
426     // all of the blocks with higher IDs. In this case, assume conservatively
427     // that those paths through loop that don't go through the current block
428     // contain all of the loop's dependencies. Also be careful to record
429     // dominator information about the current loop that's being processed,
430     // and not nested loops, which will be processed when
431     // AssignLoopSuccessorDominators gets called on their header.
432     DCHECK(outstanding_successors >= 0);
433     HBasicBlock* parent_loop_header = dominator_candidate->parent_loop_header();
434     if (outstanding_successors == 0 &&
435         (parent_loop_header == this && !dominator_candidate->IsLoopHeader())) {
436       dominator_candidate->MarkAsLoopSuccessorDominator();
437     }
438     HControlInstruction* end = dominator_candidate->end();
439     for (HSuccessorIterator it(end); !it.Done(); it.Advance()) {
440       HBasicBlock* successor = it.Current();
441       // Only count successors that remain inside the loop and don't loop back
442       // to a loop header.
443       if (successor->block_id() > dominator_candidate->block_id() &&
444           successor->block_id() <= last->block_id()) {
445         // Backwards edges must land on loop headers.
446         DCHECK(successor->block_id() > dominator_candidate->block_id() ||
447                successor->IsLoopHeader());
448         outstanding_successors++;
449       }
450     }
451   }
452 }
453
454
455 int HBasicBlock::PredecessorIndexOf(HBasicBlock* predecessor) const {
456   for (int i = 0; i < predecessors_.length(); ++i) {
457     if (predecessors_[i] == predecessor) return i;
458   }
459   UNREACHABLE();
460   return -1;
461 }
462
463
464 #ifdef DEBUG
465 void HBasicBlock::Verify() {
466   // Check that every block is finished.
467   DCHECK(IsFinished());
468   DCHECK(block_id() >= 0);
469
470   // Check that the incoming edges are in edge split form.
471   if (predecessors_.length() > 1) {
472     for (int i = 0; i < predecessors_.length(); ++i) {
473       DCHECK(predecessors_[i]->end()->SecondSuccessor() == NULL);
474     }
475   }
476 }
477 #endif
478
479
480 void HLoopInformation::RegisterBackEdge(HBasicBlock* block) {
481   this->back_edges_.Add(block, block->zone());
482   AddBlock(block);
483 }
484
485
486 HBasicBlock* HLoopInformation::GetLastBackEdge() const {
487   int max_id = -1;
488   HBasicBlock* result = NULL;
489   for (int i = 0; i < back_edges_.length(); ++i) {
490     HBasicBlock* cur = back_edges_[i];
491     if (cur->block_id() > max_id) {
492       max_id = cur->block_id();
493       result = cur;
494     }
495   }
496   return result;
497 }
498
499
500 void HLoopInformation::AddBlock(HBasicBlock* block) {
501   if (block == loop_header()) return;
502   if (block->parent_loop_header() == loop_header()) return;
503   if (block->parent_loop_header() != NULL) {
504     AddBlock(block->parent_loop_header());
505   } else {
506     block->set_parent_loop_header(loop_header());
507     blocks_.Add(block, block->zone());
508     for (int i = 0; i < block->predecessors()->length(); ++i) {
509       AddBlock(block->predecessors()->at(i));
510     }
511   }
512 }
513
514
515 #ifdef DEBUG
516
517 // Checks reachability of the blocks in this graph and stores a bit in
518 // the BitVector "reachable()" for every block that can be reached
519 // from the start block of the graph. If "dont_visit" is non-null, the given
520 // block is treated as if it would not be part of the graph. "visited_count()"
521 // returns the number of reachable blocks.
522 class ReachabilityAnalyzer BASE_EMBEDDED {
523  public:
524   ReachabilityAnalyzer(HBasicBlock* entry_block,
525                        int block_count,
526                        HBasicBlock* dont_visit)
527       : visited_count_(0),
528         stack_(16, entry_block->zone()),
529         reachable_(block_count, entry_block->zone()),
530         dont_visit_(dont_visit) {
531     PushBlock(entry_block);
532     Analyze();
533   }
534
535   int visited_count() const { return visited_count_; }
536   const BitVector* reachable() const { return &reachable_; }
537
538  private:
539   void PushBlock(HBasicBlock* block) {
540     if (block != NULL && block != dont_visit_ &&
541         !reachable_.Contains(block->block_id())) {
542       reachable_.Add(block->block_id());
543       stack_.Add(block, block->zone());
544       visited_count_++;
545     }
546   }
547
548   void Analyze() {
549     while (!stack_.is_empty()) {
550       HControlInstruction* end = stack_.RemoveLast()->end();
551       for (HSuccessorIterator it(end); !it.Done(); it.Advance()) {
552         PushBlock(it.Current());
553       }
554     }
555   }
556
557   int visited_count_;
558   ZoneList<HBasicBlock*> stack_;
559   BitVector reachable_;
560   HBasicBlock* dont_visit_;
561 };
562
563
564 void HGraph::Verify(bool do_full_verify) const {
565   Heap::RelocationLock relocation_lock(isolate()->heap());
566   AllowHandleDereference allow_deref;
567   AllowDeferredHandleDereference allow_deferred_deref;
568   for (int i = 0; i < blocks_.length(); i++) {
569     HBasicBlock* block = blocks_.at(i);
570
571     block->Verify();
572
573     // Check that every block contains at least one node and that only the last
574     // node is a control instruction.
575     HInstruction* current = block->first();
576     DCHECK(current != NULL && current->IsBlockEntry());
577     while (current != NULL) {
578       DCHECK((current->next() == NULL) == current->IsControlInstruction());
579       DCHECK(current->block() == block);
580       current->Verify();
581       current = current->next();
582     }
583
584     // Check that successors are correctly set.
585     HBasicBlock* first = block->end()->FirstSuccessor();
586     HBasicBlock* second = block->end()->SecondSuccessor();
587     DCHECK(second == NULL || first != NULL);
588
589     // Check that the predecessor array is correct.
590     if (first != NULL) {
591       DCHECK(first->predecessors()->Contains(block));
592       if (second != NULL) {
593         DCHECK(second->predecessors()->Contains(block));
594       }
595     }
596
597     // Check that phis have correct arguments.
598     for (int j = 0; j < block->phis()->length(); j++) {
599       HPhi* phi = block->phis()->at(j);
600       phi->Verify();
601     }
602
603     // Check that all join blocks have predecessors that end with an
604     // unconditional goto and agree on their environment node id.
605     if (block->predecessors()->length() >= 2) {
606       BailoutId id =
607           block->predecessors()->first()->last_environment()->ast_id();
608       for (int k = 0; k < block->predecessors()->length(); k++) {
609         HBasicBlock* predecessor = block->predecessors()->at(k);
610         DCHECK(predecessor->end()->IsGoto() ||
611                predecessor->end()->IsDeoptimize());
612         DCHECK(predecessor->last_environment()->ast_id() == id);
613       }
614     }
615   }
616
617   // Check special property of first block to have no predecessors.
618   DCHECK(blocks_.at(0)->predecessors()->is_empty());
619
620   if (do_full_verify) {
621     // Check that the graph is fully connected.
622     ReachabilityAnalyzer analyzer(entry_block_, blocks_.length(), NULL);
623     DCHECK(analyzer.visited_count() == blocks_.length());
624
625     // Check that entry block dominator is NULL.
626     DCHECK(entry_block_->dominator() == NULL);
627
628     // Check dominators.
629     for (int i = 0; i < blocks_.length(); ++i) {
630       HBasicBlock* block = blocks_.at(i);
631       if (block->dominator() == NULL) {
632         // Only start block may have no dominator assigned to.
633         DCHECK(i == 0);
634       } else {
635         // Assert that block is unreachable if dominator must not be visited.
636         ReachabilityAnalyzer dominator_analyzer(entry_block_,
637                                                 blocks_.length(),
638                                                 block->dominator());
639         DCHECK(!dominator_analyzer.reachable()->Contains(block->block_id()));
640       }
641     }
642   }
643 }
644
645 #endif
646
647
648 HConstant* HGraph::GetConstant(SetOncePointer<HConstant>* pointer,
649                                int32_t value) {
650   if (!pointer->is_set()) {
651     // Can't pass GetInvalidContext() to HConstant::New, because that will
652     // recursively call GetConstant
653     HConstant* constant = HConstant::New(zone(), NULL, value);
654     constant->InsertAfter(entry_block()->first());
655     pointer->set(constant);
656     return constant;
657   }
658   return ReinsertConstantIfNecessary(pointer->get());
659 }
660
661
662 HConstant* HGraph::ReinsertConstantIfNecessary(HConstant* constant) {
663   if (!constant->IsLinked()) {
664     // The constant was removed from the graph. Reinsert.
665     constant->ClearFlag(HValue::kIsDead);
666     constant->InsertAfter(entry_block()->first());
667   }
668   return constant;
669 }
670
671
672 HConstant* HGraph::GetConstant0() {
673   return GetConstant(&constant_0_, 0);
674 }
675
676
677 HConstant* HGraph::GetConstant1() {
678   return GetConstant(&constant_1_, 1);
679 }
680
681
682 HConstant* HGraph::GetConstantMinus1() {
683   return GetConstant(&constant_minus1_, -1);
684 }
685
686
687 #define DEFINE_GET_CONSTANT(Name, name, type, htype, boolean_value)            \
688 HConstant* HGraph::GetConstant##Name() {                                       \
689   if (!constant_##name##_.is_set()) {                                          \
690     HConstant* constant = new(zone()) HConstant(                               \
691         Unique<Object>::CreateImmovable(isolate()->factory()->name##_value()), \
692         Unique<Map>::CreateImmovable(isolate()->factory()->type##_map()),      \
693         false,                                                                 \
694         Representation::Tagged(),                                              \
695         htype,                                                                 \
696         true,                                                                  \
697         boolean_value,                                                         \
698         false,                                                                 \
699         ODDBALL_TYPE);                                                         \
700     constant->InsertAfter(entry_block()->first());                             \
701     constant_##name##_.set(constant);                                          \
702   }                                                                            \
703   return ReinsertConstantIfNecessary(constant_##name##_.get());                \
704 }
705
706
707 DEFINE_GET_CONSTANT(Undefined, undefined, undefined, HType::Undefined(), false)
708 DEFINE_GET_CONSTANT(True, true, boolean, HType::Boolean(), true)
709 DEFINE_GET_CONSTANT(False, false, boolean, HType::Boolean(), false)
710 DEFINE_GET_CONSTANT(Hole, the_hole, the_hole, HType::None(), false)
711 DEFINE_GET_CONSTANT(Null, null, null, HType::Null(), false)
712
713
714 #undef DEFINE_GET_CONSTANT
715
716 #define DEFINE_IS_CONSTANT(Name, name)                                         \
717 bool HGraph::IsConstant##Name(HConstant* constant) {                           \
718   return constant_##name##_.is_set() && constant == constant_##name##_.get();  \
719 }
720 DEFINE_IS_CONSTANT(Undefined, undefined)
721 DEFINE_IS_CONSTANT(0, 0)
722 DEFINE_IS_CONSTANT(1, 1)
723 DEFINE_IS_CONSTANT(Minus1, minus1)
724 DEFINE_IS_CONSTANT(True, true)
725 DEFINE_IS_CONSTANT(False, false)
726 DEFINE_IS_CONSTANT(Hole, the_hole)
727 DEFINE_IS_CONSTANT(Null, null)
728
729 #undef DEFINE_IS_CONSTANT
730
731
732 HConstant* HGraph::GetInvalidContext() {
733   return GetConstant(&constant_invalid_context_, 0xFFFFC0C7);
734 }
735
736
737 bool HGraph::IsStandardConstant(HConstant* constant) {
738   if (IsConstantUndefined(constant)) return true;
739   if (IsConstant0(constant)) return true;
740   if (IsConstant1(constant)) return true;
741   if (IsConstantMinus1(constant)) return true;
742   if (IsConstantTrue(constant)) return true;
743   if (IsConstantFalse(constant)) return true;
744   if (IsConstantHole(constant)) return true;
745   if (IsConstantNull(constant)) return true;
746   return false;
747 }
748
749
750 HGraphBuilder::IfBuilder::IfBuilder() : builder_(NULL), needs_compare_(true) {}
751
752
753 HGraphBuilder::IfBuilder::IfBuilder(HGraphBuilder* builder)
754     : needs_compare_(true) {
755   Initialize(builder);
756 }
757
758
759 HGraphBuilder::IfBuilder::IfBuilder(HGraphBuilder* builder,
760                                     HIfContinuation* continuation)
761     : needs_compare_(false), first_true_block_(NULL), first_false_block_(NULL) {
762   InitializeDontCreateBlocks(builder);
763   continuation->Continue(&first_true_block_, &first_false_block_);
764 }
765
766
767 void HGraphBuilder::IfBuilder::InitializeDontCreateBlocks(
768     HGraphBuilder* builder) {
769   builder_ = builder;
770   finished_ = false;
771   did_then_ = false;
772   did_else_ = false;
773   did_else_if_ = false;
774   did_and_ = false;
775   did_or_ = false;
776   captured_ = false;
777   pending_merge_block_ = false;
778   split_edge_merge_block_ = NULL;
779   merge_at_join_blocks_ = NULL;
780   normal_merge_at_join_block_count_ = 0;
781   deopt_merge_at_join_block_count_ = 0;
782 }
783
784
785 void HGraphBuilder::IfBuilder::Initialize(HGraphBuilder* builder) {
786   InitializeDontCreateBlocks(builder);
787   HEnvironment* env = builder->environment();
788   first_true_block_ = builder->CreateBasicBlock(env->Copy());
789   first_false_block_ = builder->CreateBasicBlock(env->Copy());
790 }
791
792
793 HControlInstruction* HGraphBuilder::IfBuilder::AddCompare(
794     HControlInstruction* compare) {
795   DCHECK(did_then_ == did_else_);
796   if (did_else_) {
797     // Handle if-then-elseif
798     did_else_if_ = true;
799     did_else_ = false;
800     did_then_ = false;
801     did_and_ = false;
802     did_or_ = false;
803     pending_merge_block_ = false;
804     split_edge_merge_block_ = NULL;
805     HEnvironment* env = builder()->environment();
806     first_true_block_ = builder()->CreateBasicBlock(env->Copy());
807     first_false_block_ = builder()->CreateBasicBlock(env->Copy());
808   }
809   if (split_edge_merge_block_ != NULL) {
810     HEnvironment* env = first_false_block_->last_environment();
811     HBasicBlock* split_edge = builder()->CreateBasicBlock(env->Copy());
812     if (did_or_) {
813       compare->SetSuccessorAt(0, split_edge);
814       compare->SetSuccessorAt(1, first_false_block_);
815     } else {
816       compare->SetSuccessorAt(0, first_true_block_);
817       compare->SetSuccessorAt(1, split_edge);
818     }
819     builder()->GotoNoSimulate(split_edge, split_edge_merge_block_);
820   } else {
821     compare->SetSuccessorAt(0, first_true_block_);
822     compare->SetSuccessorAt(1, first_false_block_);
823   }
824   builder()->FinishCurrentBlock(compare);
825   needs_compare_ = false;
826   return compare;
827 }
828
829
830 void HGraphBuilder::IfBuilder::Or() {
831   DCHECK(!needs_compare_);
832   DCHECK(!did_and_);
833   did_or_ = true;
834   HEnvironment* env = first_false_block_->last_environment();
835   if (split_edge_merge_block_ == NULL) {
836     split_edge_merge_block_ = builder()->CreateBasicBlock(env->Copy());
837     builder()->GotoNoSimulate(first_true_block_, split_edge_merge_block_);
838     first_true_block_ = split_edge_merge_block_;
839   }
840   builder()->set_current_block(first_false_block_);
841   first_false_block_ = builder()->CreateBasicBlock(env->Copy());
842 }
843
844
845 void HGraphBuilder::IfBuilder::And() {
846   DCHECK(!needs_compare_);
847   DCHECK(!did_or_);
848   did_and_ = true;
849   HEnvironment* env = first_false_block_->last_environment();
850   if (split_edge_merge_block_ == NULL) {
851     split_edge_merge_block_ = builder()->CreateBasicBlock(env->Copy());
852     builder()->GotoNoSimulate(first_false_block_, split_edge_merge_block_);
853     first_false_block_ = split_edge_merge_block_;
854   }
855   builder()->set_current_block(first_true_block_);
856   first_true_block_ = builder()->CreateBasicBlock(env->Copy());
857 }
858
859
860 void HGraphBuilder::IfBuilder::CaptureContinuation(
861     HIfContinuation* continuation) {
862   DCHECK(!did_else_if_);
863   DCHECK(!finished_);
864   DCHECK(!captured_);
865
866   HBasicBlock* true_block = NULL;
867   HBasicBlock* false_block = NULL;
868   Finish(&true_block, &false_block);
869   DCHECK(true_block != NULL);
870   DCHECK(false_block != NULL);
871   continuation->Capture(true_block, false_block);
872   captured_ = true;
873   builder()->set_current_block(NULL);
874   End();
875 }
876
877
878 void HGraphBuilder::IfBuilder::JoinContinuation(HIfContinuation* continuation) {
879   DCHECK(!did_else_if_);
880   DCHECK(!finished_);
881   DCHECK(!captured_);
882   HBasicBlock* true_block = NULL;
883   HBasicBlock* false_block = NULL;
884   Finish(&true_block, &false_block);
885   merge_at_join_blocks_ = NULL;
886   if (true_block != NULL && !true_block->IsFinished()) {
887     DCHECK(continuation->IsTrueReachable());
888     builder()->GotoNoSimulate(true_block, continuation->true_branch());
889   }
890   if (false_block != NULL && !false_block->IsFinished()) {
891     DCHECK(continuation->IsFalseReachable());
892     builder()->GotoNoSimulate(false_block, continuation->false_branch());
893   }
894   captured_ = true;
895   End();
896 }
897
898
899 void HGraphBuilder::IfBuilder::Then() {
900   DCHECK(!captured_);
901   DCHECK(!finished_);
902   did_then_ = true;
903   if (needs_compare_) {
904     // Handle if's without any expressions, they jump directly to the "else"
905     // branch. However, we must pretend that the "then" branch is reachable,
906     // so that the graph builder visits it and sees any live range extending
907     // constructs within it.
908     HConstant* constant_false = builder()->graph()->GetConstantFalse();
909     ToBooleanStub::Types boolean_type = ToBooleanStub::Types();
910     boolean_type.Add(ToBooleanStub::BOOLEAN);
911     HBranch* branch = builder()->New<HBranch>(
912         constant_false, boolean_type, first_true_block_, first_false_block_);
913     builder()->FinishCurrentBlock(branch);
914   }
915   builder()->set_current_block(first_true_block_);
916   pending_merge_block_ = true;
917 }
918
919
920 void HGraphBuilder::IfBuilder::Else() {
921   DCHECK(did_then_);
922   DCHECK(!captured_);
923   DCHECK(!finished_);
924   AddMergeAtJoinBlock(false);
925   builder()->set_current_block(first_false_block_);
926   pending_merge_block_ = true;
927   did_else_ = true;
928 }
929
930
931 void HGraphBuilder::IfBuilder::Deopt(const char* reason) {
932   DCHECK(did_then_);
933   builder()->Add<HDeoptimize>(reason, Deoptimizer::EAGER);
934   AddMergeAtJoinBlock(true);
935 }
936
937
938 void HGraphBuilder::IfBuilder::Return(HValue* value) {
939   HValue* parameter_count = builder()->graph()->GetConstantMinus1();
940   builder()->FinishExitCurrentBlock(
941       builder()->New<HReturn>(value, parameter_count));
942   AddMergeAtJoinBlock(false);
943 }
944
945
946 void HGraphBuilder::IfBuilder::AddMergeAtJoinBlock(bool deopt) {
947   if (!pending_merge_block_) return;
948   HBasicBlock* block = builder()->current_block();
949   DCHECK(block == NULL || !block->IsFinished());
950   MergeAtJoinBlock* record = new (builder()->zone())
951       MergeAtJoinBlock(block, deopt, merge_at_join_blocks_);
952   merge_at_join_blocks_ = record;
953   if (block != NULL) {
954     DCHECK(block->end() == NULL);
955     if (deopt) {
956       normal_merge_at_join_block_count_++;
957     } else {
958       deopt_merge_at_join_block_count_++;
959     }
960   }
961   builder()->set_current_block(NULL);
962   pending_merge_block_ = false;
963 }
964
965
966 void HGraphBuilder::IfBuilder::Finish() {
967   DCHECK(!finished_);
968   if (!did_then_) {
969     Then();
970   }
971   AddMergeAtJoinBlock(false);
972   if (!did_else_) {
973     Else();
974     AddMergeAtJoinBlock(false);
975   }
976   finished_ = true;
977 }
978
979
980 void HGraphBuilder::IfBuilder::Finish(HBasicBlock** then_continuation,
981                                       HBasicBlock** else_continuation) {
982   Finish();
983
984   MergeAtJoinBlock* else_record = merge_at_join_blocks_;
985   if (else_continuation != NULL) {
986     *else_continuation = else_record->block_;
987   }
988   MergeAtJoinBlock* then_record = else_record->next_;
989   if (then_continuation != NULL) {
990     *then_continuation = then_record->block_;
991   }
992   DCHECK(then_record->next_ == NULL);
993 }
994
995
996 void HGraphBuilder::IfBuilder::End() {
997   if (captured_) return;
998   Finish();
999
1000   int total_merged_blocks = normal_merge_at_join_block_count_ +
1001     deopt_merge_at_join_block_count_;
1002   DCHECK(total_merged_blocks >= 1);
1003   HBasicBlock* merge_block =
1004       total_merged_blocks == 1 ? NULL : builder()->graph()->CreateBasicBlock();
1005
1006   // Merge non-deopt blocks first to ensure environment has right size for
1007   // padding.
1008   MergeAtJoinBlock* current = merge_at_join_blocks_;
1009   while (current != NULL) {
1010     if (!current->deopt_ && current->block_ != NULL) {
1011       // If there is only one block that makes it through to the end of the
1012       // if, then just set it as the current block and continue rather then
1013       // creating an unnecessary merge block.
1014       if (total_merged_blocks == 1) {
1015         builder()->set_current_block(current->block_);
1016         return;
1017       }
1018       builder()->GotoNoSimulate(current->block_, merge_block);
1019     }
1020     current = current->next_;
1021   }
1022
1023   // Merge deopt blocks, padding when necessary.
1024   current = merge_at_join_blocks_;
1025   while (current != NULL) {
1026     if (current->deopt_ && current->block_ != NULL) {
1027       current->block_->FinishExit(HAbnormalExit::New(builder()->zone(), NULL),
1028                                   HSourcePosition::Unknown());
1029     }
1030     current = current->next_;
1031   }
1032   builder()->set_current_block(merge_block);
1033 }
1034
1035
1036 HGraphBuilder::LoopBuilder::LoopBuilder(HGraphBuilder* builder) {
1037   Initialize(builder, NULL, kWhileTrue, NULL);
1038 }
1039
1040
1041 HGraphBuilder::LoopBuilder::LoopBuilder(HGraphBuilder* builder, HValue* context,
1042                                         LoopBuilder::Direction direction) {
1043   Initialize(builder, context, direction, builder->graph()->GetConstant1());
1044 }
1045
1046
1047 HGraphBuilder::LoopBuilder::LoopBuilder(HGraphBuilder* builder, HValue* context,
1048                                         LoopBuilder::Direction direction,
1049                                         HValue* increment_amount) {
1050   Initialize(builder, context, direction, increment_amount);
1051   increment_amount_ = increment_amount;
1052 }
1053
1054
1055 void HGraphBuilder::LoopBuilder::Initialize(HGraphBuilder* builder,
1056                                             HValue* context,
1057                                             Direction direction,
1058                                             HValue* increment_amount) {
1059   builder_ = builder;
1060   context_ = context;
1061   direction_ = direction;
1062   increment_amount_ = increment_amount;
1063
1064   finished_ = false;
1065   header_block_ = builder->CreateLoopHeaderBlock();
1066   body_block_ = NULL;
1067   exit_block_ = NULL;
1068   exit_trampoline_block_ = NULL;
1069 }
1070
1071
1072 HValue* HGraphBuilder::LoopBuilder::BeginBody(
1073     HValue* initial,
1074     HValue* terminating,
1075     Token::Value token) {
1076   DCHECK(direction_ != kWhileTrue);
1077   HEnvironment* env = builder_->environment();
1078   phi_ = header_block_->AddNewPhi(env->values()->length());
1079   phi_->AddInput(initial);
1080   env->Push(initial);
1081   builder_->GotoNoSimulate(header_block_);
1082
1083   HEnvironment* body_env = env->Copy();
1084   HEnvironment* exit_env = env->Copy();
1085   // Remove the phi from the expression stack
1086   body_env->Pop();
1087   exit_env->Pop();
1088   body_block_ = builder_->CreateBasicBlock(body_env);
1089   exit_block_ = builder_->CreateBasicBlock(exit_env);
1090
1091   builder_->set_current_block(header_block_);
1092   env->Pop();
1093   builder_->FinishCurrentBlock(builder_->New<HCompareNumericAndBranch>(
1094           phi_, terminating, token, body_block_, exit_block_));
1095
1096   builder_->set_current_block(body_block_);
1097   if (direction_ == kPreIncrement || direction_ == kPreDecrement) {
1098     HValue* one = builder_->graph()->GetConstant1();
1099     if (direction_ == kPreIncrement) {
1100       increment_ = HAdd::New(zone(), context_, phi_, one);
1101     } else {
1102       increment_ = HSub::New(zone(), context_, phi_, one);
1103     }
1104     increment_->ClearFlag(HValue::kCanOverflow);
1105     builder_->AddInstruction(increment_);
1106     return increment_;
1107   } else {
1108     return phi_;
1109   }
1110 }
1111
1112
1113 void HGraphBuilder::LoopBuilder::BeginBody(int drop_count) {
1114   DCHECK(direction_ == kWhileTrue);
1115   HEnvironment* env = builder_->environment();
1116   builder_->GotoNoSimulate(header_block_);
1117   builder_->set_current_block(header_block_);
1118   env->Drop(drop_count);
1119 }
1120
1121
1122 void HGraphBuilder::LoopBuilder::Break() {
1123   if (exit_trampoline_block_ == NULL) {
1124     // Its the first time we saw a break.
1125     if (direction_ == kWhileTrue) {
1126       HEnvironment* env = builder_->environment()->Copy();
1127       exit_trampoline_block_ = builder_->CreateBasicBlock(env);
1128     } else {
1129       HEnvironment* env = exit_block_->last_environment()->Copy();
1130       exit_trampoline_block_ = builder_->CreateBasicBlock(env);
1131       builder_->GotoNoSimulate(exit_block_, exit_trampoline_block_);
1132     }
1133   }
1134
1135   builder_->GotoNoSimulate(exit_trampoline_block_);
1136   builder_->set_current_block(NULL);
1137 }
1138
1139
1140 void HGraphBuilder::LoopBuilder::EndBody() {
1141   DCHECK(!finished_);
1142
1143   if (direction_ == kPostIncrement || direction_ == kPostDecrement) {
1144     if (direction_ == kPostIncrement) {
1145       increment_ = HAdd::New(zone(), context_, phi_, increment_amount_);
1146     } else {
1147       increment_ = HSub::New(zone(), context_, phi_, increment_amount_);
1148     }
1149     increment_->ClearFlag(HValue::kCanOverflow);
1150     builder_->AddInstruction(increment_);
1151   }
1152
1153   if (direction_ != kWhileTrue) {
1154     // Push the new increment value on the expression stack to merge into
1155     // the phi.
1156     builder_->environment()->Push(increment_);
1157   }
1158   HBasicBlock* last_block = builder_->current_block();
1159   builder_->GotoNoSimulate(last_block, header_block_);
1160   header_block_->loop_information()->RegisterBackEdge(last_block);
1161
1162   if (exit_trampoline_block_ != NULL) {
1163     builder_->set_current_block(exit_trampoline_block_);
1164   } else {
1165     builder_->set_current_block(exit_block_);
1166   }
1167   finished_ = true;
1168 }
1169
1170
1171 HGraph* HGraphBuilder::CreateGraph() {
1172   graph_ = new(zone()) HGraph(info_);
1173   if (FLAG_hydrogen_stats) isolate()->GetHStatistics()->Initialize(info_);
1174   CompilationPhase phase("H_Block building", info_);
1175   set_current_block(graph()->entry_block());
1176   if (!BuildGraph()) return NULL;
1177   graph()->FinalizeUniqueness();
1178   return graph_;
1179 }
1180
1181
1182 HInstruction* HGraphBuilder::AddInstruction(HInstruction* instr) {
1183   DCHECK(current_block() != NULL);
1184   DCHECK(!FLAG_hydrogen_track_positions ||
1185          !position_.IsUnknown() ||
1186          !info_->IsOptimizing());
1187   current_block()->AddInstruction(instr, source_position());
1188   if (graph()->IsInsideNoSideEffectsScope()) {
1189     instr->SetFlag(HValue::kHasNoObservableSideEffects);
1190   }
1191   return instr;
1192 }
1193
1194
1195 void HGraphBuilder::FinishCurrentBlock(HControlInstruction* last) {
1196   DCHECK(!FLAG_hydrogen_track_positions ||
1197          !info_->IsOptimizing() ||
1198          !position_.IsUnknown());
1199   current_block()->Finish(last, source_position());
1200   if (last->IsReturn() || last->IsAbnormalExit()) {
1201     set_current_block(NULL);
1202   }
1203 }
1204
1205
1206 void HGraphBuilder::FinishExitCurrentBlock(HControlInstruction* instruction) {
1207   DCHECK(!FLAG_hydrogen_track_positions || !info_->IsOptimizing() ||
1208          !position_.IsUnknown());
1209   current_block()->FinishExit(instruction, source_position());
1210   if (instruction->IsReturn() || instruction->IsAbnormalExit()) {
1211     set_current_block(NULL);
1212   }
1213 }
1214
1215
1216 void HGraphBuilder::AddIncrementCounter(StatsCounter* counter) {
1217   if (FLAG_native_code_counters && counter->Enabled()) {
1218     HValue* reference = Add<HConstant>(ExternalReference(counter));
1219     HValue* old_value = Add<HLoadNamedField>(
1220         reference, static_cast<HValue*>(NULL), HObjectAccess::ForCounter());
1221     HValue* new_value = AddUncasted<HAdd>(old_value, graph()->GetConstant1());
1222     new_value->ClearFlag(HValue::kCanOverflow);  // Ignore counter overflow
1223     Add<HStoreNamedField>(reference, HObjectAccess::ForCounter(),
1224                           new_value, STORE_TO_INITIALIZED_ENTRY);
1225   }
1226 }
1227
1228
1229 void HGraphBuilder::AddSimulate(BailoutId id,
1230                                 RemovableSimulate removable) {
1231   DCHECK(current_block() != NULL);
1232   DCHECK(!graph()->IsInsideNoSideEffectsScope());
1233   current_block()->AddNewSimulate(id, source_position(), removable);
1234 }
1235
1236
1237 HBasicBlock* HGraphBuilder::CreateBasicBlock(HEnvironment* env) {
1238   HBasicBlock* b = graph()->CreateBasicBlock();
1239   b->SetInitialEnvironment(env);
1240   return b;
1241 }
1242
1243
1244 HBasicBlock* HGraphBuilder::CreateLoopHeaderBlock() {
1245   HBasicBlock* header = graph()->CreateBasicBlock();
1246   HEnvironment* entry_env = environment()->CopyAsLoopHeader(header);
1247   header->SetInitialEnvironment(entry_env);
1248   header->AttachLoopInformation();
1249   return header;
1250 }
1251
1252
1253 HValue* HGraphBuilder::BuildGetElementsKind(HValue* object) {
1254   HValue* map = Add<HLoadNamedField>(object, static_cast<HValue*>(NULL),
1255                                      HObjectAccess::ForMap());
1256
1257   HValue* bit_field2 = Add<HLoadNamedField>(map, static_cast<HValue*>(NULL),
1258                                             HObjectAccess::ForMapBitField2());
1259   return BuildDecodeField<Map::ElementsKindBits>(bit_field2);
1260 }
1261
1262
1263 HValue* HGraphBuilder::BuildCheckHeapObject(HValue* obj) {
1264   if (obj->type().IsHeapObject()) return obj;
1265   return Add<HCheckHeapObject>(obj);
1266 }
1267
1268
1269 void HGraphBuilder::FinishExitWithHardDeoptimization(const char* reason) {
1270   Add<HDeoptimize>(reason, Deoptimizer::EAGER);
1271   FinishExitCurrentBlock(New<HAbnormalExit>());
1272 }
1273
1274
1275 HValue* HGraphBuilder::BuildCheckString(HValue* string) {
1276   if (!string->type().IsString()) {
1277     DCHECK(!string->IsConstant() ||
1278            !HConstant::cast(string)->HasStringValue());
1279     BuildCheckHeapObject(string);
1280     return Add<HCheckInstanceType>(string, HCheckInstanceType::IS_STRING);
1281   }
1282   return string;
1283 }
1284
1285
1286 HValue* HGraphBuilder::BuildWrapReceiver(HValue* object, HValue* function) {
1287   if (object->type().IsJSObject()) return object;
1288   if (function->IsConstant() &&
1289       HConstant::cast(function)->handle(isolate())->IsJSFunction()) {
1290     Handle<JSFunction> f = Handle<JSFunction>::cast(
1291         HConstant::cast(function)->handle(isolate()));
1292     SharedFunctionInfo* shared = f->shared();
1293     if (shared->strict_mode() == STRICT || shared->native()) return object;
1294   }
1295   return Add<HWrapReceiver>(object, function);
1296 }
1297
1298
1299 HValue* HGraphBuilder::BuildCheckForCapacityGrow(
1300     HValue* object,
1301     HValue* elements,
1302     ElementsKind kind,
1303     HValue* length,
1304     HValue* key,
1305     bool is_js_array,
1306     PropertyAccessType access_type) {
1307   IfBuilder length_checker(this);
1308
1309   Token::Value token = IsHoleyElementsKind(kind) ? Token::GTE : Token::EQ;
1310   length_checker.If<HCompareNumericAndBranch>(key, length, token);
1311
1312   length_checker.Then();
1313
1314   HValue* current_capacity = AddLoadFixedArrayLength(elements);
1315
1316   IfBuilder capacity_checker(this);
1317
1318   capacity_checker.If<HCompareNumericAndBranch>(key, current_capacity,
1319                                                 Token::GTE);
1320   capacity_checker.Then();
1321
1322   HValue* max_gap = Add<HConstant>(static_cast<int32_t>(JSObject::kMaxGap));
1323   HValue* max_capacity = AddUncasted<HAdd>(current_capacity, max_gap);
1324
1325   Add<HBoundsCheck>(key, max_capacity);
1326
1327   HValue* new_capacity = BuildNewElementsCapacity(key);
1328   HValue* new_elements = BuildGrowElementsCapacity(object, elements,
1329                                                    kind, kind, length,
1330                                                    new_capacity);
1331
1332   environment()->Push(new_elements);
1333   capacity_checker.Else();
1334
1335   environment()->Push(elements);
1336   capacity_checker.End();
1337
1338   if (is_js_array) {
1339     HValue* new_length = AddUncasted<HAdd>(key, graph_->GetConstant1());
1340     new_length->ClearFlag(HValue::kCanOverflow);
1341
1342     Add<HStoreNamedField>(object, HObjectAccess::ForArrayLength(kind),
1343                           new_length);
1344   }
1345
1346   if (access_type == STORE && kind == FAST_SMI_ELEMENTS) {
1347     HValue* checked_elements = environment()->Top();
1348
1349     // Write zero to ensure that the new element is initialized with some smi.
1350     Add<HStoreKeyed>(checked_elements, key, graph()->GetConstant0(), kind);
1351   }
1352
1353   length_checker.Else();
1354   Add<HBoundsCheck>(key, length);
1355
1356   environment()->Push(elements);
1357   length_checker.End();
1358
1359   return environment()->Pop();
1360 }
1361
1362
1363 HValue* HGraphBuilder::BuildCopyElementsOnWrite(HValue* object,
1364                                                 HValue* elements,
1365                                                 ElementsKind kind,
1366                                                 HValue* length) {
1367   Factory* factory = isolate()->factory();
1368
1369   IfBuilder cow_checker(this);
1370
1371   cow_checker.If<HCompareMap>(elements, factory->fixed_cow_array_map());
1372   cow_checker.Then();
1373
1374   HValue* capacity = AddLoadFixedArrayLength(elements);
1375
1376   HValue* new_elements = BuildGrowElementsCapacity(object, elements, kind,
1377                                                    kind, length, capacity);
1378
1379   environment()->Push(new_elements);
1380
1381   cow_checker.Else();
1382
1383   environment()->Push(elements);
1384
1385   cow_checker.End();
1386
1387   return environment()->Pop();
1388 }
1389
1390
1391 void HGraphBuilder::BuildTransitionElementsKind(HValue* object,
1392                                                 HValue* map,
1393                                                 ElementsKind from_kind,
1394                                                 ElementsKind to_kind,
1395                                                 bool is_jsarray) {
1396   DCHECK(!IsFastHoleyElementsKind(from_kind) ||
1397          IsFastHoleyElementsKind(to_kind));
1398
1399   if (AllocationSite::GetMode(from_kind, to_kind) == TRACK_ALLOCATION_SITE) {
1400     Add<HTrapAllocationMemento>(object);
1401   }
1402
1403   if (!IsSimpleMapChangeTransition(from_kind, to_kind)) {
1404     HInstruction* elements = AddLoadElements(object);
1405
1406     HInstruction* empty_fixed_array = Add<HConstant>(
1407         isolate()->factory()->empty_fixed_array());
1408
1409     IfBuilder if_builder(this);
1410
1411     if_builder.IfNot<HCompareObjectEqAndBranch>(elements, empty_fixed_array);
1412
1413     if_builder.Then();
1414
1415     HInstruction* elements_length = AddLoadFixedArrayLength(elements);
1416
1417     HInstruction* array_length = is_jsarray
1418         ? Add<HLoadNamedField>(object, static_cast<HValue*>(NULL),
1419                                HObjectAccess::ForArrayLength(from_kind))
1420         : elements_length;
1421
1422     BuildGrowElementsCapacity(object, elements, from_kind, to_kind,
1423                               array_length, elements_length);
1424
1425     if_builder.End();
1426   }
1427
1428   Add<HStoreNamedField>(object, HObjectAccess::ForMap(), map);
1429 }
1430
1431
1432 void HGraphBuilder::BuildJSObjectCheck(HValue* receiver,
1433                                        int bit_field_mask) {
1434   // Check that the object isn't a smi.
1435   Add<HCheckHeapObject>(receiver);
1436
1437   // Get the map of the receiver.
1438   HValue* map = Add<HLoadNamedField>(receiver, static_cast<HValue*>(NULL),
1439                                      HObjectAccess::ForMap());
1440
1441   // Check the instance type and if an access check is needed, this can be
1442   // done with a single load, since both bytes are adjacent in the map.
1443   HObjectAccess access(HObjectAccess::ForMapInstanceTypeAndBitField());
1444   HValue* instance_type_and_bit_field =
1445       Add<HLoadNamedField>(map, static_cast<HValue*>(NULL), access);
1446
1447   HValue* mask = Add<HConstant>(0x00FF | (bit_field_mask << 8));
1448   HValue* and_result = AddUncasted<HBitwise>(Token::BIT_AND,
1449                                              instance_type_and_bit_field,
1450                                              mask);
1451   HValue* sub_result = AddUncasted<HSub>(and_result,
1452                                          Add<HConstant>(JS_OBJECT_TYPE));
1453   Add<HBoundsCheck>(sub_result,
1454                     Add<HConstant>(LAST_JS_OBJECT_TYPE + 1 - JS_OBJECT_TYPE));
1455 }
1456
1457
1458 void HGraphBuilder::BuildKeyedIndexCheck(HValue* key,
1459                                          HIfContinuation* join_continuation) {
1460   // The sometimes unintuitively backward ordering of the ifs below is
1461   // convoluted, but necessary.  All of the paths must guarantee that the
1462   // if-true of the continuation returns a smi element index and the if-false of
1463   // the continuation returns either a symbol or a unique string key. All other
1464   // object types cause a deopt to fall back to the runtime.
1465
1466   IfBuilder key_smi_if(this);
1467   key_smi_if.If<HIsSmiAndBranch>(key);
1468   key_smi_if.Then();
1469   {
1470     Push(key);  // Nothing to do, just continue to true of continuation.
1471   }
1472   key_smi_if.Else();
1473   {
1474     HValue* map = Add<HLoadNamedField>(key, static_cast<HValue*>(NULL),
1475                                        HObjectAccess::ForMap());
1476     HValue* instance_type =
1477         Add<HLoadNamedField>(map, static_cast<HValue*>(NULL),
1478                              HObjectAccess::ForMapInstanceType());
1479
1480     // Non-unique string, check for a string with a hash code that is actually
1481     // an index.
1482     STATIC_ASSERT(LAST_UNIQUE_NAME_TYPE == FIRST_NONSTRING_TYPE);
1483     IfBuilder not_string_or_name_if(this);
1484     not_string_or_name_if.If<HCompareNumericAndBranch>(
1485         instance_type,
1486         Add<HConstant>(LAST_UNIQUE_NAME_TYPE),
1487         Token::GT);
1488
1489     not_string_or_name_if.Then();
1490     {
1491       // Non-smi, non-Name, non-String: Try to convert to smi in case of
1492       // HeapNumber.
1493       // TODO(danno): This could call some variant of ToString
1494       Push(AddUncasted<HForceRepresentation>(key, Representation::Smi()));
1495     }
1496     not_string_or_name_if.Else();
1497     {
1498       // String or Name: check explicitly for Name, they can short-circuit
1499       // directly to unique non-index key path.
1500       IfBuilder not_symbol_if(this);
1501       not_symbol_if.If<HCompareNumericAndBranch>(
1502           instance_type,
1503           Add<HConstant>(SYMBOL_TYPE),
1504           Token::NE);
1505
1506       not_symbol_if.Then();
1507       {
1508         // String: check whether the String is a String of an index. If it is,
1509         // extract the index value from the hash.
1510         HValue* hash =
1511             Add<HLoadNamedField>(key, static_cast<HValue*>(NULL),
1512                                  HObjectAccess::ForNameHashField());
1513         HValue* not_index_mask = Add<HConstant>(static_cast<int>(
1514             String::kContainsCachedArrayIndexMask));
1515
1516         HValue* not_index_test = AddUncasted<HBitwise>(
1517             Token::BIT_AND, hash, not_index_mask);
1518
1519         IfBuilder string_index_if(this);
1520         string_index_if.If<HCompareNumericAndBranch>(not_index_test,
1521                                                      graph()->GetConstant0(),
1522                                                      Token::EQ);
1523         string_index_if.Then();
1524         {
1525           // String with index in hash: extract string and merge to index path.
1526           Push(BuildDecodeField<String::ArrayIndexValueBits>(hash));
1527         }
1528         string_index_if.Else();
1529         {
1530           // Key is a non-index String, check for uniqueness/internalization.
1531           // If it's not internalized yet, internalize it now.
1532           HValue* not_internalized_bit = AddUncasted<HBitwise>(
1533               Token::BIT_AND,
1534               instance_type,
1535               Add<HConstant>(static_cast<int>(kIsNotInternalizedMask)));
1536
1537           IfBuilder internalized(this);
1538           internalized.If<HCompareNumericAndBranch>(not_internalized_bit,
1539                                                     graph()->GetConstant0(),
1540                                                     Token::EQ);
1541           internalized.Then();
1542           Push(key);
1543
1544           internalized.Else();
1545           Add<HPushArguments>(key);
1546           HValue* intern_key = Add<HCallRuntime>(
1547               isolate()->factory()->empty_string(),
1548               Runtime::FunctionForId(Runtime::kInternalizeString), 1);
1549           Push(intern_key);
1550
1551           internalized.End();
1552           // Key guaranteed to be a unique string
1553         }
1554         string_index_if.JoinContinuation(join_continuation);
1555       }
1556       not_symbol_if.Else();
1557       {
1558         Push(key);  // Key is symbol
1559       }
1560       not_symbol_if.JoinContinuation(join_continuation);
1561     }
1562     not_string_or_name_if.JoinContinuation(join_continuation);
1563   }
1564   key_smi_if.JoinContinuation(join_continuation);
1565 }
1566
1567
1568 void HGraphBuilder::BuildNonGlobalObjectCheck(HValue* receiver) {
1569   // Get the the instance type of the receiver, and make sure that it is
1570   // not one of the global object types.
1571   HValue* map = Add<HLoadNamedField>(receiver, static_cast<HValue*>(NULL),
1572                                      HObjectAccess::ForMap());
1573   HValue* instance_type =
1574     Add<HLoadNamedField>(map, static_cast<HValue*>(NULL),
1575                          HObjectAccess::ForMapInstanceType());
1576   STATIC_ASSERT(JS_BUILTINS_OBJECT_TYPE == JS_GLOBAL_OBJECT_TYPE + 1);
1577   HValue* min_global_type = Add<HConstant>(JS_GLOBAL_OBJECT_TYPE);
1578   HValue* max_global_type = Add<HConstant>(JS_BUILTINS_OBJECT_TYPE);
1579
1580   IfBuilder if_global_object(this);
1581   if_global_object.If<HCompareNumericAndBranch>(instance_type,
1582                                                 max_global_type,
1583                                                 Token::LTE);
1584   if_global_object.And();
1585   if_global_object.If<HCompareNumericAndBranch>(instance_type,
1586                                                 min_global_type,
1587                                                 Token::GTE);
1588   if_global_object.ThenDeopt("receiver was a global object");
1589   if_global_object.End();
1590 }
1591
1592
1593 void HGraphBuilder::BuildTestForDictionaryProperties(
1594     HValue* object,
1595     HIfContinuation* continuation) {
1596   HValue* properties = Add<HLoadNamedField>(
1597       object, static_cast<HValue*>(NULL),
1598       HObjectAccess::ForPropertiesPointer());
1599   HValue* properties_map =
1600       Add<HLoadNamedField>(properties, static_cast<HValue*>(NULL),
1601                            HObjectAccess::ForMap());
1602   HValue* hash_map = Add<HLoadRoot>(Heap::kHashTableMapRootIndex);
1603   IfBuilder builder(this);
1604   builder.If<HCompareObjectEqAndBranch>(properties_map, hash_map);
1605   builder.CaptureContinuation(continuation);
1606 }
1607
1608
1609 HValue* HGraphBuilder::BuildKeyedLookupCacheHash(HValue* object,
1610                                                  HValue* key) {
1611   // Load the map of the receiver, compute the keyed lookup cache hash
1612   // based on 32 bits of the map pointer and the string hash.
1613   HValue* object_map =
1614       Add<HLoadNamedField>(object, static_cast<HValue*>(NULL),
1615                            HObjectAccess::ForMapAsInteger32());
1616   HValue* shifted_map = AddUncasted<HShr>(
1617       object_map, Add<HConstant>(KeyedLookupCache::kMapHashShift));
1618   HValue* string_hash =
1619       Add<HLoadNamedField>(key, static_cast<HValue*>(NULL),
1620                            HObjectAccess::ForStringHashField());
1621   HValue* shifted_hash = AddUncasted<HShr>(
1622       string_hash, Add<HConstant>(String::kHashShift));
1623   HValue* xor_result = AddUncasted<HBitwise>(Token::BIT_XOR, shifted_map,
1624                                              shifted_hash);
1625   int mask = (KeyedLookupCache::kCapacityMask & KeyedLookupCache::kHashMask);
1626   return AddUncasted<HBitwise>(Token::BIT_AND, xor_result,
1627                                Add<HConstant>(mask));
1628 }
1629
1630
1631 HValue* HGraphBuilder::BuildElementIndexHash(HValue* index) {
1632   int32_t seed_value = static_cast<uint32_t>(isolate()->heap()->HashSeed());
1633   HValue* seed = Add<HConstant>(seed_value);
1634   HValue* hash = AddUncasted<HBitwise>(Token::BIT_XOR, index, seed);
1635
1636   // hash = ~hash + (hash << 15);
1637   HValue* shifted_hash = AddUncasted<HShl>(hash, Add<HConstant>(15));
1638   HValue* not_hash = AddUncasted<HBitwise>(Token::BIT_XOR, hash,
1639                                            graph()->GetConstantMinus1());
1640   hash = AddUncasted<HAdd>(shifted_hash, not_hash);
1641
1642   // hash = hash ^ (hash >> 12);
1643   shifted_hash = AddUncasted<HShr>(hash, Add<HConstant>(12));
1644   hash = AddUncasted<HBitwise>(Token::BIT_XOR, hash, shifted_hash);
1645
1646   // hash = hash + (hash << 2);
1647   shifted_hash = AddUncasted<HShl>(hash, Add<HConstant>(2));
1648   hash = AddUncasted<HAdd>(hash, shifted_hash);
1649
1650   // hash = hash ^ (hash >> 4);
1651   shifted_hash = AddUncasted<HShr>(hash, Add<HConstant>(4));
1652   hash = AddUncasted<HBitwise>(Token::BIT_XOR, hash, shifted_hash);
1653
1654   // hash = hash * 2057;
1655   hash = AddUncasted<HMul>(hash, Add<HConstant>(2057));
1656   hash->ClearFlag(HValue::kCanOverflow);
1657
1658   // hash = hash ^ (hash >> 16);
1659   shifted_hash = AddUncasted<HShr>(hash, Add<HConstant>(16));
1660   return AddUncasted<HBitwise>(Token::BIT_XOR, hash, shifted_hash);
1661 }
1662
1663
1664 HValue* HGraphBuilder::BuildUncheckedDictionaryElementLoad(HValue* receiver,
1665                                                            HValue* elements,
1666                                                            HValue* key,
1667                                                            HValue* hash) {
1668   HValue* capacity = Add<HLoadKeyed>(
1669       elements,
1670       Add<HConstant>(NameDictionary::kCapacityIndex),
1671       static_cast<HValue*>(NULL),
1672       FAST_ELEMENTS);
1673
1674   HValue* mask = AddUncasted<HSub>(capacity, graph()->GetConstant1());
1675   mask->ChangeRepresentation(Representation::Integer32());
1676   mask->ClearFlag(HValue::kCanOverflow);
1677
1678   HValue* entry = hash;
1679   HValue* count = graph()->GetConstant1();
1680   Push(entry);
1681   Push(count);
1682
1683   HIfContinuation return_or_loop_continuation(graph()->CreateBasicBlock(),
1684                                               graph()->CreateBasicBlock());
1685   HIfContinuation found_key_match_continuation(graph()->CreateBasicBlock(),
1686                                                graph()->CreateBasicBlock());
1687   LoopBuilder probe_loop(this);
1688   probe_loop.BeginBody(2);  // Drop entry, count from last environment to
1689                             // appease live range building without simulates.
1690
1691   count = Pop();
1692   entry = Pop();
1693   entry = AddUncasted<HBitwise>(Token::BIT_AND, entry, mask);
1694   int entry_size = SeededNumberDictionary::kEntrySize;
1695   HValue* base_index = AddUncasted<HMul>(entry, Add<HConstant>(entry_size));
1696   base_index->ClearFlag(HValue::kCanOverflow);
1697   int start_offset = SeededNumberDictionary::kElementsStartIndex;
1698   HValue* key_index =
1699       AddUncasted<HAdd>(base_index, Add<HConstant>(start_offset));
1700   key_index->ClearFlag(HValue::kCanOverflow);
1701
1702   HValue* candidate_key = Add<HLoadKeyed>(
1703       elements, key_index, static_cast<HValue*>(NULL), FAST_ELEMENTS);
1704   IfBuilder if_undefined(this);
1705   if_undefined.If<HCompareObjectEqAndBranch>(candidate_key,
1706                                              graph()->GetConstantUndefined());
1707   if_undefined.Then();
1708   {
1709     // element == undefined means "not found". Call the runtime.
1710     // TODO(jkummerow): walk the prototype chain instead.
1711     Add<HPushArguments>(receiver, key);
1712     Push(Add<HCallRuntime>(isolate()->factory()->empty_string(),
1713                            Runtime::FunctionForId(Runtime::kKeyedGetProperty),
1714                            2));
1715   }
1716   if_undefined.Else();
1717   {
1718     IfBuilder if_match(this);
1719     if_match.If<HCompareObjectEqAndBranch>(candidate_key, key);
1720     if_match.Then();
1721     if_match.Else();
1722
1723     // Update non-internalized string in the dictionary with internalized key?
1724     IfBuilder if_update_with_internalized(this);
1725     HValue* smi_check =
1726         if_update_with_internalized.IfNot<HIsSmiAndBranch>(candidate_key);
1727     if_update_with_internalized.And();
1728     HValue* map = AddLoadMap(candidate_key, smi_check);
1729     HValue* instance_type = Add<HLoadNamedField>(
1730         map, static_cast<HValue*>(NULL), HObjectAccess::ForMapInstanceType());
1731     HValue* not_internalized_bit = AddUncasted<HBitwise>(
1732         Token::BIT_AND, instance_type,
1733         Add<HConstant>(static_cast<int>(kIsNotInternalizedMask)));
1734     if_update_with_internalized.If<HCompareNumericAndBranch>(
1735         not_internalized_bit, graph()->GetConstant0(), Token::NE);
1736     if_update_with_internalized.And();
1737     if_update_with_internalized.IfNot<HCompareObjectEqAndBranch>(
1738         candidate_key, graph()->GetConstantHole());
1739     if_update_with_internalized.AndIf<HStringCompareAndBranch>(candidate_key,
1740                                                                key, Token::EQ);
1741     if_update_with_internalized.Then();
1742     // Replace a key that is a non-internalized string by the equivalent
1743     // internalized string for faster further lookups.
1744     Add<HStoreKeyed>(elements, key_index, key, FAST_ELEMENTS);
1745     if_update_with_internalized.Else();
1746
1747     if_update_with_internalized.JoinContinuation(&found_key_match_continuation);
1748     if_match.JoinContinuation(&found_key_match_continuation);
1749
1750     IfBuilder found_key_match(this, &found_key_match_continuation);
1751     found_key_match.Then();
1752     // Key at current probe matches. Relevant bits in the |details| field must
1753     // be zero, otherwise the dictionary element requires special handling.
1754     HValue* details_index =
1755         AddUncasted<HAdd>(base_index, Add<HConstant>(start_offset + 2));
1756     details_index->ClearFlag(HValue::kCanOverflow);
1757     HValue* details = Add<HLoadKeyed>(
1758         elements, details_index, static_cast<HValue*>(NULL), FAST_ELEMENTS);
1759     int details_mask = PropertyDetails::TypeField::kMask |
1760                        PropertyDetails::DeletedField::kMask;
1761     details = AddUncasted<HBitwise>(Token::BIT_AND, details,
1762                                     Add<HConstant>(details_mask));
1763     IfBuilder details_compare(this);
1764     details_compare.If<HCompareNumericAndBranch>(
1765         details, graph()->GetConstant0(), Token::EQ);
1766     details_compare.Then();
1767     HValue* result_index =
1768         AddUncasted<HAdd>(base_index, Add<HConstant>(start_offset + 1));
1769     result_index->ClearFlag(HValue::kCanOverflow);
1770     Push(Add<HLoadKeyed>(elements, result_index, static_cast<HValue*>(NULL),
1771                          FAST_ELEMENTS));
1772     details_compare.Else();
1773     Add<HPushArguments>(receiver, key);
1774     Push(Add<HCallRuntime>(isolate()->factory()->empty_string(),
1775                            Runtime::FunctionForId(Runtime::kKeyedGetProperty),
1776                            2));
1777     details_compare.End();
1778
1779     found_key_match.Else();
1780     found_key_match.JoinContinuation(&return_or_loop_continuation);
1781   }
1782   if_undefined.JoinContinuation(&return_or_loop_continuation);
1783
1784   IfBuilder return_or_loop(this, &return_or_loop_continuation);
1785   return_or_loop.Then();
1786   probe_loop.Break();
1787
1788   return_or_loop.Else();
1789   entry = AddUncasted<HAdd>(entry, count);
1790   entry->ClearFlag(HValue::kCanOverflow);
1791   count = AddUncasted<HAdd>(count, graph()->GetConstant1());
1792   count->ClearFlag(HValue::kCanOverflow);
1793   Push(entry);
1794   Push(count);
1795
1796   probe_loop.EndBody();
1797
1798   return_or_loop.End();
1799
1800   return Pop();
1801 }
1802
1803
1804 HValue* HGraphBuilder::BuildRegExpConstructResult(HValue* length,
1805                                                   HValue* index,
1806                                                   HValue* input) {
1807   NoObservableSideEffectsScope scope(this);
1808   HConstant* max_length = Add<HConstant>(JSObject::kInitialMaxFastElementArray);
1809   Add<HBoundsCheck>(length, max_length);
1810
1811   // Generate size calculation code here in order to make it dominate
1812   // the JSRegExpResult allocation.
1813   ElementsKind elements_kind = FAST_ELEMENTS;
1814   HValue* size = BuildCalculateElementsSize(elements_kind, length);
1815
1816   // Allocate the JSRegExpResult and the FixedArray in one step.
1817   HValue* result = Add<HAllocate>(
1818       Add<HConstant>(JSRegExpResult::kSize), HType::JSArray(),
1819       NOT_TENURED, JS_ARRAY_TYPE);
1820
1821   // Initialize the JSRegExpResult header.
1822   HValue* global_object = Add<HLoadNamedField>(
1823       context(), static_cast<HValue*>(NULL),
1824       HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
1825   HValue* native_context = Add<HLoadNamedField>(
1826       global_object, static_cast<HValue*>(NULL),
1827       HObjectAccess::ForGlobalObjectNativeContext());
1828   Add<HStoreNamedField>(
1829       result, HObjectAccess::ForMap(),
1830       Add<HLoadNamedField>(
1831           native_context, static_cast<HValue*>(NULL),
1832           HObjectAccess::ForContextSlot(Context::REGEXP_RESULT_MAP_INDEX)));
1833   HConstant* empty_fixed_array =
1834       Add<HConstant>(isolate()->factory()->empty_fixed_array());
1835   Add<HStoreNamedField>(
1836       result, HObjectAccess::ForJSArrayOffset(JSArray::kPropertiesOffset),
1837       empty_fixed_array);
1838   Add<HStoreNamedField>(
1839       result, HObjectAccess::ForJSArrayOffset(JSArray::kElementsOffset),
1840       empty_fixed_array);
1841   Add<HStoreNamedField>(
1842       result, HObjectAccess::ForJSArrayOffset(JSArray::kLengthOffset), length);
1843
1844   // Initialize the additional fields.
1845   Add<HStoreNamedField>(
1846       result, HObjectAccess::ForJSArrayOffset(JSRegExpResult::kIndexOffset),
1847       index);
1848   Add<HStoreNamedField>(
1849       result, HObjectAccess::ForJSArrayOffset(JSRegExpResult::kInputOffset),
1850       input);
1851
1852   // Allocate and initialize the elements header.
1853   HAllocate* elements = BuildAllocateElements(elements_kind, size);
1854   BuildInitializeElementsHeader(elements, elements_kind, length);
1855
1856   HConstant* size_in_bytes_upper_bound = EstablishElementsAllocationSize(
1857       elements_kind, max_length->Integer32Value());
1858   elements->set_size_upper_bound(size_in_bytes_upper_bound);
1859
1860   Add<HStoreNamedField>(
1861       result, HObjectAccess::ForJSArrayOffset(JSArray::kElementsOffset),
1862       elements);
1863
1864   // Initialize the elements contents with undefined.
1865   BuildFillElementsWithValue(
1866       elements, elements_kind, graph()->GetConstant0(), length,
1867       graph()->GetConstantUndefined());
1868
1869   return result;
1870 }
1871
1872
1873 HValue* HGraphBuilder::BuildNumberToString(HValue* object, Type* type) {
1874   NoObservableSideEffectsScope scope(this);
1875
1876   // Convert constant numbers at compile time.
1877   if (object->IsConstant() && HConstant::cast(object)->HasNumberValue()) {
1878     Handle<Object> number = HConstant::cast(object)->handle(isolate());
1879     Handle<String> result = isolate()->factory()->NumberToString(number);
1880     return Add<HConstant>(result);
1881   }
1882
1883   // Create a joinable continuation.
1884   HIfContinuation found(graph()->CreateBasicBlock(),
1885                         graph()->CreateBasicBlock());
1886
1887   // Load the number string cache.
1888   HValue* number_string_cache =
1889       Add<HLoadRoot>(Heap::kNumberStringCacheRootIndex);
1890
1891   // Make the hash mask from the length of the number string cache. It
1892   // contains two elements (number and string) for each cache entry.
1893   HValue* mask = AddLoadFixedArrayLength(number_string_cache);
1894   mask->set_type(HType::Smi());
1895   mask = AddUncasted<HSar>(mask, graph()->GetConstant1());
1896   mask = AddUncasted<HSub>(mask, graph()->GetConstant1());
1897
1898   // Check whether object is a smi.
1899   IfBuilder if_objectissmi(this);
1900   if_objectissmi.If<HIsSmiAndBranch>(object);
1901   if_objectissmi.Then();
1902   {
1903     // Compute hash for smi similar to smi_get_hash().
1904     HValue* hash = AddUncasted<HBitwise>(Token::BIT_AND, object, mask);
1905
1906     // Load the key.
1907     HValue* key_index = AddUncasted<HShl>(hash, graph()->GetConstant1());
1908     HValue* key = Add<HLoadKeyed>(number_string_cache, key_index,
1909                                   static_cast<HValue*>(NULL),
1910                                   FAST_ELEMENTS, ALLOW_RETURN_HOLE);
1911
1912     // Check if object == key.
1913     IfBuilder if_objectiskey(this);
1914     if_objectiskey.If<HCompareObjectEqAndBranch>(object, key);
1915     if_objectiskey.Then();
1916     {
1917       // Make the key_index available.
1918       Push(key_index);
1919     }
1920     if_objectiskey.JoinContinuation(&found);
1921   }
1922   if_objectissmi.Else();
1923   {
1924     if (type->Is(Type::SignedSmall())) {
1925       if_objectissmi.Deopt("Expected smi");
1926     } else {
1927       // Check if the object is a heap number.
1928       IfBuilder if_objectisnumber(this);
1929       HValue* objectisnumber = if_objectisnumber.If<HCompareMap>(
1930           object, isolate()->factory()->heap_number_map());
1931       if_objectisnumber.Then();
1932       {
1933         // Compute hash for heap number similar to double_get_hash().
1934         HValue* low = Add<HLoadNamedField>(
1935             object, objectisnumber,
1936             HObjectAccess::ForHeapNumberValueLowestBits());
1937         HValue* high = Add<HLoadNamedField>(
1938             object, objectisnumber,
1939             HObjectAccess::ForHeapNumberValueHighestBits());
1940         HValue* hash = AddUncasted<HBitwise>(Token::BIT_XOR, low, high);
1941         hash = AddUncasted<HBitwise>(Token::BIT_AND, hash, mask);
1942
1943         // Load the key.
1944         HValue* key_index = AddUncasted<HShl>(hash, graph()->GetConstant1());
1945         HValue* key = Add<HLoadKeyed>(number_string_cache, key_index,
1946                                       static_cast<HValue*>(NULL),
1947                                       FAST_ELEMENTS, ALLOW_RETURN_HOLE);
1948
1949         // Check if the key is a heap number and compare it with the object.
1950         IfBuilder if_keyisnotsmi(this);
1951         HValue* keyisnotsmi = if_keyisnotsmi.IfNot<HIsSmiAndBranch>(key);
1952         if_keyisnotsmi.Then();
1953         {
1954           IfBuilder if_keyisheapnumber(this);
1955           if_keyisheapnumber.If<HCompareMap>(
1956               key, isolate()->factory()->heap_number_map());
1957           if_keyisheapnumber.Then();
1958           {
1959             // Check if values of key and object match.
1960             IfBuilder if_keyeqobject(this);
1961             if_keyeqobject.If<HCompareNumericAndBranch>(
1962                 Add<HLoadNamedField>(key, keyisnotsmi,
1963                                      HObjectAccess::ForHeapNumberValue()),
1964                 Add<HLoadNamedField>(object, objectisnumber,
1965                                      HObjectAccess::ForHeapNumberValue()),
1966                 Token::EQ);
1967             if_keyeqobject.Then();
1968             {
1969               // Make the key_index available.
1970               Push(key_index);
1971             }
1972             if_keyeqobject.JoinContinuation(&found);
1973           }
1974           if_keyisheapnumber.JoinContinuation(&found);
1975         }
1976         if_keyisnotsmi.JoinContinuation(&found);
1977       }
1978       if_objectisnumber.Else();
1979       {
1980         if (type->Is(Type::Number())) {
1981           if_objectisnumber.Deopt("Expected heap number");
1982         }
1983       }
1984       if_objectisnumber.JoinContinuation(&found);
1985     }
1986   }
1987   if_objectissmi.JoinContinuation(&found);
1988
1989   // Check for cache hit.
1990   IfBuilder if_found(this, &found);
1991   if_found.Then();
1992   {
1993     // Count number to string operation in native code.
1994     AddIncrementCounter(isolate()->counters()->number_to_string_native());
1995
1996     // Load the value in case of cache hit.
1997     HValue* key_index = Pop();
1998     HValue* value_index = AddUncasted<HAdd>(key_index, graph()->GetConstant1());
1999     Push(Add<HLoadKeyed>(number_string_cache, value_index,
2000                          static_cast<HValue*>(NULL),
2001                          FAST_ELEMENTS, ALLOW_RETURN_HOLE));
2002   }
2003   if_found.Else();
2004   {
2005     // Cache miss, fallback to runtime.
2006     Add<HPushArguments>(object);
2007     Push(Add<HCallRuntime>(
2008             isolate()->factory()->empty_string(),
2009             Runtime::FunctionForId(Runtime::kNumberToStringSkipCache),
2010             1));
2011   }
2012   if_found.End();
2013
2014   return Pop();
2015 }
2016
2017
2018 HAllocate* HGraphBuilder::BuildAllocate(
2019     HValue* object_size,
2020     HType type,
2021     InstanceType instance_type,
2022     HAllocationMode allocation_mode) {
2023   // Compute the effective allocation size.
2024   HValue* size = object_size;
2025   if (allocation_mode.CreateAllocationMementos()) {
2026     size = AddUncasted<HAdd>(size, Add<HConstant>(AllocationMemento::kSize));
2027     size->ClearFlag(HValue::kCanOverflow);
2028   }
2029
2030   // Perform the actual allocation.
2031   HAllocate* object = Add<HAllocate>(
2032       size, type, allocation_mode.GetPretenureMode(),
2033       instance_type, allocation_mode.feedback_site());
2034
2035   // Setup the allocation memento.
2036   if (allocation_mode.CreateAllocationMementos()) {
2037     BuildCreateAllocationMemento(
2038         object, object_size, allocation_mode.current_site());
2039   }
2040
2041   return object;
2042 }
2043
2044
2045 HValue* HGraphBuilder::BuildAddStringLengths(HValue* left_length,
2046                                              HValue* right_length) {
2047   // Compute the combined string length and check against max string length.
2048   HValue* length = AddUncasted<HAdd>(left_length, right_length);
2049   // Check that length <= kMaxLength <=> length < MaxLength + 1.
2050   HValue* max_length = Add<HConstant>(String::kMaxLength + 1);
2051   Add<HBoundsCheck>(length, max_length);
2052   return length;
2053 }
2054
2055
2056 HValue* HGraphBuilder::BuildCreateConsString(
2057     HValue* length,
2058     HValue* left,
2059     HValue* right,
2060     HAllocationMode allocation_mode) {
2061   // Determine the string instance types.
2062   HInstruction* left_instance_type = AddLoadStringInstanceType(left);
2063   HInstruction* right_instance_type = AddLoadStringInstanceType(right);
2064
2065   // Allocate the cons string object. HAllocate does not care whether we
2066   // pass CONS_STRING_TYPE or CONS_ASCII_STRING_TYPE here, so we just use
2067   // CONS_STRING_TYPE here. Below we decide whether the cons string is
2068   // one-byte or two-byte and set the appropriate map.
2069   DCHECK(HAllocate::CompatibleInstanceTypes(CONS_STRING_TYPE,
2070                                             CONS_ASCII_STRING_TYPE));
2071   HAllocate* result = BuildAllocate(Add<HConstant>(ConsString::kSize),
2072                                     HType::String(), CONS_STRING_TYPE,
2073                                     allocation_mode);
2074
2075   // Compute intersection and difference of instance types.
2076   HValue* anded_instance_types = AddUncasted<HBitwise>(
2077       Token::BIT_AND, left_instance_type, right_instance_type);
2078   HValue* xored_instance_types = AddUncasted<HBitwise>(
2079       Token::BIT_XOR, left_instance_type, right_instance_type);
2080
2081   // We create a one-byte cons string if
2082   // 1. both strings are one-byte, or
2083   // 2. at least one of the strings is two-byte, but happens to contain only
2084   //    one-byte characters.
2085   // To do this, we check
2086   // 1. if both strings are one-byte, or if the one-byte data hint is set in
2087   //    both strings, or
2088   // 2. if one of the strings has the one-byte data hint set and the other
2089   //    string is one-byte.
2090   IfBuilder if_onebyte(this);
2091   STATIC_ASSERT(kOneByteStringTag != 0);
2092   STATIC_ASSERT(kOneByteDataHintMask != 0);
2093   if_onebyte.If<HCompareNumericAndBranch>(
2094       AddUncasted<HBitwise>(
2095           Token::BIT_AND, anded_instance_types,
2096           Add<HConstant>(static_cast<int32_t>(
2097                   kStringEncodingMask | kOneByteDataHintMask))),
2098       graph()->GetConstant0(), Token::NE);
2099   if_onebyte.Or();
2100   STATIC_ASSERT(kOneByteStringTag != 0 &&
2101                 kOneByteDataHintTag != 0 &&
2102                 kOneByteDataHintTag != kOneByteStringTag);
2103   if_onebyte.If<HCompareNumericAndBranch>(
2104       AddUncasted<HBitwise>(
2105           Token::BIT_AND, xored_instance_types,
2106           Add<HConstant>(static_cast<int32_t>(
2107                   kOneByteStringTag | kOneByteDataHintTag))),
2108       Add<HConstant>(static_cast<int32_t>(
2109               kOneByteStringTag | kOneByteDataHintTag)), Token::EQ);
2110   if_onebyte.Then();
2111   {
2112     // We can safely skip the write barrier for storing the map here.
2113     Add<HStoreNamedField>(
2114         result, HObjectAccess::ForMap(),
2115         Add<HConstant>(isolate()->factory()->cons_ascii_string_map()));
2116   }
2117   if_onebyte.Else();
2118   {
2119     // We can safely skip the write barrier for storing the map here.
2120     Add<HStoreNamedField>(
2121         result, HObjectAccess::ForMap(),
2122         Add<HConstant>(isolate()->factory()->cons_string_map()));
2123   }
2124   if_onebyte.End();
2125
2126   // Initialize the cons string fields.
2127   Add<HStoreNamedField>(result, HObjectAccess::ForStringHashField(),
2128                         Add<HConstant>(String::kEmptyHashField));
2129   Add<HStoreNamedField>(result, HObjectAccess::ForStringLength(), length);
2130   Add<HStoreNamedField>(result, HObjectAccess::ForConsStringFirst(), left);
2131   Add<HStoreNamedField>(result, HObjectAccess::ForConsStringSecond(), right);
2132
2133   // Count the native string addition.
2134   AddIncrementCounter(isolate()->counters()->string_add_native());
2135
2136   return result;
2137 }
2138
2139
2140 void HGraphBuilder::BuildCopySeqStringChars(HValue* src,
2141                                             HValue* src_offset,
2142                                             String::Encoding src_encoding,
2143                                             HValue* dst,
2144                                             HValue* dst_offset,
2145                                             String::Encoding dst_encoding,
2146                                             HValue* length) {
2147   DCHECK(dst_encoding != String::ONE_BYTE_ENCODING ||
2148          src_encoding == String::ONE_BYTE_ENCODING);
2149   LoopBuilder loop(this, context(), LoopBuilder::kPostIncrement);
2150   HValue* index = loop.BeginBody(graph()->GetConstant0(), length, Token::LT);
2151   {
2152     HValue* src_index = AddUncasted<HAdd>(src_offset, index);
2153     HValue* value =
2154         AddUncasted<HSeqStringGetChar>(src_encoding, src, src_index);
2155     HValue* dst_index = AddUncasted<HAdd>(dst_offset, index);
2156     Add<HSeqStringSetChar>(dst_encoding, dst, dst_index, value);
2157   }
2158   loop.EndBody();
2159 }
2160
2161
2162 HValue* HGraphBuilder::BuildObjectSizeAlignment(
2163     HValue* unaligned_size, int header_size) {
2164   DCHECK((header_size & kObjectAlignmentMask) == 0);
2165   HValue* size = AddUncasted<HAdd>(
2166       unaligned_size, Add<HConstant>(static_cast<int32_t>(
2167           header_size + kObjectAlignmentMask)));
2168   size->ClearFlag(HValue::kCanOverflow);
2169   return AddUncasted<HBitwise>(
2170       Token::BIT_AND, size, Add<HConstant>(static_cast<int32_t>(
2171           ~kObjectAlignmentMask)));
2172 }
2173
2174
2175 HValue* HGraphBuilder::BuildUncheckedStringAdd(
2176     HValue* left,
2177     HValue* right,
2178     HAllocationMode allocation_mode) {
2179   // Determine the string lengths.
2180   HValue* left_length = AddLoadStringLength(left);
2181   HValue* right_length = AddLoadStringLength(right);
2182
2183   // Compute the combined string length.
2184   HValue* length = BuildAddStringLengths(left_length, right_length);
2185
2186   // Do some manual constant folding here.
2187   if (left_length->IsConstant()) {
2188     HConstant* c_left_length = HConstant::cast(left_length);
2189     DCHECK_NE(0, c_left_length->Integer32Value());
2190     if (c_left_length->Integer32Value() + 1 >= ConsString::kMinLength) {
2191       // The right string contains at least one character.
2192       return BuildCreateConsString(length, left, right, allocation_mode);
2193     }
2194   } else if (right_length->IsConstant()) {
2195     HConstant* c_right_length = HConstant::cast(right_length);
2196     DCHECK_NE(0, c_right_length->Integer32Value());
2197     if (c_right_length->Integer32Value() + 1 >= ConsString::kMinLength) {
2198       // The left string contains at least one character.
2199       return BuildCreateConsString(length, left, right, allocation_mode);
2200     }
2201   }
2202
2203   // Check if we should create a cons string.
2204   IfBuilder if_createcons(this);
2205   if_createcons.If<HCompareNumericAndBranch>(
2206       length, Add<HConstant>(ConsString::kMinLength), Token::GTE);
2207   if_createcons.Then();
2208   {
2209     // Create a cons string.
2210     Push(BuildCreateConsString(length, left, right, allocation_mode));
2211   }
2212   if_createcons.Else();
2213   {
2214     // Determine the string instance types.
2215     HValue* left_instance_type = AddLoadStringInstanceType(left);
2216     HValue* right_instance_type = AddLoadStringInstanceType(right);
2217
2218     // Compute union and difference of instance types.
2219     HValue* ored_instance_types = AddUncasted<HBitwise>(
2220         Token::BIT_OR, left_instance_type, right_instance_type);
2221     HValue* xored_instance_types = AddUncasted<HBitwise>(
2222         Token::BIT_XOR, left_instance_type, right_instance_type);
2223
2224     // Check if both strings have the same encoding and both are
2225     // sequential.
2226     IfBuilder if_sameencodingandsequential(this);
2227     if_sameencodingandsequential.If<HCompareNumericAndBranch>(
2228         AddUncasted<HBitwise>(
2229             Token::BIT_AND, xored_instance_types,
2230             Add<HConstant>(static_cast<int32_t>(kStringEncodingMask))),
2231         graph()->GetConstant0(), Token::EQ);
2232     if_sameencodingandsequential.And();
2233     STATIC_ASSERT(kSeqStringTag == 0);
2234     if_sameencodingandsequential.If<HCompareNumericAndBranch>(
2235         AddUncasted<HBitwise>(
2236             Token::BIT_AND, ored_instance_types,
2237             Add<HConstant>(static_cast<int32_t>(kStringRepresentationMask))),
2238         graph()->GetConstant0(), Token::EQ);
2239     if_sameencodingandsequential.Then();
2240     {
2241       HConstant* string_map =
2242           Add<HConstant>(isolate()->factory()->string_map());
2243       HConstant* ascii_string_map =
2244           Add<HConstant>(isolate()->factory()->ascii_string_map());
2245
2246       // Determine map and size depending on whether result is one-byte string.
2247       IfBuilder if_onebyte(this);
2248       STATIC_ASSERT(kOneByteStringTag != 0);
2249       if_onebyte.If<HCompareNumericAndBranch>(
2250           AddUncasted<HBitwise>(
2251               Token::BIT_AND, ored_instance_types,
2252               Add<HConstant>(static_cast<int32_t>(kStringEncodingMask))),
2253           graph()->GetConstant0(), Token::NE);
2254       if_onebyte.Then();
2255       {
2256         // Allocate sequential one-byte string object.
2257         Push(length);
2258         Push(ascii_string_map);
2259       }
2260       if_onebyte.Else();
2261       {
2262         // Allocate sequential two-byte string object.
2263         HValue* size = AddUncasted<HShl>(length, graph()->GetConstant1());
2264         size->ClearFlag(HValue::kCanOverflow);
2265         size->SetFlag(HValue::kUint32);
2266         Push(size);
2267         Push(string_map);
2268       }
2269       if_onebyte.End();
2270       HValue* map = Pop();
2271
2272       // Calculate the number of bytes needed for the characters in the
2273       // string while observing object alignment.
2274       STATIC_ASSERT((SeqString::kHeaderSize & kObjectAlignmentMask) == 0);
2275       HValue* size = BuildObjectSizeAlignment(Pop(), SeqString::kHeaderSize);
2276
2277       // Allocate the string object. HAllocate does not care whether we pass
2278       // STRING_TYPE or ASCII_STRING_TYPE here, so we just use STRING_TYPE here.
2279       HAllocate* result = BuildAllocate(
2280           size, HType::String(), STRING_TYPE, allocation_mode);
2281       Add<HStoreNamedField>(result, HObjectAccess::ForMap(), map);
2282
2283       // Initialize the string fields.
2284       Add<HStoreNamedField>(result, HObjectAccess::ForStringHashField(),
2285                             Add<HConstant>(String::kEmptyHashField));
2286       Add<HStoreNamedField>(result, HObjectAccess::ForStringLength(), length);
2287
2288       // Copy characters to the result string.
2289       IfBuilder if_twobyte(this);
2290       if_twobyte.If<HCompareObjectEqAndBranch>(map, string_map);
2291       if_twobyte.Then();
2292       {
2293         // Copy characters from the left string.
2294         BuildCopySeqStringChars(
2295             left, graph()->GetConstant0(), String::TWO_BYTE_ENCODING,
2296             result, graph()->GetConstant0(), String::TWO_BYTE_ENCODING,
2297             left_length);
2298
2299         // Copy characters from the right string.
2300         BuildCopySeqStringChars(
2301             right, graph()->GetConstant0(), String::TWO_BYTE_ENCODING,
2302             result, left_length, String::TWO_BYTE_ENCODING,
2303             right_length);
2304       }
2305       if_twobyte.Else();
2306       {
2307         // Copy characters from the left string.
2308         BuildCopySeqStringChars(
2309             left, graph()->GetConstant0(), String::ONE_BYTE_ENCODING,
2310             result, graph()->GetConstant0(), String::ONE_BYTE_ENCODING,
2311             left_length);
2312
2313         // Copy characters from the right string.
2314         BuildCopySeqStringChars(
2315             right, graph()->GetConstant0(), String::ONE_BYTE_ENCODING,
2316             result, left_length, String::ONE_BYTE_ENCODING,
2317             right_length);
2318       }
2319       if_twobyte.End();
2320
2321       // Count the native string addition.
2322       AddIncrementCounter(isolate()->counters()->string_add_native());
2323
2324       // Return the sequential string.
2325       Push(result);
2326     }
2327     if_sameencodingandsequential.Else();
2328     {
2329       // Fallback to the runtime to add the two strings.
2330       Add<HPushArguments>(left, right);
2331       Push(Add<HCallRuntime>(
2332             isolate()->factory()->empty_string(),
2333             Runtime::FunctionForId(Runtime::kStringAdd),
2334             2));
2335     }
2336     if_sameencodingandsequential.End();
2337   }
2338   if_createcons.End();
2339
2340   return Pop();
2341 }
2342
2343
2344 HValue* HGraphBuilder::BuildStringAdd(
2345     HValue* left,
2346     HValue* right,
2347     HAllocationMode allocation_mode) {
2348   NoObservableSideEffectsScope no_effects(this);
2349
2350   // Determine string lengths.
2351   HValue* left_length = AddLoadStringLength(left);
2352   HValue* right_length = AddLoadStringLength(right);
2353
2354   // Check if left string is empty.
2355   IfBuilder if_leftempty(this);
2356   if_leftempty.If<HCompareNumericAndBranch>(
2357       left_length, graph()->GetConstant0(), Token::EQ);
2358   if_leftempty.Then();
2359   {
2360     // Count the native string addition.
2361     AddIncrementCounter(isolate()->counters()->string_add_native());
2362
2363     // Just return the right string.
2364     Push(right);
2365   }
2366   if_leftempty.Else();
2367   {
2368     // Check if right string is empty.
2369     IfBuilder if_rightempty(this);
2370     if_rightempty.If<HCompareNumericAndBranch>(
2371         right_length, graph()->GetConstant0(), Token::EQ);
2372     if_rightempty.Then();
2373     {
2374       // Count the native string addition.
2375       AddIncrementCounter(isolate()->counters()->string_add_native());
2376
2377       // Just return the left string.
2378       Push(left);
2379     }
2380     if_rightempty.Else();
2381     {
2382       // Add the two non-empty strings.
2383       Push(BuildUncheckedStringAdd(left, right, allocation_mode));
2384     }
2385     if_rightempty.End();
2386   }
2387   if_leftempty.End();
2388
2389   return Pop();
2390 }
2391
2392
2393 HInstruction* HGraphBuilder::BuildUncheckedMonomorphicElementAccess(
2394     HValue* checked_object,
2395     HValue* key,
2396     HValue* val,
2397     bool is_js_array,
2398     ElementsKind elements_kind,
2399     PropertyAccessType access_type,
2400     LoadKeyedHoleMode load_mode,
2401     KeyedAccessStoreMode store_mode) {
2402   DCHECK((!IsExternalArrayElementsKind(elements_kind) &&
2403               !IsFixedTypedArrayElementsKind(elements_kind)) ||
2404          !is_js_array);
2405   // No GVNFlag is necessary for ElementsKind if there is an explicit dependency
2406   // on a HElementsTransition instruction. The flag can also be removed if the
2407   // map to check has FAST_HOLEY_ELEMENTS, since there can be no further
2408   // ElementsKind transitions. Finally, the dependency can be removed for stores
2409   // for FAST_ELEMENTS, since a transition to HOLEY elements won't change the
2410   // generated store code.
2411   if ((elements_kind == FAST_HOLEY_ELEMENTS) ||
2412       (elements_kind == FAST_ELEMENTS && access_type == STORE)) {
2413     checked_object->ClearDependsOnFlag(kElementsKind);
2414   }
2415
2416   bool fast_smi_only_elements = IsFastSmiElementsKind(elements_kind);
2417   bool fast_elements = IsFastObjectElementsKind(elements_kind);
2418   HValue* elements = AddLoadElements(checked_object);
2419   if (access_type == STORE && (fast_elements || fast_smi_only_elements) &&
2420       store_mode != STORE_NO_TRANSITION_HANDLE_COW) {
2421     HCheckMaps* check_cow_map = Add<HCheckMaps>(
2422         elements, isolate()->factory()->fixed_array_map());
2423     check_cow_map->ClearDependsOnFlag(kElementsKind);
2424   }
2425   HInstruction* length = NULL;
2426   if (is_js_array) {
2427     length = Add<HLoadNamedField>(
2428         checked_object->ActualValue(), checked_object,
2429         HObjectAccess::ForArrayLength(elements_kind));
2430   } else {
2431     length = AddLoadFixedArrayLength(elements);
2432   }
2433   length->set_type(HType::Smi());
2434   HValue* checked_key = NULL;
2435   if (IsExternalArrayElementsKind(elements_kind) ||
2436       IsFixedTypedArrayElementsKind(elements_kind)) {
2437     HValue* backing_store;
2438     if (IsExternalArrayElementsKind(elements_kind)) {
2439       backing_store = Add<HLoadNamedField>(
2440           elements, static_cast<HValue*>(NULL),
2441           HObjectAccess::ForExternalArrayExternalPointer());
2442     } else {
2443       backing_store = elements;
2444     }
2445     if (store_mode == STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
2446       NoObservableSideEffectsScope no_effects(this);
2447       IfBuilder length_checker(this);
2448       length_checker.If<HCompareNumericAndBranch>(key, length, Token::LT);
2449       length_checker.Then();
2450       IfBuilder negative_checker(this);
2451       HValue* bounds_check = negative_checker.If<HCompareNumericAndBranch>(
2452           key, graph()->GetConstant0(), Token::GTE);
2453       negative_checker.Then();
2454       HInstruction* result = AddElementAccess(
2455           backing_store, key, val, bounds_check, elements_kind, access_type);
2456       negative_checker.ElseDeopt("Negative key encountered");
2457       negative_checker.End();
2458       length_checker.End();
2459       return result;
2460     } else {
2461       DCHECK(store_mode == STANDARD_STORE);
2462       checked_key = Add<HBoundsCheck>(key, length);
2463       return AddElementAccess(
2464           backing_store, checked_key, val,
2465           checked_object, elements_kind, access_type);
2466     }
2467   }
2468   DCHECK(fast_smi_only_elements ||
2469          fast_elements ||
2470          IsFastDoubleElementsKind(elements_kind));
2471
2472   // In case val is stored into a fast smi array, assure that the value is a smi
2473   // before manipulating the backing store. Otherwise the actual store may
2474   // deopt, leaving the backing store in an invalid state.
2475   if (access_type == STORE && IsFastSmiElementsKind(elements_kind) &&
2476       !val->type().IsSmi()) {
2477     val = AddUncasted<HForceRepresentation>(val, Representation::Smi());
2478   }
2479
2480   if (IsGrowStoreMode(store_mode)) {
2481     NoObservableSideEffectsScope no_effects(this);
2482     Representation representation = HStoreKeyed::RequiredValueRepresentation(
2483         elements_kind, STORE_TO_INITIALIZED_ENTRY);
2484     val = AddUncasted<HForceRepresentation>(val, representation);
2485     elements = BuildCheckForCapacityGrow(checked_object, elements,
2486                                          elements_kind, length, key,
2487                                          is_js_array, access_type);
2488     checked_key = key;
2489   } else {
2490     checked_key = Add<HBoundsCheck>(key, length);
2491
2492     if (access_type == STORE && (fast_elements || fast_smi_only_elements)) {
2493       if (store_mode == STORE_NO_TRANSITION_HANDLE_COW) {
2494         NoObservableSideEffectsScope no_effects(this);
2495         elements = BuildCopyElementsOnWrite(checked_object, elements,
2496                                             elements_kind, length);
2497       } else {
2498         HCheckMaps* check_cow_map = Add<HCheckMaps>(
2499             elements, isolate()->factory()->fixed_array_map());
2500         check_cow_map->ClearDependsOnFlag(kElementsKind);
2501       }
2502     }
2503   }
2504   return AddElementAccess(elements, checked_key, val, checked_object,
2505                           elements_kind, access_type, load_mode);
2506 }
2507
2508
2509 HValue* HGraphBuilder::BuildAllocateArrayFromLength(
2510     JSArrayBuilder* array_builder,
2511     HValue* length_argument) {
2512   if (length_argument->IsConstant() &&
2513       HConstant::cast(length_argument)->HasSmiValue()) {
2514     int array_length = HConstant::cast(length_argument)->Integer32Value();
2515     if (array_length == 0) {
2516       return array_builder->AllocateEmptyArray();
2517     } else {
2518       return array_builder->AllocateArray(length_argument,
2519                                           array_length,
2520                                           length_argument);
2521     }
2522   }
2523
2524   HValue* constant_zero = graph()->GetConstant0();
2525   HConstant* max_alloc_length =
2526       Add<HConstant>(JSObject::kInitialMaxFastElementArray);
2527   HInstruction* checked_length = Add<HBoundsCheck>(length_argument,
2528                                                    max_alloc_length);
2529   IfBuilder if_builder(this);
2530   if_builder.If<HCompareNumericAndBranch>(checked_length, constant_zero,
2531                                           Token::EQ);
2532   if_builder.Then();
2533   const int initial_capacity = JSArray::kPreallocatedArrayElements;
2534   HConstant* initial_capacity_node = Add<HConstant>(initial_capacity);
2535   Push(initial_capacity_node);  // capacity
2536   Push(constant_zero);          // length
2537   if_builder.Else();
2538   if (!(top_info()->IsStub()) &&
2539       IsFastPackedElementsKind(array_builder->kind())) {
2540     // We'll come back later with better (holey) feedback.
2541     if_builder.Deopt("Holey array despite packed elements_kind feedback");
2542   } else {
2543     Push(checked_length);         // capacity
2544     Push(checked_length);         // length
2545   }
2546   if_builder.End();
2547
2548   // Figure out total size
2549   HValue* length = Pop();
2550   HValue* capacity = Pop();
2551   return array_builder->AllocateArray(capacity, max_alloc_length, length);
2552 }
2553
2554
2555 HValue* HGraphBuilder::BuildCalculateElementsSize(ElementsKind kind,
2556                                                   HValue* capacity) {
2557   int elements_size = IsFastDoubleElementsKind(kind)
2558       ? kDoubleSize
2559       : kPointerSize;
2560
2561   HConstant* elements_size_value = Add<HConstant>(elements_size);
2562   HInstruction* mul = HMul::NewImul(zone(), context(),
2563                                     capacity->ActualValue(),
2564                                     elements_size_value);
2565   AddInstruction(mul);
2566   mul->ClearFlag(HValue::kCanOverflow);
2567
2568   STATIC_ASSERT(FixedDoubleArray::kHeaderSize == FixedArray::kHeaderSize);
2569
2570   HConstant* header_size = Add<HConstant>(FixedArray::kHeaderSize);
2571   HValue* total_size = AddUncasted<HAdd>(mul, header_size);
2572   total_size->ClearFlag(HValue::kCanOverflow);
2573   return total_size;
2574 }
2575
2576
2577 HAllocate* HGraphBuilder::AllocateJSArrayObject(AllocationSiteMode mode) {
2578   int base_size = JSArray::kSize;
2579   if (mode == TRACK_ALLOCATION_SITE) {
2580     base_size += AllocationMemento::kSize;
2581   }
2582   HConstant* size_in_bytes = Add<HConstant>(base_size);
2583   return Add<HAllocate>(
2584       size_in_bytes, HType::JSArray(), NOT_TENURED, JS_OBJECT_TYPE);
2585 }
2586
2587
2588 HConstant* HGraphBuilder::EstablishElementsAllocationSize(
2589     ElementsKind kind,
2590     int capacity) {
2591   int base_size = IsFastDoubleElementsKind(kind)
2592       ? FixedDoubleArray::SizeFor(capacity)
2593       : FixedArray::SizeFor(capacity);
2594
2595   return Add<HConstant>(base_size);
2596 }
2597
2598
2599 HAllocate* HGraphBuilder::BuildAllocateElements(ElementsKind kind,
2600                                                 HValue* size_in_bytes) {
2601   InstanceType instance_type = IsFastDoubleElementsKind(kind)
2602       ? FIXED_DOUBLE_ARRAY_TYPE
2603       : FIXED_ARRAY_TYPE;
2604
2605   return Add<HAllocate>(size_in_bytes, HType::HeapObject(), NOT_TENURED,
2606                         instance_type);
2607 }
2608
2609
2610 void HGraphBuilder::BuildInitializeElementsHeader(HValue* elements,
2611                                                   ElementsKind kind,
2612                                                   HValue* capacity) {
2613   Factory* factory = isolate()->factory();
2614   Handle<Map> map = IsFastDoubleElementsKind(kind)
2615       ? factory->fixed_double_array_map()
2616       : factory->fixed_array_map();
2617
2618   Add<HStoreNamedField>(elements, HObjectAccess::ForMap(), Add<HConstant>(map));
2619   Add<HStoreNamedField>(elements, HObjectAccess::ForFixedArrayLength(),
2620                         capacity);
2621 }
2622
2623
2624 HValue* HGraphBuilder::BuildAllocateElementsAndInitializeElementsHeader(
2625     ElementsKind kind,
2626     HValue* capacity) {
2627   // The HForceRepresentation is to prevent possible deopt on int-smi
2628   // conversion after allocation but before the new object fields are set.
2629   capacity = AddUncasted<HForceRepresentation>(capacity, Representation::Smi());
2630   HValue* size_in_bytes = BuildCalculateElementsSize(kind, capacity);
2631   HValue* new_elements = BuildAllocateElements(kind, size_in_bytes);
2632   BuildInitializeElementsHeader(new_elements, kind, capacity);
2633   return new_elements;
2634 }
2635
2636
2637 void HGraphBuilder::BuildJSArrayHeader(HValue* array,
2638                                        HValue* array_map,
2639                                        HValue* elements,
2640                                        AllocationSiteMode mode,
2641                                        ElementsKind elements_kind,
2642                                        HValue* allocation_site_payload,
2643                                        HValue* length_field) {
2644   Add<HStoreNamedField>(array, HObjectAccess::ForMap(), array_map);
2645
2646   HConstant* empty_fixed_array =
2647     Add<HConstant>(isolate()->factory()->empty_fixed_array());
2648
2649   Add<HStoreNamedField>(
2650       array, HObjectAccess::ForPropertiesPointer(), empty_fixed_array);
2651
2652   Add<HStoreNamedField>(
2653       array, HObjectAccess::ForElementsPointer(),
2654       elements != NULL ? elements : empty_fixed_array);
2655
2656   Add<HStoreNamedField>(
2657       array, HObjectAccess::ForArrayLength(elements_kind), length_field);
2658
2659   if (mode == TRACK_ALLOCATION_SITE) {
2660     BuildCreateAllocationMemento(
2661         array, Add<HConstant>(JSArray::kSize), allocation_site_payload);
2662   }
2663 }
2664
2665
2666 HInstruction* HGraphBuilder::AddElementAccess(
2667     HValue* elements,
2668     HValue* checked_key,
2669     HValue* val,
2670     HValue* dependency,
2671     ElementsKind elements_kind,
2672     PropertyAccessType access_type,
2673     LoadKeyedHoleMode load_mode) {
2674   if (access_type == STORE) {
2675     DCHECK(val != NULL);
2676     if (elements_kind == EXTERNAL_UINT8_CLAMPED_ELEMENTS ||
2677         elements_kind == UINT8_CLAMPED_ELEMENTS) {
2678       val = Add<HClampToUint8>(val);
2679     }
2680     return Add<HStoreKeyed>(elements, checked_key, val, elements_kind,
2681                             STORE_TO_INITIALIZED_ENTRY);
2682   }
2683
2684   DCHECK(access_type == LOAD);
2685   DCHECK(val == NULL);
2686   HLoadKeyed* load = Add<HLoadKeyed>(
2687       elements, checked_key, dependency, elements_kind, load_mode);
2688   if (FLAG_opt_safe_uint32_operations &&
2689       (elements_kind == EXTERNAL_UINT32_ELEMENTS ||
2690        elements_kind == UINT32_ELEMENTS)) {
2691     graph()->RecordUint32Instruction(load);
2692   }
2693   return load;
2694 }
2695
2696
2697 HLoadNamedField* HGraphBuilder::AddLoadMap(HValue* object,
2698                                            HValue* dependency) {
2699   return Add<HLoadNamedField>(object, dependency, HObjectAccess::ForMap());
2700 }
2701
2702
2703 HLoadNamedField* HGraphBuilder::AddLoadElements(HValue* object,
2704                                                 HValue* dependency) {
2705   return Add<HLoadNamedField>(
2706       object, dependency, HObjectAccess::ForElementsPointer());
2707 }
2708
2709
2710 HLoadNamedField* HGraphBuilder::AddLoadFixedArrayLength(
2711     HValue* array,
2712     HValue* dependency) {
2713   return Add<HLoadNamedField>(
2714       array, dependency, HObjectAccess::ForFixedArrayLength());
2715 }
2716
2717
2718 HLoadNamedField* HGraphBuilder::AddLoadArrayLength(HValue* array,
2719                                                    ElementsKind kind,
2720                                                    HValue* dependency) {
2721   return Add<HLoadNamedField>(
2722       array, dependency, HObjectAccess::ForArrayLength(kind));
2723 }
2724
2725
2726 HValue* HGraphBuilder::BuildNewElementsCapacity(HValue* old_capacity) {
2727   HValue* half_old_capacity = AddUncasted<HShr>(old_capacity,
2728                                                 graph_->GetConstant1());
2729
2730   HValue* new_capacity = AddUncasted<HAdd>(half_old_capacity, old_capacity);
2731   new_capacity->ClearFlag(HValue::kCanOverflow);
2732
2733   HValue* min_growth = Add<HConstant>(16);
2734
2735   new_capacity = AddUncasted<HAdd>(new_capacity, min_growth);
2736   new_capacity->ClearFlag(HValue::kCanOverflow);
2737
2738   return new_capacity;
2739 }
2740
2741
2742 HValue* HGraphBuilder::BuildGrowElementsCapacity(HValue* object,
2743                                                  HValue* elements,
2744                                                  ElementsKind kind,
2745                                                  ElementsKind new_kind,
2746                                                  HValue* length,
2747                                                  HValue* new_capacity) {
2748   Add<HBoundsCheck>(new_capacity, Add<HConstant>(
2749           (Page::kMaxRegularHeapObjectSize - FixedArray::kHeaderSize) >>
2750           ElementsKindToShiftSize(new_kind)));
2751
2752   HValue* new_elements = BuildAllocateElementsAndInitializeElementsHeader(
2753       new_kind, new_capacity);
2754
2755   BuildCopyElements(elements, kind, new_elements,
2756                     new_kind, length, new_capacity);
2757
2758   Add<HStoreNamedField>(object, HObjectAccess::ForElementsPointer(),
2759                         new_elements);
2760
2761   return new_elements;
2762 }
2763
2764
2765 void HGraphBuilder::BuildFillElementsWithValue(HValue* elements,
2766                                                ElementsKind elements_kind,
2767                                                HValue* from,
2768                                                HValue* to,
2769                                                HValue* value) {
2770   if (to == NULL) {
2771     to = AddLoadFixedArrayLength(elements);
2772   }
2773
2774   // Special loop unfolding case
2775   STATIC_ASSERT(JSArray::kPreallocatedArrayElements <=
2776                 kElementLoopUnrollThreshold);
2777   int initial_capacity = -1;
2778   if (from->IsInteger32Constant() && to->IsInteger32Constant()) {
2779     int constant_from = from->GetInteger32Constant();
2780     int constant_to = to->GetInteger32Constant();
2781
2782     if (constant_from == 0 && constant_to <= kElementLoopUnrollThreshold) {
2783       initial_capacity = constant_to;
2784     }
2785   }
2786
2787   // Since we're about to store a hole value, the store instruction below must
2788   // assume an elements kind that supports heap object values.
2789   if (IsFastSmiOrObjectElementsKind(elements_kind)) {
2790     elements_kind = FAST_HOLEY_ELEMENTS;
2791   }
2792
2793   if (initial_capacity >= 0) {
2794     for (int i = 0; i < initial_capacity; i++) {
2795       HInstruction* key = Add<HConstant>(i);
2796       Add<HStoreKeyed>(elements, key, value, elements_kind);
2797     }
2798   } else {
2799     // Carefully loop backwards so that the "from" remains live through the loop
2800     // rather than the to. This often corresponds to keeping length live rather
2801     // then capacity, which helps register allocation, since length is used more
2802     // other than capacity after filling with holes.
2803     LoopBuilder builder(this, context(), LoopBuilder::kPostDecrement);
2804
2805     HValue* key = builder.BeginBody(to, from, Token::GT);
2806
2807     HValue* adjusted_key = AddUncasted<HSub>(key, graph()->GetConstant1());
2808     adjusted_key->ClearFlag(HValue::kCanOverflow);
2809
2810     Add<HStoreKeyed>(elements, adjusted_key, value, elements_kind);
2811
2812     builder.EndBody();
2813   }
2814 }
2815
2816
2817 void HGraphBuilder::BuildFillElementsWithHole(HValue* elements,
2818                                               ElementsKind elements_kind,
2819                                               HValue* from,
2820                                               HValue* to) {
2821   // Fast elements kinds need to be initialized in case statements below cause a
2822   // garbage collection.
2823   Factory* factory = isolate()->factory();
2824
2825   double nan_double = FixedDoubleArray::hole_nan_as_double();
2826   HValue* hole = IsFastSmiOrObjectElementsKind(elements_kind)
2827       ? Add<HConstant>(factory->the_hole_value())
2828       : Add<HConstant>(nan_double);
2829
2830   BuildFillElementsWithValue(elements, elements_kind, from, to, hole);
2831 }
2832
2833
2834 void HGraphBuilder::BuildCopyElements(HValue* from_elements,
2835                                       ElementsKind from_elements_kind,
2836                                       HValue* to_elements,
2837                                       ElementsKind to_elements_kind,
2838                                       HValue* length,
2839                                       HValue* capacity) {
2840   int constant_capacity = -1;
2841   if (capacity != NULL &&
2842       capacity->IsConstant() &&
2843       HConstant::cast(capacity)->HasInteger32Value()) {
2844     int constant_candidate = HConstant::cast(capacity)->Integer32Value();
2845     if (constant_candidate <= kElementLoopUnrollThreshold) {
2846       constant_capacity = constant_candidate;
2847     }
2848   }
2849
2850   bool pre_fill_with_holes =
2851     IsFastDoubleElementsKind(from_elements_kind) &&
2852     IsFastObjectElementsKind(to_elements_kind);
2853   if (pre_fill_with_holes) {
2854     // If the copy might trigger a GC, make sure that the FixedArray is
2855     // pre-initialized with holes to make sure that it's always in a
2856     // consistent state.
2857     BuildFillElementsWithHole(to_elements, to_elements_kind,
2858                               graph()->GetConstant0(), NULL);
2859   }
2860
2861   if (constant_capacity != -1) {
2862     // Unroll the loop for small elements kinds.
2863     for (int i = 0; i < constant_capacity; i++) {
2864       HValue* key_constant = Add<HConstant>(i);
2865       HInstruction* value = Add<HLoadKeyed>(from_elements, key_constant,
2866                                             static_cast<HValue*>(NULL),
2867                                             from_elements_kind);
2868       Add<HStoreKeyed>(to_elements, key_constant, value, to_elements_kind);
2869     }
2870   } else {
2871     if (!pre_fill_with_holes &&
2872         (capacity == NULL || !length->Equals(capacity))) {
2873       BuildFillElementsWithHole(to_elements, to_elements_kind,
2874                                 length, NULL);
2875     }
2876
2877     if (capacity == NULL) {
2878       capacity = AddLoadFixedArrayLength(to_elements);
2879     }
2880
2881     LoopBuilder builder(this, context(), LoopBuilder::kPostDecrement);
2882
2883     HValue* key = builder.BeginBody(length, graph()->GetConstant0(),
2884                                     Token::GT);
2885
2886     key = AddUncasted<HSub>(key, graph()->GetConstant1());
2887     key->ClearFlag(HValue::kCanOverflow);
2888
2889     HValue* element = Add<HLoadKeyed>(from_elements, key,
2890                                       static_cast<HValue*>(NULL),
2891                                       from_elements_kind,
2892                                       ALLOW_RETURN_HOLE);
2893
2894     ElementsKind kind = (IsHoleyElementsKind(from_elements_kind) &&
2895                          IsFastSmiElementsKind(to_elements_kind))
2896       ? FAST_HOLEY_ELEMENTS : to_elements_kind;
2897
2898     if (IsHoleyElementsKind(from_elements_kind) &&
2899         from_elements_kind != to_elements_kind) {
2900       IfBuilder if_hole(this);
2901       if_hole.If<HCompareHoleAndBranch>(element);
2902       if_hole.Then();
2903       HConstant* hole_constant = IsFastDoubleElementsKind(to_elements_kind)
2904         ? Add<HConstant>(FixedDoubleArray::hole_nan_as_double())
2905         : graph()->GetConstantHole();
2906       Add<HStoreKeyed>(to_elements, key, hole_constant, kind);
2907       if_hole.Else();
2908       HStoreKeyed* store = Add<HStoreKeyed>(to_elements, key, element, kind);
2909       store->SetFlag(HValue::kAllowUndefinedAsNaN);
2910       if_hole.End();
2911     } else {
2912       HStoreKeyed* store = Add<HStoreKeyed>(to_elements, key, element, kind);
2913       store->SetFlag(HValue::kAllowUndefinedAsNaN);
2914     }
2915
2916     builder.EndBody();
2917   }
2918
2919   Counters* counters = isolate()->counters();
2920   AddIncrementCounter(counters->inlined_copied_elements());
2921 }
2922
2923
2924 HValue* HGraphBuilder::BuildCloneShallowArrayCow(HValue* boilerplate,
2925                                                  HValue* allocation_site,
2926                                                  AllocationSiteMode mode,
2927                                                  ElementsKind kind) {
2928   HAllocate* array = AllocateJSArrayObject(mode);
2929
2930   HValue* map = AddLoadMap(boilerplate);
2931   HValue* elements = AddLoadElements(boilerplate);
2932   HValue* length = AddLoadArrayLength(boilerplate, kind);
2933
2934   BuildJSArrayHeader(array,
2935                      map,
2936                      elements,
2937                      mode,
2938                      FAST_ELEMENTS,
2939                      allocation_site,
2940                      length);
2941   return array;
2942 }
2943
2944
2945 HValue* HGraphBuilder::BuildCloneShallowArrayEmpty(HValue* boilerplate,
2946                                                    HValue* allocation_site,
2947                                                    AllocationSiteMode mode) {
2948   HAllocate* array = AllocateJSArrayObject(mode);
2949
2950   HValue* map = AddLoadMap(boilerplate);
2951
2952   BuildJSArrayHeader(array,
2953                      map,
2954                      NULL,  // set elements to empty fixed array
2955                      mode,
2956                      FAST_ELEMENTS,
2957                      allocation_site,
2958                      graph()->GetConstant0());
2959   return array;
2960 }
2961
2962
2963 HValue* HGraphBuilder::BuildCloneShallowArrayNonEmpty(HValue* boilerplate,
2964                                                       HValue* allocation_site,
2965                                                       AllocationSiteMode mode,
2966                                                       ElementsKind kind) {
2967   HValue* boilerplate_elements = AddLoadElements(boilerplate);
2968   HValue* capacity = AddLoadFixedArrayLength(boilerplate_elements);
2969
2970   // Generate size calculation code here in order to make it dominate
2971   // the JSArray allocation.
2972   HValue* elements_size = BuildCalculateElementsSize(kind, capacity);
2973
2974   // Create empty JSArray object for now, store elimination should remove
2975   // redundant initialization of elements and length fields and at the same
2976   // time the object will be fully prepared for GC if it happens during
2977   // elements allocation.
2978   HValue* result = BuildCloneShallowArrayEmpty(
2979       boilerplate, allocation_site, mode);
2980
2981   HAllocate* elements = BuildAllocateElements(kind, elements_size);
2982
2983   // This function implicitly relies on the fact that the
2984   // FastCloneShallowArrayStub is called only for literals shorter than
2985   // JSObject::kInitialMaxFastElementArray.
2986   // Can't add HBoundsCheck here because otherwise the stub will eager a frame.
2987   HConstant* size_upper_bound = EstablishElementsAllocationSize(
2988       kind, JSObject::kInitialMaxFastElementArray);
2989   elements->set_size_upper_bound(size_upper_bound);
2990
2991   Add<HStoreNamedField>(result, HObjectAccess::ForElementsPointer(), elements);
2992
2993   // The allocation for the cloned array above causes register pressure on
2994   // machines with low register counts. Force a reload of the boilerplate
2995   // elements here to free up a register for the allocation to avoid unnecessary
2996   // spillage.
2997   boilerplate_elements = AddLoadElements(boilerplate);
2998   boilerplate_elements->SetFlag(HValue::kCantBeReplaced);
2999
3000   // Copy the elements array header.
3001   for (int i = 0; i < FixedArrayBase::kHeaderSize; i += kPointerSize) {
3002     HObjectAccess access = HObjectAccess::ForFixedArrayHeader(i);
3003     Add<HStoreNamedField>(elements, access,
3004         Add<HLoadNamedField>(boilerplate_elements,
3005                              static_cast<HValue*>(NULL), access));
3006   }
3007
3008   // And the result of the length
3009   HValue* length = AddLoadArrayLength(boilerplate, kind);
3010   Add<HStoreNamedField>(result, HObjectAccess::ForArrayLength(kind), length);
3011
3012   BuildCopyElements(boilerplate_elements, kind, elements,
3013                     kind, length, NULL);
3014   return result;
3015 }
3016
3017
3018 void HGraphBuilder::BuildCompareNil(
3019     HValue* value,
3020     Type* type,
3021     HIfContinuation* continuation) {
3022   IfBuilder if_nil(this);
3023   bool some_case_handled = false;
3024   bool some_case_missing = false;
3025
3026   if (type->Maybe(Type::Null())) {
3027     if (some_case_handled) if_nil.Or();
3028     if_nil.If<HCompareObjectEqAndBranch>(value, graph()->GetConstantNull());
3029     some_case_handled = true;
3030   } else {
3031     some_case_missing = true;
3032   }
3033
3034   if (type->Maybe(Type::Undefined())) {
3035     if (some_case_handled) if_nil.Or();
3036     if_nil.If<HCompareObjectEqAndBranch>(value,
3037                                          graph()->GetConstantUndefined());
3038     some_case_handled = true;
3039   } else {
3040     some_case_missing = true;
3041   }
3042
3043   if (type->Maybe(Type::Undetectable())) {
3044     if (some_case_handled) if_nil.Or();
3045     if_nil.If<HIsUndetectableAndBranch>(value);
3046     some_case_handled = true;
3047   } else {
3048     some_case_missing = true;
3049   }
3050
3051   if (some_case_missing) {
3052     if_nil.Then();
3053     if_nil.Else();
3054     if (type->NumClasses() == 1) {
3055       BuildCheckHeapObject(value);
3056       // For ICs, the map checked below is a sentinel map that gets replaced by
3057       // the monomorphic map when the code is used as a template to generate a
3058       // new IC. For optimized functions, there is no sentinel map, the map
3059       // emitted below is the actual monomorphic map.
3060       Add<HCheckMaps>(value, type->Classes().Current());
3061     } else {
3062       if_nil.Deopt("Too many undetectable types");
3063     }
3064   }
3065
3066   if_nil.CaptureContinuation(continuation);
3067 }
3068
3069
3070 void HGraphBuilder::BuildCreateAllocationMemento(
3071     HValue* previous_object,
3072     HValue* previous_object_size,
3073     HValue* allocation_site) {
3074   DCHECK(allocation_site != NULL);
3075   HInnerAllocatedObject* allocation_memento = Add<HInnerAllocatedObject>(
3076       previous_object, previous_object_size, HType::HeapObject());
3077   AddStoreMapConstant(
3078       allocation_memento, isolate()->factory()->allocation_memento_map());
3079   Add<HStoreNamedField>(
3080       allocation_memento,
3081       HObjectAccess::ForAllocationMementoSite(),
3082       allocation_site);
3083   if (FLAG_allocation_site_pretenuring) {
3084     HValue* memento_create_count = Add<HLoadNamedField>(
3085         allocation_site, static_cast<HValue*>(NULL),
3086         HObjectAccess::ForAllocationSiteOffset(
3087             AllocationSite::kPretenureCreateCountOffset));
3088     memento_create_count = AddUncasted<HAdd>(
3089         memento_create_count, graph()->GetConstant1());
3090     // This smi value is reset to zero after every gc, overflow isn't a problem
3091     // since the counter is bounded by the new space size.
3092     memento_create_count->ClearFlag(HValue::kCanOverflow);
3093     Add<HStoreNamedField>(
3094         allocation_site, HObjectAccess::ForAllocationSiteOffset(
3095             AllocationSite::kPretenureCreateCountOffset), memento_create_count);
3096   }
3097 }
3098
3099
3100 HInstruction* HGraphBuilder::BuildGetNativeContext(HValue* closure) {
3101   // Get the global context, then the native context
3102   HInstruction* context =
3103       Add<HLoadNamedField>(closure, static_cast<HValue*>(NULL),
3104                            HObjectAccess::ForFunctionContextPointer());
3105   HInstruction* global_object = Add<HLoadNamedField>(
3106       context, static_cast<HValue*>(NULL),
3107       HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
3108   HObjectAccess access = HObjectAccess::ForObservableJSObjectOffset(
3109       GlobalObject::kNativeContextOffset);
3110   return Add<HLoadNamedField>(
3111       global_object, static_cast<HValue*>(NULL), access);
3112 }
3113
3114
3115 HInstruction* HGraphBuilder::BuildGetNativeContext() {
3116   // Get the global context, then the native context
3117   HValue* global_object = Add<HLoadNamedField>(
3118       context(), static_cast<HValue*>(NULL),
3119       HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
3120   return Add<HLoadNamedField>(
3121       global_object, static_cast<HValue*>(NULL),
3122       HObjectAccess::ForObservableJSObjectOffset(
3123           GlobalObject::kNativeContextOffset));
3124 }
3125
3126
3127 HInstruction* HGraphBuilder::BuildGetArrayFunction() {
3128   HInstruction* native_context = BuildGetNativeContext();
3129   HInstruction* index =
3130       Add<HConstant>(static_cast<int32_t>(Context::ARRAY_FUNCTION_INDEX));
3131   return Add<HLoadKeyed>(
3132       native_context, index, static_cast<HValue*>(NULL), FAST_ELEMENTS);
3133 }
3134
3135
3136 HGraphBuilder::JSArrayBuilder::JSArrayBuilder(HGraphBuilder* builder,
3137     ElementsKind kind,
3138     HValue* allocation_site_payload,
3139     HValue* constructor_function,
3140     AllocationSiteOverrideMode override_mode) :
3141         builder_(builder),
3142         kind_(kind),
3143         allocation_site_payload_(allocation_site_payload),
3144         constructor_function_(constructor_function) {
3145   DCHECK(!allocation_site_payload->IsConstant() ||
3146          HConstant::cast(allocation_site_payload)->handle(
3147              builder_->isolate())->IsAllocationSite());
3148   mode_ = override_mode == DISABLE_ALLOCATION_SITES
3149       ? DONT_TRACK_ALLOCATION_SITE
3150       : AllocationSite::GetMode(kind);
3151 }
3152
3153
3154 HGraphBuilder::JSArrayBuilder::JSArrayBuilder(HGraphBuilder* builder,
3155                                               ElementsKind kind,
3156                                               HValue* constructor_function) :
3157     builder_(builder),
3158     kind_(kind),
3159     mode_(DONT_TRACK_ALLOCATION_SITE),
3160     allocation_site_payload_(NULL),
3161     constructor_function_(constructor_function) {
3162 }
3163
3164
3165 HValue* HGraphBuilder::JSArrayBuilder::EmitMapCode() {
3166   if (!builder()->top_info()->IsStub()) {
3167     // A constant map is fine.
3168     Handle<Map> map(builder()->isolate()->get_initial_js_array_map(kind_),
3169                     builder()->isolate());
3170     return builder()->Add<HConstant>(map);
3171   }
3172
3173   if (constructor_function_ != NULL && kind_ == GetInitialFastElementsKind()) {
3174     // No need for a context lookup if the kind_ matches the initial
3175     // map, because we can just load the map in that case.
3176     HObjectAccess access = HObjectAccess::ForPrototypeOrInitialMap();
3177     return builder()->Add<HLoadNamedField>(
3178         constructor_function_, static_cast<HValue*>(NULL), access);
3179   }
3180
3181   // TODO(mvstanton): we should always have a constructor function if we
3182   // are creating a stub.
3183   HInstruction* native_context = constructor_function_ != NULL
3184       ? builder()->BuildGetNativeContext(constructor_function_)
3185       : builder()->BuildGetNativeContext();
3186
3187   HInstruction* index = builder()->Add<HConstant>(
3188       static_cast<int32_t>(Context::JS_ARRAY_MAPS_INDEX));
3189
3190   HInstruction* map_array = builder()->Add<HLoadKeyed>(
3191       native_context, index, static_cast<HValue*>(NULL), FAST_ELEMENTS);
3192
3193   HInstruction* kind_index = builder()->Add<HConstant>(kind_);
3194
3195   return builder()->Add<HLoadKeyed>(
3196       map_array, kind_index, static_cast<HValue*>(NULL), FAST_ELEMENTS);
3197 }
3198
3199
3200 HValue* HGraphBuilder::JSArrayBuilder::EmitInternalMapCode() {
3201   // Find the map near the constructor function
3202   HObjectAccess access = HObjectAccess::ForPrototypeOrInitialMap();
3203   return builder()->Add<HLoadNamedField>(
3204       constructor_function_, static_cast<HValue*>(NULL), access);
3205 }
3206
3207
3208 HAllocate* HGraphBuilder::JSArrayBuilder::AllocateEmptyArray() {
3209   HConstant* capacity = builder()->Add<HConstant>(initial_capacity());
3210   return AllocateArray(capacity,
3211                        capacity,
3212                        builder()->graph()->GetConstant0());
3213 }
3214
3215
3216 HAllocate* HGraphBuilder::JSArrayBuilder::AllocateArray(
3217     HValue* capacity,
3218     HConstant* capacity_upper_bound,
3219     HValue* length_field,
3220     FillMode fill_mode) {
3221   return AllocateArray(capacity,
3222                        capacity_upper_bound->GetInteger32Constant(),
3223                        length_field,
3224                        fill_mode);
3225 }
3226
3227
3228 HAllocate* HGraphBuilder::JSArrayBuilder::AllocateArray(
3229     HValue* capacity,
3230     int capacity_upper_bound,
3231     HValue* length_field,
3232     FillMode fill_mode) {
3233   HConstant* elememts_size_upper_bound = capacity->IsInteger32Constant()
3234       ? HConstant::cast(capacity)
3235       : builder()->EstablishElementsAllocationSize(kind_, capacity_upper_bound);
3236
3237   HAllocate* array = AllocateArray(capacity, length_field, fill_mode);
3238   if (!elements_location_->has_size_upper_bound()) {
3239     elements_location_->set_size_upper_bound(elememts_size_upper_bound);
3240   }
3241   return array;
3242 }
3243
3244
3245 HAllocate* HGraphBuilder::JSArrayBuilder::AllocateArray(
3246     HValue* capacity,
3247     HValue* length_field,
3248     FillMode fill_mode) {
3249   // These HForceRepresentations are because we store these as fields in the
3250   // objects we construct, and an int32-to-smi HChange could deopt. Accept
3251   // the deopt possibility now, before allocation occurs.
3252   capacity =
3253       builder()->AddUncasted<HForceRepresentation>(capacity,
3254                                                    Representation::Smi());
3255   length_field =
3256       builder()->AddUncasted<HForceRepresentation>(length_field,
3257                                                    Representation::Smi());
3258
3259   // Generate size calculation code here in order to make it dominate
3260   // the JSArray allocation.
3261   HValue* elements_size =
3262       builder()->BuildCalculateElementsSize(kind_, capacity);
3263
3264   // Allocate (dealing with failure appropriately)
3265   HAllocate* array_object = builder()->AllocateJSArrayObject(mode_);
3266
3267   // Fill in the fields: map, properties, length
3268   HValue* map;
3269   if (allocation_site_payload_ == NULL) {
3270     map = EmitInternalMapCode();
3271   } else {
3272     map = EmitMapCode();
3273   }
3274
3275   builder()->BuildJSArrayHeader(array_object,
3276                                 map,
3277                                 NULL,  // set elements to empty fixed array
3278                                 mode_,
3279                                 kind_,
3280                                 allocation_site_payload_,
3281                                 length_field);
3282
3283   // Allocate and initialize the elements
3284   elements_location_ = builder()->BuildAllocateElements(kind_, elements_size);
3285
3286   builder()->BuildInitializeElementsHeader(elements_location_, kind_, capacity);
3287
3288   // Set the elements
3289   builder()->Add<HStoreNamedField>(
3290       array_object, HObjectAccess::ForElementsPointer(), elements_location_);
3291
3292   if (fill_mode == FILL_WITH_HOLE) {
3293     builder()->BuildFillElementsWithHole(elements_location_, kind_,
3294                                          graph()->GetConstant0(), capacity);
3295   }
3296
3297   return array_object;
3298 }
3299
3300
3301 HValue* HGraphBuilder::AddLoadJSBuiltin(Builtins::JavaScript builtin) {
3302   HValue* global_object = Add<HLoadNamedField>(
3303       context(), static_cast<HValue*>(NULL),
3304       HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
3305   HObjectAccess access = HObjectAccess::ForObservableJSObjectOffset(
3306       GlobalObject::kBuiltinsOffset);
3307   HValue* builtins = Add<HLoadNamedField>(
3308       global_object, static_cast<HValue*>(NULL), access);
3309   HObjectAccess function_access = HObjectAccess::ForObservableJSObjectOffset(
3310           JSBuiltinsObject::OffsetOfFunctionWithId(builtin));
3311   return Add<HLoadNamedField>(
3312       builtins, static_cast<HValue*>(NULL), function_access);
3313 }
3314
3315
3316 HOptimizedGraphBuilder::HOptimizedGraphBuilder(CompilationInfo* info)
3317     : HGraphBuilder(info),
3318       function_state_(NULL),
3319       initial_function_state_(this, info, NORMAL_RETURN, 0),
3320       ast_context_(NULL),
3321       break_scope_(NULL),
3322       inlined_count_(0),
3323       globals_(10, info->zone()),
3324       inline_bailout_(false),
3325       osr_(new(info->zone()) HOsrBuilder(this)) {
3326   // This is not initialized in the initializer list because the
3327   // constructor for the initial state relies on function_state_ == NULL
3328   // to know it's the initial state.
3329   function_state_= &initial_function_state_;
3330   InitializeAstVisitor(info->zone());
3331   if (FLAG_hydrogen_track_positions) {
3332     SetSourcePosition(info->shared_info()->start_position());
3333   }
3334 }
3335
3336
3337 HBasicBlock* HOptimizedGraphBuilder::CreateJoin(HBasicBlock* first,
3338                                                 HBasicBlock* second,
3339                                                 BailoutId join_id) {
3340   if (first == NULL) {
3341     return second;
3342   } else if (second == NULL) {
3343     return first;
3344   } else {
3345     HBasicBlock* join_block = graph()->CreateBasicBlock();
3346     Goto(first, join_block);
3347     Goto(second, join_block);
3348     join_block->SetJoinId(join_id);
3349     return join_block;
3350   }
3351 }
3352
3353
3354 HBasicBlock* HOptimizedGraphBuilder::JoinContinue(IterationStatement* statement,
3355                                                   HBasicBlock* exit_block,
3356                                                   HBasicBlock* continue_block) {
3357   if (continue_block != NULL) {
3358     if (exit_block != NULL) Goto(exit_block, continue_block);
3359     continue_block->SetJoinId(statement->ContinueId());
3360     return continue_block;
3361   }
3362   return exit_block;
3363 }
3364
3365
3366 HBasicBlock* HOptimizedGraphBuilder::CreateLoop(IterationStatement* statement,
3367                                                 HBasicBlock* loop_entry,
3368                                                 HBasicBlock* body_exit,
3369                                                 HBasicBlock* loop_successor,
3370                                                 HBasicBlock* break_block) {
3371   if (body_exit != NULL) Goto(body_exit, loop_entry);
3372   loop_entry->PostProcessLoopHeader(statement);
3373   if (break_block != NULL) {
3374     if (loop_successor != NULL) Goto(loop_successor, break_block);
3375     break_block->SetJoinId(statement->ExitId());
3376     return break_block;
3377   }
3378   return loop_successor;
3379 }
3380
3381
3382 // Build a new loop header block and set it as the current block.
3383 HBasicBlock* HOptimizedGraphBuilder::BuildLoopEntry() {
3384   HBasicBlock* loop_entry = CreateLoopHeaderBlock();
3385   Goto(loop_entry);
3386   set_current_block(loop_entry);
3387   return loop_entry;
3388 }
3389
3390
3391 HBasicBlock* HOptimizedGraphBuilder::BuildLoopEntry(
3392     IterationStatement* statement) {
3393   HBasicBlock* loop_entry = osr()->HasOsrEntryAt(statement)
3394       ? osr()->BuildOsrLoopEntry(statement)
3395       : BuildLoopEntry();
3396   return loop_entry;
3397 }
3398
3399
3400 void HBasicBlock::FinishExit(HControlInstruction* instruction,
3401                              HSourcePosition position) {
3402   Finish(instruction, position);
3403   ClearEnvironment();
3404 }
3405
3406
3407 OStream& operator<<(OStream& os, const HBasicBlock& b) {
3408   return os << "B" << b.block_id();
3409 }
3410
3411
3412 HGraph::HGraph(CompilationInfo* info)
3413     : isolate_(info->isolate()),
3414       next_block_id_(0),
3415       entry_block_(NULL),
3416       blocks_(8, info->zone()),
3417       values_(16, info->zone()),
3418       phi_list_(NULL),
3419       uint32_instructions_(NULL),
3420       osr_(NULL),
3421       info_(info),
3422       zone_(info->zone()),
3423       is_recursive_(false),
3424       use_optimistic_licm_(false),
3425       depends_on_empty_array_proto_elements_(false),
3426       type_change_checksum_(0),
3427       maximum_environment_size_(0),
3428       no_side_effects_scope_count_(0),
3429       disallow_adding_new_values_(false),
3430       next_inline_id_(0),
3431       inlined_functions_(5, info->zone()) {
3432   if (info->IsStub()) {
3433     HydrogenCodeStub* stub = info->code_stub();
3434     CodeStubInterfaceDescriptor* descriptor = stub->GetInterfaceDescriptor();
3435     start_environment_ = new(zone_) HEnvironment(
3436         zone_, descriptor->GetEnvironmentParameterCount());
3437   } else {
3438     TraceInlinedFunction(info->shared_info(), HSourcePosition::Unknown());
3439     start_environment_ =
3440         new(zone_) HEnvironment(NULL, info->scope(), info->closure(), zone_);
3441   }
3442   start_environment_->set_ast_id(BailoutId::FunctionEntry());
3443   entry_block_ = CreateBasicBlock();
3444   entry_block_->SetInitialEnvironment(start_environment_);
3445 }
3446
3447
3448 HBasicBlock* HGraph::CreateBasicBlock() {
3449   HBasicBlock* result = new(zone()) HBasicBlock(this);
3450   blocks_.Add(result, zone());
3451   return result;
3452 }
3453
3454
3455 void HGraph::FinalizeUniqueness() {
3456   DisallowHeapAllocation no_gc;
3457   DCHECK(!OptimizingCompilerThread::IsOptimizerThread(isolate()));
3458   for (int i = 0; i < blocks()->length(); ++i) {
3459     for (HInstructionIterator it(blocks()->at(i)); !it.Done(); it.Advance()) {
3460       it.Current()->FinalizeUniqueness();
3461     }
3462   }
3463 }
3464
3465
3466 int HGraph::TraceInlinedFunction(
3467     Handle<SharedFunctionInfo> shared,
3468     HSourcePosition position) {
3469   if (!FLAG_hydrogen_track_positions) {
3470     return 0;
3471   }
3472
3473   int id = 0;
3474   for (; id < inlined_functions_.length(); id++) {
3475     if (inlined_functions_[id].shared().is_identical_to(shared)) {
3476       break;
3477     }
3478   }
3479
3480   if (id == inlined_functions_.length()) {
3481     inlined_functions_.Add(InlinedFunctionInfo(shared), zone());
3482
3483     if (!shared->script()->IsUndefined()) {
3484       Handle<Script> script(Script::cast(shared->script()));
3485       if (!script->source()->IsUndefined()) {
3486         CodeTracer::Scope tracing_scopex(isolate()->GetCodeTracer());
3487         OFStream os(tracing_scopex.file());
3488         os << "--- FUNCTION SOURCE (" << shared->DebugName()->ToCString().get()
3489            << ") id{" << info()->optimization_id() << "," << id << "} ---\n";
3490         {
3491           ConsStringIteratorOp op;
3492           StringCharacterStream stream(String::cast(script->source()),
3493                                        &op,
3494                                        shared->start_position());
3495           // fun->end_position() points to the last character in the stream. We
3496           // need to compensate by adding one to calculate the length.
3497           int source_len =
3498               shared->end_position() - shared->start_position() + 1;
3499           for (int i = 0; i < source_len; i++) {
3500             if (stream.HasMore()) {
3501               os << AsUC16(stream.GetNext());
3502             }
3503           }
3504         }
3505
3506         os << "\n--- END ---\n";
3507       }
3508     }
3509   }
3510
3511   int inline_id = next_inline_id_++;
3512
3513   if (inline_id != 0) {
3514     CodeTracer::Scope tracing_scope(isolate()->GetCodeTracer());
3515     OFStream os(tracing_scope.file());
3516     os << "INLINE (" << shared->DebugName()->ToCString().get() << ") id{"
3517        << info()->optimization_id() << "," << id << "} AS " << inline_id
3518        << " AT " << position << endl;
3519   }
3520
3521   return inline_id;
3522 }
3523
3524
3525 int HGraph::SourcePositionToScriptPosition(HSourcePosition pos) {
3526   if (!FLAG_hydrogen_track_positions || pos.IsUnknown()) {
3527     return pos.raw();
3528   }
3529
3530   return inlined_functions_[pos.inlining_id()].start_position() +
3531       pos.position();
3532 }
3533
3534
3535 // Block ordering was implemented with two mutually recursive methods,
3536 // HGraph::Postorder and HGraph::PostorderLoopBlocks.
3537 // The recursion could lead to stack overflow so the algorithm has been
3538 // implemented iteratively.
3539 // At a high level the algorithm looks like this:
3540 //
3541 // Postorder(block, loop_header) : {
3542 //   if (block has already been visited or is of another loop) return;
3543 //   mark block as visited;
3544 //   if (block is a loop header) {
3545 //     VisitLoopMembers(block, loop_header);
3546 //     VisitSuccessorsOfLoopHeader(block);
3547 //   } else {
3548 //     VisitSuccessors(block)
3549 //   }
3550 //   put block in result list;
3551 // }
3552 //
3553 // VisitLoopMembers(block, outer_loop_header) {
3554 //   foreach (block b in block loop members) {
3555 //     VisitSuccessorsOfLoopMember(b, outer_loop_header);
3556 //     if (b is loop header) VisitLoopMembers(b);
3557 //   }
3558 // }
3559 //
3560 // VisitSuccessorsOfLoopMember(block, outer_loop_header) {
3561 //   foreach (block b in block successors) Postorder(b, outer_loop_header)
3562 // }
3563 //
3564 // VisitSuccessorsOfLoopHeader(block) {
3565 //   foreach (block b in block successors) Postorder(b, block)
3566 // }
3567 //
3568 // VisitSuccessors(block, loop_header) {
3569 //   foreach (block b in block successors) Postorder(b, loop_header)
3570 // }
3571 //
3572 // The ordering is started calling Postorder(entry, NULL).
3573 //
3574 // Each instance of PostorderProcessor represents the "stack frame" of the
3575 // recursion, and particularly keeps the state of the loop (iteration) of the
3576 // "Visit..." function it represents.
3577 // To recycle memory we keep all the frames in a double linked list but
3578 // this means that we cannot use constructors to initialize the frames.
3579 //
3580 class PostorderProcessor : public ZoneObject {
3581  public:
3582   // Back link (towards the stack bottom).
3583   PostorderProcessor* parent() {return father_; }
3584   // Forward link (towards the stack top).
3585   PostorderProcessor* child() {return child_; }
3586   HBasicBlock* block() { return block_; }
3587   HLoopInformation* loop() { return loop_; }
3588   HBasicBlock* loop_header() { return loop_header_; }
3589
3590   static PostorderProcessor* CreateEntryProcessor(Zone* zone,
3591                                                   HBasicBlock* block) {
3592     PostorderProcessor* result = new(zone) PostorderProcessor(NULL);
3593     return result->SetupSuccessors(zone, block, NULL);
3594   }
3595
3596   PostorderProcessor* PerformStep(Zone* zone,
3597                                   ZoneList<HBasicBlock*>* order) {
3598     PostorderProcessor* next =
3599         PerformNonBacktrackingStep(zone, order);
3600     if (next != NULL) {
3601       return next;
3602     } else {
3603       return Backtrack(zone, order);
3604     }
3605   }
3606
3607  private:
3608   explicit PostorderProcessor(PostorderProcessor* father)
3609       : father_(father), child_(NULL), successor_iterator(NULL) { }
3610
3611   // Each enum value states the cycle whose state is kept by this instance.
3612   enum LoopKind {
3613     NONE,
3614     SUCCESSORS,
3615     SUCCESSORS_OF_LOOP_HEADER,
3616     LOOP_MEMBERS,
3617     SUCCESSORS_OF_LOOP_MEMBER
3618   };
3619
3620   // Each "Setup..." method is like a constructor for a cycle state.
3621   PostorderProcessor* SetupSuccessors(Zone* zone,
3622                                       HBasicBlock* block,
3623                                       HBasicBlock* loop_header) {
3624     if (block == NULL || block->IsOrdered() ||
3625         block->parent_loop_header() != loop_header) {
3626       kind_ = NONE;
3627       block_ = NULL;
3628       loop_ = NULL;
3629       loop_header_ = NULL;
3630       return this;
3631     } else {
3632       block_ = block;
3633       loop_ = NULL;
3634       block->MarkAsOrdered();
3635
3636       if (block->IsLoopHeader()) {
3637         kind_ = SUCCESSORS_OF_LOOP_HEADER;
3638         loop_header_ = block;
3639         InitializeSuccessors();
3640         PostorderProcessor* result = Push(zone);
3641         return result->SetupLoopMembers(zone, block, block->loop_information(),
3642                                         loop_header);
3643       } else {
3644         DCHECK(block->IsFinished());
3645         kind_ = SUCCESSORS;
3646         loop_header_ = loop_header;
3647         InitializeSuccessors();
3648         return this;
3649       }
3650     }
3651   }
3652
3653   PostorderProcessor* SetupLoopMembers(Zone* zone,
3654                                        HBasicBlock* block,
3655                                        HLoopInformation* loop,
3656                                        HBasicBlock* loop_header) {
3657     kind_ = LOOP_MEMBERS;
3658     block_ = block;
3659     loop_ = loop;
3660     loop_header_ = loop_header;
3661     InitializeLoopMembers();
3662     return this;
3663   }
3664
3665   PostorderProcessor* SetupSuccessorsOfLoopMember(
3666       HBasicBlock* block,
3667       HLoopInformation* loop,
3668       HBasicBlock* loop_header) {
3669     kind_ = SUCCESSORS_OF_LOOP_MEMBER;
3670     block_ = block;
3671     loop_ = loop;
3672     loop_header_ = loop_header;
3673     InitializeSuccessors();
3674     return this;
3675   }
3676
3677   // This method "allocates" a new stack frame.
3678   PostorderProcessor* Push(Zone* zone) {
3679     if (child_ == NULL) {
3680       child_ = new(zone) PostorderProcessor(this);
3681     }
3682     return child_;
3683   }
3684
3685   void ClosePostorder(ZoneList<HBasicBlock*>* order, Zone* zone) {
3686     DCHECK(block_->end()->FirstSuccessor() == NULL ||
3687            order->Contains(block_->end()->FirstSuccessor()) ||
3688            block_->end()->FirstSuccessor()->IsLoopHeader());
3689     DCHECK(block_->end()->SecondSuccessor() == NULL ||
3690            order->Contains(block_->end()->SecondSuccessor()) ||
3691            block_->end()->SecondSuccessor()->IsLoopHeader());
3692     order->Add(block_, zone);
3693   }
3694
3695   // This method is the basic block to walk up the stack.
3696   PostorderProcessor* Pop(Zone* zone,
3697                           ZoneList<HBasicBlock*>* order) {
3698     switch (kind_) {
3699       case SUCCESSORS:
3700       case SUCCESSORS_OF_LOOP_HEADER:
3701         ClosePostorder(order, zone);
3702         return father_;
3703       case LOOP_MEMBERS:
3704         return father_;
3705       case SUCCESSORS_OF_LOOP_MEMBER:
3706         if (block()->IsLoopHeader() && block() != loop_->loop_header()) {
3707           // In this case we need to perform a LOOP_MEMBERS cycle so we
3708           // initialize it and return this instead of father.
3709           return SetupLoopMembers(zone, block(),
3710                                   block()->loop_information(), loop_header_);
3711         } else {
3712           return father_;
3713         }
3714       case NONE:
3715         return father_;
3716     }
3717     UNREACHABLE();
3718     return NULL;
3719   }
3720
3721   // Walks up the stack.
3722   PostorderProcessor* Backtrack(Zone* zone,
3723                                 ZoneList<HBasicBlock*>* order) {
3724     PostorderProcessor* parent = Pop(zone, order);
3725     while (parent != NULL) {
3726       PostorderProcessor* next =
3727           parent->PerformNonBacktrackingStep(zone, order);
3728       if (next != NULL) {
3729         return next;
3730       } else {
3731         parent = parent->Pop(zone, order);
3732       }
3733     }
3734     return NULL;
3735   }
3736
3737   PostorderProcessor* PerformNonBacktrackingStep(
3738       Zone* zone,
3739       ZoneList<HBasicBlock*>* order) {
3740     HBasicBlock* next_block;
3741     switch (kind_) {
3742       case SUCCESSORS:
3743         next_block = AdvanceSuccessors();
3744         if (next_block != NULL) {
3745           PostorderProcessor* result = Push(zone);
3746           return result->SetupSuccessors(zone, next_block, loop_header_);
3747         }
3748         break;
3749       case SUCCESSORS_OF_LOOP_HEADER:
3750         next_block = AdvanceSuccessors();
3751         if (next_block != NULL) {
3752           PostorderProcessor* result = Push(zone);
3753           return result->SetupSuccessors(zone, next_block, block());
3754         }
3755         break;
3756       case LOOP_MEMBERS:
3757         next_block = AdvanceLoopMembers();
3758         if (next_block != NULL) {
3759           PostorderProcessor* result = Push(zone);
3760           return result->SetupSuccessorsOfLoopMember(next_block,
3761                                                      loop_, loop_header_);
3762         }
3763         break;
3764       case SUCCESSORS_OF_LOOP_MEMBER:
3765         next_block = AdvanceSuccessors();
3766         if (next_block != NULL) {
3767           PostorderProcessor* result = Push(zone);
3768           return result->SetupSuccessors(zone, next_block, loop_header_);
3769         }
3770         break;
3771       case NONE:
3772         return NULL;
3773     }
3774     return NULL;
3775   }
3776
3777   // The following two methods implement a "foreach b in successors" cycle.
3778   void InitializeSuccessors() {
3779     loop_index = 0;
3780     loop_length = 0;
3781     successor_iterator = HSuccessorIterator(block_->end());
3782   }
3783
3784   HBasicBlock* AdvanceSuccessors() {
3785     if (!successor_iterator.Done()) {
3786       HBasicBlock* result = successor_iterator.Current();
3787       successor_iterator.Advance();
3788       return result;
3789     }
3790     return NULL;
3791   }
3792
3793   // The following two methods implement a "foreach b in loop members" cycle.
3794   void InitializeLoopMembers() {
3795     loop_index = 0;
3796     loop_length = loop_->blocks()->length();
3797   }
3798
3799   HBasicBlock* AdvanceLoopMembers() {
3800     if (loop_index < loop_length) {
3801       HBasicBlock* result = loop_->blocks()->at(loop_index);
3802       loop_index++;
3803       return result;
3804     } else {
3805       return NULL;
3806     }
3807   }
3808
3809   LoopKind kind_;
3810   PostorderProcessor* father_;
3811   PostorderProcessor* child_;
3812   HLoopInformation* loop_;
3813   HBasicBlock* block_;
3814   HBasicBlock* loop_header_;
3815   int loop_index;
3816   int loop_length;
3817   HSuccessorIterator successor_iterator;
3818 };
3819
3820
3821 void HGraph::OrderBlocks() {
3822   CompilationPhase phase("H_Block ordering", info());
3823
3824 #ifdef DEBUG
3825   // Initially the blocks must not be ordered.
3826   for (int i = 0; i < blocks_.length(); ++i) {
3827     DCHECK(!blocks_[i]->IsOrdered());
3828   }
3829 #endif
3830
3831   PostorderProcessor* postorder =
3832       PostorderProcessor::CreateEntryProcessor(zone(), blocks_[0]);
3833   blocks_.Rewind(0);
3834   while (postorder) {
3835     postorder = postorder->PerformStep(zone(), &blocks_);
3836   }
3837
3838 #ifdef DEBUG
3839   // Now all blocks must be marked as ordered.
3840   for (int i = 0; i < blocks_.length(); ++i) {
3841     DCHECK(blocks_[i]->IsOrdered());
3842   }
3843 #endif
3844
3845   // Reverse block list and assign block IDs.
3846   for (int i = 0, j = blocks_.length(); --j >= i; ++i) {
3847     HBasicBlock* bi = blocks_[i];
3848     HBasicBlock* bj = blocks_[j];
3849     bi->set_block_id(j);
3850     bj->set_block_id(i);
3851     blocks_[i] = bj;
3852     blocks_[j] = bi;
3853   }
3854 }
3855
3856
3857 void HGraph::AssignDominators() {
3858   HPhase phase("H_Assign dominators", this);
3859   for (int i = 0; i < blocks_.length(); ++i) {
3860     HBasicBlock* block = blocks_[i];
3861     if (block->IsLoopHeader()) {
3862       // Only the first predecessor of a loop header is from outside the loop.
3863       // All others are back edges, and thus cannot dominate the loop header.
3864       block->AssignCommonDominator(block->predecessors()->first());
3865       block->AssignLoopSuccessorDominators();
3866     } else {
3867       for (int j = blocks_[i]->predecessors()->length() - 1; j >= 0; --j) {
3868         blocks_[i]->AssignCommonDominator(blocks_[i]->predecessors()->at(j));
3869       }
3870     }
3871   }
3872 }
3873
3874
3875 bool HGraph::CheckArgumentsPhiUses() {
3876   int block_count = blocks_.length();
3877   for (int i = 0; i < block_count; ++i) {
3878     for (int j = 0; j < blocks_[i]->phis()->length(); ++j) {
3879       HPhi* phi = blocks_[i]->phis()->at(j);
3880       // We don't support phi uses of arguments for now.
3881       if (phi->CheckFlag(HValue::kIsArguments)) return false;
3882     }
3883   }
3884   return true;
3885 }
3886
3887
3888 bool HGraph::CheckConstPhiUses() {
3889   int block_count = blocks_.length();
3890   for (int i = 0; i < block_count; ++i) {
3891     for (int j = 0; j < blocks_[i]->phis()->length(); ++j) {
3892       HPhi* phi = blocks_[i]->phis()->at(j);
3893       // Check for the hole value (from an uninitialized const).
3894       for (int k = 0; k < phi->OperandCount(); k++) {
3895         if (phi->OperandAt(k) == GetConstantHole()) return false;
3896       }
3897     }
3898   }
3899   return true;
3900 }
3901
3902
3903 void HGraph::CollectPhis() {
3904   int block_count = blocks_.length();
3905   phi_list_ = new(zone()) ZoneList<HPhi*>(block_count, zone());
3906   for (int i = 0; i < block_count; ++i) {
3907     for (int j = 0; j < blocks_[i]->phis()->length(); ++j) {
3908       HPhi* phi = blocks_[i]->phis()->at(j);
3909       phi_list_->Add(phi, zone());
3910     }
3911   }
3912 }
3913
3914
3915 // Implementation of utility class to encapsulate the translation state for
3916 // a (possibly inlined) function.
3917 FunctionState::FunctionState(HOptimizedGraphBuilder* owner,
3918                              CompilationInfo* info,
3919                              InliningKind inlining_kind,
3920                              int inlining_id)
3921     : owner_(owner),
3922       compilation_info_(info),
3923       call_context_(NULL),
3924       inlining_kind_(inlining_kind),
3925       function_return_(NULL),
3926       test_context_(NULL),
3927       entry_(NULL),
3928       arguments_object_(NULL),
3929       arguments_elements_(NULL),
3930       inlining_id_(inlining_id),
3931       outer_source_position_(HSourcePosition::Unknown()),
3932       outer_(owner->function_state()) {
3933   if (outer_ != NULL) {
3934     // State for an inline function.
3935     if (owner->ast_context()->IsTest()) {
3936       HBasicBlock* if_true = owner->graph()->CreateBasicBlock();
3937       HBasicBlock* if_false = owner->graph()->CreateBasicBlock();
3938       if_true->MarkAsInlineReturnTarget(owner->current_block());
3939       if_false->MarkAsInlineReturnTarget(owner->current_block());
3940       TestContext* outer_test_context = TestContext::cast(owner->ast_context());
3941       Expression* cond = outer_test_context->condition();
3942       // The AstContext constructor pushed on the context stack.  This newed
3943       // instance is the reason that AstContext can't be BASE_EMBEDDED.
3944       test_context_ = new TestContext(owner, cond, if_true, if_false);
3945     } else {
3946       function_return_ = owner->graph()->CreateBasicBlock();
3947       function_return()->MarkAsInlineReturnTarget(owner->current_block());
3948     }
3949     // Set this after possibly allocating a new TestContext above.
3950     call_context_ = owner->ast_context();
3951   }
3952
3953   // Push on the state stack.
3954   owner->set_function_state(this);
3955
3956   if (FLAG_hydrogen_track_positions) {
3957     outer_source_position_ = owner->source_position();
3958     owner->EnterInlinedSource(
3959       info->shared_info()->start_position(),
3960       inlining_id);
3961     owner->SetSourcePosition(info->shared_info()->start_position());
3962   }
3963 }
3964
3965
3966 FunctionState::~FunctionState() {
3967   delete test_context_;
3968   owner_->set_function_state(outer_);
3969
3970   if (FLAG_hydrogen_track_positions) {
3971     owner_->set_source_position(outer_source_position_);
3972     owner_->EnterInlinedSource(
3973       outer_->compilation_info()->shared_info()->start_position(),
3974       outer_->inlining_id());
3975   }
3976 }
3977
3978
3979 // Implementation of utility classes to represent an expression's context in
3980 // the AST.
3981 AstContext::AstContext(HOptimizedGraphBuilder* owner, Expression::Context kind)
3982     : owner_(owner),
3983       kind_(kind),
3984       outer_(owner->ast_context()),
3985       for_typeof_(false) {
3986   owner->set_ast_context(this);  // Push.
3987 #ifdef DEBUG
3988   DCHECK(owner->environment()->frame_type() == JS_FUNCTION);
3989   original_length_ = owner->environment()->length();
3990 #endif
3991 }
3992
3993
3994 AstContext::~AstContext() {
3995   owner_->set_ast_context(outer_);  // Pop.
3996 }
3997
3998
3999 EffectContext::~EffectContext() {
4000   DCHECK(owner()->HasStackOverflow() ||
4001          owner()->current_block() == NULL ||
4002          (owner()->environment()->length() == original_length_ &&
4003           owner()->environment()->frame_type() == JS_FUNCTION));
4004 }
4005
4006
4007 ValueContext::~ValueContext() {
4008   DCHECK(owner()->HasStackOverflow() ||
4009          owner()->current_block() == NULL ||
4010          (owner()->environment()->length() == original_length_ + 1 &&
4011           owner()->environment()->frame_type() == JS_FUNCTION));
4012 }
4013
4014
4015 void EffectContext::ReturnValue(HValue* value) {
4016   // The value is simply ignored.
4017 }
4018
4019
4020 void ValueContext::ReturnValue(HValue* value) {
4021   // The value is tracked in the bailout environment, and communicated
4022   // through the environment as the result of the expression.
4023   if (!arguments_allowed() && value->CheckFlag(HValue::kIsArguments)) {
4024     owner()->Bailout(kBadValueContextForArgumentsValue);
4025   }
4026   owner()->Push(value);
4027 }
4028
4029
4030 void TestContext::ReturnValue(HValue* value) {
4031   BuildBranch(value);
4032 }
4033
4034
4035 void EffectContext::ReturnInstruction(HInstruction* instr, BailoutId ast_id) {
4036   DCHECK(!instr->IsControlInstruction());
4037   owner()->AddInstruction(instr);
4038   if (instr->HasObservableSideEffects()) {
4039     owner()->Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
4040   }
4041 }
4042
4043
4044 void EffectContext::ReturnControl(HControlInstruction* instr,
4045                                   BailoutId ast_id) {
4046   DCHECK(!instr->HasObservableSideEffects());
4047   HBasicBlock* empty_true = owner()->graph()->CreateBasicBlock();
4048   HBasicBlock* empty_false = owner()->graph()->CreateBasicBlock();
4049   instr->SetSuccessorAt(0, empty_true);
4050   instr->SetSuccessorAt(1, empty_false);
4051   owner()->FinishCurrentBlock(instr);
4052   HBasicBlock* join = owner()->CreateJoin(empty_true, empty_false, ast_id);
4053   owner()->set_current_block(join);
4054 }
4055
4056
4057 void EffectContext::ReturnContinuation(HIfContinuation* continuation,
4058                                        BailoutId ast_id) {
4059   HBasicBlock* true_branch = NULL;
4060   HBasicBlock* false_branch = NULL;
4061   continuation->Continue(&true_branch, &false_branch);
4062   if (!continuation->IsTrueReachable()) {
4063     owner()->set_current_block(false_branch);
4064   } else if (!continuation->IsFalseReachable()) {
4065     owner()->set_current_block(true_branch);
4066   } else {
4067     HBasicBlock* join = owner()->CreateJoin(true_branch, false_branch, ast_id);
4068     owner()->set_current_block(join);
4069   }
4070 }
4071
4072
4073 void ValueContext::ReturnInstruction(HInstruction* instr, BailoutId ast_id) {
4074   DCHECK(!instr->IsControlInstruction());
4075   if (!arguments_allowed() && instr->CheckFlag(HValue::kIsArguments)) {
4076     return owner()->Bailout(kBadValueContextForArgumentsObjectValue);
4077   }
4078   owner()->AddInstruction(instr);
4079   owner()->Push(instr);
4080   if (instr->HasObservableSideEffects()) {
4081     owner()->Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
4082   }
4083 }
4084
4085
4086 void ValueContext::ReturnControl(HControlInstruction* instr, BailoutId ast_id) {
4087   DCHECK(!instr->HasObservableSideEffects());
4088   if (!arguments_allowed() && instr->CheckFlag(HValue::kIsArguments)) {
4089     return owner()->Bailout(kBadValueContextForArgumentsObjectValue);
4090   }
4091   HBasicBlock* materialize_false = owner()->graph()->CreateBasicBlock();
4092   HBasicBlock* materialize_true = owner()->graph()->CreateBasicBlock();
4093   instr->SetSuccessorAt(0, materialize_true);
4094   instr->SetSuccessorAt(1, materialize_false);
4095   owner()->FinishCurrentBlock(instr);
4096   owner()->set_current_block(materialize_true);
4097   owner()->Push(owner()->graph()->GetConstantTrue());
4098   owner()->set_current_block(materialize_false);
4099   owner()->Push(owner()->graph()->GetConstantFalse());
4100   HBasicBlock* join =
4101     owner()->CreateJoin(materialize_true, materialize_false, ast_id);
4102   owner()->set_current_block(join);
4103 }
4104
4105
4106 void ValueContext::ReturnContinuation(HIfContinuation* continuation,
4107                                       BailoutId ast_id) {
4108   HBasicBlock* materialize_true = NULL;
4109   HBasicBlock* materialize_false = NULL;
4110   continuation->Continue(&materialize_true, &materialize_false);
4111   if (continuation->IsTrueReachable()) {
4112     owner()->set_current_block(materialize_true);
4113     owner()->Push(owner()->graph()->GetConstantTrue());
4114     owner()->set_current_block(materialize_true);
4115   }
4116   if (continuation->IsFalseReachable()) {
4117     owner()->set_current_block(materialize_false);
4118     owner()->Push(owner()->graph()->GetConstantFalse());
4119     owner()->set_current_block(materialize_false);
4120   }
4121   if (continuation->TrueAndFalseReachable()) {
4122     HBasicBlock* join =
4123         owner()->CreateJoin(materialize_true, materialize_false, ast_id);
4124     owner()->set_current_block(join);
4125   }
4126 }
4127
4128
4129 void TestContext::ReturnInstruction(HInstruction* instr, BailoutId ast_id) {
4130   DCHECK(!instr->IsControlInstruction());
4131   HOptimizedGraphBuilder* builder = owner();
4132   builder->AddInstruction(instr);
4133   // We expect a simulate after every expression with side effects, though
4134   // this one isn't actually needed (and wouldn't work if it were targeted).
4135   if (instr->HasObservableSideEffects()) {
4136     builder->Push(instr);
4137     builder->Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
4138     builder->Pop();
4139   }
4140   BuildBranch(instr);
4141 }
4142
4143
4144 void TestContext::ReturnControl(HControlInstruction* instr, BailoutId ast_id) {
4145   DCHECK(!instr->HasObservableSideEffects());
4146   HBasicBlock* empty_true = owner()->graph()->CreateBasicBlock();
4147   HBasicBlock* empty_false = owner()->graph()->CreateBasicBlock();
4148   instr->SetSuccessorAt(0, empty_true);
4149   instr->SetSuccessorAt(1, empty_false);
4150   owner()->FinishCurrentBlock(instr);
4151   owner()->Goto(empty_true, if_true(), owner()->function_state());
4152   owner()->Goto(empty_false, if_false(), owner()->function_state());
4153   owner()->set_current_block(NULL);
4154 }
4155
4156
4157 void TestContext::ReturnContinuation(HIfContinuation* continuation,
4158                                      BailoutId ast_id) {
4159   HBasicBlock* true_branch = NULL;
4160   HBasicBlock* false_branch = NULL;
4161   continuation->Continue(&true_branch, &false_branch);
4162   if (continuation->IsTrueReachable()) {
4163     owner()->Goto(true_branch, if_true(), owner()->function_state());
4164   }
4165   if (continuation->IsFalseReachable()) {
4166     owner()->Goto(false_branch, if_false(), owner()->function_state());
4167   }
4168   owner()->set_current_block(NULL);
4169 }
4170
4171
4172 void TestContext::BuildBranch(HValue* value) {
4173   // We expect the graph to be in edge-split form: there is no edge that
4174   // connects a branch node to a join node.  We conservatively ensure that
4175   // property by always adding an empty block on the outgoing edges of this
4176   // branch.
4177   HOptimizedGraphBuilder* builder = owner();
4178   if (value != NULL && value->CheckFlag(HValue::kIsArguments)) {
4179     builder->Bailout(kArgumentsObjectValueInATestContext);
4180   }
4181   ToBooleanStub::Types expected(condition()->to_boolean_types());
4182   ReturnControl(owner()->New<HBranch>(value, expected), BailoutId::None());
4183 }
4184
4185
4186 // HOptimizedGraphBuilder infrastructure for bailing out and checking bailouts.
4187 #define CHECK_BAILOUT(call)                     \
4188   do {                                          \
4189     call;                                       \
4190     if (HasStackOverflow()) return;             \
4191   } while (false)
4192
4193
4194 #define CHECK_ALIVE(call)                                       \
4195   do {                                                          \
4196     call;                                                       \
4197     if (HasStackOverflow() || current_block() == NULL) return;  \
4198   } while (false)
4199
4200
4201 #define CHECK_ALIVE_OR_RETURN(call, value)                            \
4202   do {                                                                \
4203     call;                                                             \
4204     if (HasStackOverflow() || current_block() == NULL) return value;  \
4205   } while (false)
4206
4207
4208 void HOptimizedGraphBuilder::Bailout(BailoutReason reason) {
4209   current_info()->set_bailout_reason(reason);
4210   SetStackOverflow();
4211 }
4212
4213
4214 void HOptimizedGraphBuilder::VisitForEffect(Expression* expr) {
4215   EffectContext for_effect(this);
4216   Visit(expr);
4217 }
4218
4219
4220 void HOptimizedGraphBuilder::VisitForValue(Expression* expr,
4221                                            ArgumentsAllowedFlag flag) {
4222   ValueContext for_value(this, flag);
4223   Visit(expr);
4224 }
4225
4226
4227 void HOptimizedGraphBuilder::VisitForTypeOf(Expression* expr) {
4228   ValueContext for_value(this, ARGUMENTS_NOT_ALLOWED);
4229   for_value.set_for_typeof(true);
4230   Visit(expr);
4231 }
4232
4233
4234 void HOptimizedGraphBuilder::VisitForControl(Expression* expr,
4235                                              HBasicBlock* true_block,
4236                                              HBasicBlock* false_block) {
4237   TestContext for_test(this, expr, true_block, false_block);
4238   Visit(expr);
4239 }
4240
4241
4242 void HOptimizedGraphBuilder::VisitExpressions(
4243     ZoneList<Expression*>* exprs) {
4244   for (int i = 0; i < exprs->length(); ++i) {
4245     CHECK_ALIVE(VisitForValue(exprs->at(i)));
4246   }
4247 }
4248
4249
4250 bool HOptimizedGraphBuilder::BuildGraph() {
4251   if (current_info()->function()->is_generator()) {
4252     Bailout(kFunctionIsAGenerator);
4253     return false;
4254   }
4255   Scope* scope = current_info()->scope();
4256   if (scope->HasIllegalRedeclaration()) {
4257     Bailout(kFunctionWithIllegalRedeclaration);
4258     return false;
4259   }
4260   if (scope->calls_eval()) {
4261     Bailout(kFunctionCallsEval);
4262     return false;
4263   }
4264   SetUpScope(scope);
4265
4266   // Add an edge to the body entry.  This is warty: the graph's start
4267   // environment will be used by the Lithium translation as the initial
4268   // environment on graph entry, but it has now been mutated by the
4269   // Hydrogen translation of the instructions in the start block.  This
4270   // environment uses values which have not been defined yet.  These
4271   // Hydrogen instructions will then be replayed by the Lithium
4272   // translation, so they cannot have an environment effect.  The edge to
4273   // the body's entry block (along with some special logic for the start
4274   // block in HInstruction::InsertAfter) seals the start block from
4275   // getting unwanted instructions inserted.
4276   //
4277   // TODO(kmillikin): Fix this.  Stop mutating the initial environment.
4278   // Make the Hydrogen instructions in the initial block into Hydrogen
4279   // values (but not instructions), present in the initial environment and
4280   // not replayed by the Lithium translation.
4281   HEnvironment* initial_env = environment()->CopyWithoutHistory();
4282   HBasicBlock* body_entry = CreateBasicBlock(initial_env);
4283   Goto(body_entry);
4284   body_entry->SetJoinId(BailoutId::FunctionEntry());
4285   set_current_block(body_entry);
4286
4287   // Handle implicit declaration of the function name in named function
4288   // expressions before other declarations.
4289   if (scope->is_function_scope() && scope->function() != NULL) {
4290     VisitVariableDeclaration(scope->function());
4291   }
4292   VisitDeclarations(scope->declarations());
4293   Add<HSimulate>(BailoutId::Declarations());
4294
4295   Add<HStackCheck>(HStackCheck::kFunctionEntry);
4296
4297   VisitStatements(current_info()->function()->body());
4298   if (HasStackOverflow()) return false;
4299
4300   if (current_block() != NULL) {
4301     Add<HReturn>(graph()->GetConstantUndefined());
4302     set_current_block(NULL);
4303   }
4304
4305   // If the checksum of the number of type info changes is the same as the
4306   // last time this function was compiled, then this recompile is likely not
4307   // due to missing/inadequate type feedback, but rather too aggressive
4308   // optimization. Disable optimistic LICM in that case.
4309   Handle<Code> unoptimized_code(current_info()->shared_info()->code());
4310   DCHECK(unoptimized_code->kind() == Code::FUNCTION);
4311   Handle<TypeFeedbackInfo> type_info(
4312       TypeFeedbackInfo::cast(unoptimized_code->type_feedback_info()));
4313   int checksum = type_info->own_type_change_checksum();
4314   int composite_checksum = graph()->update_type_change_checksum(checksum);
4315   graph()->set_use_optimistic_licm(
4316       !type_info->matches_inlined_type_change_checksum(composite_checksum));
4317   type_info->set_inlined_type_change_checksum(composite_checksum);
4318
4319   // Perform any necessary OSR-specific cleanups or changes to the graph.
4320   osr()->FinishGraph();
4321
4322   return true;
4323 }
4324
4325
4326 bool HGraph::Optimize(BailoutReason* bailout_reason) {
4327   OrderBlocks();
4328   AssignDominators();
4329
4330   // We need to create a HConstant "zero" now so that GVN will fold every
4331   // zero-valued constant in the graph together.
4332   // The constant is needed to make idef-based bounds check work: the pass
4333   // evaluates relations with "zero" and that zero cannot be created after GVN.
4334   GetConstant0();
4335
4336 #ifdef DEBUG
4337   // Do a full verify after building the graph and computing dominators.
4338   Verify(true);
4339 #endif
4340
4341   if (FLAG_analyze_environment_liveness && maximum_environment_size() != 0) {
4342     Run<HEnvironmentLivenessAnalysisPhase>();
4343   }
4344
4345   if (!CheckConstPhiUses()) {
4346     *bailout_reason = kUnsupportedPhiUseOfConstVariable;
4347     return false;
4348   }
4349   Run<HRedundantPhiEliminationPhase>();
4350   if (!CheckArgumentsPhiUses()) {
4351     *bailout_reason = kUnsupportedPhiUseOfArguments;
4352     return false;
4353   }
4354
4355   // Find and mark unreachable code to simplify optimizations, especially gvn,
4356   // where unreachable code could unnecessarily defeat LICM.
4357   Run<HMarkUnreachableBlocksPhase>();
4358
4359   if (FLAG_dead_code_elimination) Run<HDeadCodeEliminationPhase>();
4360   if (FLAG_use_escape_analysis) Run<HEscapeAnalysisPhase>();
4361
4362   if (FLAG_load_elimination) Run<HLoadEliminationPhase>();
4363
4364   CollectPhis();
4365
4366   if (has_osr()) osr()->FinishOsrValues();
4367
4368   Run<HInferRepresentationPhase>();
4369
4370   // Remove HSimulate instructions that have turned out not to be needed
4371   // after all by folding them into the following HSimulate.
4372   // This must happen after inferring representations.
4373   Run<HMergeRemovableSimulatesPhase>();
4374
4375   Run<HMarkDeoptimizeOnUndefinedPhase>();
4376   Run<HRepresentationChangesPhase>();
4377
4378   Run<HInferTypesPhase>();
4379
4380   // Must be performed before canonicalization to ensure that Canonicalize
4381   // will not remove semantically meaningful ToInt32 operations e.g. BIT_OR with
4382   // zero.
4383   if (FLAG_opt_safe_uint32_operations) Run<HUint32AnalysisPhase>();
4384
4385   if (FLAG_use_canonicalizing) Run<HCanonicalizePhase>();
4386
4387   if (FLAG_use_gvn) Run<HGlobalValueNumberingPhase>();
4388
4389   if (FLAG_check_elimination) Run<HCheckEliminationPhase>();
4390
4391   if (FLAG_store_elimination) Run<HStoreEliminationPhase>();
4392
4393   Run<HRangeAnalysisPhase>();
4394
4395   Run<HComputeChangeUndefinedToNaN>();
4396
4397   // Eliminate redundant stack checks on backwards branches.
4398   Run<HStackCheckEliminationPhase>();
4399
4400   if (FLAG_array_bounds_checks_elimination) Run<HBoundsCheckEliminationPhase>();
4401   if (FLAG_array_bounds_checks_hoisting) Run<HBoundsCheckHoistingPhase>();
4402   if (FLAG_array_index_dehoisting) Run<HDehoistIndexComputationsPhase>();
4403   if (FLAG_dead_code_elimination) Run<HDeadCodeEliminationPhase>();
4404
4405   RestoreActualValues();
4406
4407   // Find unreachable code a second time, GVN and other optimizations may have
4408   // made blocks unreachable that were previously reachable.
4409   Run<HMarkUnreachableBlocksPhase>();
4410
4411   return true;
4412 }
4413
4414
4415 void HGraph::RestoreActualValues() {
4416   HPhase phase("H_Restore actual values", this);
4417
4418   for (int block_index = 0; block_index < blocks()->length(); block_index++) {
4419     HBasicBlock* block = blocks()->at(block_index);
4420
4421 #ifdef DEBUG
4422     for (int i = 0; i < block->phis()->length(); i++) {
4423       HPhi* phi = block->phis()->at(i);
4424       DCHECK(phi->ActualValue() == phi);
4425     }
4426 #endif
4427
4428     for (HInstructionIterator it(block); !it.Done(); it.Advance()) {
4429       HInstruction* instruction = it.Current();
4430       if (instruction->ActualValue() == instruction) continue;
4431       if (instruction->CheckFlag(HValue::kIsDead)) {
4432         // The instruction was marked as deleted but left in the graph
4433         // as a control flow dependency point for subsequent
4434         // instructions.
4435         instruction->DeleteAndReplaceWith(instruction->ActualValue());
4436       } else {
4437         DCHECK(instruction->IsInformativeDefinition());
4438         if (instruction->IsPurelyInformativeDefinition()) {
4439           instruction->DeleteAndReplaceWith(instruction->RedefinedOperand());
4440         } else {
4441           instruction->ReplaceAllUsesWith(instruction->ActualValue());
4442         }
4443       }
4444     }
4445   }
4446 }
4447
4448
4449 void HOptimizedGraphBuilder::PushArgumentsFromEnvironment(int count) {
4450   ZoneList<HValue*> arguments(count, zone());
4451   for (int i = 0; i < count; ++i) {
4452     arguments.Add(Pop(), zone());
4453   }
4454
4455   HPushArguments* push_args = New<HPushArguments>();
4456   while (!arguments.is_empty()) {
4457     push_args->AddInput(arguments.RemoveLast());
4458   }
4459   AddInstruction(push_args);
4460 }
4461
4462
4463 template <class Instruction>
4464 HInstruction* HOptimizedGraphBuilder::PreProcessCall(Instruction* call) {
4465   PushArgumentsFromEnvironment(call->argument_count());
4466   return call;
4467 }
4468
4469
4470 void HOptimizedGraphBuilder::SetUpScope(Scope* scope) {
4471   // First special is HContext.
4472   HInstruction* context = Add<HContext>();
4473   environment()->BindContext(context);
4474
4475   // Create an arguments object containing the initial parameters.  Set the
4476   // initial values of parameters including "this" having parameter index 0.
4477   DCHECK_EQ(scope->num_parameters() + 1, environment()->parameter_count());
4478   HArgumentsObject* arguments_object =
4479       New<HArgumentsObject>(environment()->parameter_count());
4480   for (int i = 0; i < environment()->parameter_count(); ++i) {
4481     HInstruction* parameter = Add<HParameter>(i);
4482     arguments_object->AddArgument(parameter, zone());
4483     environment()->Bind(i, parameter);
4484   }
4485   AddInstruction(arguments_object);
4486   graph()->SetArgumentsObject(arguments_object);
4487
4488   HConstant* undefined_constant = graph()->GetConstantUndefined();
4489   // Initialize specials and locals to undefined.
4490   for (int i = environment()->parameter_count() + 1;
4491        i < environment()->length();
4492        ++i) {
4493     environment()->Bind(i, undefined_constant);
4494   }
4495
4496   // Handle the arguments and arguments shadow variables specially (they do
4497   // not have declarations).
4498   if (scope->arguments() != NULL) {
4499     if (!scope->arguments()->IsStackAllocated()) {
4500       return Bailout(kContextAllocatedArguments);
4501     }
4502
4503     environment()->Bind(scope->arguments(),
4504                         graph()->GetArgumentsObject());
4505   }
4506 }
4507
4508
4509 void HOptimizedGraphBuilder::VisitStatements(ZoneList<Statement*>* statements) {
4510   for (int i = 0; i < statements->length(); i++) {
4511     Statement* stmt = statements->at(i);
4512     CHECK_ALIVE(Visit(stmt));
4513     if (stmt->IsJump()) break;
4514   }
4515 }
4516
4517
4518 void HOptimizedGraphBuilder::VisitBlock(Block* stmt) {
4519   DCHECK(!HasStackOverflow());
4520   DCHECK(current_block() != NULL);
4521   DCHECK(current_block()->HasPredecessor());
4522
4523   Scope* outer_scope = scope();
4524   Scope* scope = stmt->scope();
4525   BreakAndContinueInfo break_info(stmt, outer_scope);
4526
4527   { BreakAndContinueScope push(&break_info, this);
4528     if (scope != NULL) {
4529       // Load the function object.
4530       Scope* declaration_scope = scope->DeclarationScope();
4531       HInstruction* function;
4532       HValue* outer_context = environment()->context();
4533       if (declaration_scope->is_global_scope() ||
4534           declaration_scope->is_eval_scope()) {
4535         function = new(zone()) HLoadContextSlot(
4536             outer_context, Context::CLOSURE_INDEX, HLoadContextSlot::kNoCheck);
4537       } else {
4538         function = New<HThisFunction>();
4539       }
4540       AddInstruction(function);
4541       // Allocate a block context and store it to the stack frame.
4542       HInstruction* inner_context = Add<HAllocateBlockContext>(
4543           outer_context, function, scope->GetScopeInfo());
4544       HInstruction* instr = Add<HStoreFrameContext>(inner_context);
4545       if (instr->HasObservableSideEffects()) {
4546         AddSimulate(stmt->EntryId(), REMOVABLE_SIMULATE);
4547       }
4548       set_scope(scope);
4549       environment()->BindContext(inner_context);
4550       VisitDeclarations(scope->declarations());
4551       AddSimulate(stmt->DeclsId(), REMOVABLE_SIMULATE);
4552     }
4553     CHECK_BAILOUT(VisitStatements(stmt->statements()));
4554   }
4555   set_scope(outer_scope);
4556   if (scope != NULL && current_block() != NULL) {
4557     HValue* inner_context = environment()->context();
4558     HValue* outer_context = Add<HLoadNamedField>(
4559         inner_context, static_cast<HValue*>(NULL),
4560         HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX));
4561
4562     HInstruction* instr = Add<HStoreFrameContext>(outer_context);
4563     if (instr->HasObservableSideEffects()) {
4564       AddSimulate(stmt->ExitId(), REMOVABLE_SIMULATE);
4565     }
4566     environment()->BindContext(outer_context);
4567   }
4568   HBasicBlock* break_block = break_info.break_block();
4569   if (break_block != NULL) {
4570     if (current_block() != NULL) Goto(break_block);
4571     break_block->SetJoinId(stmt->ExitId());
4572     set_current_block(break_block);
4573   }
4574 }
4575
4576
4577 void HOptimizedGraphBuilder::VisitExpressionStatement(
4578     ExpressionStatement* stmt) {
4579   DCHECK(!HasStackOverflow());
4580   DCHECK(current_block() != NULL);
4581   DCHECK(current_block()->HasPredecessor());
4582   VisitForEffect(stmt->expression());
4583 }
4584
4585
4586 void HOptimizedGraphBuilder::VisitEmptyStatement(EmptyStatement* stmt) {
4587   DCHECK(!HasStackOverflow());
4588   DCHECK(current_block() != NULL);
4589   DCHECK(current_block()->HasPredecessor());
4590 }
4591
4592
4593 void HOptimizedGraphBuilder::VisitIfStatement(IfStatement* stmt) {
4594   DCHECK(!HasStackOverflow());
4595   DCHECK(current_block() != NULL);
4596   DCHECK(current_block()->HasPredecessor());
4597   if (stmt->condition()->ToBooleanIsTrue()) {
4598     Add<HSimulate>(stmt->ThenId());
4599     Visit(stmt->then_statement());
4600   } else if (stmt->condition()->ToBooleanIsFalse()) {
4601     Add<HSimulate>(stmt->ElseId());
4602     Visit(stmt->else_statement());
4603   } else {
4604     HBasicBlock* cond_true = graph()->CreateBasicBlock();
4605     HBasicBlock* cond_false = graph()->CreateBasicBlock();
4606     CHECK_BAILOUT(VisitForControl(stmt->condition(), cond_true, cond_false));
4607
4608     if (cond_true->HasPredecessor()) {
4609       cond_true->SetJoinId(stmt->ThenId());
4610       set_current_block(cond_true);
4611       CHECK_BAILOUT(Visit(stmt->then_statement()));
4612       cond_true = current_block();
4613     } else {
4614       cond_true = NULL;
4615     }
4616
4617     if (cond_false->HasPredecessor()) {
4618       cond_false->SetJoinId(stmt->ElseId());
4619       set_current_block(cond_false);
4620       CHECK_BAILOUT(Visit(stmt->else_statement()));
4621       cond_false = current_block();
4622     } else {
4623       cond_false = NULL;
4624     }
4625
4626     HBasicBlock* join = CreateJoin(cond_true, cond_false, stmt->IfId());
4627     set_current_block(join);
4628   }
4629 }
4630
4631
4632 HBasicBlock* HOptimizedGraphBuilder::BreakAndContinueScope::Get(
4633     BreakableStatement* stmt,
4634     BreakType type,
4635     Scope** scope,
4636     int* drop_extra) {
4637   *drop_extra = 0;
4638   BreakAndContinueScope* current = this;
4639   while (current != NULL && current->info()->target() != stmt) {
4640     *drop_extra += current->info()->drop_extra();
4641     current = current->next();
4642   }
4643   DCHECK(current != NULL);  // Always found (unless stack is malformed).
4644   *scope = current->info()->scope();
4645
4646   if (type == BREAK) {
4647     *drop_extra += current->info()->drop_extra();
4648   }
4649
4650   HBasicBlock* block = NULL;
4651   switch (type) {
4652     case BREAK:
4653       block = current->info()->break_block();
4654       if (block == NULL) {
4655         block = current->owner()->graph()->CreateBasicBlock();
4656         current->info()->set_break_block(block);
4657       }
4658       break;
4659
4660     case CONTINUE:
4661       block = current->info()->continue_block();
4662       if (block == NULL) {
4663         block = current->owner()->graph()->CreateBasicBlock();
4664         current->info()->set_continue_block(block);
4665       }
4666       break;
4667   }
4668
4669   return block;
4670 }
4671
4672
4673 void HOptimizedGraphBuilder::VisitContinueStatement(
4674     ContinueStatement* stmt) {
4675   DCHECK(!HasStackOverflow());
4676   DCHECK(current_block() != NULL);
4677   DCHECK(current_block()->HasPredecessor());
4678   Scope* outer_scope = NULL;
4679   Scope* inner_scope = scope();
4680   int drop_extra = 0;
4681   HBasicBlock* continue_block = break_scope()->Get(
4682       stmt->target(), BreakAndContinueScope::CONTINUE,
4683       &outer_scope, &drop_extra);
4684   HValue* context = environment()->context();
4685   Drop(drop_extra);
4686   int context_pop_count = inner_scope->ContextChainLength(outer_scope);
4687   if (context_pop_count > 0) {
4688     while (context_pop_count-- > 0) {
4689       HInstruction* context_instruction = Add<HLoadNamedField>(
4690           context, static_cast<HValue*>(NULL),
4691           HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX));
4692       context = context_instruction;
4693     }
4694     HInstruction* instr = Add<HStoreFrameContext>(context);
4695     if (instr->HasObservableSideEffects()) {
4696       AddSimulate(stmt->target()->EntryId(), REMOVABLE_SIMULATE);
4697     }
4698     environment()->BindContext(context);
4699   }
4700
4701   Goto(continue_block);
4702   set_current_block(NULL);
4703 }
4704
4705
4706 void HOptimizedGraphBuilder::VisitBreakStatement(BreakStatement* stmt) {
4707   DCHECK(!HasStackOverflow());
4708   DCHECK(current_block() != NULL);
4709   DCHECK(current_block()->HasPredecessor());
4710   Scope* outer_scope = NULL;
4711   Scope* inner_scope = scope();
4712   int drop_extra = 0;
4713   HBasicBlock* break_block = break_scope()->Get(
4714       stmt->target(), BreakAndContinueScope::BREAK,
4715       &outer_scope, &drop_extra);
4716   HValue* context = environment()->context();
4717   Drop(drop_extra);
4718   int context_pop_count = inner_scope->ContextChainLength(outer_scope);
4719   if (context_pop_count > 0) {
4720     while (context_pop_count-- > 0) {
4721       HInstruction* context_instruction = Add<HLoadNamedField>(
4722           context, static_cast<HValue*>(NULL),
4723           HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX));
4724       context = context_instruction;
4725     }
4726     HInstruction* instr = Add<HStoreFrameContext>(context);
4727     if (instr->HasObservableSideEffects()) {
4728       AddSimulate(stmt->target()->ExitId(), REMOVABLE_SIMULATE);
4729     }
4730     environment()->BindContext(context);
4731   }
4732   Goto(break_block);
4733   set_current_block(NULL);
4734 }
4735
4736
4737 void HOptimizedGraphBuilder::VisitReturnStatement(ReturnStatement* stmt) {
4738   DCHECK(!HasStackOverflow());
4739   DCHECK(current_block() != NULL);
4740   DCHECK(current_block()->HasPredecessor());
4741   FunctionState* state = function_state();
4742   AstContext* context = call_context();
4743   if (context == NULL) {
4744     // Not an inlined return, so an actual one.
4745     CHECK_ALIVE(VisitForValue(stmt->expression()));
4746     HValue* result = environment()->Pop();
4747     Add<HReturn>(result);
4748   } else if (state->inlining_kind() == CONSTRUCT_CALL_RETURN) {
4749     // Return from an inlined construct call. In a test context the return value
4750     // will always evaluate to true, in a value context the return value needs
4751     // to be a JSObject.
4752     if (context->IsTest()) {
4753       TestContext* test = TestContext::cast(context);
4754       CHECK_ALIVE(VisitForEffect(stmt->expression()));
4755       Goto(test->if_true(), state);
4756     } else if (context->IsEffect()) {
4757       CHECK_ALIVE(VisitForEffect(stmt->expression()));
4758       Goto(function_return(), state);
4759     } else {
4760       DCHECK(context->IsValue());
4761       CHECK_ALIVE(VisitForValue(stmt->expression()));
4762       HValue* return_value = Pop();
4763       HValue* receiver = environment()->arguments_environment()->Lookup(0);
4764       HHasInstanceTypeAndBranch* typecheck =
4765           New<HHasInstanceTypeAndBranch>(return_value,
4766                                          FIRST_SPEC_OBJECT_TYPE,
4767                                          LAST_SPEC_OBJECT_TYPE);
4768       HBasicBlock* if_spec_object = graph()->CreateBasicBlock();
4769       HBasicBlock* not_spec_object = graph()->CreateBasicBlock();
4770       typecheck->SetSuccessorAt(0, if_spec_object);
4771       typecheck->SetSuccessorAt(1, not_spec_object);
4772       FinishCurrentBlock(typecheck);
4773       AddLeaveInlined(if_spec_object, return_value, state);
4774       AddLeaveInlined(not_spec_object, receiver, state);
4775     }
4776   } else if (state->inlining_kind() == SETTER_CALL_RETURN) {
4777     // Return from an inlined setter call. The returned value is never used, the
4778     // value of an assignment is always the value of the RHS of the assignment.
4779     CHECK_ALIVE(VisitForEffect(stmt->expression()));
4780     if (context->IsTest()) {
4781       HValue* rhs = environment()->arguments_environment()->Lookup(1);
4782       context->ReturnValue(rhs);
4783     } else if (context->IsEffect()) {
4784       Goto(function_return(), state);
4785     } else {
4786       DCHECK(context->IsValue());
4787       HValue* rhs = environment()->arguments_environment()->Lookup(1);
4788       AddLeaveInlined(rhs, state);
4789     }
4790   } else {
4791     // Return from a normal inlined function. Visit the subexpression in the
4792     // expression context of the call.
4793     if (context->IsTest()) {
4794       TestContext* test = TestContext::cast(context);
4795       VisitForControl(stmt->expression(), test->if_true(), test->if_false());
4796     } else if (context->IsEffect()) {
4797       // Visit in value context and ignore the result. This is needed to keep
4798       // environment in sync with full-codegen since some visitors (e.g.
4799       // VisitCountOperation) use the operand stack differently depending on
4800       // context.
4801       CHECK_ALIVE(VisitForValue(stmt->expression()));
4802       Pop();
4803       Goto(function_return(), state);
4804     } else {
4805       DCHECK(context->IsValue());
4806       CHECK_ALIVE(VisitForValue(stmt->expression()));
4807       AddLeaveInlined(Pop(), state);
4808     }
4809   }
4810   set_current_block(NULL);
4811 }
4812
4813
4814 void HOptimizedGraphBuilder::VisitWithStatement(WithStatement* stmt) {
4815   DCHECK(!HasStackOverflow());
4816   DCHECK(current_block() != NULL);
4817   DCHECK(current_block()->HasPredecessor());
4818   return Bailout(kWithStatement);
4819 }
4820
4821
4822 void HOptimizedGraphBuilder::VisitSwitchStatement(SwitchStatement* stmt) {
4823   DCHECK(!HasStackOverflow());
4824   DCHECK(current_block() != NULL);
4825   DCHECK(current_block()->HasPredecessor());
4826
4827   // We only optimize switch statements with a bounded number of clauses.
4828   const int kCaseClauseLimit = 128;
4829   ZoneList<CaseClause*>* clauses = stmt->cases();
4830   int clause_count = clauses->length();
4831   ZoneList<HBasicBlock*> body_blocks(clause_count, zone());
4832   if (clause_count > kCaseClauseLimit) {
4833     return Bailout(kSwitchStatementTooManyClauses);
4834   }
4835
4836   CHECK_ALIVE(VisitForValue(stmt->tag()));
4837   Add<HSimulate>(stmt->EntryId());
4838   HValue* tag_value = Top();
4839   Type* tag_type = stmt->tag()->bounds().lower;
4840
4841   // 1. Build all the tests, with dangling true branches
4842   BailoutId default_id = BailoutId::None();
4843   for (int i = 0; i < clause_count; ++i) {
4844     CaseClause* clause = clauses->at(i);
4845     if (clause->is_default()) {
4846       body_blocks.Add(NULL, zone());
4847       if (default_id.IsNone()) default_id = clause->EntryId();
4848       continue;
4849     }
4850
4851     // Generate a compare and branch.
4852     CHECK_ALIVE(VisitForValue(clause->label()));
4853     HValue* label_value = Pop();
4854
4855     Type* label_type = clause->label()->bounds().lower;
4856     Type* combined_type = clause->compare_type();
4857     HControlInstruction* compare = BuildCompareInstruction(
4858         Token::EQ_STRICT, tag_value, label_value, tag_type, label_type,
4859         combined_type,
4860         ScriptPositionToSourcePosition(stmt->tag()->position()),
4861         ScriptPositionToSourcePosition(clause->label()->position()),
4862         PUSH_BEFORE_SIMULATE, clause->id());
4863
4864     HBasicBlock* next_test_block = graph()->CreateBasicBlock();
4865     HBasicBlock* body_block = graph()->CreateBasicBlock();
4866     body_blocks.Add(body_block, zone());
4867     compare->SetSuccessorAt(0, body_block);
4868     compare->SetSuccessorAt(1, next_test_block);
4869     FinishCurrentBlock(compare);
4870
4871     set_current_block(body_block);
4872     Drop(1);  // tag_value
4873
4874     set_current_block(next_test_block);
4875   }
4876
4877   // Save the current block to use for the default or to join with the
4878   // exit.
4879   HBasicBlock* last_block = current_block();
4880   Drop(1);  // tag_value
4881
4882   // 2. Loop over the clauses and the linked list of tests in lockstep,
4883   // translating the clause bodies.
4884   HBasicBlock* fall_through_block = NULL;
4885
4886   BreakAndContinueInfo break_info(stmt, scope());
4887   { BreakAndContinueScope push(&break_info, this);
4888     for (int i = 0; i < clause_count; ++i) {
4889       CaseClause* clause = clauses->at(i);
4890
4891       // Identify the block where normal (non-fall-through) control flow
4892       // goes to.
4893       HBasicBlock* normal_block = NULL;
4894       if (clause->is_default()) {
4895         if (last_block == NULL) continue;
4896         normal_block = last_block;
4897         last_block = NULL;  // Cleared to indicate we've handled it.
4898       } else {
4899         normal_block = body_blocks[i];
4900       }
4901
4902       if (fall_through_block == NULL) {
4903         set_current_block(normal_block);
4904       } else {
4905         HBasicBlock* join = CreateJoin(fall_through_block,
4906                                        normal_block,
4907                                        clause->EntryId());
4908         set_current_block(join);
4909       }
4910
4911       CHECK_BAILOUT(VisitStatements(clause->statements()));
4912       fall_through_block = current_block();
4913     }
4914   }
4915
4916   // Create an up-to-3-way join.  Use the break block if it exists since
4917   // it's already a join block.
4918   HBasicBlock* break_block = break_info.break_block();
4919   if (break_block == NULL) {
4920     set_current_block(CreateJoin(fall_through_block,
4921                                  last_block,
4922                                  stmt->ExitId()));
4923   } else {
4924     if (fall_through_block != NULL) Goto(fall_through_block, break_block);
4925     if (last_block != NULL) Goto(last_block, break_block);
4926     break_block->SetJoinId(stmt->ExitId());
4927     set_current_block(break_block);
4928   }
4929 }
4930
4931
4932 void HOptimizedGraphBuilder::VisitLoopBody(IterationStatement* stmt,
4933                                            HBasicBlock* loop_entry) {
4934   Add<HSimulate>(stmt->StackCheckId());
4935   HStackCheck* stack_check =
4936       HStackCheck::cast(Add<HStackCheck>(HStackCheck::kBackwardsBranch));
4937   DCHECK(loop_entry->IsLoopHeader());
4938   loop_entry->loop_information()->set_stack_check(stack_check);
4939   CHECK_BAILOUT(Visit(stmt->body()));
4940 }
4941
4942
4943 void HOptimizedGraphBuilder::VisitDoWhileStatement(DoWhileStatement* stmt) {
4944   DCHECK(!HasStackOverflow());
4945   DCHECK(current_block() != NULL);
4946   DCHECK(current_block()->HasPredecessor());
4947   DCHECK(current_block() != NULL);
4948   HBasicBlock* loop_entry = BuildLoopEntry(stmt);
4949
4950   BreakAndContinueInfo break_info(stmt, scope());
4951   {
4952     BreakAndContinueScope push(&break_info, this);
4953     CHECK_BAILOUT(VisitLoopBody(stmt, loop_entry));
4954   }
4955   HBasicBlock* body_exit =
4956       JoinContinue(stmt, current_block(), break_info.continue_block());
4957   HBasicBlock* loop_successor = NULL;
4958   if (body_exit != NULL && !stmt->cond()->ToBooleanIsTrue()) {
4959     set_current_block(body_exit);
4960     loop_successor = graph()->CreateBasicBlock();
4961     if (stmt->cond()->ToBooleanIsFalse()) {
4962       loop_entry->loop_information()->stack_check()->Eliminate();
4963       Goto(loop_successor);
4964       body_exit = NULL;
4965     } else {
4966       // The block for a true condition, the actual predecessor block of the
4967       // back edge.
4968       body_exit = graph()->CreateBasicBlock();
4969       CHECK_BAILOUT(VisitForControl(stmt->cond(), body_exit, loop_successor));
4970     }
4971     if (body_exit != NULL && body_exit->HasPredecessor()) {
4972       body_exit->SetJoinId(stmt->BackEdgeId());
4973     } else {
4974       body_exit = NULL;
4975     }
4976     if (loop_successor->HasPredecessor()) {
4977       loop_successor->SetJoinId(stmt->ExitId());
4978     } else {
4979       loop_successor = NULL;
4980     }
4981   }
4982   HBasicBlock* loop_exit = CreateLoop(stmt,
4983                                       loop_entry,
4984                                       body_exit,
4985                                       loop_successor,
4986                                       break_info.break_block());
4987   set_current_block(loop_exit);
4988 }
4989
4990
4991 void HOptimizedGraphBuilder::VisitWhileStatement(WhileStatement* stmt) {
4992   DCHECK(!HasStackOverflow());
4993   DCHECK(current_block() != NULL);
4994   DCHECK(current_block()->HasPredecessor());
4995   DCHECK(current_block() != NULL);
4996   HBasicBlock* loop_entry = BuildLoopEntry(stmt);
4997
4998   // If the condition is constant true, do not generate a branch.
4999   HBasicBlock* loop_successor = NULL;
5000   if (!stmt->cond()->ToBooleanIsTrue()) {
5001     HBasicBlock* body_entry = graph()->CreateBasicBlock();
5002     loop_successor = graph()->CreateBasicBlock();
5003     CHECK_BAILOUT(VisitForControl(stmt->cond(), body_entry, loop_successor));
5004     if (body_entry->HasPredecessor()) {
5005       body_entry->SetJoinId(stmt->BodyId());
5006       set_current_block(body_entry);
5007     }
5008     if (loop_successor->HasPredecessor()) {
5009       loop_successor->SetJoinId(stmt->ExitId());
5010     } else {
5011       loop_successor = NULL;
5012     }
5013   }
5014
5015   BreakAndContinueInfo break_info(stmt, scope());
5016   if (current_block() != NULL) {
5017     BreakAndContinueScope push(&break_info, this);
5018     CHECK_BAILOUT(VisitLoopBody(stmt, loop_entry));
5019   }
5020   HBasicBlock* body_exit =
5021       JoinContinue(stmt, current_block(), break_info.continue_block());
5022   HBasicBlock* loop_exit = CreateLoop(stmt,
5023                                       loop_entry,
5024                                       body_exit,
5025                                       loop_successor,
5026                                       break_info.break_block());
5027   set_current_block(loop_exit);
5028 }
5029
5030
5031 void HOptimizedGraphBuilder::VisitForStatement(ForStatement* stmt) {
5032   DCHECK(!HasStackOverflow());
5033   DCHECK(current_block() != NULL);
5034   DCHECK(current_block()->HasPredecessor());
5035   if (stmt->init() != NULL) {
5036     CHECK_ALIVE(Visit(stmt->init()));
5037   }
5038   DCHECK(current_block() != NULL);
5039   HBasicBlock* loop_entry = BuildLoopEntry(stmt);
5040
5041   HBasicBlock* loop_successor = NULL;
5042   if (stmt->cond() != NULL) {
5043     HBasicBlock* body_entry = graph()->CreateBasicBlock();
5044     loop_successor = graph()->CreateBasicBlock();
5045     CHECK_BAILOUT(VisitForControl(stmt->cond(), body_entry, loop_successor));
5046     if (body_entry->HasPredecessor()) {
5047       body_entry->SetJoinId(stmt->BodyId());
5048       set_current_block(body_entry);
5049     }
5050     if (loop_successor->HasPredecessor()) {
5051       loop_successor->SetJoinId(stmt->ExitId());
5052     } else {
5053       loop_successor = NULL;
5054     }
5055   }
5056
5057   BreakAndContinueInfo break_info(stmt, scope());
5058   if (current_block() != NULL) {
5059     BreakAndContinueScope push(&break_info, this);
5060     CHECK_BAILOUT(VisitLoopBody(stmt, loop_entry));
5061   }
5062   HBasicBlock* body_exit =
5063       JoinContinue(stmt, current_block(), break_info.continue_block());
5064
5065   if (stmt->next() != NULL && body_exit != NULL) {
5066     set_current_block(body_exit);
5067     CHECK_BAILOUT(Visit(stmt->next()));
5068     body_exit = current_block();
5069   }
5070
5071   HBasicBlock* loop_exit = CreateLoop(stmt,
5072                                       loop_entry,
5073                                       body_exit,
5074                                       loop_successor,
5075                                       break_info.break_block());
5076   set_current_block(loop_exit);
5077 }
5078
5079
5080 void HOptimizedGraphBuilder::VisitForInStatement(ForInStatement* stmt) {
5081   DCHECK(!HasStackOverflow());
5082   DCHECK(current_block() != NULL);
5083   DCHECK(current_block()->HasPredecessor());
5084
5085   if (!FLAG_optimize_for_in) {
5086     return Bailout(kForInStatementOptimizationIsDisabled);
5087   }
5088
5089   if (stmt->for_in_type() != ForInStatement::FAST_FOR_IN) {
5090     return Bailout(kForInStatementIsNotFastCase);
5091   }
5092
5093   if (!stmt->each()->IsVariableProxy() ||
5094       !stmt->each()->AsVariableProxy()->var()->IsStackLocal()) {
5095     return Bailout(kForInStatementWithNonLocalEachVariable);
5096   }
5097
5098   Variable* each_var = stmt->each()->AsVariableProxy()->var();
5099
5100   CHECK_ALIVE(VisitForValue(stmt->enumerable()));
5101   HValue* enumerable = Top();  // Leave enumerable at the top.
5102
5103   HInstruction* map = Add<HForInPrepareMap>(enumerable);
5104   Add<HSimulate>(stmt->PrepareId());
5105
5106   HInstruction* array = Add<HForInCacheArray>(
5107       enumerable, map, DescriptorArray::kEnumCacheBridgeCacheIndex);
5108
5109   HInstruction* enum_length = Add<HMapEnumLength>(map);
5110
5111   HInstruction* start_index = Add<HConstant>(0);
5112
5113   Push(map);
5114   Push(array);
5115   Push(enum_length);
5116   Push(start_index);
5117
5118   HInstruction* index_cache = Add<HForInCacheArray>(
5119       enumerable, map, DescriptorArray::kEnumCacheBridgeIndicesCacheIndex);
5120   HForInCacheArray::cast(array)->set_index_cache(
5121       HForInCacheArray::cast(index_cache));
5122
5123   HBasicBlock* loop_entry = BuildLoopEntry(stmt);
5124
5125   HValue* index = environment()->ExpressionStackAt(0);
5126   HValue* limit = environment()->ExpressionStackAt(1);
5127
5128   // Check that we still have more keys.
5129   HCompareNumericAndBranch* compare_index =
5130       New<HCompareNumericAndBranch>(index, limit, Token::LT);
5131   compare_index->set_observed_input_representation(
5132       Representation::Smi(), Representation::Smi());
5133
5134   HBasicBlock* loop_body = graph()->CreateBasicBlock();
5135   HBasicBlock* loop_successor = graph()->CreateBasicBlock();
5136
5137   compare_index->SetSuccessorAt(0, loop_body);
5138   compare_index->SetSuccessorAt(1, loop_successor);
5139   FinishCurrentBlock(compare_index);
5140
5141   set_current_block(loop_successor);
5142   Drop(5);
5143
5144   set_current_block(loop_body);
5145
5146   HValue* key = Add<HLoadKeyed>(
5147       environment()->ExpressionStackAt(2),  // Enum cache.
5148       environment()->ExpressionStackAt(0),  // Iteration index.
5149       environment()->ExpressionStackAt(0),
5150       FAST_ELEMENTS);
5151
5152   // Check if the expected map still matches that of the enumerable.
5153   // If not just deoptimize.
5154   Add<HCheckMapValue>(environment()->ExpressionStackAt(4),
5155                       environment()->ExpressionStackAt(3));
5156
5157   Bind(each_var, key);
5158
5159   BreakAndContinueInfo break_info(stmt, scope(), 5);
5160   {
5161     BreakAndContinueScope push(&break_info, this);
5162     CHECK_BAILOUT(VisitLoopBody(stmt, loop_entry));
5163   }
5164
5165   HBasicBlock* body_exit =
5166       JoinContinue(stmt, current_block(), break_info.continue_block());
5167
5168   if (body_exit != NULL) {
5169     set_current_block(body_exit);
5170
5171     HValue* current_index = Pop();
5172     Push(AddUncasted<HAdd>(current_index, graph()->GetConstant1()));
5173     body_exit = current_block();
5174   }
5175
5176   HBasicBlock* loop_exit = CreateLoop(stmt,
5177                                       loop_entry,
5178                                       body_exit,
5179                                       loop_successor,
5180                                       break_info.break_block());
5181
5182   set_current_block(loop_exit);
5183 }
5184
5185
5186 void HOptimizedGraphBuilder::VisitForOfStatement(ForOfStatement* stmt) {
5187   DCHECK(!HasStackOverflow());
5188   DCHECK(current_block() != NULL);
5189   DCHECK(current_block()->HasPredecessor());
5190   return Bailout(kForOfStatement);
5191 }
5192
5193
5194 void HOptimizedGraphBuilder::VisitTryCatchStatement(TryCatchStatement* stmt) {
5195   DCHECK(!HasStackOverflow());
5196   DCHECK(current_block() != NULL);
5197   DCHECK(current_block()->HasPredecessor());
5198   return Bailout(kTryCatchStatement);
5199 }
5200
5201
5202 void HOptimizedGraphBuilder::VisitTryFinallyStatement(
5203     TryFinallyStatement* stmt) {
5204   DCHECK(!HasStackOverflow());
5205   DCHECK(current_block() != NULL);
5206   DCHECK(current_block()->HasPredecessor());
5207   return Bailout(kTryFinallyStatement);
5208 }
5209
5210
5211 void HOptimizedGraphBuilder::VisitDebuggerStatement(DebuggerStatement* stmt) {
5212   DCHECK(!HasStackOverflow());
5213   DCHECK(current_block() != NULL);
5214   DCHECK(current_block()->HasPredecessor());
5215   return Bailout(kDebuggerStatement);
5216 }
5217
5218
5219 void HOptimizedGraphBuilder::VisitCaseClause(CaseClause* clause) {
5220   UNREACHABLE();
5221 }
5222
5223
5224 void HOptimizedGraphBuilder::VisitFunctionLiteral(FunctionLiteral* expr) {
5225   DCHECK(!HasStackOverflow());
5226   DCHECK(current_block() != NULL);
5227   DCHECK(current_block()->HasPredecessor());
5228   Handle<SharedFunctionInfo> shared_info = expr->shared_info();
5229   if (shared_info.is_null()) {
5230     shared_info =
5231         Compiler::BuildFunctionInfo(expr, current_info()->script(), top_info());
5232   }
5233   // We also have a stack overflow if the recursive compilation did.
5234   if (HasStackOverflow()) return;
5235   HFunctionLiteral* instr =
5236       New<HFunctionLiteral>(shared_info, expr->pretenure());
5237   return ast_context()->ReturnInstruction(instr, expr->id());
5238 }
5239
5240
5241 void HOptimizedGraphBuilder::VisitNativeFunctionLiteral(
5242     NativeFunctionLiteral* expr) {
5243   DCHECK(!HasStackOverflow());
5244   DCHECK(current_block() != NULL);
5245   DCHECK(current_block()->HasPredecessor());
5246   return Bailout(kNativeFunctionLiteral);
5247 }
5248
5249
5250 void HOptimizedGraphBuilder::VisitConditional(Conditional* expr) {
5251   DCHECK(!HasStackOverflow());
5252   DCHECK(current_block() != NULL);
5253   DCHECK(current_block()->HasPredecessor());
5254   HBasicBlock* cond_true = graph()->CreateBasicBlock();
5255   HBasicBlock* cond_false = graph()->CreateBasicBlock();
5256   CHECK_BAILOUT(VisitForControl(expr->condition(), cond_true, cond_false));
5257
5258   // Visit the true and false subexpressions in the same AST context as the
5259   // whole expression.
5260   if (cond_true->HasPredecessor()) {
5261     cond_true->SetJoinId(expr->ThenId());
5262     set_current_block(cond_true);
5263     CHECK_BAILOUT(Visit(expr->then_expression()));
5264     cond_true = current_block();
5265   } else {
5266     cond_true = NULL;
5267   }
5268
5269   if (cond_false->HasPredecessor()) {
5270     cond_false->SetJoinId(expr->ElseId());
5271     set_current_block(cond_false);
5272     CHECK_BAILOUT(Visit(expr->else_expression()));
5273     cond_false = current_block();
5274   } else {
5275     cond_false = NULL;
5276   }
5277
5278   if (!ast_context()->IsTest()) {
5279     HBasicBlock* join = CreateJoin(cond_true, cond_false, expr->id());
5280     set_current_block(join);
5281     if (join != NULL && !ast_context()->IsEffect()) {
5282       return ast_context()->ReturnValue(Pop());
5283     }
5284   }
5285 }
5286
5287
5288 HOptimizedGraphBuilder::GlobalPropertyAccess
5289     HOptimizedGraphBuilder::LookupGlobalProperty(
5290         Variable* var, LookupResult* lookup, PropertyAccessType access_type) {
5291   if (var->is_this() || !current_info()->has_global_object()) {
5292     return kUseGeneric;
5293   }
5294   Handle<GlobalObject> global(current_info()->global_object());
5295   global->Lookup(var->name(), lookup);
5296   if (!lookup->IsNormal() ||
5297       (access_type == STORE && lookup->IsReadOnly()) ||
5298       lookup->holder() != *global) {
5299     return kUseGeneric;
5300   }
5301
5302   return kUseCell;
5303 }
5304
5305
5306 HValue* HOptimizedGraphBuilder::BuildContextChainWalk(Variable* var) {
5307   DCHECK(var->IsContextSlot());
5308   HValue* context = environment()->context();
5309   int length = scope()->ContextChainLength(var->scope());
5310   while (length-- > 0) {
5311     context = Add<HLoadNamedField>(
5312         context, static_cast<HValue*>(NULL),
5313         HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX));
5314   }
5315   return context;
5316 }
5317
5318
5319 void HOptimizedGraphBuilder::VisitVariableProxy(VariableProxy* expr) {
5320   if (expr->is_this()) {
5321     current_info()->set_this_has_uses(true);
5322   }
5323
5324   DCHECK(!HasStackOverflow());
5325   DCHECK(current_block() != NULL);
5326   DCHECK(current_block()->HasPredecessor());
5327   Variable* variable = expr->var();
5328   switch (variable->location()) {
5329     case Variable::UNALLOCATED: {
5330       if (IsLexicalVariableMode(variable->mode())) {
5331         // TODO(rossberg): should this be an DCHECK?
5332         return Bailout(kReferenceToGlobalLexicalVariable);
5333       }
5334       // Handle known global constants like 'undefined' specially to avoid a
5335       // load from a global cell for them.
5336       Handle<Object> constant_value =
5337           isolate()->factory()->GlobalConstantFor(variable->name());
5338       if (!constant_value.is_null()) {
5339         HConstant* instr = New<HConstant>(constant_value);
5340         return ast_context()->ReturnInstruction(instr, expr->id());
5341       }
5342
5343       LookupResult lookup(isolate());
5344       GlobalPropertyAccess type = LookupGlobalProperty(variable, &lookup, LOAD);
5345
5346       if (type == kUseCell &&
5347           current_info()->global_object()->IsAccessCheckNeeded()) {
5348         type = kUseGeneric;
5349       }
5350
5351       if (type == kUseCell) {
5352         Handle<GlobalObject> global(current_info()->global_object());
5353         Handle<PropertyCell> cell(global->GetPropertyCell(&lookup));
5354         if (cell->type()->IsConstant()) {
5355           PropertyCell::AddDependentCompilationInfo(cell, top_info());
5356           Handle<Object> constant_object = cell->type()->AsConstant()->Value();
5357           if (constant_object->IsConsString()) {
5358             constant_object =
5359                 String::Flatten(Handle<String>::cast(constant_object));
5360           }
5361           HConstant* constant = New<HConstant>(constant_object);
5362           return ast_context()->ReturnInstruction(constant, expr->id());
5363         } else {
5364           HLoadGlobalCell* instr =
5365               New<HLoadGlobalCell>(cell, lookup.GetPropertyDetails());
5366           return ast_context()->ReturnInstruction(instr, expr->id());
5367         }
5368       } else {
5369         HValue* global_object = Add<HLoadNamedField>(
5370             context(), static_cast<HValue*>(NULL),
5371             HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
5372         HLoadGlobalGeneric* instr =
5373             New<HLoadGlobalGeneric>(global_object,
5374                                     variable->name(),
5375                                     ast_context()->is_for_typeof());
5376         if (FLAG_vector_ics) {
5377           Handle<SharedFunctionInfo> current_shared =
5378               function_state()->compilation_info()->shared_info();
5379           instr->SetVectorAndSlot(
5380               handle(current_shared->feedback_vector(), isolate()),
5381               expr->VariableFeedbackSlot());
5382         }
5383         return ast_context()->ReturnInstruction(instr, expr->id());
5384       }
5385     }
5386
5387     case Variable::PARAMETER:
5388     case Variable::LOCAL: {
5389       HValue* value = LookupAndMakeLive(variable);
5390       if (value == graph()->GetConstantHole()) {
5391         DCHECK(IsDeclaredVariableMode(variable->mode()) &&
5392                variable->mode() != VAR);
5393         return Bailout(kReferenceToUninitializedVariable);
5394       }
5395       return ast_context()->ReturnValue(value);
5396     }
5397
5398     case Variable::CONTEXT: {
5399       HValue* context = BuildContextChainWalk(variable);
5400       HLoadContextSlot::Mode mode;
5401       switch (variable->mode()) {
5402         case LET:
5403         case CONST:
5404           mode = HLoadContextSlot::kCheckDeoptimize;
5405           break;
5406         case CONST_LEGACY:
5407           mode = HLoadContextSlot::kCheckReturnUndefined;
5408           break;
5409         default:
5410           mode = HLoadContextSlot::kNoCheck;
5411           break;
5412       }
5413       HLoadContextSlot* instr =
5414           new(zone()) HLoadContextSlot(context, variable->index(), mode);
5415       return ast_context()->ReturnInstruction(instr, expr->id());
5416     }
5417
5418     case Variable::LOOKUP:
5419       return Bailout(kReferenceToAVariableWhichRequiresDynamicLookup);
5420   }
5421 }
5422
5423
5424 void HOptimizedGraphBuilder::VisitLiteral(Literal* expr) {
5425   DCHECK(!HasStackOverflow());
5426   DCHECK(current_block() != NULL);
5427   DCHECK(current_block()->HasPredecessor());
5428   HConstant* instr = New<HConstant>(expr->value());
5429   return ast_context()->ReturnInstruction(instr, expr->id());
5430 }
5431
5432
5433 void HOptimizedGraphBuilder::VisitRegExpLiteral(RegExpLiteral* expr) {
5434   DCHECK(!HasStackOverflow());
5435   DCHECK(current_block() != NULL);
5436   DCHECK(current_block()->HasPredecessor());
5437   Handle<JSFunction> closure = function_state()->compilation_info()->closure();
5438   Handle<FixedArray> literals(closure->literals());
5439   HRegExpLiteral* instr = New<HRegExpLiteral>(literals,
5440                                               expr->pattern(),
5441                                               expr->flags(),
5442                                               expr->literal_index());
5443   return ast_context()->ReturnInstruction(instr, expr->id());
5444 }
5445
5446
5447 static bool CanInlinePropertyAccess(Type* type) {
5448   if (type->Is(Type::NumberOrString())) return true;
5449   if (!type->IsClass()) return false;
5450   Handle<Map> map = type->AsClass()->Map();
5451   return map->IsJSObjectMap() &&
5452       !map->is_dictionary_map() &&
5453       !map->has_named_interceptor();
5454 }
5455
5456
5457 // Determines whether the given array or object literal boilerplate satisfies
5458 // all limits to be considered for fast deep-copying and computes the total
5459 // size of all objects that are part of the graph.
5460 static bool IsFastLiteral(Handle<JSObject> boilerplate,
5461                           int max_depth,
5462                           int* max_properties) {
5463   if (boilerplate->map()->is_deprecated() &&
5464       !JSObject::TryMigrateInstance(boilerplate)) {
5465     return false;
5466   }
5467
5468   DCHECK(max_depth >= 0 && *max_properties >= 0);
5469   if (max_depth == 0) return false;
5470
5471   Isolate* isolate = boilerplate->GetIsolate();
5472   Handle<FixedArrayBase> elements(boilerplate->elements());
5473   if (elements->length() > 0 &&
5474       elements->map() != isolate->heap()->fixed_cow_array_map()) {
5475     if (boilerplate->HasFastObjectElements()) {
5476       Handle<FixedArray> fast_elements = Handle<FixedArray>::cast(elements);
5477       int length = elements->length();
5478       for (int i = 0; i < length; i++) {
5479         if ((*max_properties)-- == 0) return false;
5480         Handle<Object> value(fast_elements->get(i), isolate);
5481         if (value->IsJSObject()) {
5482           Handle<JSObject> value_object = Handle<JSObject>::cast(value);
5483           if (!IsFastLiteral(value_object,
5484                              max_depth - 1,
5485                              max_properties)) {
5486             return false;
5487           }
5488         }
5489       }
5490     } else if (!boilerplate->HasFastDoubleElements()) {
5491       return false;
5492     }
5493   }
5494
5495   Handle<FixedArray> properties(boilerplate->properties());
5496   if (properties->length() > 0) {
5497     return false;
5498   } else {
5499     Handle<DescriptorArray> descriptors(
5500         boilerplate->map()->instance_descriptors());
5501     int limit = boilerplate->map()->NumberOfOwnDescriptors();
5502     for (int i = 0; i < limit; i++) {
5503       PropertyDetails details = descriptors->GetDetails(i);
5504       if (details.type() != FIELD) continue;
5505       int index = descriptors->GetFieldIndex(i);
5506       if ((*max_properties)-- == 0) return false;
5507       Handle<Object> value(boilerplate->InObjectPropertyAt(index), isolate);
5508       if (value->IsJSObject()) {
5509         Handle<JSObject> value_object = Handle<JSObject>::cast(value);
5510         if (!IsFastLiteral(value_object,
5511                            max_depth - 1,
5512                            max_properties)) {
5513           return false;
5514         }
5515       }
5516     }
5517   }
5518   return true;
5519 }
5520
5521
5522 void HOptimizedGraphBuilder::VisitObjectLiteral(ObjectLiteral* expr) {
5523   DCHECK(!HasStackOverflow());
5524   DCHECK(current_block() != NULL);
5525   DCHECK(current_block()->HasPredecessor());
5526   expr->BuildConstantProperties(isolate());
5527   Handle<JSFunction> closure = function_state()->compilation_info()->closure();
5528   HInstruction* literal;
5529
5530   // Check whether to use fast or slow deep-copying for boilerplate.
5531   int max_properties = kMaxFastLiteralProperties;
5532   Handle<Object> literals_cell(closure->literals()->get(expr->literal_index()),
5533                                isolate());
5534   Handle<AllocationSite> site;
5535   Handle<JSObject> boilerplate;
5536   if (!literals_cell->IsUndefined()) {
5537     // Retrieve the boilerplate
5538     site = Handle<AllocationSite>::cast(literals_cell);
5539     boilerplate = Handle<JSObject>(JSObject::cast(site->transition_info()),
5540                                    isolate());
5541   }
5542
5543   if (!boilerplate.is_null() &&
5544       IsFastLiteral(boilerplate, kMaxFastLiteralDepth, &max_properties)) {
5545     AllocationSiteUsageContext usage_context(isolate(), site, false);
5546     usage_context.EnterNewScope();
5547     literal = BuildFastLiteral(boilerplate, &usage_context);
5548     usage_context.ExitScope(site, boilerplate);
5549   } else {
5550     NoObservableSideEffectsScope no_effects(this);
5551     Handle<FixedArray> closure_literals(closure->literals(), isolate());
5552     Handle<FixedArray> constant_properties = expr->constant_properties();
5553     int literal_index = expr->literal_index();
5554     int flags = expr->fast_elements()
5555         ? ObjectLiteral::kFastElements : ObjectLiteral::kNoFlags;
5556     flags |= expr->has_function()
5557         ? ObjectLiteral::kHasFunction : ObjectLiteral::kNoFlags;
5558
5559     Add<HPushArguments>(Add<HConstant>(closure_literals),
5560                         Add<HConstant>(literal_index),
5561                         Add<HConstant>(constant_properties),
5562                         Add<HConstant>(flags));
5563
5564     // TODO(mvstanton): Add a flag to turn off creation of any
5565     // AllocationMementos for this call: we are in crankshaft and should have
5566     // learned enough about transition behavior to stop emitting mementos.
5567     Runtime::FunctionId function_id = Runtime::kCreateObjectLiteral;
5568     literal = Add<HCallRuntime>(isolate()->factory()->empty_string(),
5569                                 Runtime::FunctionForId(function_id),
5570                                 4);
5571   }
5572
5573   // The object is expected in the bailout environment during computation
5574   // of the property values and is the value of the entire expression.
5575   Push(literal);
5576
5577   expr->CalculateEmitStore(zone());
5578
5579   for (int i = 0; i < expr->properties()->length(); i++) {
5580     ObjectLiteral::Property* property = expr->properties()->at(i);
5581     if (property->IsCompileTimeValue()) continue;
5582
5583     Literal* key = property->key();
5584     Expression* value = property->value();
5585
5586     switch (property->kind()) {
5587       case ObjectLiteral::Property::MATERIALIZED_LITERAL:
5588         DCHECK(!CompileTimeValue::IsCompileTimeValue(value));
5589         // Fall through.
5590       case ObjectLiteral::Property::COMPUTED:
5591         if (key->value()->IsInternalizedString()) {
5592           if (property->emit_store()) {
5593             CHECK_ALIVE(VisitForValue(value));
5594             HValue* value = Pop();
5595             Handle<Map> map = property->GetReceiverType();
5596             Handle<String> name = property->key()->AsPropertyName();
5597             HInstruction* store;
5598             if (map.is_null()) {
5599               // If we don't know the monomorphic type, do a generic store.
5600               CHECK_ALIVE(store = BuildNamedGeneric(
5601                   STORE, NULL, literal, name, value));
5602             } else {
5603               PropertyAccessInfo info(this, STORE, ToType(map), name);
5604               if (info.CanAccessMonomorphic()) {
5605                 HValue* checked_literal = Add<HCheckMaps>(literal, map);
5606                 DCHECK(!info.lookup()->IsPropertyCallbacks());
5607                 store = BuildMonomorphicAccess(
5608                     &info, literal, checked_literal, value,
5609                     BailoutId::None(), BailoutId::None());
5610               } else {
5611                 CHECK_ALIVE(store = BuildNamedGeneric(
5612                     STORE, NULL, literal, name, value));
5613               }
5614             }
5615             AddInstruction(store);
5616             if (store->HasObservableSideEffects()) {
5617               Add<HSimulate>(key->id(), REMOVABLE_SIMULATE);
5618             }
5619           } else {
5620             CHECK_ALIVE(VisitForEffect(value));
5621           }
5622           break;
5623         }
5624         // Fall through.
5625       case ObjectLiteral::Property::PROTOTYPE:
5626       case ObjectLiteral::Property::SETTER:
5627       case ObjectLiteral::Property::GETTER:
5628         return Bailout(kObjectLiteralWithComplexProperty);
5629       default: UNREACHABLE();
5630     }
5631   }
5632
5633   if (expr->has_function()) {
5634     // Return the result of the transformation to fast properties
5635     // instead of the original since this operation changes the map
5636     // of the object. This makes sure that the original object won't
5637     // be used by other optimized code before it is transformed
5638     // (e.g. because of code motion).
5639     HToFastProperties* result = Add<HToFastProperties>(Pop());
5640     return ast_context()->ReturnValue(result);
5641   } else {
5642     return ast_context()->ReturnValue(Pop());
5643   }
5644 }
5645
5646
5647 void HOptimizedGraphBuilder::VisitArrayLiteral(ArrayLiteral* expr) {
5648   DCHECK(!HasStackOverflow());
5649   DCHECK(current_block() != NULL);
5650   DCHECK(current_block()->HasPredecessor());
5651   expr->BuildConstantElements(isolate());
5652   ZoneList<Expression*>* subexprs = expr->values();
5653   int length = subexprs->length();
5654   HInstruction* literal;
5655
5656   Handle<AllocationSite> site;
5657   Handle<FixedArray> literals(environment()->closure()->literals(), isolate());
5658   bool uninitialized = false;
5659   Handle<Object> literals_cell(literals->get(expr->literal_index()),
5660                                isolate());
5661   Handle<JSObject> boilerplate_object;
5662   if (literals_cell->IsUndefined()) {
5663     uninitialized = true;
5664     Handle<Object> raw_boilerplate;
5665     ASSIGN_RETURN_ON_EXCEPTION_VALUE(
5666         isolate(), raw_boilerplate,
5667         Runtime::CreateArrayLiteralBoilerplate(
5668             isolate(), literals, expr->constant_elements()),
5669         Bailout(kArrayBoilerplateCreationFailed));
5670
5671     boilerplate_object = Handle<JSObject>::cast(raw_boilerplate);
5672     AllocationSiteCreationContext creation_context(isolate());
5673     site = creation_context.EnterNewScope();
5674     if (JSObject::DeepWalk(boilerplate_object, &creation_context).is_null()) {
5675       return Bailout(kArrayBoilerplateCreationFailed);
5676     }
5677     creation_context.ExitScope(site, boilerplate_object);
5678     literals->set(expr->literal_index(), *site);
5679
5680     if (boilerplate_object->elements()->map() ==
5681         isolate()->heap()->fixed_cow_array_map()) {
5682       isolate()->counters()->cow_arrays_created_runtime()->Increment();
5683     }
5684   } else {
5685     DCHECK(literals_cell->IsAllocationSite());
5686     site = Handle<AllocationSite>::cast(literals_cell);
5687     boilerplate_object = Handle<JSObject>(
5688         JSObject::cast(site->transition_info()), isolate());
5689   }
5690
5691   DCHECK(!boilerplate_object.is_null());
5692   DCHECK(site->SitePointsToLiteral());
5693
5694   ElementsKind boilerplate_elements_kind =
5695       boilerplate_object->GetElementsKind();
5696
5697   // Check whether to use fast or slow deep-copying for boilerplate.
5698   int max_properties = kMaxFastLiteralProperties;
5699   if (IsFastLiteral(boilerplate_object,
5700                     kMaxFastLiteralDepth,
5701                     &max_properties)) {
5702     AllocationSiteUsageContext usage_context(isolate(), site, false);
5703     usage_context.EnterNewScope();
5704     literal = BuildFastLiteral(boilerplate_object, &usage_context);
5705     usage_context.ExitScope(site, boilerplate_object);
5706   } else {
5707     NoObservableSideEffectsScope no_effects(this);
5708     // Boilerplate already exists and constant elements are never accessed,
5709     // pass an empty fixed array to the runtime function instead.
5710     Handle<FixedArray> constants = isolate()->factory()->empty_fixed_array();
5711     int literal_index = expr->literal_index();
5712     int flags = expr->depth() == 1
5713         ? ArrayLiteral::kShallowElements
5714         : ArrayLiteral::kNoFlags;
5715     flags |= ArrayLiteral::kDisableMementos;
5716
5717     Add<HPushArguments>(Add<HConstant>(literals),
5718                         Add<HConstant>(literal_index),
5719                         Add<HConstant>(constants),
5720                         Add<HConstant>(flags));
5721
5722     // TODO(mvstanton): Consider a flag to turn off creation of any
5723     // AllocationMementos for this call: we are in crankshaft and should have
5724     // learned enough about transition behavior to stop emitting mementos.
5725     Runtime::FunctionId function_id = Runtime::kCreateArrayLiteral;
5726     literal = Add<HCallRuntime>(isolate()->factory()->empty_string(),
5727                                 Runtime::FunctionForId(function_id),
5728                                 4);
5729
5730     // De-opt if elements kind changed from boilerplate_elements_kind.
5731     Handle<Map> map = Handle<Map>(boilerplate_object->map(), isolate());
5732     literal = Add<HCheckMaps>(literal, map);
5733   }
5734
5735   // The array is expected in the bailout environment during computation
5736   // of the property values and is the value of the entire expression.
5737   Push(literal);
5738   // The literal index is on the stack, too.
5739   Push(Add<HConstant>(expr->literal_index()));
5740
5741   HInstruction* elements = NULL;
5742
5743   for (int i = 0; i < length; i++) {
5744     Expression* subexpr = subexprs->at(i);
5745     // If the subexpression is a literal or a simple materialized literal it
5746     // is already set in the cloned array.
5747     if (CompileTimeValue::IsCompileTimeValue(subexpr)) continue;
5748
5749     CHECK_ALIVE(VisitForValue(subexpr));
5750     HValue* value = Pop();
5751     if (!Smi::IsValid(i)) return Bailout(kNonSmiKeyInArrayLiteral);
5752
5753     elements = AddLoadElements(literal);
5754
5755     HValue* key = Add<HConstant>(i);
5756
5757     switch (boilerplate_elements_kind) {
5758       case FAST_SMI_ELEMENTS:
5759       case FAST_HOLEY_SMI_ELEMENTS:
5760       case FAST_ELEMENTS:
5761       case FAST_HOLEY_ELEMENTS:
5762       case FAST_DOUBLE_ELEMENTS:
5763       case FAST_HOLEY_DOUBLE_ELEMENTS: {
5764         HStoreKeyed* instr = Add<HStoreKeyed>(elements, key, value,
5765                                               boilerplate_elements_kind);
5766         instr->SetUninitialized(uninitialized);
5767         break;
5768       }
5769       default:
5770         UNREACHABLE();
5771         break;
5772     }
5773
5774     Add<HSimulate>(expr->GetIdForElement(i));
5775   }
5776
5777   Drop(1);  // array literal index
5778   return ast_context()->ReturnValue(Pop());
5779 }
5780
5781
5782 HCheckMaps* HOptimizedGraphBuilder::AddCheckMap(HValue* object,
5783                                                 Handle<Map> map) {
5784   BuildCheckHeapObject(object);
5785   return Add<HCheckMaps>(object, map);
5786 }
5787
5788
5789 HInstruction* HOptimizedGraphBuilder::BuildLoadNamedField(
5790     PropertyAccessInfo* info,
5791     HValue* checked_object) {
5792   // See if this is a load for an immutable property
5793   if (checked_object->ActualValue()->IsConstant() &&
5794       info->lookup()->IsCacheable() &&
5795       info->lookup()->IsReadOnly() && info->lookup()->IsDontDelete()) {
5796     Handle<Object> object(
5797         HConstant::cast(checked_object->ActualValue())->handle(isolate()));
5798
5799     if (object->IsJSObject()) {
5800       LookupResult lookup(isolate());
5801       Handle<JSObject>::cast(object)->Lookup(info->name(), &lookup);
5802       Handle<Object> value(lookup.GetLazyValue(), isolate());
5803
5804       DCHECK(!value->IsTheHole());
5805       return New<HConstant>(value);
5806     }
5807   }
5808
5809   HObjectAccess access = info->access();
5810   if (access.representation().IsDouble()) {
5811     // Load the heap number.
5812     checked_object = Add<HLoadNamedField>(
5813         checked_object, static_cast<HValue*>(NULL),
5814         access.WithRepresentation(Representation::Tagged()));
5815     // Load the double value from it.
5816     access = HObjectAccess::ForHeapNumberValue();
5817   }
5818
5819   SmallMapList* map_list = info->field_maps();
5820   if (map_list->length() == 0) {
5821     return New<HLoadNamedField>(checked_object, checked_object, access);
5822   }
5823
5824   UniqueSet<Map>* maps = new(zone()) UniqueSet<Map>(map_list->length(), zone());
5825   for (int i = 0; i < map_list->length(); ++i) {
5826     maps->Add(Unique<Map>::CreateImmovable(map_list->at(i)), zone());
5827   }
5828   return New<HLoadNamedField>(
5829       checked_object, checked_object, access, maps, info->field_type());
5830 }
5831
5832
5833 HInstruction* HOptimizedGraphBuilder::BuildStoreNamedField(
5834     PropertyAccessInfo* info,
5835     HValue* checked_object,
5836     HValue* value) {
5837   bool transition_to_field = info->lookup()->IsTransition();
5838   // TODO(verwaest): Move this logic into PropertyAccessInfo.
5839   HObjectAccess field_access = info->access();
5840
5841   HStoreNamedField *instr;
5842   if (field_access.representation().IsDouble()) {
5843     HObjectAccess heap_number_access =
5844         field_access.WithRepresentation(Representation::Tagged());
5845     if (transition_to_field) {
5846       // The store requires a mutable HeapNumber to be allocated.
5847       NoObservableSideEffectsScope no_side_effects(this);
5848       HInstruction* heap_number_size = Add<HConstant>(HeapNumber::kSize);
5849
5850       // TODO(hpayer): Allocation site pretenuring support.
5851       HInstruction* heap_number = Add<HAllocate>(heap_number_size,
5852           HType::HeapObject(),
5853           NOT_TENURED,
5854           MUTABLE_HEAP_NUMBER_TYPE);
5855       AddStoreMapConstant(
5856           heap_number, isolate()->factory()->mutable_heap_number_map());
5857       Add<HStoreNamedField>(heap_number, HObjectAccess::ForHeapNumberValue(),
5858                             value);
5859       instr = New<HStoreNamedField>(checked_object->ActualValue(),
5860                                     heap_number_access,
5861                                     heap_number);
5862     } else {
5863       // Already holds a HeapNumber; load the box and write its value field.
5864       HInstruction* heap_number = Add<HLoadNamedField>(
5865           checked_object, static_cast<HValue*>(NULL), heap_number_access);
5866       instr = New<HStoreNamedField>(heap_number,
5867                                     HObjectAccess::ForHeapNumberValue(),
5868                                     value, STORE_TO_INITIALIZED_ENTRY);
5869     }
5870   } else {
5871     if (field_access.representation().IsHeapObject()) {
5872       BuildCheckHeapObject(value);
5873     }
5874
5875     if (!info->field_maps()->is_empty()) {
5876       DCHECK(field_access.representation().IsHeapObject());
5877       value = Add<HCheckMaps>(value, info->field_maps());
5878     }
5879
5880     // This is a normal store.
5881     instr = New<HStoreNamedField>(
5882         checked_object->ActualValue(), field_access, value,
5883         transition_to_field ? INITIALIZING_STORE : STORE_TO_INITIALIZED_ENTRY);
5884   }
5885
5886   if (transition_to_field) {
5887     Handle<Map> transition(info->transition());
5888     DCHECK(!transition->is_deprecated());
5889     instr->SetTransition(Add<HConstant>(transition));
5890   }
5891   return instr;
5892 }
5893
5894
5895 bool HOptimizedGraphBuilder::PropertyAccessInfo::IsCompatible(
5896     PropertyAccessInfo* info) {
5897   if (!CanInlinePropertyAccess(type_)) return false;
5898
5899   // Currently only handle Type::Number as a polymorphic case.
5900   // TODO(verwaest): Support monomorphic handling of numbers with a HCheckNumber
5901   // instruction.
5902   if (type_->Is(Type::Number())) return false;
5903
5904   // Values are only compatible for monomorphic load if they all behave the same
5905   // regarding value wrappers.
5906   if (type_->Is(Type::NumberOrString())) {
5907     if (!info->type_->Is(Type::NumberOrString())) return false;
5908   } else {
5909     if (info->type_->Is(Type::NumberOrString())) return false;
5910   }
5911
5912   if (!LookupDescriptor()) return false;
5913
5914   if (!lookup_.IsFound()) {
5915     return (!info->lookup_.IsFound() || info->has_holder()) &&
5916         map()->prototype() == info->map()->prototype();
5917   }
5918
5919   // Mismatch if the other access info found the property in the prototype
5920   // chain.
5921   if (info->has_holder()) return false;
5922
5923   if (lookup_.IsPropertyCallbacks()) {
5924     return accessor_.is_identical_to(info->accessor_) &&
5925         api_holder_.is_identical_to(info->api_holder_);
5926   }
5927
5928   if (lookup_.IsConstant()) {
5929     return constant_.is_identical_to(info->constant_);
5930   }
5931
5932   DCHECK(lookup_.IsField());
5933   if (!info->lookup_.IsField()) return false;
5934
5935   Representation r = access_.representation();
5936   if (IsLoad()) {
5937     if (!info->access_.representation().IsCompatibleForLoad(r)) return false;
5938   } else {
5939     if (!info->access_.representation().IsCompatibleForStore(r)) return false;
5940   }
5941   if (info->access_.offset() != access_.offset()) return false;
5942   if (info->access_.IsInobject() != access_.IsInobject()) return false;
5943   if (IsLoad()) {
5944     if (field_maps_.is_empty()) {
5945       info->field_maps_.Clear();
5946     } else if (!info->field_maps_.is_empty()) {
5947       for (int i = 0; i < field_maps_.length(); ++i) {
5948         info->field_maps_.AddMapIfMissing(field_maps_.at(i), info->zone());
5949       }
5950       info->field_maps_.Sort();
5951     }
5952   } else {
5953     // We can only merge stores that agree on their field maps. The comparison
5954     // below is safe, since we keep the field maps sorted.
5955     if (field_maps_.length() != info->field_maps_.length()) return false;
5956     for (int i = 0; i < field_maps_.length(); ++i) {
5957       if (!field_maps_.at(i).is_identical_to(info->field_maps_.at(i))) {
5958         return false;
5959       }
5960     }
5961   }
5962   info->GeneralizeRepresentation(r);
5963   info->field_type_ = info->field_type_.Combine(field_type_);
5964   return true;
5965 }
5966
5967
5968 bool HOptimizedGraphBuilder::PropertyAccessInfo::LookupDescriptor() {
5969   if (!type_->IsClass()) return true;
5970   map()->LookupDescriptor(NULL, *name_, &lookup_);
5971   return LoadResult(map());
5972 }
5973
5974
5975 bool HOptimizedGraphBuilder::PropertyAccessInfo::LoadResult(Handle<Map> map) {
5976   if (!IsLoad() && lookup_.IsProperty() &&
5977       (lookup_.IsReadOnly() || !lookup_.IsCacheable())) {
5978     return false;
5979   }
5980
5981   if (lookup_.IsField()) {
5982     // Construct the object field access.
5983     access_ = HObjectAccess::ForField(map, &lookup_, name_);
5984
5985     // Load field map for heap objects.
5986     LoadFieldMaps(map);
5987   } else if (lookup_.IsPropertyCallbacks()) {
5988     Handle<Object> callback(lookup_.GetValueFromMap(*map), isolate());
5989     if (!callback->IsAccessorPair()) return false;
5990     Object* raw_accessor = IsLoad()
5991         ? Handle<AccessorPair>::cast(callback)->getter()
5992         : Handle<AccessorPair>::cast(callback)->setter();
5993     if (!raw_accessor->IsJSFunction()) return false;
5994     Handle<JSFunction> accessor = handle(JSFunction::cast(raw_accessor));
5995     if (accessor->shared()->IsApiFunction()) {
5996       CallOptimization call_optimization(accessor);
5997       if (call_optimization.is_simple_api_call()) {
5998         CallOptimization::HolderLookup holder_lookup;
5999         Handle<Map> receiver_map = this->map();
6000         api_holder_ = call_optimization.LookupHolderOfExpectedType(
6001             receiver_map, &holder_lookup);
6002       }
6003     }
6004     accessor_ = accessor;
6005   } else if (lookup_.IsConstant()) {
6006     constant_ = handle(lookup_.GetConstantFromMap(*map), isolate());
6007   }
6008
6009   return true;
6010 }
6011
6012
6013 void HOptimizedGraphBuilder::PropertyAccessInfo::LoadFieldMaps(
6014     Handle<Map> map) {
6015   // Clear any previously collected field maps/type.
6016   field_maps_.Clear();
6017   field_type_ = HType::Tagged();
6018
6019   // Figure out the field type from the accessor map.
6020   Handle<HeapType> field_type(lookup_.GetFieldTypeFromMap(*map), isolate());
6021
6022   // Collect the (stable) maps from the field type.
6023   int num_field_maps = field_type->NumClasses();
6024   if (num_field_maps == 0) return;
6025   DCHECK(access_.representation().IsHeapObject());
6026   field_maps_.Reserve(num_field_maps, zone());
6027   HeapType::Iterator<Map> it = field_type->Classes();
6028   while (!it.Done()) {
6029     Handle<Map> field_map = it.Current();
6030     if (!field_map->is_stable()) {
6031       field_maps_.Clear();
6032       return;
6033     }
6034     field_maps_.Add(field_map, zone());
6035     it.Advance();
6036   }
6037   field_maps_.Sort();
6038   DCHECK_EQ(num_field_maps, field_maps_.length());
6039
6040   // Determine field HType from field HeapType.
6041   field_type_ = HType::FromType<HeapType>(field_type);
6042   DCHECK(field_type_.IsHeapObject());
6043
6044   // Add dependency on the map that introduced the field.
6045   Map::AddDependentCompilationInfo(
6046       handle(lookup_.GetFieldOwnerFromMap(*map), isolate()),
6047       DependentCode::kFieldTypeGroup, top_info());
6048 }
6049
6050
6051 bool HOptimizedGraphBuilder::PropertyAccessInfo::LookupInPrototypes() {
6052   Handle<Map> map = this->map();
6053
6054   while (map->prototype()->IsJSObject()) {
6055     holder_ = handle(JSObject::cast(map->prototype()));
6056     if (holder_->map()->is_deprecated()) {
6057       JSObject::TryMigrateInstance(holder_);
6058     }
6059     map = Handle<Map>(holder_->map());
6060     if (!CanInlinePropertyAccess(ToType(map))) {
6061       lookup_.NotFound();
6062       return false;
6063     }
6064     map->LookupDescriptor(*holder_, *name_, &lookup_);
6065     if (lookup_.IsFound()) return LoadResult(map);
6066   }
6067   lookup_.NotFound();
6068   return true;
6069 }
6070
6071
6072 bool HOptimizedGraphBuilder::PropertyAccessInfo::CanAccessMonomorphic() {
6073   if (!CanInlinePropertyAccess(type_)) return false;
6074   if (IsJSObjectFieldAccessor()) return IsLoad();
6075   if (this->map()->function_with_prototype() &&
6076       !this->map()->has_non_instance_prototype() &&
6077       name_.is_identical_to(isolate()->factory()->prototype_string())) {
6078     return IsLoad();
6079   }
6080   if (!LookupDescriptor()) return false;
6081   if (lookup_.IsFound()) {
6082     if (IsLoad()) return true;
6083     return !lookup_.IsReadOnly() && lookup_.IsCacheable();
6084   }
6085   if (!LookupInPrototypes()) return false;
6086   if (IsLoad()) return true;
6087
6088   if (lookup_.IsPropertyCallbacks()) return true;
6089   Handle<Map> map = this->map();
6090   map->LookupTransition(NULL, *name_, &lookup_);
6091   if (lookup_.IsTransitionToField() && map->unused_property_fields() > 0) {
6092     // Construct the object field access.
6093     access_ = HObjectAccess::ForField(map, &lookup_, name_);
6094
6095     // Load field map for heap objects.
6096     LoadFieldMaps(transition());
6097     return true;
6098   }
6099   return false;
6100 }
6101
6102
6103 bool HOptimizedGraphBuilder::PropertyAccessInfo::CanAccessAsMonomorphic(
6104     SmallMapList* types) {
6105   DCHECK(type_->Is(ToType(types->first())));
6106   if (!CanAccessMonomorphic()) return false;
6107   STATIC_ASSERT(kMaxLoadPolymorphism == kMaxStorePolymorphism);
6108   if (types->length() > kMaxLoadPolymorphism) return false;
6109
6110   HObjectAccess access = HObjectAccess::ForMap();  // bogus default
6111   if (GetJSObjectFieldAccess(&access)) {
6112     for (int i = 1; i < types->length(); ++i) {
6113       PropertyAccessInfo test_info(
6114           builder_, access_type_, ToType(types->at(i)), name_);
6115       HObjectAccess test_access = HObjectAccess::ForMap();  // bogus default
6116       if (!test_info.GetJSObjectFieldAccess(&test_access)) return false;
6117       if (!access.Equals(test_access)) return false;
6118     }
6119     return true;
6120   }
6121
6122   // Currently only handle Type::Number as a polymorphic case.
6123   // TODO(verwaest): Support monomorphic handling of numbers with a HCheckNumber
6124   // instruction.
6125   if (type_->Is(Type::Number())) return false;
6126
6127   // Multiple maps cannot transition to the same target map.
6128   DCHECK(!IsLoad() || !lookup_.IsTransition());
6129   if (lookup_.IsTransition() && types->length() > 1) return false;
6130
6131   for (int i = 1; i < types->length(); ++i) {
6132     PropertyAccessInfo test_info(
6133         builder_, access_type_, ToType(types->at(i)), name_);
6134     if (!test_info.IsCompatible(this)) return false;
6135   }
6136
6137   return true;
6138 }
6139
6140
6141 Handle<Map> HOptimizedGraphBuilder::PropertyAccessInfo::map() {
6142   JSFunction* ctor = IC::GetRootConstructor(
6143       type_, current_info()->closure()->context()->native_context());
6144   if (ctor != NULL) return handle(ctor->initial_map());
6145   return type_->AsClass()->Map();
6146 }
6147
6148
6149 static bool NeedsWrappingFor(Type* type, Handle<JSFunction> target) {
6150   return type->Is(Type::NumberOrString()) &&
6151       target->shared()->strict_mode() == SLOPPY &&
6152       !target->shared()->native();
6153 }
6154
6155
6156 HInstruction* HOptimizedGraphBuilder::BuildMonomorphicAccess(
6157     PropertyAccessInfo* info,
6158     HValue* object,
6159     HValue* checked_object,
6160     HValue* value,
6161     BailoutId ast_id,
6162     BailoutId return_id,
6163     bool can_inline_accessor) {
6164
6165   HObjectAccess access = HObjectAccess::ForMap();  // bogus default
6166   if (info->GetJSObjectFieldAccess(&access)) {
6167     DCHECK(info->IsLoad());
6168     return New<HLoadNamedField>(object, checked_object, access);
6169   }
6170
6171   if (info->name().is_identical_to(isolate()->factory()->prototype_string()) &&
6172       info->map()->function_with_prototype()) {
6173     DCHECK(!info->map()->has_non_instance_prototype());
6174     return New<HLoadFunctionPrototype>(checked_object);
6175   }
6176
6177   HValue* checked_holder = checked_object;
6178   if (info->has_holder()) {
6179     Handle<JSObject> prototype(JSObject::cast(info->map()->prototype()));
6180     checked_holder = BuildCheckPrototypeMaps(prototype, info->holder());
6181   }
6182
6183   if (!info->lookup()->IsFound()) {
6184     DCHECK(info->IsLoad());
6185     return graph()->GetConstantUndefined();
6186   }
6187
6188   if (info->lookup()->IsField()) {
6189     if (info->IsLoad()) {
6190       return BuildLoadNamedField(info, checked_holder);
6191     } else {
6192       return BuildStoreNamedField(info, checked_object, value);
6193     }
6194   }
6195
6196   if (info->lookup()->IsTransition()) {
6197     DCHECK(!info->IsLoad());
6198     return BuildStoreNamedField(info, checked_object, value);
6199   }
6200
6201   if (info->lookup()->IsPropertyCallbacks()) {
6202     Push(checked_object);
6203     int argument_count = 1;
6204     if (!info->IsLoad()) {
6205       argument_count = 2;
6206       Push(value);
6207     }
6208
6209     if (NeedsWrappingFor(info->type(), info->accessor())) {
6210       HValue* function = Add<HConstant>(info->accessor());
6211       PushArgumentsFromEnvironment(argument_count);
6212       return New<HCallFunction>(function, argument_count, WRAP_AND_CALL);
6213     } else if (FLAG_inline_accessors && can_inline_accessor) {
6214       bool success = info->IsLoad()
6215           ? TryInlineGetter(info->accessor(), info->map(), ast_id, return_id)
6216           : TryInlineSetter(
6217               info->accessor(), info->map(), ast_id, return_id, value);
6218       if (success || HasStackOverflow()) return NULL;
6219     }
6220
6221     PushArgumentsFromEnvironment(argument_count);
6222     return BuildCallConstantFunction(info->accessor(), argument_count);
6223   }
6224
6225   DCHECK(info->lookup()->IsConstant());
6226   if (info->IsLoad()) {
6227     return New<HConstant>(info->constant());
6228   } else {
6229     return New<HCheckValue>(value, Handle<JSFunction>::cast(info->constant()));
6230   }
6231 }
6232
6233
6234 void HOptimizedGraphBuilder::HandlePolymorphicNamedFieldAccess(
6235     PropertyAccessType access_type,
6236     Expression* expr,
6237     BailoutId ast_id,
6238     BailoutId return_id,
6239     HValue* object,
6240     HValue* value,
6241     SmallMapList* types,
6242     Handle<String> name) {
6243   // Something did not match; must use a polymorphic load.
6244   int count = 0;
6245   HBasicBlock* join = NULL;
6246   HBasicBlock* number_block = NULL;
6247   bool handled_string = false;
6248
6249   bool handle_smi = false;
6250   STATIC_ASSERT(kMaxLoadPolymorphism == kMaxStorePolymorphism);
6251   for (int i = 0; i < types->length() && count < kMaxLoadPolymorphism; ++i) {
6252     PropertyAccessInfo info(this, access_type, ToType(types->at(i)), name);
6253     if (info.type()->Is(Type::String())) {
6254       if (handled_string) continue;
6255       handled_string = true;
6256     }
6257     if (info.CanAccessMonomorphic()) {
6258       count++;
6259       if (info.type()->Is(Type::Number())) {
6260         handle_smi = true;
6261         break;
6262       }
6263     }
6264   }
6265
6266   count = 0;
6267   HControlInstruction* smi_check = NULL;
6268   handled_string = false;
6269
6270   for (int i = 0; i < types->length() && count < kMaxLoadPolymorphism; ++i) {
6271     PropertyAccessInfo info(this, access_type, ToType(types->at(i)), name);
6272     if (info.type()->Is(Type::String())) {
6273       if (handled_string) continue;
6274       handled_string = true;
6275     }
6276     if (!info.CanAccessMonomorphic()) continue;
6277
6278     if (count == 0) {
6279       join = graph()->CreateBasicBlock();
6280       if (handle_smi) {
6281         HBasicBlock* empty_smi_block = graph()->CreateBasicBlock();
6282         HBasicBlock* not_smi_block = graph()->CreateBasicBlock();
6283         number_block = graph()->CreateBasicBlock();
6284         smi_check = New<HIsSmiAndBranch>(
6285             object, empty_smi_block, not_smi_block);
6286         FinishCurrentBlock(smi_check);
6287         GotoNoSimulate(empty_smi_block, number_block);
6288         set_current_block(not_smi_block);
6289       } else {
6290         BuildCheckHeapObject(object);
6291       }
6292     }
6293     ++count;
6294     HBasicBlock* if_true = graph()->CreateBasicBlock();
6295     HBasicBlock* if_false = graph()->CreateBasicBlock();
6296     HUnaryControlInstruction* compare;
6297
6298     HValue* dependency;
6299     if (info.type()->Is(Type::Number())) {
6300       Handle<Map> heap_number_map = isolate()->factory()->heap_number_map();
6301       compare = New<HCompareMap>(object, heap_number_map, if_true, if_false);
6302       dependency = smi_check;
6303     } else if (info.type()->Is(Type::String())) {
6304       compare = New<HIsStringAndBranch>(object, if_true, if_false);
6305       dependency = compare;
6306     } else {
6307       compare = New<HCompareMap>(object, info.map(), if_true, if_false);
6308       dependency = compare;
6309     }
6310     FinishCurrentBlock(compare);
6311
6312     if (info.type()->Is(Type::Number())) {
6313       GotoNoSimulate(if_true, number_block);
6314       if_true = number_block;
6315     }
6316
6317     set_current_block(if_true);
6318
6319     HInstruction* access = BuildMonomorphicAccess(
6320         &info, object, dependency, value, ast_id,
6321         return_id, FLAG_polymorphic_inlining);
6322
6323     HValue* result = NULL;
6324     switch (access_type) {
6325       case LOAD:
6326         result = access;
6327         break;
6328       case STORE:
6329         result = value;
6330         break;
6331     }
6332
6333     if (access == NULL) {
6334       if (HasStackOverflow()) return;
6335     } else {
6336       if (!access->IsLinked()) AddInstruction(access);
6337       if (!ast_context()->IsEffect()) Push(result);
6338     }
6339
6340     if (current_block() != NULL) Goto(join);
6341     set_current_block(if_false);
6342   }
6343
6344   // Finish up.  Unconditionally deoptimize if we've handled all the maps we
6345   // know about and do not want to handle ones we've never seen.  Otherwise
6346   // use a generic IC.
6347   if (count == types->length() && FLAG_deoptimize_uncommon_cases) {
6348     FinishExitWithHardDeoptimization("Uknown map in polymorphic access");
6349   } else {
6350     HInstruction* instr = BuildNamedGeneric(access_type, expr, object, name,
6351                                             value);
6352     AddInstruction(instr);
6353     if (!ast_context()->IsEffect()) Push(access_type == LOAD ? instr : value);
6354
6355     if (join != NULL) {
6356       Goto(join);
6357     } else {
6358       Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6359       if (!ast_context()->IsEffect()) ast_context()->ReturnValue(Pop());
6360       return;
6361     }
6362   }
6363
6364   DCHECK(join != NULL);
6365   if (join->HasPredecessor()) {
6366     join->SetJoinId(ast_id);
6367     set_current_block(join);
6368     if (!ast_context()->IsEffect()) ast_context()->ReturnValue(Pop());
6369   } else {
6370     set_current_block(NULL);
6371   }
6372 }
6373
6374
6375 static bool ComputeReceiverTypes(Expression* expr,
6376                                  HValue* receiver,
6377                                  SmallMapList** t,
6378                                  Zone* zone) {
6379   SmallMapList* types = expr->GetReceiverTypes();
6380   *t = types;
6381   bool monomorphic = expr->IsMonomorphic();
6382   if (types != NULL && receiver->HasMonomorphicJSObjectType()) {
6383     Map* root_map = receiver->GetMonomorphicJSObjectMap()->FindRootMap();
6384     types->FilterForPossibleTransitions(root_map);
6385     monomorphic = types->length() == 1;
6386   }
6387   return monomorphic && CanInlinePropertyAccess(
6388       IC::MapToType<Type>(types->first(), zone));
6389 }
6390
6391
6392 static bool AreStringTypes(SmallMapList* types) {
6393   for (int i = 0; i < types->length(); i++) {
6394     if (types->at(i)->instance_type() >= FIRST_NONSTRING_TYPE) return false;
6395   }
6396   return true;
6397 }
6398
6399
6400 void HOptimizedGraphBuilder::BuildStore(Expression* expr,
6401                                         Property* prop,
6402                                         BailoutId ast_id,
6403                                         BailoutId return_id,
6404                                         bool is_uninitialized) {
6405   if (!prop->key()->IsPropertyName()) {
6406     // Keyed store.
6407     HValue* value = environment()->ExpressionStackAt(0);
6408     HValue* key = environment()->ExpressionStackAt(1);
6409     HValue* object = environment()->ExpressionStackAt(2);
6410     bool has_side_effects = false;
6411     HandleKeyedElementAccess(object, key, value, expr,
6412                              STORE, &has_side_effects);
6413     Drop(3);
6414     Push(value);
6415     Add<HSimulate>(return_id, REMOVABLE_SIMULATE);
6416     return ast_context()->ReturnValue(Pop());
6417   }
6418
6419   // Named store.
6420   HValue* value = Pop();
6421   HValue* object = Pop();
6422
6423   Literal* key = prop->key()->AsLiteral();
6424   Handle<String> name = Handle<String>::cast(key->value());
6425   DCHECK(!name.is_null());
6426
6427   HInstruction* instr = BuildNamedAccess(STORE, ast_id, return_id, expr,
6428                                          object, name, value, is_uninitialized);
6429   if (instr == NULL) return;
6430
6431   if (!ast_context()->IsEffect()) Push(value);
6432   AddInstruction(instr);
6433   if (instr->HasObservableSideEffects()) {
6434     Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6435   }
6436   if (!ast_context()->IsEffect()) Drop(1);
6437   return ast_context()->ReturnValue(value);
6438 }
6439
6440
6441 void HOptimizedGraphBuilder::HandlePropertyAssignment(Assignment* expr) {
6442   Property* prop = expr->target()->AsProperty();
6443   DCHECK(prop != NULL);
6444   CHECK_ALIVE(VisitForValue(prop->obj()));
6445   if (!prop->key()->IsPropertyName()) {
6446     CHECK_ALIVE(VisitForValue(prop->key()));
6447   }
6448   CHECK_ALIVE(VisitForValue(expr->value()));
6449   BuildStore(expr, prop, expr->id(),
6450              expr->AssignmentId(), expr->IsUninitialized());
6451 }
6452
6453
6454 // Because not every expression has a position and there is not common
6455 // superclass of Assignment and CountOperation, we cannot just pass the
6456 // owning expression instead of position and ast_id separately.
6457 void HOptimizedGraphBuilder::HandleGlobalVariableAssignment(
6458     Variable* var,
6459     HValue* value,
6460     BailoutId ast_id) {
6461   LookupResult lookup(isolate());
6462   GlobalPropertyAccess type = LookupGlobalProperty(var, &lookup, STORE);
6463   if (type == kUseCell) {
6464     Handle<GlobalObject> global(current_info()->global_object());
6465     Handle<PropertyCell> cell(global->GetPropertyCell(&lookup));
6466     if (cell->type()->IsConstant()) {
6467       Handle<Object> constant = cell->type()->AsConstant()->Value();
6468       if (value->IsConstant()) {
6469         HConstant* c_value = HConstant::cast(value);
6470         if (!constant.is_identical_to(c_value->handle(isolate()))) {
6471           Add<HDeoptimize>("Constant global variable assignment",
6472                            Deoptimizer::EAGER);
6473         }
6474       } else {
6475         HValue* c_constant = Add<HConstant>(constant);
6476         IfBuilder builder(this);
6477         if (constant->IsNumber()) {
6478           builder.If<HCompareNumericAndBranch>(value, c_constant, Token::EQ);
6479         } else {
6480           builder.If<HCompareObjectEqAndBranch>(value, c_constant);
6481         }
6482         builder.Then();
6483         builder.Else();
6484         Add<HDeoptimize>("Constant global variable assignment",
6485                          Deoptimizer::EAGER);
6486         builder.End();
6487       }
6488     }
6489     HInstruction* instr =
6490         Add<HStoreGlobalCell>(value, cell, lookup.GetPropertyDetails());
6491     if (instr->HasObservableSideEffects()) {
6492       Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6493     }
6494   } else {
6495     HValue* global_object = Add<HLoadNamedField>(
6496         context(), static_cast<HValue*>(NULL),
6497         HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
6498     HStoreNamedGeneric* instr =
6499         Add<HStoreNamedGeneric>(global_object, var->name(),
6500                                  value, function_strict_mode());
6501     USE(instr);
6502     DCHECK(instr->HasObservableSideEffects());
6503     Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6504   }
6505 }
6506
6507
6508 void HOptimizedGraphBuilder::HandleCompoundAssignment(Assignment* expr) {
6509   Expression* target = expr->target();
6510   VariableProxy* proxy = target->AsVariableProxy();
6511   Property* prop = target->AsProperty();
6512   DCHECK(proxy == NULL || prop == NULL);
6513
6514   // We have a second position recorded in the FullCodeGenerator to have
6515   // type feedback for the binary operation.
6516   BinaryOperation* operation = expr->binary_operation();
6517
6518   if (proxy != NULL) {
6519     Variable* var = proxy->var();
6520     if (var->mode() == LET)  {
6521       return Bailout(kUnsupportedLetCompoundAssignment);
6522     }
6523
6524     CHECK_ALIVE(VisitForValue(operation));
6525
6526     switch (var->location()) {
6527       case Variable::UNALLOCATED:
6528         HandleGlobalVariableAssignment(var,
6529                                        Top(),
6530                                        expr->AssignmentId());
6531         break;
6532
6533       case Variable::PARAMETER:
6534       case Variable::LOCAL:
6535         if (var->mode() == CONST_LEGACY)  {
6536           return Bailout(kUnsupportedConstCompoundAssignment);
6537         }
6538         BindIfLive(var, Top());
6539         break;
6540
6541       case Variable::CONTEXT: {
6542         // Bail out if we try to mutate a parameter value in a function
6543         // using the arguments object.  We do not (yet) correctly handle the
6544         // arguments property of the function.
6545         if (current_info()->scope()->arguments() != NULL) {
6546           // Parameters will be allocated to context slots.  We have no
6547           // direct way to detect that the variable is a parameter so we do
6548           // a linear search of the parameter variables.
6549           int count = current_info()->scope()->num_parameters();
6550           for (int i = 0; i < count; ++i) {
6551             if (var == current_info()->scope()->parameter(i)) {
6552               Bailout(kAssignmentToParameterFunctionUsesArgumentsObject);
6553             }
6554           }
6555         }
6556
6557         HStoreContextSlot::Mode mode;
6558
6559         switch (var->mode()) {
6560           case LET:
6561             mode = HStoreContextSlot::kCheckDeoptimize;
6562             break;
6563           case CONST:
6564             // This case is checked statically so no need to
6565             // perform checks here
6566             UNREACHABLE();
6567           case CONST_LEGACY:
6568             return ast_context()->ReturnValue(Pop());
6569           default:
6570             mode = HStoreContextSlot::kNoCheck;
6571         }
6572
6573         HValue* context = BuildContextChainWalk(var);
6574         HStoreContextSlot* instr = Add<HStoreContextSlot>(
6575             context, var->index(), mode, Top());
6576         if (instr->HasObservableSideEffects()) {
6577           Add<HSimulate>(expr->AssignmentId(), REMOVABLE_SIMULATE);
6578         }
6579         break;
6580       }
6581
6582       case Variable::LOOKUP:
6583         return Bailout(kCompoundAssignmentToLookupSlot);
6584     }
6585     return ast_context()->ReturnValue(Pop());
6586
6587   } else if (prop != NULL) {
6588     CHECK_ALIVE(VisitForValue(prop->obj()));
6589     HValue* object = Top();
6590     HValue* key = NULL;
6591     if (!prop->key()->IsPropertyName() || prop->IsStringAccess()) {
6592       CHECK_ALIVE(VisitForValue(prop->key()));
6593       key = Top();
6594     }
6595
6596     CHECK_ALIVE(PushLoad(prop, object, key));
6597
6598     CHECK_ALIVE(VisitForValue(expr->value()));
6599     HValue* right = Pop();
6600     HValue* left = Pop();
6601
6602     Push(BuildBinaryOperation(operation, left, right, PUSH_BEFORE_SIMULATE));
6603
6604     BuildStore(expr, prop, expr->id(),
6605                expr->AssignmentId(), expr->IsUninitialized());
6606   } else {
6607     return Bailout(kInvalidLhsInCompoundAssignment);
6608   }
6609 }
6610
6611
6612 void HOptimizedGraphBuilder::VisitAssignment(Assignment* expr) {
6613   DCHECK(!HasStackOverflow());
6614   DCHECK(current_block() != NULL);
6615   DCHECK(current_block()->HasPredecessor());
6616   VariableProxy* proxy = expr->target()->AsVariableProxy();
6617   Property* prop = expr->target()->AsProperty();
6618   DCHECK(proxy == NULL || prop == NULL);
6619
6620   if (expr->is_compound()) {
6621     HandleCompoundAssignment(expr);
6622     return;
6623   }
6624
6625   if (prop != NULL) {
6626     HandlePropertyAssignment(expr);
6627   } else if (proxy != NULL) {
6628     Variable* var = proxy->var();
6629
6630     if (var->mode() == CONST) {
6631       if (expr->op() != Token::INIT_CONST) {
6632         return Bailout(kNonInitializerAssignmentToConst);
6633       }
6634     } else if (var->mode() == CONST_LEGACY) {
6635       if (expr->op() != Token::INIT_CONST_LEGACY) {
6636         CHECK_ALIVE(VisitForValue(expr->value()));
6637         return ast_context()->ReturnValue(Pop());
6638       }
6639
6640       if (var->IsStackAllocated()) {
6641         // We insert a use of the old value to detect unsupported uses of const
6642         // variables (e.g. initialization inside a loop).
6643         HValue* old_value = environment()->Lookup(var);
6644         Add<HUseConst>(old_value);
6645       }
6646     }
6647
6648     if (proxy->IsArguments()) return Bailout(kAssignmentToArguments);
6649
6650     // Handle the assignment.
6651     switch (var->location()) {
6652       case Variable::UNALLOCATED:
6653         CHECK_ALIVE(VisitForValue(expr->value()));
6654         HandleGlobalVariableAssignment(var,
6655                                        Top(),
6656                                        expr->AssignmentId());
6657         return ast_context()->ReturnValue(Pop());
6658
6659       case Variable::PARAMETER:
6660       case Variable::LOCAL: {
6661         // Perform an initialization check for let declared variables
6662         // or parameters.
6663         if (var->mode() == LET && expr->op() == Token::ASSIGN) {
6664           HValue* env_value = environment()->Lookup(var);
6665           if (env_value == graph()->GetConstantHole()) {
6666             return Bailout(kAssignmentToLetVariableBeforeInitialization);
6667           }
6668         }
6669         // We do not allow the arguments object to occur in a context where it
6670         // may escape, but assignments to stack-allocated locals are
6671         // permitted.
6672         CHECK_ALIVE(VisitForValue(expr->value(), ARGUMENTS_ALLOWED));
6673         HValue* value = Pop();
6674         BindIfLive(var, value);
6675         return ast_context()->ReturnValue(value);
6676       }
6677
6678       case Variable::CONTEXT: {
6679         // Bail out if we try to mutate a parameter value in a function using
6680         // the arguments object.  We do not (yet) correctly handle the
6681         // arguments property of the function.
6682         if (current_info()->scope()->arguments() != NULL) {
6683           // Parameters will rewrite to context slots.  We have no direct way
6684           // to detect that the variable is a parameter.
6685           int count = current_info()->scope()->num_parameters();
6686           for (int i = 0; i < count; ++i) {
6687             if (var == current_info()->scope()->parameter(i)) {
6688               return Bailout(kAssignmentToParameterInArgumentsObject);
6689             }
6690           }
6691         }
6692
6693         CHECK_ALIVE(VisitForValue(expr->value()));
6694         HStoreContextSlot::Mode mode;
6695         if (expr->op() == Token::ASSIGN) {
6696           switch (var->mode()) {
6697             case LET:
6698               mode = HStoreContextSlot::kCheckDeoptimize;
6699               break;
6700             case CONST:
6701               // This case is checked statically so no need to
6702               // perform checks here
6703               UNREACHABLE();
6704             case CONST_LEGACY:
6705               return ast_context()->ReturnValue(Pop());
6706             default:
6707               mode = HStoreContextSlot::kNoCheck;
6708           }
6709         } else if (expr->op() == Token::INIT_VAR ||
6710                    expr->op() == Token::INIT_LET ||
6711                    expr->op() == Token::INIT_CONST) {
6712           mode = HStoreContextSlot::kNoCheck;
6713         } else {
6714           DCHECK(expr->op() == Token::INIT_CONST_LEGACY);
6715
6716           mode = HStoreContextSlot::kCheckIgnoreAssignment;
6717         }
6718
6719         HValue* context = BuildContextChainWalk(var);
6720         HStoreContextSlot* instr = Add<HStoreContextSlot>(
6721             context, var->index(), mode, Top());
6722         if (instr->HasObservableSideEffects()) {
6723           Add<HSimulate>(expr->AssignmentId(), REMOVABLE_SIMULATE);
6724         }
6725         return ast_context()->ReturnValue(Pop());
6726       }
6727
6728       case Variable::LOOKUP:
6729         return Bailout(kAssignmentToLOOKUPVariable);
6730     }
6731   } else {
6732     return Bailout(kInvalidLeftHandSideInAssignment);
6733   }
6734 }
6735
6736
6737 void HOptimizedGraphBuilder::VisitYield(Yield* expr) {
6738   // Generators are not optimized, so we should never get here.
6739   UNREACHABLE();
6740 }
6741
6742
6743 void HOptimizedGraphBuilder::VisitThrow(Throw* expr) {
6744   DCHECK(!HasStackOverflow());
6745   DCHECK(current_block() != NULL);
6746   DCHECK(current_block()->HasPredecessor());
6747   // We don't optimize functions with invalid left-hand sides in
6748   // assignments, count operations, or for-in.  Consequently throw can
6749   // currently only occur in an effect context.
6750   DCHECK(ast_context()->IsEffect());
6751   CHECK_ALIVE(VisitForValue(expr->exception()));
6752
6753   HValue* value = environment()->Pop();
6754   if (!FLAG_hydrogen_track_positions) SetSourcePosition(expr->position());
6755   Add<HPushArguments>(value);
6756   Add<HCallRuntime>(isolate()->factory()->empty_string(),
6757                     Runtime::FunctionForId(Runtime::kThrow), 1);
6758   Add<HSimulate>(expr->id());
6759
6760   // If the throw definitely exits the function, we can finish with a dummy
6761   // control flow at this point.  This is not the case if the throw is inside
6762   // an inlined function which may be replaced.
6763   if (call_context() == NULL) {
6764     FinishExitCurrentBlock(New<HAbnormalExit>());
6765   }
6766 }
6767
6768
6769 HInstruction* HGraphBuilder::AddLoadStringInstanceType(HValue* string) {
6770   if (string->IsConstant()) {
6771     HConstant* c_string = HConstant::cast(string);
6772     if (c_string->HasStringValue()) {
6773       return Add<HConstant>(c_string->StringValue()->map()->instance_type());
6774     }
6775   }
6776   return Add<HLoadNamedField>(
6777       Add<HLoadNamedField>(string, static_cast<HValue*>(NULL),
6778                            HObjectAccess::ForMap()),
6779       static_cast<HValue*>(NULL), HObjectAccess::ForMapInstanceType());
6780 }
6781
6782
6783 HInstruction* HGraphBuilder::AddLoadStringLength(HValue* string) {
6784   if (string->IsConstant()) {
6785     HConstant* c_string = HConstant::cast(string);
6786     if (c_string->HasStringValue()) {
6787       return Add<HConstant>(c_string->StringValue()->length());
6788     }
6789   }
6790   return Add<HLoadNamedField>(string, static_cast<HValue*>(NULL),
6791                               HObjectAccess::ForStringLength());
6792 }
6793
6794
6795 HInstruction* HOptimizedGraphBuilder::BuildNamedGeneric(
6796     PropertyAccessType access_type,
6797     Expression* expr,
6798     HValue* object,
6799     Handle<String> name,
6800     HValue* value,
6801     bool is_uninitialized) {
6802   if (is_uninitialized) {
6803     Add<HDeoptimize>("Insufficient type feedback for generic named access",
6804                      Deoptimizer::SOFT);
6805   }
6806   if (access_type == LOAD) {
6807     HLoadNamedGeneric* result = New<HLoadNamedGeneric>(object, name);
6808     if (FLAG_vector_ics) {
6809       Handle<SharedFunctionInfo> current_shared =
6810           function_state()->compilation_info()->shared_info();
6811       result->SetVectorAndSlot(
6812           handle(current_shared->feedback_vector(), isolate()),
6813           expr->AsProperty()->PropertyFeedbackSlot());
6814     }
6815     return result;
6816   } else {
6817     return New<HStoreNamedGeneric>(object, name, value, function_strict_mode());
6818   }
6819 }
6820
6821
6822
6823 HInstruction* HOptimizedGraphBuilder::BuildKeyedGeneric(
6824     PropertyAccessType access_type,
6825     Expression* expr,
6826     HValue* object,
6827     HValue* key,
6828     HValue* value) {
6829   if (access_type == LOAD) {
6830     HLoadKeyedGeneric* result = New<HLoadKeyedGeneric>(object, key);
6831     if (FLAG_vector_ics) {
6832       Handle<SharedFunctionInfo> current_shared =
6833           function_state()->compilation_info()->shared_info();
6834       result->SetVectorAndSlot(
6835           handle(current_shared->feedback_vector(), isolate()),
6836           expr->AsProperty()->PropertyFeedbackSlot());
6837     }
6838     return result;
6839   } else {
6840     return New<HStoreKeyedGeneric>(object, key, value, function_strict_mode());
6841   }
6842 }
6843
6844
6845 LoadKeyedHoleMode HOptimizedGraphBuilder::BuildKeyedHoleMode(Handle<Map> map) {
6846   // Loads from a "stock" fast holey double arrays can elide the hole check.
6847   LoadKeyedHoleMode load_mode = NEVER_RETURN_HOLE;
6848   if (*map == isolate()->get_initial_js_array_map(FAST_HOLEY_DOUBLE_ELEMENTS) &&
6849       isolate()->IsFastArrayConstructorPrototypeChainIntact()) {
6850     Handle<JSObject> prototype(JSObject::cast(map->prototype()), isolate());
6851     Handle<JSObject> object_prototype = isolate()->initial_object_prototype();
6852     BuildCheckPrototypeMaps(prototype, object_prototype);
6853     load_mode = ALLOW_RETURN_HOLE;
6854     graph()->MarkDependsOnEmptyArrayProtoElements();
6855   }
6856
6857   return load_mode;
6858 }
6859
6860
6861 HInstruction* HOptimizedGraphBuilder::BuildMonomorphicElementAccess(
6862     HValue* object,
6863     HValue* key,
6864     HValue* val,
6865     HValue* dependency,
6866     Handle<Map> map,
6867     PropertyAccessType access_type,
6868     KeyedAccessStoreMode store_mode) {
6869   HCheckMaps* checked_object = Add<HCheckMaps>(object, map, dependency);
6870   if (dependency) {
6871     checked_object->ClearDependsOnFlag(kElementsKind);
6872   }
6873
6874   if (access_type == STORE && map->prototype()->IsJSObject()) {
6875     // monomorphic stores need a prototype chain check because shape
6876     // changes could allow callbacks on elements in the chain that
6877     // aren't compatible with monomorphic keyed stores.
6878     PrototypeIterator iter(map);
6879     JSObject* holder = NULL;
6880     while (!iter.IsAtEnd()) {
6881       holder = JSObject::cast(*PrototypeIterator::GetCurrent(iter));
6882       iter.Advance();
6883     }
6884     DCHECK(holder && holder->IsJSObject());
6885
6886     BuildCheckPrototypeMaps(handle(JSObject::cast(map->prototype())),
6887                             Handle<JSObject>(holder));
6888   }
6889
6890   LoadKeyedHoleMode load_mode = BuildKeyedHoleMode(map);
6891   return BuildUncheckedMonomorphicElementAccess(
6892       checked_object, key, val,
6893       map->instance_type() == JS_ARRAY_TYPE,
6894       map->elements_kind(), access_type,
6895       load_mode, store_mode);
6896 }
6897
6898
6899 HInstruction* HOptimizedGraphBuilder::TryBuildConsolidatedElementLoad(
6900     HValue* object,
6901     HValue* key,
6902     HValue* val,
6903     SmallMapList* maps) {
6904   // For polymorphic loads of similar elements kinds (i.e. all tagged or all
6905   // double), always use the "worst case" code without a transition.  This is
6906   // much faster than transitioning the elements to the worst case, trading a
6907   // HTransitionElements for a HCheckMaps, and avoiding mutation of the array.
6908   bool has_double_maps = false;
6909   bool has_smi_or_object_maps = false;
6910   bool has_js_array_access = false;
6911   bool has_non_js_array_access = false;
6912   bool has_seen_holey_elements = false;
6913   Handle<Map> most_general_consolidated_map;
6914   for (int i = 0; i < maps->length(); ++i) {
6915     Handle<Map> map = maps->at(i);
6916     if (!map->IsJSObjectMap()) return NULL;
6917     // Don't allow mixing of JSArrays with JSObjects.
6918     if (map->instance_type() == JS_ARRAY_TYPE) {
6919       if (has_non_js_array_access) return NULL;
6920       has_js_array_access = true;
6921     } else if (has_js_array_access) {
6922       return NULL;
6923     } else {
6924       has_non_js_array_access = true;
6925     }
6926     // Don't allow mixed, incompatible elements kinds.
6927     if (map->has_fast_double_elements()) {
6928       if (has_smi_or_object_maps) return NULL;
6929       has_double_maps = true;
6930     } else if (map->has_fast_smi_or_object_elements()) {
6931       if (has_double_maps) return NULL;
6932       has_smi_or_object_maps = true;
6933     } else {
6934       return NULL;
6935     }
6936     // Remember if we've ever seen holey elements.
6937     if (IsHoleyElementsKind(map->elements_kind())) {
6938       has_seen_holey_elements = true;
6939     }
6940     // Remember the most general elements kind, the code for its load will
6941     // properly handle all of the more specific cases.
6942     if ((i == 0) || IsMoreGeneralElementsKindTransition(
6943             most_general_consolidated_map->elements_kind(),
6944             map->elements_kind())) {
6945       most_general_consolidated_map = map;
6946     }
6947   }
6948   if (!has_double_maps && !has_smi_or_object_maps) return NULL;
6949
6950   HCheckMaps* checked_object = Add<HCheckMaps>(object, maps);
6951   // FAST_ELEMENTS is considered more general than FAST_HOLEY_SMI_ELEMENTS.
6952   // If we've seen both, the consolidated load must use FAST_HOLEY_ELEMENTS.
6953   ElementsKind consolidated_elements_kind = has_seen_holey_elements
6954       ? GetHoleyElementsKind(most_general_consolidated_map->elements_kind())
6955       : most_general_consolidated_map->elements_kind();
6956   HInstruction* instr = BuildUncheckedMonomorphicElementAccess(
6957       checked_object, key, val,
6958       most_general_consolidated_map->instance_type() == JS_ARRAY_TYPE,
6959       consolidated_elements_kind,
6960       LOAD, NEVER_RETURN_HOLE, STANDARD_STORE);
6961   return instr;
6962 }
6963
6964
6965 HValue* HOptimizedGraphBuilder::HandlePolymorphicElementAccess(
6966     Expression* expr,
6967     HValue* object,
6968     HValue* key,
6969     HValue* val,
6970     SmallMapList* maps,
6971     PropertyAccessType access_type,
6972     KeyedAccessStoreMode store_mode,
6973     bool* has_side_effects) {
6974   *has_side_effects = false;
6975   BuildCheckHeapObject(object);
6976
6977   if (access_type == LOAD) {
6978     HInstruction* consolidated_load =
6979         TryBuildConsolidatedElementLoad(object, key, val, maps);
6980     if (consolidated_load != NULL) {
6981       *has_side_effects |= consolidated_load->HasObservableSideEffects();
6982       return consolidated_load;
6983     }
6984   }
6985
6986   // Elements_kind transition support.
6987   MapHandleList transition_target(maps->length());
6988   // Collect possible transition targets.
6989   MapHandleList possible_transitioned_maps(maps->length());
6990   for (int i = 0; i < maps->length(); ++i) {
6991     Handle<Map> map = maps->at(i);
6992     ElementsKind elements_kind = map->elements_kind();
6993     if (IsFastElementsKind(elements_kind) &&
6994         elements_kind != GetInitialFastElementsKind()) {
6995       possible_transitioned_maps.Add(map);
6996     }
6997     if (elements_kind == SLOPPY_ARGUMENTS_ELEMENTS) {
6998       HInstruction* result = BuildKeyedGeneric(access_type, expr, object, key,
6999                                                val);
7000       *has_side_effects = result->HasObservableSideEffects();
7001       return AddInstruction(result);
7002     }
7003   }
7004   // Get transition target for each map (NULL == no transition).
7005   for (int i = 0; i < maps->length(); ++i) {
7006     Handle<Map> map = maps->at(i);
7007     Handle<Map> transitioned_map =
7008         map->FindTransitionedMap(&possible_transitioned_maps);
7009     transition_target.Add(transitioned_map);
7010   }
7011
7012   MapHandleList untransitionable_maps(maps->length());
7013   HTransitionElementsKind* transition = NULL;
7014   for (int i = 0; i < maps->length(); ++i) {
7015     Handle<Map> map = maps->at(i);
7016     DCHECK(map->IsMap());
7017     if (!transition_target.at(i).is_null()) {
7018       DCHECK(Map::IsValidElementsTransition(
7019           map->elements_kind(),
7020           transition_target.at(i)->elements_kind()));
7021       transition = Add<HTransitionElementsKind>(object, map,
7022                                                 transition_target.at(i));
7023     } else {
7024       untransitionable_maps.Add(map);
7025     }
7026   }
7027
7028   // If only one map is left after transitioning, handle this case
7029   // monomorphically.
7030   DCHECK(untransitionable_maps.length() >= 1);
7031   if (untransitionable_maps.length() == 1) {
7032     Handle<Map> untransitionable_map = untransitionable_maps[0];
7033     HInstruction* instr = NULL;
7034     if (untransitionable_map->has_slow_elements_kind() ||
7035         !untransitionable_map->IsJSObjectMap()) {
7036       instr = AddInstruction(BuildKeyedGeneric(access_type, expr, object, key,
7037                                                val));
7038     } else {
7039       instr = BuildMonomorphicElementAccess(
7040           object, key, val, transition, untransitionable_map, access_type,
7041           store_mode);
7042     }
7043     *has_side_effects |= instr->HasObservableSideEffects();
7044     return access_type == STORE ? NULL : instr;
7045   }
7046
7047   HBasicBlock* join = graph()->CreateBasicBlock();
7048
7049   for (int i = 0; i < untransitionable_maps.length(); ++i) {
7050     Handle<Map> map = untransitionable_maps[i];
7051     if (!map->IsJSObjectMap()) continue;
7052     ElementsKind elements_kind = map->elements_kind();
7053     HBasicBlock* this_map = graph()->CreateBasicBlock();
7054     HBasicBlock* other_map = graph()->CreateBasicBlock();
7055     HCompareMap* mapcompare =
7056         New<HCompareMap>(object, map, this_map, other_map);
7057     FinishCurrentBlock(mapcompare);
7058
7059     set_current_block(this_map);
7060     HInstruction* access = NULL;
7061     if (IsDictionaryElementsKind(elements_kind)) {
7062       access = AddInstruction(BuildKeyedGeneric(access_type, expr, object, key,
7063                                                 val));
7064     } else {
7065       DCHECK(IsFastElementsKind(elements_kind) ||
7066              IsExternalArrayElementsKind(elements_kind) ||
7067              IsFixedTypedArrayElementsKind(elements_kind));
7068       LoadKeyedHoleMode load_mode = BuildKeyedHoleMode(map);
7069       // Happily, mapcompare is a checked object.
7070       access = BuildUncheckedMonomorphicElementAccess(
7071           mapcompare, key, val,
7072           map->instance_type() == JS_ARRAY_TYPE,
7073           elements_kind, access_type,
7074           load_mode,
7075           store_mode);
7076     }
7077     *has_side_effects |= access->HasObservableSideEffects();
7078     // The caller will use has_side_effects and add a correct Simulate.
7079     access->SetFlag(HValue::kHasNoObservableSideEffects);
7080     if (access_type == LOAD) {
7081       Push(access);
7082     }
7083     NoObservableSideEffectsScope scope(this);
7084     GotoNoSimulate(join);
7085     set_current_block(other_map);
7086   }
7087
7088   // Ensure that we visited at least one map above that goes to join. This is
7089   // necessary because FinishExitWithHardDeoptimization does an AbnormalExit
7090   // rather than joining the join block. If this becomes an issue, insert a
7091   // generic access in the case length() == 0.
7092   DCHECK(join->predecessors()->length() > 0);
7093   // Deopt if none of the cases matched.
7094   NoObservableSideEffectsScope scope(this);
7095   FinishExitWithHardDeoptimization("Unknown map in polymorphic element access");
7096   set_current_block(join);
7097   return access_type == STORE ? NULL : Pop();
7098 }
7099
7100
7101 HValue* HOptimizedGraphBuilder::HandleKeyedElementAccess(
7102     HValue* obj,
7103     HValue* key,
7104     HValue* val,
7105     Expression* expr,
7106     PropertyAccessType access_type,
7107     bool* has_side_effects) {
7108   DCHECK(!expr->IsPropertyName());
7109   HInstruction* instr = NULL;
7110
7111   SmallMapList* types;
7112   bool monomorphic = ComputeReceiverTypes(expr, obj, &types, zone());
7113
7114   bool force_generic = false;
7115   if (access_type == STORE &&
7116       (monomorphic || (types != NULL && !types->is_empty()))) {
7117     // Stores can't be mono/polymorphic if their prototype chain has dictionary
7118     // elements. However a receiver map that has dictionary elements itself
7119     // should be left to normal mono/poly behavior (the other maps may benefit
7120     // from highly optimized stores).
7121     for (int i = 0; i < types->length(); i++) {
7122       Handle<Map> current_map = types->at(i);
7123       if (current_map->DictionaryElementsInPrototypeChainOnly()) {
7124         force_generic = true;
7125         monomorphic = false;
7126         break;
7127       }
7128     }
7129   }
7130
7131   if (monomorphic) {
7132     Handle<Map> map = types->first();
7133     if (map->has_slow_elements_kind() || !map->IsJSObjectMap()) {
7134       instr = AddInstruction(BuildKeyedGeneric(access_type, expr, obj, key,
7135                                                val));
7136     } else {
7137       BuildCheckHeapObject(obj);
7138       instr = BuildMonomorphicElementAccess(
7139           obj, key, val, NULL, map, access_type, expr->GetStoreMode());
7140     }
7141   } else if (!force_generic && (types != NULL && !types->is_empty())) {
7142     return HandlePolymorphicElementAccess(
7143         expr, obj, key, val, types, access_type,
7144         expr->GetStoreMode(), has_side_effects);
7145   } else {
7146     if (access_type == STORE) {
7147       if (expr->IsAssignment() &&
7148           expr->AsAssignment()->HasNoTypeInformation()) {
7149         Add<HDeoptimize>("Insufficient type feedback for keyed store",
7150                          Deoptimizer::SOFT);
7151       }
7152     } else {
7153       if (expr->AsProperty()->HasNoTypeInformation()) {
7154         Add<HDeoptimize>("Insufficient type feedback for keyed load",
7155                          Deoptimizer::SOFT);
7156       }
7157     }
7158     instr = AddInstruction(BuildKeyedGeneric(access_type, expr, obj, key, val));
7159   }
7160   *has_side_effects = instr->HasObservableSideEffects();
7161   return instr;
7162 }
7163
7164
7165 void HOptimizedGraphBuilder::EnsureArgumentsArePushedForAccess() {
7166   // Outermost function already has arguments on the stack.
7167   if (function_state()->outer() == NULL) return;
7168
7169   if (function_state()->arguments_pushed()) return;
7170
7171   // Push arguments when entering inlined function.
7172   HEnterInlined* entry = function_state()->entry();
7173   entry->set_arguments_pushed();
7174
7175   HArgumentsObject* arguments = entry->arguments_object();
7176   const ZoneList<HValue*>* arguments_values = arguments->arguments_values();
7177
7178   HInstruction* insert_after = entry;
7179   for (int i = 0; i < arguments_values->length(); i++) {
7180     HValue* argument = arguments_values->at(i);
7181     HInstruction* push_argument = New<HPushArguments>(argument);
7182     push_argument->InsertAfter(insert_after);
7183     insert_after = push_argument;
7184   }
7185
7186   HArgumentsElements* arguments_elements = New<HArgumentsElements>(true);
7187   arguments_elements->ClearFlag(HValue::kUseGVN);
7188   arguments_elements->InsertAfter(insert_after);
7189   function_state()->set_arguments_elements(arguments_elements);
7190 }
7191
7192
7193 bool HOptimizedGraphBuilder::TryArgumentsAccess(Property* expr) {
7194   VariableProxy* proxy = expr->obj()->AsVariableProxy();
7195   if (proxy == NULL) return false;
7196   if (!proxy->var()->IsStackAllocated()) return false;
7197   if (!environment()->Lookup(proxy->var())->CheckFlag(HValue::kIsArguments)) {
7198     return false;
7199   }
7200
7201   HInstruction* result = NULL;
7202   if (expr->key()->IsPropertyName()) {
7203     Handle<String> name = expr->key()->AsLiteral()->AsPropertyName();
7204     if (!name->IsOneByteEqualTo(STATIC_ASCII_VECTOR("length"))) return false;
7205
7206     if (function_state()->outer() == NULL) {
7207       HInstruction* elements = Add<HArgumentsElements>(false);
7208       result = New<HArgumentsLength>(elements);
7209     } else {
7210       // Number of arguments without receiver.
7211       int argument_count = environment()->
7212           arguments_environment()->parameter_count() - 1;
7213       result = New<HConstant>(argument_count);
7214     }
7215   } else {
7216     Push(graph()->GetArgumentsObject());
7217     CHECK_ALIVE_OR_RETURN(VisitForValue(expr->key()), true);
7218     HValue* key = Pop();
7219     Drop(1);  // Arguments object.
7220     if (function_state()->outer() == NULL) {
7221       HInstruction* elements = Add<HArgumentsElements>(false);
7222       HInstruction* length = Add<HArgumentsLength>(elements);
7223       HInstruction* checked_key = Add<HBoundsCheck>(key, length);
7224       result = New<HAccessArgumentsAt>(elements, length, checked_key);
7225     } else {
7226       EnsureArgumentsArePushedForAccess();
7227
7228       // Number of arguments without receiver.
7229       HInstruction* elements = function_state()->arguments_elements();
7230       int argument_count = environment()->
7231           arguments_environment()->parameter_count() - 1;
7232       HInstruction* length = Add<HConstant>(argument_count);
7233       HInstruction* checked_key = Add<HBoundsCheck>(key, length);
7234       result = New<HAccessArgumentsAt>(elements, length, checked_key);
7235     }
7236   }
7237   ast_context()->ReturnInstruction(result, expr->id());
7238   return true;
7239 }
7240
7241
7242 HInstruction* HOptimizedGraphBuilder::BuildNamedAccess(
7243     PropertyAccessType access,
7244     BailoutId ast_id,
7245     BailoutId return_id,
7246     Expression* expr,
7247     HValue* object,
7248     Handle<String> name,
7249     HValue* value,
7250     bool is_uninitialized) {
7251   SmallMapList* types;
7252   ComputeReceiverTypes(expr, object, &types, zone());
7253   DCHECK(types != NULL);
7254
7255   if (types->length() > 0) {
7256     PropertyAccessInfo info(this, access, ToType(types->first()), name);
7257     if (!info.CanAccessAsMonomorphic(types)) {
7258       HandlePolymorphicNamedFieldAccess(
7259           access, expr, ast_id, return_id, object, value, types, name);
7260       return NULL;
7261     }
7262
7263     HValue* checked_object;
7264     // Type::Number() is only supported by polymorphic load/call handling.
7265     DCHECK(!info.type()->Is(Type::Number()));
7266     BuildCheckHeapObject(object);
7267     if (AreStringTypes(types)) {
7268       checked_object =
7269           Add<HCheckInstanceType>(object, HCheckInstanceType::IS_STRING);
7270     } else {
7271       checked_object = Add<HCheckMaps>(object, types);
7272     }
7273     return BuildMonomorphicAccess(
7274         &info, object, checked_object, value, ast_id, return_id);
7275   }
7276
7277   return BuildNamedGeneric(access, expr, object, name, value, is_uninitialized);
7278 }
7279
7280
7281 void HOptimizedGraphBuilder::PushLoad(Property* expr,
7282                                       HValue* object,
7283                                       HValue* key) {
7284   ValueContext for_value(this, ARGUMENTS_NOT_ALLOWED);
7285   Push(object);
7286   if (key != NULL) Push(key);
7287   BuildLoad(expr, expr->LoadId());
7288 }
7289
7290
7291 void HOptimizedGraphBuilder::BuildLoad(Property* expr,
7292                                        BailoutId ast_id) {
7293   HInstruction* instr = NULL;
7294   if (expr->IsStringAccess()) {
7295     HValue* index = Pop();
7296     HValue* string = Pop();
7297     HInstruction* char_code = BuildStringCharCodeAt(string, index);
7298     AddInstruction(char_code);
7299     instr = NewUncasted<HStringCharFromCode>(char_code);
7300
7301   } else if (expr->key()->IsPropertyName()) {
7302     Handle<String> name = expr->key()->AsLiteral()->AsPropertyName();
7303     HValue* object = Pop();
7304
7305     instr = BuildNamedAccess(LOAD, ast_id, expr->LoadId(), expr,
7306                              object, name, NULL, expr->IsUninitialized());
7307     if (instr == NULL) return;
7308     if (instr->IsLinked()) return ast_context()->ReturnValue(instr);
7309
7310   } else {
7311     HValue* key = Pop();
7312     HValue* obj = Pop();
7313
7314     bool has_side_effects = false;
7315     HValue* load = HandleKeyedElementAccess(
7316         obj, key, NULL, expr, LOAD, &has_side_effects);
7317     if (has_side_effects) {
7318       if (ast_context()->IsEffect()) {
7319         Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
7320       } else {
7321         Push(load);
7322         Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
7323         Drop(1);
7324       }
7325     }
7326     return ast_context()->ReturnValue(load);
7327   }
7328   return ast_context()->ReturnInstruction(instr, ast_id);
7329 }
7330
7331
7332 void HOptimizedGraphBuilder::VisitProperty(Property* expr) {
7333   DCHECK(!HasStackOverflow());
7334   DCHECK(current_block() != NULL);
7335   DCHECK(current_block()->HasPredecessor());
7336
7337   if (TryArgumentsAccess(expr)) return;
7338
7339   CHECK_ALIVE(VisitForValue(expr->obj()));
7340   if (!expr->key()->IsPropertyName() || expr->IsStringAccess()) {
7341     CHECK_ALIVE(VisitForValue(expr->key()));
7342   }
7343
7344   BuildLoad(expr, expr->id());
7345 }
7346
7347
7348 HInstruction* HGraphBuilder::BuildConstantMapCheck(Handle<JSObject> constant) {
7349   HCheckMaps* check = Add<HCheckMaps>(
7350       Add<HConstant>(constant), handle(constant->map()));
7351   check->ClearDependsOnFlag(kElementsKind);
7352   return check;
7353 }
7354
7355
7356 HInstruction* HGraphBuilder::BuildCheckPrototypeMaps(Handle<JSObject> prototype,
7357                                                      Handle<JSObject> holder) {
7358   PrototypeIterator iter(isolate(), prototype,
7359                          PrototypeIterator::START_AT_RECEIVER);
7360   while (holder.is_null() ||
7361          !PrototypeIterator::GetCurrent(iter).is_identical_to(holder)) {
7362     BuildConstantMapCheck(
7363         Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter)));
7364     iter.Advance();
7365     if (iter.IsAtEnd()) {
7366       return NULL;
7367     }
7368   }
7369   return BuildConstantMapCheck(
7370       Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter)));
7371 }
7372
7373
7374 void HOptimizedGraphBuilder::AddCheckPrototypeMaps(Handle<JSObject> holder,
7375                                                    Handle<Map> receiver_map) {
7376   if (!holder.is_null()) {
7377     Handle<JSObject> prototype(JSObject::cast(receiver_map->prototype()));
7378     BuildCheckPrototypeMaps(prototype, holder);
7379   }
7380 }
7381
7382
7383 HInstruction* HOptimizedGraphBuilder::NewPlainFunctionCall(
7384     HValue* fun, int argument_count, bool pass_argument_count) {
7385   return New<HCallJSFunction>(
7386       fun, argument_count, pass_argument_count);
7387 }
7388
7389
7390 HInstruction* HOptimizedGraphBuilder::NewArgumentAdaptorCall(
7391     HValue* fun, HValue* context,
7392     int argument_count, HValue* expected_param_count) {
7393   CallInterfaceDescriptor* descriptor =
7394       isolate()->call_descriptor(Isolate::ArgumentAdaptorCall);
7395
7396   HValue* arity = Add<HConstant>(argument_count - 1);
7397
7398   HValue* op_vals[] = { context, fun, arity, expected_param_count };
7399
7400   Handle<Code> adaptor =
7401       isolate()->builtins()->ArgumentsAdaptorTrampoline();
7402   HConstant* adaptor_value = Add<HConstant>(adaptor);
7403
7404   return New<HCallWithDescriptor>(
7405       adaptor_value, argument_count, descriptor,
7406       Vector<HValue*>(op_vals, descriptor->GetEnvironmentLength()));
7407 }
7408
7409
7410 HInstruction* HOptimizedGraphBuilder::BuildCallConstantFunction(
7411     Handle<JSFunction> jsfun, int argument_count) {
7412   HValue* target = Add<HConstant>(jsfun);
7413   // For constant functions, we try to avoid calling the
7414   // argument adaptor and instead call the function directly
7415   int formal_parameter_count = jsfun->shared()->formal_parameter_count();
7416   bool dont_adapt_arguments =
7417       (formal_parameter_count ==
7418        SharedFunctionInfo::kDontAdaptArgumentsSentinel);
7419   int arity = argument_count - 1;
7420   bool can_invoke_directly =
7421       dont_adapt_arguments || formal_parameter_count == arity;
7422   if (can_invoke_directly) {
7423     if (jsfun.is_identical_to(current_info()->closure())) {
7424       graph()->MarkRecursive();
7425     }
7426     return NewPlainFunctionCall(target, argument_count, dont_adapt_arguments);
7427   } else {
7428     HValue* param_count_value = Add<HConstant>(formal_parameter_count);
7429     HValue* context = Add<HLoadNamedField>(
7430         target, static_cast<HValue*>(NULL),
7431         HObjectAccess::ForFunctionContextPointer());
7432     return NewArgumentAdaptorCall(target, context,
7433         argument_count, param_count_value);
7434   }
7435   UNREACHABLE();
7436   return NULL;
7437 }
7438
7439
7440 class FunctionSorter {
7441  public:
7442   explicit FunctionSorter(int index = 0, int ticks = 0, int size = 0)
7443       : index_(index), ticks_(ticks), size_(size) {}
7444
7445   int index() const { return index_; }
7446   int ticks() const { return ticks_; }
7447   int size() const { return size_; }
7448
7449  private:
7450   int index_;
7451   int ticks_;
7452   int size_;
7453 };
7454
7455
7456 inline bool operator<(const FunctionSorter& lhs, const FunctionSorter& rhs) {
7457   int diff = lhs.ticks() - rhs.ticks();
7458   if (diff != 0) return diff > 0;
7459   return lhs.size() < rhs.size();
7460 }
7461
7462
7463 void HOptimizedGraphBuilder::HandlePolymorphicCallNamed(
7464     Call* expr,
7465     HValue* receiver,
7466     SmallMapList* types,
7467     Handle<String> name) {
7468   int argument_count = expr->arguments()->length() + 1;  // Includes receiver.
7469   FunctionSorter order[kMaxCallPolymorphism];
7470
7471   bool handle_smi = false;
7472   bool handled_string = false;
7473   int ordered_functions = 0;
7474
7475   for (int i = 0;
7476        i < types->length() && ordered_functions < kMaxCallPolymorphism;
7477        ++i) {
7478     PropertyAccessInfo info(this, LOAD, ToType(types->at(i)), name);
7479     if (info.CanAccessMonomorphic() &&
7480         info.lookup()->IsConstant() &&
7481         info.constant()->IsJSFunction()) {
7482       if (info.type()->Is(Type::String())) {
7483         if (handled_string) continue;
7484         handled_string = true;
7485       }
7486       Handle<JSFunction> target = Handle<JSFunction>::cast(info.constant());
7487       if (info.type()->Is(Type::Number())) {
7488         handle_smi = true;
7489       }
7490       expr->set_target(target);
7491       order[ordered_functions++] = FunctionSorter(
7492           i, target->shared()->profiler_ticks(), InliningAstSize(target));
7493     }
7494   }
7495
7496   std::sort(order, order + ordered_functions);
7497
7498   HBasicBlock* number_block = NULL;
7499   HBasicBlock* join = NULL;
7500   handled_string = false;
7501   int count = 0;
7502
7503   for (int fn = 0; fn < ordered_functions; ++fn) {
7504     int i = order[fn].index();
7505     PropertyAccessInfo info(this, LOAD, ToType(types->at(i)), name);
7506     if (info.type()->Is(Type::String())) {
7507       if (handled_string) continue;
7508       handled_string = true;
7509     }
7510     // Reloads the target.
7511     info.CanAccessMonomorphic();
7512     Handle<JSFunction> target = Handle<JSFunction>::cast(info.constant());
7513
7514     expr->set_target(target);
7515     if (count == 0) {
7516       // Only needed once.
7517       join = graph()->CreateBasicBlock();
7518       if (handle_smi) {
7519         HBasicBlock* empty_smi_block = graph()->CreateBasicBlock();
7520         HBasicBlock* not_smi_block = graph()->CreateBasicBlock();
7521         number_block = graph()->CreateBasicBlock();
7522         FinishCurrentBlock(New<HIsSmiAndBranch>(
7523                 receiver, empty_smi_block, not_smi_block));
7524         GotoNoSimulate(empty_smi_block, number_block);
7525         set_current_block(not_smi_block);
7526       } else {
7527         BuildCheckHeapObject(receiver);
7528       }
7529     }
7530     ++count;
7531     HBasicBlock* if_true = graph()->CreateBasicBlock();
7532     HBasicBlock* if_false = graph()->CreateBasicBlock();
7533     HUnaryControlInstruction* compare;
7534
7535     Handle<Map> map = info.map();
7536     if (info.type()->Is(Type::Number())) {
7537       Handle<Map> heap_number_map = isolate()->factory()->heap_number_map();
7538       compare = New<HCompareMap>(receiver, heap_number_map, if_true, if_false);
7539     } else if (info.type()->Is(Type::String())) {
7540       compare = New<HIsStringAndBranch>(receiver, if_true, if_false);
7541     } else {
7542       compare = New<HCompareMap>(receiver, map, if_true, if_false);
7543     }
7544     FinishCurrentBlock(compare);
7545
7546     if (info.type()->Is(Type::Number())) {
7547       GotoNoSimulate(if_true, number_block);
7548       if_true = number_block;
7549     }
7550
7551     set_current_block(if_true);
7552
7553     AddCheckPrototypeMaps(info.holder(), map);
7554
7555     HValue* function = Add<HConstant>(expr->target());
7556     environment()->SetExpressionStackAt(0, function);
7557     Push(receiver);
7558     CHECK_ALIVE(VisitExpressions(expr->arguments()));
7559     bool needs_wrapping = NeedsWrappingFor(info.type(), target);
7560     bool try_inline = FLAG_polymorphic_inlining && !needs_wrapping;
7561     if (FLAG_trace_inlining && try_inline) {
7562       Handle<JSFunction> caller = current_info()->closure();
7563       SmartArrayPointer<char> caller_name =
7564           caller->shared()->DebugName()->ToCString();
7565       PrintF("Trying to inline the polymorphic call to %s from %s\n",
7566              name->ToCString().get(),
7567              caller_name.get());
7568     }
7569     if (try_inline && TryInlineCall(expr)) {
7570       // Trying to inline will signal that we should bailout from the
7571       // entire compilation by setting stack overflow on the visitor.
7572       if (HasStackOverflow()) return;
7573     } else {
7574       // Since HWrapReceiver currently cannot actually wrap numbers and strings,
7575       // use the regular CallFunctionStub for method calls to wrap the receiver.
7576       // TODO(verwaest): Support creation of value wrappers directly in
7577       // HWrapReceiver.
7578       HInstruction* call = needs_wrapping
7579           ? NewUncasted<HCallFunction>(
7580               function, argument_count, WRAP_AND_CALL)
7581           : BuildCallConstantFunction(target, argument_count);
7582       PushArgumentsFromEnvironment(argument_count);
7583       AddInstruction(call);
7584       Drop(1);  // Drop the function.
7585       if (!ast_context()->IsEffect()) Push(call);
7586     }
7587
7588     if (current_block() != NULL) Goto(join);
7589     set_current_block(if_false);
7590   }
7591
7592   // Finish up.  Unconditionally deoptimize if we've handled all the maps we
7593   // know about and do not want to handle ones we've never seen.  Otherwise
7594   // use a generic IC.
7595   if (ordered_functions == types->length() && FLAG_deoptimize_uncommon_cases) {
7596     FinishExitWithHardDeoptimization("Unknown map in polymorphic call");
7597   } else {
7598     Property* prop = expr->expression()->AsProperty();
7599     HInstruction* function = BuildNamedGeneric(
7600         LOAD, prop, receiver, name, NULL, prop->IsUninitialized());
7601     AddInstruction(function);
7602     Push(function);
7603     AddSimulate(prop->LoadId(), REMOVABLE_SIMULATE);
7604
7605     environment()->SetExpressionStackAt(1, function);
7606     environment()->SetExpressionStackAt(0, receiver);
7607     CHECK_ALIVE(VisitExpressions(expr->arguments()));
7608
7609     CallFunctionFlags flags = receiver->type().IsJSObject()
7610         ? NO_CALL_FUNCTION_FLAGS : CALL_AS_METHOD;
7611     HInstruction* call = New<HCallFunction>(
7612         function, argument_count, flags);
7613
7614     PushArgumentsFromEnvironment(argument_count);
7615
7616     Drop(1);  // Function.
7617
7618     if (join != NULL) {
7619       AddInstruction(call);
7620       if (!ast_context()->IsEffect()) Push(call);
7621       Goto(join);
7622     } else {
7623       return ast_context()->ReturnInstruction(call, expr->id());
7624     }
7625   }
7626
7627   // We assume that control flow is always live after an expression.  So
7628   // even without predecessors to the join block, we set it as the exit
7629   // block and continue by adding instructions there.
7630   DCHECK(join != NULL);
7631   if (join->HasPredecessor()) {
7632     set_current_block(join);
7633     join->SetJoinId(expr->id());
7634     if (!ast_context()->IsEffect()) return ast_context()->ReturnValue(Pop());
7635   } else {
7636     set_current_block(NULL);
7637   }
7638 }
7639
7640
7641 void HOptimizedGraphBuilder::TraceInline(Handle<JSFunction> target,
7642                                          Handle<JSFunction> caller,
7643                                          const char* reason) {
7644   if (FLAG_trace_inlining) {
7645     SmartArrayPointer<char> target_name =
7646         target->shared()->DebugName()->ToCString();
7647     SmartArrayPointer<char> caller_name =
7648         caller->shared()->DebugName()->ToCString();
7649     if (reason == NULL) {
7650       PrintF("Inlined %s called from %s.\n", target_name.get(),
7651              caller_name.get());
7652     } else {
7653       PrintF("Did not inline %s called from %s (%s).\n",
7654              target_name.get(), caller_name.get(), reason);
7655     }
7656   }
7657 }
7658
7659
7660 static const int kNotInlinable = 1000000000;
7661
7662
7663 int HOptimizedGraphBuilder::InliningAstSize(Handle<JSFunction> target) {
7664   if (!FLAG_use_inlining) return kNotInlinable;
7665
7666   // Precondition: call is monomorphic and we have found a target with the
7667   // appropriate arity.
7668   Handle<JSFunction> caller = current_info()->closure();
7669   Handle<SharedFunctionInfo> target_shared(target->shared());
7670
7671   // Always inline builtins marked for inlining.
7672   if (target->IsBuiltin()) {
7673     return target_shared->inline_builtin() ? 0 : kNotInlinable;
7674   }
7675
7676   if (target_shared->IsApiFunction()) {
7677     TraceInline(target, caller, "target is api function");
7678     return kNotInlinable;
7679   }
7680
7681   // Do a quick check on source code length to avoid parsing large
7682   // inlining candidates.
7683   if (target_shared->SourceSize() >
7684       Min(FLAG_max_inlined_source_size, kUnlimitedMaxInlinedSourceSize)) {
7685     TraceInline(target, caller, "target text too big");
7686     return kNotInlinable;
7687   }
7688
7689   // Target must be inlineable.
7690   if (!target_shared->IsInlineable()) {
7691     TraceInline(target, caller, "target not inlineable");
7692     return kNotInlinable;
7693   }
7694   if (target_shared->DisableOptimizationReason() != kNoReason) {
7695     TraceInline(target, caller, "target contains unsupported syntax [early]");
7696     return kNotInlinable;
7697   }
7698
7699   int nodes_added = target_shared->ast_node_count();
7700   return nodes_added;
7701 }
7702
7703
7704 bool HOptimizedGraphBuilder::TryInline(Handle<JSFunction> target,
7705                                        int arguments_count,
7706                                        HValue* implicit_return_value,
7707                                        BailoutId ast_id,
7708                                        BailoutId return_id,
7709                                        InliningKind inlining_kind,
7710                                        HSourcePosition position) {
7711   int nodes_added = InliningAstSize(target);
7712   if (nodes_added == kNotInlinable) return false;
7713
7714   Handle<JSFunction> caller = current_info()->closure();
7715
7716   if (nodes_added > Min(FLAG_max_inlined_nodes, kUnlimitedMaxInlinedNodes)) {
7717     TraceInline(target, caller, "target AST is too large [early]");
7718     return false;
7719   }
7720
7721   // Don't inline deeper than the maximum number of inlining levels.
7722   HEnvironment* env = environment();
7723   int current_level = 1;
7724   while (env->outer() != NULL) {
7725     if (current_level == FLAG_max_inlining_levels) {
7726       TraceInline(target, caller, "inline depth limit reached");
7727       return false;
7728     }
7729     if (env->outer()->frame_type() == JS_FUNCTION) {
7730       current_level++;
7731     }
7732     env = env->outer();
7733   }
7734
7735   // Don't inline recursive functions.
7736   for (FunctionState* state = function_state();
7737        state != NULL;
7738        state = state->outer()) {
7739     if (*state->compilation_info()->closure() == *target) {
7740       TraceInline(target, caller, "target is recursive");
7741       return false;
7742     }
7743   }
7744
7745   // We don't want to add more than a certain number of nodes from inlining.
7746   if (inlined_count_ > Min(FLAG_max_inlined_nodes_cumulative,
7747                            kUnlimitedMaxInlinedNodesCumulative)) {
7748     TraceInline(target, caller, "cumulative AST node limit reached");
7749     return false;
7750   }
7751
7752   // Parse and allocate variables.
7753   CompilationInfo target_info(target, zone());
7754   // Use the same AstValueFactory for creating strings in the sub-compilation
7755   // step, but don't transfer ownership to target_info.
7756   target_info.SetAstValueFactory(top_info()->ast_value_factory(), false);
7757   Handle<SharedFunctionInfo> target_shared(target->shared());
7758   if (!Parser::Parse(&target_info) || !Scope::Analyze(&target_info)) {
7759     if (target_info.isolate()->has_pending_exception()) {
7760       // Parse or scope error, never optimize this function.
7761       SetStackOverflow();
7762       target_shared->DisableOptimization(kParseScopeError);
7763     }
7764     TraceInline(target, caller, "parse failure");
7765     return false;
7766   }
7767
7768   if (target_info.scope()->num_heap_slots() > 0) {
7769     TraceInline(target, caller, "target has context-allocated variables");
7770     return false;
7771   }
7772   FunctionLiteral* function = target_info.function();
7773
7774   // The following conditions must be checked again after re-parsing, because
7775   // earlier the information might not have been complete due to lazy parsing.
7776   nodes_added = function->ast_node_count();
7777   if (nodes_added > Min(FLAG_max_inlined_nodes, kUnlimitedMaxInlinedNodes)) {
7778     TraceInline(target, caller, "target AST is too large [late]");
7779     return false;
7780   }
7781   if (function->dont_optimize()) {
7782     TraceInline(target, caller, "target contains unsupported syntax [late]");
7783     return false;
7784   }
7785
7786   // If the function uses the arguments object check that inlining of functions
7787   // with arguments object is enabled and the arguments-variable is
7788   // stack allocated.
7789   if (function->scope()->arguments() != NULL) {
7790     if (!FLAG_inline_arguments) {
7791       TraceInline(target, caller, "target uses arguments object");
7792       return false;
7793     }
7794
7795     if (!function->scope()->arguments()->IsStackAllocated()) {
7796       TraceInline(target,
7797                   caller,
7798                   "target uses non-stackallocated arguments object");
7799       return false;
7800     }
7801   }
7802
7803   // All declarations must be inlineable.
7804   ZoneList<Declaration*>* decls = target_info.scope()->declarations();
7805   int decl_count = decls->length();
7806   for (int i = 0; i < decl_count; ++i) {
7807     if (!decls->at(i)->IsInlineable()) {
7808       TraceInline(target, caller, "target has non-trivial declaration");
7809       return false;
7810     }
7811   }
7812
7813   // Generate the deoptimization data for the unoptimized version of
7814   // the target function if we don't already have it.
7815   if (!target_shared->has_deoptimization_support()) {
7816     // Note that we compile here using the same AST that we will use for
7817     // generating the optimized inline code.
7818     target_info.EnableDeoptimizationSupport();
7819     if (!FullCodeGenerator::MakeCode(&target_info)) {
7820       TraceInline(target, caller, "could not generate deoptimization info");
7821       return false;
7822     }
7823     if (target_shared->scope_info() == ScopeInfo::Empty(isolate())) {
7824       // The scope info might not have been set if a lazily compiled
7825       // function is inlined before being called for the first time.
7826       Handle<ScopeInfo> target_scope_info =
7827           ScopeInfo::Create(target_info.scope(), zone());
7828       target_shared->set_scope_info(*target_scope_info);
7829     }
7830     target_shared->EnableDeoptimizationSupport(*target_info.code());
7831     target_shared->set_feedback_vector(*target_info.feedback_vector());
7832     Compiler::RecordFunctionCompilation(Logger::FUNCTION_TAG,
7833                                         &target_info,
7834                                         target_shared);
7835   }
7836
7837   // ----------------------------------------------------------------
7838   // After this point, we've made a decision to inline this function (so
7839   // TryInline should always return true).
7840
7841   // Type-check the inlined function.
7842   DCHECK(target_shared->has_deoptimization_support());
7843   AstTyper::Run(&target_info);
7844
7845   int function_id = graph()->TraceInlinedFunction(target_shared, position);
7846
7847   // Save the pending call context. Set up new one for the inlined function.
7848   // The function state is new-allocated because we need to delete it
7849   // in two different places.
7850   FunctionState* target_state = new FunctionState(
7851       this, &target_info, inlining_kind, function_id);
7852
7853   HConstant* undefined = graph()->GetConstantUndefined();
7854
7855   HEnvironment* inner_env =
7856       environment()->CopyForInlining(target,
7857                                      arguments_count,
7858                                      function,
7859                                      undefined,
7860                                      function_state()->inlining_kind());
7861
7862   HConstant* context = Add<HConstant>(Handle<Context>(target->context()));
7863   inner_env->BindContext(context);
7864
7865   // Create a dematerialized arguments object for the function, also copy the
7866   // current arguments values to use them for materialization.
7867   HEnvironment* arguments_env = inner_env->arguments_environment();
7868   int parameter_count = arguments_env->parameter_count();
7869   HArgumentsObject* arguments_object = Add<HArgumentsObject>(parameter_count);
7870   for (int i = 0; i < parameter_count; i++) {
7871     arguments_object->AddArgument(arguments_env->Lookup(i), zone());
7872   }
7873
7874   // If the function uses arguments object then bind bind one.
7875   if (function->scope()->arguments() != NULL) {
7876     DCHECK(function->scope()->arguments()->IsStackAllocated());
7877     inner_env->Bind(function->scope()->arguments(), arguments_object);
7878   }
7879
7880   // Capture the state before invoking the inlined function for deopt in the
7881   // inlined function. This simulate has no bailout-id since it's not directly
7882   // reachable for deopt, and is only used to capture the state. If the simulate
7883   // becomes reachable by merging, the ast id of the simulate merged into it is
7884   // adopted.
7885   Add<HSimulate>(BailoutId::None());
7886
7887   current_block()->UpdateEnvironment(inner_env);
7888   Scope* saved_scope = scope();
7889   set_scope(target_info.scope());
7890   HEnterInlined* enter_inlined =
7891       Add<HEnterInlined>(return_id, target, arguments_count, function,
7892                          function_state()->inlining_kind(),
7893                          function->scope()->arguments(),
7894                          arguments_object);
7895   function_state()->set_entry(enter_inlined);
7896
7897   VisitDeclarations(target_info.scope()->declarations());
7898   VisitStatements(function->body());
7899   set_scope(saved_scope);
7900   if (HasStackOverflow()) {
7901     // Bail out if the inline function did, as we cannot residualize a call
7902     // instead.
7903     TraceInline(target, caller, "inline graph construction failed");
7904     target_shared->DisableOptimization(kInliningBailedOut);
7905     inline_bailout_ = true;
7906     delete target_state;
7907     return true;
7908   }
7909
7910   // Update inlined nodes count.
7911   inlined_count_ += nodes_added;
7912
7913   Handle<Code> unoptimized_code(target_shared->code());
7914   DCHECK(unoptimized_code->kind() == Code::FUNCTION);
7915   Handle<TypeFeedbackInfo> type_info(
7916       TypeFeedbackInfo::cast(unoptimized_code->type_feedback_info()));
7917   graph()->update_type_change_checksum(type_info->own_type_change_checksum());
7918
7919   TraceInline(target, caller, NULL);
7920
7921   if (current_block() != NULL) {
7922     FunctionState* state = function_state();
7923     if (state->inlining_kind() == CONSTRUCT_CALL_RETURN) {
7924       // Falling off the end of an inlined construct call. In a test context the
7925       // return value will always evaluate to true, in a value context the
7926       // return value is the newly allocated receiver.
7927       if (call_context()->IsTest()) {
7928         Goto(inlined_test_context()->if_true(), state);
7929       } else if (call_context()->IsEffect()) {
7930         Goto(function_return(), state);
7931       } else {
7932         DCHECK(call_context()->IsValue());
7933         AddLeaveInlined(implicit_return_value, state);
7934       }
7935     } else if (state->inlining_kind() == SETTER_CALL_RETURN) {
7936       // Falling off the end of an inlined setter call. The returned value is
7937       // never used, the value of an assignment is always the value of the RHS
7938       // of the assignment.
7939       if (call_context()->IsTest()) {
7940         inlined_test_context()->ReturnValue(implicit_return_value);
7941       } else if (call_context()->IsEffect()) {
7942         Goto(function_return(), state);
7943       } else {
7944         DCHECK(call_context()->IsValue());
7945         AddLeaveInlined(implicit_return_value, state);
7946       }
7947     } else {
7948       // Falling off the end of a normal inlined function. This basically means
7949       // returning undefined.
7950       if (call_context()->IsTest()) {
7951         Goto(inlined_test_context()->if_false(), state);
7952       } else if (call_context()->IsEffect()) {
7953         Goto(function_return(), state);
7954       } else {
7955         DCHECK(call_context()->IsValue());
7956         AddLeaveInlined(undefined, state);
7957       }
7958     }
7959   }
7960
7961   // Fix up the function exits.
7962   if (inlined_test_context() != NULL) {
7963     HBasicBlock* if_true = inlined_test_context()->if_true();
7964     HBasicBlock* if_false = inlined_test_context()->if_false();
7965
7966     HEnterInlined* entry = function_state()->entry();
7967
7968     // Pop the return test context from the expression context stack.
7969     DCHECK(ast_context() == inlined_test_context());
7970     ClearInlinedTestContext();
7971     delete target_state;
7972
7973     // Forward to the real test context.
7974     if (if_true->HasPredecessor()) {
7975       entry->RegisterReturnTarget(if_true, zone());
7976       if_true->SetJoinId(ast_id);
7977       HBasicBlock* true_target = TestContext::cast(ast_context())->if_true();
7978       Goto(if_true, true_target, function_state());
7979     }
7980     if (if_false->HasPredecessor()) {
7981       entry->RegisterReturnTarget(if_false, zone());
7982       if_false->SetJoinId(ast_id);
7983       HBasicBlock* false_target = TestContext::cast(ast_context())->if_false();
7984       Goto(if_false, false_target, function_state());
7985     }
7986     set_current_block(NULL);
7987     return true;
7988
7989   } else if (function_return()->HasPredecessor()) {
7990     function_state()->entry()->RegisterReturnTarget(function_return(), zone());
7991     function_return()->SetJoinId(ast_id);
7992     set_current_block(function_return());
7993   } else {
7994     set_current_block(NULL);
7995   }
7996   delete target_state;
7997   return true;
7998 }
7999
8000
8001 bool HOptimizedGraphBuilder::TryInlineCall(Call* expr) {
8002   return TryInline(expr->target(),
8003                    expr->arguments()->length(),
8004                    NULL,
8005                    expr->id(),
8006                    expr->ReturnId(),
8007                    NORMAL_RETURN,
8008                    ScriptPositionToSourcePosition(expr->position()));
8009 }
8010
8011
8012 bool HOptimizedGraphBuilder::TryInlineConstruct(CallNew* expr,
8013                                                 HValue* implicit_return_value) {
8014   return TryInline(expr->target(),
8015                    expr->arguments()->length(),
8016                    implicit_return_value,
8017                    expr->id(),
8018                    expr->ReturnId(),
8019                    CONSTRUCT_CALL_RETURN,
8020                    ScriptPositionToSourcePosition(expr->position()));
8021 }
8022
8023
8024 bool HOptimizedGraphBuilder::TryInlineGetter(Handle<JSFunction> getter,
8025                                              Handle<Map> receiver_map,
8026                                              BailoutId ast_id,
8027                                              BailoutId return_id) {
8028   if (TryInlineApiGetter(getter, receiver_map, ast_id)) return true;
8029   return TryInline(getter,
8030                    0,
8031                    NULL,
8032                    ast_id,
8033                    return_id,
8034                    GETTER_CALL_RETURN,
8035                    source_position());
8036 }
8037
8038
8039 bool HOptimizedGraphBuilder::TryInlineSetter(Handle<JSFunction> setter,
8040                                              Handle<Map> receiver_map,
8041                                              BailoutId id,
8042                                              BailoutId assignment_id,
8043                                              HValue* implicit_return_value) {
8044   if (TryInlineApiSetter(setter, receiver_map, id)) return true;
8045   return TryInline(setter,
8046                    1,
8047                    implicit_return_value,
8048                    id, assignment_id,
8049                    SETTER_CALL_RETURN,
8050                    source_position());
8051 }
8052
8053
8054 bool HOptimizedGraphBuilder::TryInlineApply(Handle<JSFunction> function,
8055                                             Call* expr,
8056                                             int arguments_count) {
8057   return TryInline(function,
8058                    arguments_count,
8059                    NULL,
8060                    expr->id(),
8061                    expr->ReturnId(),
8062                    NORMAL_RETURN,
8063                    ScriptPositionToSourcePosition(expr->position()));
8064 }
8065
8066
8067 bool HOptimizedGraphBuilder::TryInlineBuiltinFunctionCall(Call* expr) {
8068   if (!expr->target()->shared()->HasBuiltinFunctionId()) return false;
8069   BuiltinFunctionId id = expr->target()->shared()->builtin_function_id();
8070   switch (id) {
8071     case kMathExp:
8072       if (!FLAG_fast_math) break;
8073       // Fall through if FLAG_fast_math.
8074     case kMathRound:
8075     case kMathFround:
8076     case kMathFloor:
8077     case kMathAbs:
8078     case kMathSqrt:
8079     case kMathLog:
8080     case kMathClz32:
8081       if (expr->arguments()->length() == 1) {
8082         HValue* argument = Pop();
8083         Drop(2);  // Receiver and function.
8084         HInstruction* op = NewUncasted<HUnaryMathOperation>(argument, id);
8085         ast_context()->ReturnInstruction(op, expr->id());
8086         return true;
8087       }
8088       break;
8089     case kMathImul:
8090       if (expr->arguments()->length() == 2) {
8091         HValue* right = Pop();
8092         HValue* left = Pop();
8093         Drop(2);  // Receiver and function.
8094         HInstruction* op = HMul::NewImul(zone(), context(), left, right);
8095         ast_context()->ReturnInstruction(op, expr->id());
8096         return true;
8097       }
8098       break;
8099     default:
8100       // Not supported for inlining yet.
8101       break;
8102   }
8103   return false;
8104 }
8105
8106
8107 bool HOptimizedGraphBuilder::TryInlineBuiltinMethodCall(
8108     Call* expr,
8109     HValue* receiver,
8110     Handle<Map> receiver_map) {
8111   // Try to inline calls like Math.* as operations in the calling function.
8112   if (!expr->target()->shared()->HasBuiltinFunctionId()) return false;
8113   BuiltinFunctionId id = expr->target()->shared()->builtin_function_id();
8114   int argument_count = expr->arguments()->length() + 1;  // Plus receiver.
8115   switch (id) {
8116     case kStringCharCodeAt:
8117     case kStringCharAt:
8118       if (argument_count == 2) {
8119         HValue* index = Pop();
8120         HValue* string = Pop();
8121         Drop(1);  // Function.
8122         HInstruction* char_code =
8123             BuildStringCharCodeAt(string, index);
8124         if (id == kStringCharCodeAt) {
8125           ast_context()->ReturnInstruction(char_code, expr->id());
8126           return true;
8127         }
8128         AddInstruction(char_code);
8129         HInstruction* result = NewUncasted<HStringCharFromCode>(char_code);
8130         ast_context()->ReturnInstruction(result, expr->id());
8131         return true;
8132       }
8133       break;
8134     case kStringFromCharCode:
8135       if (argument_count == 2) {
8136         HValue* argument = Pop();
8137         Drop(2);  // Receiver and function.
8138         HInstruction* result = NewUncasted<HStringCharFromCode>(argument);
8139         ast_context()->ReturnInstruction(result, expr->id());
8140         return true;
8141       }
8142       break;
8143     case kMathExp:
8144       if (!FLAG_fast_math) break;
8145       // Fall through if FLAG_fast_math.
8146     case kMathRound:
8147     case kMathFround:
8148     case kMathFloor:
8149     case kMathAbs:
8150     case kMathSqrt:
8151     case kMathLog:
8152     case kMathClz32:
8153       if (argument_count == 2) {
8154         HValue* argument = Pop();
8155         Drop(2);  // Receiver and function.
8156         HInstruction* op = NewUncasted<HUnaryMathOperation>(argument, id);
8157         ast_context()->ReturnInstruction(op, expr->id());
8158         return true;
8159       }
8160       break;
8161     case kMathPow:
8162       if (argument_count == 3) {
8163         HValue* right = Pop();
8164         HValue* left = Pop();
8165         Drop(2);  // Receiver and function.
8166         HInstruction* result = NULL;
8167         // Use sqrt() if exponent is 0.5 or -0.5.
8168         if (right->IsConstant() && HConstant::cast(right)->HasDoubleValue()) {
8169           double exponent = HConstant::cast(right)->DoubleValue();
8170           if (exponent == 0.5) {
8171             result = NewUncasted<HUnaryMathOperation>(left, kMathPowHalf);
8172           } else if (exponent == -0.5) {
8173             HValue* one = graph()->GetConstant1();
8174             HInstruction* sqrt = AddUncasted<HUnaryMathOperation>(
8175                 left, kMathPowHalf);
8176             // MathPowHalf doesn't have side effects so there's no need for
8177             // an environment simulation here.
8178             DCHECK(!sqrt->HasObservableSideEffects());
8179             result = NewUncasted<HDiv>(one, sqrt);
8180           } else if (exponent == 2.0) {
8181             result = NewUncasted<HMul>(left, left);
8182           }
8183         }
8184
8185         if (result == NULL) {
8186           result = NewUncasted<HPower>(left, right);
8187         }
8188         ast_context()->ReturnInstruction(result, expr->id());
8189         return true;
8190       }
8191       break;
8192     case kMathMax:
8193     case kMathMin:
8194       if (argument_count == 3) {
8195         HValue* right = Pop();
8196         HValue* left = Pop();
8197         Drop(2);  // Receiver and function.
8198         HMathMinMax::Operation op = (id == kMathMin) ? HMathMinMax::kMathMin
8199                                                      : HMathMinMax::kMathMax;
8200         HInstruction* result = NewUncasted<HMathMinMax>(left, right, op);
8201         ast_context()->ReturnInstruction(result, expr->id());
8202         return true;
8203       }
8204       break;
8205     case kMathImul:
8206       if (argument_count == 3) {
8207         HValue* right = Pop();
8208         HValue* left = Pop();
8209         Drop(2);  // Receiver and function.
8210         HInstruction* result = HMul::NewImul(zone(), context(), left, right);
8211         ast_context()->ReturnInstruction(result, expr->id());
8212         return true;
8213       }
8214       break;
8215     case kArrayPop: {
8216       if (receiver_map.is_null()) return false;
8217       if (receiver_map->instance_type() != JS_ARRAY_TYPE) return false;
8218       ElementsKind elements_kind = receiver_map->elements_kind();
8219       if (!IsFastElementsKind(elements_kind)) return false;
8220       if (receiver_map->is_observed()) return false;
8221       DCHECK(receiver_map->is_extensible());
8222
8223       Drop(expr->arguments()->length());
8224       HValue* result;
8225       HValue* reduced_length;
8226       HValue* receiver = Pop();
8227
8228       HValue* checked_object = AddCheckMap(receiver, receiver_map);
8229       HValue* length = Add<HLoadNamedField>(
8230           checked_object, static_cast<HValue*>(NULL),
8231           HObjectAccess::ForArrayLength(elements_kind));
8232
8233       Drop(1);  // Function.
8234
8235       { NoObservableSideEffectsScope scope(this);
8236         IfBuilder length_checker(this);
8237
8238         HValue* bounds_check = length_checker.If<HCompareNumericAndBranch>(
8239             length, graph()->GetConstant0(), Token::EQ);
8240         length_checker.Then();
8241
8242         if (!ast_context()->IsEffect()) Push(graph()->GetConstantUndefined());
8243
8244         length_checker.Else();
8245         HValue* elements = AddLoadElements(checked_object);
8246         // Ensure that we aren't popping from a copy-on-write array.
8247         if (IsFastSmiOrObjectElementsKind(elements_kind)) {
8248           elements = BuildCopyElementsOnWrite(checked_object, elements,
8249                                               elements_kind, length);
8250         }
8251         reduced_length = AddUncasted<HSub>(length, graph()->GetConstant1());
8252         result = AddElementAccess(elements, reduced_length, NULL,
8253                                   bounds_check, elements_kind, LOAD);
8254         Factory* factory = isolate()->factory();
8255         double nan_double = FixedDoubleArray::hole_nan_as_double();
8256         HValue* hole = IsFastSmiOrObjectElementsKind(elements_kind)
8257             ? Add<HConstant>(factory->the_hole_value())
8258             : Add<HConstant>(nan_double);
8259         if (IsFastSmiOrObjectElementsKind(elements_kind)) {
8260           elements_kind = FAST_HOLEY_ELEMENTS;
8261         }
8262         AddElementAccess(
8263             elements, reduced_length, hole, bounds_check, elements_kind, STORE);
8264         Add<HStoreNamedField>(
8265             checked_object, HObjectAccess::ForArrayLength(elements_kind),
8266             reduced_length, STORE_TO_INITIALIZED_ENTRY);
8267
8268         if (!ast_context()->IsEffect()) Push(result);
8269
8270         length_checker.End();
8271       }
8272       result = ast_context()->IsEffect() ? graph()->GetConstant0() : Top();
8273       Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
8274       if (!ast_context()->IsEffect()) Drop(1);
8275
8276       ast_context()->ReturnValue(result);
8277       return true;
8278     }
8279     case kArrayPush: {
8280       if (receiver_map.is_null()) return false;
8281       if (receiver_map->instance_type() != JS_ARRAY_TYPE) return false;
8282       ElementsKind elements_kind = receiver_map->elements_kind();
8283       if (!IsFastElementsKind(elements_kind)) return false;
8284       if (receiver_map->is_observed()) return false;
8285       if (JSArray::IsReadOnlyLengthDescriptor(receiver_map)) return false;
8286       DCHECK(receiver_map->is_extensible());
8287
8288       // If there may be elements accessors in the prototype chain, the fast
8289       // inlined version can't be used.
8290       if (receiver_map->DictionaryElementsInPrototypeChainOnly()) return false;
8291       // If there currently can be no elements accessors on the prototype chain,
8292       // it doesn't mean that there won't be any later. Install a full prototype
8293       // chain check to trap element accessors being installed on the prototype
8294       // chain, which would cause elements to go to dictionary mode and result
8295       // in a map change.
8296       Handle<JSObject> prototype(JSObject::cast(receiver_map->prototype()));
8297       BuildCheckPrototypeMaps(prototype, Handle<JSObject>());
8298
8299       const int argc = expr->arguments()->length();
8300       if (argc != 1) return false;
8301
8302       HValue* value_to_push = Pop();
8303       HValue* array = Pop();
8304       Drop(1);  // Drop function.
8305
8306       HInstruction* new_size = NULL;
8307       HValue* length = NULL;
8308
8309       {
8310         NoObservableSideEffectsScope scope(this);
8311
8312         length = Add<HLoadNamedField>(array, static_cast<HValue*>(NULL),
8313           HObjectAccess::ForArrayLength(elements_kind));
8314
8315         new_size = AddUncasted<HAdd>(length, graph()->GetConstant1());
8316
8317         bool is_array = receiver_map->instance_type() == JS_ARRAY_TYPE;
8318         BuildUncheckedMonomorphicElementAccess(array, length,
8319                                                value_to_push, is_array,
8320                                                elements_kind, STORE,
8321                                                NEVER_RETURN_HOLE,
8322                                                STORE_AND_GROW_NO_TRANSITION);
8323
8324         if (!ast_context()->IsEffect()) Push(new_size);
8325         Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
8326         if (!ast_context()->IsEffect()) Drop(1);
8327       }
8328
8329       ast_context()->ReturnValue(new_size);
8330       return true;
8331     }
8332     case kArrayShift: {
8333       if (receiver_map.is_null()) return false;
8334       if (receiver_map->instance_type() != JS_ARRAY_TYPE) return false;
8335       ElementsKind kind = receiver_map->elements_kind();
8336       if (!IsFastElementsKind(kind)) return false;
8337       if (receiver_map->is_observed()) return false;
8338       DCHECK(receiver_map->is_extensible());
8339
8340       // If there may be elements accessors in the prototype chain, the fast
8341       // inlined version can't be used.
8342       if (receiver_map->DictionaryElementsInPrototypeChainOnly()) return false;
8343
8344       // If there currently can be no elements accessors on the prototype chain,
8345       // it doesn't mean that there won't be any later. Install a full prototype
8346       // chain check to trap element accessors being installed on the prototype
8347       // chain, which would cause elements to go to dictionary mode and result
8348       // in a map change.
8349       BuildCheckPrototypeMaps(
8350           handle(JSObject::cast(receiver_map->prototype()), isolate()),
8351           Handle<JSObject>::null());
8352
8353       // Threshold for fast inlined Array.shift().
8354       HConstant* inline_threshold = Add<HConstant>(static_cast<int32_t>(16));
8355
8356       Drop(expr->arguments()->length());
8357       HValue* receiver = Pop();
8358       HValue* function = Pop();
8359       HValue* result;
8360
8361       {
8362         NoObservableSideEffectsScope scope(this);
8363
8364         HValue* length = Add<HLoadNamedField>(
8365             receiver, static_cast<HValue*>(NULL),
8366             HObjectAccess::ForArrayLength(kind));
8367
8368         IfBuilder if_lengthiszero(this);
8369         HValue* lengthiszero = if_lengthiszero.If<HCompareNumericAndBranch>(
8370             length, graph()->GetConstant0(), Token::EQ);
8371         if_lengthiszero.Then();
8372         {
8373           if (!ast_context()->IsEffect()) Push(graph()->GetConstantUndefined());
8374         }
8375         if_lengthiszero.Else();
8376         {
8377           HValue* elements = AddLoadElements(receiver);
8378
8379           // Check if we can use the fast inlined Array.shift().
8380           IfBuilder if_inline(this);
8381           if_inline.If<HCompareNumericAndBranch>(
8382               length, inline_threshold, Token::LTE);
8383           if (IsFastSmiOrObjectElementsKind(kind)) {
8384             // We cannot handle copy-on-write backing stores here.
8385             if_inline.AndIf<HCompareMap>(
8386                 elements, isolate()->factory()->fixed_array_map());
8387           }
8388           if_inline.Then();
8389           {
8390             // Remember the result.
8391             if (!ast_context()->IsEffect()) {
8392               Push(AddElementAccess(elements, graph()->GetConstant0(), NULL,
8393                                     lengthiszero, kind, LOAD));
8394             }
8395
8396             // Compute the new length.
8397             HValue* new_length = AddUncasted<HSub>(
8398                 length, graph()->GetConstant1());
8399             new_length->ClearFlag(HValue::kCanOverflow);
8400
8401             // Copy the remaining elements.
8402             LoopBuilder loop(this, context(), LoopBuilder::kPostIncrement);
8403             {
8404               HValue* new_key = loop.BeginBody(
8405                   graph()->GetConstant0(), new_length, Token::LT);
8406               HValue* key = AddUncasted<HAdd>(new_key, graph()->GetConstant1());
8407               key->ClearFlag(HValue::kCanOverflow);
8408               HValue* element = AddUncasted<HLoadKeyed>(
8409                   elements, key, lengthiszero, kind, ALLOW_RETURN_HOLE);
8410               HStoreKeyed* store = Add<HStoreKeyed>(
8411                   elements, new_key, element, kind);
8412               store->SetFlag(HValue::kAllowUndefinedAsNaN);
8413             }
8414             loop.EndBody();
8415
8416             // Put a hole at the end.
8417             HValue* hole = IsFastSmiOrObjectElementsKind(kind)
8418                 ? Add<HConstant>(isolate()->factory()->the_hole_value())
8419                 : Add<HConstant>(FixedDoubleArray::hole_nan_as_double());
8420             if (IsFastSmiOrObjectElementsKind(kind)) kind = FAST_HOLEY_ELEMENTS;
8421             Add<HStoreKeyed>(
8422                 elements, new_length, hole, kind, INITIALIZING_STORE);
8423
8424             // Remember new length.
8425             Add<HStoreNamedField>(
8426                 receiver, HObjectAccess::ForArrayLength(kind),
8427                 new_length, STORE_TO_INITIALIZED_ENTRY);
8428           }
8429           if_inline.Else();
8430           {
8431             Add<HPushArguments>(receiver);
8432             result = Add<HCallJSFunction>(function, 1, true);
8433             if (!ast_context()->IsEffect()) Push(result);
8434           }
8435           if_inline.End();
8436         }
8437         if_lengthiszero.End();
8438       }
8439       result = ast_context()->IsEffect() ? graph()->GetConstant0() : Top();
8440       Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
8441       if (!ast_context()->IsEffect()) Drop(1);
8442       ast_context()->ReturnValue(result);
8443       return true;
8444     }
8445     case kArrayIndexOf:
8446     case kArrayLastIndexOf: {
8447       if (receiver_map.is_null()) return false;
8448       if (receiver_map->instance_type() != JS_ARRAY_TYPE) return false;
8449       ElementsKind kind = receiver_map->elements_kind();
8450       if (!IsFastElementsKind(kind)) return false;
8451       if (receiver_map->is_observed()) return false;
8452       if (argument_count != 2) return false;
8453       DCHECK(receiver_map->is_extensible());
8454
8455       // If there may be elements accessors in the prototype chain, the fast
8456       // inlined version can't be used.
8457       if (receiver_map->DictionaryElementsInPrototypeChainOnly()) return false;
8458
8459       // If there currently can be no elements accessors on the prototype chain,
8460       // it doesn't mean that there won't be any later. Install a full prototype
8461       // chain check to trap element accessors being installed on the prototype
8462       // chain, which would cause elements to go to dictionary mode and result
8463       // in a map change.
8464       BuildCheckPrototypeMaps(
8465           handle(JSObject::cast(receiver_map->prototype()), isolate()),
8466           Handle<JSObject>::null());
8467
8468       HValue* search_element = Pop();
8469       HValue* receiver = Pop();
8470       Drop(1);  // Drop function.
8471
8472       ArrayIndexOfMode mode = (id == kArrayIndexOf)
8473           ? kFirstIndexOf : kLastIndexOf;
8474       HValue* index = BuildArrayIndexOf(receiver, search_element, kind, mode);
8475
8476       if (!ast_context()->IsEffect()) Push(index);
8477       Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
8478       if (!ast_context()->IsEffect()) Drop(1);
8479       ast_context()->ReturnValue(index);
8480       return true;
8481     }
8482     default:
8483       // Not yet supported for inlining.
8484       break;
8485   }
8486   return false;
8487 }
8488
8489
8490 bool HOptimizedGraphBuilder::TryInlineApiFunctionCall(Call* expr,
8491                                                       HValue* receiver) {
8492   Handle<JSFunction> function = expr->target();
8493   int argc = expr->arguments()->length();
8494   SmallMapList receiver_maps;
8495   return TryInlineApiCall(function,
8496                           receiver,
8497                           &receiver_maps,
8498                           argc,
8499                           expr->id(),
8500                           kCallApiFunction);
8501 }
8502
8503
8504 bool HOptimizedGraphBuilder::TryInlineApiMethodCall(
8505     Call* expr,
8506     HValue* receiver,
8507     SmallMapList* receiver_maps) {
8508   Handle<JSFunction> function = expr->target();
8509   int argc = expr->arguments()->length();
8510   return TryInlineApiCall(function,
8511                           receiver,
8512                           receiver_maps,
8513                           argc,
8514                           expr->id(),
8515                           kCallApiMethod);
8516 }
8517
8518
8519 bool HOptimizedGraphBuilder::TryInlineApiGetter(Handle<JSFunction> function,
8520                                                 Handle<Map> receiver_map,
8521                                                 BailoutId ast_id) {
8522   SmallMapList receiver_maps(1, zone());
8523   receiver_maps.Add(receiver_map, zone());
8524   return TryInlineApiCall(function,
8525                           NULL,  // Receiver is on expression stack.
8526                           &receiver_maps,
8527                           0,
8528                           ast_id,
8529                           kCallApiGetter);
8530 }
8531
8532
8533 bool HOptimizedGraphBuilder::TryInlineApiSetter(Handle<JSFunction> function,
8534                                                 Handle<Map> receiver_map,
8535                                                 BailoutId ast_id) {
8536   SmallMapList receiver_maps(1, zone());
8537   receiver_maps.Add(receiver_map, zone());
8538   return TryInlineApiCall(function,
8539                           NULL,  // Receiver is on expression stack.
8540                           &receiver_maps,
8541                           1,
8542                           ast_id,
8543                           kCallApiSetter);
8544 }
8545
8546
8547 bool HOptimizedGraphBuilder::TryInlineApiCall(Handle<JSFunction> function,
8548                                                HValue* receiver,
8549                                                SmallMapList* receiver_maps,
8550                                                int argc,
8551                                                BailoutId ast_id,
8552                                                ApiCallType call_type) {
8553   CallOptimization optimization(function);
8554   if (!optimization.is_simple_api_call()) return false;
8555   Handle<Map> holder_map;
8556   if (call_type == kCallApiFunction) {
8557     // Cannot embed a direct reference to the global proxy map
8558     // as it maybe dropped on deserialization.
8559     CHECK(!isolate()->serializer_enabled());
8560     DCHECK_EQ(0, receiver_maps->length());
8561     receiver_maps->Add(handle(function->global_proxy()->map()), zone());
8562   }
8563   CallOptimization::HolderLookup holder_lookup =
8564       CallOptimization::kHolderNotFound;
8565   Handle<JSObject> api_holder = optimization.LookupHolderOfExpectedType(
8566       receiver_maps->first(), &holder_lookup);
8567   if (holder_lookup == CallOptimization::kHolderNotFound) return false;
8568
8569   if (FLAG_trace_inlining) {
8570     PrintF("Inlining api function ");
8571     function->ShortPrint();
8572     PrintF("\n");
8573   }
8574
8575   bool drop_extra = false;
8576   bool is_store = false;
8577   switch (call_type) {
8578     case kCallApiFunction:
8579     case kCallApiMethod:
8580       // Need to check that none of the receiver maps could have changed.
8581       Add<HCheckMaps>(receiver, receiver_maps);
8582       // Need to ensure the chain between receiver and api_holder is intact.
8583       if (holder_lookup == CallOptimization::kHolderFound) {
8584         AddCheckPrototypeMaps(api_holder, receiver_maps->first());
8585       } else {
8586         DCHECK_EQ(holder_lookup, CallOptimization::kHolderIsReceiver);
8587       }
8588       // Includes receiver.
8589       PushArgumentsFromEnvironment(argc + 1);
8590       // Drop function after call.
8591       drop_extra = true;
8592       break;
8593     case kCallApiGetter:
8594       // Receiver and prototype chain cannot have changed.
8595       DCHECK_EQ(0, argc);
8596       DCHECK_EQ(NULL, receiver);
8597       // Receiver is on expression stack.
8598       receiver = Pop();
8599       Add<HPushArguments>(receiver);
8600       break;
8601     case kCallApiSetter:
8602       {
8603         is_store = true;
8604         // Receiver and prototype chain cannot have changed.
8605         DCHECK_EQ(1, argc);
8606         DCHECK_EQ(NULL, receiver);
8607         // Receiver and value are on expression stack.
8608         HValue* value = Pop();
8609         receiver = Pop();
8610         Add<HPushArguments>(receiver, value);
8611         break;
8612      }
8613   }
8614
8615   HValue* holder = NULL;
8616   switch (holder_lookup) {
8617     case CallOptimization::kHolderFound:
8618       holder = Add<HConstant>(api_holder);
8619       break;
8620     case CallOptimization::kHolderIsReceiver:
8621       holder = receiver;
8622       break;
8623     case CallOptimization::kHolderNotFound:
8624       UNREACHABLE();
8625       break;
8626   }
8627   Handle<CallHandlerInfo> api_call_info = optimization.api_call_info();
8628   Handle<Object> call_data_obj(api_call_info->data(), isolate());
8629   bool call_data_is_undefined = call_data_obj->IsUndefined();
8630   HValue* call_data = Add<HConstant>(call_data_obj);
8631   ApiFunction fun(v8::ToCData<Address>(api_call_info->callback()));
8632   ExternalReference ref = ExternalReference(&fun,
8633                                             ExternalReference::DIRECT_API_CALL,
8634                                             isolate());
8635   HValue* api_function_address = Add<HConstant>(ExternalReference(ref));
8636
8637   HValue* op_vals[] = {
8638     context(),
8639     Add<HConstant>(function),
8640     call_data,
8641     holder,
8642     api_function_address
8643   };
8644
8645   CallInterfaceDescriptor* descriptor =
8646       isolate()->call_descriptor(Isolate::ApiFunctionCall);
8647
8648   CallApiFunctionStub stub(isolate(), is_store, call_data_is_undefined, argc);
8649   Handle<Code> code = stub.GetCode();
8650   HConstant* code_value = Add<HConstant>(code);
8651
8652   DCHECK((sizeof(op_vals) / kPointerSize) ==
8653          descriptor->GetEnvironmentLength());
8654
8655   HInstruction* call = New<HCallWithDescriptor>(
8656       code_value, argc + 1, descriptor,
8657       Vector<HValue*>(op_vals, descriptor->GetEnvironmentLength()));
8658
8659   if (drop_extra) Drop(1);  // Drop function.
8660   ast_context()->ReturnInstruction(call, ast_id);
8661   return true;
8662 }
8663
8664
8665 bool HOptimizedGraphBuilder::TryCallApply(Call* expr) {
8666   DCHECK(expr->expression()->IsProperty());
8667
8668   if (!expr->IsMonomorphic()) {
8669     return false;
8670   }
8671   Handle<Map> function_map = expr->GetReceiverTypes()->first();
8672   if (function_map->instance_type() != JS_FUNCTION_TYPE ||
8673       !expr->target()->shared()->HasBuiltinFunctionId() ||
8674       expr->target()->shared()->builtin_function_id() != kFunctionApply) {
8675     return false;
8676   }
8677
8678   if (current_info()->scope()->arguments() == NULL) return false;
8679
8680   ZoneList<Expression*>* args = expr->arguments();
8681   if (args->length() != 2) return false;
8682
8683   VariableProxy* arg_two = args->at(1)->AsVariableProxy();
8684   if (arg_two == NULL || !arg_two->var()->IsStackAllocated()) return false;
8685   HValue* arg_two_value = LookupAndMakeLive(arg_two->var());
8686   if (!arg_two_value->CheckFlag(HValue::kIsArguments)) return false;
8687
8688   // Found pattern f.apply(receiver, arguments).
8689   CHECK_ALIVE_OR_RETURN(VisitForValue(args->at(0)), true);
8690   HValue* receiver = Pop();  // receiver
8691   HValue* function = Pop();  // f
8692   Drop(1);  // apply
8693
8694   HValue* checked_function = AddCheckMap(function, function_map);
8695
8696   if (function_state()->outer() == NULL) {
8697     HInstruction* elements = Add<HArgumentsElements>(false);
8698     HInstruction* length = Add<HArgumentsLength>(elements);
8699     HValue* wrapped_receiver = BuildWrapReceiver(receiver, checked_function);
8700     HInstruction* result = New<HApplyArguments>(function,
8701                                                 wrapped_receiver,
8702                                                 length,
8703                                                 elements);
8704     ast_context()->ReturnInstruction(result, expr->id());
8705     return true;
8706   } else {
8707     // We are inside inlined function and we know exactly what is inside
8708     // arguments object. But we need to be able to materialize at deopt.
8709     DCHECK_EQ(environment()->arguments_environment()->parameter_count(),
8710               function_state()->entry()->arguments_object()->arguments_count());
8711     HArgumentsObject* args = function_state()->entry()->arguments_object();
8712     const ZoneList<HValue*>* arguments_values = args->arguments_values();
8713     int arguments_count = arguments_values->length();
8714     Push(function);
8715     Push(BuildWrapReceiver(receiver, checked_function));
8716     for (int i = 1; i < arguments_count; i++) {
8717       Push(arguments_values->at(i));
8718     }
8719
8720     Handle<JSFunction> known_function;
8721     if (function->IsConstant() &&
8722         HConstant::cast(function)->handle(isolate())->IsJSFunction()) {
8723       known_function = Handle<JSFunction>::cast(
8724           HConstant::cast(function)->handle(isolate()));
8725       int args_count = arguments_count - 1;  // Excluding receiver.
8726       if (TryInlineApply(known_function, expr, args_count)) return true;
8727     }
8728
8729     PushArgumentsFromEnvironment(arguments_count);
8730     HInvokeFunction* call = New<HInvokeFunction>(
8731         function, known_function, arguments_count);
8732     Drop(1);  // Function.
8733     ast_context()->ReturnInstruction(call, expr->id());
8734     return true;
8735   }
8736 }
8737
8738
8739 HValue* HOptimizedGraphBuilder::ImplicitReceiverFor(HValue* function,
8740                                                     Handle<JSFunction> target) {
8741   SharedFunctionInfo* shared = target->shared();
8742   if (shared->strict_mode() == SLOPPY && !shared->native()) {
8743     // Cannot embed a direct reference to the global proxy
8744     // as is it dropped on deserialization.
8745     CHECK(!isolate()->serializer_enabled());
8746     Handle<JSObject> global_proxy(target->context()->global_proxy());
8747     return Add<HConstant>(global_proxy);
8748   }
8749   return graph()->GetConstantUndefined();
8750 }
8751
8752
8753 void HOptimizedGraphBuilder::BuildArrayCall(Expression* expression,
8754                                             int arguments_count,
8755                                             HValue* function,
8756                                             Handle<AllocationSite> site) {
8757   Add<HCheckValue>(function, array_function());
8758
8759   if (IsCallArrayInlineable(arguments_count, site)) {
8760     BuildInlinedCallArray(expression, arguments_count, site);
8761     return;
8762   }
8763
8764   HInstruction* call = PreProcessCall(New<HCallNewArray>(
8765       function, arguments_count + 1, site->GetElementsKind()));
8766   if (expression->IsCall()) {
8767     Drop(1);
8768   }
8769   ast_context()->ReturnInstruction(call, expression->id());
8770 }
8771
8772
8773 HValue* HOptimizedGraphBuilder::BuildArrayIndexOf(HValue* receiver,
8774                                                   HValue* search_element,
8775                                                   ElementsKind kind,
8776                                                   ArrayIndexOfMode mode) {
8777   DCHECK(IsFastElementsKind(kind));
8778
8779   NoObservableSideEffectsScope no_effects(this);
8780
8781   HValue* elements = AddLoadElements(receiver);
8782   HValue* length = AddLoadArrayLength(receiver, kind);
8783
8784   HValue* initial;
8785   HValue* terminating;
8786   Token::Value token;
8787   LoopBuilder::Direction direction;
8788   if (mode == kFirstIndexOf) {
8789     initial = graph()->GetConstant0();
8790     terminating = length;
8791     token = Token::LT;
8792     direction = LoopBuilder::kPostIncrement;
8793   } else {
8794     DCHECK_EQ(kLastIndexOf, mode);
8795     initial = length;
8796     terminating = graph()->GetConstant0();
8797     token = Token::GT;
8798     direction = LoopBuilder::kPreDecrement;
8799   }
8800
8801   Push(graph()->GetConstantMinus1());
8802   if (IsFastDoubleElementsKind(kind) || IsFastSmiElementsKind(kind)) {
8803     LoopBuilder loop(this, context(), direction);
8804     {
8805       HValue* index = loop.BeginBody(initial, terminating, token);
8806       HValue* element = AddUncasted<HLoadKeyed>(
8807           elements, index, static_cast<HValue*>(NULL),
8808           kind, ALLOW_RETURN_HOLE);
8809       IfBuilder if_issame(this);
8810       if (IsFastDoubleElementsKind(kind)) {
8811         if_issame.If<HCompareNumericAndBranch>(
8812             element, search_element, Token::EQ_STRICT);
8813       } else {
8814         if_issame.If<HCompareObjectEqAndBranch>(element, search_element);
8815       }
8816       if_issame.Then();
8817       {
8818         Drop(1);
8819         Push(index);
8820         loop.Break();
8821       }
8822       if_issame.End();
8823     }
8824     loop.EndBody();
8825   } else {
8826     IfBuilder if_isstring(this);
8827     if_isstring.If<HIsStringAndBranch>(search_element);
8828     if_isstring.Then();
8829     {
8830       LoopBuilder loop(this, context(), direction);
8831       {
8832         HValue* index = loop.BeginBody(initial, terminating, token);
8833         HValue* element = AddUncasted<HLoadKeyed>(
8834             elements, index, static_cast<HValue*>(NULL),
8835             kind, ALLOW_RETURN_HOLE);
8836         IfBuilder if_issame(this);
8837         if_issame.If<HIsStringAndBranch>(element);
8838         if_issame.AndIf<HStringCompareAndBranch>(
8839             element, search_element, Token::EQ_STRICT);
8840         if_issame.Then();
8841         {
8842           Drop(1);
8843           Push(index);
8844           loop.Break();
8845         }
8846         if_issame.End();
8847       }
8848       loop.EndBody();
8849     }
8850     if_isstring.Else();
8851     {
8852       IfBuilder if_isnumber(this);
8853       if_isnumber.If<HIsSmiAndBranch>(search_element);
8854       if_isnumber.OrIf<HCompareMap>(
8855           search_element, isolate()->factory()->heap_number_map());
8856       if_isnumber.Then();
8857       {
8858         HValue* search_number =
8859             AddUncasted<HForceRepresentation>(search_element,
8860                                               Representation::Double());
8861         LoopBuilder loop(this, context(), direction);
8862         {
8863           HValue* index = loop.BeginBody(initial, terminating, token);
8864           HValue* element = AddUncasted<HLoadKeyed>(
8865               elements, index, static_cast<HValue*>(NULL),
8866               kind, ALLOW_RETURN_HOLE);
8867
8868           IfBuilder if_element_isnumber(this);
8869           if_element_isnumber.If<HIsSmiAndBranch>(element);
8870           if_element_isnumber.OrIf<HCompareMap>(
8871               element, isolate()->factory()->heap_number_map());
8872           if_element_isnumber.Then();
8873           {
8874             HValue* number =
8875                 AddUncasted<HForceRepresentation>(element,
8876                                                   Representation::Double());
8877             IfBuilder if_issame(this);
8878             if_issame.If<HCompareNumericAndBranch>(
8879                 number, search_number, Token::EQ_STRICT);
8880             if_issame.Then();
8881             {
8882               Drop(1);
8883               Push(index);
8884               loop.Break();
8885             }
8886             if_issame.End();
8887           }
8888           if_element_isnumber.End();
8889         }
8890         loop.EndBody();
8891       }
8892       if_isnumber.Else();
8893       {
8894         LoopBuilder loop(this, context(), direction);
8895         {
8896           HValue* index = loop.BeginBody(initial, terminating, token);
8897           HValue* element = AddUncasted<HLoadKeyed>(
8898               elements, index, static_cast<HValue*>(NULL),
8899               kind, ALLOW_RETURN_HOLE);
8900           IfBuilder if_issame(this);
8901           if_issame.If<HCompareObjectEqAndBranch>(
8902               element, search_element);
8903           if_issame.Then();
8904           {
8905             Drop(1);
8906             Push(index);
8907             loop.Break();
8908           }
8909           if_issame.End();
8910         }
8911         loop.EndBody();
8912       }
8913       if_isnumber.End();
8914     }
8915     if_isstring.End();
8916   }
8917
8918   return Pop();
8919 }
8920
8921
8922 bool HOptimizedGraphBuilder::TryHandleArrayCall(Call* expr, HValue* function) {
8923   if (!array_function().is_identical_to(expr->target())) {
8924     return false;
8925   }
8926
8927   Handle<AllocationSite> site = expr->allocation_site();
8928   if (site.is_null()) return false;
8929
8930   BuildArrayCall(expr,
8931                  expr->arguments()->length(),
8932                  function,
8933                  site);
8934   return true;
8935 }
8936
8937
8938 bool HOptimizedGraphBuilder::TryHandleArrayCallNew(CallNew* expr,
8939                                                    HValue* function) {
8940   if (!array_function().is_identical_to(expr->target())) {
8941     return false;
8942   }
8943
8944   BuildArrayCall(expr,
8945                  expr->arguments()->length(),
8946                  function,
8947                  expr->allocation_site());
8948   return true;
8949 }
8950
8951
8952 void HOptimizedGraphBuilder::VisitCall(Call* expr) {
8953   DCHECK(!HasStackOverflow());
8954   DCHECK(current_block() != NULL);
8955   DCHECK(current_block()->HasPredecessor());
8956   Expression* callee = expr->expression();
8957   int argument_count = expr->arguments()->length() + 1;  // Plus receiver.
8958   HInstruction* call = NULL;
8959
8960   Property* prop = callee->AsProperty();
8961   if (prop != NULL) {
8962     CHECK_ALIVE(VisitForValue(prop->obj()));
8963     HValue* receiver = Top();
8964
8965     SmallMapList* types;
8966     ComputeReceiverTypes(expr, receiver, &types, zone());
8967
8968     if (prop->key()->IsPropertyName() && types->length() > 0) {
8969       Handle<String> name = prop->key()->AsLiteral()->AsPropertyName();
8970       PropertyAccessInfo info(this, LOAD, ToType(types->first()), name);
8971       if (!info.CanAccessAsMonomorphic(types)) {
8972         HandlePolymorphicCallNamed(expr, receiver, types, name);
8973         return;
8974       }
8975     }
8976
8977     HValue* key = NULL;
8978     if (!prop->key()->IsPropertyName()) {
8979       CHECK_ALIVE(VisitForValue(prop->key()));
8980       key = Pop();
8981     }
8982
8983     CHECK_ALIVE(PushLoad(prop, receiver, key));
8984     HValue* function = Pop();
8985
8986     if (FLAG_hydrogen_track_positions) SetSourcePosition(expr->position());
8987
8988     // Push the function under the receiver.
8989     environment()->SetExpressionStackAt(0, function);
8990
8991     Push(receiver);
8992
8993     if (function->IsConstant() &&
8994         HConstant::cast(function)->handle(isolate())->IsJSFunction()) {
8995       Handle<JSFunction> known_function = Handle<JSFunction>::cast(
8996           HConstant::cast(function)->handle(isolate()));
8997       expr->set_target(known_function);
8998
8999       if (TryCallApply(expr)) return;
9000       CHECK_ALIVE(VisitExpressions(expr->arguments()));
9001
9002       Handle<Map> map = types->length() == 1 ? types->first() : Handle<Map>();
9003       if (TryInlineBuiltinMethodCall(expr, receiver, map)) {
9004         if (FLAG_trace_inlining) {
9005           PrintF("Inlining builtin ");
9006           known_function->ShortPrint();
9007           PrintF("\n");
9008         }
9009         return;
9010       }
9011       if (TryInlineApiMethodCall(expr, receiver, types)) return;
9012
9013       // Wrap the receiver if necessary.
9014       if (NeedsWrappingFor(ToType(types->first()), known_function)) {
9015         // Since HWrapReceiver currently cannot actually wrap numbers and
9016         // strings, use the regular CallFunctionStub for method calls to wrap
9017         // the receiver.
9018         // TODO(verwaest): Support creation of value wrappers directly in
9019         // HWrapReceiver.
9020         call = New<HCallFunction>(
9021             function, argument_count, WRAP_AND_CALL);
9022       } else if (TryInlineCall(expr)) {
9023         return;
9024       } else {
9025         call = BuildCallConstantFunction(known_function, argument_count);
9026       }
9027
9028     } else {
9029       CHECK_ALIVE(VisitExpressions(expr->arguments()));
9030       CallFunctionFlags flags = receiver->type().IsJSObject()
9031           ? NO_CALL_FUNCTION_FLAGS : CALL_AS_METHOD;
9032       call = New<HCallFunction>(function, argument_count, flags);
9033     }
9034     PushArgumentsFromEnvironment(argument_count);
9035
9036   } else {
9037     VariableProxy* proxy = expr->expression()->AsVariableProxy();
9038     if (proxy != NULL && proxy->var()->is_possibly_eval(isolate())) {
9039       return Bailout(kPossibleDirectCallToEval);
9040     }
9041
9042     // The function is on the stack in the unoptimized code during
9043     // evaluation of the arguments.
9044     CHECK_ALIVE(VisitForValue(expr->expression()));
9045     HValue* function = Top();
9046     if (expr->global_call()) {
9047       Variable* var = proxy->var();
9048       bool known_global_function = false;
9049       // If there is a global property cell for the name at compile time and
9050       // access check is not enabled we assume that the function will not change
9051       // and generate optimized code for calling the function.
9052       LookupResult lookup(isolate());
9053       GlobalPropertyAccess type = LookupGlobalProperty(var, &lookup, LOAD);
9054       if (type == kUseCell &&
9055           !current_info()->global_object()->IsAccessCheckNeeded()) {
9056         Handle<GlobalObject> global(current_info()->global_object());
9057         known_global_function = expr->ComputeGlobalTarget(global, &lookup);
9058       }
9059       if (known_global_function) {
9060         Add<HCheckValue>(function, expr->target());
9061
9062         // Placeholder for the receiver.
9063         Push(graph()->GetConstantUndefined());
9064         CHECK_ALIVE(VisitExpressions(expr->arguments()));
9065
9066         // Patch the global object on the stack by the expected receiver.
9067         HValue* receiver = ImplicitReceiverFor(function, expr->target());
9068         const int receiver_index = argument_count - 1;
9069         environment()->SetExpressionStackAt(receiver_index, receiver);
9070
9071         if (TryInlineBuiltinFunctionCall(expr)) {
9072           if (FLAG_trace_inlining) {
9073             PrintF("Inlining builtin ");
9074             expr->target()->ShortPrint();
9075             PrintF("\n");
9076           }
9077           return;
9078         }
9079         if (TryInlineApiFunctionCall(expr, receiver)) return;
9080         if (TryHandleArrayCall(expr, function)) return;
9081         if (TryInlineCall(expr)) return;
9082
9083         PushArgumentsFromEnvironment(argument_count);
9084         call = BuildCallConstantFunction(expr->target(), argument_count);
9085       } else {
9086         Push(graph()->GetConstantUndefined());
9087         CHECK_ALIVE(VisitExpressions(expr->arguments()));
9088         PushArgumentsFromEnvironment(argument_count);
9089         call = New<HCallFunction>(function, argument_count);
9090       }
9091
9092     } else if (expr->IsMonomorphic()) {
9093       Add<HCheckValue>(function, expr->target());
9094
9095       Push(graph()->GetConstantUndefined());
9096       CHECK_ALIVE(VisitExpressions(expr->arguments()));
9097
9098       HValue* receiver = ImplicitReceiverFor(function, expr->target());
9099       const int receiver_index = argument_count - 1;
9100       environment()->SetExpressionStackAt(receiver_index, receiver);
9101
9102       if (TryInlineBuiltinFunctionCall(expr)) {
9103         if (FLAG_trace_inlining) {
9104           PrintF("Inlining builtin ");
9105           expr->target()->ShortPrint();
9106           PrintF("\n");
9107         }
9108         return;
9109       }
9110       if (TryInlineApiFunctionCall(expr, receiver)) return;
9111
9112       if (TryInlineCall(expr)) return;
9113
9114       call = PreProcessCall(New<HInvokeFunction>(
9115           function, expr->target(), argument_count));
9116
9117     } else {
9118       Push(graph()->GetConstantUndefined());
9119       CHECK_ALIVE(VisitExpressions(expr->arguments()));
9120       PushArgumentsFromEnvironment(argument_count);
9121       call = New<HCallFunction>(function, argument_count);
9122     }
9123   }
9124
9125   Drop(1);  // Drop the function.
9126   return ast_context()->ReturnInstruction(call, expr->id());
9127 }
9128
9129
9130 void HOptimizedGraphBuilder::BuildInlinedCallArray(
9131     Expression* expression,
9132     int argument_count,
9133     Handle<AllocationSite> site) {
9134   DCHECK(!site.is_null());
9135   DCHECK(argument_count >= 0 && argument_count <= 1);
9136   NoObservableSideEffectsScope no_effects(this);
9137
9138   // We should at least have the constructor on the expression stack.
9139   HValue* constructor = environment()->ExpressionStackAt(argument_count);
9140
9141   // Register on the site for deoptimization if the transition feedback changes.
9142   AllocationSite::AddDependentCompilationInfo(
9143       site, AllocationSite::TRANSITIONS, top_info());
9144   ElementsKind kind = site->GetElementsKind();
9145   HInstruction* site_instruction = Add<HConstant>(site);
9146
9147   // In the single constant argument case, we may have to adjust elements kind
9148   // to avoid creating a packed non-empty array.
9149   if (argument_count == 1 && !IsHoleyElementsKind(kind)) {
9150     HValue* argument = environment()->Top();
9151     if (argument->IsConstant()) {
9152       HConstant* constant_argument = HConstant::cast(argument);
9153       DCHECK(constant_argument->HasSmiValue());
9154       int constant_array_size = constant_argument->Integer32Value();
9155       if (constant_array_size != 0) {
9156         kind = GetHoleyElementsKind(kind);
9157       }
9158     }
9159   }
9160
9161   // Build the array.
9162   JSArrayBuilder array_builder(this,
9163                                kind,
9164                                site_instruction,
9165                                constructor,
9166                                DISABLE_ALLOCATION_SITES);
9167   HValue* new_object = argument_count == 0
9168       ? array_builder.AllocateEmptyArray()
9169       : BuildAllocateArrayFromLength(&array_builder, Top());
9170
9171   int args_to_drop = argument_count + (expression->IsCall() ? 2 : 1);
9172   Drop(args_to_drop);
9173   ast_context()->ReturnValue(new_object);
9174 }
9175
9176
9177 // Checks whether allocation using the given constructor can be inlined.
9178 static bool IsAllocationInlineable(Handle<JSFunction> constructor) {
9179   return constructor->has_initial_map() &&
9180       constructor->initial_map()->instance_type() == JS_OBJECT_TYPE &&
9181       constructor->initial_map()->instance_size() < HAllocate::kMaxInlineSize &&
9182       constructor->initial_map()->InitialPropertiesLength() == 0;
9183 }
9184
9185
9186 bool HOptimizedGraphBuilder::IsCallArrayInlineable(
9187     int argument_count,
9188     Handle<AllocationSite> site) {
9189   Handle<JSFunction> caller = current_info()->closure();
9190   Handle<JSFunction> target = array_function();
9191   // We should have the function plus array arguments on the environment stack.
9192   DCHECK(environment()->length() >= (argument_count + 1));
9193   DCHECK(!site.is_null());
9194
9195   bool inline_ok = false;
9196   if (site->CanInlineCall()) {
9197     // We also want to avoid inlining in certain 1 argument scenarios.
9198     if (argument_count == 1) {
9199       HValue* argument = Top();
9200       if (argument->IsConstant()) {
9201         // Do not inline if the constant length argument is not a smi or
9202         // outside the valid range for unrolled loop initialization.
9203         HConstant* constant_argument = HConstant::cast(argument);
9204         if (constant_argument->HasSmiValue()) {
9205           int value = constant_argument->Integer32Value();
9206           inline_ok = value >= 0 && value <= kElementLoopUnrollThreshold;
9207           if (!inline_ok) {
9208             TraceInline(target, caller,
9209                         "Constant length outside of valid inlining range.");
9210           }
9211         }
9212       } else {
9213         TraceInline(target, caller,
9214                     "Dont inline [new] Array(n) where n isn't constant.");
9215       }
9216     } else if (argument_count == 0) {
9217       inline_ok = true;
9218     } else {
9219       TraceInline(target, caller, "Too many arguments to inline.");
9220     }
9221   } else {
9222     TraceInline(target, caller, "AllocationSite requested no inlining.");
9223   }
9224
9225   if (inline_ok) {
9226     TraceInline(target, caller, NULL);
9227   }
9228   return inline_ok;
9229 }
9230
9231
9232 void HOptimizedGraphBuilder::VisitCallNew(CallNew* expr) {
9233   DCHECK(!HasStackOverflow());
9234   DCHECK(current_block() != NULL);
9235   DCHECK(current_block()->HasPredecessor());
9236   if (!FLAG_hydrogen_track_positions) SetSourcePosition(expr->position());
9237   int argument_count = expr->arguments()->length() + 1;  // Plus constructor.
9238   Factory* factory = isolate()->factory();
9239
9240   // The constructor function is on the stack in the unoptimized code
9241   // during evaluation of the arguments.
9242   CHECK_ALIVE(VisitForValue(expr->expression()));
9243   HValue* function = Top();
9244   CHECK_ALIVE(VisitExpressions(expr->arguments()));
9245
9246   if (FLAG_inline_construct &&
9247       expr->IsMonomorphic() &&
9248       IsAllocationInlineable(expr->target())) {
9249     Handle<JSFunction> constructor = expr->target();
9250     HValue* check = Add<HCheckValue>(function, constructor);
9251
9252     // Force completion of inobject slack tracking before generating
9253     // allocation code to finalize instance size.
9254     if (constructor->IsInobjectSlackTrackingInProgress()) {
9255       constructor->CompleteInobjectSlackTracking();
9256     }
9257
9258     // Calculate instance size from initial map of constructor.
9259     DCHECK(constructor->has_initial_map());
9260     Handle<Map> initial_map(constructor->initial_map());
9261     int instance_size = initial_map->instance_size();
9262     DCHECK(initial_map->InitialPropertiesLength() == 0);
9263
9264     // Allocate an instance of the implicit receiver object.
9265     HValue* size_in_bytes = Add<HConstant>(instance_size);
9266     HAllocationMode allocation_mode;
9267     if (FLAG_pretenuring_call_new) {
9268       if (FLAG_allocation_site_pretenuring) {
9269         // Try to use pretenuring feedback.
9270         Handle<AllocationSite> allocation_site = expr->allocation_site();
9271         allocation_mode = HAllocationMode(allocation_site);
9272         // Take a dependency on allocation site.
9273         AllocationSite::AddDependentCompilationInfo(allocation_site,
9274                                                     AllocationSite::TENURING,
9275                                                     top_info());
9276       }
9277     }
9278
9279     HAllocate* receiver = BuildAllocate(
9280         size_in_bytes, HType::JSObject(), JS_OBJECT_TYPE, allocation_mode);
9281     receiver->set_known_initial_map(initial_map);
9282
9283     // Initialize map and fields of the newly allocated object.
9284     { NoObservableSideEffectsScope no_effects(this);
9285       DCHECK(initial_map->instance_type() == JS_OBJECT_TYPE);
9286       Add<HStoreNamedField>(receiver,
9287           HObjectAccess::ForMapAndOffset(initial_map, JSObject::kMapOffset),
9288           Add<HConstant>(initial_map));
9289       HValue* empty_fixed_array = Add<HConstant>(factory->empty_fixed_array());
9290       Add<HStoreNamedField>(receiver,
9291           HObjectAccess::ForMapAndOffset(initial_map,
9292                                          JSObject::kPropertiesOffset),
9293           empty_fixed_array);
9294       Add<HStoreNamedField>(receiver,
9295           HObjectAccess::ForMapAndOffset(initial_map,
9296                                          JSObject::kElementsOffset),
9297           empty_fixed_array);
9298       if (initial_map->inobject_properties() != 0) {
9299         HConstant* undefined = graph()->GetConstantUndefined();
9300         for (int i = 0; i < initial_map->inobject_properties(); i++) {
9301           int property_offset = initial_map->GetInObjectPropertyOffset(i);
9302           Add<HStoreNamedField>(receiver,
9303               HObjectAccess::ForMapAndOffset(initial_map, property_offset),
9304               undefined);
9305         }
9306       }
9307     }
9308
9309     // Replace the constructor function with a newly allocated receiver using
9310     // the index of the receiver from the top of the expression stack.
9311     const int receiver_index = argument_count - 1;
9312     DCHECK(environment()->ExpressionStackAt(receiver_index) == function);
9313     environment()->SetExpressionStackAt(receiver_index, receiver);
9314
9315     if (TryInlineConstruct(expr, receiver)) {
9316       // Inlining worked, add a dependency on the initial map to make sure that
9317       // this code is deoptimized whenever the initial map of the constructor
9318       // changes.
9319       Map::AddDependentCompilationInfo(
9320           initial_map, DependentCode::kInitialMapChangedGroup, top_info());
9321       return;
9322     }
9323
9324     // TODO(mstarzinger): For now we remove the previous HAllocate and all
9325     // corresponding instructions and instead add HPushArguments for the
9326     // arguments in case inlining failed.  What we actually should do is for
9327     // inlining to try to build a subgraph without mutating the parent graph.
9328     HInstruction* instr = current_block()->last();
9329     do {
9330       HInstruction* prev_instr = instr->previous();
9331       instr->DeleteAndReplaceWith(NULL);
9332       instr = prev_instr;
9333     } while (instr != check);
9334     environment()->SetExpressionStackAt(receiver_index, function);
9335     HInstruction* call =
9336       PreProcessCall(New<HCallNew>(function, argument_count));
9337     return ast_context()->ReturnInstruction(call, expr->id());
9338   } else {
9339     // The constructor function is both an operand to the instruction and an
9340     // argument to the construct call.
9341     if (TryHandleArrayCallNew(expr, function)) return;
9342
9343     HInstruction* call =
9344         PreProcessCall(New<HCallNew>(function, argument_count));
9345     return ast_context()->ReturnInstruction(call, expr->id());
9346   }
9347 }
9348
9349
9350 // Support for generating inlined runtime functions.
9351
9352 // Lookup table for generators for runtime calls that are generated inline.
9353 // Elements of the table are member pointers to functions of
9354 // HOptimizedGraphBuilder.
9355 #define INLINE_FUNCTION_GENERATOR_ADDRESS(Name, argc, ressize)  \
9356     &HOptimizedGraphBuilder::Generate##Name,
9357
9358 const HOptimizedGraphBuilder::InlineFunctionGenerator
9359     HOptimizedGraphBuilder::kInlineFunctionGenerators[] = {
9360         INLINE_FUNCTION_LIST(INLINE_FUNCTION_GENERATOR_ADDRESS)
9361         INLINE_OPTIMIZED_FUNCTION_LIST(INLINE_FUNCTION_GENERATOR_ADDRESS)
9362 };
9363 #undef INLINE_FUNCTION_GENERATOR_ADDRESS
9364
9365
9366 template <class ViewClass>
9367 void HGraphBuilder::BuildArrayBufferViewInitialization(
9368     HValue* obj,
9369     HValue* buffer,
9370     HValue* byte_offset,
9371     HValue* byte_length) {
9372
9373   for (int offset = ViewClass::kSize;
9374        offset < ViewClass::kSizeWithInternalFields;
9375        offset += kPointerSize) {
9376     Add<HStoreNamedField>(obj,
9377         HObjectAccess::ForObservableJSObjectOffset(offset),
9378         graph()->GetConstant0());
9379   }
9380
9381   Add<HStoreNamedField>(
9382       obj,
9383       HObjectAccess::ForJSArrayBufferViewByteOffset(),
9384       byte_offset);
9385   Add<HStoreNamedField>(
9386       obj,
9387       HObjectAccess::ForJSArrayBufferViewByteLength(),
9388       byte_length);
9389
9390   if (buffer != NULL) {
9391     Add<HStoreNamedField>(
9392         obj,
9393         HObjectAccess::ForJSArrayBufferViewBuffer(), buffer);
9394     HObjectAccess weak_first_view_access =
9395         HObjectAccess::ForJSArrayBufferWeakFirstView();
9396     Add<HStoreNamedField>(obj,
9397         HObjectAccess::ForJSArrayBufferViewWeakNext(),
9398         Add<HLoadNamedField>(buffer,
9399                              static_cast<HValue*>(NULL),
9400                              weak_first_view_access));
9401     Add<HStoreNamedField>(buffer, weak_first_view_access, obj);
9402   } else {
9403     Add<HStoreNamedField>(
9404         obj,
9405         HObjectAccess::ForJSArrayBufferViewBuffer(),
9406         Add<HConstant>(static_cast<int32_t>(0)));
9407     Add<HStoreNamedField>(obj,
9408         HObjectAccess::ForJSArrayBufferViewWeakNext(),
9409         graph()->GetConstantUndefined());
9410   }
9411 }
9412
9413
9414 void HOptimizedGraphBuilder::GenerateDataViewInitialize(
9415     CallRuntime* expr) {
9416   ZoneList<Expression*>* arguments = expr->arguments();
9417
9418   DCHECK(arguments->length()== 4);
9419   CHECK_ALIVE(VisitForValue(arguments->at(0)));
9420   HValue* obj = Pop();
9421
9422   CHECK_ALIVE(VisitForValue(arguments->at(1)));
9423   HValue* buffer = Pop();
9424
9425   CHECK_ALIVE(VisitForValue(arguments->at(2)));
9426   HValue* byte_offset = Pop();
9427
9428   CHECK_ALIVE(VisitForValue(arguments->at(3)));
9429   HValue* byte_length = Pop();
9430
9431   {
9432     NoObservableSideEffectsScope scope(this);
9433     BuildArrayBufferViewInitialization<JSDataView>(
9434         obj, buffer, byte_offset, byte_length);
9435   }
9436 }
9437
9438
9439 static Handle<Map> TypedArrayMap(Isolate* isolate,
9440                                  ExternalArrayType array_type,
9441                                  ElementsKind target_kind) {
9442   Handle<Context> native_context = isolate->native_context();
9443   Handle<JSFunction> fun;
9444   switch (array_type) {
9445 #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size)                       \
9446     case kExternal##Type##Array:                                              \
9447       fun = Handle<JSFunction>(native_context->type##_array_fun());           \
9448       break;
9449
9450     TYPED_ARRAYS(TYPED_ARRAY_CASE)
9451 #undef TYPED_ARRAY_CASE
9452   }
9453   Handle<Map> map(fun->initial_map());
9454   return Map::AsElementsKind(map, target_kind);
9455 }
9456
9457
9458 HValue* HOptimizedGraphBuilder::BuildAllocateExternalElements(
9459     ExternalArrayType array_type,
9460     bool is_zero_byte_offset,
9461     HValue* buffer, HValue* byte_offset, HValue* length) {
9462   Handle<Map> external_array_map(
9463       isolate()->heap()->MapForExternalArrayType(array_type));
9464
9465   // The HForceRepresentation is to prevent possible deopt on int-smi
9466   // conversion after allocation but before the new object fields are set.
9467   length = AddUncasted<HForceRepresentation>(length, Representation::Smi());
9468   HValue* elements =
9469       Add<HAllocate>(
9470           Add<HConstant>(ExternalArray::kAlignedSize),
9471           HType::HeapObject(),
9472           NOT_TENURED,
9473           external_array_map->instance_type());
9474
9475   AddStoreMapConstant(elements, external_array_map);
9476   Add<HStoreNamedField>(elements,
9477       HObjectAccess::ForFixedArrayLength(), length);
9478
9479   HValue* backing_store = Add<HLoadNamedField>(
9480       buffer, static_cast<HValue*>(NULL),
9481       HObjectAccess::ForJSArrayBufferBackingStore());
9482
9483   HValue* typed_array_start;
9484   if (is_zero_byte_offset) {
9485     typed_array_start = backing_store;
9486   } else {
9487     HInstruction* external_pointer =
9488         AddUncasted<HAdd>(backing_store, byte_offset);
9489     // Arguments are checked prior to call to TypedArrayInitialize,
9490     // including byte_offset.
9491     external_pointer->ClearFlag(HValue::kCanOverflow);
9492     typed_array_start = external_pointer;
9493   }
9494
9495   Add<HStoreNamedField>(elements,
9496       HObjectAccess::ForExternalArrayExternalPointer(),
9497       typed_array_start);
9498
9499   return elements;
9500 }
9501
9502
9503 HValue* HOptimizedGraphBuilder::BuildAllocateFixedTypedArray(
9504     ExternalArrayType array_type, size_t element_size,
9505     ElementsKind fixed_elements_kind,
9506     HValue* byte_length, HValue* length) {
9507   STATIC_ASSERT(
9508       (FixedTypedArrayBase::kHeaderSize & kObjectAlignmentMask) == 0);
9509   HValue* total_size;
9510
9511   // if fixed array's elements are not aligned to object's alignment,
9512   // we need to align the whole array to object alignment.
9513   if (element_size % kObjectAlignment != 0) {
9514     total_size = BuildObjectSizeAlignment(
9515         byte_length, FixedTypedArrayBase::kHeaderSize);
9516   } else {
9517     total_size = AddUncasted<HAdd>(byte_length,
9518         Add<HConstant>(FixedTypedArrayBase::kHeaderSize));
9519     total_size->ClearFlag(HValue::kCanOverflow);
9520   }
9521
9522   // The HForceRepresentation is to prevent possible deopt on int-smi
9523   // conversion after allocation but before the new object fields are set.
9524   length = AddUncasted<HForceRepresentation>(length, Representation::Smi());
9525   Handle<Map> fixed_typed_array_map(
9526       isolate()->heap()->MapForFixedTypedArray(array_type));
9527   HValue* elements =
9528       Add<HAllocate>(total_size, HType::HeapObject(),
9529                      NOT_TENURED, fixed_typed_array_map->instance_type());
9530   AddStoreMapConstant(elements, fixed_typed_array_map);
9531
9532   Add<HStoreNamedField>(elements,
9533       HObjectAccess::ForFixedArrayLength(),
9534       length);
9535
9536   HValue* filler = Add<HConstant>(static_cast<int32_t>(0));
9537
9538   {
9539     LoopBuilder builder(this, context(), LoopBuilder::kPostIncrement);
9540
9541     HValue* key = builder.BeginBody(
9542         Add<HConstant>(static_cast<int32_t>(0)),
9543         length, Token::LT);
9544     Add<HStoreKeyed>(elements, key, filler, fixed_elements_kind);
9545
9546     builder.EndBody();
9547   }
9548   return elements;
9549 }
9550
9551
9552 void HOptimizedGraphBuilder::GenerateTypedArrayInitialize(
9553     CallRuntime* expr) {
9554   ZoneList<Expression*>* arguments = expr->arguments();
9555
9556   static const int kObjectArg = 0;
9557   static const int kArrayIdArg = 1;
9558   static const int kBufferArg = 2;
9559   static const int kByteOffsetArg = 3;
9560   static const int kByteLengthArg = 4;
9561   static const int kArgsLength = 5;
9562   DCHECK(arguments->length() == kArgsLength);
9563
9564
9565   CHECK_ALIVE(VisitForValue(arguments->at(kObjectArg)));
9566   HValue* obj = Pop();
9567
9568   if (arguments->at(kArrayIdArg)->IsLiteral()) {
9569     // This should never happen in real use, but can happen when fuzzing.
9570     // Just bail out.
9571     Bailout(kNeedSmiLiteral);
9572     return;
9573   }
9574   Handle<Object> value =
9575       static_cast<Literal*>(arguments->at(kArrayIdArg))->value();
9576   if (!value->IsSmi()) {
9577     // This should never happen in real use, but can happen when fuzzing.
9578     // Just bail out.
9579     Bailout(kNeedSmiLiteral);
9580     return;
9581   }
9582   int array_id = Smi::cast(*value)->value();
9583
9584   HValue* buffer;
9585   if (!arguments->at(kBufferArg)->IsNullLiteral()) {
9586     CHECK_ALIVE(VisitForValue(arguments->at(kBufferArg)));
9587     buffer = Pop();
9588   } else {
9589     buffer = NULL;
9590   }
9591
9592   HValue* byte_offset;
9593   bool is_zero_byte_offset;
9594
9595   if (arguments->at(kByteOffsetArg)->IsLiteral()
9596       && Smi::FromInt(0) ==
9597       *static_cast<Literal*>(arguments->at(kByteOffsetArg))->value()) {
9598     byte_offset = Add<HConstant>(static_cast<int32_t>(0));
9599     is_zero_byte_offset = true;
9600   } else {
9601     CHECK_ALIVE(VisitForValue(arguments->at(kByteOffsetArg)));
9602     byte_offset = Pop();
9603     is_zero_byte_offset = false;
9604     DCHECK(buffer != NULL);
9605   }
9606
9607   CHECK_ALIVE(VisitForValue(arguments->at(kByteLengthArg)));
9608   HValue* byte_length = Pop();
9609
9610   NoObservableSideEffectsScope scope(this);
9611   IfBuilder byte_offset_smi(this);
9612
9613   if (!is_zero_byte_offset) {
9614     byte_offset_smi.If<HIsSmiAndBranch>(byte_offset);
9615     byte_offset_smi.Then();
9616   }
9617
9618   ExternalArrayType array_type =
9619       kExternalInt8Array;  // Bogus initialization.
9620   size_t element_size = 1;  // Bogus initialization.
9621   ElementsKind external_elements_kind =  // Bogus initialization.
9622       EXTERNAL_INT8_ELEMENTS;
9623   ElementsKind fixed_elements_kind =  // Bogus initialization.
9624       INT8_ELEMENTS;
9625   Runtime::ArrayIdToTypeAndSize(array_id,
9626       &array_type,
9627       &external_elements_kind,
9628       &fixed_elements_kind,
9629       &element_size);
9630
9631
9632   { //  byte_offset is Smi.
9633     BuildArrayBufferViewInitialization<JSTypedArray>(
9634         obj, buffer, byte_offset, byte_length);
9635
9636
9637     HInstruction* length = AddUncasted<HDiv>(byte_length,
9638         Add<HConstant>(static_cast<int32_t>(element_size)));
9639
9640     Add<HStoreNamedField>(obj,
9641         HObjectAccess::ForJSTypedArrayLength(),
9642         length);
9643
9644     HValue* elements;
9645     if (buffer != NULL) {
9646       elements = BuildAllocateExternalElements(
9647           array_type, is_zero_byte_offset, buffer, byte_offset, length);
9648       Handle<Map> obj_map = TypedArrayMap(
9649           isolate(), array_type, external_elements_kind);
9650       AddStoreMapConstant(obj, obj_map);
9651     } else {
9652       DCHECK(is_zero_byte_offset);
9653       elements = BuildAllocateFixedTypedArray(
9654           array_type, element_size, fixed_elements_kind,
9655           byte_length, length);
9656     }
9657     Add<HStoreNamedField>(
9658         obj, HObjectAccess::ForElementsPointer(), elements);
9659   }
9660
9661   if (!is_zero_byte_offset) {
9662     byte_offset_smi.Else();
9663     { //  byte_offset is not Smi.
9664       Push(obj);
9665       CHECK_ALIVE(VisitForValue(arguments->at(kArrayIdArg)));
9666       Push(buffer);
9667       Push(byte_offset);
9668       Push(byte_length);
9669       PushArgumentsFromEnvironment(kArgsLength);
9670       Add<HCallRuntime>(expr->name(), expr->function(), kArgsLength);
9671     }
9672   }
9673   byte_offset_smi.End();
9674 }
9675
9676
9677 void HOptimizedGraphBuilder::GenerateMaxSmi(CallRuntime* expr) {
9678   DCHECK(expr->arguments()->length() == 0);
9679   HConstant* max_smi = New<HConstant>(static_cast<int32_t>(Smi::kMaxValue));
9680   return ast_context()->ReturnInstruction(max_smi, expr->id());
9681 }
9682
9683
9684 void HOptimizedGraphBuilder::GenerateTypedArrayMaxSizeInHeap(
9685     CallRuntime* expr) {
9686   DCHECK(expr->arguments()->length() == 0);
9687   HConstant* result = New<HConstant>(static_cast<int32_t>(
9688         FLAG_typed_array_max_size_in_heap));
9689   return ast_context()->ReturnInstruction(result, expr->id());
9690 }
9691
9692
9693 void HOptimizedGraphBuilder::GenerateArrayBufferGetByteLength(
9694     CallRuntime* expr) {
9695   DCHECK(expr->arguments()->length() == 1);
9696   CHECK_ALIVE(VisitForValue(expr->arguments()->at(0)));
9697   HValue* buffer = Pop();
9698   HInstruction* result = New<HLoadNamedField>(
9699     buffer,
9700     static_cast<HValue*>(NULL),
9701     HObjectAccess::ForJSArrayBufferByteLength());
9702   return ast_context()->ReturnInstruction(result, expr->id());
9703 }
9704
9705
9706 void HOptimizedGraphBuilder::GenerateArrayBufferViewGetByteLength(
9707     CallRuntime* expr) {
9708   DCHECK(expr->arguments()->length() == 1);
9709   CHECK_ALIVE(VisitForValue(expr->arguments()->at(0)));
9710   HValue* buffer = Pop();
9711   HInstruction* result = New<HLoadNamedField>(
9712     buffer,
9713     static_cast<HValue*>(NULL),
9714     HObjectAccess::ForJSArrayBufferViewByteLength());
9715   return ast_context()->ReturnInstruction(result, expr->id());
9716 }
9717
9718
9719 void HOptimizedGraphBuilder::GenerateArrayBufferViewGetByteOffset(
9720     CallRuntime* expr) {
9721   DCHECK(expr->arguments()->length() == 1);
9722   CHECK_ALIVE(VisitForValue(expr->arguments()->at(0)));
9723   HValue* buffer = Pop();
9724   HInstruction* result = New<HLoadNamedField>(
9725     buffer,
9726     static_cast<HValue*>(NULL),
9727     HObjectAccess::ForJSArrayBufferViewByteOffset());
9728   return ast_context()->ReturnInstruction(result, expr->id());
9729 }
9730
9731
9732 void HOptimizedGraphBuilder::GenerateTypedArrayGetLength(
9733     CallRuntime* expr) {
9734   DCHECK(expr->arguments()->length() == 1);
9735   CHECK_ALIVE(VisitForValue(expr->arguments()->at(0)));
9736   HValue* buffer = Pop();
9737   HInstruction* result = New<HLoadNamedField>(
9738     buffer,
9739     static_cast<HValue*>(NULL),
9740     HObjectAccess::ForJSTypedArrayLength());
9741   return ast_context()->ReturnInstruction(result, expr->id());
9742 }
9743
9744
9745 void HOptimizedGraphBuilder::VisitCallRuntime(CallRuntime* expr) {
9746   DCHECK(!HasStackOverflow());
9747   DCHECK(current_block() != NULL);
9748   DCHECK(current_block()->HasPredecessor());
9749   if (expr->is_jsruntime()) {
9750     return Bailout(kCallToAJavaScriptRuntimeFunction);
9751   }
9752
9753   const Runtime::Function* function = expr->function();
9754   DCHECK(function != NULL);
9755
9756   if (function->intrinsic_type == Runtime::INLINE ||
9757       function->intrinsic_type == Runtime::INLINE_OPTIMIZED) {
9758     DCHECK(expr->name()->length() > 0);
9759     DCHECK(expr->name()->Get(0) == '_');
9760     // Call to an inline function.
9761     int lookup_index = static_cast<int>(function->function_id) -
9762         static_cast<int>(Runtime::kFirstInlineFunction);
9763     DCHECK(lookup_index >= 0);
9764     DCHECK(static_cast<size_t>(lookup_index) <
9765            ARRAY_SIZE(kInlineFunctionGenerators));
9766     InlineFunctionGenerator generator = kInlineFunctionGenerators[lookup_index];
9767
9768     // Call the inline code generator using the pointer-to-member.
9769     (this->*generator)(expr);
9770   } else {
9771     DCHECK(function->intrinsic_type == Runtime::RUNTIME);
9772     Handle<String> name = expr->name();
9773     int argument_count = expr->arguments()->length();
9774     CHECK_ALIVE(VisitExpressions(expr->arguments()));
9775     PushArgumentsFromEnvironment(argument_count);
9776     HCallRuntime* call = New<HCallRuntime>(name, function,
9777                                            argument_count);
9778     return ast_context()->ReturnInstruction(call, expr->id());
9779   }
9780 }
9781
9782
9783 void HOptimizedGraphBuilder::VisitUnaryOperation(UnaryOperation* expr) {
9784   DCHECK(!HasStackOverflow());
9785   DCHECK(current_block() != NULL);
9786   DCHECK(current_block()->HasPredecessor());
9787   switch (expr->op()) {
9788     case Token::DELETE: return VisitDelete(expr);
9789     case Token::VOID: return VisitVoid(expr);
9790     case Token::TYPEOF: return VisitTypeof(expr);
9791     case Token::NOT: return VisitNot(expr);
9792     default: UNREACHABLE();
9793   }
9794 }
9795
9796
9797 void HOptimizedGraphBuilder::VisitDelete(UnaryOperation* expr) {
9798   Property* prop = expr->expression()->AsProperty();
9799   VariableProxy* proxy = expr->expression()->AsVariableProxy();
9800   if (prop != NULL) {
9801     CHECK_ALIVE(VisitForValue(prop->obj()));
9802     CHECK_ALIVE(VisitForValue(prop->key()));
9803     HValue* key = Pop();
9804     HValue* obj = Pop();
9805     HValue* function = AddLoadJSBuiltin(Builtins::DELETE);
9806     Add<HPushArguments>(obj, key, Add<HConstant>(function_strict_mode()));
9807     // TODO(olivf) InvokeFunction produces a check for the parameter count,
9808     // even though we are certain to pass the correct number of arguments here.
9809     HInstruction* instr = New<HInvokeFunction>(function, 3);
9810     return ast_context()->ReturnInstruction(instr, expr->id());
9811   } else if (proxy != NULL) {
9812     Variable* var = proxy->var();
9813     if (var->IsUnallocated()) {
9814       Bailout(kDeleteWithGlobalVariable);
9815     } else if (var->IsStackAllocated() || var->IsContextSlot()) {
9816       // Result of deleting non-global variables is false.  'this' is not
9817       // really a variable, though we implement it as one.  The
9818       // subexpression does not have side effects.
9819       HValue* value = var->is_this()
9820           ? graph()->GetConstantTrue()
9821           : graph()->GetConstantFalse();
9822       return ast_context()->ReturnValue(value);
9823     } else {
9824       Bailout(kDeleteWithNonGlobalVariable);
9825     }
9826   } else {
9827     // Result of deleting non-property, non-variable reference is true.
9828     // Evaluate the subexpression for side effects.
9829     CHECK_ALIVE(VisitForEffect(expr->expression()));
9830     return ast_context()->ReturnValue(graph()->GetConstantTrue());
9831   }
9832 }
9833
9834
9835 void HOptimizedGraphBuilder::VisitVoid(UnaryOperation* expr) {
9836   CHECK_ALIVE(VisitForEffect(expr->expression()));
9837   return ast_context()->ReturnValue(graph()->GetConstantUndefined());
9838 }
9839
9840
9841 void HOptimizedGraphBuilder::VisitTypeof(UnaryOperation* expr) {
9842   CHECK_ALIVE(VisitForTypeOf(expr->expression()));
9843   HValue* value = Pop();
9844   HInstruction* instr = New<HTypeof>(value);
9845   return ast_context()->ReturnInstruction(instr, expr->id());
9846 }
9847
9848
9849 void HOptimizedGraphBuilder::VisitNot(UnaryOperation* expr) {
9850   if (ast_context()->IsTest()) {
9851     TestContext* context = TestContext::cast(ast_context());
9852     VisitForControl(expr->expression(),
9853                     context->if_false(),
9854                     context->if_true());
9855     return;
9856   }
9857
9858   if (ast_context()->IsEffect()) {
9859     VisitForEffect(expr->expression());
9860     return;
9861   }
9862
9863   DCHECK(ast_context()->IsValue());
9864   HBasicBlock* materialize_false = graph()->CreateBasicBlock();
9865   HBasicBlock* materialize_true = graph()->CreateBasicBlock();
9866   CHECK_BAILOUT(VisitForControl(expr->expression(),
9867                                 materialize_false,
9868                                 materialize_true));
9869
9870   if (materialize_false->HasPredecessor()) {
9871     materialize_false->SetJoinId(expr->MaterializeFalseId());
9872     set_current_block(materialize_false);
9873     Push(graph()->GetConstantFalse());
9874   } else {
9875     materialize_false = NULL;
9876   }
9877
9878   if (materialize_true->HasPredecessor()) {
9879     materialize_true->SetJoinId(expr->MaterializeTrueId());
9880     set_current_block(materialize_true);
9881     Push(graph()->GetConstantTrue());
9882   } else {
9883     materialize_true = NULL;
9884   }
9885
9886   HBasicBlock* join =
9887     CreateJoin(materialize_false, materialize_true, expr->id());
9888   set_current_block(join);
9889   if (join != NULL) return ast_context()->ReturnValue(Pop());
9890 }
9891
9892
9893 HInstruction* HOptimizedGraphBuilder::BuildIncrement(
9894     bool returns_original_input,
9895     CountOperation* expr) {
9896   // The input to the count operation is on top of the expression stack.
9897   Representation rep = Representation::FromType(expr->type());
9898   if (rep.IsNone() || rep.IsTagged()) {
9899     rep = Representation::Smi();
9900   }
9901
9902   if (returns_original_input) {
9903     // We need an explicit HValue representing ToNumber(input).  The
9904     // actual HChange instruction we need is (sometimes) added in a later
9905     // phase, so it is not available now to be used as an input to HAdd and
9906     // as the return value.
9907     HInstruction* number_input = AddUncasted<HForceRepresentation>(Pop(), rep);
9908     if (!rep.IsDouble()) {
9909       number_input->SetFlag(HInstruction::kFlexibleRepresentation);
9910       number_input->SetFlag(HInstruction::kCannotBeTagged);
9911     }
9912     Push(number_input);
9913   }
9914
9915   // The addition has no side effects, so we do not need
9916   // to simulate the expression stack after this instruction.
9917   // Any later failures deopt to the load of the input or earlier.
9918   HConstant* delta = (expr->op() == Token::INC)
9919       ? graph()->GetConstant1()
9920       : graph()->GetConstantMinus1();
9921   HInstruction* instr = AddUncasted<HAdd>(Top(), delta);
9922   if (instr->IsAdd()) {
9923     HAdd* add = HAdd::cast(instr);
9924     add->set_observed_input_representation(1, rep);
9925     add->set_observed_input_representation(2, Representation::Smi());
9926   }
9927   instr->SetFlag(HInstruction::kCannotBeTagged);
9928   instr->ClearAllSideEffects();
9929   return instr;
9930 }
9931
9932
9933 void HOptimizedGraphBuilder::BuildStoreForEffect(Expression* expr,
9934                                                  Property* prop,
9935                                                  BailoutId ast_id,
9936                                                  BailoutId return_id,
9937                                                  HValue* object,
9938                                                  HValue* key,
9939                                                  HValue* value) {
9940   EffectContext for_effect(this);
9941   Push(object);
9942   if (key != NULL) Push(key);
9943   Push(value);
9944   BuildStore(expr, prop, ast_id, return_id);
9945 }
9946
9947
9948 void HOptimizedGraphBuilder::VisitCountOperation(CountOperation* expr) {
9949   DCHECK(!HasStackOverflow());
9950   DCHECK(current_block() != NULL);
9951   DCHECK(current_block()->HasPredecessor());
9952   if (!FLAG_hydrogen_track_positions) SetSourcePosition(expr->position());
9953   Expression* target = expr->expression();
9954   VariableProxy* proxy = target->AsVariableProxy();
9955   Property* prop = target->AsProperty();
9956   if (proxy == NULL && prop == NULL) {
9957     return Bailout(kInvalidLhsInCountOperation);
9958   }
9959
9960   // Match the full code generator stack by simulating an extra stack
9961   // element for postfix operations in a non-effect context.  The return
9962   // value is ToNumber(input).
9963   bool returns_original_input =
9964       expr->is_postfix() && !ast_context()->IsEffect();
9965   HValue* input = NULL;  // ToNumber(original_input).
9966   HValue* after = NULL;  // The result after incrementing or decrementing.
9967
9968   if (proxy != NULL) {
9969     Variable* var = proxy->var();
9970     if (var->mode() == CONST_LEGACY)  {
9971       return Bailout(kUnsupportedCountOperationWithConst);
9972     }
9973     // Argument of the count operation is a variable, not a property.
9974     DCHECK(prop == NULL);
9975     CHECK_ALIVE(VisitForValue(target));
9976
9977     after = BuildIncrement(returns_original_input, expr);
9978     input = returns_original_input ? Top() : Pop();
9979     Push(after);
9980
9981     switch (var->location()) {
9982       case Variable::UNALLOCATED:
9983         HandleGlobalVariableAssignment(var,
9984                                        after,
9985                                        expr->AssignmentId());
9986         break;
9987
9988       case Variable::PARAMETER:
9989       case Variable::LOCAL:
9990         BindIfLive(var, after);
9991         break;
9992
9993       case Variable::CONTEXT: {
9994         // Bail out if we try to mutate a parameter value in a function
9995         // using the arguments object.  We do not (yet) correctly handle the
9996         // arguments property of the function.
9997         if (current_info()->scope()->arguments() != NULL) {
9998           // Parameters will rewrite to context slots.  We have no direct
9999           // way to detect that the variable is a parameter so we use a
10000           // linear search of the parameter list.
10001           int count = current_info()->scope()->num_parameters();
10002           for (int i = 0; i < count; ++i) {
10003             if (var == current_info()->scope()->parameter(i)) {
10004               return Bailout(kAssignmentToParameterInArgumentsObject);
10005             }
10006           }
10007         }
10008
10009         HValue* context = BuildContextChainWalk(var);
10010         HStoreContextSlot::Mode mode = IsLexicalVariableMode(var->mode())
10011             ? HStoreContextSlot::kCheckDeoptimize : HStoreContextSlot::kNoCheck;
10012         HStoreContextSlot* instr = Add<HStoreContextSlot>(context, var->index(),
10013                                                           mode, after);
10014         if (instr->HasObservableSideEffects()) {
10015           Add<HSimulate>(expr->AssignmentId(), REMOVABLE_SIMULATE);
10016         }
10017         break;
10018       }
10019
10020       case Variable::LOOKUP:
10021         return Bailout(kLookupVariableInCountOperation);
10022     }
10023
10024     Drop(returns_original_input ? 2 : 1);
10025     return ast_context()->ReturnValue(expr->is_postfix() ? input : after);
10026   }
10027
10028   // Argument of the count operation is a property.
10029   DCHECK(prop != NULL);
10030   if (returns_original_input) Push(graph()->GetConstantUndefined());
10031
10032   CHECK_ALIVE(VisitForValue(prop->obj()));
10033   HValue* object = Top();
10034
10035   HValue* key = NULL;
10036   if (!prop->key()->IsPropertyName() || prop->IsStringAccess()) {
10037     CHECK_ALIVE(VisitForValue(prop->key()));
10038     key = Top();
10039   }
10040
10041   CHECK_ALIVE(PushLoad(prop, object, key));
10042
10043   after = BuildIncrement(returns_original_input, expr);
10044
10045   if (returns_original_input) {
10046     input = Pop();
10047     // Drop object and key to push it again in the effect context below.
10048     Drop(key == NULL ? 1 : 2);
10049     environment()->SetExpressionStackAt(0, input);
10050     CHECK_ALIVE(BuildStoreForEffect(
10051         expr, prop, expr->id(), expr->AssignmentId(), object, key, after));
10052     return ast_context()->ReturnValue(Pop());
10053   }
10054
10055   environment()->SetExpressionStackAt(0, after);
10056   return BuildStore(expr, prop, expr->id(), expr->AssignmentId());
10057 }
10058
10059
10060 HInstruction* HOptimizedGraphBuilder::BuildStringCharCodeAt(
10061     HValue* string,
10062     HValue* index) {
10063   if (string->IsConstant() && index->IsConstant()) {
10064     HConstant* c_string = HConstant::cast(string);
10065     HConstant* c_index = HConstant::cast(index);
10066     if (c_string->HasStringValue() && c_index->HasNumberValue()) {
10067       int32_t i = c_index->NumberValueAsInteger32();
10068       Handle<String> s = c_string->StringValue();
10069       if (i < 0 || i >= s->length()) {
10070         return New<HConstant>(base::OS::nan_value());
10071       }
10072       return New<HConstant>(s->Get(i));
10073     }
10074   }
10075   string = BuildCheckString(string);
10076   index = Add<HBoundsCheck>(index, AddLoadStringLength(string));
10077   return New<HStringCharCodeAt>(string, index);
10078 }
10079
10080
10081 // Checks if the given shift amounts have following forms:
10082 // (N1) and (N2) with N1 + N2 = 32; (sa) and (32 - sa).
10083 static bool ShiftAmountsAllowReplaceByRotate(HValue* sa,
10084                                              HValue* const32_minus_sa) {
10085   if (sa->IsConstant() && const32_minus_sa->IsConstant()) {
10086     const HConstant* c1 = HConstant::cast(sa);
10087     const HConstant* c2 = HConstant::cast(const32_minus_sa);
10088     return c1->HasInteger32Value() && c2->HasInteger32Value() &&
10089         (c1->Integer32Value() + c2->Integer32Value() == 32);
10090   }
10091   if (!const32_minus_sa->IsSub()) return false;
10092   HSub* sub = HSub::cast(const32_minus_sa);
10093   return sub->left()->EqualsInteger32Constant(32) && sub->right() == sa;
10094 }
10095
10096
10097 // Checks if the left and the right are shift instructions with the oposite
10098 // directions that can be replaced by one rotate right instruction or not.
10099 // Returns the operand and the shift amount for the rotate instruction in the
10100 // former case.
10101 bool HGraphBuilder::MatchRotateRight(HValue* left,
10102                                      HValue* right,
10103                                      HValue** operand,
10104                                      HValue** shift_amount) {
10105   HShl* shl;
10106   HShr* shr;
10107   if (left->IsShl() && right->IsShr()) {
10108     shl = HShl::cast(left);
10109     shr = HShr::cast(right);
10110   } else if (left->IsShr() && right->IsShl()) {
10111     shl = HShl::cast(right);
10112     shr = HShr::cast(left);
10113   } else {
10114     return false;
10115   }
10116   if (shl->left() != shr->left()) return false;
10117
10118   if (!ShiftAmountsAllowReplaceByRotate(shl->right(), shr->right()) &&
10119       !ShiftAmountsAllowReplaceByRotate(shr->right(), shl->right())) {
10120     return false;
10121   }
10122   *operand= shr->left();
10123   *shift_amount = shr->right();
10124   return true;
10125 }
10126
10127
10128 bool CanBeZero(HValue* right) {
10129   if (right->IsConstant()) {
10130     HConstant* right_const = HConstant::cast(right);
10131     if (right_const->HasInteger32Value() &&
10132        (right_const->Integer32Value() & 0x1f) != 0) {
10133       return false;
10134     }
10135   }
10136   return true;
10137 }
10138
10139
10140 HValue* HGraphBuilder::EnforceNumberType(HValue* number,
10141                                          Type* expected) {
10142   if (expected->Is(Type::SignedSmall())) {
10143     return AddUncasted<HForceRepresentation>(number, Representation::Smi());
10144   }
10145   if (expected->Is(Type::Signed32())) {
10146     return AddUncasted<HForceRepresentation>(number,
10147                                              Representation::Integer32());
10148   }
10149   return number;
10150 }
10151
10152
10153 HValue* HGraphBuilder::TruncateToNumber(HValue* value, Type** expected) {
10154   if (value->IsConstant()) {
10155     HConstant* constant = HConstant::cast(value);
10156     Maybe<HConstant*> number = constant->CopyToTruncatedNumber(zone());
10157     if (number.has_value) {
10158       *expected = Type::Number(zone());
10159       return AddInstruction(number.value);
10160     }
10161   }
10162
10163   // We put temporary values on the stack, which don't correspond to anything
10164   // in baseline code. Since nothing is observable we avoid recording those
10165   // pushes with a NoObservableSideEffectsScope.
10166   NoObservableSideEffectsScope no_effects(this);
10167
10168   Type* expected_type = *expected;
10169
10170   // Separate the number type from the rest.
10171   Type* expected_obj =
10172       Type::Intersect(expected_type, Type::NonNumber(zone()), zone());
10173   Type* expected_number =
10174       Type::Intersect(expected_type, Type::Number(zone()), zone());
10175
10176   // We expect to get a number.
10177   // (We need to check first, since Type::None->Is(Type::Any()) == true.
10178   if (expected_obj->Is(Type::None())) {
10179     DCHECK(!expected_number->Is(Type::None(zone())));
10180     return value;
10181   }
10182
10183   if (expected_obj->Is(Type::Undefined(zone()))) {
10184     // This is already done by HChange.
10185     *expected = Type::Union(expected_number, Type::Number(zone()), zone());
10186     return value;
10187   }
10188
10189   return value;
10190 }
10191
10192
10193 HValue* HOptimizedGraphBuilder::BuildBinaryOperation(
10194     BinaryOperation* expr,
10195     HValue* left,
10196     HValue* right,
10197     PushBeforeSimulateBehavior push_sim_result) {
10198   Type* left_type = expr->left()->bounds().lower;
10199   Type* right_type = expr->right()->bounds().lower;
10200   Type* result_type = expr->bounds().lower;
10201   Maybe<int> fixed_right_arg = expr->fixed_right_arg();
10202   Handle<AllocationSite> allocation_site = expr->allocation_site();
10203
10204   HAllocationMode allocation_mode;
10205   if (FLAG_allocation_site_pretenuring && !allocation_site.is_null()) {
10206     allocation_mode = HAllocationMode(allocation_site);
10207   }
10208
10209   HValue* result = HGraphBuilder::BuildBinaryOperation(
10210       expr->op(), left, right, left_type, right_type, result_type,
10211       fixed_right_arg, allocation_mode);
10212   // Add a simulate after instructions with observable side effects, and
10213   // after phis, which are the result of BuildBinaryOperation when we
10214   // inlined some complex subgraph.
10215   if (result->HasObservableSideEffects() || result->IsPhi()) {
10216     if (push_sim_result == PUSH_BEFORE_SIMULATE) {
10217       Push(result);
10218       Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
10219       Drop(1);
10220     } else {
10221       Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
10222     }
10223   }
10224   return result;
10225 }
10226
10227
10228 HValue* HGraphBuilder::BuildBinaryOperation(
10229     Token::Value op,
10230     HValue* left,
10231     HValue* right,
10232     Type* left_type,
10233     Type* right_type,
10234     Type* result_type,
10235     Maybe<int> fixed_right_arg,
10236     HAllocationMode allocation_mode) {
10237
10238   Representation left_rep = Representation::FromType(left_type);
10239   Representation right_rep = Representation::FromType(right_type);
10240
10241   bool maybe_string_add = op == Token::ADD &&
10242                           (left_type->Maybe(Type::String()) ||
10243                            left_type->Maybe(Type::Receiver()) ||
10244                            right_type->Maybe(Type::String()) ||
10245                            right_type->Maybe(Type::Receiver()));
10246
10247   if (left_type->Is(Type::None())) {
10248     Add<HDeoptimize>("Insufficient type feedback for LHS of binary operation",
10249                      Deoptimizer::SOFT);
10250     // TODO(rossberg): we should be able to get rid of non-continuous
10251     // defaults.
10252     left_type = Type::Any(zone());
10253   } else {
10254     if (!maybe_string_add) left = TruncateToNumber(left, &left_type);
10255     left_rep = Representation::FromType(left_type);
10256   }
10257
10258   if (right_type->Is(Type::None())) {
10259     Add<HDeoptimize>("Insufficient type feedback for RHS of binary operation",
10260                      Deoptimizer::SOFT);
10261     right_type = Type::Any(zone());
10262   } else {
10263     if (!maybe_string_add) right = TruncateToNumber(right, &right_type);
10264     right_rep = Representation::FromType(right_type);
10265   }
10266
10267   // Special case for string addition here.
10268   if (op == Token::ADD &&
10269       (left_type->Is(Type::String()) || right_type->Is(Type::String()))) {
10270     // Validate type feedback for left argument.
10271     if (left_type->Is(Type::String())) {
10272       left = BuildCheckString(left);
10273     }
10274
10275     // Validate type feedback for right argument.
10276     if (right_type->Is(Type::String())) {
10277       right = BuildCheckString(right);
10278     }
10279
10280     // Convert left argument as necessary.
10281     if (left_type->Is(Type::Number())) {
10282       DCHECK(right_type->Is(Type::String()));
10283       left = BuildNumberToString(left, left_type);
10284     } else if (!left_type->Is(Type::String())) {
10285       DCHECK(right_type->Is(Type::String()));
10286       HValue* function = AddLoadJSBuiltin(Builtins::STRING_ADD_RIGHT);
10287       Add<HPushArguments>(left, right);
10288       return AddUncasted<HInvokeFunction>(function, 2);
10289     }
10290
10291     // Convert right argument as necessary.
10292     if (right_type->Is(Type::Number())) {
10293       DCHECK(left_type->Is(Type::String()));
10294       right = BuildNumberToString(right, right_type);
10295     } else if (!right_type->Is(Type::String())) {
10296       DCHECK(left_type->Is(Type::String()));
10297       HValue* function = AddLoadJSBuiltin(Builtins::STRING_ADD_LEFT);
10298       Add<HPushArguments>(left, right);
10299       return AddUncasted<HInvokeFunction>(function, 2);
10300     }
10301
10302     // Fast path for empty constant strings.
10303     if (left->IsConstant() &&
10304         HConstant::cast(left)->HasStringValue() &&
10305         HConstant::cast(left)->StringValue()->length() == 0) {
10306       return right;
10307     }
10308     if (right->IsConstant() &&
10309         HConstant::cast(right)->HasStringValue() &&
10310         HConstant::cast(right)->StringValue()->length() == 0) {
10311       return left;
10312     }
10313
10314     // Register the dependent code with the allocation site.
10315     if (!allocation_mode.feedback_site().is_null()) {
10316       DCHECK(!graph()->info()->IsStub());
10317       Handle<AllocationSite> site(allocation_mode.feedback_site());
10318       AllocationSite::AddDependentCompilationInfo(
10319           site, AllocationSite::TENURING, top_info());
10320     }
10321
10322     // Inline the string addition into the stub when creating allocation
10323     // mementos to gather allocation site feedback, or if we can statically
10324     // infer that we're going to create a cons string.
10325     if ((graph()->info()->IsStub() &&
10326          allocation_mode.CreateAllocationMementos()) ||
10327         (left->IsConstant() &&
10328          HConstant::cast(left)->HasStringValue() &&
10329          HConstant::cast(left)->StringValue()->length() + 1 >=
10330            ConsString::kMinLength) ||
10331         (right->IsConstant() &&
10332          HConstant::cast(right)->HasStringValue() &&
10333          HConstant::cast(right)->StringValue()->length() + 1 >=
10334            ConsString::kMinLength)) {
10335       return BuildStringAdd(left, right, allocation_mode);
10336     }
10337
10338     // Fallback to using the string add stub.
10339     return AddUncasted<HStringAdd>(
10340         left, right, allocation_mode.GetPretenureMode(),
10341         STRING_ADD_CHECK_NONE, allocation_mode.feedback_site());
10342   }
10343
10344   if (graph()->info()->IsStub()) {
10345     left = EnforceNumberType(left, left_type);
10346     right = EnforceNumberType(right, right_type);
10347   }
10348
10349   Representation result_rep = Representation::FromType(result_type);
10350
10351   bool is_non_primitive = (left_rep.IsTagged() && !left_rep.IsSmi()) ||
10352                           (right_rep.IsTagged() && !right_rep.IsSmi());
10353
10354   HInstruction* instr = NULL;
10355   // Only the stub is allowed to call into the runtime, since otherwise we would
10356   // inline several instructions (including the two pushes) for every tagged
10357   // operation in optimized code, which is more expensive, than a stub call.
10358   if (graph()->info()->IsStub() && is_non_primitive) {
10359     HValue* function = AddLoadJSBuiltin(BinaryOpIC::TokenToJSBuiltin(op));
10360     Add<HPushArguments>(left, right);
10361     instr = AddUncasted<HInvokeFunction>(function, 2);
10362   } else {
10363     switch (op) {
10364       case Token::ADD:
10365         instr = AddUncasted<HAdd>(left, right);
10366         break;
10367       case Token::SUB:
10368         instr = AddUncasted<HSub>(left, right);
10369         break;
10370       case Token::MUL:
10371         instr = AddUncasted<HMul>(left, right);
10372         break;
10373       case Token::MOD: {
10374         if (fixed_right_arg.has_value &&
10375             !right->EqualsInteger32Constant(fixed_right_arg.value)) {
10376           HConstant* fixed_right = Add<HConstant>(
10377               static_cast<int>(fixed_right_arg.value));
10378           IfBuilder if_same(this);
10379           if_same.If<HCompareNumericAndBranch>(right, fixed_right, Token::EQ);
10380           if_same.Then();
10381           if_same.ElseDeopt("Unexpected RHS of binary operation");
10382           right = fixed_right;
10383         }
10384         instr = AddUncasted<HMod>(left, right);
10385         break;
10386       }
10387       case Token::DIV:
10388         instr = AddUncasted<HDiv>(left, right);
10389         break;
10390       case Token::BIT_XOR:
10391       case Token::BIT_AND:
10392         instr = AddUncasted<HBitwise>(op, left, right);
10393         break;
10394       case Token::BIT_OR: {
10395         HValue* operand, *shift_amount;
10396         if (left_type->Is(Type::Signed32()) &&
10397             right_type->Is(Type::Signed32()) &&
10398             MatchRotateRight(left, right, &operand, &shift_amount)) {
10399           instr = AddUncasted<HRor>(operand, shift_amount);
10400         } else {
10401           instr = AddUncasted<HBitwise>(op, left, right);
10402         }
10403         break;
10404       }
10405       case Token::SAR:
10406         instr = AddUncasted<HSar>(left, right);
10407         break;
10408       case Token::SHR:
10409         instr = AddUncasted<HShr>(left, right);
10410         if (FLAG_opt_safe_uint32_operations && instr->IsShr() &&
10411             CanBeZero(right)) {
10412           graph()->RecordUint32Instruction(instr);
10413         }
10414         break;
10415       case Token::SHL:
10416         instr = AddUncasted<HShl>(left, right);
10417         break;
10418       default:
10419         UNREACHABLE();
10420     }
10421   }
10422
10423   if (instr->IsBinaryOperation()) {
10424     HBinaryOperation* binop = HBinaryOperation::cast(instr);
10425     binop->set_observed_input_representation(1, left_rep);
10426     binop->set_observed_input_representation(2, right_rep);
10427     binop->initialize_output_representation(result_rep);
10428     if (graph()->info()->IsStub()) {
10429       // Stub should not call into stub.
10430       instr->SetFlag(HValue::kCannotBeTagged);
10431       // And should truncate on HForceRepresentation already.
10432       if (left->IsForceRepresentation()) {
10433         left->CopyFlag(HValue::kTruncatingToSmi, instr);
10434         left->CopyFlag(HValue::kTruncatingToInt32, instr);
10435       }
10436       if (right->IsForceRepresentation()) {
10437         right->CopyFlag(HValue::kTruncatingToSmi, instr);
10438         right->CopyFlag(HValue::kTruncatingToInt32, instr);
10439       }
10440     }
10441   }
10442   return instr;
10443 }
10444
10445
10446 // Check for the form (%_ClassOf(foo) === 'BarClass').
10447 static bool IsClassOfTest(CompareOperation* expr) {
10448   if (expr->op() != Token::EQ_STRICT) return false;
10449   CallRuntime* call = expr->left()->AsCallRuntime();
10450   if (call == NULL) return false;
10451   Literal* literal = expr->right()->AsLiteral();
10452   if (literal == NULL) return false;
10453   if (!literal->value()->IsString()) return false;
10454   if (!call->name()->IsOneByteEqualTo(STATIC_ASCII_VECTOR("_ClassOf"))) {
10455     return false;
10456   }
10457   DCHECK(call->arguments()->length() == 1);
10458   return true;
10459 }
10460
10461
10462 void HOptimizedGraphBuilder::VisitBinaryOperation(BinaryOperation* expr) {
10463   DCHECK(!HasStackOverflow());
10464   DCHECK(current_block() != NULL);
10465   DCHECK(current_block()->HasPredecessor());
10466   switch (expr->op()) {
10467     case Token::COMMA:
10468       return VisitComma(expr);
10469     case Token::OR:
10470     case Token::AND:
10471       return VisitLogicalExpression(expr);
10472     default:
10473       return VisitArithmeticExpression(expr);
10474   }
10475 }
10476
10477
10478 void HOptimizedGraphBuilder::VisitComma(BinaryOperation* expr) {
10479   CHECK_ALIVE(VisitForEffect(expr->left()));
10480   // Visit the right subexpression in the same AST context as the entire
10481   // expression.
10482   Visit(expr->right());
10483 }
10484
10485
10486 void HOptimizedGraphBuilder::VisitLogicalExpression(BinaryOperation* expr) {
10487   bool is_logical_and = expr->op() == Token::AND;
10488   if (ast_context()->IsTest()) {
10489     TestContext* context = TestContext::cast(ast_context());
10490     // Translate left subexpression.
10491     HBasicBlock* eval_right = graph()->CreateBasicBlock();
10492     if (is_logical_and) {
10493       CHECK_BAILOUT(VisitForControl(expr->left(),
10494                                     eval_right,
10495                                     context->if_false()));
10496     } else {
10497       CHECK_BAILOUT(VisitForControl(expr->left(),
10498                                     context->if_true(),
10499                                     eval_right));
10500     }
10501
10502     // Translate right subexpression by visiting it in the same AST
10503     // context as the entire expression.
10504     if (eval_right->HasPredecessor()) {
10505       eval_right->SetJoinId(expr->RightId());
10506       set_current_block(eval_right);
10507       Visit(expr->right());
10508     }
10509
10510   } else if (ast_context()->IsValue()) {
10511     CHECK_ALIVE(VisitForValue(expr->left()));
10512     DCHECK(current_block() != NULL);
10513     HValue* left_value = Top();
10514
10515     // Short-circuit left values that always evaluate to the same boolean value.
10516     if (expr->left()->ToBooleanIsTrue() || expr->left()->ToBooleanIsFalse()) {
10517       // l (evals true)  && r -> r
10518       // l (evals true)  || r -> l
10519       // l (evals false) && r -> l
10520       // l (evals false) || r -> r
10521       if (is_logical_and == expr->left()->ToBooleanIsTrue()) {
10522         Drop(1);
10523         CHECK_ALIVE(VisitForValue(expr->right()));
10524       }
10525       return ast_context()->ReturnValue(Pop());
10526     }
10527
10528     // We need an extra block to maintain edge-split form.
10529     HBasicBlock* empty_block = graph()->CreateBasicBlock();
10530     HBasicBlock* eval_right = graph()->CreateBasicBlock();
10531     ToBooleanStub::Types expected(expr->left()->to_boolean_types());
10532     HBranch* test = is_logical_and
10533         ? New<HBranch>(left_value, expected, eval_right, empty_block)
10534         : New<HBranch>(left_value, expected, empty_block, eval_right);
10535     FinishCurrentBlock(test);
10536
10537     set_current_block(eval_right);
10538     Drop(1);  // Value of the left subexpression.
10539     CHECK_BAILOUT(VisitForValue(expr->right()));
10540
10541     HBasicBlock* join_block =
10542       CreateJoin(empty_block, current_block(), expr->id());
10543     set_current_block(join_block);
10544     return ast_context()->ReturnValue(Pop());
10545
10546   } else {
10547     DCHECK(ast_context()->IsEffect());
10548     // In an effect context, we don't need the value of the left subexpression,
10549     // only its control flow and side effects.  We need an extra block to
10550     // maintain edge-split form.
10551     HBasicBlock* empty_block = graph()->CreateBasicBlock();
10552     HBasicBlock* right_block = graph()->CreateBasicBlock();
10553     if (is_logical_and) {
10554       CHECK_BAILOUT(VisitForControl(expr->left(), right_block, empty_block));
10555     } else {
10556       CHECK_BAILOUT(VisitForControl(expr->left(), empty_block, right_block));
10557     }
10558
10559     // TODO(kmillikin): Find a way to fix this.  It's ugly that there are
10560     // actually two empty blocks (one here and one inserted by
10561     // TestContext::BuildBranch, and that they both have an HSimulate though the
10562     // second one is not a merge node, and that we really have no good AST ID to
10563     // put on that first HSimulate.
10564
10565     if (empty_block->HasPredecessor()) {
10566       empty_block->SetJoinId(expr->id());
10567     } else {
10568       empty_block = NULL;
10569     }
10570
10571     if (right_block->HasPredecessor()) {
10572       right_block->SetJoinId(expr->RightId());
10573       set_current_block(right_block);
10574       CHECK_BAILOUT(VisitForEffect(expr->right()));
10575       right_block = current_block();
10576     } else {
10577       right_block = NULL;
10578     }
10579
10580     HBasicBlock* join_block =
10581       CreateJoin(empty_block, right_block, expr->id());
10582     set_current_block(join_block);
10583     // We did not materialize any value in the predecessor environments,
10584     // so there is no need to handle it here.
10585   }
10586 }
10587
10588
10589 void HOptimizedGraphBuilder::VisitArithmeticExpression(BinaryOperation* expr) {
10590   CHECK_ALIVE(VisitForValue(expr->left()));
10591   CHECK_ALIVE(VisitForValue(expr->right()));
10592   SetSourcePosition(expr->position());
10593   HValue* right = Pop();
10594   HValue* left = Pop();
10595   HValue* result =
10596       BuildBinaryOperation(expr, left, right,
10597           ast_context()->IsEffect() ? NO_PUSH_BEFORE_SIMULATE
10598                                     : PUSH_BEFORE_SIMULATE);
10599   if (FLAG_hydrogen_track_positions && result->IsBinaryOperation()) {
10600     HBinaryOperation::cast(result)->SetOperandPositions(
10601         zone(),
10602         ScriptPositionToSourcePosition(expr->left()->position()),
10603         ScriptPositionToSourcePosition(expr->right()->position()));
10604   }
10605   return ast_context()->ReturnValue(result);
10606 }
10607
10608
10609 void HOptimizedGraphBuilder::HandleLiteralCompareTypeof(CompareOperation* expr,
10610                                                         Expression* sub_expr,
10611                                                         Handle<String> check) {
10612   CHECK_ALIVE(VisitForTypeOf(sub_expr));
10613   SetSourcePosition(expr->position());
10614   HValue* value = Pop();
10615   HTypeofIsAndBranch* instr = New<HTypeofIsAndBranch>(value, check);
10616   return ast_context()->ReturnControl(instr, expr->id());
10617 }
10618
10619
10620 static bool IsLiteralCompareBool(Isolate* isolate,
10621                                  HValue* left,
10622                                  Token::Value op,
10623                                  HValue* right) {
10624   return op == Token::EQ_STRICT &&
10625       ((left->IsConstant() &&
10626           HConstant::cast(left)->handle(isolate)->IsBoolean()) ||
10627        (right->IsConstant() &&
10628            HConstant::cast(right)->handle(isolate)->IsBoolean()));
10629 }
10630
10631
10632 void HOptimizedGraphBuilder::VisitCompareOperation(CompareOperation* expr) {
10633   DCHECK(!HasStackOverflow());
10634   DCHECK(current_block() != NULL);
10635   DCHECK(current_block()->HasPredecessor());
10636
10637   if (!FLAG_hydrogen_track_positions) SetSourcePosition(expr->position());
10638
10639   // Check for a few fast cases. The AST visiting behavior must be in sync
10640   // with the full codegen: We don't push both left and right values onto
10641   // the expression stack when one side is a special-case literal.
10642   Expression* sub_expr = NULL;
10643   Handle<String> check;
10644   if (expr->IsLiteralCompareTypeof(&sub_expr, &check)) {
10645     return HandleLiteralCompareTypeof(expr, sub_expr, check);
10646   }
10647   if (expr->IsLiteralCompareUndefined(&sub_expr, isolate())) {
10648     return HandleLiteralCompareNil(expr, sub_expr, kUndefinedValue);
10649   }
10650   if (expr->IsLiteralCompareNull(&sub_expr)) {
10651     return HandleLiteralCompareNil(expr, sub_expr, kNullValue);
10652   }
10653
10654   if (IsClassOfTest(expr)) {
10655     CallRuntime* call = expr->left()->AsCallRuntime();
10656     DCHECK(call->arguments()->length() == 1);
10657     CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
10658     HValue* value = Pop();
10659     Literal* literal = expr->right()->AsLiteral();
10660     Handle<String> rhs = Handle<String>::cast(literal->value());
10661     HClassOfTestAndBranch* instr = New<HClassOfTestAndBranch>(value, rhs);
10662     return ast_context()->ReturnControl(instr, expr->id());
10663   }
10664
10665   Type* left_type = expr->left()->bounds().lower;
10666   Type* right_type = expr->right()->bounds().lower;
10667   Type* combined_type = expr->combined_type();
10668
10669   CHECK_ALIVE(VisitForValue(expr->left()));
10670   CHECK_ALIVE(VisitForValue(expr->right()));
10671
10672   if (FLAG_hydrogen_track_positions) SetSourcePosition(expr->position());
10673
10674   HValue* right = Pop();
10675   HValue* left = Pop();
10676   Token::Value op = expr->op();
10677
10678   if (IsLiteralCompareBool(isolate(), left, op, right)) {
10679     HCompareObjectEqAndBranch* result =
10680         New<HCompareObjectEqAndBranch>(left, right);
10681     return ast_context()->ReturnControl(result, expr->id());
10682   }
10683
10684   if (op == Token::INSTANCEOF) {
10685     // Check to see if the rhs of the instanceof is a global function not
10686     // residing in new space. If it is we assume that the function will stay the
10687     // same.
10688     Handle<JSFunction> target = Handle<JSFunction>::null();
10689     VariableProxy* proxy = expr->right()->AsVariableProxy();
10690     bool global_function = (proxy != NULL) && proxy->var()->IsUnallocated();
10691     if (global_function &&
10692         current_info()->has_global_object() &&
10693         !current_info()->global_object()->IsAccessCheckNeeded()) {
10694       Handle<String> name = proxy->name();
10695       Handle<GlobalObject> global(current_info()->global_object());
10696       LookupResult lookup(isolate());
10697       global->Lookup(name, &lookup);
10698       if (lookup.IsNormal() && lookup.GetValue()->IsJSFunction()) {
10699         Handle<JSFunction> candidate(JSFunction::cast(lookup.GetValue()));
10700         // If the function is in new space we assume it's more likely to
10701         // change and thus prefer the general IC code.
10702         if (!isolate()->heap()->InNewSpace(*candidate)) {
10703           target = candidate;
10704         }
10705       }
10706     }
10707
10708     // If the target is not null we have found a known global function that is
10709     // assumed to stay the same for this instanceof.
10710     if (target.is_null()) {
10711       HInstanceOf* result = New<HInstanceOf>(left, right);
10712       return ast_context()->ReturnInstruction(result, expr->id());
10713     } else {
10714       Add<HCheckValue>(right, target);
10715       HInstanceOfKnownGlobal* result =
10716         New<HInstanceOfKnownGlobal>(left, target);
10717       return ast_context()->ReturnInstruction(result, expr->id());
10718     }
10719
10720     // Code below assumes that we don't fall through.
10721     UNREACHABLE();
10722   } else if (op == Token::IN) {
10723     HValue* function = AddLoadJSBuiltin(Builtins::IN);
10724     Add<HPushArguments>(left, right);
10725     // TODO(olivf) InvokeFunction produces a check for the parameter count,
10726     // even though we are certain to pass the correct number of arguments here.
10727     HInstruction* result = New<HInvokeFunction>(function, 2);
10728     return ast_context()->ReturnInstruction(result, expr->id());
10729   }
10730
10731   PushBeforeSimulateBehavior push_behavior =
10732     ast_context()->IsEffect() ? NO_PUSH_BEFORE_SIMULATE
10733                               : PUSH_BEFORE_SIMULATE;
10734   HControlInstruction* compare = BuildCompareInstruction(
10735       op, left, right, left_type, right_type, combined_type,
10736       ScriptPositionToSourcePosition(expr->left()->position()),
10737       ScriptPositionToSourcePosition(expr->right()->position()),
10738       push_behavior, expr->id());
10739   if (compare == NULL) return;  // Bailed out.
10740   return ast_context()->ReturnControl(compare, expr->id());
10741 }
10742
10743
10744 HControlInstruction* HOptimizedGraphBuilder::BuildCompareInstruction(
10745     Token::Value op,
10746     HValue* left,
10747     HValue* right,
10748     Type* left_type,
10749     Type* right_type,
10750     Type* combined_type,
10751     HSourcePosition left_position,
10752     HSourcePosition right_position,
10753     PushBeforeSimulateBehavior push_sim_result,
10754     BailoutId bailout_id) {
10755   // Cases handled below depend on collected type feedback. They should
10756   // soft deoptimize when there is no type feedback.
10757   if (combined_type->Is(Type::None())) {
10758     Add<HDeoptimize>("Insufficient type feedback for combined type "
10759                      "of binary operation",
10760                      Deoptimizer::SOFT);
10761     combined_type = left_type = right_type = Type::Any(zone());
10762   }
10763
10764   Representation left_rep = Representation::FromType(left_type);
10765   Representation right_rep = Representation::FromType(right_type);
10766   Representation combined_rep = Representation::FromType(combined_type);
10767
10768   if (combined_type->Is(Type::Receiver())) {
10769     if (Token::IsEqualityOp(op)) {
10770       // HCompareObjectEqAndBranch can only deal with object, so
10771       // exclude numbers.
10772       if ((left->IsConstant() &&
10773            HConstant::cast(left)->HasNumberValue()) ||
10774           (right->IsConstant() &&
10775            HConstant::cast(right)->HasNumberValue())) {
10776         Add<HDeoptimize>("Type mismatch between feedback and constant",
10777                          Deoptimizer::SOFT);
10778         // The caller expects a branch instruction, so make it happy.
10779         return New<HBranch>(graph()->GetConstantTrue());
10780       }
10781       // Can we get away with map check and not instance type check?
10782       HValue* operand_to_check =
10783           left->block()->block_id() < right->block()->block_id() ? left : right;
10784       if (combined_type->IsClass()) {
10785         Handle<Map> map = combined_type->AsClass()->Map();
10786         AddCheckMap(operand_to_check, map);
10787         HCompareObjectEqAndBranch* result =
10788             New<HCompareObjectEqAndBranch>(left, right);
10789         if (FLAG_hydrogen_track_positions) {
10790           result->set_operand_position(zone(), 0, left_position);
10791           result->set_operand_position(zone(), 1, right_position);
10792         }
10793         return result;
10794       } else {
10795         BuildCheckHeapObject(operand_to_check);
10796         Add<HCheckInstanceType>(operand_to_check,
10797                                 HCheckInstanceType::IS_SPEC_OBJECT);
10798         HCompareObjectEqAndBranch* result =
10799             New<HCompareObjectEqAndBranch>(left, right);
10800         return result;
10801       }
10802     } else {
10803       Bailout(kUnsupportedNonPrimitiveCompare);
10804       return NULL;
10805     }
10806   } else if (combined_type->Is(Type::InternalizedString()) &&
10807              Token::IsEqualityOp(op)) {
10808     // If we have a constant argument, it should be consistent with the type
10809     // feedback (otherwise we fail assertions in HCompareObjectEqAndBranch).
10810     if ((left->IsConstant() &&
10811          !HConstant::cast(left)->HasInternalizedStringValue()) ||
10812         (right->IsConstant() &&
10813          !HConstant::cast(right)->HasInternalizedStringValue())) {
10814       Add<HDeoptimize>("Type mismatch between feedback and constant",
10815                        Deoptimizer::SOFT);
10816       // The caller expects a branch instruction, so make it happy.
10817       return New<HBranch>(graph()->GetConstantTrue());
10818     }
10819     BuildCheckHeapObject(left);
10820     Add<HCheckInstanceType>(left, HCheckInstanceType::IS_INTERNALIZED_STRING);
10821     BuildCheckHeapObject(right);
10822     Add<HCheckInstanceType>(right, HCheckInstanceType::IS_INTERNALIZED_STRING);
10823     HCompareObjectEqAndBranch* result =
10824         New<HCompareObjectEqAndBranch>(left, right);
10825     return result;
10826   } else if (combined_type->Is(Type::String())) {
10827     BuildCheckHeapObject(left);
10828     Add<HCheckInstanceType>(left, HCheckInstanceType::IS_STRING);
10829     BuildCheckHeapObject(right);
10830     Add<HCheckInstanceType>(right, HCheckInstanceType::IS_STRING);
10831     HStringCompareAndBranch* result =
10832         New<HStringCompareAndBranch>(left, right, op);
10833     return result;
10834   } else {
10835     if (combined_rep.IsTagged() || combined_rep.IsNone()) {
10836       HCompareGeneric* result = Add<HCompareGeneric>(left, right, op);
10837       result->set_observed_input_representation(1, left_rep);
10838       result->set_observed_input_representation(2, right_rep);
10839       if (result->HasObservableSideEffects()) {
10840         if (push_sim_result == PUSH_BEFORE_SIMULATE) {
10841           Push(result);
10842           AddSimulate(bailout_id, REMOVABLE_SIMULATE);
10843           Drop(1);
10844         } else {
10845           AddSimulate(bailout_id, REMOVABLE_SIMULATE);
10846         }
10847       }
10848       // TODO(jkummerow): Can we make this more efficient?
10849       HBranch* branch = New<HBranch>(result);
10850       return branch;
10851     } else {
10852       HCompareNumericAndBranch* result =
10853           New<HCompareNumericAndBranch>(left, right, op);
10854       result->set_observed_input_representation(left_rep, right_rep);
10855       if (FLAG_hydrogen_track_positions) {
10856         result->SetOperandPositions(zone(), left_position, right_position);
10857       }
10858       return result;
10859     }
10860   }
10861 }
10862
10863
10864 void HOptimizedGraphBuilder::HandleLiteralCompareNil(CompareOperation* expr,
10865                                                      Expression* sub_expr,
10866                                                      NilValue nil) {
10867   DCHECK(!HasStackOverflow());
10868   DCHECK(current_block() != NULL);
10869   DCHECK(current_block()->HasPredecessor());
10870   DCHECK(expr->op() == Token::EQ || expr->op() == Token::EQ_STRICT);
10871   if (!FLAG_hydrogen_track_positions) SetSourcePosition(expr->position());
10872   CHECK_ALIVE(VisitForValue(sub_expr));
10873   HValue* value = Pop();
10874   if (expr->op() == Token::EQ_STRICT) {
10875     HConstant* nil_constant = nil == kNullValue
10876         ? graph()->GetConstantNull()
10877         : graph()->GetConstantUndefined();
10878     HCompareObjectEqAndBranch* instr =
10879         New<HCompareObjectEqAndBranch>(value, nil_constant);
10880     return ast_context()->ReturnControl(instr, expr->id());
10881   } else {
10882     DCHECK_EQ(Token::EQ, expr->op());
10883     Type* type = expr->combined_type()->Is(Type::None())
10884         ? Type::Any(zone()) : expr->combined_type();
10885     HIfContinuation continuation;
10886     BuildCompareNil(value, type, &continuation);
10887     return ast_context()->ReturnContinuation(&continuation, expr->id());
10888   }
10889 }
10890
10891
10892 HInstruction* HOptimizedGraphBuilder::BuildThisFunction() {
10893   // If we share optimized code between different closures, the
10894   // this-function is not a constant, except inside an inlined body.
10895   if (function_state()->outer() != NULL) {
10896       return New<HConstant>(
10897           function_state()->compilation_info()->closure());
10898   } else {
10899       return New<HThisFunction>();
10900   }
10901 }
10902
10903
10904 HInstruction* HOptimizedGraphBuilder::BuildFastLiteral(
10905     Handle<JSObject> boilerplate_object,
10906     AllocationSiteUsageContext* site_context) {
10907   NoObservableSideEffectsScope no_effects(this);
10908   InstanceType instance_type = boilerplate_object->map()->instance_type();
10909   DCHECK(instance_type == JS_ARRAY_TYPE || instance_type == JS_OBJECT_TYPE);
10910
10911   HType type = instance_type == JS_ARRAY_TYPE
10912       ? HType::JSArray() : HType::JSObject();
10913   HValue* object_size_constant = Add<HConstant>(
10914       boilerplate_object->map()->instance_size());
10915
10916   PretenureFlag pretenure_flag = NOT_TENURED;
10917   if (FLAG_allocation_site_pretenuring) {
10918     pretenure_flag = site_context->current()->GetPretenureMode();
10919     Handle<AllocationSite> site(site_context->current());
10920     AllocationSite::AddDependentCompilationInfo(
10921         site, AllocationSite::TENURING, top_info());
10922   }
10923
10924   HInstruction* object = Add<HAllocate>(object_size_constant, type,
10925       pretenure_flag, instance_type, site_context->current());
10926
10927   // If allocation folding reaches Page::kMaxRegularHeapObjectSize the
10928   // elements array may not get folded into the object. Hence, we set the
10929   // elements pointer to empty fixed array and let store elimination remove
10930   // this store in the folding case.
10931   HConstant* empty_fixed_array = Add<HConstant>(
10932       isolate()->factory()->empty_fixed_array());
10933   Add<HStoreNamedField>(object, HObjectAccess::ForElementsPointer(),
10934       empty_fixed_array);
10935
10936   BuildEmitObjectHeader(boilerplate_object, object);
10937
10938   Handle<FixedArrayBase> elements(boilerplate_object->elements());
10939   int elements_size = (elements->length() > 0 &&
10940       elements->map() != isolate()->heap()->fixed_cow_array_map()) ?
10941           elements->Size() : 0;
10942
10943   if (pretenure_flag == TENURED &&
10944       elements->map() == isolate()->heap()->fixed_cow_array_map() &&
10945       isolate()->heap()->InNewSpace(*elements)) {
10946     // If we would like to pretenure a fixed cow array, we must ensure that the
10947     // array is already in old space, otherwise we'll create too many old-to-
10948     // new-space pointers (overflowing the store buffer).
10949     elements = Handle<FixedArrayBase>(
10950         isolate()->factory()->CopyAndTenureFixedCOWArray(
10951             Handle<FixedArray>::cast(elements)));
10952     boilerplate_object->set_elements(*elements);
10953   }
10954
10955   HInstruction* object_elements = NULL;
10956   if (elements_size > 0) {
10957     HValue* object_elements_size = Add<HConstant>(elements_size);
10958     InstanceType instance_type = boilerplate_object->HasFastDoubleElements()
10959         ? FIXED_DOUBLE_ARRAY_TYPE : FIXED_ARRAY_TYPE;
10960     object_elements = Add<HAllocate>(
10961         object_elements_size, HType::HeapObject(),
10962         pretenure_flag, instance_type, site_context->current());
10963   }
10964   BuildInitElementsInObjectHeader(boilerplate_object, object, object_elements);
10965
10966   // Copy object elements if non-COW.
10967   if (object_elements != NULL) {
10968     BuildEmitElements(boilerplate_object, elements, object_elements,
10969                       site_context);
10970   }
10971
10972   // Copy in-object properties.
10973   if (boilerplate_object->map()->NumberOfFields() != 0) {
10974     BuildEmitInObjectProperties(boilerplate_object, object, site_context,
10975                                 pretenure_flag);
10976   }
10977   return object;
10978 }
10979
10980
10981 void HOptimizedGraphBuilder::BuildEmitObjectHeader(
10982     Handle<JSObject> boilerplate_object,
10983     HInstruction* object) {
10984   DCHECK(boilerplate_object->properties()->length() == 0);
10985
10986   Handle<Map> boilerplate_object_map(boilerplate_object->map());
10987   AddStoreMapConstant(object, boilerplate_object_map);
10988
10989   Handle<Object> properties_field =
10990       Handle<Object>(boilerplate_object->properties(), isolate());
10991   DCHECK(*properties_field == isolate()->heap()->empty_fixed_array());
10992   HInstruction* properties = Add<HConstant>(properties_field);
10993   HObjectAccess access = HObjectAccess::ForPropertiesPointer();
10994   Add<HStoreNamedField>(object, access, properties);
10995
10996   if (boilerplate_object->IsJSArray()) {
10997     Handle<JSArray> boilerplate_array =
10998         Handle<JSArray>::cast(boilerplate_object);
10999     Handle<Object> length_field =
11000         Handle<Object>(boilerplate_array->length(), isolate());
11001     HInstruction* length = Add<HConstant>(length_field);
11002
11003     DCHECK(boilerplate_array->length()->IsSmi());
11004     Add<HStoreNamedField>(object, HObjectAccess::ForArrayLength(
11005         boilerplate_array->GetElementsKind()), length);
11006   }
11007 }
11008
11009
11010 void HOptimizedGraphBuilder::BuildInitElementsInObjectHeader(
11011     Handle<JSObject> boilerplate_object,
11012     HInstruction* object,
11013     HInstruction* object_elements) {
11014   DCHECK(boilerplate_object->properties()->length() == 0);
11015   if (object_elements == NULL) {
11016     Handle<Object> elements_field =
11017         Handle<Object>(boilerplate_object->elements(), isolate());
11018     object_elements = Add<HConstant>(elements_field);
11019   }
11020   Add<HStoreNamedField>(object, HObjectAccess::ForElementsPointer(),
11021       object_elements);
11022 }
11023
11024
11025 void HOptimizedGraphBuilder::BuildEmitInObjectProperties(
11026     Handle<JSObject> boilerplate_object,
11027     HInstruction* object,
11028     AllocationSiteUsageContext* site_context,
11029     PretenureFlag pretenure_flag) {
11030   Handle<Map> boilerplate_map(boilerplate_object->map());
11031   Handle<DescriptorArray> descriptors(boilerplate_map->instance_descriptors());
11032   int limit = boilerplate_map->NumberOfOwnDescriptors();
11033
11034   int copied_fields = 0;
11035   for (int i = 0; i < limit; i++) {
11036     PropertyDetails details = descriptors->GetDetails(i);
11037     if (details.type() != FIELD) continue;
11038     copied_fields++;
11039     int index = descriptors->GetFieldIndex(i);
11040     int property_offset = boilerplate_object->GetInObjectPropertyOffset(index);
11041     Handle<Name> name(descriptors->GetKey(i));
11042     Handle<Object> value =
11043         Handle<Object>(boilerplate_object->InObjectPropertyAt(index),
11044         isolate());
11045
11046     // The access for the store depends on the type of the boilerplate.
11047     HObjectAccess access = boilerplate_object->IsJSArray() ?
11048         HObjectAccess::ForJSArrayOffset(property_offset) :
11049         HObjectAccess::ForMapAndOffset(boilerplate_map, property_offset);
11050
11051     if (value->IsJSObject()) {
11052       Handle<JSObject> value_object = Handle<JSObject>::cast(value);
11053       Handle<AllocationSite> current_site = site_context->EnterNewScope();
11054       HInstruction* result =
11055           BuildFastLiteral(value_object, site_context);
11056       site_context->ExitScope(current_site, value_object);
11057       Add<HStoreNamedField>(object, access, result);
11058     } else {
11059       Representation representation = details.representation();
11060       HInstruction* value_instruction;
11061
11062       if (representation.IsDouble()) {
11063         // Allocate a HeapNumber box and store the value into it.
11064         HValue* heap_number_constant = Add<HConstant>(HeapNumber::kSize);
11065         // This heap number alloc does not have a corresponding
11066         // AllocationSite. That is okay because
11067         // 1) it's a child object of another object with a valid allocation site
11068         // 2) we can just use the mode of the parent object for pretenuring
11069         HInstruction* double_box =
11070             Add<HAllocate>(heap_number_constant, HType::HeapObject(),
11071                 pretenure_flag, MUTABLE_HEAP_NUMBER_TYPE);
11072         AddStoreMapConstant(double_box,
11073             isolate()->factory()->mutable_heap_number_map());
11074         // Unwrap the mutable heap number from the boilerplate.
11075         HValue* double_value =
11076             Add<HConstant>(Handle<HeapNumber>::cast(value)->value());
11077         Add<HStoreNamedField>(
11078             double_box, HObjectAccess::ForHeapNumberValue(), double_value);
11079         value_instruction = double_box;
11080       } else if (representation.IsSmi()) {
11081         value_instruction = value->IsUninitialized()
11082             ? graph()->GetConstant0()
11083             : Add<HConstant>(value);
11084         // Ensure that value is stored as smi.
11085         access = access.WithRepresentation(representation);
11086       } else {
11087         value_instruction = Add<HConstant>(value);
11088       }
11089
11090       Add<HStoreNamedField>(object, access, value_instruction);
11091     }
11092   }
11093
11094   int inobject_properties = boilerplate_object->map()->inobject_properties();
11095   HInstruction* value_instruction =
11096       Add<HConstant>(isolate()->factory()->one_pointer_filler_map());
11097   for (int i = copied_fields; i < inobject_properties; i++) {
11098     DCHECK(boilerplate_object->IsJSObject());
11099     int property_offset = boilerplate_object->GetInObjectPropertyOffset(i);
11100     HObjectAccess access =
11101         HObjectAccess::ForMapAndOffset(boilerplate_map, property_offset);
11102     Add<HStoreNamedField>(object, access, value_instruction);
11103   }
11104 }
11105
11106
11107 void HOptimizedGraphBuilder::BuildEmitElements(
11108     Handle<JSObject> boilerplate_object,
11109     Handle<FixedArrayBase> elements,
11110     HValue* object_elements,
11111     AllocationSiteUsageContext* site_context) {
11112   ElementsKind kind = boilerplate_object->map()->elements_kind();
11113   int elements_length = elements->length();
11114   HValue* object_elements_length = Add<HConstant>(elements_length);
11115   BuildInitializeElementsHeader(object_elements, kind, object_elements_length);
11116
11117   // Copy elements backing store content.
11118   if (elements->IsFixedDoubleArray()) {
11119     BuildEmitFixedDoubleArray(elements, kind, object_elements);
11120   } else if (elements->IsFixedArray()) {
11121     BuildEmitFixedArray(elements, kind, object_elements,
11122                         site_context);
11123   } else {
11124     UNREACHABLE();
11125   }
11126 }
11127
11128
11129 void HOptimizedGraphBuilder::BuildEmitFixedDoubleArray(
11130     Handle<FixedArrayBase> elements,
11131     ElementsKind kind,
11132     HValue* object_elements) {
11133   HInstruction* boilerplate_elements = Add<HConstant>(elements);
11134   int elements_length = elements->length();
11135   for (int i = 0; i < elements_length; i++) {
11136     HValue* key_constant = Add<HConstant>(i);
11137     HInstruction* value_instruction =
11138         Add<HLoadKeyed>(boilerplate_elements, key_constant,
11139                         static_cast<HValue*>(NULL), kind,
11140                         ALLOW_RETURN_HOLE);
11141     HInstruction* store = Add<HStoreKeyed>(object_elements, key_constant,
11142                                            value_instruction, kind);
11143     store->SetFlag(HValue::kAllowUndefinedAsNaN);
11144   }
11145 }
11146
11147
11148 void HOptimizedGraphBuilder::BuildEmitFixedArray(
11149     Handle<FixedArrayBase> elements,
11150     ElementsKind kind,
11151     HValue* object_elements,
11152     AllocationSiteUsageContext* site_context) {
11153   HInstruction* boilerplate_elements = Add<HConstant>(elements);
11154   int elements_length = elements->length();
11155   Handle<FixedArray> fast_elements = Handle<FixedArray>::cast(elements);
11156   for (int i = 0; i < elements_length; i++) {
11157     Handle<Object> value(fast_elements->get(i), isolate());
11158     HValue* key_constant = Add<HConstant>(i);
11159     if (value->IsJSObject()) {
11160       Handle<JSObject> value_object = Handle<JSObject>::cast(value);
11161       Handle<AllocationSite> current_site = site_context->EnterNewScope();
11162       HInstruction* result =
11163           BuildFastLiteral(value_object, site_context);
11164       site_context->ExitScope(current_site, value_object);
11165       Add<HStoreKeyed>(object_elements, key_constant, result, kind);
11166     } else {
11167       HInstruction* value_instruction =
11168           Add<HLoadKeyed>(boilerplate_elements, key_constant,
11169                           static_cast<HValue*>(NULL), kind,
11170                           ALLOW_RETURN_HOLE);
11171       Add<HStoreKeyed>(object_elements, key_constant, value_instruction, kind);
11172     }
11173   }
11174 }
11175
11176
11177 void HOptimizedGraphBuilder::VisitThisFunction(ThisFunction* expr) {
11178   DCHECK(!HasStackOverflow());
11179   DCHECK(current_block() != NULL);
11180   DCHECK(current_block()->HasPredecessor());
11181   HInstruction* instr = BuildThisFunction();
11182   return ast_context()->ReturnInstruction(instr, expr->id());
11183 }
11184
11185
11186 void HOptimizedGraphBuilder::VisitDeclarations(
11187     ZoneList<Declaration*>* declarations) {
11188   DCHECK(globals_.is_empty());
11189   AstVisitor::VisitDeclarations(declarations);
11190   if (!globals_.is_empty()) {
11191     Handle<FixedArray> array =
11192        isolate()->factory()->NewFixedArray(globals_.length(), TENURED);
11193     for (int i = 0; i < globals_.length(); ++i) array->set(i, *globals_.at(i));
11194     int flags = DeclareGlobalsEvalFlag::encode(current_info()->is_eval()) |
11195         DeclareGlobalsNativeFlag::encode(current_info()->is_native()) |
11196         DeclareGlobalsStrictMode::encode(current_info()->strict_mode());
11197     Add<HDeclareGlobals>(array, flags);
11198     globals_.Rewind(0);
11199   }
11200 }
11201
11202
11203 void HOptimizedGraphBuilder::VisitVariableDeclaration(
11204     VariableDeclaration* declaration) {
11205   VariableProxy* proxy = declaration->proxy();
11206   VariableMode mode = declaration->mode();
11207   Variable* variable = proxy->var();
11208   bool hole_init = mode == LET || mode == CONST || mode == CONST_LEGACY;
11209   switch (variable->location()) {
11210     case Variable::UNALLOCATED:
11211       globals_.Add(variable->name(), zone());
11212       globals_.Add(variable->binding_needs_init()
11213                        ? isolate()->factory()->the_hole_value()
11214                        : isolate()->factory()->undefined_value(), zone());
11215       return;
11216     case Variable::PARAMETER:
11217     case Variable::LOCAL:
11218       if (hole_init) {
11219         HValue* value = graph()->GetConstantHole();
11220         environment()->Bind(variable, value);
11221       }
11222       break;
11223     case Variable::CONTEXT:
11224       if (hole_init) {
11225         HValue* value = graph()->GetConstantHole();
11226         HValue* context = environment()->context();
11227         HStoreContextSlot* store = Add<HStoreContextSlot>(
11228             context, variable->index(), HStoreContextSlot::kNoCheck, value);
11229         if (store->HasObservableSideEffects()) {
11230           Add<HSimulate>(proxy->id(), REMOVABLE_SIMULATE);
11231         }
11232       }
11233       break;
11234     case Variable::LOOKUP:
11235       return Bailout(kUnsupportedLookupSlotInDeclaration);
11236   }
11237 }
11238
11239
11240 void HOptimizedGraphBuilder::VisitFunctionDeclaration(
11241     FunctionDeclaration* declaration) {
11242   VariableProxy* proxy = declaration->proxy();
11243   Variable* variable = proxy->var();
11244   switch (variable->location()) {
11245     case Variable::UNALLOCATED: {
11246       globals_.Add(variable->name(), zone());
11247       Handle<SharedFunctionInfo> function = Compiler::BuildFunctionInfo(
11248           declaration->fun(), current_info()->script(), top_info());
11249       // Check for stack-overflow exception.
11250       if (function.is_null()) return SetStackOverflow();
11251       globals_.Add(function, zone());
11252       return;
11253     }
11254     case Variable::PARAMETER:
11255     case Variable::LOCAL: {
11256       CHECK_ALIVE(VisitForValue(declaration->fun()));
11257       HValue* value = Pop();
11258       BindIfLive(variable, value);
11259       break;
11260     }
11261     case Variable::CONTEXT: {
11262       CHECK_ALIVE(VisitForValue(declaration->fun()));
11263       HValue* value = Pop();
11264       HValue* context = environment()->context();
11265       HStoreContextSlot* store = Add<HStoreContextSlot>(
11266           context, variable->index(), HStoreContextSlot::kNoCheck, value);
11267       if (store->HasObservableSideEffects()) {
11268         Add<HSimulate>(proxy->id(), REMOVABLE_SIMULATE);
11269       }
11270       break;
11271     }
11272     case Variable::LOOKUP:
11273       return Bailout(kUnsupportedLookupSlotInDeclaration);
11274   }
11275 }
11276
11277
11278 void HOptimizedGraphBuilder::VisitModuleDeclaration(
11279     ModuleDeclaration* declaration) {
11280   UNREACHABLE();
11281 }
11282
11283
11284 void HOptimizedGraphBuilder::VisitImportDeclaration(
11285     ImportDeclaration* declaration) {
11286   UNREACHABLE();
11287 }
11288
11289
11290 void HOptimizedGraphBuilder::VisitExportDeclaration(
11291     ExportDeclaration* declaration) {
11292   UNREACHABLE();
11293 }
11294
11295
11296 void HOptimizedGraphBuilder::VisitModuleLiteral(ModuleLiteral* module) {
11297   UNREACHABLE();
11298 }
11299
11300
11301 void HOptimizedGraphBuilder::VisitModuleVariable(ModuleVariable* module) {
11302   UNREACHABLE();
11303 }
11304
11305
11306 void HOptimizedGraphBuilder::VisitModulePath(ModulePath* module) {
11307   UNREACHABLE();
11308 }
11309
11310
11311 void HOptimizedGraphBuilder::VisitModuleUrl(ModuleUrl* module) {
11312   UNREACHABLE();
11313 }
11314
11315
11316 void HOptimizedGraphBuilder::VisitModuleStatement(ModuleStatement* stmt) {
11317   UNREACHABLE();
11318 }
11319
11320
11321 // Generators for inline runtime functions.
11322 // Support for types.
11323 void HOptimizedGraphBuilder::GenerateIsSmi(CallRuntime* call) {
11324   DCHECK(call->arguments()->length() == 1);
11325   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11326   HValue* value = Pop();
11327   HIsSmiAndBranch* result = New<HIsSmiAndBranch>(value);
11328   return ast_context()->ReturnControl(result, call->id());
11329 }
11330
11331
11332 void HOptimizedGraphBuilder::GenerateIsSpecObject(CallRuntime* call) {
11333   DCHECK(call->arguments()->length() == 1);
11334   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11335   HValue* value = Pop();
11336   HHasInstanceTypeAndBranch* result =
11337       New<HHasInstanceTypeAndBranch>(value,
11338                                      FIRST_SPEC_OBJECT_TYPE,
11339                                      LAST_SPEC_OBJECT_TYPE);
11340   return ast_context()->ReturnControl(result, call->id());
11341 }
11342
11343
11344 void HOptimizedGraphBuilder::GenerateIsFunction(CallRuntime* call) {
11345   DCHECK(call->arguments()->length() == 1);
11346   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11347   HValue* value = Pop();
11348   HHasInstanceTypeAndBranch* result =
11349       New<HHasInstanceTypeAndBranch>(value, JS_FUNCTION_TYPE);
11350   return ast_context()->ReturnControl(result, call->id());
11351 }
11352
11353
11354 void HOptimizedGraphBuilder::GenerateIsMinusZero(CallRuntime* call) {
11355   DCHECK(call->arguments()->length() == 1);
11356   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11357   HValue* value = Pop();
11358   HCompareMinusZeroAndBranch* result = New<HCompareMinusZeroAndBranch>(value);
11359   return ast_context()->ReturnControl(result, call->id());
11360 }
11361
11362
11363 void HOptimizedGraphBuilder::GenerateHasCachedArrayIndex(CallRuntime* call) {
11364   DCHECK(call->arguments()->length() == 1);
11365   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11366   HValue* value = Pop();
11367   HHasCachedArrayIndexAndBranch* result =
11368       New<HHasCachedArrayIndexAndBranch>(value);
11369   return ast_context()->ReturnControl(result, call->id());
11370 }
11371
11372
11373 void HOptimizedGraphBuilder::GenerateIsArray(CallRuntime* call) {
11374   DCHECK(call->arguments()->length() == 1);
11375   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11376   HValue* value = Pop();
11377   HHasInstanceTypeAndBranch* result =
11378       New<HHasInstanceTypeAndBranch>(value, JS_ARRAY_TYPE);
11379   return ast_context()->ReturnControl(result, call->id());
11380 }
11381
11382
11383 void HOptimizedGraphBuilder::GenerateIsRegExp(CallRuntime* call) {
11384   DCHECK(call->arguments()->length() == 1);
11385   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11386   HValue* value = Pop();
11387   HHasInstanceTypeAndBranch* result =
11388       New<HHasInstanceTypeAndBranch>(value, JS_REGEXP_TYPE);
11389   return ast_context()->ReturnControl(result, call->id());
11390 }
11391
11392
11393 void HOptimizedGraphBuilder::GenerateIsObject(CallRuntime* call) {
11394   DCHECK(call->arguments()->length() == 1);
11395   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11396   HValue* value = Pop();
11397   HIsObjectAndBranch* result = New<HIsObjectAndBranch>(value);
11398   return ast_context()->ReturnControl(result, call->id());
11399 }
11400
11401
11402 void HOptimizedGraphBuilder::GenerateIsNonNegativeSmi(CallRuntime* call) {
11403   return Bailout(kInlinedRuntimeFunctionIsNonNegativeSmi);
11404 }
11405
11406
11407 void HOptimizedGraphBuilder::GenerateIsUndetectableObject(CallRuntime* call) {
11408   DCHECK(call->arguments()->length() == 1);
11409   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11410   HValue* value = Pop();
11411   HIsUndetectableAndBranch* result = New<HIsUndetectableAndBranch>(value);
11412   return ast_context()->ReturnControl(result, call->id());
11413 }
11414
11415
11416 void HOptimizedGraphBuilder::GenerateIsStringWrapperSafeForDefaultValueOf(
11417     CallRuntime* call) {
11418   return Bailout(kInlinedRuntimeFunctionIsStringWrapperSafeForDefaultValueOf);
11419 }
11420
11421
11422 // Support for construct call checks.
11423 void HOptimizedGraphBuilder::GenerateIsConstructCall(CallRuntime* call) {
11424   DCHECK(call->arguments()->length() == 0);
11425   if (function_state()->outer() != NULL) {
11426     // We are generating graph for inlined function.
11427     HValue* value = function_state()->inlining_kind() == CONSTRUCT_CALL_RETURN
11428         ? graph()->GetConstantTrue()
11429         : graph()->GetConstantFalse();
11430     return ast_context()->ReturnValue(value);
11431   } else {
11432     return ast_context()->ReturnControl(New<HIsConstructCallAndBranch>(),
11433                                         call->id());
11434   }
11435 }
11436
11437
11438 // Support for arguments.length and arguments[?].
11439 void HOptimizedGraphBuilder::GenerateArgumentsLength(CallRuntime* call) {
11440   DCHECK(call->arguments()->length() == 0);
11441   HInstruction* result = NULL;
11442   if (function_state()->outer() == NULL) {
11443     HInstruction* elements = Add<HArgumentsElements>(false);
11444     result = New<HArgumentsLength>(elements);
11445   } else {
11446     // Number of arguments without receiver.
11447     int argument_count = environment()->
11448         arguments_environment()->parameter_count() - 1;
11449     result = New<HConstant>(argument_count);
11450   }
11451   return ast_context()->ReturnInstruction(result, call->id());
11452 }
11453
11454
11455 void HOptimizedGraphBuilder::GenerateArguments(CallRuntime* call) {
11456   DCHECK(call->arguments()->length() == 1);
11457   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11458   HValue* index = Pop();
11459   HInstruction* result = NULL;
11460   if (function_state()->outer() == NULL) {
11461     HInstruction* elements = Add<HArgumentsElements>(false);
11462     HInstruction* length = Add<HArgumentsLength>(elements);
11463     HInstruction* checked_index = Add<HBoundsCheck>(index, length);
11464     result = New<HAccessArgumentsAt>(elements, length, checked_index);
11465   } else {
11466     EnsureArgumentsArePushedForAccess();
11467
11468     // Number of arguments without receiver.
11469     HInstruction* elements = function_state()->arguments_elements();
11470     int argument_count = environment()->
11471         arguments_environment()->parameter_count() - 1;
11472     HInstruction* length = Add<HConstant>(argument_count);
11473     HInstruction* checked_key = Add<HBoundsCheck>(index, length);
11474     result = New<HAccessArgumentsAt>(elements, length, checked_key);
11475   }
11476   return ast_context()->ReturnInstruction(result, call->id());
11477 }
11478
11479
11480 // Support for accessing the class and value fields of an object.
11481 void HOptimizedGraphBuilder::GenerateClassOf(CallRuntime* call) {
11482   // The special form detected by IsClassOfTest is detected before we get here
11483   // and does not cause a bailout.
11484   return Bailout(kInlinedRuntimeFunctionClassOf);
11485 }
11486
11487
11488 void HOptimizedGraphBuilder::GenerateValueOf(CallRuntime* call) {
11489   DCHECK(call->arguments()->length() == 1);
11490   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11491   HValue* object = Pop();
11492
11493   IfBuilder if_objectisvalue(this);
11494   HValue* objectisvalue = if_objectisvalue.If<HHasInstanceTypeAndBranch>(
11495       object, JS_VALUE_TYPE);
11496   if_objectisvalue.Then();
11497   {
11498     // Return the actual value.
11499     Push(Add<HLoadNamedField>(
11500             object, objectisvalue,
11501             HObjectAccess::ForObservableJSObjectOffset(
11502                 JSValue::kValueOffset)));
11503     Add<HSimulate>(call->id(), FIXED_SIMULATE);
11504   }
11505   if_objectisvalue.Else();
11506   {
11507     // If the object is not a value return the object.
11508     Push(object);
11509     Add<HSimulate>(call->id(), FIXED_SIMULATE);
11510   }
11511   if_objectisvalue.End();
11512   return ast_context()->ReturnValue(Pop());
11513 }
11514
11515
11516 void HOptimizedGraphBuilder::GenerateDateField(CallRuntime* call) {
11517   DCHECK(call->arguments()->length() == 2);
11518   DCHECK_NE(NULL, call->arguments()->at(1)->AsLiteral());
11519   Smi* index = Smi::cast(*(call->arguments()->at(1)->AsLiteral()->value()));
11520   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11521   HValue* date = Pop();
11522   HDateField* result = New<HDateField>(date, index);
11523   return ast_context()->ReturnInstruction(result, call->id());
11524 }
11525
11526
11527 void HOptimizedGraphBuilder::GenerateOneByteSeqStringSetChar(
11528     CallRuntime* call) {
11529   DCHECK(call->arguments()->length() == 3);
11530   // We need to follow the evaluation order of full codegen.
11531   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
11532   CHECK_ALIVE(VisitForValue(call->arguments()->at(2)));
11533   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11534   HValue* string = Pop();
11535   HValue* value = Pop();
11536   HValue* index = Pop();
11537   Add<HSeqStringSetChar>(String::ONE_BYTE_ENCODING, string,
11538                          index, value);
11539   Add<HSimulate>(call->id(), FIXED_SIMULATE);
11540   return ast_context()->ReturnValue(graph()->GetConstantUndefined());
11541 }
11542
11543
11544 void HOptimizedGraphBuilder::GenerateTwoByteSeqStringSetChar(
11545     CallRuntime* call) {
11546   DCHECK(call->arguments()->length() == 3);
11547   // We need to follow the evaluation order of full codegen.
11548   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
11549   CHECK_ALIVE(VisitForValue(call->arguments()->at(2)));
11550   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11551   HValue* string = Pop();
11552   HValue* value = Pop();
11553   HValue* index = Pop();
11554   Add<HSeqStringSetChar>(String::TWO_BYTE_ENCODING, string,
11555                          index, value);
11556   Add<HSimulate>(call->id(), FIXED_SIMULATE);
11557   return ast_context()->ReturnValue(graph()->GetConstantUndefined());
11558 }
11559
11560
11561 void HOptimizedGraphBuilder::GenerateSetValueOf(CallRuntime* call) {
11562   DCHECK(call->arguments()->length() == 2);
11563   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11564   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
11565   HValue* value = Pop();
11566   HValue* object = Pop();
11567
11568   // Check if object is a JSValue.
11569   IfBuilder if_objectisvalue(this);
11570   if_objectisvalue.If<HHasInstanceTypeAndBranch>(object, JS_VALUE_TYPE);
11571   if_objectisvalue.Then();
11572   {
11573     // Create in-object property store to kValueOffset.
11574     Add<HStoreNamedField>(object,
11575         HObjectAccess::ForObservableJSObjectOffset(JSValue::kValueOffset),
11576         value);
11577     if (!ast_context()->IsEffect()) {
11578       Push(value);
11579     }
11580     Add<HSimulate>(call->id(), FIXED_SIMULATE);
11581   }
11582   if_objectisvalue.Else();
11583   {
11584     // Nothing to do in this case.
11585     if (!ast_context()->IsEffect()) {
11586       Push(value);
11587     }
11588     Add<HSimulate>(call->id(), FIXED_SIMULATE);
11589   }
11590   if_objectisvalue.End();
11591   if (!ast_context()->IsEffect()) {
11592     Drop(1);
11593   }
11594   return ast_context()->ReturnValue(value);
11595 }
11596
11597
11598 // Fast support for charCodeAt(n).
11599 void HOptimizedGraphBuilder::GenerateStringCharCodeAt(CallRuntime* call) {
11600   DCHECK(call->arguments()->length() == 2);
11601   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11602   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
11603   HValue* index = Pop();
11604   HValue* string = Pop();
11605   HInstruction* result = BuildStringCharCodeAt(string, index);
11606   return ast_context()->ReturnInstruction(result, call->id());
11607 }
11608
11609
11610 // Fast support for string.charAt(n) and string[n].
11611 void HOptimizedGraphBuilder::GenerateStringCharFromCode(CallRuntime* call) {
11612   DCHECK(call->arguments()->length() == 1);
11613   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11614   HValue* char_code = Pop();
11615   HInstruction* result = NewUncasted<HStringCharFromCode>(char_code);
11616   return ast_context()->ReturnInstruction(result, call->id());
11617 }
11618
11619
11620 // Fast support for string.charAt(n) and string[n].
11621 void HOptimizedGraphBuilder::GenerateStringCharAt(CallRuntime* call) {
11622   DCHECK(call->arguments()->length() == 2);
11623   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11624   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
11625   HValue* index = Pop();
11626   HValue* string = Pop();
11627   HInstruction* char_code = BuildStringCharCodeAt(string, index);
11628   AddInstruction(char_code);
11629   HInstruction* result = NewUncasted<HStringCharFromCode>(char_code);
11630   return ast_context()->ReturnInstruction(result, call->id());
11631 }
11632
11633
11634 // Fast support for object equality testing.
11635 void HOptimizedGraphBuilder::GenerateObjectEquals(CallRuntime* call) {
11636   DCHECK(call->arguments()->length() == 2);
11637   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11638   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
11639   HValue* right = Pop();
11640   HValue* left = Pop();
11641   HCompareObjectEqAndBranch* result =
11642       New<HCompareObjectEqAndBranch>(left, right);
11643   return ast_context()->ReturnControl(result, call->id());
11644 }
11645
11646
11647 // Fast support for StringAdd.
11648 void HOptimizedGraphBuilder::GenerateStringAdd(CallRuntime* call) {
11649   DCHECK_EQ(2, call->arguments()->length());
11650   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11651   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
11652   HValue* right = Pop();
11653   HValue* left = Pop();
11654   HInstruction* result = NewUncasted<HStringAdd>(left, right);
11655   return ast_context()->ReturnInstruction(result, call->id());
11656 }
11657
11658
11659 // Fast support for SubString.
11660 void HOptimizedGraphBuilder::GenerateSubString(CallRuntime* call) {
11661   DCHECK_EQ(3, call->arguments()->length());
11662   CHECK_ALIVE(VisitExpressions(call->arguments()));
11663   PushArgumentsFromEnvironment(call->arguments()->length());
11664   HCallStub* result = New<HCallStub>(CodeStub::SubString, 3);
11665   return ast_context()->ReturnInstruction(result, call->id());
11666 }
11667
11668
11669 // Fast support for StringCompare.
11670 void HOptimizedGraphBuilder::GenerateStringCompare(CallRuntime* call) {
11671   DCHECK_EQ(2, call->arguments()->length());
11672   CHECK_ALIVE(VisitExpressions(call->arguments()));
11673   PushArgumentsFromEnvironment(call->arguments()->length());
11674   HCallStub* result = New<HCallStub>(CodeStub::StringCompare, 2);
11675   return ast_context()->ReturnInstruction(result, call->id());
11676 }
11677
11678
11679 // Support for direct calls from JavaScript to native RegExp code.
11680 void HOptimizedGraphBuilder::GenerateRegExpExec(CallRuntime* call) {
11681   DCHECK_EQ(4, call->arguments()->length());
11682   CHECK_ALIVE(VisitExpressions(call->arguments()));
11683   PushArgumentsFromEnvironment(call->arguments()->length());
11684   HCallStub* result = New<HCallStub>(CodeStub::RegExpExec, 4);
11685   return ast_context()->ReturnInstruction(result, call->id());
11686 }
11687
11688
11689 void HOptimizedGraphBuilder::GenerateDoubleLo(CallRuntime* call) {
11690   DCHECK_EQ(1, call->arguments()->length());
11691   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11692   HValue* value = Pop();
11693   HInstruction* result = NewUncasted<HDoubleBits>(value, HDoubleBits::LOW);
11694   return ast_context()->ReturnInstruction(result, call->id());
11695 }
11696
11697
11698 void HOptimizedGraphBuilder::GenerateDoubleHi(CallRuntime* call) {
11699   DCHECK_EQ(1, call->arguments()->length());
11700   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11701   HValue* value = Pop();
11702   HInstruction* result = NewUncasted<HDoubleBits>(value, HDoubleBits::HIGH);
11703   return ast_context()->ReturnInstruction(result, call->id());
11704 }
11705
11706
11707 void HOptimizedGraphBuilder::GenerateConstructDouble(CallRuntime* call) {
11708   DCHECK_EQ(2, call->arguments()->length());
11709   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11710   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
11711   HValue* lo = Pop();
11712   HValue* hi = Pop();
11713   HInstruction* result = NewUncasted<HConstructDouble>(hi, lo);
11714   return ast_context()->ReturnInstruction(result, call->id());
11715 }
11716
11717
11718 // Construct a RegExp exec result with two in-object properties.
11719 void HOptimizedGraphBuilder::GenerateRegExpConstructResult(CallRuntime* call) {
11720   DCHECK_EQ(3, call->arguments()->length());
11721   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11722   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
11723   CHECK_ALIVE(VisitForValue(call->arguments()->at(2)));
11724   HValue* input = Pop();
11725   HValue* index = Pop();
11726   HValue* length = Pop();
11727   HValue* result = BuildRegExpConstructResult(length, index, input);
11728   return ast_context()->ReturnValue(result);
11729 }
11730
11731
11732 // Support for fast native caches.
11733 void HOptimizedGraphBuilder::GenerateGetFromCache(CallRuntime* call) {
11734   return Bailout(kInlinedRuntimeFunctionGetFromCache);
11735 }
11736
11737
11738 // Fast support for number to string.
11739 void HOptimizedGraphBuilder::GenerateNumberToString(CallRuntime* call) {
11740   DCHECK_EQ(1, call->arguments()->length());
11741   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11742   HValue* number = Pop();
11743   HValue* result = BuildNumberToString(number, Type::Any(zone()));
11744   return ast_context()->ReturnValue(result);
11745 }
11746
11747
11748 // Fast call for custom callbacks.
11749 void HOptimizedGraphBuilder::GenerateCallFunction(CallRuntime* call) {
11750   // 1 ~ The function to call is not itself an argument to the call.
11751   int arg_count = call->arguments()->length() - 1;
11752   DCHECK(arg_count >= 1);  // There's always at least a receiver.
11753
11754   CHECK_ALIVE(VisitExpressions(call->arguments()));
11755   // The function is the last argument
11756   HValue* function = Pop();
11757   // Push the arguments to the stack
11758   PushArgumentsFromEnvironment(arg_count);
11759
11760   IfBuilder if_is_jsfunction(this);
11761   if_is_jsfunction.If<HHasInstanceTypeAndBranch>(function, JS_FUNCTION_TYPE);
11762
11763   if_is_jsfunction.Then();
11764   {
11765     HInstruction* invoke_result =
11766         Add<HInvokeFunction>(function, arg_count);
11767     if (!ast_context()->IsEffect()) {
11768       Push(invoke_result);
11769     }
11770     Add<HSimulate>(call->id(), FIXED_SIMULATE);
11771   }
11772
11773   if_is_jsfunction.Else();
11774   {
11775     HInstruction* call_result =
11776         Add<HCallFunction>(function, arg_count);
11777     if (!ast_context()->IsEffect()) {
11778       Push(call_result);
11779     }
11780     Add<HSimulate>(call->id(), FIXED_SIMULATE);
11781   }
11782   if_is_jsfunction.End();
11783
11784   if (ast_context()->IsEffect()) {
11785     // EffectContext::ReturnValue ignores the value, so we can just pass
11786     // 'undefined' (as we do not have the call result anymore).
11787     return ast_context()->ReturnValue(graph()->GetConstantUndefined());
11788   } else {
11789     return ast_context()->ReturnValue(Pop());
11790   }
11791 }
11792
11793
11794 // Fast call to math functions.
11795 void HOptimizedGraphBuilder::GenerateMathPow(CallRuntime* call) {
11796   DCHECK_EQ(2, call->arguments()->length());
11797   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11798   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
11799   HValue* right = Pop();
11800   HValue* left = Pop();
11801   HInstruction* result = NewUncasted<HPower>(left, right);
11802   return ast_context()->ReturnInstruction(result, call->id());
11803 }
11804
11805
11806 void HOptimizedGraphBuilder::GenerateMathLogRT(CallRuntime* call) {
11807   DCHECK(call->arguments()->length() == 1);
11808   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11809   HValue* value = Pop();
11810   HInstruction* result = NewUncasted<HUnaryMathOperation>(value, kMathLog);
11811   return ast_context()->ReturnInstruction(result, call->id());
11812 }
11813
11814
11815 void HOptimizedGraphBuilder::GenerateMathSqrtRT(CallRuntime* call) {
11816   DCHECK(call->arguments()->length() == 1);
11817   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11818   HValue* value = Pop();
11819   HInstruction* result = NewUncasted<HUnaryMathOperation>(value, kMathSqrt);
11820   return ast_context()->ReturnInstruction(result, call->id());
11821 }
11822
11823
11824 void HOptimizedGraphBuilder::GenerateGetCachedArrayIndex(CallRuntime* call) {
11825   DCHECK(call->arguments()->length() == 1);
11826   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11827   HValue* value = Pop();
11828   HGetCachedArrayIndex* result = New<HGetCachedArrayIndex>(value);
11829   return ast_context()->ReturnInstruction(result, call->id());
11830 }
11831
11832
11833 void HOptimizedGraphBuilder::GenerateFastAsciiArrayJoin(CallRuntime* call) {
11834   return Bailout(kInlinedRuntimeFunctionFastAsciiArrayJoin);
11835 }
11836
11837
11838 // Support for generators.
11839 void HOptimizedGraphBuilder::GenerateGeneratorNext(CallRuntime* call) {
11840   return Bailout(kInlinedRuntimeFunctionGeneratorNext);
11841 }
11842
11843
11844 void HOptimizedGraphBuilder::GenerateGeneratorThrow(CallRuntime* call) {
11845   return Bailout(kInlinedRuntimeFunctionGeneratorThrow);
11846 }
11847
11848
11849 void HOptimizedGraphBuilder::GenerateDebugBreakInOptimizedCode(
11850     CallRuntime* call) {
11851   Add<HDebugBreak>();
11852   return ast_context()->ReturnValue(graph()->GetConstant0());
11853 }
11854
11855
11856 void HOptimizedGraphBuilder::GenerateDebugIsActive(CallRuntime* call) {
11857   DCHECK(call->arguments()->length() == 0);
11858   HValue* ref =
11859       Add<HConstant>(ExternalReference::debug_is_active_address(isolate()));
11860   HValue* value = Add<HLoadNamedField>(
11861       ref, static_cast<HValue*>(NULL), HObjectAccess::ForExternalUInteger8());
11862   return ast_context()->ReturnValue(value);
11863 }
11864
11865
11866 #undef CHECK_BAILOUT
11867 #undef CHECK_ALIVE
11868
11869
11870 HEnvironment::HEnvironment(HEnvironment* outer,
11871                            Scope* scope,
11872                            Handle<JSFunction> closure,
11873                            Zone* zone)
11874     : closure_(closure),
11875       values_(0, zone),
11876       frame_type_(JS_FUNCTION),
11877       parameter_count_(0),
11878       specials_count_(1),
11879       local_count_(0),
11880       outer_(outer),
11881       entry_(NULL),
11882       pop_count_(0),
11883       push_count_(0),
11884       ast_id_(BailoutId::None()),
11885       zone_(zone) {
11886   Scope* declaration_scope = scope->DeclarationScope();
11887   Initialize(declaration_scope->num_parameters() + 1,
11888              declaration_scope->num_stack_slots(), 0);
11889 }
11890
11891
11892 HEnvironment::HEnvironment(Zone* zone, int parameter_count)
11893     : values_(0, zone),
11894       frame_type_(STUB),
11895       parameter_count_(parameter_count),
11896       specials_count_(1),
11897       local_count_(0),
11898       outer_(NULL),
11899       entry_(NULL),
11900       pop_count_(0),
11901       push_count_(0),
11902       ast_id_(BailoutId::None()),
11903       zone_(zone) {
11904   Initialize(parameter_count, 0, 0);
11905 }
11906
11907
11908 HEnvironment::HEnvironment(const HEnvironment* other, Zone* zone)
11909     : values_(0, zone),
11910       frame_type_(JS_FUNCTION),
11911       parameter_count_(0),
11912       specials_count_(0),
11913       local_count_(0),
11914       outer_(NULL),
11915       entry_(NULL),
11916       pop_count_(0),
11917       push_count_(0),
11918       ast_id_(other->ast_id()),
11919       zone_(zone) {
11920   Initialize(other);
11921 }
11922
11923
11924 HEnvironment::HEnvironment(HEnvironment* outer,
11925                            Handle<JSFunction> closure,
11926                            FrameType frame_type,
11927                            int arguments,
11928                            Zone* zone)
11929     : closure_(closure),
11930       values_(arguments, zone),
11931       frame_type_(frame_type),
11932       parameter_count_(arguments),
11933       specials_count_(0),
11934       local_count_(0),
11935       outer_(outer),
11936       entry_(NULL),
11937       pop_count_(0),
11938       push_count_(0),
11939       ast_id_(BailoutId::None()),
11940       zone_(zone) {
11941 }
11942
11943
11944 void HEnvironment::Initialize(int parameter_count,
11945                               int local_count,
11946                               int stack_height) {
11947   parameter_count_ = parameter_count;
11948   local_count_ = local_count;
11949
11950   // Avoid reallocating the temporaries' backing store on the first Push.
11951   int total = parameter_count + specials_count_ + local_count + stack_height;
11952   values_.Initialize(total + 4, zone());
11953   for (int i = 0; i < total; ++i) values_.Add(NULL, zone());
11954 }
11955
11956
11957 void HEnvironment::Initialize(const HEnvironment* other) {
11958   closure_ = other->closure();
11959   values_.AddAll(other->values_, zone());
11960   assigned_variables_.Union(other->assigned_variables_, zone());
11961   frame_type_ = other->frame_type_;
11962   parameter_count_ = other->parameter_count_;
11963   local_count_ = other->local_count_;
11964   if (other->outer_ != NULL) outer_ = other->outer_->Copy();  // Deep copy.
11965   entry_ = other->entry_;
11966   pop_count_ = other->pop_count_;
11967   push_count_ = other->push_count_;
11968   specials_count_ = other->specials_count_;
11969   ast_id_ = other->ast_id_;
11970 }
11971
11972
11973 void HEnvironment::AddIncomingEdge(HBasicBlock* block, HEnvironment* other) {
11974   DCHECK(!block->IsLoopHeader());
11975   DCHECK(values_.length() == other->values_.length());
11976
11977   int length = values_.length();
11978   for (int i = 0; i < length; ++i) {
11979     HValue* value = values_[i];
11980     if (value != NULL && value->IsPhi() && value->block() == block) {
11981       // There is already a phi for the i'th value.
11982       HPhi* phi = HPhi::cast(value);
11983       // Assert index is correct and that we haven't missed an incoming edge.
11984       DCHECK(phi->merged_index() == i || !phi->HasMergedIndex());
11985       DCHECK(phi->OperandCount() == block->predecessors()->length());
11986       phi->AddInput(other->values_[i]);
11987     } else if (values_[i] != other->values_[i]) {
11988       // There is a fresh value on the incoming edge, a phi is needed.
11989       DCHECK(values_[i] != NULL && other->values_[i] != NULL);
11990       HPhi* phi = block->AddNewPhi(i);
11991       HValue* old_value = values_[i];
11992       for (int j = 0; j < block->predecessors()->length(); j++) {
11993         phi->AddInput(old_value);
11994       }
11995       phi->AddInput(other->values_[i]);
11996       this->values_[i] = phi;
11997     }
11998   }
11999 }
12000
12001
12002 void HEnvironment::Bind(int index, HValue* value) {
12003   DCHECK(value != NULL);
12004   assigned_variables_.Add(index, zone());
12005   values_[index] = value;
12006 }
12007
12008
12009 bool HEnvironment::HasExpressionAt(int index) const {
12010   return index >= parameter_count_ + specials_count_ + local_count_;
12011 }
12012
12013
12014 bool HEnvironment::ExpressionStackIsEmpty() const {
12015   DCHECK(length() >= first_expression_index());
12016   return length() == first_expression_index();
12017 }
12018
12019
12020 void HEnvironment::SetExpressionStackAt(int index_from_top, HValue* value) {
12021   int count = index_from_top + 1;
12022   int index = values_.length() - count;
12023   DCHECK(HasExpressionAt(index));
12024   // The push count must include at least the element in question or else
12025   // the new value will not be included in this environment's history.
12026   if (push_count_ < count) {
12027     // This is the same effect as popping then re-pushing 'count' elements.
12028     pop_count_ += (count - push_count_);
12029     push_count_ = count;
12030   }
12031   values_[index] = value;
12032 }
12033
12034
12035 void HEnvironment::Drop(int count) {
12036   for (int i = 0; i < count; ++i) {
12037     Pop();
12038   }
12039 }
12040
12041
12042 HEnvironment* HEnvironment::Copy() const {
12043   return new(zone()) HEnvironment(this, zone());
12044 }
12045
12046
12047 HEnvironment* HEnvironment::CopyWithoutHistory() const {
12048   HEnvironment* result = Copy();
12049   result->ClearHistory();
12050   return result;
12051 }
12052
12053
12054 HEnvironment* HEnvironment::CopyAsLoopHeader(HBasicBlock* loop_header) const {
12055   HEnvironment* new_env = Copy();
12056   for (int i = 0; i < values_.length(); ++i) {
12057     HPhi* phi = loop_header->AddNewPhi(i);
12058     phi->AddInput(values_[i]);
12059     new_env->values_[i] = phi;
12060   }
12061   new_env->ClearHistory();
12062   return new_env;
12063 }
12064
12065
12066 HEnvironment* HEnvironment::CreateStubEnvironment(HEnvironment* outer,
12067                                                   Handle<JSFunction> target,
12068                                                   FrameType frame_type,
12069                                                   int arguments) const {
12070   HEnvironment* new_env =
12071       new(zone()) HEnvironment(outer, target, frame_type,
12072                                arguments + 1, zone());
12073   for (int i = 0; i <= arguments; ++i) {  // Include receiver.
12074     new_env->Push(ExpressionStackAt(arguments - i));
12075   }
12076   new_env->ClearHistory();
12077   return new_env;
12078 }
12079
12080
12081 HEnvironment* HEnvironment::CopyForInlining(
12082     Handle<JSFunction> target,
12083     int arguments,
12084     FunctionLiteral* function,
12085     HConstant* undefined,
12086     InliningKind inlining_kind) const {
12087   DCHECK(frame_type() == JS_FUNCTION);
12088
12089   // Outer environment is a copy of this one without the arguments.
12090   int arity = function->scope()->num_parameters();
12091
12092   HEnvironment* outer = Copy();
12093   outer->Drop(arguments + 1);  // Including receiver.
12094   outer->ClearHistory();
12095
12096   if (inlining_kind == CONSTRUCT_CALL_RETURN) {
12097     // Create artificial constructor stub environment.  The receiver should
12098     // actually be the constructor function, but we pass the newly allocated
12099     // object instead, DoComputeConstructStubFrame() relies on that.
12100     outer = CreateStubEnvironment(outer, target, JS_CONSTRUCT, arguments);
12101   } else if (inlining_kind == GETTER_CALL_RETURN) {
12102     // We need an additional StackFrame::INTERNAL frame for restoring the
12103     // correct context.
12104     outer = CreateStubEnvironment(outer, target, JS_GETTER, arguments);
12105   } else if (inlining_kind == SETTER_CALL_RETURN) {
12106     // We need an additional StackFrame::INTERNAL frame for temporarily saving
12107     // the argument of the setter, see StoreStubCompiler::CompileStoreViaSetter.
12108     outer = CreateStubEnvironment(outer, target, JS_SETTER, arguments);
12109   }
12110
12111   if (arity != arguments) {
12112     // Create artificial arguments adaptation environment.
12113     outer = CreateStubEnvironment(outer, target, ARGUMENTS_ADAPTOR, arguments);
12114   }
12115
12116   HEnvironment* inner =
12117       new(zone()) HEnvironment(outer, function->scope(), target, zone());
12118   // Get the argument values from the original environment.
12119   for (int i = 0; i <= arity; ++i) {  // Include receiver.
12120     HValue* push = (i <= arguments) ?
12121         ExpressionStackAt(arguments - i) : undefined;
12122     inner->SetValueAt(i, push);
12123   }
12124   inner->SetValueAt(arity + 1, context());
12125   for (int i = arity + 2; i < inner->length(); ++i) {
12126     inner->SetValueAt(i, undefined);
12127   }
12128
12129   inner->set_ast_id(BailoutId::FunctionEntry());
12130   return inner;
12131 }
12132
12133
12134 OStream& operator<<(OStream& os, const HEnvironment& env) {
12135   for (int i = 0; i < env.length(); i++) {
12136     if (i == 0) os << "parameters\n";
12137     if (i == env.parameter_count()) os << "specials\n";
12138     if (i == env.parameter_count() + env.specials_count()) os << "locals\n";
12139     if (i == env.parameter_count() + env.specials_count() + env.local_count()) {
12140       os << "expressions\n";
12141     }
12142     HValue* val = env.values()->at(i);
12143     os << i << ": ";
12144     if (val != NULL) {
12145       os << val;
12146     } else {
12147       os << "NULL";
12148     }
12149     os << "\n";
12150   }
12151   return os << "\n";
12152 }
12153
12154
12155 void HTracer::TraceCompilation(CompilationInfo* info) {
12156   Tag tag(this, "compilation");
12157   if (info->IsOptimizing()) {
12158     Handle<String> name = info->function()->debug_name();
12159     PrintStringProperty("name", name->ToCString().get());
12160     PrintIndent();
12161     trace_.Add("method \"%s:%d\"\n",
12162                name->ToCString().get(),
12163                info->optimization_id());
12164   } else {
12165     CodeStub::Major major_key = info->code_stub()->MajorKey();
12166     PrintStringProperty("name", CodeStub::MajorName(major_key, false));
12167     PrintStringProperty("method", "stub");
12168   }
12169   PrintLongProperty("date",
12170                     static_cast<int64_t>(base::OS::TimeCurrentMillis()));
12171 }
12172
12173
12174 void HTracer::TraceLithium(const char* name, LChunk* chunk) {
12175   DCHECK(!chunk->isolate()->concurrent_recompilation_enabled());
12176   AllowHandleDereference allow_deref;
12177   AllowDeferredHandleDereference allow_deferred_deref;
12178   Trace(name, chunk->graph(), chunk);
12179 }
12180
12181
12182 void HTracer::TraceHydrogen(const char* name, HGraph* graph) {
12183   DCHECK(!graph->isolate()->concurrent_recompilation_enabled());
12184   AllowHandleDereference allow_deref;
12185   AllowDeferredHandleDereference allow_deferred_deref;
12186   Trace(name, graph, NULL);
12187 }
12188
12189
12190 void HTracer::Trace(const char* name, HGraph* graph, LChunk* chunk) {
12191   Tag tag(this, "cfg");
12192   PrintStringProperty("name", name);
12193   const ZoneList<HBasicBlock*>* blocks = graph->blocks();
12194   for (int i = 0; i < blocks->length(); i++) {
12195     HBasicBlock* current = blocks->at(i);
12196     Tag block_tag(this, "block");
12197     PrintBlockProperty("name", current->block_id());
12198     PrintIntProperty("from_bci", -1);
12199     PrintIntProperty("to_bci", -1);
12200
12201     if (!current->predecessors()->is_empty()) {
12202       PrintIndent();
12203       trace_.Add("predecessors");
12204       for (int j = 0; j < current->predecessors()->length(); ++j) {
12205         trace_.Add(" \"B%d\"", current->predecessors()->at(j)->block_id());
12206       }
12207       trace_.Add("\n");
12208     } else {
12209       PrintEmptyProperty("predecessors");
12210     }
12211
12212     if (current->end()->SuccessorCount() == 0) {
12213       PrintEmptyProperty("successors");
12214     } else  {
12215       PrintIndent();
12216       trace_.Add("successors");
12217       for (HSuccessorIterator it(current->end()); !it.Done(); it.Advance()) {
12218         trace_.Add(" \"B%d\"", it.Current()->block_id());
12219       }
12220       trace_.Add("\n");
12221     }
12222
12223     PrintEmptyProperty("xhandlers");
12224
12225     {
12226       PrintIndent();
12227       trace_.Add("flags");
12228       if (current->IsLoopSuccessorDominator()) {
12229         trace_.Add(" \"dom-loop-succ\"");
12230       }
12231       if (current->IsUnreachable()) {
12232         trace_.Add(" \"dead\"");
12233       }
12234       if (current->is_osr_entry()) {
12235         trace_.Add(" \"osr\"");
12236       }
12237       trace_.Add("\n");
12238     }
12239
12240     if (current->dominator() != NULL) {
12241       PrintBlockProperty("dominator", current->dominator()->block_id());
12242     }
12243
12244     PrintIntProperty("loop_depth", current->LoopNestingDepth());
12245
12246     if (chunk != NULL) {
12247       int first_index = current->first_instruction_index();
12248       int last_index = current->last_instruction_index();
12249       PrintIntProperty(
12250           "first_lir_id",
12251           LifetimePosition::FromInstructionIndex(first_index).Value());
12252       PrintIntProperty(
12253           "last_lir_id",
12254           LifetimePosition::FromInstructionIndex(last_index).Value());
12255     }
12256
12257     {
12258       Tag states_tag(this, "states");
12259       Tag locals_tag(this, "locals");
12260       int total = current->phis()->length();
12261       PrintIntProperty("size", current->phis()->length());
12262       PrintStringProperty("method", "None");
12263       for (int j = 0; j < total; ++j) {
12264         HPhi* phi = current->phis()->at(j);
12265         PrintIndent();
12266         OStringStream os;
12267         os << phi->merged_index() << " " << NameOf(phi) << " " << *phi << "\n";
12268         trace_.Add(os.c_str());
12269       }
12270     }
12271
12272     {
12273       Tag HIR_tag(this, "HIR");
12274       for (HInstructionIterator it(current); !it.Done(); it.Advance()) {
12275         HInstruction* instruction = it.Current();
12276         int uses = instruction->UseCount();
12277         PrintIndent();
12278         OStringStream os;
12279         os << "0 " << uses << " " << NameOf(instruction) << " " << *instruction;
12280         if (FLAG_hydrogen_track_positions &&
12281             instruction->has_position() &&
12282             instruction->position().raw() != 0) {
12283           const HSourcePosition pos = instruction->position();
12284           os << " pos:";
12285           if (pos.inlining_id() != 0) os << pos.inlining_id() << "_";
12286           os << pos.position();
12287         }
12288         os << " <|@\n";
12289         trace_.Add(os.c_str());
12290       }
12291     }
12292
12293
12294     if (chunk != NULL) {
12295       Tag LIR_tag(this, "LIR");
12296       int first_index = current->first_instruction_index();
12297       int last_index = current->last_instruction_index();
12298       if (first_index != -1 && last_index != -1) {
12299         const ZoneList<LInstruction*>* instructions = chunk->instructions();
12300         for (int i = first_index; i <= last_index; ++i) {
12301           LInstruction* linstr = instructions->at(i);
12302           if (linstr != NULL) {
12303             PrintIndent();
12304             trace_.Add("%d ",
12305                        LifetimePosition::FromInstructionIndex(i).Value());
12306             linstr->PrintTo(&trace_);
12307             OStringStream os;
12308             os << " [hir:" << NameOf(linstr->hydrogen_value()) << "] <|@\n";
12309             trace_.Add(os.c_str());
12310           }
12311         }
12312       }
12313     }
12314   }
12315 }
12316
12317
12318 void HTracer::TraceLiveRanges(const char* name, LAllocator* allocator) {
12319   Tag tag(this, "intervals");
12320   PrintStringProperty("name", name);
12321
12322   const Vector<LiveRange*>* fixed_d = allocator->fixed_double_live_ranges();
12323   for (int i = 0; i < fixed_d->length(); ++i) {
12324     TraceLiveRange(fixed_d->at(i), "fixed", allocator->zone());
12325   }
12326
12327   const Vector<LiveRange*>* fixed = allocator->fixed_live_ranges();
12328   for (int i = 0; i < fixed->length(); ++i) {
12329     TraceLiveRange(fixed->at(i), "fixed", allocator->zone());
12330   }
12331
12332   const ZoneList<LiveRange*>* live_ranges = allocator->live_ranges();
12333   for (int i = 0; i < live_ranges->length(); ++i) {
12334     TraceLiveRange(live_ranges->at(i), "object", allocator->zone());
12335   }
12336 }
12337
12338
12339 void HTracer::TraceLiveRange(LiveRange* range, const char* type,
12340                              Zone* zone) {
12341   if (range != NULL && !range->IsEmpty()) {
12342     PrintIndent();
12343     trace_.Add("%d %s", range->id(), type);
12344     if (range->HasRegisterAssigned()) {
12345       LOperand* op = range->CreateAssignedOperand(zone);
12346       int assigned_reg = op->index();
12347       if (op->IsDoubleRegister()) {
12348         trace_.Add(" \"%s\"",
12349                    DoubleRegister::AllocationIndexToString(assigned_reg));
12350       } else {
12351         DCHECK(op->IsRegister());
12352         trace_.Add(" \"%s\"", Register::AllocationIndexToString(assigned_reg));
12353       }
12354     } else if (range->IsSpilled()) {
12355       LOperand* op = range->TopLevel()->GetSpillOperand();
12356       if (op->IsDoubleStackSlot()) {
12357         trace_.Add(" \"double_stack:%d\"", op->index());
12358       } else {
12359         DCHECK(op->IsStackSlot());
12360         trace_.Add(" \"stack:%d\"", op->index());
12361       }
12362     }
12363     int parent_index = -1;
12364     if (range->IsChild()) {
12365       parent_index = range->parent()->id();
12366     } else {
12367       parent_index = range->id();
12368     }
12369     LOperand* op = range->FirstHint();
12370     int hint_index = -1;
12371     if (op != NULL && op->IsUnallocated()) {
12372       hint_index = LUnallocated::cast(op)->virtual_register();
12373     }
12374     trace_.Add(" %d %d", parent_index, hint_index);
12375     UseInterval* cur_interval = range->first_interval();
12376     while (cur_interval != NULL && range->Covers(cur_interval->start())) {
12377       trace_.Add(" [%d, %d[",
12378                  cur_interval->start().Value(),
12379                  cur_interval->end().Value());
12380       cur_interval = cur_interval->next();
12381     }
12382
12383     UsePosition* current_pos = range->first_pos();
12384     while (current_pos != NULL) {
12385       if (current_pos->RegisterIsBeneficial() || FLAG_trace_all_uses) {
12386         trace_.Add(" %d M", current_pos->pos().Value());
12387       }
12388       current_pos = current_pos->next();
12389     }
12390
12391     trace_.Add(" \"\"\n");
12392   }
12393 }
12394
12395
12396 void HTracer::FlushToFile() {
12397   AppendChars(filename_.start(), trace_.ToCString().get(), trace_.length(),
12398               false);
12399   trace_.Reset();
12400 }
12401
12402
12403 void HStatistics::Initialize(CompilationInfo* info) {
12404   if (info->shared_info().is_null()) return;
12405   source_size_ += info->shared_info()->SourceSize();
12406 }
12407
12408
12409 void HStatistics::Print(const char* stats_name) {
12410   PrintF(
12411       "\n"
12412       "----------------------------------------"
12413       "----------------------------------------\n"
12414       "--- %s timing results:\n"
12415       "----------------------------------------"
12416       "----------------------------------------\n",
12417       stats_name);
12418   base::TimeDelta sum;
12419   for (int i = 0; i < times_.length(); ++i) {
12420     sum += times_[i];
12421   }
12422
12423   for (int i = 0; i < names_.length(); ++i) {
12424     PrintF("%33s", names_[i]);
12425     double ms = times_[i].InMillisecondsF();
12426     double percent = times_[i].PercentOf(sum);
12427     PrintF(" %8.3f ms / %4.1f %% ", ms, percent);
12428
12429     unsigned size = sizes_[i];
12430     double size_percent = static_cast<double>(size) * 100 / total_size_;
12431     PrintF(" %9u bytes / %4.1f %%\n", size, size_percent);
12432   }
12433
12434   PrintF(
12435       "----------------------------------------"
12436       "----------------------------------------\n");
12437   base::TimeDelta total = create_graph_ + optimize_graph_ + generate_code_;
12438   PrintF("%33s %8.3f ms / %4.1f %% \n", "Create graph",
12439          create_graph_.InMillisecondsF(), create_graph_.PercentOf(total));
12440   PrintF("%33s %8.3f ms / %4.1f %% \n", "Optimize graph",
12441          optimize_graph_.InMillisecondsF(), optimize_graph_.PercentOf(total));
12442   PrintF("%33s %8.3f ms / %4.1f %% \n", "Generate and install code",
12443          generate_code_.InMillisecondsF(), generate_code_.PercentOf(total));
12444   PrintF(
12445       "----------------------------------------"
12446       "----------------------------------------\n");
12447   PrintF("%33s %8.3f ms           %9u bytes\n", "Total",
12448          total.InMillisecondsF(), total_size_);
12449   PrintF("%33s     (%.1f times slower than full code gen)\n", "",
12450          total.TimesOf(full_code_gen_));
12451
12452   double source_size_in_kb = static_cast<double>(source_size_) / 1024;
12453   double normalized_time =  source_size_in_kb > 0
12454       ? total.InMillisecondsF() / source_size_in_kb
12455       : 0;
12456   double normalized_size_in_kb = source_size_in_kb > 0
12457       ? total_size_ / 1024 / source_size_in_kb
12458       : 0;
12459   PrintF("%33s %8.3f ms           %7.3f kB allocated\n",
12460          "Average per kB source", normalized_time, normalized_size_in_kb);
12461 }
12462
12463
12464 void HStatistics::SaveTiming(const char* name, base::TimeDelta time,
12465                              unsigned size) {
12466   total_size_ += size;
12467   for (int i = 0; i < names_.length(); ++i) {
12468     if (strcmp(names_[i], name) == 0) {
12469       times_[i] += time;
12470       sizes_[i] += size;
12471       return;
12472     }
12473   }
12474   names_.Add(name);
12475   times_.Add(time);
12476   sizes_.Add(size);
12477 }
12478
12479
12480 HPhase::~HPhase() {
12481   if (ShouldProduceTraceOutput()) {
12482     isolate()->GetHTracer()->TraceHydrogen(name(), graph_);
12483   }
12484
12485 #ifdef DEBUG
12486   graph_->Verify(false);  // No full verify.
12487 #endif
12488 }
12489
12490 } }  // namespace v8::internal