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