125ec58c6920a1e6645b575c61225ff7d31cb980
[platform/upstream/v8.git] / src / hydrogen.h
1 // Copyright 2012 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 #ifndef V8_HYDROGEN_H_
6 #define V8_HYDROGEN_H_
7
8 #include "src/v8.h"
9
10 #include "src/accessors.h"
11 #include "src/allocation.h"
12 #include "src/ast.h"
13 #include "src/bailout-reason.h"
14 #include "src/compiler.h"
15 #include "src/hydrogen-instructions.h"
16 #include "src/scopes.h"
17 #include "src/zone.h"
18
19 namespace v8 {
20 namespace internal {
21
22 // Forward declarations.
23 class BitVector;
24 class FunctionState;
25 class HEnvironment;
26 class HGraph;
27 class HLoopInformation;
28 class HOsrBuilder;
29 class HTracer;
30 class LAllocator;
31 class LChunk;
32 class LiveRange;
33
34
35 class HBasicBlock final : public ZoneObject {
36  public:
37   explicit HBasicBlock(HGraph* graph);
38   ~HBasicBlock() { }
39
40   // Simple accessors.
41   int block_id() const { return block_id_; }
42   void set_block_id(int id) { block_id_ = id; }
43   HGraph* graph() const { return graph_; }
44   Isolate* isolate() const;
45   const ZoneList<HPhi*>* phis() const { return &phis_; }
46   HInstruction* first() const { return first_; }
47   HInstruction* last() const { return last_; }
48   void set_last(HInstruction* instr) { last_ = instr; }
49   HControlInstruction* end() const { return end_; }
50   HLoopInformation* loop_information() const { return loop_information_; }
51   HLoopInformation* current_loop() const {
52     return IsLoopHeader() ? loop_information()
53                           : (parent_loop_header() != NULL
54                             ? parent_loop_header()->loop_information() : NULL);
55   }
56   const ZoneList<HBasicBlock*>* predecessors() const { return &predecessors_; }
57   bool HasPredecessor() const { return predecessors_.length() > 0; }
58   const ZoneList<HBasicBlock*>* dominated_blocks() const {
59     return &dominated_blocks_;
60   }
61   const ZoneList<int>* deleted_phis() const {
62     return &deleted_phis_;
63   }
64   void RecordDeletedPhi(int merge_index) {
65     deleted_phis_.Add(merge_index, zone());
66   }
67   HBasicBlock* dominator() const { return dominator_; }
68   HEnvironment* last_environment() const { return last_environment_; }
69   int argument_count() const { return argument_count_; }
70   void set_argument_count(int count) { argument_count_ = count; }
71   int first_instruction_index() const { return first_instruction_index_; }
72   void set_first_instruction_index(int index) {
73     first_instruction_index_ = index;
74   }
75   int last_instruction_index() const { return last_instruction_index_; }
76   void set_last_instruction_index(int index) {
77     last_instruction_index_ = index;
78   }
79   bool is_osr_entry() { return is_osr_entry_; }
80   void set_osr_entry() { is_osr_entry_ = true; }
81
82   void AttachLoopInformation();
83   void DetachLoopInformation();
84   bool IsLoopHeader() const { return loop_information() != NULL; }
85   bool IsStartBlock() const { return block_id() == 0; }
86   void PostProcessLoopHeader(IterationStatement* stmt);
87
88   bool IsFinished() const { return end_ != NULL; }
89   void AddPhi(HPhi* phi);
90   void RemovePhi(HPhi* phi);
91   void AddInstruction(HInstruction* instr, SourcePosition position);
92   bool Dominates(HBasicBlock* other) const;
93   bool EqualToOrDominates(HBasicBlock* other) const;
94   int LoopNestingDepth() const;
95
96   void SetInitialEnvironment(HEnvironment* env);
97   void ClearEnvironment() {
98     DCHECK(IsFinished());
99     DCHECK(end()->SuccessorCount() == 0);
100     last_environment_ = NULL;
101   }
102   bool HasEnvironment() const { return last_environment_ != NULL; }
103   void UpdateEnvironment(HEnvironment* env);
104   HBasicBlock* parent_loop_header() const { return parent_loop_header_; }
105
106   void set_parent_loop_header(HBasicBlock* block) {
107     DCHECK(parent_loop_header_ == NULL);
108     parent_loop_header_ = block;
109   }
110
111   bool HasParentLoopHeader() const { return parent_loop_header_ != NULL; }
112
113   void SetJoinId(BailoutId ast_id);
114
115   int PredecessorIndexOf(HBasicBlock* predecessor) const;
116   HPhi* AddNewPhi(int merged_index);
117   HSimulate* AddNewSimulate(BailoutId ast_id, SourcePosition position,
118                             RemovableSimulate removable = FIXED_SIMULATE) {
119     HSimulate* instr = CreateSimulate(ast_id, removable);
120     AddInstruction(instr, position);
121     return instr;
122   }
123   void AssignCommonDominator(HBasicBlock* other);
124   void AssignLoopSuccessorDominators();
125
126   // If a target block is tagged as an inline function return, all
127   // predecessors should contain the inlined exit sequence:
128   //
129   // LeaveInlined
130   // Simulate (caller's environment)
131   // Goto (target block)
132   bool IsInlineReturnTarget() const { return is_inline_return_target_; }
133   void MarkAsInlineReturnTarget(HBasicBlock* inlined_entry_block) {
134     is_inline_return_target_ = true;
135     inlined_entry_block_ = inlined_entry_block;
136   }
137   HBasicBlock* inlined_entry_block() { return inlined_entry_block_; }
138
139   bool IsDeoptimizing() const {
140     return end() != NULL && end()->IsDeoptimize();
141   }
142
143   void MarkUnreachable();
144   bool IsUnreachable() const { return !is_reachable_; }
145   bool IsReachable() const { return is_reachable_; }
146
147   bool IsLoopSuccessorDominator() const {
148     return dominates_loop_successors_;
149   }
150   void MarkAsLoopSuccessorDominator() {
151     dominates_loop_successors_ = true;
152   }
153
154   bool IsOrdered() const { return is_ordered_; }
155   void MarkAsOrdered() { is_ordered_ = true; }
156
157   void MarkSuccEdgeUnreachable(int succ);
158
159   inline Zone* zone() const;
160
161 #ifdef DEBUG
162   void Verify();
163 #endif
164
165  protected:
166   friend class HGraphBuilder;
167
168   HSimulate* CreateSimulate(BailoutId ast_id, RemovableSimulate removable);
169   void Finish(HControlInstruction* last, SourcePosition position);
170   void FinishExit(HControlInstruction* instruction, SourcePosition position);
171   void Goto(HBasicBlock* block, SourcePosition position,
172             FunctionState* state = NULL, bool add_simulate = true);
173   void GotoNoSimulate(HBasicBlock* block, SourcePosition position) {
174     Goto(block, position, NULL, false);
175   }
176
177   // Add the inlined function exit sequence, adding an HLeaveInlined
178   // instruction and updating the bailout environment.
179   void AddLeaveInlined(HValue* return_value, FunctionState* state,
180                        SourcePosition position);
181
182  private:
183   void RegisterPredecessor(HBasicBlock* pred);
184   void AddDominatedBlock(HBasicBlock* block);
185
186   int block_id_;
187   HGraph* graph_;
188   ZoneList<HPhi*> phis_;
189   HInstruction* first_;
190   HInstruction* last_;
191   HControlInstruction* end_;
192   HLoopInformation* loop_information_;
193   ZoneList<HBasicBlock*> predecessors_;
194   HBasicBlock* dominator_;
195   ZoneList<HBasicBlock*> dominated_blocks_;
196   HEnvironment* last_environment_;
197   // Outgoing parameter count at block exit, set during lithium translation.
198   int argument_count_;
199   // Instruction indices into the lithium code stream.
200   int first_instruction_index_;
201   int last_instruction_index_;
202   ZoneList<int> deleted_phis_;
203   HBasicBlock* parent_loop_header_;
204   // For blocks marked as inline return target: the block with HEnterInlined.
205   HBasicBlock* inlined_entry_block_;
206   bool is_inline_return_target_ : 1;
207   bool is_reachable_ : 1;
208   bool dominates_loop_successors_ : 1;
209   bool is_osr_entry_ : 1;
210   bool is_ordered_ : 1;
211 };
212
213
214 std::ostream& operator<<(std::ostream& os, const HBasicBlock& b);
215
216
217 class HPredecessorIterator final BASE_EMBEDDED {
218  public:
219   explicit HPredecessorIterator(HBasicBlock* block)
220       : predecessor_list_(block->predecessors()), current_(0) { }
221
222   bool Done() { return current_ >= predecessor_list_->length(); }
223   HBasicBlock* Current() { return predecessor_list_->at(current_); }
224   void Advance() { current_++; }
225
226  private:
227   const ZoneList<HBasicBlock*>* predecessor_list_;
228   int current_;
229 };
230
231
232 class HInstructionIterator final BASE_EMBEDDED {
233  public:
234   explicit HInstructionIterator(HBasicBlock* block)
235       : instr_(block->first()) {
236     next_ = Done() ? NULL : instr_->next();
237   }
238
239   inline bool Done() const { return instr_ == NULL; }
240   inline HInstruction* Current() { return instr_; }
241   inline void Advance() {
242     instr_ = next_;
243     next_ = Done() ? NULL : instr_->next();
244   }
245
246  private:
247   HInstruction* instr_;
248   HInstruction* next_;
249 };
250
251
252 class HLoopInformation final : public ZoneObject {
253  public:
254   HLoopInformation(HBasicBlock* loop_header, Zone* zone)
255       : back_edges_(4, zone),
256         loop_header_(loop_header),
257         blocks_(8, zone),
258         stack_check_(NULL) {
259     blocks_.Add(loop_header, zone);
260   }
261   ~HLoopInformation() {}
262
263   const ZoneList<HBasicBlock*>* back_edges() const { return &back_edges_; }
264   const ZoneList<HBasicBlock*>* blocks() const { return &blocks_; }
265   HBasicBlock* loop_header() const { return loop_header_; }
266   HBasicBlock* GetLastBackEdge() const;
267   void RegisterBackEdge(HBasicBlock* block);
268
269   HStackCheck* stack_check() const { return stack_check_; }
270   void set_stack_check(HStackCheck* stack_check) {
271     stack_check_ = stack_check;
272   }
273
274   bool IsNestedInThisLoop(HLoopInformation* other) {
275     while (other != NULL) {
276       if (other == this) {
277         return true;
278       }
279       other = other->parent_loop();
280     }
281     return false;
282   }
283   HLoopInformation* parent_loop() {
284     HBasicBlock* parent_header = loop_header()->parent_loop_header();
285     return parent_header != NULL ? parent_header->loop_information() : NULL;
286   }
287
288  private:
289   void AddBlock(HBasicBlock* block);
290
291   ZoneList<HBasicBlock*> back_edges_;
292   HBasicBlock* loop_header_;
293   ZoneList<HBasicBlock*> blocks_;
294   HStackCheck* stack_check_;
295 };
296
297
298 class BoundsCheckTable;
299 class InductionVariableBlocksTable;
300 class HGraph final : public ZoneObject {
301  public:
302   explicit HGraph(CompilationInfo* info);
303
304   Isolate* isolate() const { return isolate_; }
305   Zone* zone() const { return zone_; }
306   CompilationInfo* info() const { return info_; }
307
308   const ZoneList<HBasicBlock*>* blocks() const { return &blocks_; }
309   const ZoneList<HPhi*>* phi_list() const { return phi_list_; }
310   HBasicBlock* entry_block() const { return entry_block_; }
311   HEnvironment* start_environment() const { return start_environment_; }
312
313   void FinalizeUniqueness();
314   void OrderBlocks();
315   void AssignDominators();
316   void RestoreActualValues();
317
318   // Returns false if there are phi-uses of the arguments-object
319   // which are not supported by the optimizing compiler.
320   bool CheckArgumentsPhiUses();
321
322   // Returns false if there are phi-uses of an uninitialized const
323   // which are not supported by the optimizing compiler.
324   bool CheckConstPhiUses();
325
326   void CollectPhis();
327
328   HConstant* GetConstantUndefined();
329   HConstant* GetConstant0();
330   HConstant* GetConstant1();
331   HConstant* GetConstantMinus1();
332   HConstant* GetConstantTrue();
333   HConstant* GetConstantFalse();
334   HConstant* GetConstantHole();
335   HConstant* GetConstantNull();
336   HConstant* GetInvalidContext();
337
338   bool IsConstantUndefined(HConstant* constant);
339   bool IsConstant0(HConstant* constant);
340   bool IsConstant1(HConstant* constant);
341   bool IsConstantMinus1(HConstant* constant);
342   bool IsConstantTrue(HConstant* constant);
343   bool IsConstantFalse(HConstant* constant);
344   bool IsConstantHole(HConstant* constant);
345   bool IsConstantNull(HConstant* constant);
346   bool IsStandardConstant(HConstant* constant);
347
348   HBasicBlock* CreateBasicBlock();
349   HArgumentsObject* GetArgumentsObject() const {
350     return arguments_object_.get();
351   }
352
353   void SetArgumentsObject(HArgumentsObject* object) {
354     arguments_object_.set(object);
355   }
356
357   int GetMaximumValueID() const { return values_.length(); }
358   int GetNextBlockID() { return next_block_id_++; }
359   int GetNextValueID(HValue* value) {
360     DCHECK(!disallow_adding_new_values_);
361     values_.Add(value, zone());
362     return values_.length() - 1;
363   }
364   HValue* LookupValue(int id) const {
365     if (id >= 0 && id < values_.length()) return values_[id];
366     return NULL;
367   }
368   void DisallowAddingNewValues() {
369     disallow_adding_new_values_ = true;
370   }
371
372   bool Optimize(BailoutReason* bailout_reason);
373
374 #ifdef DEBUG
375   void Verify(bool do_full_verify) const;
376 #endif
377
378   bool has_osr() {
379     return osr_ != NULL;
380   }
381
382   void set_osr(HOsrBuilder* osr) {
383     osr_ = osr;
384   }
385
386   HOsrBuilder* osr() {
387     return osr_;
388   }
389
390   int update_type_change_checksum(int delta) {
391     type_change_checksum_ += delta;
392     return type_change_checksum_;
393   }
394
395   void update_maximum_environment_size(int environment_size) {
396     if (environment_size > maximum_environment_size_) {
397       maximum_environment_size_ = environment_size;
398     }
399   }
400   int maximum_environment_size() { return maximum_environment_size_; }
401
402   bool use_optimistic_licm() {
403     return use_optimistic_licm_;
404   }
405
406   void set_use_optimistic_licm(bool value) {
407     use_optimistic_licm_ = value;
408   }
409
410   void MarkRecursive() { is_recursive_ = true; }
411   bool is_recursive() const { return is_recursive_; }
412
413   void MarkDependsOnEmptyArrayProtoElements() {
414     // Add map dependency if not already added.
415     if (depends_on_empty_array_proto_elements_) return;
416     info()->dependencies()->AssumePropertyCell(
417         isolate()->factory()->array_protector());
418     depends_on_empty_array_proto_elements_ = true;
419   }
420
421   bool depends_on_empty_array_proto_elements() {
422     return depends_on_empty_array_proto_elements_;
423   }
424
425   bool has_uint32_instructions() {
426     DCHECK(uint32_instructions_ == NULL || !uint32_instructions_->is_empty());
427     return uint32_instructions_ != NULL;
428   }
429
430   ZoneList<HInstruction*>* uint32_instructions() {
431     DCHECK(uint32_instructions_ == NULL || !uint32_instructions_->is_empty());
432     return uint32_instructions_;
433   }
434
435   void RecordUint32Instruction(HInstruction* instr) {
436     DCHECK(uint32_instructions_ == NULL || !uint32_instructions_->is_empty());
437     if (uint32_instructions_ == NULL) {
438       uint32_instructions_ = new(zone()) ZoneList<HInstruction*>(4, zone());
439     }
440     uint32_instructions_->Add(instr, zone());
441   }
442
443   void IncrementInNoSideEffectsScope() { no_side_effects_scope_count_++; }
444   void DecrementInNoSideEffectsScope() { no_side_effects_scope_count_--; }
445   bool IsInsideNoSideEffectsScope() { return no_side_effects_scope_count_ > 0; }
446
447   // If we are tracking source positions then this function assigns a unique
448   // identifier to each inlining and dumps function source if it was inlined
449   // for the first time during the current optimization.
450   int TraceInlinedFunction(Handle<SharedFunctionInfo> shared,
451                            SourcePosition position);
452
453   // Converts given SourcePosition to the absolute offset from the start of
454   // the corresponding script.
455   int SourcePositionToScriptPosition(SourcePosition position);
456
457  private:
458   HConstant* ReinsertConstantIfNecessary(HConstant* constant);
459   HConstant* GetConstant(SetOncePointer<HConstant>* pointer,
460                          int32_t integer_value);
461
462   template<class Phase>
463   void Run() {
464     Phase phase(this);
465     phase.Run();
466   }
467
468   Isolate* isolate_;
469   int next_block_id_;
470   HBasicBlock* entry_block_;
471   HEnvironment* start_environment_;
472   ZoneList<HBasicBlock*> blocks_;
473   ZoneList<HValue*> values_;
474   ZoneList<HPhi*>* phi_list_;
475   ZoneList<HInstruction*>* uint32_instructions_;
476   SetOncePointer<HConstant> constant_undefined_;
477   SetOncePointer<HConstant> constant_0_;
478   SetOncePointer<HConstant> constant_1_;
479   SetOncePointer<HConstant> constant_minus1_;
480   SetOncePointer<HConstant> constant_true_;
481   SetOncePointer<HConstant> constant_false_;
482   SetOncePointer<HConstant> constant_the_hole_;
483   SetOncePointer<HConstant> constant_null_;
484   SetOncePointer<HConstant> constant_invalid_context_;
485   SetOncePointer<HArgumentsObject> arguments_object_;
486
487   HOsrBuilder* osr_;
488
489   CompilationInfo* info_;
490   Zone* zone_;
491
492   bool is_recursive_;
493   bool use_optimistic_licm_;
494   bool depends_on_empty_array_proto_elements_;
495   int type_change_checksum_;
496   int maximum_environment_size_;
497   int no_side_effects_scope_count_;
498   bool disallow_adding_new_values_;
499
500   DISALLOW_COPY_AND_ASSIGN(HGraph);
501 };
502
503
504 Zone* HBasicBlock::zone() const { return graph_->zone(); }
505
506
507 // Type of stack frame an environment might refer to.
508 enum FrameType {
509   JS_FUNCTION,
510   JS_CONSTRUCT,
511   JS_GETTER,
512   JS_SETTER,
513   ARGUMENTS_ADAPTOR,
514   STUB
515 };
516
517
518 class HEnvironment final : public ZoneObject {
519  public:
520   HEnvironment(HEnvironment* outer,
521                Scope* scope,
522                Handle<JSFunction> closure,
523                Zone* zone);
524
525   HEnvironment(Zone* zone, int parameter_count);
526
527   HEnvironment* arguments_environment() {
528     return outer()->frame_type() == ARGUMENTS_ADAPTOR ? outer() : this;
529   }
530
531   // Simple accessors.
532   Handle<JSFunction> closure() const { return closure_; }
533   const ZoneList<HValue*>* values() const { return &values_; }
534   const GrowableBitVector* assigned_variables() const {
535     return &assigned_variables_;
536   }
537   FrameType frame_type() const { return frame_type_; }
538   int parameter_count() const { return parameter_count_; }
539   int specials_count() const { return specials_count_; }
540   int local_count() const { return local_count_; }
541   HEnvironment* outer() const { return outer_; }
542   int pop_count() const { return pop_count_; }
543   int push_count() const { return push_count_; }
544
545   BailoutId ast_id() const { return ast_id_; }
546   void set_ast_id(BailoutId id) { ast_id_ = id; }
547
548   HEnterInlined* entry() const { return entry_; }
549   void set_entry(HEnterInlined* entry) { entry_ = entry; }
550
551   int length() const { return values_.length(); }
552
553   int first_expression_index() const {
554     return parameter_count() + specials_count() + local_count();
555   }
556
557   int first_local_index() const {
558     return parameter_count() + specials_count();
559   }
560
561   void Bind(Variable* variable, HValue* value) {
562     Bind(IndexFor(variable), value);
563   }
564
565   void Bind(int index, HValue* value);
566
567   void BindContext(HValue* value) {
568     Bind(parameter_count(), value);
569   }
570
571   HValue* Lookup(Variable* variable) const {
572     return Lookup(IndexFor(variable));
573   }
574
575   HValue* Lookup(int index) const {
576     HValue* result = values_[index];
577     DCHECK(result != NULL);
578     return result;
579   }
580
581   HValue* context() const {
582     // Return first special.
583     return Lookup(parameter_count());
584   }
585
586   void Push(HValue* value) {
587     DCHECK(value != NULL);
588     ++push_count_;
589     values_.Add(value, zone());
590   }
591
592   HValue* Pop() {
593     DCHECK(!ExpressionStackIsEmpty());
594     if (push_count_ > 0) {
595       --push_count_;
596     } else {
597       ++pop_count_;
598     }
599     return values_.RemoveLast();
600   }
601
602   void Drop(int count);
603
604   HValue* Top() const { return ExpressionStackAt(0); }
605
606   bool ExpressionStackIsEmpty() const;
607
608   HValue* ExpressionStackAt(int index_from_top) const {
609     int index = length() - index_from_top - 1;
610     DCHECK(HasExpressionAt(index));
611     return values_[index];
612   }
613
614   void SetExpressionStackAt(int index_from_top, HValue* value);
615   HValue* RemoveExpressionStackAt(int index_from_top);
616
617   HEnvironment* Copy() const;
618   HEnvironment* CopyWithoutHistory() const;
619   HEnvironment* CopyAsLoopHeader(HBasicBlock* block) const;
620
621   // Create an "inlined version" of this environment, where the original
622   // environment is the outer environment but the top expression stack
623   // elements are moved to an inner environment as parameters.
624   HEnvironment* CopyForInlining(Handle<JSFunction> target,
625                                 int arguments,
626                                 FunctionLiteral* function,
627                                 HConstant* undefined,
628                                 InliningKind inlining_kind) const;
629
630   HEnvironment* DiscardInlined(bool drop_extra) {
631     HEnvironment* outer = outer_;
632     while (outer->frame_type() != JS_FUNCTION) outer = outer->outer_;
633     if (drop_extra) outer->Drop(1);
634     return outer;
635   }
636
637   void AddIncomingEdge(HBasicBlock* block, HEnvironment* other);
638
639   void ClearHistory() {
640     pop_count_ = 0;
641     push_count_ = 0;
642     assigned_variables_.Clear();
643   }
644
645   void SetValueAt(int index, HValue* value) {
646     DCHECK(index < length());
647     values_[index] = value;
648   }
649
650   // Map a variable to an environment index.  Parameter indices are shifted
651   // by 1 (receiver is parameter index -1 but environment index 0).
652   // Stack-allocated local indices are shifted by the number of parameters.
653   int IndexFor(Variable* variable) const {
654     DCHECK(variable->IsStackAllocated());
655     int shift = variable->IsParameter()
656         ? 1
657         : parameter_count_ + specials_count_;
658     return variable->index() + shift;
659   }
660
661   bool is_local_index(int i) const {
662     return i >= first_local_index() && i < first_expression_index();
663   }
664
665   bool is_parameter_index(int i) const {
666     return i >= 0 && i < parameter_count();
667   }
668
669   bool is_special_index(int i) const {
670     return i >= parameter_count() && i < parameter_count() + specials_count();
671   }
672
673   Zone* zone() const { return zone_; }
674
675  private:
676   HEnvironment(const HEnvironment* other, Zone* zone);
677
678   HEnvironment(HEnvironment* outer,
679                Handle<JSFunction> closure,
680                FrameType frame_type,
681                int arguments,
682                Zone* zone);
683
684   // Create an artificial stub environment (e.g. for argument adaptor or
685   // constructor stub).
686   HEnvironment* CreateStubEnvironment(HEnvironment* outer,
687                                       Handle<JSFunction> target,
688                                       FrameType frame_type,
689                                       int arguments) const;
690
691   // True if index is included in the expression stack part of the environment.
692   bool HasExpressionAt(int index) const;
693
694   void Initialize(int parameter_count, int local_count, int stack_height);
695   void Initialize(const HEnvironment* other);
696
697   Handle<JSFunction> closure_;
698   // Value array [parameters] [specials] [locals] [temporaries].
699   ZoneList<HValue*> values_;
700   GrowableBitVector assigned_variables_;
701   FrameType frame_type_;
702   int parameter_count_;
703   int specials_count_;
704   int local_count_;
705   HEnvironment* outer_;
706   HEnterInlined* entry_;
707   int pop_count_;
708   int push_count_;
709   BailoutId ast_id_;
710   Zone* zone_;
711 };
712
713
714 std::ostream& operator<<(std::ostream& os, const HEnvironment& env);
715
716
717 class HOptimizedGraphBuilder;
718
719 enum ArgumentsAllowedFlag {
720   ARGUMENTS_NOT_ALLOWED,
721   ARGUMENTS_ALLOWED,
722   ARGUMENTS_FAKED
723 };
724
725
726 class HIfContinuation;
727
728 // This class is not BASE_EMBEDDED because our inlining implementation uses
729 // new and delete.
730 class AstContext {
731  public:
732   bool IsEffect() const { return kind_ == Expression::kEffect; }
733   bool IsValue() const { return kind_ == Expression::kValue; }
734   bool IsTest() const { return kind_ == Expression::kTest; }
735
736   // 'Fill' this context with a hydrogen value.  The value is assumed to
737   // have already been inserted in the instruction stream (or not need to
738   // be, e.g., HPhi).  Call this function in tail position in the Visit
739   // functions for expressions.
740   virtual void ReturnValue(HValue* value) = 0;
741
742   // Add a hydrogen instruction to the instruction stream (recording an
743   // environment simulation if necessary) and then fill this context with
744   // the instruction as value.
745   virtual void ReturnInstruction(HInstruction* instr, BailoutId ast_id) = 0;
746
747   // Finishes the current basic block and materialize a boolean for
748   // value context, nothing for effect, generate a branch for test context.
749   // Call this function in tail position in the Visit functions for
750   // expressions.
751   virtual void ReturnControl(HControlInstruction* instr, BailoutId ast_id) = 0;
752
753   // Finishes the current basic block and materialize a boolean for
754   // value context, nothing for effect, generate a branch for test context.
755   // Call this function in tail position in the Visit functions for
756   // expressions that use an IfBuilder.
757   virtual void ReturnContinuation(HIfContinuation* continuation,
758                                   BailoutId ast_id) = 0;
759
760   void set_for_typeof(bool for_typeof) { for_typeof_ = for_typeof; }
761   bool is_for_typeof() { return for_typeof_; }
762
763  protected:
764   AstContext(HOptimizedGraphBuilder* owner, Expression::Context kind);
765   virtual ~AstContext();
766
767   HOptimizedGraphBuilder* owner() const { return owner_; }
768
769   inline Zone* zone() const;
770
771   // We want to be able to assert, in a context-specific way, that the stack
772   // height makes sense when the context is filled.
773 #ifdef DEBUG
774   int original_length_;
775 #endif
776
777  private:
778   HOptimizedGraphBuilder* owner_;
779   Expression::Context kind_;
780   AstContext* outer_;
781   bool for_typeof_;
782 };
783
784
785 class EffectContext final : public AstContext {
786  public:
787   explicit EffectContext(HOptimizedGraphBuilder* owner)
788       : AstContext(owner, Expression::kEffect) {
789   }
790   virtual ~EffectContext();
791
792   void ReturnValue(HValue* value) override;
793   virtual void ReturnInstruction(HInstruction* instr,
794                                  BailoutId ast_id) override;
795   virtual void ReturnControl(HControlInstruction* instr,
796                              BailoutId ast_id) override;
797   virtual void ReturnContinuation(HIfContinuation* continuation,
798                                   BailoutId ast_id) override;
799 };
800
801
802 class ValueContext final : public AstContext {
803  public:
804   ValueContext(HOptimizedGraphBuilder* owner, ArgumentsAllowedFlag flag)
805       : AstContext(owner, Expression::kValue), flag_(flag) {
806   }
807   virtual ~ValueContext();
808
809   void ReturnValue(HValue* value) override;
810   virtual void ReturnInstruction(HInstruction* instr,
811                                  BailoutId ast_id) override;
812   virtual void ReturnControl(HControlInstruction* instr,
813                              BailoutId ast_id) override;
814   virtual void ReturnContinuation(HIfContinuation* continuation,
815                                   BailoutId ast_id) override;
816
817   bool arguments_allowed() { return flag_ == ARGUMENTS_ALLOWED; }
818
819  private:
820   ArgumentsAllowedFlag flag_;
821 };
822
823
824 class TestContext final : public AstContext {
825  public:
826   TestContext(HOptimizedGraphBuilder* owner,
827               Expression* condition,
828               HBasicBlock* if_true,
829               HBasicBlock* if_false)
830       : AstContext(owner, Expression::kTest),
831         condition_(condition),
832         if_true_(if_true),
833         if_false_(if_false) {
834   }
835
836   void ReturnValue(HValue* value) override;
837   virtual void ReturnInstruction(HInstruction* instr,
838                                  BailoutId ast_id) override;
839   virtual void ReturnControl(HControlInstruction* instr,
840                              BailoutId ast_id) override;
841   virtual void ReturnContinuation(HIfContinuation* continuation,
842                                   BailoutId ast_id) override;
843
844   static TestContext* cast(AstContext* context) {
845     DCHECK(context->IsTest());
846     return reinterpret_cast<TestContext*>(context);
847   }
848
849   Expression* condition() const { return condition_; }
850   HBasicBlock* if_true() const { return if_true_; }
851   HBasicBlock* if_false() const { return if_false_; }
852
853  private:
854   // Build the shared core part of the translation unpacking a value into
855   // control flow.
856   void BuildBranch(HValue* value);
857
858   Expression* condition_;
859   HBasicBlock* if_true_;
860   HBasicBlock* if_false_;
861 };
862
863
864 class FunctionState final {
865  public:
866   FunctionState(HOptimizedGraphBuilder* owner,
867                 CompilationInfo* info,
868                 InliningKind inlining_kind,
869                 int inlining_id);
870   ~FunctionState();
871
872   CompilationInfo* compilation_info() { return compilation_info_; }
873   AstContext* call_context() { return call_context_; }
874   InliningKind inlining_kind() const { return inlining_kind_; }
875   HBasicBlock* function_return() { return function_return_; }
876   TestContext* test_context() { return test_context_; }
877   void ClearInlinedTestContext() {
878     delete test_context_;
879     test_context_ = NULL;
880   }
881
882   FunctionState* outer() { return outer_; }
883
884   HEnterInlined* entry() { return entry_; }
885   void set_entry(HEnterInlined* entry) { entry_ = entry; }
886
887   HArgumentsObject* arguments_object() { return arguments_object_; }
888   void set_arguments_object(HArgumentsObject* arguments_object) {
889     arguments_object_ = arguments_object;
890   }
891
892   HArgumentsElements* arguments_elements() { return arguments_elements_; }
893   void set_arguments_elements(HArgumentsElements* arguments_elements) {
894     arguments_elements_ = arguments_elements;
895   }
896
897   bool arguments_pushed() { return arguments_elements() != NULL; }
898
899   int inlining_id() const { return inlining_id_; }
900
901  private:
902   HOptimizedGraphBuilder* owner_;
903
904   CompilationInfo* compilation_info_;
905
906   // During function inlining, expression context of the call being
907   // inlined. NULL when not inlining.
908   AstContext* call_context_;
909
910   // The kind of call which is currently being inlined.
911   InliningKind inlining_kind_;
912
913   // When inlining in an effect or value context, this is the return block.
914   // It is NULL otherwise.  When inlining in a test context, there are a
915   // pair of return blocks in the context.  When not inlining, there is no
916   // local return point.
917   HBasicBlock* function_return_;
918
919   // When inlining a call in a test context, a context containing a pair of
920   // return blocks.  NULL in all other cases.
921   TestContext* test_context_;
922
923   // When inlining HEnterInlined instruction corresponding to the function
924   // entry.
925   HEnterInlined* entry_;
926
927   HArgumentsObject* arguments_object_;
928   HArgumentsElements* arguments_elements_;
929
930   int inlining_id_;
931   SourcePosition outer_source_position_;
932
933   FunctionState* outer_;
934 };
935
936
937 class HIfContinuation final {
938  public:
939   HIfContinuation()
940     : continuation_captured_(false),
941       true_branch_(NULL),
942       false_branch_(NULL) {}
943   HIfContinuation(HBasicBlock* true_branch,
944                   HBasicBlock* false_branch)
945       : continuation_captured_(true), true_branch_(true_branch),
946         false_branch_(false_branch) {}
947   ~HIfContinuation() { DCHECK(!continuation_captured_); }
948
949   void Capture(HBasicBlock* true_branch,
950                HBasicBlock* false_branch) {
951     DCHECK(!continuation_captured_);
952     true_branch_ = true_branch;
953     false_branch_ = false_branch;
954     continuation_captured_ = true;
955   }
956
957   void Continue(HBasicBlock** true_branch,
958                 HBasicBlock** false_branch) {
959     DCHECK(continuation_captured_);
960     *true_branch = true_branch_;
961     *false_branch = false_branch_;
962     continuation_captured_ = false;
963   }
964
965   bool IsTrueReachable() { return true_branch_ != NULL; }
966   bool IsFalseReachable() { return false_branch_ != NULL; }
967   bool TrueAndFalseReachable() {
968     return IsTrueReachable() || IsFalseReachable();
969   }
970
971   HBasicBlock* true_branch() const { return true_branch_; }
972   HBasicBlock* false_branch() const { return false_branch_; }
973
974  private:
975   bool continuation_captured_;
976   HBasicBlock* true_branch_;
977   HBasicBlock* false_branch_;
978 };
979
980
981 class HAllocationMode final BASE_EMBEDDED {
982  public:
983   explicit HAllocationMode(Handle<AllocationSite> feedback_site)
984       : current_site_(NULL), feedback_site_(feedback_site),
985         pretenure_flag_(NOT_TENURED) {}
986   explicit HAllocationMode(HValue* current_site)
987       : current_site_(current_site), pretenure_flag_(NOT_TENURED) {}
988   explicit HAllocationMode(PretenureFlag pretenure_flag)
989       : current_site_(NULL), pretenure_flag_(pretenure_flag) {}
990   HAllocationMode()
991       : current_site_(NULL), pretenure_flag_(NOT_TENURED) {}
992
993   HValue* current_site() const { return current_site_; }
994   Handle<AllocationSite> feedback_site() const { return feedback_site_; }
995
996   bool CreateAllocationMementos() const WARN_UNUSED_RESULT {
997     return current_site() != NULL;
998   }
999
1000   PretenureFlag GetPretenureMode() const WARN_UNUSED_RESULT {
1001     if (!feedback_site().is_null()) return feedback_site()->GetPretenureMode();
1002     return pretenure_flag_;
1003   }
1004
1005  private:
1006   HValue* current_site_;
1007   Handle<AllocationSite> feedback_site_;
1008   PretenureFlag pretenure_flag_;
1009 };
1010
1011
1012 class HGraphBuilder {
1013  public:
1014   explicit HGraphBuilder(CompilationInfo* info)
1015       : info_(info),
1016         graph_(NULL),
1017         current_block_(NULL),
1018         scope_(info->scope()),
1019         position_(SourcePosition::Unknown()),
1020         start_position_(0) {}
1021   virtual ~HGraphBuilder() {}
1022
1023   Scope* scope() const { return scope_; }
1024   void set_scope(Scope* scope) { scope_ = scope; }
1025
1026   HBasicBlock* current_block() const { return current_block_; }
1027   void set_current_block(HBasicBlock* block) { current_block_ = block; }
1028   HEnvironment* environment() const {
1029     return current_block()->last_environment();
1030   }
1031   Zone* zone() const { return info_->zone(); }
1032   HGraph* graph() const { return graph_; }
1033   Isolate* isolate() const { return graph_->isolate(); }
1034   CompilationInfo* top_info() { return info_; }
1035
1036   HGraph* CreateGraph();
1037
1038   // Bailout environment manipulation.
1039   void Push(HValue* value) { environment()->Push(value); }
1040   HValue* Pop() { return environment()->Pop(); }
1041
1042   virtual HValue* context() = 0;
1043
1044   // Adding instructions.
1045   HInstruction* AddInstruction(HInstruction* instr);
1046   void FinishCurrentBlock(HControlInstruction* last);
1047   void FinishExitCurrentBlock(HControlInstruction* instruction);
1048
1049   void Goto(HBasicBlock* from,
1050             HBasicBlock* target,
1051             FunctionState* state = NULL,
1052             bool add_simulate = true) {
1053     from->Goto(target, source_position(), state, add_simulate);
1054   }
1055   void Goto(HBasicBlock* target,
1056             FunctionState* state = NULL,
1057             bool add_simulate = true) {
1058     Goto(current_block(), target, state, add_simulate);
1059   }
1060   void GotoNoSimulate(HBasicBlock* from, HBasicBlock* target) {
1061     Goto(from, target, NULL, false);
1062   }
1063   void GotoNoSimulate(HBasicBlock* target) {
1064     Goto(target, NULL, false);
1065   }
1066   void AddLeaveInlined(HBasicBlock* block,
1067                        HValue* return_value,
1068                        FunctionState* state) {
1069     block->AddLeaveInlined(return_value, state, source_position());
1070   }
1071   void AddLeaveInlined(HValue* return_value, FunctionState* state) {
1072     return AddLeaveInlined(current_block(), return_value, state);
1073   }
1074
1075   template <class I>
1076   HInstruction* NewUncasted() {
1077     return I::New(isolate(), zone(), context());
1078   }
1079
1080   template <class I>
1081   I* New() {
1082     return I::New(isolate(), zone(), context());
1083   }
1084
1085   template<class I>
1086   HInstruction* AddUncasted() { return AddInstruction(NewUncasted<I>());}
1087
1088   template<class I>
1089   I* Add() { return AddInstructionTyped(New<I>());}
1090
1091   template<class I, class P1>
1092   HInstruction* NewUncasted(P1 p1) {
1093     return I::New(isolate(), zone(), context(), p1);
1094   }
1095
1096   template <class I, class P1>
1097   I* New(P1 p1) {
1098     return I::New(isolate(), zone(), context(), p1);
1099   }
1100
1101   template<class I, class P1>
1102   HInstruction* AddUncasted(P1 p1) {
1103     HInstruction* result = AddInstruction(NewUncasted<I>(p1));
1104     // Specializations must have their parameters properly casted
1105     // to avoid landing here.
1106     DCHECK(!result->IsReturn() && !result->IsSimulate() &&
1107            !result->IsDeoptimize());
1108     return result;
1109   }
1110
1111   template<class I, class P1>
1112   I* Add(P1 p1) {
1113     I* result = AddInstructionTyped(New<I>(p1));
1114     // Specializations must have their parameters properly casted
1115     // to avoid landing here.
1116     DCHECK(!result->IsReturn() && !result->IsSimulate() &&
1117            !result->IsDeoptimize());
1118     return result;
1119   }
1120
1121   template<class I, class P1, class P2>
1122   HInstruction* NewUncasted(P1 p1, P2 p2) {
1123     return I::New(isolate(), zone(), context(), p1, p2);
1124   }
1125
1126   template<class I, class P1, class P2>
1127   I* New(P1 p1, P2 p2) {
1128     return I::New(isolate(), zone(), context(), p1, p2);
1129   }
1130
1131   template<class I, class P1, class P2>
1132   HInstruction* AddUncasted(P1 p1, P2 p2) {
1133     HInstruction* result = AddInstruction(NewUncasted<I>(p1, p2));
1134     // Specializations must have their parameters properly casted
1135     // to avoid landing here.
1136     DCHECK(!result->IsSimulate());
1137     return result;
1138   }
1139
1140   template<class I, class P1, class P2>
1141   I* Add(P1 p1, P2 p2) {
1142     I* result = AddInstructionTyped(New<I>(p1, p2));
1143     // Specializations must have their parameters properly casted
1144     // to avoid landing here.
1145     DCHECK(!result->IsSimulate());
1146     return result;
1147   }
1148
1149   template<class I, class P1, class P2, class P3>
1150   HInstruction* NewUncasted(P1 p1, P2 p2, P3 p3) {
1151     return I::New(isolate(), zone(), context(), p1, p2, p3);
1152   }
1153
1154   template<class I, class P1, class P2, class P3>
1155   I* New(P1 p1, P2 p2, P3 p3) {
1156     return I::New(isolate(), zone(), context(), p1, p2, p3);
1157   }
1158
1159   template<class I, class P1, class P2, class P3>
1160   HInstruction* AddUncasted(P1 p1, P2 p2, P3 p3) {
1161     return AddInstruction(NewUncasted<I>(p1, p2, p3));
1162   }
1163
1164   template<class I, class P1, class P2, class P3>
1165   I* Add(P1 p1, P2 p2, P3 p3) {
1166     return AddInstructionTyped(New<I>(p1, p2, p3));
1167   }
1168
1169   template<class I, class P1, class P2, class P3, class P4>
1170   HInstruction* NewUncasted(P1 p1, P2 p2, P3 p3, P4 p4) {
1171     return I::New(isolate(), zone(), context(), p1, p2, p3, p4);
1172   }
1173
1174   template<class I, class P1, class P2, class P3, class P4>
1175   I* New(P1 p1, P2 p2, P3 p3, P4 p4) {
1176     return I::New(isolate(), zone(), context(), p1, p2, p3, p4);
1177   }
1178
1179   template<class I, class P1, class P2, class P3, class P4>
1180   HInstruction* AddUncasted(P1 p1, P2 p2, P3 p3, P4 p4) {
1181     return AddInstruction(NewUncasted<I>(p1, p2, p3, p4));
1182   }
1183
1184   template<class I, class P1, class P2, class P3, class P4>
1185   I* Add(P1 p1, P2 p2, P3 p3, P4 p4) {
1186     return AddInstructionTyped(New<I>(p1, p2, p3, p4));
1187   }
1188
1189   template<class I, class P1, class P2, class P3, class P4, class P5>
1190   HInstruction* NewUncasted(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) {
1191     return I::New(isolate(), zone(), context(), p1, p2, p3, p4, p5);
1192   }
1193
1194   template<class I, class P1, class P2, class P3, class P4, class P5>
1195   I* New(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) {
1196     return I::New(isolate(), zone(), context(), p1, p2, p3, p4, p5);
1197   }
1198
1199   template<class I, class P1, class P2, class P3, class P4, class P5>
1200   HInstruction* AddUncasted(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) {
1201     return AddInstruction(NewUncasted<I>(p1, p2, p3, p4, p5));
1202   }
1203
1204   template<class I, class P1, class P2, class P3, class P4, class P5>
1205   I* Add(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) {
1206     return AddInstructionTyped(New<I>(p1, p2, p3, p4, p5));
1207   }
1208
1209   template<class I, class P1, class P2, class P3, class P4, class P5, class P6>
1210   HInstruction* NewUncasted(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6) {
1211     return I::New(isolate(), zone(), context(), p1, p2, p3, p4, p5, p6);
1212   }
1213
1214   template<class I, class P1, class P2, class P3, class P4, class P5, class P6>
1215   I* New(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6) {
1216     return I::New(isolate(), zone(), context(), p1, p2, p3, p4, p5, p6);
1217   }
1218
1219   template<class I, class P1, class P2, class P3, class P4, class P5, class P6>
1220   HInstruction* AddUncasted(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6) {
1221     return AddInstruction(NewUncasted<I>(p1, p2, p3, p4, p5, p6));
1222   }
1223
1224   template<class I, class P1, class P2, class P3, class P4, class P5, class P6>
1225   I* Add(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6) {
1226     return AddInstructionTyped(New<I>(p1, p2, p3, p4, p5, p6));
1227   }
1228
1229   template<class I, class P1, class P2, class P3, class P4,
1230       class P5, class P6, class P7>
1231   HInstruction* NewUncasted(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7) {
1232     return I::New(isolate(), zone(), context(), p1, p2, p3, p4, p5, p6, p7);
1233   }
1234
1235   template<class I, class P1, class P2, class P3, class P4,
1236       class P5, class P6, class P7>
1237       I* New(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7) {
1238     return I::New(isolate(), zone(), context(), p1, p2, p3, p4, p5, p6, p7);
1239   }
1240
1241   template<class I, class P1, class P2, class P3,
1242            class P4, class P5, class P6, class P7>
1243   HInstruction* AddUncasted(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7) {
1244     return AddInstruction(NewUncasted<I>(p1, p2, p3, p4, p5, p6, p7));
1245   }
1246
1247   template<class I, class P1, class P2, class P3,
1248            class P4, class P5, class P6, class P7>
1249   I* Add(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7) {
1250     return AddInstructionTyped(New<I>(p1, p2, p3, p4, p5, p6, p7));
1251   }
1252
1253   template<class I, class P1, class P2, class P3, class P4,
1254       class P5, class P6, class P7, class P8>
1255   HInstruction* NewUncasted(P1 p1, P2 p2, P3 p3, P4 p4,
1256                             P5 p5, P6 p6, P7 p7, P8 p8) {
1257     return I::New(isolate(), zone(), context(), p1, p2, p3, p4, p5, p6, p7, p8);
1258   }
1259
1260   template<class I, class P1, class P2, class P3, class P4,
1261       class P5, class P6, class P7, class P8>
1262       I* New(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8) {
1263     return I::New(isolate(), zone(), context(), p1, p2, p3, p4, p5, p6, p7, p8);
1264   }
1265
1266   template<class I, class P1, class P2, class P3, class P4,
1267            class P5, class P6, class P7, class P8>
1268   HInstruction* AddUncasted(P1 p1, P2 p2, P3 p3, P4 p4,
1269                             P5 p5, P6 p6, P7 p7, P8 p8) {
1270     return AddInstruction(NewUncasted<I>(p1, p2, p3, p4, p5, p6, p7, p8));
1271   }
1272
1273   template<class I, class P1, class P2, class P3, class P4,
1274            class P5, class P6, class P7, class P8>
1275   I* Add(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8) {
1276     return AddInstructionTyped(New<I>(p1, p2, p3, p4, p5, p6, p7, p8));
1277   }
1278
1279   void AddSimulate(BailoutId id, RemovableSimulate removable = FIXED_SIMULATE);
1280
1281   // When initializing arrays, we'll unfold the loop if the number of elements
1282   // is known at compile time and is <= kElementLoopUnrollThreshold.
1283   static const int kElementLoopUnrollThreshold = 8;
1284
1285  protected:
1286   virtual bool BuildGraph() = 0;
1287
1288   HBasicBlock* CreateBasicBlock(HEnvironment* env);
1289   HBasicBlock* CreateLoopHeaderBlock();
1290
1291   template <class BitFieldClass>
1292   HValue* BuildDecodeField(HValue* encoded_field) {
1293     HValue* mask_value = Add<HConstant>(static_cast<int>(BitFieldClass::kMask));
1294     HValue* masked_field =
1295         AddUncasted<HBitwise>(Token::BIT_AND, encoded_field, mask_value);
1296     return AddUncasted<HShr>(masked_field,
1297         Add<HConstant>(static_cast<int>(BitFieldClass::kShift)));
1298   }
1299
1300   HValue* BuildGetElementsKind(HValue* object);
1301
1302   HValue* BuildCheckHeapObject(HValue* object);
1303   HValue* BuildCheckString(HValue* string);
1304   HValue* BuildWrapReceiver(HValue* object, HValue* function);
1305
1306   // Building common constructs
1307   HValue* BuildCheckForCapacityGrow(HValue* object,
1308                                     HValue* elements,
1309                                     ElementsKind kind,
1310                                     HValue* length,
1311                                     HValue* key,
1312                                     bool is_js_array,
1313                                     PropertyAccessType access_type);
1314
1315   HValue* BuildCheckAndGrowElementsCapacity(HValue* object, HValue* elements,
1316                                             ElementsKind kind, HValue* length,
1317                                             HValue* capacity, HValue* key);
1318
1319   HValue* BuildCopyElementsOnWrite(HValue* object,
1320                                    HValue* elements,
1321                                    ElementsKind kind,
1322                                    HValue* length);
1323
1324   void BuildTransitionElementsKind(HValue* object,
1325                                    HValue* map,
1326                                    ElementsKind from_kind,
1327                                    ElementsKind to_kind,
1328                                    bool is_jsarray);
1329
1330   HValue* BuildNumberToString(HValue* object, Type* type);
1331
1332   void BuildJSObjectCheck(HValue* receiver,
1333                           int bit_field_mask);
1334
1335   // Checks a key value that's being used for a keyed element access context. If
1336   // the key is a index, i.e. a smi or a number in a unique string with a cached
1337   // numeric value, the "true" of the continuation is joined. Otherwise,
1338   // if the key is a name or a unique string, the "false" of the continuation is
1339   // joined. Otherwise, a deoptimization is triggered. In both paths of the
1340   // continuation, the key is pushed on the top of the environment.
1341   void BuildKeyedIndexCheck(HValue* key,
1342                             HIfContinuation* join_continuation);
1343
1344   // Checks the properties of an object if they are in dictionary case, in which
1345   // case "true" of continuation is taken, otherwise the "false"
1346   void BuildTestForDictionaryProperties(HValue* object,
1347                                         HIfContinuation* continuation);
1348
1349   void BuildNonGlobalObjectCheck(HValue* receiver);
1350
1351   HValue* BuildKeyedLookupCacheHash(HValue* object,
1352                                     HValue* key);
1353
1354   HValue* BuildUncheckedDictionaryElementLoad(HValue* receiver,
1355                                               HValue* elements,
1356                                               HValue* key,
1357                                               HValue* hash);
1358
1359   HValue* BuildRegExpConstructResult(HValue* length,
1360                                      HValue* index,
1361                                      HValue* input);
1362
1363   // Allocates a new object according with the given allocation properties.
1364   HAllocate* BuildAllocate(HValue* object_size,
1365                            HType type,
1366                            InstanceType instance_type,
1367                            HAllocationMode allocation_mode);
1368   // Computes the sum of two string lengths, taking care of overflow handling.
1369   HValue* BuildAddStringLengths(HValue* left_length, HValue* right_length);
1370   // Creates a cons string using the two input strings.
1371   HValue* BuildCreateConsString(HValue* length,
1372                                 HValue* left,
1373                                 HValue* right,
1374                                 HAllocationMode allocation_mode);
1375   // Copies characters from one sequential string to another.
1376   void BuildCopySeqStringChars(HValue* src,
1377                                HValue* src_offset,
1378                                String::Encoding src_encoding,
1379                                HValue* dst,
1380                                HValue* dst_offset,
1381                                String::Encoding dst_encoding,
1382                                HValue* length);
1383
1384   // Align an object size to object alignment boundary
1385   HValue* BuildObjectSizeAlignment(HValue* unaligned_size, int header_size);
1386
1387   // Both operands are non-empty strings.
1388   HValue* BuildUncheckedStringAdd(HValue* left,
1389                                   HValue* right,
1390                                   HAllocationMode allocation_mode);
1391   // Add two strings using allocation mode, validating type feedback.
1392   HValue* BuildStringAdd(HValue* left,
1393                          HValue* right,
1394                          HAllocationMode allocation_mode);
1395
1396   HInstruction* BuildUncheckedMonomorphicElementAccess(
1397       HValue* checked_object,
1398       HValue* key,
1399       HValue* val,
1400       bool is_js_array,
1401       ElementsKind elements_kind,
1402       PropertyAccessType access_type,
1403       LoadKeyedHoleMode load_mode,
1404       KeyedAccessStoreMode store_mode);
1405
1406   HInstruction* AddElementAccess(
1407       HValue* elements,
1408       HValue* checked_key,
1409       HValue* val,
1410       HValue* dependency,
1411       ElementsKind elements_kind,
1412       PropertyAccessType access_type,
1413       LoadKeyedHoleMode load_mode = NEVER_RETURN_HOLE);
1414
1415   HInstruction* AddLoadStringInstanceType(HValue* string);
1416   HInstruction* AddLoadStringLength(HValue* string);
1417   HInstruction* BuildLoadStringLength(HValue* string);
1418   HStoreNamedField* AddStoreMapConstant(HValue* object, Handle<Map> map) {
1419     return Add<HStoreNamedField>(object, HObjectAccess::ForMap(),
1420                                  Add<HConstant>(map));
1421   }
1422   HLoadNamedField* AddLoadMap(HValue* object,
1423                               HValue* dependency = NULL);
1424   HLoadNamedField* AddLoadElements(HValue* object,
1425                                    HValue* dependency = NULL);
1426
1427   bool MatchRotateRight(HValue* left,
1428                         HValue* right,
1429                         HValue** operand,
1430                         HValue** shift_amount);
1431
1432   HValue* BuildBinaryOperation(Token::Value op,
1433                                HValue* left,
1434                                HValue* right,
1435                                Type* left_type,
1436                                Type* right_type,
1437                                Type* result_type,
1438                                Maybe<int> fixed_right_arg,
1439                                HAllocationMode allocation_mode,
1440                                LanguageMode language_mode);
1441
1442   HLoadNamedField* AddLoadFixedArrayLength(HValue *object,
1443                                            HValue *dependency = NULL);
1444
1445   HLoadNamedField* AddLoadArrayLength(HValue *object,
1446                                       ElementsKind kind,
1447                                       HValue *dependency = NULL);
1448
1449   HValue* AddLoadJSBuiltin(Builtins::JavaScript builtin);
1450
1451   HValue* EnforceNumberType(HValue* number, Type* expected);
1452   HValue* TruncateToNumber(HValue* value, Type** expected);
1453
1454   void FinishExitWithHardDeoptimization(Deoptimizer::DeoptReason reason);
1455
1456   void AddIncrementCounter(StatsCounter* counter);
1457
1458   class IfBuilder final {
1459    public:
1460     // If using this constructor, Initialize() must be called explicitly!
1461     IfBuilder();
1462
1463     explicit IfBuilder(HGraphBuilder* builder);
1464     IfBuilder(HGraphBuilder* builder,
1465               HIfContinuation* continuation);
1466
1467     ~IfBuilder() {
1468       if (!finished_) End();
1469     }
1470
1471     void Initialize(HGraphBuilder* builder);
1472
1473     template<class Condition>
1474     Condition* If(HValue *p) {
1475       Condition* compare = builder()->New<Condition>(p);
1476       AddCompare(compare);
1477       return compare;
1478     }
1479
1480     template<class Condition, class P2>
1481     Condition* If(HValue* p1, P2 p2) {
1482       Condition* compare = builder()->New<Condition>(p1, p2);
1483       AddCompare(compare);
1484       return compare;
1485     }
1486
1487     template<class Condition, class P2, class P3>
1488     Condition* If(HValue* p1, P2 p2, P3 p3) {
1489       Condition* compare = builder()->New<Condition>(p1, p2, p3);
1490       AddCompare(compare);
1491       return compare;
1492     }
1493
1494     template<class Condition>
1495     Condition* IfNot(HValue* p) {
1496       Condition* compare = If<Condition>(p);
1497       compare->Not();
1498       return compare;
1499     }
1500
1501     template<class Condition, class P2>
1502     Condition* IfNot(HValue* p1, P2 p2) {
1503       Condition* compare = If<Condition>(p1, p2);
1504       compare->Not();
1505       return compare;
1506     }
1507
1508     template<class Condition, class P2, class P3>
1509     Condition* IfNot(HValue* p1, P2 p2, P3 p3) {
1510       Condition* compare = If<Condition>(p1, p2, p3);
1511       compare->Not();
1512       return compare;
1513     }
1514
1515     template<class Condition>
1516     Condition* OrIf(HValue *p) {
1517       Or();
1518       return If<Condition>(p);
1519     }
1520
1521     template<class Condition, class P2>
1522     Condition* OrIf(HValue* p1, P2 p2) {
1523       Or();
1524       return If<Condition>(p1, p2);
1525     }
1526
1527     template<class Condition, class P2, class P3>
1528     Condition* OrIf(HValue* p1, P2 p2, P3 p3) {
1529       Or();
1530       return If<Condition>(p1, p2, p3);
1531     }
1532
1533     template<class Condition>
1534     Condition* AndIf(HValue *p) {
1535       And();
1536       return If<Condition>(p);
1537     }
1538
1539     template<class Condition, class P2>
1540     Condition* AndIf(HValue* p1, P2 p2) {
1541       And();
1542       return If<Condition>(p1, p2);
1543     }
1544
1545     template<class Condition, class P2, class P3>
1546     Condition* AndIf(HValue* p1, P2 p2, P3 p3) {
1547       And();
1548       return If<Condition>(p1, p2, p3);
1549     }
1550
1551     void Or();
1552     void And();
1553
1554     // Captures the current state of this IfBuilder in the specified
1555     // continuation and ends this IfBuilder.
1556     void CaptureContinuation(HIfContinuation* continuation);
1557
1558     // Joins the specified continuation from this IfBuilder and ends this
1559     // IfBuilder. This appends a Goto instruction from the true branch of
1560     // this IfBuilder to the true branch of the continuation unless the
1561     // true branch of this IfBuilder is already finished. And vice versa
1562     // for the false branch.
1563     //
1564     // The basic idea is as follows: You have several nested IfBuilder's
1565     // that you want to join based on two possible outcomes (i.e. success
1566     // and failure, or whatever). You can do this easily using this method
1567     // now, for example:
1568     //
1569     //   HIfContinuation cont(graph()->CreateBasicBlock(),
1570     //                        graph()->CreateBasicBlock());
1571     //   ...
1572     //     IfBuilder if_whatever(this);
1573     //     if_whatever.If<Condition>(arg);
1574     //     if_whatever.Then();
1575     //     ...
1576     //     if_whatever.Else();
1577     //     ...
1578     //     if_whatever.JoinContinuation(&cont);
1579     //   ...
1580     //     IfBuilder if_something(this);
1581     //     if_something.If<Condition>(arg1, arg2);
1582     //     if_something.Then();
1583     //     ...
1584     //     if_something.Else();
1585     //     ...
1586     //     if_something.JoinContinuation(&cont);
1587     //   ...
1588     //   IfBuilder if_finally(this, &cont);
1589     //   if_finally.Then();
1590     //   // continues after then code of if_whatever or if_something.
1591     //   ...
1592     //   if_finally.Else();
1593     //   // continues after else code of if_whatever or if_something.
1594     //   ...
1595     //   if_finally.End();
1596     void JoinContinuation(HIfContinuation* continuation);
1597
1598     void Then();
1599     void Else();
1600     void End();
1601
1602     void Deopt(Deoptimizer::DeoptReason reason);
1603     void ThenDeopt(Deoptimizer::DeoptReason reason) {
1604       Then();
1605       Deopt(reason);
1606     }
1607     void ElseDeopt(Deoptimizer::DeoptReason reason) {
1608       Else();
1609       Deopt(reason);
1610     }
1611
1612     void Return(HValue* value);
1613
1614    private:
1615     void InitializeDontCreateBlocks(HGraphBuilder* builder);
1616
1617     HControlInstruction* AddCompare(HControlInstruction* compare);
1618
1619     HGraphBuilder* builder() const {
1620       DCHECK(builder_ != NULL);  // Have you called "Initialize"?
1621       return builder_;
1622     }
1623
1624     void AddMergeAtJoinBlock(bool deopt);
1625
1626     void Finish();
1627     void Finish(HBasicBlock** then_continuation,
1628                 HBasicBlock** else_continuation);
1629
1630     class MergeAtJoinBlock : public ZoneObject {
1631      public:
1632       MergeAtJoinBlock(HBasicBlock* block,
1633                        bool deopt,
1634                        MergeAtJoinBlock* next)
1635         : block_(block),
1636           deopt_(deopt),
1637           next_(next) {}
1638       HBasicBlock* block_;
1639       bool deopt_;
1640       MergeAtJoinBlock* next_;
1641     };
1642
1643     HGraphBuilder* builder_;
1644     bool finished_ : 1;
1645     bool did_then_ : 1;
1646     bool did_else_ : 1;
1647     bool did_else_if_ : 1;
1648     bool did_and_ : 1;
1649     bool did_or_ : 1;
1650     bool captured_ : 1;
1651     bool needs_compare_ : 1;
1652     bool pending_merge_block_ : 1;
1653     HBasicBlock* first_true_block_;
1654     HBasicBlock* first_false_block_;
1655     HBasicBlock* split_edge_merge_block_;
1656     MergeAtJoinBlock* merge_at_join_blocks_;
1657     int normal_merge_at_join_block_count_;
1658     int deopt_merge_at_join_block_count_;
1659   };
1660
1661   class LoopBuilder final {
1662    public:
1663     enum Direction {
1664       kPreIncrement,
1665       kPostIncrement,
1666       kPreDecrement,
1667       kPostDecrement,
1668       kWhileTrue
1669     };
1670
1671     explicit LoopBuilder(HGraphBuilder* builder);  // while (true) {...}
1672     LoopBuilder(HGraphBuilder* builder,
1673                 HValue* context,
1674                 Direction direction);
1675     LoopBuilder(HGraphBuilder* builder,
1676                 HValue* context,
1677                 Direction direction,
1678                 HValue* increment_amount);
1679
1680     ~LoopBuilder() {
1681       DCHECK(finished_);
1682     }
1683
1684     HValue* BeginBody(
1685         HValue* initial,
1686         HValue* terminating,
1687         Token::Value token);
1688
1689     void BeginBody(int drop_count);
1690
1691     void Break();
1692
1693     void EndBody();
1694
1695    private:
1696     void Initialize(HGraphBuilder* builder, HValue* context,
1697                     Direction direction, HValue* increment_amount);
1698     Zone* zone() { return builder_->zone(); }
1699
1700     HGraphBuilder* builder_;
1701     HValue* context_;
1702     HValue* increment_amount_;
1703     HInstruction* increment_;
1704     HPhi* phi_;
1705     HBasicBlock* header_block_;
1706     HBasicBlock* body_block_;
1707     HBasicBlock* exit_block_;
1708     HBasicBlock* exit_trampoline_block_;
1709     Direction direction_;
1710     bool finished_;
1711   };
1712
1713   HValue* BuildNewElementsCapacity(HValue* old_capacity);
1714
1715   class JSArrayBuilder final {
1716    public:
1717     JSArrayBuilder(HGraphBuilder* builder,
1718                    ElementsKind kind,
1719                    HValue* allocation_site_payload,
1720                    HValue* constructor_function,
1721                    AllocationSiteOverrideMode override_mode);
1722
1723     JSArrayBuilder(HGraphBuilder* builder,
1724                    ElementsKind kind,
1725                    HValue* constructor_function = NULL);
1726
1727     enum FillMode {
1728       DONT_FILL_WITH_HOLE,
1729       FILL_WITH_HOLE
1730     };
1731
1732     ElementsKind kind() { return kind_; }
1733     HAllocate* elements_location() { return elements_location_; }
1734
1735     HAllocate* AllocateEmptyArray();
1736     HAllocate* AllocateArray(HValue* capacity,
1737                              HValue* length_field,
1738                              FillMode fill_mode = FILL_WITH_HOLE);
1739     // Use these allocators when capacity could be unknown at compile time
1740     // but its limit is known. For constant |capacity| the value of
1741     // |capacity_upper_bound| is ignored and the actual |capacity|
1742     // value is used as an upper bound.
1743     HAllocate* AllocateArray(HValue* capacity,
1744                              int capacity_upper_bound,
1745                              HValue* length_field,
1746                              FillMode fill_mode = FILL_WITH_HOLE);
1747     HAllocate* AllocateArray(HValue* capacity,
1748                              HConstant* capacity_upper_bound,
1749                              HValue* length_field,
1750                              FillMode fill_mode = FILL_WITH_HOLE);
1751     HValue* GetElementsLocation() { return elements_location_; }
1752     HValue* EmitMapCode();
1753
1754    private:
1755     Zone* zone() const { return builder_->zone(); }
1756     int elements_size() const {
1757       return IsFastDoubleElementsKind(kind_) ? kDoubleSize : kPointerSize;
1758     }
1759     HGraphBuilder* builder() { return builder_; }
1760     HGraph* graph() { return builder_->graph(); }
1761     int initial_capacity() {
1762       STATIC_ASSERT(JSArray::kPreallocatedArrayElements > 0);
1763       return JSArray::kPreallocatedArrayElements;
1764     }
1765
1766     HValue* EmitInternalMapCode();
1767
1768     HGraphBuilder* builder_;
1769     ElementsKind kind_;
1770     AllocationSiteMode mode_;
1771     HValue* allocation_site_payload_;
1772     HValue* constructor_function_;
1773     HAllocate* elements_location_;
1774   };
1775
1776   HValue* BuildAllocateArrayFromLength(JSArrayBuilder* array_builder,
1777                                        HValue* length_argument);
1778   HValue* BuildCalculateElementsSize(ElementsKind kind,
1779                                      HValue* capacity);
1780   HAllocate* AllocateJSArrayObject(AllocationSiteMode mode);
1781   HConstant* EstablishElementsAllocationSize(ElementsKind kind, int capacity);
1782
1783   HAllocate* BuildAllocateElements(ElementsKind kind, HValue* size_in_bytes);
1784
1785   void BuildInitializeElementsHeader(HValue* elements,
1786                                      ElementsKind kind,
1787                                      HValue* capacity);
1788
1789   // Build allocation and header initialization code for respective successor
1790   // of FixedArrayBase.
1791   HValue* BuildAllocateAndInitializeArray(ElementsKind kind, HValue* capacity);
1792
1793   // |array| must have been allocated with enough room for
1794   // 1) the JSArray and 2) an AllocationMemento if mode requires it.
1795   // If the |elements| value provided is NULL then the array elements storage
1796   // is initialized with empty array.
1797   void BuildJSArrayHeader(HValue* array,
1798                           HValue* array_map,
1799                           HValue* elements,
1800                           AllocationSiteMode mode,
1801                           ElementsKind elements_kind,
1802                           HValue* allocation_site_payload,
1803                           HValue* length_field);
1804
1805   HValue* BuildGrowElementsCapacity(HValue* object,
1806                                     HValue* elements,
1807                                     ElementsKind kind,
1808                                     ElementsKind new_kind,
1809                                     HValue* length,
1810                                     HValue* new_capacity);
1811
1812   void BuildFillElementsWithValue(HValue* elements,
1813                                   ElementsKind elements_kind,
1814                                   HValue* from,
1815                                   HValue* to,
1816                                   HValue* value);
1817
1818   void BuildFillElementsWithHole(HValue* elements,
1819                                  ElementsKind elements_kind,
1820                                  HValue* from,
1821                                  HValue* to);
1822
1823   void BuildCopyProperties(HValue* from_properties, HValue* to_properties,
1824                            HValue* length, HValue* capacity);
1825
1826   void BuildCopyElements(HValue* from_elements,
1827                          ElementsKind from_elements_kind,
1828                          HValue* to_elements,
1829                          ElementsKind to_elements_kind,
1830                          HValue* length,
1831                          HValue* capacity);
1832
1833   HValue* BuildCloneShallowArrayCow(HValue* boilerplate,
1834                                     HValue* allocation_site,
1835                                     AllocationSiteMode mode,
1836                                     ElementsKind kind);
1837
1838   HValue* BuildCloneShallowArrayEmpty(HValue* boilerplate,
1839                                       HValue* allocation_site,
1840                                       AllocationSiteMode mode);
1841
1842   HValue* BuildCloneShallowArrayNonEmpty(HValue* boilerplate,
1843                                          HValue* allocation_site,
1844                                          AllocationSiteMode mode,
1845                                          ElementsKind kind);
1846
1847   HValue* BuildElementIndexHash(HValue* index);
1848
1849   enum MapEmbedding { kEmbedMapsDirectly, kEmbedMapsViaWeakCells };
1850
1851   void BuildCompareNil(HValue* value, Type* type, HIfContinuation* continuation,
1852                        MapEmbedding map_embedding = kEmbedMapsDirectly);
1853
1854   void BuildCreateAllocationMemento(HValue* previous_object,
1855                                     HValue* previous_object_size,
1856                                     HValue* payload);
1857
1858   HInstruction* BuildConstantMapCheck(Handle<JSObject> constant);
1859   HInstruction* BuildCheckPrototypeMaps(Handle<JSObject> prototype,
1860                                         Handle<JSObject> holder);
1861
1862   HInstruction* BuildGetNativeContext(HValue* closure);
1863   HInstruction* BuildGetNativeContext();
1864   HInstruction* BuildGetScriptContext(int context_index);
1865   HInstruction* BuildGetArrayFunction();
1866   HValue* BuildArrayBufferViewFieldAccessor(HValue* object,
1867                                             HValue* checked_object,
1868                                             FieldIndex index);
1869
1870
1871  protected:
1872   void SetSourcePosition(int position) {
1873     if (position != RelocInfo::kNoPosition) {
1874       position_.set_position(position - start_position_);
1875     }
1876     // Otherwise position remains unknown.
1877   }
1878
1879   void EnterInlinedSource(int start_position, int id) {
1880     if (top_info()->is_tracking_positions()) {
1881       start_position_ = start_position;
1882       position_.set_inlining_id(id);
1883     }
1884   }
1885
1886   // Convert the given absolute offset from the start of the script to
1887   // the SourcePosition assuming that this position corresponds to the
1888   // same function as current position_.
1889   SourcePosition ScriptPositionToSourcePosition(int position) {
1890     SourcePosition pos = position_;
1891     pos.set_position(position - start_position_);
1892     return pos;
1893   }
1894
1895   SourcePosition source_position() { return position_; }
1896   void set_source_position(SourcePosition position) { position_ = position; }
1897
1898   HValue* BuildAllocateEmptyArrayBuffer(HValue* byte_length);
1899   template <typename ViewClass>
1900   void BuildArrayBufferViewInitialization(HValue* obj,
1901                                           HValue* buffer,
1902                                           HValue* byte_offset,
1903                                           HValue* byte_length);
1904
1905  private:
1906   HGraphBuilder();
1907
1908   template <class I>
1909   I* AddInstructionTyped(I* instr) {
1910     return I::cast(AddInstruction(instr));
1911   }
1912
1913   CompilationInfo* info_;
1914   HGraph* graph_;
1915   HBasicBlock* current_block_;
1916   Scope* scope_;
1917   SourcePosition position_;
1918   int start_position_;
1919 };
1920
1921
1922 template <>
1923 inline HDeoptimize* HGraphBuilder::Add<HDeoptimize>(
1924     Deoptimizer::DeoptReason reason, Deoptimizer::BailoutType type) {
1925   if (type == Deoptimizer::SOFT) {
1926     isolate()->counters()->soft_deopts_requested()->Increment();
1927     if (FLAG_always_opt) return NULL;
1928   }
1929   if (current_block()->IsDeoptimizing()) return NULL;
1930   HBasicBlock* after_deopt_block = CreateBasicBlock(
1931       current_block()->last_environment());
1932   HDeoptimize* instr = New<HDeoptimize>(reason, type, after_deopt_block);
1933   if (type == Deoptimizer::SOFT) {
1934     isolate()->counters()->soft_deopts_inserted()->Increment();
1935   }
1936   FinishCurrentBlock(instr);
1937   set_current_block(after_deopt_block);
1938   return instr;
1939 }
1940
1941
1942 template <>
1943 inline HInstruction* HGraphBuilder::AddUncasted<HDeoptimize>(
1944     Deoptimizer::DeoptReason reason, Deoptimizer::BailoutType type) {
1945   return Add<HDeoptimize>(reason, type);
1946 }
1947
1948
1949 template<>
1950 inline HSimulate* HGraphBuilder::Add<HSimulate>(
1951     BailoutId id,
1952     RemovableSimulate removable) {
1953   HSimulate* instr = current_block()->CreateSimulate(id, removable);
1954   AddInstruction(instr);
1955   return instr;
1956 }
1957
1958
1959 template<>
1960 inline HSimulate* HGraphBuilder::Add<HSimulate>(
1961     BailoutId id) {
1962   return Add<HSimulate>(id, FIXED_SIMULATE);
1963 }
1964
1965
1966 template<>
1967 inline HInstruction* HGraphBuilder::AddUncasted<HSimulate>(BailoutId id) {
1968   return Add<HSimulate>(id, FIXED_SIMULATE);
1969 }
1970
1971
1972 template<>
1973 inline HReturn* HGraphBuilder::Add<HReturn>(HValue* value) {
1974   int num_parameters = graph()->info()->num_parameters();
1975   HValue* params = AddUncasted<HConstant>(num_parameters);
1976   HReturn* return_instruction = New<HReturn>(value, params);
1977   FinishExitCurrentBlock(return_instruction);
1978   return return_instruction;
1979 }
1980
1981
1982 template<>
1983 inline HReturn* HGraphBuilder::Add<HReturn>(HConstant* value) {
1984   return Add<HReturn>(static_cast<HValue*>(value));
1985 }
1986
1987 template<>
1988 inline HInstruction* HGraphBuilder::AddUncasted<HReturn>(HValue* value) {
1989   return Add<HReturn>(value);
1990 }
1991
1992
1993 template<>
1994 inline HInstruction* HGraphBuilder::AddUncasted<HReturn>(HConstant* value) {
1995   return Add<HReturn>(value);
1996 }
1997
1998
1999 template<>
2000 inline HCallRuntime* HGraphBuilder::Add<HCallRuntime>(
2001     Handle<String> name,
2002     const Runtime::Function* c_function,
2003     int argument_count) {
2004   HCallRuntime* instr = New<HCallRuntime>(name, c_function, argument_count);
2005   if (graph()->info()->IsStub()) {
2006     // When compiling code stubs, we don't want to save all double registers
2007     // upon entry to the stub, but instead have the call runtime instruction
2008     // save the double registers only on-demand (in the fallback case).
2009     instr->set_save_doubles(kSaveFPRegs);
2010   }
2011   AddInstruction(instr);
2012   return instr;
2013 }
2014
2015
2016 template<>
2017 inline HInstruction* HGraphBuilder::AddUncasted<HCallRuntime>(
2018     Handle<String> name,
2019     const Runtime::Function* c_function,
2020     int argument_count) {
2021   return Add<HCallRuntime>(name, c_function, argument_count);
2022 }
2023
2024
2025 template<>
2026 inline HContext* HGraphBuilder::New<HContext>() {
2027   return HContext::New(zone());
2028 }
2029
2030
2031 template<>
2032 inline HInstruction* HGraphBuilder::NewUncasted<HContext>() {
2033   return New<HContext>();
2034 }
2035
2036 class HOptimizedGraphBuilder : public HGraphBuilder, public AstVisitor {
2037  public:
2038   // A class encapsulating (lazily-allocated) break and continue blocks for
2039   // a breakable statement.  Separated from BreakAndContinueScope so that it
2040   // can have a separate lifetime.
2041   class BreakAndContinueInfo final BASE_EMBEDDED {
2042    public:
2043     explicit BreakAndContinueInfo(BreakableStatement* target,
2044                                   Scope* scope,
2045                                   int drop_extra = 0)
2046         : target_(target),
2047           break_block_(NULL),
2048           continue_block_(NULL),
2049           scope_(scope),
2050           drop_extra_(drop_extra) {
2051     }
2052
2053     BreakableStatement* target() { return target_; }
2054     HBasicBlock* break_block() { return break_block_; }
2055     void set_break_block(HBasicBlock* block) { break_block_ = block; }
2056     HBasicBlock* continue_block() { return continue_block_; }
2057     void set_continue_block(HBasicBlock* block) { continue_block_ = block; }
2058     Scope* scope() { return scope_; }
2059     int drop_extra() { return drop_extra_; }
2060
2061    private:
2062     BreakableStatement* target_;
2063     HBasicBlock* break_block_;
2064     HBasicBlock* continue_block_;
2065     Scope* scope_;
2066     int drop_extra_;
2067   };
2068
2069   // A helper class to maintain a stack of current BreakAndContinueInfo
2070   // structures mirroring BreakableStatement nesting.
2071   class BreakAndContinueScope final BASE_EMBEDDED {
2072    public:
2073     BreakAndContinueScope(BreakAndContinueInfo* info,
2074                           HOptimizedGraphBuilder* owner)
2075         : info_(info), owner_(owner), next_(owner->break_scope()) {
2076       owner->set_break_scope(this);
2077     }
2078
2079     ~BreakAndContinueScope() { owner_->set_break_scope(next_); }
2080
2081     BreakAndContinueInfo* info() { return info_; }
2082     HOptimizedGraphBuilder* owner() { return owner_; }
2083     BreakAndContinueScope* next() { return next_; }
2084
2085     // Search the break stack for a break or continue target.
2086     enum BreakType { BREAK, CONTINUE };
2087     HBasicBlock* Get(BreakableStatement* stmt, BreakType type,
2088                      Scope** scope, int* drop_extra);
2089
2090    private:
2091     BreakAndContinueInfo* info_;
2092     HOptimizedGraphBuilder* owner_;
2093     BreakAndContinueScope* next_;
2094   };
2095
2096   explicit HOptimizedGraphBuilder(CompilationInfo* info);
2097
2098   bool BuildGraph() override;
2099
2100   // Simple accessors.
2101   BreakAndContinueScope* break_scope() const { return break_scope_; }
2102   void set_break_scope(BreakAndContinueScope* head) { break_scope_ = head; }
2103
2104   HValue* context() override { return environment()->context(); }
2105
2106   HOsrBuilder* osr() const { return osr_; }
2107
2108   void Bailout(BailoutReason reason);
2109
2110   HBasicBlock* CreateJoin(HBasicBlock* first,
2111                           HBasicBlock* second,
2112                           BailoutId join_id);
2113
2114   FunctionState* function_state() const { return function_state_; }
2115
2116   void VisitDeclarations(ZoneList<Declaration*>* declarations) override;
2117
2118   void* operator new(size_t size, Zone* zone) { return zone->New(size); }
2119   void operator delete(void* pointer, Zone* zone) { }
2120   void operator delete(void* pointer) { }
2121
2122   DEFINE_AST_VISITOR_SUBCLASS_MEMBERS();
2123
2124  protected:
2125   // Forward declarations for inner scope classes.
2126   class SubgraphScope;
2127
2128   static const int kMaxCallPolymorphism = 4;
2129   static const int kMaxLoadPolymorphism = 4;
2130   static const int kMaxStorePolymorphism = 4;
2131
2132   // Even in the 'unlimited' case we have to have some limit in order not to
2133   // overflow the stack.
2134   static const int kUnlimitedMaxInlinedSourceSize = 100000;
2135   static const int kUnlimitedMaxInlinedNodes = 10000;
2136   static const int kUnlimitedMaxInlinedNodesCumulative = 10000;
2137
2138   // Maximum depth and total number of elements and properties for literal
2139   // graphs to be considered for fast deep-copying.
2140   static const int kMaxFastLiteralDepth = 3;
2141   static const int kMaxFastLiteralProperties = 8;
2142
2143   // Simple accessors.
2144   void set_function_state(FunctionState* state) { function_state_ = state; }
2145
2146   AstContext* ast_context() const { return ast_context_; }
2147   void set_ast_context(AstContext* context) { ast_context_ = context; }
2148
2149   // Accessors forwarded to the function state.
2150   CompilationInfo* current_info() const {
2151     return function_state()->compilation_info();
2152   }
2153   AstContext* call_context() const {
2154     return function_state()->call_context();
2155   }
2156   HBasicBlock* function_return() const {
2157     return function_state()->function_return();
2158   }
2159   TestContext* inlined_test_context() const {
2160     return function_state()->test_context();
2161   }
2162   Handle<SharedFunctionInfo> current_shared_info() const {
2163     return current_info()->shared_info();
2164   }
2165   TypeFeedbackVector* current_feedback_vector() const {
2166     return current_shared_info()->feedback_vector();
2167   }
2168   void ClearInlinedTestContext() {
2169     function_state()->ClearInlinedTestContext();
2170   }
2171   LanguageMode function_language_mode() {
2172     return function_state()->compilation_info()->language_mode();
2173   }
2174
2175 #define FOR_EACH_HYDROGEN_INTRINSIC(F) \
2176   F(IsSmi)                             \
2177   F(IsArray)                           \
2178   F(IsRegExp)                          \
2179   F(IsJSProxy)                         \
2180   F(IsConstructCall)                   \
2181   F(CallFunction)                      \
2182   F(ArgumentsLength)                   \
2183   F(Arguments)                         \
2184   F(ValueOf)                           \
2185   F(SetValueOf)                        \
2186   F(ThrowIfNotADate)                   \
2187   F(DateField)                         \
2188   F(StringCharFromCode)                \
2189   F(StringCharAt)                      \
2190   F(OneByteSeqStringSetChar)           \
2191   F(TwoByteSeqStringSetChar)           \
2192   F(ObjectEquals)                      \
2193   F(IsObject)                          \
2194   F(IsFunction)                        \
2195   F(IsUndetectableObject)              \
2196   F(IsSpecObject)                      \
2197   F(MathPow)                           \
2198   F(IsMinusZero)                       \
2199   F(HasCachedArrayIndex)               \
2200   F(GetCachedArrayIndex)               \
2201   F(FastOneByteArrayJoin)              \
2202   F(DebugBreakInOptimizedCode)         \
2203   F(StringCharCodeAt)                  \
2204   F(StringAdd)                         \
2205   F(SubString)                         \
2206   F(StringCompare)                     \
2207   F(RegExpExec)                        \
2208   F(RegExpConstructResult)             \
2209   F(GetFromCache)                      \
2210   F(NumberToString)                    \
2211   F(DebugIsActive)                     \
2212   F(Likely)                            \
2213   F(Unlikely)                          \
2214   /* Typed Arrays */                   \
2215   F(TypedArrayInitialize)              \
2216   F(DataViewInitialize)                \
2217   F(MaxSmi)                            \
2218   F(TypedArrayMaxSizeInHeap)           \
2219   F(ArrayBufferViewGetByteLength)      \
2220   F(ArrayBufferViewGetByteOffset)      \
2221   F(TypedArrayGetLength)               \
2222   /* ArrayBuffer */                    \
2223   F(ArrayBufferGetByteLength)          \
2224   /* Maths */                          \
2225   F(ConstructDouble)                   \
2226   F(DoubleHi)                          \
2227   F(DoubleLo)                          \
2228   F(MathClz32)                         \
2229   F(MathFloor)                         \
2230   F(MathSqrt)                          \
2231   F(MathLogRT)                         \
2232   /* ES6 Collections */                \
2233   F(MapClear)                          \
2234   F(MapInitialize)                     \
2235   F(SetClear)                          \
2236   F(SetInitialize)                     \
2237   F(FixedArrayGet)                     \
2238   F(FixedArraySet)                     \
2239   F(JSCollectionGetTable)              \
2240   F(StringGetRawHashField)             \
2241   F(TheHole)                           \
2242   /* Arrays */                         \
2243   F(HasFastPackedElements)             \
2244   F(GetPrototype)                      \
2245   /* Strings */                        \
2246   F(StringGetLength)                   \
2247   /* JSValue */                        \
2248   F(JSValueGetValue)
2249
2250 #define GENERATOR_DECLARATION(Name) void Generate##Name(CallRuntime* call);
2251   FOR_EACH_HYDROGEN_INTRINSIC(GENERATOR_DECLARATION)
2252 #undef GENERATOR_DECLARATION
2253
2254   void VisitDelete(UnaryOperation* expr);
2255   void VisitVoid(UnaryOperation* expr);
2256   void VisitTypeof(UnaryOperation* expr);
2257   void VisitNot(UnaryOperation* expr);
2258
2259   void VisitComma(BinaryOperation* expr);
2260   void VisitLogicalExpression(BinaryOperation* expr);
2261   void VisitArithmeticExpression(BinaryOperation* expr);
2262
2263   void VisitLoopBody(IterationStatement* stmt,
2264                      HBasicBlock* loop_entry);
2265
2266   void BuildForInBody(ForInStatement* stmt, Variable* each_var,
2267                       HValue* enumerable);
2268
2269   // Create a back edge in the flow graph.  body_exit is the predecessor
2270   // block and loop_entry is the successor block.  loop_successor is the
2271   // block where control flow exits the loop normally (e.g., via failure of
2272   // the condition) and break_block is the block where control flow breaks
2273   // from the loop.  All blocks except loop_entry can be NULL.  The return
2274   // value is the new successor block which is the join of loop_successor
2275   // and break_block, or NULL.
2276   HBasicBlock* CreateLoop(IterationStatement* statement,
2277                           HBasicBlock* loop_entry,
2278                           HBasicBlock* body_exit,
2279                           HBasicBlock* loop_successor,
2280                           HBasicBlock* break_block);
2281
2282   // Build a loop entry
2283   HBasicBlock* BuildLoopEntry();
2284
2285   // Builds a loop entry respectful of OSR requirements
2286   HBasicBlock* BuildLoopEntry(IterationStatement* statement);
2287
2288   HBasicBlock* JoinContinue(IterationStatement* statement,
2289                             HBasicBlock* exit_block,
2290                             HBasicBlock* continue_block);
2291
2292   HValue* Top() const { return environment()->Top(); }
2293   void Drop(int n) { environment()->Drop(n); }
2294   void Bind(Variable* var, HValue* value) { environment()->Bind(var, value); }
2295   bool IsEligibleForEnvironmentLivenessAnalysis(Variable* var,
2296                                                 int index,
2297                                                 HValue* value,
2298                                                 HEnvironment* env) {
2299     if (!FLAG_analyze_environment_liveness) return false;
2300     // |this| and |arguments| are always live; zapping parameters isn't
2301     // safe because function.arguments can inspect them at any time.
2302     return !var->is_this() &&
2303            !var->is_arguments() &&
2304            !value->IsArgumentsObject() &&
2305            env->is_local_index(index);
2306   }
2307   void BindIfLive(Variable* var, HValue* value) {
2308     HEnvironment* env = environment();
2309     int index = env->IndexFor(var);
2310     env->Bind(index, value);
2311     if (IsEligibleForEnvironmentLivenessAnalysis(var, index, value, env)) {
2312       HEnvironmentMarker* bind =
2313           Add<HEnvironmentMarker>(HEnvironmentMarker::BIND, index);
2314       USE(bind);
2315 #ifdef DEBUG
2316       bind->set_closure(env->closure());
2317 #endif
2318     }
2319   }
2320   HValue* LookupAndMakeLive(Variable* var) {
2321     HEnvironment* env = environment();
2322     int index = env->IndexFor(var);
2323     HValue* value = env->Lookup(index);
2324     if (IsEligibleForEnvironmentLivenessAnalysis(var, index, value, env)) {
2325       HEnvironmentMarker* lookup =
2326           Add<HEnvironmentMarker>(HEnvironmentMarker::LOOKUP, index);
2327       USE(lookup);
2328 #ifdef DEBUG
2329       lookup->set_closure(env->closure());
2330 #endif
2331     }
2332     return value;
2333   }
2334
2335   // The value of the arguments object is allowed in some but not most value
2336   // contexts.  (It's allowed in all effect contexts and disallowed in all
2337   // test contexts.)
2338   void VisitForValue(Expression* expr,
2339                      ArgumentsAllowedFlag flag = ARGUMENTS_NOT_ALLOWED);
2340   void VisitForTypeOf(Expression* expr);
2341   void VisitForEffect(Expression* expr);
2342   void VisitForControl(Expression* expr,
2343                        HBasicBlock* true_block,
2344                        HBasicBlock* false_block);
2345
2346   // Visit a list of expressions from left to right, each in a value context.
2347   void VisitExpressions(ZoneList<Expression*>* exprs) override;
2348   void VisitExpressions(ZoneList<Expression*>* exprs,
2349                         ArgumentsAllowedFlag flag);
2350
2351   // Remove the arguments from the bailout environment and emit instructions
2352   // to push them as outgoing parameters.
2353   template <class Instruction> HInstruction* PreProcessCall(Instruction* call);
2354   void PushArgumentsFromEnvironment(int count);
2355
2356   void SetUpScope(Scope* scope);
2357   void VisitStatements(ZoneList<Statement*>* statements) override;
2358
2359 #define DECLARE_VISIT(type) virtual void Visit##type(type* node) override;
2360   AST_NODE_LIST(DECLARE_VISIT)
2361 #undef DECLARE_VISIT
2362
2363  private:
2364   // Helpers for flow graph construction.
2365   enum GlobalPropertyAccess {
2366     kUseCell,
2367     kUseGeneric
2368   };
2369   GlobalPropertyAccess LookupGlobalProperty(Variable* var, LookupIterator* it,
2370                                             PropertyAccessType access_type);
2371
2372   void EnsureArgumentsArePushedForAccess();
2373   bool TryArgumentsAccess(Property* expr);
2374
2375   // Shared code for .call and .apply optimizations.
2376   void HandleIndirectCall(Call* expr, HValue* function, int arguments_count);
2377   // Try to optimize indirect calls such as fun.apply(receiver, arguments)
2378   // or fun.call(...).
2379   bool TryIndirectCall(Call* expr);
2380   void BuildFunctionApply(Call* expr);
2381   void BuildFunctionCall(Call* expr);
2382
2383   bool TryHandleArrayCall(Call* expr, HValue* function);
2384   bool TryHandleArrayCallNew(CallNew* expr, HValue* function);
2385   void BuildArrayCall(Expression* expr, int arguments_count, HValue* function,
2386                       Handle<AllocationSite> cell);
2387
2388   enum ArrayIndexOfMode { kFirstIndexOf, kLastIndexOf };
2389   HValue* BuildArrayIndexOf(HValue* receiver,
2390                             HValue* search_element,
2391                             ElementsKind kind,
2392                             ArrayIndexOfMode mode);
2393
2394   HValue* ImplicitReceiverFor(HValue* function,
2395                               Handle<JSFunction> target);
2396
2397   int InliningAstSize(Handle<JSFunction> target);
2398   bool TryInline(Handle<JSFunction> target, int arguments_count,
2399                  HValue* implicit_return_value, BailoutId ast_id,
2400                  BailoutId return_id, InliningKind inlining_kind);
2401
2402   bool TryInlineCall(Call* expr);
2403   bool TryInlineConstruct(CallNew* expr, HValue* implicit_return_value);
2404   bool TryInlineGetter(Handle<JSFunction> getter,
2405                        Handle<Map> receiver_map,
2406                        BailoutId ast_id,
2407                        BailoutId return_id);
2408   bool TryInlineSetter(Handle<JSFunction> setter,
2409                        Handle<Map> receiver_map,
2410                        BailoutId id,
2411                        BailoutId assignment_id,
2412                        HValue* implicit_return_value);
2413   bool TryInlineIndirectCall(Handle<JSFunction> function, Call* expr,
2414                              int arguments_count);
2415   bool TryInlineBuiltinMethodCall(Call* expr, Handle<JSFunction> function,
2416                                   Handle<Map> receiver_map,
2417                                   int args_count_no_receiver);
2418   bool TryInlineBuiltinFunctionCall(Call* expr);
2419   enum ApiCallType {
2420     kCallApiFunction,
2421     kCallApiMethod,
2422     kCallApiGetter,
2423     kCallApiSetter
2424   };
2425   bool TryInlineApiMethodCall(Call* expr,
2426                               HValue* receiver,
2427                               SmallMapList* receiver_types);
2428   bool TryInlineApiFunctionCall(Call* expr, HValue* receiver);
2429   bool TryInlineApiGetter(Handle<JSFunction> function,
2430                           Handle<Map> receiver_map,
2431                           BailoutId ast_id);
2432   bool TryInlineApiSetter(Handle<JSFunction> function,
2433                           Handle<Map> receiver_map,
2434                           BailoutId ast_id);
2435   bool TryInlineApiCall(Handle<JSFunction> function,
2436                          HValue* receiver,
2437                          SmallMapList* receiver_maps,
2438                          int argc,
2439                          BailoutId ast_id,
2440                          ApiCallType call_type);
2441   static bool IsReadOnlyLengthDescriptor(Handle<Map> jsarray_map);
2442   static bool CanInlineArrayResizeOperation(Handle<Map> receiver_map);
2443
2444   // If --trace-inlining, print a line of the inlining trace.  Inlining
2445   // succeeded if the reason string is NULL and failed if there is a
2446   // non-NULL reason string.
2447   void TraceInline(Handle<JSFunction> target,
2448                    Handle<JSFunction> caller,
2449                    const char* failure_reason);
2450
2451   void HandleGlobalVariableAssignment(Variable* var,
2452                                       HValue* value,
2453                                       BailoutId ast_id);
2454
2455   void HandlePropertyAssignment(Assignment* expr);
2456   void HandleCompoundAssignment(Assignment* expr);
2457   void HandlePolymorphicNamedFieldAccess(PropertyAccessType access_type,
2458                                          Expression* expr,
2459                                          BailoutId ast_id,
2460                                          BailoutId return_id,
2461                                          HValue* object,
2462                                          HValue* value,
2463                                          SmallMapList* types,
2464                                          Handle<String> name);
2465
2466   HValue* BuildAllocateExternalElements(
2467       ExternalArrayType array_type,
2468       bool is_zero_byte_offset,
2469       HValue* buffer, HValue* byte_offset, HValue* length);
2470   HValue* BuildAllocateFixedTypedArray(ExternalArrayType array_type,
2471                                        size_t element_size,
2472                                        ElementsKind fixed_elements_kind,
2473                                        HValue* byte_length, HValue* length,
2474                                        bool initialize);
2475
2476   // TODO(adamk): Move all OrderedHashTable functions to their own class.
2477   HValue* BuildOrderedHashTableHashToBucket(HValue* hash, HValue* num_buckets);
2478   template <typename CollectionType>
2479   HValue* BuildOrderedHashTableHashToEntry(HValue* table, HValue* hash,
2480                                            HValue* num_buckets);
2481   template <typename CollectionType>
2482   HValue* BuildOrderedHashTableEntryToIndex(HValue* entry, HValue* num_buckets);
2483   template <typename CollectionType>
2484   HValue* BuildOrderedHashTableFindEntry(HValue* table, HValue* key,
2485                                          HValue* hash);
2486   template <typename CollectionType>
2487   HValue* BuildOrderedHashTableAddEntry(HValue* table, HValue* key,
2488                                         HValue* hash,
2489                                         HIfContinuation* join_continuation);
2490   template <typename CollectionType>
2491   HValue* BuildAllocateOrderedHashTable();
2492   template <typename CollectionType>
2493   void BuildOrderedHashTableClear(HValue* receiver);
2494   template <typename CollectionType>
2495   void BuildJSCollectionDelete(CallRuntime* call,
2496                                const Runtime::Function* c_function);
2497   template <typename CollectionType>
2498   void BuildJSCollectionHas(CallRuntime* call,
2499                             const Runtime::Function* c_function);
2500   HValue* BuildStringHashLoadIfIsStringAndHashComputed(
2501       HValue* object, HIfContinuation* continuation);
2502
2503   Handle<JSFunction> array_function() {
2504     return handle(isolate()->native_context()->array_function());
2505   }
2506
2507   bool IsCallArrayInlineable(int argument_count, Handle<AllocationSite> site);
2508   void BuildInlinedCallArray(Expression* expression, int argument_count,
2509                              Handle<AllocationSite> site);
2510
2511   class PropertyAccessInfo {
2512    public:
2513     PropertyAccessInfo(HOptimizedGraphBuilder* builder,
2514                        PropertyAccessType access_type, Handle<Map> map,
2515                        Handle<String> name)
2516         : builder_(builder),
2517           access_type_(access_type),
2518           map_(map),
2519           name_(name),
2520           field_type_(HType::Tagged()),
2521           access_(HObjectAccess::ForMap()),
2522           lookup_type_(NOT_FOUND),
2523           details_(NONE, DATA, Representation::None()) {}
2524
2525     // Checkes whether this PropertyAccessInfo can be handled as a monomorphic
2526     // load named. It additionally fills in the fields necessary to generate the
2527     // lookup code.
2528     bool CanAccessMonomorphic();
2529
2530     // Checks whether all types behave uniform when loading name. If all maps
2531     // behave the same, a single monomorphic load instruction can be emitted,
2532     // guarded by a single map-checks instruction that whether the receiver is
2533     // an instance of any of the types.
2534     // This method skips the first type in types, assuming that this
2535     // PropertyAccessInfo is built for types->first().
2536     bool CanAccessAsMonomorphic(SmallMapList* types);
2537
2538     bool NeedsWrappingFor(Handle<JSFunction> target) const;
2539
2540     Handle<Map> map();
2541     Handle<String> name() const { return name_; }
2542
2543     bool IsJSObjectFieldAccessor() {
2544       int offset;  // unused
2545       return Accessors::IsJSObjectFieldAccessor(map_, name_, &offset);
2546     }
2547
2548     bool GetJSObjectFieldAccess(HObjectAccess* access) {
2549       int offset;
2550       if (Accessors::IsJSObjectFieldAccessor(map_, name_, &offset)) {
2551         if (IsStringType()) {
2552           DCHECK(String::Equals(isolate()->factory()->length_string(), name_));
2553           *access = HObjectAccess::ForStringLength();
2554         } else if (IsArrayType()) {
2555           DCHECK(String::Equals(isolate()->factory()->length_string(), name_));
2556           *access = HObjectAccess::ForArrayLength(map_->elements_kind());
2557         } else {
2558           *access = HObjectAccess::ForMapAndOffset(map_, offset);
2559         }
2560         return true;
2561       }
2562       return false;
2563     }
2564
2565     bool IsJSArrayBufferViewFieldAccessor() {
2566       int offset;  // unused
2567       return Accessors::IsJSArrayBufferViewFieldAccessor(map_, name_, &offset);
2568     }
2569
2570     bool GetJSArrayBufferViewFieldAccess(HObjectAccess* access) {
2571       int offset;
2572       if (Accessors::IsJSArrayBufferViewFieldAccessor(map_, name_, &offset)) {
2573         *access = HObjectAccess::ForMapAndOffset(map_, offset);
2574         return true;
2575       }
2576       return false;
2577     }
2578
2579     bool has_holder() { return !holder_.is_null(); }
2580     bool IsLoad() const { return access_type_ == LOAD; }
2581
2582     Isolate* isolate() const { return builder_->isolate(); }
2583     Handle<JSObject> holder() { return holder_; }
2584     Handle<JSFunction> accessor() { return accessor_; }
2585     Handle<Object> constant() { return constant_; }
2586     Handle<Map> transition() { return transition_; }
2587     SmallMapList* field_maps() { return &field_maps_; }
2588     HType field_type() const { return field_type_; }
2589     HObjectAccess access() { return access_; }
2590
2591     bool IsFound() const { return lookup_type_ != NOT_FOUND; }
2592     bool IsProperty() const { return IsFound() && !IsTransition(); }
2593     bool IsTransition() const { return lookup_type_ == TRANSITION_TYPE; }
2594     bool IsData() const {
2595       return lookup_type_ == DESCRIPTOR_TYPE && details_.type() == DATA;
2596     }
2597     bool IsDataConstant() const {
2598       return lookup_type_ == DESCRIPTOR_TYPE &&
2599              details_.type() == DATA_CONSTANT;
2600     }
2601     bool IsAccessorConstant() const {
2602       return !IsTransition() && details_.type() == ACCESSOR_CONSTANT;
2603     }
2604     bool IsConfigurable() const { return details_.IsConfigurable(); }
2605     bool IsReadOnly() const { return details_.IsReadOnly(); }
2606
2607     bool IsStringType() { return map_->instance_type() < FIRST_NONSTRING_TYPE; }
2608     bool IsNumberType() { return map_->instance_type() == HEAP_NUMBER_TYPE; }
2609     bool IsValueWrapped() { return IsStringType() || IsNumberType(); }
2610     bool IsArrayType() { return map_->instance_type() == JS_ARRAY_TYPE; }
2611
2612    private:
2613     Handle<Object> GetConstantFromMap(Handle<Map> map) const {
2614       DCHECK_EQ(DESCRIPTOR_TYPE, lookup_type_);
2615       DCHECK(number_ < map->NumberOfOwnDescriptors());
2616       return handle(map->instance_descriptors()->GetValue(number_), isolate());
2617     }
2618     Handle<Object> GetAccessorsFromMap(Handle<Map> map) const {
2619       return GetConstantFromMap(map);
2620     }
2621     Handle<HeapType> GetFieldTypeFromMap(Handle<Map> map) const {
2622       DCHECK(IsFound());
2623       DCHECK(number_ < map->NumberOfOwnDescriptors());
2624       return handle(map->instance_descriptors()->GetFieldType(number_),
2625                     isolate());
2626     }
2627     Handle<Map> GetFieldOwnerFromMap(Handle<Map> map) const {
2628       DCHECK(IsFound());
2629       DCHECK(number_ < map->NumberOfOwnDescriptors());
2630       return handle(map->FindFieldOwner(number_));
2631     }
2632     int GetLocalFieldIndexFromMap(Handle<Map> map) const {
2633       DCHECK(lookup_type_ == DESCRIPTOR_TYPE ||
2634              lookup_type_ == TRANSITION_TYPE);
2635       DCHECK(number_ < map->NumberOfOwnDescriptors());
2636       int field_index = map->instance_descriptors()->GetFieldIndex(number_);
2637       return field_index - map->inobject_properties();
2638     }
2639
2640     void LookupDescriptor(Map* map, Name* name) {
2641       DescriptorArray* descriptors = map->instance_descriptors();
2642       int number = descriptors->SearchWithCache(name, map);
2643       if (number == DescriptorArray::kNotFound) return NotFound();
2644       lookup_type_ = DESCRIPTOR_TYPE;
2645       details_ = descriptors->GetDetails(number);
2646       number_ = number;
2647     }
2648     void LookupTransition(Map* map, Name* name, PropertyAttributes attributes) {
2649       Map* target =
2650           TransitionArray::SearchTransition(map, kData, name, attributes);
2651       if (target == NULL) return NotFound();
2652       lookup_type_ = TRANSITION_TYPE;
2653       transition_ = handle(target);
2654       number_ = transition_->LastAdded();
2655       details_ = transition_->instance_descriptors()->GetDetails(number_);
2656     }
2657     void NotFound() {
2658       lookup_type_ = NOT_FOUND;
2659       details_ = PropertyDetails::Empty();
2660     }
2661     Representation representation() const {
2662       DCHECK(IsFound());
2663       return details_.representation();
2664     }
2665     bool IsTransitionToData() const {
2666       return IsTransition() && details_.type() == DATA;
2667     }
2668
2669     Zone* zone() { return builder_->zone(); }
2670     CompilationInfo* top_info() { return builder_->top_info(); }
2671     CompilationInfo* current_info() { return builder_->current_info(); }
2672
2673     bool LoadResult(Handle<Map> map);
2674     bool LoadFieldMaps(Handle<Map> map);
2675     bool LookupDescriptor();
2676     bool LookupInPrototypes();
2677     bool IsIntegerIndexedExotic();
2678     bool IsCompatible(PropertyAccessInfo* other);
2679
2680     void GeneralizeRepresentation(Representation r) {
2681       access_ = access_.WithRepresentation(
2682           access_.representation().generalize(r));
2683     }
2684
2685     HOptimizedGraphBuilder* builder_;
2686     PropertyAccessType access_type_;
2687     Handle<Map> map_;
2688     Handle<String> name_;
2689     Handle<JSObject> holder_;
2690     Handle<JSFunction> accessor_;
2691     Handle<JSObject> api_holder_;
2692     Handle<Object> constant_;
2693     SmallMapList field_maps_;
2694     HType field_type_;
2695     HObjectAccess access_;
2696
2697     enum { NOT_FOUND, DESCRIPTOR_TYPE, TRANSITION_TYPE } lookup_type_;
2698     Handle<Map> transition_;
2699     int number_;
2700     PropertyDetails details_;
2701   };
2702
2703   HValue* BuildMonomorphicAccess(PropertyAccessInfo* info, HValue* object,
2704                                  HValue* checked_object, HValue* value,
2705                                  BailoutId ast_id, BailoutId return_id,
2706                                  bool can_inline_accessor = true);
2707
2708   HValue* BuildNamedAccess(PropertyAccessType access, BailoutId ast_id,
2709                            BailoutId reutrn_id, Expression* expr,
2710                            HValue* object, Handle<String> name, HValue* value,
2711                            bool is_uninitialized = false);
2712
2713   void HandlePolymorphicCallNamed(Call* expr,
2714                                   HValue* receiver,
2715                                   SmallMapList* types,
2716                                   Handle<String> name);
2717   void HandleLiteralCompareTypeof(CompareOperation* expr,
2718                                   Expression* sub_expr,
2719                                   Handle<String> check);
2720   void HandleLiteralCompareNil(CompareOperation* expr,
2721                                Expression* sub_expr,
2722                                NilValue nil);
2723
2724   enum PushBeforeSimulateBehavior {
2725     PUSH_BEFORE_SIMULATE,
2726     NO_PUSH_BEFORE_SIMULATE
2727   };
2728
2729   HControlInstruction* BuildCompareInstruction(
2730       Token::Value op, HValue* left, HValue* right, Type* left_type,
2731       Type* right_type, Type* combined_type, SourcePosition left_position,
2732       SourcePosition right_position, PushBeforeSimulateBehavior push_sim_result,
2733       BailoutId bailout_id);
2734
2735   HInstruction* BuildStringCharCodeAt(HValue* string,
2736                                       HValue* index);
2737
2738   HValue* BuildBinaryOperation(
2739       BinaryOperation* expr,
2740       HValue* left,
2741       HValue* right,
2742       PushBeforeSimulateBehavior push_sim_result);
2743   HInstruction* BuildIncrement(bool returns_original_input,
2744                                CountOperation* expr);
2745   HInstruction* BuildKeyedGeneric(PropertyAccessType access_type,
2746                                   Expression* expr,
2747                                   HValue* object,
2748                                   HValue* key,
2749                                   HValue* value);
2750
2751   HInstruction* TryBuildConsolidatedElementLoad(HValue* object,
2752                                                 HValue* key,
2753                                                 HValue* val,
2754                                                 SmallMapList* maps);
2755
2756   LoadKeyedHoleMode BuildKeyedHoleMode(Handle<Map> map);
2757
2758   HInstruction* BuildMonomorphicElementAccess(HValue* object,
2759                                               HValue* key,
2760                                               HValue* val,
2761                                               HValue* dependency,
2762                                               Handle<Map> map,
2763                                               PropertyAccessType access_type,
2764                                               KeyedAccessStoreMode store_mode);
2765
2766   HValue* HandlePolymorphicElementAccess(Expression* expr,
2767                                          HValue* object,
2768                                          HValue* key,
2769                                          HValue* val,
2770                                          SmallMapList* maps,
2771                                          PropertyAccessType access_type,
2772                                          KeyedAccessStoreMode store_mode,
2773                                          bool* has_side_effects);
2774
2775   HValue* HandleKeyedElementAccess(HValue* obj, HValue* key, HValue* val,
2776                                    Expression* expr, BailoutId ast_id,
2777                                    BailoutId return_id,
2778                                    PropertyAccessType access_type,
2779                                    bool* has_side_effects);
2780
2781   HInstruction* BuildNamedGeneric(PropertyAccessType access, Expression* expr,
2782                                   HValue* object, Handle<String> name,
2783                                   HValue* value, bool is_uninitialized = false);
2784
2785   HCheckMaps* AddCheckMap(HValue* object, Handle<Map> map);
2786
2787   void BuildLoad(Property* property,
2788                  BailoutId ast_id);
2789   void PushLoad(Property* property,
2790                 HValue* object,
2791                 HValue* key);
2792
2793   void BuildStoreForEffect(Expression* expression,
2794                            Property* prop,
2795                            BailoutId ast_id,
2796                            BailoutId return_id,
2797                            HValue* object,
2798                            HValue* key,
2799                            HValue* value);
2800
2801   void BuildStore(Expression* expression,
2802                   Property* prop,
2803                   BailoutId ast_id,
2804                   BailoutId return_id,
2805                   bool is_uninitialized = false);
2806
2807   HInstruction* BuildLoadNamedField(PropertyAccessInfo* info,
2808                                     HValue* checked_object);
2809   HInstruction* BuildStoreNamedField(PropertyAccessInfo* info,
2810                                      HValue* checked_object,
2811                                      HValue* value);
2812
2813   HValue* BuildContextChainWalk(Variable* var);
2814
2815   HInstruction* BuildThisFunction();
2816
2817   HInstruction* BuildFastLiteral(Handle<JSObject> boilerplate_object,
2818                                  AllocationSiteUsageContext* site_context);
2819
2820   void BuildEmitObjectHeader(Handle<JSObject> boilerplate_object,
2821                              HInstruction* object);
2822
2823   void BuildEmitInObjectProperties(Handle<JSObject> boilerplate_object,
2824                                    HInstruction* object,
2825                                    AllocationSiteUsageContext* site_context,
2826                                    PretenureFlag pretenure_flag);
2827
2828   void BuildEmitElements(Handle<JSObject> boilerplate_object,
2829                          Handle<FixedArrayBase> elements,
2830                          HValue* object_elements,
2831                          AllocationSiteUsageContext* site_context);
2832
2833   void BuildEmitFixedDoubleArray(Handle<FixedArrayBase> elements,
2834                                  ElementsKind kind,
2835                                  HValue* object_elements);
2836
2837   void BuildEmitFixedArray(Handle<FixedArrayBase> elements,
2838                            ElementsKind kind,
2839                            HValue* object_elements,
2840                            AllocationSiteUsageContext* site_context);
2841
2842   void AddCheckPrototypeMaps(Handle<JSObject> holder,
2843                              Handle<Map> receiver_map);
2844
2845   HInstruction* NewPlainFunctionCall(HValue* fun,
2846                                      int argument_count,
2847                                      bool pass_argument_count);
2848
2849   HInstruction* NewArgumentAdaptorCall(HValue* fun, HValue* context,
2850                                        int argument_count,
2851                                        HValue* expected_param_count);
2852
2853   HInstruction* BuildCallConstantFunction(Handle<JSFunction> target,
2854                                           int argument_count);
2855
2856   bool CanBeFunctionApplyArguments(Call* expr);
2857
2858   // The translation state of the currently-being-translated function.
2859   FunctionState* function_state_;
2860
2861   // The base of the function state stack.
2862   FunctionState initial_function_state_;
2863
2864   // Expression context of the currently visited subexpression. NULL when
2865   // visiting statements.
2866   AstContext* ast_context_;
2867
2868   // A stack of breakable statements entered.
2869   BreakAndContinueScope* break_scope_;
2870
2871   int inlined_count_;
2872   ZoneList<Handle<Object> > globals_;
2873
2874   bool inline_bailout_;
2875
2876   HOsrBuilder* osr_;
2877
2878   friend class FunctionState;  // Pushes and pops the state stack.
2879   friend class AstContext;  // Pushes and pops the AST context stack.
2880   friend class KeyedLoadFastElementStub;
2881   friend class HOsrBuilder;
2882
2883   DISALLOW_COPY_AND_ASSIGN(HOptimizedGraphBuilder);
2884 };
2885
2886
2887 Zone* AstContext::zone() const { return owner_->zone(); }
2888
2889
2890 class HStatistics final : public Malloced {
2891  public:
2892   HStatistics()
2893       : times_(5),
2894         names_(5),
2895         sizes_(5),
2896         total_size_(0),
2897         source_size_(0) { }
2898
2899   void Initialize(CompilationInfo* info);
2900   void Print();
2901   void SaveTiming(const char* name, base::TimeDelta time, size_t size);
2902
2903   void IncrementFullCodeGen(base::TimeDelta full_code_gen) {
2904     full_code_gen_ += full_code_gen;
2905   }
2906
2907   void IncrementCreateGraph(base::TimeDelta delta) { create_graph_ += delta; }
2908
2909   void IncrementOptimizeGraph(base::TimeDelta delta) {
2910     optimize_graph_ += delta;
2911   }
2912
2913   void IncrementGenerateCode(base::TimeDelta delta) { generate_code_ += delta; }
2914
2915   void IncrementSubtotals(base::TimeDelta create_graph,
2916                           base::TimeDelta optimize_graph,
2917                           base::TimeDelta generate_code) {
2918     IncrementCreateGraph(create_graph);
2919     IncrementOptimizeGraph(optimize_graph);
2920     IncrementGenerateCode(generate_code);
2921   }
2922
2923  private:
2924   List<base::TimeDelta> times_;
2925   List<const char*> names_;
2926   List<size_t> sizes_;
2927   base::TimeDelta create_graph_;
2928   base::TimeDelta optimize_graph_;
2929   base::TimeDelta generate_code_;
2930   size_t total_size_;
2931   base::TimeDelta full_code_gen_;
2932   double source_size_;
2933 };
2934
2935
2936 class HPhase : public CompilationPhase {
2937  public:
2938   HPhase(const char* name, HGraph* graph)
2939       : CompilationPhase(name, graph->info()),
2940         graph_(graph) { }
2941   ~HPhase();
2942
2943  protected:
2944   HGraph* graph() const { return graph_; }
2945
2946  private:
2947   HGraph* graph_;
2948
2949   DISALLOW_COPY_AND_ASSIGN(HPhase);
2950 };
2951
2952
2953 class HTracer final : public Malloced {
2954  public:
2955   explicit HTracer(int isolate_id)
2956       : trace_(&string_allocator_), indent_(0) {
2957     if (FLAG_trace_hydrogen_file == NULL) {
2958       SNPrintF(filename_,
2959                "hydrogen-%d-%d.cfg",
2960                base::OS::GetCurrentProcessId(),
2961                isolate_id);
2962     } else {
2963       StrNCpy(filename_, FLAG_trace_hydrogen_file, filename_.length());
2964     }
2965     WriteChars(filename_.start(), "", 0, false);
2966   }
2967
2968   void TraceCompilation(CompilationInfo* info);
2969   void TraceHydrogen(const char* name, HGraph* graph);
2970   void TraceLithium(const char* name, LChunk* chunk);
2971   void TraceLiveRanges(const char* name, LAllocator* allocator);
2972
2973  private:
2974   class Tag final BASE_EMBEDDED {
2975    public:
2976     Tag(HTracer* tracer, const char* name) {
2977       name_ = name;
2978       tracer_ = tracer;
2979       tracer->PrintIndent();
2980       tracer->trace_.Add("begin_%s\n", name);
2981       tracer->indent_++;
2982     }
2983
2984     ~Tag() {
2985       tracer_->indent_--;
2986       tracer_->PrintIndent();
2987       tracer_->trace_.Add("end_%s\n", name_);
2988       DCHECK(tracer_->indent_ >= 0);
2989       tracer_->FlushToFile();
2990     }
2991
2992    private:
2993     HTracer* tracer_;
2994     const char* name_;
2995   };
2996
2997   void TraceLiveRange(LiveRange* range, const char* type, Zone* zone);
2998   void Trace(const char* name, HGraph* graph, LChunk* chunk);
2999   void FlushToFile();
3000
3001   void PrintEmptyProperty(const char* name) {
3002     PrintIndent();
3003     trace_.Add("%s\n", name);
3004   }
3005
3006   void PrintStringProperty(const char* name, const char* value) {
3007     PrintIndent();
3008     trace_.Add("%s \"%s\"\n", name, value);
3009   }
3010
3011   void PrintLongProperty(const char* name, int64_t value) {
3012     PrintIndent();
3013     trace_.Add("%s %d000\n", name, static_cast<int>(value / 1000));
3014   }
3015
3016   void PrintBlockProperty(const char* name, int block_id) {
3017     PrintIndent();
3018     trace_.Add("%s \"B%d\"\n", name, block_id);
3019   }
3020
3021   void PrintIntProperty(const char* name, int value) {
3022     PrintIndent();
3023     trace_.Add("%s %d\n", name, value);
3024   }
3025
3026   void PrintIndent() {
3027     for (int i = 0; i < indent_; i++) {
3028       trace_.Add("  ");
3029     }
3030   }
3031
3032   EmbeddedVector<char, 64> filename_;
3033   HeapStringAllocator string_allocator_;
3034   StringStream trace_;
3035   int indent_;
3036 };
3037
3038
3039 class NoObservableSideEffectsScope final {
3040  public:
3041   explicit NoObservableSideEffectsScope(HGraphBuilder* builder) :
3042       builder_(builder) {
3043     builder_->graph()->IncrementInNoSideEffectsScope();
3044   }
3045   ~NoObservableSideEffectsScope() {
3046     builder_->graph()->DecrementInNoSideEffectsScope();
3047   }
3048
3049  private:
3050   HGraphBuilder* builder_;
3051 };
3052
3053
3054 } }  // namespace v8::internal
3055
3056 #endif  // V8_HYDROGEN_H_