Reland r21101: "ARM64: use jssp for stack slots"
[platform/upstream/v8.git] / src / arm64 / lithium-codegen-arm64.h
1 // Copyright 2013 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef V8_ARM64_LITHIUM_CODEGEN_ARM64_H_
6 #define V8_ARM64_LITHIUM_CODEGEN_ARM64_H_
7
8 #include "src/arm64/lithium-arm64.h"
9
10 #include "src/arm64/lithium-gap-resolver-arm64.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
17 namespace v8 {
18 namespace internal {
19
20 // Forward declarations.
21 class LDeferredCode;
22 class SafepointGenerator;
23 class BranchGenerator;
24
25 class LCodeGen: public LCodeGenBase {
26  public:
27   LCodeGen(LChunk* chunk, MacroAssembler* assembler, CompilationInfo* info)
28       : LCodeGenBase(chunk, assembler, info),
29         deoptimizations_(4, info->zone()),
30         jump_table_(4, info->zone()),
31         inlined_function_count_(0),
32         scope_(info->scope()),
33         translations_(info->zone()),
34         deferred_(8, info->zone()),
35         osr_pc_offset_(-1),
36         frame_is_built_(false),
37         safepoints_(info->zone()),
38         resolver_(this),
39         expected_safepoint_kind_(Safepoint::kSimple),
40         pushed_arguments_(0) {
41     PopulateDeoptimizationLiteralsWithInlinedFunctions();
42   }
43
44   // Simple accessors.
45   Scope* scope() const { return scope_; }
46
47   int LookupDestination(int block_id) const {
48     return chunk()->LookupDestination(block_id);
49   }
50
51   bool IsNextEmittedBlock(int block_id) const {
52     return LookupDestination(block_id) == GetNextEmittedBlock();
53   }
54
55   bool NeedsEagerFrame() const {
56     return GetStackSlotCount() > 0 ||
57         info()->is_non_deferred_calling() ||
58         !info()->IsStub() ||
59         info()->requires_frame();
60   }
61   bool NeedsDeferredFrame() const {
62     return !NeedsEagerFrame() && info()->is_deferred_calling();
63   }
64
65   LinkRegisterStatus GetLinkRegisterState() const {
66     return frame_is_built_ ? kLRHasBeenSaved : kLRHasNotBeenSaved;
67   }
68
69   // Try to generate code for the entire chunk, but it may fail if the
70   // chunk contains constructs we cannot handle. Returns true if the
71   // code generation attempt succeeded.
72   bool GenerateCode();
73
74   // Finish the code by setting stack height, safepoint, and bailout
75   // information on it.
76   void FinishCode(Handle<Code> code);
77
78   enum IntegerSignedness { SIGNED_INT32, UNSIGNED_INT32 };
79   // Support for converting LOperands to assembler types.
80   Register ToRegister(LOperand* op) const;
81   Register ToRegister32(LOperand* op) const;
82   Operand ToOperand(LOperand* op);
83   Operand ToOperand32(LOperand* op);
84   enum StackMode { kMustUseFramePointer, kCanUseStackPointer };
85   MemOperand ToMemOperand(LOperand* op,
86                           StackMode stack_mode = kCanUseStackPointer) const;
87   Handle<Object> ToHandle(LConstantOperand* op) const;
88
89   template <class LI>
90   Operand ToShiftedRightOperand32(LOperand* right, LI* shift_info);
91
92   int JSShiftAmountFromLConstant(LOperand* constant) {
93     return ToInteger32(LConstantOperand::cast(constant)) & 0x1f;
94   }
95
96   // TODO(jbramley): Examine these helpers and check that they make sense.
97   // IsInteger32Constant returns true for smi constants, for example.
98   bool IsInteger32Constant(LConstantOperand* op) const;
99   bool IsSmi(LConstantOperand* op) const;
100
101   int32_t ToInteger32(LConstantOperand* op) const;
102   Smi* ToSmi(LConstantOperand* op) const;
103   double ToDouble(LConstantOperand* op) const;
104   DoubleRegister ToDoubleRegister(LOperand* op) const;
105
106   // Declare methods that deal with the individual node types.
107 #define DECLARE_DO(type) void Do##type(L##type* node);
108   LITHIUM_CONCRETE_INSTRUCTION_LIST(DECLARE_DO)
109 #undef DECLARE_DO
110
111  private:
112   // Return a double scratch register which can be used locally
113   // when generating code for a lithium instruction.
114   DoubleRegister double_scratch() { return crankshaft_fp_scratch; }
115
116   // Deferred code support.
117   void DoDeferredNumberTagD(LNumberTagD* instr);
118   void DoDeferredStackCheck(LStackCheck* instr);
119   void DoDeferredMaybeGrowElements(LMaybeGrowElements* instr);
120   void DoDeferredStringCharCodeAt(LStringCharCodeAt* instr);
121   void DoDeferredStringCharFromCode(LStringCharFromCode* instr);
122   void DoDeferredMathAbsTagged(LMathAbsTagged* instr,
123                                Label* exit,
124                                Label* allocation_entry);
125
126   void DoDeferredNumberTagU(LInstruction* instr,
127                             LOperand* value,
128                             LOperand* temp1,
129                             LOperand* temp2);
130   void DoDeferredTaggedToI(LTaggedToI* instr,
131                            LOperand* value,
132                            LOperand* temp1,
133                            LOperand* temp2);
134   void DoDeferredAllocate(LAllocate* instr);
135   void DoDeferredInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr);
136   void DoDeferredInstanceMigration(LCheckMaps* instr, Register object);
137   void DoDeferredLoadMutableDouble(LLoadFieldByIndex* instr,
138                                    Register result,
139                                    Register object,
140                                    Register index);
141
142   static Condition TokenToCondition(Token::Value op, bool is_unsigned);
143   void EmitGoto(int block);
144   void DoGap(LGap* instr);
145
146   // Generic version of EmitBranch. It contains some code to avoid emitting a
147   // branch on the next emitted basic block where we could just fall-through.
148   // You shouldn't use that directly but rather consider one of the helper like
149   // LCodeGen::EmitBranch, LCodeGen::EmitCompareAndBranch...
150   template<class InstrType>
151   void EmitBranchGeneric(InstrType instr,
152                          const BranchGenerator& branch);
153
154   template<class InstrType>
155   void EmitBranch(InstrType instr, Condition condition);
156
157   template<class InstrType>
158   void EmitCompareAndBranch(InstrType instr,
159                             Condition condition,
160                             const Register& lhs,
161                             const Operand& rhs);
162
163   template<class InstrType>
164   void EmitTestAndBranch(InstrType instr,
165                          Condition condition,
166                          const Register& value,
167                          uint64_t mask);
168
169   template<class InstrType>
170   void EmitBranchIfNonZeroNumber(InstrType instr,
171                                  const FPRegister& value,
172                                  const FPRegister& scratch);
173
174   template<class InstrType>
175   void EmitBranchIfHeapNumber(InstrType instr,
176                               const Register& value);
177
178   template<class InstrType>
179   void EmitBranchIfRoot(InstrType instr,
180                         const Register& value,
181                         Heap::RootListIndex index);
182
183   // Emits optimized code to deep-copy the contents of statically known object
184   // graphs (e.g. object literal boilerplate). Expects a pointer to the
185   // allocated destination object in the result register, and a pointer to the
186   // source object in the source register.
187   void EmitDeepCopy(Handle<JSObject> object,
188                     Register result,
189                     Register source,
190                     Register scratch,
191                     int* offset,
192                     AllocationSiteMode mode);
193
194   template <class T>
195   void EmitVectorLoadICRegisters(T* instr);
196
197   // Emits optimized code for %_IsString(x).  Preserves input register.
198   // Returns the condition on which a final split to
199   // true and false label should be made, to optimize fallthrough.
200   Condition EmitIsString(Register input, Register temp1, Label* is_not_string,
201                          SmiCheck check_needed);
202
203   void PopulateDeoptimizationData(Handle<Code> code);
204   void PopulateDeoptimizationLiteralsWithInlinedFunctions();
205
206   MemOperand BuildSeqStringOperand(Register string,
207                                    Register temp,
208                                    LOperand* index,
209                                    String::Encoding encoding);
210   void DeoptimizeBranch(LInstruction* instr,
211                         Deoptimizer::DeoptReason deopt_reason,
212                         BranchType branch_type, Register reg = NoReg,
213                         int bit = -1,
214                         Deoptimizer::BailoutType* override_bailout_type = NULL);
215   void Deoptimize(LInstruction* instr, Deoptimizer::DeoptReason deopt_reason,
216                   Deoptimizer::BailoutType* override_bailout_type = NULL);
217   void DeoptimizeIf(Condition cond, LInstruction* instr,
218                     Deoptimizer::DeoptReason deopt_reason);
219   void DeoptimizeIfZero(Register rt, LInstruction* instr,
220                         Deoptimizer::DeoptReason deopt_reason);
221   void DeoptimizeIfNotZero(Register rt, LInstruction* instr,
222                            Deoptimizer::DeoptReason deopt_reason);
223   void DeoptimizeIfNegative(Register rt, LInstruction* instr,
224                             Deoptimizer::DeoptReason deopt_reason);
225   void DeoptimizeIfSmi(Register rt, LInstruction* instr,
226                        Deoptimizer::DeoptReason deopt_reason);
227   void DeoptimizeIfNotSmi(Register rt, LInstruction* instr,
228                           Deoptimizer::DeoptReason deopt_reason);
229   void DeoptimizeIfRoot(Register rt, Heap::RootListIndex index,
230                         LInstruction* instr,
231                         Deoptimizer::DeoptReason deopt_reason);
232   void DeoptimizeIfNotRoot(Register rt, Heap::RootListIndex index,
233                            LInstruction* instr,
234                            Deoptimizer::DeoptReason deopt_reason);
235   void DeoptimizeIfNotHeapNumber(Register object, LInstruction* instr);
236   void DeoptimizeIfMinusZero(DoubleRegister input, LInstruction* instr,
237                              Deoptimizer::DeoptReason deopt_reason);
238   void DeoptimizeIfBitSet(Register rt, int bit, LInstruction* instr,
239                           Deoptimizer::DeoptReason deopt_reason);
240   void DeoptimizeIfBitClear(Register rt, int bit, LInstruction* instr,
241                             Deoptimizer::DeoptReason deopt_reason);
242
243   MemOperand PrepareKeyedExternalArrayOperand(Register key,
244                                               Register base,
245                                               Register scratch,
246                                               bool key_is_smi,
247                                               bool key_is_constant,
248                                               int constant_key,
249                                               ElementsKind elements_kind,
250                                               int base_offset);
251   MemOperand PrepareKeyedArrayOperand(Register base,
252                                       Register elements,
253                                       Register key,
254                                       bool key_is_tagged,
255                                       ElementsKind elements_kind,
256                                       Representation representation,
257                                       int base_offset);
258
259   void RegisterEnvironmentForDeoptimization(LEnvironment* environment,
260                                             Safepoint::DeoptMode mode);
261
262   int GetStackSlotCount() const { return chunk()->spill_slot_count(); }
263
264   void AddDeferredCode(LDeferredCode* code) { deferred_.Add(code, zone()); }
265
266   // Emit frame translation commands for an environment.
267   void WriteTranslation(LEnvironment* environment, Translation* translation);
268
269   void AddToTranslation(LEnvironment* environment,
270                         Translation* translation,
271                         LOperand* op,
272                         bool is_tagged,
273                         bool is_uint32,
274                         int* object_index_pointer,
275                         int* dematerialized_index_pointer);
276
277   void SaveCallerDoubles();
278   void RestoreCallerDoubles();
279
280   // Code generation steps.  Returns true if code generation should continue.
281   void GenerateBodyInstructionPre(LInstruction* instr) override;
282   bool GeneratePrologue();
283   bool GenerateDeferredCode();
284   bool GenerateJumpTable();
285   bool GenerateSafepointTable();
286
287   // Generates the custom OSR entrypoint and sets the osr_pc_offset.
288   void GenerateOsrPrologue();
289
290   enum SafepointMode {
291     RECORD_SIMPLE_SAFEPOINT,
292     RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS
293   };
294
295   void CallCode(Handle<Code> code,
296                 RelocInfo::Mode mode,
297                 LInstruction* instr);
298
299   void CallCodeGeneric(Handle<Code> code,
300                        RelocInfo::Mode mode,
301                        LInstruction* instr,
302                        SafepointMode safepoint_mode);
303
304   void CallRuntime(const Runtime::Function* function,
305                    int num_arguments,
306                    LInstruction* instr,
307                    SaveFPRegsMode save_doubles = kDontSaveFPRegs);
308
309   void CallRuntime(Runtime::FunctionId id,
310                    int num_arguments,
311                    LInstruction* instr) {
312     const Runtime::Function* function = Runtime::FunctionForId(id);
313     CallRuntime(function, num_arguments, instr);
314   }
315
316   void LoadContextFromDeferred(LOperand* context);
317   void CallRuntimeFromDeferred(Runtime::FunctionId id,
318                                int argc,
319                                LInstruction* instr,
320                                LOperand* context);
321
322   // Generate a direct call to a known function.  Expects the function
323   // to be in x1.
324   void CallKnownFunction(Handle<JSFunction> function,
325                          int formal_parameter_count, int arity,
326                          LInstruction* instr);
327
328   // Support for recording safepoint and position information.
329   void RecordAndWritePosition(int position) override;
330   void RecordSafepoint(LPointerMap* pointers,
331                        Safepoint::Kind kind,
332                        int arguments,
333                        Safepoint::DeoptMode mode);
334   void RecordSafepoint(LPointerMap* pointers, Safepoint::DeoptMode mode);
335   void RecordSafepoint(Safepoint::DeoptMode mode);
336   void RecordSafepointWithRegisters(LPointerMap* pointers,
337                                     int arguments,
338                                     Safepoint::DeoptMode mode);
339   void RecordSafepointWithLazyDeopt(LInstruction* instr,
340                                     SafepointMode safepoint_mode);
341
342   void EnsureSpaceForLazyDeopt(int space_needed) override;
343
344   ZoneList<LEnvironment*> deoptimizations_;
345   ZoneList<Deoptimizer::JumpTableEntry*> jump_table_;
346   int inlined_function_count_;
347   Scope* const scope_;
348   TranslationBuffer translations_;
349   ZoneList<LDeferredCode*> deferred_;
350   int osr_pc_offset_;
351   bool frame_is_built_;
352
353   // Builder that keeps track of safepoints in the code. The table itself is
354   // emitted at the end of the generated code.
355   SafepointTableBuilder safepoints_;
356
357   // Compiler from a set of parallel moves to a sequential list of moves.
358   LGapResolver resolver_;
359
360   Safepoint::Kind expected_safepoint_kind_;
361
362   // The number of arguments pushed onto the stack, either by this block or by a
363   // predecessor.
364   int pushed_arguments_;
365
366   void RecordPushedArgumentsDelta(int delta) {
367     pushed_arguments_ += delta;
368     DCHECK(pushed_arguments_ >= 0);
369   }
370
371   int old_position_;
372
373   class PushSafepointRegistersScope BASE_EMBEDDED {
374    public:
375     explicit PushSafepointRegistersScope(LCodeGen* codegen)
376         : codegen_(codegen) {
377       DCHECK(codegen_->info()->is_calling());
378       DCHECK(codegen_->expected_safepoint_kind_ == Safepoint::kSimple);
379       codegen_->expected_safepoint_kind_ = Safepoint::kWithRegisters;
380
381       UseScratchRegisterScope temps(codegen_->masm_);
382       // Preserve the value of lr which must be saved on the stack (the call to
383       // the stub will clobber it).
384       Register to_be_pushed_lr =
385           temps.UnsafeAcquire(StoreRegistersStateStub::to_be_pushed_lr());
386       codegen_->masm_->Mov(to_be_pushed_lr, lr);
387       StoreRegistersStateStub stub(codegen_->isolate());
388       codegen_->masm_->CallStub(&stub);
389     }
390
391     ~PushSafepointRegistersScope() {
392       DCHECK(codegen_->expected_safepoint_kind_ == Safepoint::kWithRegisters);
393       RestoreRegistersStateStub stub(codegen_->isolate());
394       codegen_->masm_->CallStub(&stub);
395       codegen_->expected_safepoint_kind_ = Safepoint::kSimple;
396     }
397
398    private:
399     LCodeGen* codegen_;
400   };
401
402   friend class LDeferredCode;
403   friend class SafepointGenerator;
404   DISALLOW_COPY_AND_ASSIGN(LCodeGen);
405 };
406
407
408 class LDeferredCode: public ZoneObject {
409  public:
410   explicit LDeferredCode(LCodeGen* codegen)
411       : codegen_(codegen),
412         external_exit_(NULL),
413         instruction_index_(codegen->current_instruction_) {
414     codegen->AddDeferredCode(this);
415   }
416
417   virtual ~LDeferredCode() { }
418   virtual void Generate() = 0;
419   virtual LInstruction* instr() = 0;
420
421   void SetExit(Label* exit) { external_exit_ = exit; }
422   Label* entry() { return &entry_; }
423   Label* exit() { return (external_exit_ != NULL) ? external_exit_ : &exit_; }
424   int instruction_index() const { return instruction_index_; }
425
426  protected:
427   LCodeGen* codegen() const { return codegen_; }
428   MacroAssembler* masm() const { return codegen_->masm(); }
429
430  private:
431   LCodeGen* codegen_;
432   Label entry_;
433   Label exit_;
434   Label* external_exit_;
435   int instruction_index_;
436 };
437
438
439 // This is the abstract class used by EmitBranchGeneric.
440 // It is used to emit code for conditional branching. The Emit() function
441 // emits code to branch when the condition holds and EmitInverted() emits
442 // the branch when the inverted condition is verified.
443 //
444 // For actual examples of condition see the concrete implementation in
445 // lithium-codegen-arm64.cc (e.g. BranchOnCondition, CompareAndBranch).
446 class BranchGenerator BASE_EMBEDDED {
447  public:
448   explicit BranchGenerator(LCodeGen* codegen)
449     : codegen_(codegen) { }
450
451   virtual ~BranchGenerator() { }
452
453   virtual void Emit(Label* label) const = 0;
454   virtual void EmitInverted(Label* label) const = 0;
455
456  protected:
457   MacroAssembler* masm() const { return codegen_->masm(); }
458
459   LCodeGen* codegen_;
460 };
461
462 } }  // namespace v8::internal
463
464 #endif  // V8_ARM64_LITHIUM_CODEGEN_ARM64_H_