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