Thread the Lithium instruction down to DeoptimizeIf and friends.
[platform/upstream/v8.git] / src / x87 / lithium-codegen-x87.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_X87_LITHIUM_CODEGEN_X87_H_
6 #define V8_X87_LITHIUM_CODEGEN_X87_H_
7
8 #include "src/x87/lithium-x87.h"
9
10 #include "src/base/logging.h"
11 #include "src/deoptimizer.h"
12 #include "src/lithium-codegen.h"
13 #include "src/safepoint-table.h"
14 #include "src/scopes.h"
15 #include "src/utils.h"
16 #include "src/x87/lithium-gap-resolver-x87.h"
17
18 namespace v8 {
19 namespace internal {
20
21 // Forward declarations.
22 class LDeferredCode;
23 class LGapNode;
24 class SafepointGenerator;
25
26 class LCodeGen: public LCodeGenBase {
27  public:
28   LCodeGen(LChunk* chunk, MacroAssembler* assembler, CompilationInfo* info)
29       : LCodeGenBase(chunk, assembler, info),
30         deoptimizations_(4, info->zone()),
31         jump_table_(4, info->zone()),
32         deoptimization_literals_(8, info->zone()),
33         inlined_function_count_(0),
34         scope_(info->scope()),
35         translations_(info->zone()),
36         deferred_(8, info->zone()),
37         dynamic_frame_alignment_(false),
38         support_aligned_spilled_doubles_(false),
39         osr_pc_offset_(-1),
40         frame_is_built_(false),
41         x87_stack_(assembler),
42         safepoints_(info->zone()),
43         resolver_(this),
44         expected_safepoint_kind_(Safepoint::kSimple) {
45     PopulateDeoptimizationLiteralsWithInlinedFunctions();
46   }
47
48   int LookupDestination(int block_id) const {
49     return chunk()->LookupDestination(block_id);
50   }
51
52   bool IsNextEmittedBlock(int block_id) const {
53     return LookupDestination(block_id) == GetNextEmittedBlock();
54   }
55
56   bool NeedsEagerFrame() const {
57     return GetStackSlotCount() > 0 ||
58         info()->is_non_deferred_calling() ||
59         !info()->IsStub() ||
60         info()->requires_frame();
61   }
62   bool NeedsDeferredFrame() const {
63     return !NeedsEagerFrame() && info()->is_deferred_calling();
64   }
65
66   // Support for converting LOperands to assembler types.
67   Operand ToOperand(LOperand* op) const;
68   Register ToRegister(LOperand* op) const;
69   X87Register ToX87Register(LOperand* op) const;
70
71   bool IsInteger32(LConstantOperand* op) const;
72   bool IsSmi(LConstantOperand* op) const;
73   Immediate ToImmediate(LOperand* op, const Representation& r) const {
74     return Immediate(ToRepresentation(LConstantOperand::cast(op), r));
75   }
76   double ToDouble(LConstantOperand* op) const;
77
78   // Support for non-sse2 (x87) floating point stack handling.
79   // These functions maintain the mapping of physical stack registers to our
80   // virtual registers between instructions.
81   enum X87OperandType { kX87DoubleOperand, kX87FloatOperand, kX87IntOperand };
82
83   void X87Mov(X87Register reg, Operand src,
84       X87OperandType operand = kX87DoubleOperand);
85   void X87Mov(Operand src, X87Register reg,
86       X87OperandType operand = kX87DoubleOperand);
87
88   void X87PrepareBinaryOp(
89       X87Register left, X87Register right, X87Register result);
90
91   void X87LoadForUsage(X87Register reg);
92   void X87LoadForUsage(X87Register reg1, X87Register reg2);
93   void X87PrepareToWrite(X87Register reg) { x87_stack_.PrepareToWrite(reg); }
94   void X87CommitWrite(X87Register reg) { x87_stack_.CommitWrite(reg); }
95
96   void X87Fxch(X87Register reg, int other_slot = 0) {
97     x87_stack_.Fxch(reg, other_slot);
98   }
99   void X87Free(X87Register reg) {
100     x87_stack_.Free(reg);
101   }
102
103
104   bool X87StackEmpty() {
105     return x87_stack_.depth() == 0;
106   }
107
108   Handle<Object> ToHandle(LConstantOperand* op) const;
109
110   // The operand denoting the second word (the one with a higher address) of
111   // a double stack slot.
112   Operand HighOperand(LOperand* op);
113
114   // Try to generate code for the entire chunk, but it may fail if the
115   // chunk contains constructs we cannot handle. Returns true if the
116   // code generation attempt succeeded.
117   bool GenerateCode();
118
119   // Finish the code by setting stack height, safepoint, and bailout
120   // information on it.
121   void FinishCode(Handle<Code> code);
122
123   // Deferred code support.
124   void DoDeferredNumberTagD(LNumberTagD* instr);
125
126   enum IntegerSignedness { SIGNED_INT32, UNSIGNED_INT32 };
127   void DoDeferredNumberTagIU(LInstruction* instr,
128                              LOperand* value,
129                              LOperand* temp,
130                              IntegerSignedness signedness);
131
132   void DoDeferredTaggedToI(LTaggedToI* instr, Label* done);
133   void DoDeferredMathAbsTaggedHeapNumber(LMathAbs* instr);
134   void DoDeferredStackCheck(LStackCheck* instr);
135   void DoDeferredStringCharCodeAt(LStringCharCodeAt* instr);
136   void DoDeferredStringCharFromCode(LStringCharFromCode* instr);
137   void DoDeferredAllocate(LAllocate* instr);
138   void DoDeferredInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr,
139                                        Label* map_check);
140   void DoDeferredInstanceMigration(LCheckMaps* instr, Register object);
141   void DoDeferredLoadMutableDouble(LLoadFieldByIndex* instr,
142                                    Register object,
143                                    Register index);
144
145   // Parallel move support.
146   void DoParallelMove(LParallelMove* move);
147   void DoGap(LGap* instr);
148
149   // Emit frame translation commands for an environment.
150   void WriteTranslation(LEnvironment* environment, Translation* translation);
151
152   void EnsureRelocSpaceForDeoptimization();
153
154   // Declare methods that deal with the individual node types.
155 #define DECLARE_DO(type) void Do##type(L##type* node);
156   LITHIUM_CONCRETE_INSTRUCTION_LIST(DECLARE_DO)
157 #undef DECLARE_DO
158
159  private:
160   StrictMode strict_mode() const { return info()->strict_mode(); }
161
162   Scope* scope() const { return scope_; }
163
164   void EmitClassOfTest(Label* if_true,
165                        Label* if_false,
166                        Handle<String> class_name,
167                        Register input,
168                        Register temporary,
169                        Register temporary2);
170
171   int GetStackSlotCount() const { return chunk()->spill_slot_count(); }
172
173   void AddDeferredCode(LDeferredCode* code) { deferred_.Add(code, zone()); }
174
175   // Code generation passes.  Returns true if code generation should
176   // continue.
177   void GenerateBodyInstructionPre(LInstruction* instr) OVERRIDE;
178   void GenerateBodyInstructionPost(LInstruction* instr) OVERRIDE;
179   bool GeneratePrologue();
180   bool GenerateDeferredCode();
181   bool GenerateJumpTable();
182   bool GenerateSafepointTable();
183
184   // Generates the custom OSR entrypoint and sets the osr_pc_offset.
185   void GenerateOsrPrologue();
186
187   enum SafepointMode {
188     RECORD_SIMPLE_SAFEPOINT,
189     RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS
190   };
191
192   void CallCode(Handle<Code> code,
193                 RelocInfo::Mode mode,
194                 LInstruction* instr);
195
196   void CallCodeGeneric(Handle<Code> code,
197                        RelocInfo::Mode mode,
198                        LInstruction* instr,
199                        SafepointMode safepoint_mode);
200
201   void CallRuntime(const Runtime::Function* fun,
202                    int argc,
203                    LInstruction* instr);
204
205   void CallRuntime(Runtime::FunctionId id,
206                    int argc,
207                    LInstruction* instr) {
208     const Runtime::Function* function = Runtime::FunctionForId(id);
209     CallRuntime(function, argc, instr);
210   }
211
212   void CallRuntimeFromDeferred(Runtime::FunctionId id,
213                                int argc,
214                                LInstruction* instr,
215                                LOperand* context);
216
217   void LoadContextFromDeferred(LOperand* context);
218
219   enum EDIState {
220     EDI_UNINITIALIZED,
221     EDI_CONTAINS_TARGET
222   };
223
224   // Generate a direct call to a known function.  Expects the function
225   // to be in edi.
226   void CallKnownFunction(Handle<JSFunction> function,
227                          int formal_parameter_count,
228                          int arity,
229                          LInstruction* instr,
230                          EDIState edi_state);
231
232   void RecordSafepointWithLazyDeopt(LInstruction* instr,
233                                     SafepointMode safepoint_mode);
234
235   void RegisterEnvironmentForDeoptimization(LEnvironment* environment,
236                                             Safepoint::DeoptMode mode);
237   void DeoptimizeIf(Condition cc, LInstruction* instr,
238                     Deoptimizer::BailoutType bailout_type);
239   void DeoptimizeIf(Condition cc, LInstruction* instr);
240
241   bool DeoptEveryNTimes() {
242     return FLAG_deopt_every_n_times != 0 && !info()->IsStub();
243   }
244
245   void AddToTranslation(LEnvironment* environment,
246                         Translation* translation,
247                         LOperand* op,
248                         bool is_tagged,
249                         bool is_uint32,
250                         int* object_index_pointer,
251                         int* dematerialized_index_pointer);
252   void PopulateDeoptimizationData(Handle<Code> code);
253   int DefineDeoptimizationLiteral(Handle<Object> literal);
254
255   void PopulateDeoptimizationLiteralsWithInlinedFunctions();
256
257   Register ToRegister(int index) const;
258   X87Register ToX87Register(int index) const;
259   int32_t ToRepresentation(LConstantOperand* op, const Representation& r) const;
260   int32_t ToInteger32(LConstantOperand* op) const;
261   ExternalReference ToExternalReference(LConstantOperand* op) const;
262
263   Operand BuildFastArrayOperand(LOperand* elements_pointer,
264                                 LOperand* key,
265                                 Representation key_representation,
266                                 ElementsKind elements_kind,
267                                 uint32_t base_offset);
268
269   Operand BuildSeqStringOperand(Register string,
270                                 LOperand* index,
271                                 String::Encoding encoding);
272
273   void EmitIntegerMathAbs(LMathAbs* instr);
274
275   // Support for recording safepoint and position information.
276   void RecordSafepoint(LPointerMap* pointers,
277                        Safepoint::Kind kind,
278                        int arguments,
279                        Safepoint::DeoptMode mode);
280   void RecordSafepoint(LPointerMap* pointers, Safepoint::DeoptMode mode);
281   void RecordSafepoint(Safepoint::DeoptMode mode);
282   void RecordSafepointWithRegisters(LPointerMap* pointers,
283                                     int arguments,
284                                     Safepoint::DeoptMode mode);
285
286   void RecordAndWritePosition(int position) OVERRIDE;
287
288   static Condition TokenToCondition(Token::Value op, bool is_unsigned);
289   void EmitGoto(int block);
290
291   // EmitBranch expects to be the last instruction of a block.
292   template<class InstrType>
293   void EmitBranch(InstrType instr, Condition cc);
294   template<class InstrType>
295   void EmitFalseBranch(InstrType instr, Condition cc);
296   void EmitNumberUntagDNoSSE2(LNumberUntagD* instr, Register input,
297                               Register temp, X87Register res_reg,
298                               NumberUntagDMode mode);
299
300   // Emits optimized code for typeof x == "y".  Modifies input register.
301   // Returns the condition on which a final split to
302   // true and false label should be made, to optimize fallthrough.
303   Condition EmitTypeofIs(LTypeofIsAndBranch* instr, Register input);
304
305   // Emits optimized code for %_IsObject(x).  Preserves input register.
306   // Returns the condition on which a final split to
307   // true and false label should be made, to optimize fallthrough.
308   Condition EmitIsObject(Register input,
309                          Register temp1,
310                          Label* is_not_object,
311                          Label* is_object);
312
313   // Emits optimized code for %_IsString(x).  Preserves input register.
314   // Returns the condition on which a final split to
315   // true and false label should be made, to optimize fallthrough.
316   Condition EmitIsString(Register input,
317                          Register temp1,
318                          Label* is_not_string,
319                          SmiCheck check_needed);
320
321   // Emits optimized code for %_IsConstructCall().
322   // Caller should branch on equal condition.
323   void EmitIsConstructCall(Register temp);
324
325   // Emits optimized code to deep-copy the contents of statically known
326   // object graphs (e.g. object literal boilerplate).
327   void EmitDeepCopy(Handle<JSObject> object,
328                     Register result,
329                     Register source,
330                     int* offset,
331                     AllocationSiteMode mode);
332
333   void EnsureSpaceForLazyDeopt(int space_needed) OVERRIDE;
334   void DoLoadKeyedExternalArray(LLoadKeyed* instr);
335   void DoLoadKeyedFixedDoubleArray(LLoadKeyed* instr);
336   void DoLoadKeyedFixedArray(LLoadKeyed* instr);
337   void DoStoreKeyedExternalArray(LStoreKeyed* instr);
338   void DoStoreKeyedFixedDoubleArray(LStoreKeyed* instr);
339   void DoStoreKeyedFixedArray(LStoreKeyed* instr);
340
341   template <class T>
342   void EmitVectorLoadICRegisters(T* instr);
343
344   void EmitReturn(LReturn* instr, bool dynamic_frame_alignment);
345
346   // Emits code for pushing either a tagged constant, a (non-double)
347   // register, or a stack slot operand.
348   void EmitPushTaggedOperand(LOperand* operand);
349
350   void X87Fld(Operand src, X87OperandType opts);
351
352   void EmitFlushX87ForDeopt();
353   void FlushX87StackIfNecessary(LInstruction* instr) {
354     x87_stack_.FlushIfNecessary(instr, this);
355   }
356   friend class LGapResolver;
357
358 #ifdef _MSC_VER
359   // On windows, you may not access the stack more than one page below
360   // the most recently mapped page. To make the allocated area randomly
361   // accessible, we write an arbitrary value to each page in range
362   // esp + offset - page_size .. esp in turn.
363   void MakeSureStackPagesMapped(int offset);
364 #endif
365
366   ZoneList<LEnvironment*> deoptimizations_;
367   ZoneList<Deoptimizer::JumpTableEntry> jump_table_;
368   ZoneList<Handle<Object> > deoptimization_literals_;
369   int inlined_function_count_;
370   Scope* const scope_;
371   TranslationBuffer translations_;
372   ZoneList<LDeferredCode*> deferred_;
373   bool dynamic_frame_alignment_;
374   bool support_aligned_spilled_doubles_;
375   int osr_pc_offset_;
376   bool frame_is_built_;
377
378   class X87Stack {
379    public:
380     explicit X87Stack(MacroAssembler* masm)
381         : stack_depth_(0), is_mutable_(true), masm_(masm) { }
382     explicit X87Stack(const X87Stack& other)
383         : stack_depth_(other.stack_depth_), is_mutable_(false), masm_(masm()) {
384       for (int i = 0; i < stack_depth_; i++) {
385         stack_[i] = other.stack_[i];
386       }
387     }
388     bool operator==(const X87Stack& other) const {
389       if (stack_depth_ != other.stack_depth_) return false;
390       for (int i = 0; i < stack_depth_; i++) {
391         if (!stack_[i].is(other.stack_[i])) return false;
392       }
393       return true;
394     }
395     bool Contains(X87Register reg);
396     void Fxch(X87Register reg, int other_slot = 0);
397     void Free(X87Register reg);
398     void PrepareToWrite(X87Register reg);
399     void CommitWrite(X87Register reg);
400     void FlushIfNecessary(LInstruction* instr, LCodeGen* cgen);
401     void LeavingBlock(int current_block_id, LGoto* goto_instr);
402     int depth() const { return stack_depth_; }
403     void pop() {
404       DCHECK(is_mutable_);
405       stack_depth_--;
406     }
407     void push(X87Register reg) {
408       DCHECK(is_mutable_);
409       DCHECK(stack_depth_ < X87Register::kMaxNumAllocatableRegisters);
410       stack_[stack_depth_] = reg;
411       stack_depth_++;
412     }
413
414     MacroAssembler* masm() const { return masm_; }
415     Isolate* isolate() const { return masm_->isolate(); }
416
417    private:
418     int ArrayIndex(X87Register reg);
419     int st2idx(int pos);
420
421     X87Register stack_[X87Register::kMaxNumAllocatableRegisters];
422     int stack_depth_;
423     bool is_mutable_;
424     MacroAssembler* masm_;
425   };
426   X87Stack x87_stack_;
427
428   // Builder that keeps track of safepoints in the code. The table
429   // itself is emitted at the end of the generated code.
430   SafepointTableBuilder safepoints_;
431
432   // Compiler from a set of parallel moves to a sequential list of moves.
433   LGapResolver resolver_;
434
435   Safepoint::Kind expected_safepoint_kind_;
436
437   class PushSafepointRegistersScope FINAL  BASE_EMBEDDED {
438    public:
439     explicit PushSafepointRegistersScope(LCodeGen* codegen)
440         : codegen_(codegen) {
441       DCHECK(codegen_->expected_safepoint_kind_ == Safepoint::kSimple);
442       codegen_->masm_->PushSafepointRegisters();
443       codegen_->expected_safepoint_kind_ = Safepoint::kWithRegisters;
444       DCHECK(codegen_->info()->is_calling());
445     }
446
447     ~PushSafepointRegistersScope() {
448       DCHECK(codegen_->expected_safepoint_kind_ == Safepoint::kWithRegisters);
449       codegen_->masm_->PopSafepointRegisters();
450       codegen_->expected_safepoint_kind_ = Safepoint::kSimple;
451     }
452
453    private:
454     LCodeGen* codegen_;
455   };
456
457   friend class LDeferredCode;
458   friend class LEnvironment;
459   friend class SafepointGenerator;
460   DISALLOW_COPY_AND_ASSIGN(LCodeGen);
461 };
462
463
464 class LDeferredCode : public ZoneObject {
465  public:
466   explicit LDeferredCode(LCodeGen* codegen, const LCodeGen::X87Stack& x87_stack)
467       : codegen_(codegen),
468         external_exit_(NULL),
469         instruction_index_(codegen->current_instruction_),
470         x87_stack_(x87_stack) {
471     codegen->AddDeferredCode(this);
472   }
473
474   virtual ~LDeferredCode() {}
475   virtual void Generate() = 0;
476   virtual LInstruction* instr() = 0;
477
478   void SetExit(Label* exit) { external_exit_ = exit; }
479   Label* entry() { return &entry_; }
480   Label* exit() { return external_exit_ != NULL ? external_exit_ : &exit_; }
481   Label* done() { return codegen_->NeedsDeferredFrame() ? &done_ : exit(); }
482   int instruction_index() const { return instruction_index_; }
483   const LCodeGen::X87Stack& x87_stack() const { return x87_stack_; }
484
485  protected:
486   LCodeGen* codegen() const { return codegen_; }
487   MacroAssembler* masm() const { return codegen_->masm(); }
488
489  private:
490   LCodeGen* codegen_;
491   Label entry_;
492   Label exit_;
493   Label* external_exit_;
494   Label done_;
495   int instruction_index_;
496   LCodeGen::X87Stack x87_stack_;
497 };
498
499 } }  // namespace v8::internal
500
501 #endif  // V8_X87_LITHIUM_CODEGEN_X87_H_