• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef ART_COMPILER_OPTIMIZING_CODE_GENERATOR_X86_64_H_
18 #define ART_COMPILER_OPTIMIZING_CODE_GENERATOR_X86_64_H_
19 
20 #include "arch/x86_64/instruction_set_features_x86_64.h"
21 #include "code_generator.h"
22 #include "driver/compiler_options.h"
23 #include "nodes.h"
24 #include "parallel_move_resolver.h"
25 #include "utils/x86_64/assembler_x86_64.h"
26 
27 namespace art {
28 namespace x86_64 {
29 
30 // Use a local definition to prevent copying mistakes.
31 static constexpr size_t kX86_64WordSize = static_cast<size_t>(kX86_64PointerSize);
32 
33 // Some x86_64 instructions require a register to be available as temp.
34 static constexpr Register TMP = R11;
35 
36 static constexpr Register kParameterCoreRegisters[] = { RSI, RDX, RCX, R8, R9 };
37 static constexpr FloatRegister kParameterFloatRegisters[] =
38     { XMM0, XMM1, XMM2, XMM3, XMM4, XMM5, XMM6, XMM7 };
39 
40 static constexpr size_t kParameterCoreRegistersLength = arraysize(kParameterCoreRegisters);
41 static constexpr size_t kParameterFloatRegistersLength = arraysize(kParameterFloatRegisters);
42 
43 static constexpr Register kRuntimeParameterCoreRegisters[] = { RDI, RSI, RDX, RCX };
44 static constexpr size_t kRuntimeParameterCoreRegistersLength =
45     arraysize(kRuntimeParameterCoreRegisters);
46 static constexpr FloatRegister kRuntimeParameterFpuRegisters[] = { XMM0, XMM1 };
47 static constexpr size_t kRuntimeParameterFpuRegistersLength =
48     arraysize(kRuntimeParameterFpuRegisters);
49 
50 // These XMM registers are non-volatile in ART ABI, but volatile in native ABI.
51 // If the ART ABI changes, this list must be updated.  It is used to ensure that
52 // these are not clobbered by any direct call to native code (such as math intrinsics).
53 static constexpr FloatRegister non_volatile_xmm_regs[] = { XMM12, XMM13, XMM14, XMM15 };
54 
55 
56 class InvokeRuntimeCallingConvention : public CallingConvention<Register, FloatRegister> {
57  public:
InvokeRuntimeCallingConvention()58   InvokeRuntimeCallingConvention()
59       : CallingConvention(kRuntimeParameterCoreRegisters,
60                           kRuntimeParameterCoreRegistersLength,
61                           kRuntimeParameterFpuRegisters,
62                           kRuntimeParameterFpuRegistersLength,
63                           kX86_64PointerSize) {}
64 
65  private:
66   DISALLOW_COPY_AND_ASSIGN(InvokeRuntimeCallingConvention);
67 };
68 
69 class InvokeDexCallingConvention : public CallingConvention<Register, FloatRegister> {
70  public:
InvokeDexCallingConvention()71   InvokeDexCallingConvention() : CallingConvention(
72       kParameterCoreRegisters,
73       kParameterCoreRegistersLength,
74       kParameterFloatRegisters,
75       kParameterFloatRegistersLength,
76       kX86_64PointerSize) {}
77 
78  private:
79   DISALLOW_COPY_AND_ASSIGN(InvokeDexCallingConvention);
80 };
81 
82 class CriticalNativeCallingConventionVisitorX86_64 : public InvokeDexCallingConventionVisitor {
83  public:
CriticalNativeCallingConventionVisitorX86_64(bool for_register_allocation)84   explicit CriticalNativeCallingConventionVisitorX86_64(bool for_register_allocation)
85       : for_register_allocation_(for_register_allocation) {}
86 
~CriticalNativeCallingConventionVisitorX86_64()87   virtual ~CriticalNativeCallingConventionVisitorX86_64() {}
88 
89   Location GetNextLocation(DataType::Type type) override;
90   Location GetReturnLocation(DataType::Type type) const override;
91   Location GetMethodLocation() const override;
92 
GetStackOffset()93   size_t GetStackOffset() const { return stack_offset_; }
94 
95  private:
96   // Register allocator does not support adjusting frame size, so we cannot provide final locations
97   // of stack arguments for register allocation. We ask the register allocator for any location and
98   // move these arguments to the right place after adjusting the SP when generating the call.
99   const bool for_register_allocation_;
100   size_t gpr_index_ = 0u;
101   size_t fpr_index_ = 0u;
102   size_t stack_offset_ = 0u;
103 
104   DISALLOW_COPY_AND_ASSIGN(CriticalNativeCallingConventionVisitorX86_64);
105 };
106 
107 class FieldAccessCallingConventionX86_64 : public FieldAccessCallingConvention {
108  public:
FieldAccessCallingConventionX86_64()109   FieldAccessCallingConventionX86_64() {}
110 
GetObjectLocation()111   Location GetObjectLocation() const override {
112     return Location::RegisterLocation(RSI);
113   }
GetFieldIndexLocation()114   Location GetFieldIndexLocation() const override {
115     return Location::RegisterLocation(RDI);
116   }
GetReturnLocation(DataType::Type type ATTRIBUTE_UNUSED)117   Location GetReturnLocation(DataType::Type type ATTRIBUTE_UNUSED) const override {
118     return Location::RegisterLocation(RAX);
119   }
GetSetValueLocation(DataType::Type type ATTRIBUTE_UNUSED,bool is_instance)120   Location GetSetValueLocation(DataType::Type type ATTRIBUTE_UNUSED, bool is_instance)
121       const override {
122     return is_instance
123         ? Location::RegisterLocation(RDX)
124         : Location::RegisterLocation(RSI);
125   }
GetFpuLocation(DataType::Type type ATTRIBUTE_UNUSED)126   Location GetFpuLocation(DataType::Type type ATTRIBUTE_UNUSED) const override {
127     return Location::FpuRegisterLocation(XMM0);
128   }
129 
130  private:
131   DISALLOW_COPY_AND_ASSIGN(FieldAccessCallingConventionX86_64);
132 };
133 
134 
135 class InvokeDexCallingConventionVisitorX86_64 : public InvokeDexCallingConventionVisitor {
136  public:
InvokeDexCallingConventionVisitorX86_64()137   InvokeDexCallingConventionVisitorX86_64() {}
~InvokeDexCallingConventionVisitorX86_64()138   virtual ~InvokeDexCallingConventionVisitorX86_64() {}
139 
140   Location GetNextLocation(DataType::Type type) override;
141   Location GetReturnLocation(DataType::Type type) const override;
142   Location GetMethodLocation() const override;
143 
144  private:
145   InvokeDexCallingConvention calling_convention;
146 
147   DISALLOW_COPY_AND_ASSIGN(InvokeDexCallingConventionVisitorX86_64);
148 };
149 
150 class CodeGeneratorX86_64;
151 
152 class ParallelMoveResolverX86_64 : public ParallelMoveResolverWithSwap {
153  public:
ParallelMoveResolverX86_64(ArenaAllocator * allocator,CodeGeneratorX86_64 * codegen)154   ParallelMoveResolverX86_64(ArenaAllocator* allocator, CodeGeneratorX86_64* codegen)
155       : ParallelMoveResolverWithSwap(allocator), codegen_(codegen) {}
156 
157   void EmitMove(size_t index) override;
158   void EmitSwap(size_t index) override;
159   void SpillScratch(int reg) override;
160   void RestoreScratch(int reg) override;
161 
162   X86_64Assembler* GetAssembler() const;
163 
164  private:
165   void Exchange32(CpuRegister reg, int mem);
166   void Exchange32(XmmRegister reg, int mem);
167   void Exchange64(CpuRegister reg1, CpuRegister reg2);
168   void Exchange64(CpuRegister reg, int mem);
169   void Exchange64(XmmRegister reg, int mem);
170   void Exchange128(XmmRegister reg, int mem);
171   void ExchangeMemory32(int mem1, int mem2);
172   void ExchangeMemory64(int mem1, int mem2, int num_of_qwords);
173 
174   CodeGeneratorX86_64* const codegen_;
175 
176   DISALLOW_COPY_AND_ASSIGN(ParallelMoveResolverX86_64);
177 };
178 
179 class LocationsBuilderX86_64 : public HGraphVisitor {
180  public:
LocationsBuilderX86_64(HGraph * graph,CodeGeneratorX86_64 * codegen)181   LocationsBuilderX86_64(HGraph* graph, CodeGeneratorX86_64* codegen)
182       : HGraphVisitor(graph), codegen_(codegen) {}
183 
184 #define DECLARE_VISIT_INSTRUCTION(name, super)     \
185   void Visit##name(H##name* instr) override;
186 
187   FOR_EACH_CONCRETE_INSTRUCTION_COMMON(DECLARE_VISIT_INSTRUCTION)
FOR_EACH_CONCRETE_INSTRUCTION_X86_64(DECLARE_VISIT_INSTRUCTION)188   FOR_EACH_CONCRETE_INSTRUCTION_X86_64(DECLARE_VISIT_INSTRUCTION)
189   FOR_EACH_CONCRETE_INSTRUCTION_X86_COMMON(DECLARE_VISIT_INSTRUCTION)
190 
191 #undef DECLARE_VISIT_INSTRUCTION
192 
193   void VisitInstruction(HInstruction* instruction) override {
194     LOG(FATAL) << "Unreachable instruction " << instruction->DebugName()
195                << " (id " << instruction->GetId() << ")";
196   }
197 
198  private:
199   void HandleInvoke(HInvoke* invoke);
200   void HandleBitwiseOperation(HBinaryOperation* operation);
201   void HandleCondition(HCondition* condition);
202   void HandleShift(HBinaryOperation* operation);
203   void HandleFieldSet(HInstruction* instruction, const FieldInfo& field_info);
204   void HandleFieldGet(HInstruction* instruction);
205   bool CpuHasAvxFeatureFlag();
206   bool CpuHasAvx2FeatureFlag();
207 
208   CodeGeneratorX86_64* const codegen_;
209   InvokeDexCallingConventionVisitorX86_64 parameter_visitor_;
210 
211   DISALLOW_COPY_AND_ASSIGN(LocationsBuilderX86_64);
212 };
213 
214 class InstructionCodeGeneratorX86_64 : public InstructionCodeGenerator {
215  public:
216   InstructionCodeGeneratorX86_64(HGraph* graph, CodeGeneratorX86_64* codegen);
217 
218 #define DECLARE_VISIT_INSTRUCTION(name, super)     \
219   void Visit##name(H##name* instr) override;
220 
221   FOR_EACH_CONCRETE_INSTRUCTION_COMMON(DECLARE_VISIT_INSTRUCTION)
FOR_EACH_CONCRETE_INSTRUCTION_X86_64(DECLARE_VISIT_INSTRUCTION)222   FOR_EACH_CONCRETE_INSTRUCTION_X86_64(DECLARE_VISIT_INSTRUCTION)
223   FOR_EACH_CONCRETE_INSTRUCTION_X86_COMMON(DECLARE_VISIT_INSTRUCTION)
224 
225 #undef DECLARE_VISIT_INSTRUCTION
226 
227   void VisitInstruction(HInstruction* instruction) override {
228     LOG(FATAL) << "Unreachable instruction " << instruction->DebugName()
229                << " (id " << instruction->GetId() << ")";
230   }
231 
GetAssembler()232   X86_64Assembler* GetAssembler() const { return assembler_; }
233 
234   // Generate a GC root reference load:
235   //
236   //   root <- *address
237   //
238   // while honoring read barriers based on read_barrier_option.
239   void GenerateGcRootFieldLoad(HInstruction* instruction,
240                                Location root,
241                                const Address& address,
242                                Label* fixup_label,
243                                ReadBarrierOption read_barrier_option);
244   void HandleFieldSet(HInstruction* instruction,
245                       uint32_t value_index,
246                       uint32_t extra_temp_index,
247                       DataType::Type field_type,
248                       Address field_addr,
249                       CpuRegister base,
250                       bool is_volatile,
251                       bool is_atomic,
252                       bool value_can_be_null,
253                       bool byte_swap = false);
254 
255   void Bswap(Location value, DataType::Type type, CpuRegister* temp = nullptr);
256 
257  private:
258   // Generate code for the given suspend check. If not null, `successor`
259   // is the block to branch to if the suspend check is not needed, and after
260   // the suspend call.
261   void GenerateSuspendCheck(HSuspendCheck* instruction, HBasicBlock* successor);
262   void GenerateClassInitializationCheck(SlowPathCode* slow_path, CpuRegister class_reg);
263   void GenerateBitstringTypeCheckCompare(HTypeCheckInstruction* check, CpuRegister temp);
264   void HandleBitwiseOperation(HBinaryOperation* operation);
265   void GenerateRemFP(HRem* rem);
266   void DivRemOneOrMinusOne(HBinaryOperation* instruction);
267   void DivByPowerOfTwo(HDiv* instruction);
268   void RemByPowerOfTwo(HRem* instruction);
269   void GenerateDivRemWithAnyConstant(HBinaryOperation* instruction);
270   void GenerateDivRemIntegral(HBinaryOperation* instruction);
271   void HandleCondition(HCondition* condition);
272   void HandleShift(HBinaryOperation* operation);
273 
274   void HandleFieldSet(HInstruction* instruction,
275                       const FieldInfo& field_info,
276                       bool value_can_be_null);
277   void HandleFieldGet(HInstruction* instruction, const FieldInfo& field_info);
278 
279   void GenerateMinMaxInt(LocationSummary* locations, bool is_min, DataType::Type type);
280   void GenerateMinMaxFP(LocationSummary* locations, bool is_min, DataType::Type type);
281   void GenerateMinMax(HBinaryOperation* minmax, bool is_min);
282   void GenerateMethodEntryExitHook(HInstruction* instruction);
283 
284   // Generate a heap reference load using one register `out`:
285   //
286   //   out <- *(out + offset)
287   //
288   // while honoring heap poisoning and/or read barriers (if any).
289   //
290   // Location `maybe_temp` is used when generating a read barrier and
291   // shall be a register in that case; it may be an invalid location
292   // otherwise.
293   void GenerateReferenceLoadOneRegister(HInstruction* instruction,
294                                         Location out,
295                                         uint32_t offset,
296                                         Location maybe_temp,
297                                         ReadBarrierOption read_barrier_option);
298   // Generate a heap reference load using two different registers
299   // `out` and `obj`:
300   //
301   //   out <- *(obj + offset)
302   //
303   // while honoring heap poisoning and/or read barriers (if any).
304   //
305   // Location `maybe_temp` is used when generating a Baker's (fast
306   // path) read barrier and shall be a register in that case; it may
307   // be an invalid location otherwise.
308   void GenerateReferenceLoadTwoRegisters(HInstruction* instruction,
309                                          Location out,
310                                          Location obj,
311                                          uint32_t offset,
312                                          ReadBarrierOption read_barrier_option);
313 
314   void PushOntoFPStack(Location source, uint32_t temp_offset,
315                        uint32_t stack_adjustment, bool is_float);
316   void GenerateCompareTest(HCondition* condition);
317   template<class LabelType>
318   void GenerateTestAndBranch(HInstruction* instruction,
319                              size_t condition_input_index,
320                              LabelType* true_target,
321                              LabelType* false_target);
322   template<class LabelType>
323   void GenerateCompareTestAndBranch(HCondition* condition,
324                                     LabelType* true_target,
325                                     LabelType* false_target);
326   template<class LabelType>
327   void GenerateFPJumps(HCondition* cond, LabelType* true_label, LabelType* false_label);
328 
329   void HandleGoto(HInstruction* got, HBasicBlock* successor);
330 
331   bool CpuHasAvxFeatureFlag();
332   bool CpuHasAvx2FeatureFlag();
333 
334   X86_64Assembler* const assembler_;
335   CodeGeneratorX86_64* const codegen_;
336 
337   DISALLOW_COPY_AND_ASSIGN(InstructionCodeGeneratorX86_64);
338 };
339 
340 // Class for fixups to jump tables.
341 class JumpTableRIPFixup;
342 
343 class CodeGeneratorX86_64 : public CodeGenerator {
344  public:
345   CodeGeneratorX86_64(HGraph* graph,
346                   const CompilerOptions& compiler_options,
347                   OptimizingCompilerStats* stats = nullptr);
~CodeGeneratorX86_64()348   virtual ~CodeGeneratorX86_64() {}
349 
350   void GenerateFrameEntry() override;
351   void GenerateFrameExit() override;
352   void Bind(HBasicBlock* block) override;
353   void MoveConstant(Location destination, int32_t value) override;
354   void MoveLocation(Location dst, Location src, DataType::Type dst_type) override;
355   void AddLocationAsTemp(Location location, LocationSummary* locations) override;
356 
357   size_t SaveCoreRegister(size_t stack_index, uint32_t reg_id) override;
358   size_t RestoreCoreRegister(size_t stack_index, uint32_t reg_id) override;
359   size_t SaveFloatingPointRegister(size_t stack_index, uint32_t reg_id) override;
360   size_t RestoreFloatingPointRegister(size_t stack_index, uint32_t reg_id) override;
361 
362   // Generate code to invoke a runtime entry point.
363   void InvokeRuntime(QuickEntrypointEnum entrypoint,
364                      HInstruction* instruction,
365                      uint32_t dex_pc,
366                      SlowPathCode* slow_path = nullptr) override;
367 
368   // Generate code to invoke a runtime entry point, but do not record
369   // PC-related information in a stack map.
370   void InvokeRuntimeWithoutRecordingPcInfo(int32_t entry_point_offset,
371                                            HInstruction* instruction,
372                                            SlowPathCode* slow_path);
373 
374   void GenerateInvokeRuntime(int32_t entry_point_offset);
375 
GetWordSize()376   size_t GetWordSize() const override {
377     return kX86_64WordSize;
378   }
379 
GetSlowPathFPWidth()380   size_t GetSlowPathFPWidth() const override {
381     return GetGraph()->HasSIMD()
382         ? GetSIMDRegisterWidth()
383         : 1 * kX86_64WordSize;  //  8 bytes == 1 x86_64 words for each spill
384   }
385 
GetCalleePreservedFPWidth()386   size_t GetCalleePreservedFPWidth() const override {
387     return 1 * kX86_64WordSize;
388   }
389 
GetSIMDRegisterWidth()390   size_t GetSIMDRegisterWidth() const override {
391     return 2 * kX86_64WordSize;
392   }
393 
GetLocationBuilder()394   HGraphVisitor* GetLocationBuilder() override {
395     return &location_builder_;
396   }
397 
GetInstructionVisitor()398   HGraphVisitor* GetInstructionVisitor() override {
399     return &instruction_visitor_;
400   }
401 
GetAssembler()402   X86_64Assembler* GetAssembler() override {
403     return &assembler_;
404   }
405 
GetAssembler()406   const X86_64Assembler& GetAssembler() const override {
407     return assembler_;
408   }
409 
GetMoveResolver()410   ParallelMoveResolverX86_64* GetMoveResolver() override {
411     return &move_resolver_;
412   }
413 
GetAddressOf(HBasicBlock * block)414   uintptr_t GetAddressOf(HBasicBlock* block) override {
415     return GetLabelOf(block)->Position();
416   }
417 
418   void SetupBlockedRegisters() const override;
419   void DumpCoreRegister(std::ostream& stream, int reg) const override;
420   void DumpFloatingPointRegister(std::ostream& stream, int reg) const override;
421   void Finalize(CodeAllocator* allocator) override;
422 
GetInstructionSet()423   InstructionSet GetInstructionSet() const override {
424     return InstructionSet::kX86_64;
425   }
426 
GetInstructionCodegen()427   InstructionCodeGeneratorX86_64* GetInstructionCodegen() {
428     return down_cast<InstructionCodeGeneratorX86_64*>(GetInstructionVisitor());
429   }
430 
431   const X86_64InstructionSetFeatures& GetInstructionSetFeatures() const;
432 
433   // Emit a write barrier.
434   void MarkGCCard(CpuRegister temp,
435                   CpuRegister card,
436                   CpuRegister object,
437                   CpuRegister value,
438                   bool value_can_be_null);
439 
440   void GenerateMemoryBarrier(MemBarrierKind kind);
441 
442   // Helper method to move a value between two locations.
443   void Move(Location destination, Location source);
444   // Helper method to load a value of non-reference type from memory.
445   void LoadFromMemoryNoReference(DataType::Type type, Location dst, Address src);
446 
GetLabelOf(HBasicBlock * block)447   Label* GetLabelOf(HBasicBlock* block) const {
448     return CommonGetLabelOf<Label>(block_labels_, block);
449   }
450 
Initialize()451   void Initialize() override {
452     block_labels_ = CommonInitializeLabels<Label>();
453   }
454 
NeedsTwoRegisters(DataType::Type type ATTRIBUTE_UNUSED)455   bool NeedsTwoRegisters(DataType::Type type ATTRIBUTE_UNUSED) const override {
456     return false;
457   }
458 
459   // Check if the desired_string_load_kind is supported. If it is, return it,
460   // otherwise return a fall-back kind that should be used instead.
461   HLoadString::LoadKind GetSupportedLoadStringKind(
462       HLoadString::LoadKind desired_string_load_kind) override;
463 
464   // Check if the desired_class_load_kind is supported. If it is, return it,
465   // otherwise return a fall-back kind that should be used instead.
466   HLoadClass::LoadKind GetSupportedLoadClassKind(
467       HLoadClass::LoadKind desired_class_load_kind) override;
468 
469   // Check if the desired_dispatch_info is supported. If it is, return it,
470   // otherwise return a fall-back info that should be used instead.
471   HInvokeStaticOrDirect::DispatchInfo GetSupportedInvokeStaticOrDirectDispatch(
472       const HInvokeStaticOrDirect::DispatchInfo& desired_dispatch_info,
473       ArtMethod* method) override;
474 
475   void LoadMethod(MethodLoadKind load_kind, Location temp, HInvoke* invoke);
476   void GenerateStaticOrDirectCall(
477       HInvokeStaticOrDirect* invoke, Location temp, SlowPathCode* slow_path = nullptr) override;
478   void GenerateVirtualCall(
479       HInvokeVirtual* invoke, Location temp, SlowPathCode* slow_path = nullptr) override;
480 
481   void RecordBootImageIntrinsicPatch(uint32_t intrinsic_data);
482   void RecordBootImageRelRoPatch(uint32_t boot_image_offset);
483   void RecordBootImageMethodPatch(HInvoke* invoke);
484   void RecordMethodBssEntryPatch(HInvoke* invoke);
485   void RecordBootImageTypePatch(const DexFile& dex_file, dex::TypeIndex type_index);
486   Label* NewTypeBssEntryPatch(HLoadClass* load_class);
487   void RecordBootImageStringPatch(HLoadString* load_string);
488   Label* NewStringBssEntryPatch(HLoadString* load_string);
489   void RecordBootImageJniEntrypointPatch(HInvokeStaticOrDirect* invoke);
490   Label* NewJitRootStringPatch(const DexFile& dex_file,
491                                dex::StringIndex string_index,
492                                Handle<mirror::String> handle);
493   Label* NewJitRootClassPatch(const DexFile& dex_file,
494                               dex::TypeIndex type_index,
495                               Handle<mirror::Class> handle);
496 
497   void LoadBootImageAddress(CpuRegister reg, uint32_t boot_image_reference);
498   void LoadIntrinsicDeclaringClass(CpuRegister reg, HInvoke* invoke);
499   void LoadClassRootForIntrinsic(CpuRegister reg, ClassRoot class_root);
500 
501   void EmitLinkerPatches(ArenaVector<linker::LinkerPatch>* linker_patches) override;
502 
503   void PatchJitRootUse(uint8_t* code,
504                        const uint8_t* roots_data,
505                        const PatchInfo<Label>& info,
506                        uint64_t index_in_table) const;
507 
508   void EmitJitRootPatches(uint8_t* code, const uint8_t* roots_data) override;
509 
510   // Fast path implementation of ReadBarrier::Barrier for a heap
511   // reference field load when Baker's read barriers are used.
512   void GenerateFieldLoadWithBakerReadBarrier(HInstruction* instruction,
513                                              Location ref,
514                                              CpuRegister obj,
515                                              uint32_t offset,
516                                              bool needs_null_check);
517   // Fast path implementation of ReadBarrier::Barrier for a heap
518   // reference array load when Baker's read barriers are used.
519   void GenerateArrayLoadWithBakerReadBarrier(HInstruction* instruction,
520                                              Location ref,
521                                              CpuRegister obj,
522                                              uint32_t data_offset,
523                                              Location index,
524                                              bool needs_null_check);
525   // Factored implementation, used by GenerateFieldLoadWithBakerReadBarrier,
526   // GenerateArrayLoadWithBakerReadBarrier and some intrinsics.
527   //
528   // Load the object reference located at address `src`, held by
529   // object `obj`, into `ref`, and mark it if needed.  The base of
530   // address `src` must be `obj`.
531   //
532   // If `always_update_field` is true, the value of the reference is
533   // atomically updated in the holder (`obj`).  This operation
534   // requires two temporary registers, which must be provided as
535   // non-null pointers (`temp1` and `temp2`).
536   void GenerateReferenceLoadWithBakerReadBarrier(HInstruction* instruction,
537                                                  Location ref,
538                                                  CpuRegister obj,
539                                                  const Address& src,
540                                                  bool needs_null_check,
541                                                  bool always_update_field = false,
542                                                  CpuRegister* temp1 = nullptr,
543                                                  CpuRegister* temp2 = nullptr);
544 
545   // Generate a read barrier for a heap reference within `instruction`
546   // using a slow path.
547   //
548   // A read barrier for an object reference read from the heap is
549   // implemented as a call to the artReadBarrierSlow runtime entry
550   // point, which is passed the values in locations `ref`, `obj`, and
551   // `offset`:
552   //
553   //   mirror::Object* artReadBarrierSlow(mirror::Object* ref,
554   //                                      mirror::Object* obj,
555   //                                      uint32_t offset);
556   //
557   // The `out` location contains the value returned by
558   // artReadBarrierSlow.
559   //
560   // When `index` provided (i.e., when it is different from
561   // Location::NoLocation()), the offset value passed to
562   // artReadBarrierSlow is adjusted to take `index` into account.
563   void GenerateReadBarrierSlow(HInstruction* instruction,
564                                Location out,
565                                Location ref,
566                                Location obj,
567                                uint32_t offset,
568                                Location index = Location::NoLocation());
569 
570   // If read barriers are enabled, generate a read barrier for a heap
571   // reference using a slow path. If heap poisoning is enabled, also
572   // unpoison the reference in `out`.
573   void MaybeGenerateReadBarrierSlow(HInstruction* instruction,
574                                     Location out,
575                                     Location ref,
576                                     Location obj,
577                                     uint32_t offset,
578                                     Location index = Location::NoLocation());
579 
580   // Generate a read barrier for a GC root within `instruction` using
581   // a slow path.
582   //
583   // A read barrier for an object reference GC root is implemented as
584   // a call to the artReadBarrierForRootSlow runtime entry point,
585   // which is passed the value in location `root`:
586   //
587   //   mirror::Object* artReadBarrierForRootSlow(GcRoot<mirror::Object>* root);
588   //
589   // The `out` location contains the value returned by
590   // artReadBarrierForRootSlow.
591   void GenerateReadBarrierForRootSlow(HInstruction* instruction, Location out, Location root);
592 
ConstantAreaStart()593   int ConstantAreaStart() const {
594     return constant_area_start_;
595   }
596 
597   Address LiteralDoubleAddress(double v);
598   Address LiteralFloatAddress(float v);
599   Address LiteralInt32Address(int32_t v);
600   Address LiteralInt64Address(int64_t v);
601 
602   // Load a 32/64-bit value into a register in the most efficient manner.
603   void Load32BitValue(CpuRegister dest, int32_t value);
604   void Load64BitValue(CpuRegister dest, int64_t value);
605   void Load32BitValue(XmmRegister dest, int32_t value);
606   void Load64BitValue(XmmRegister dest, int64_t value);
607   void Load32BitValue(XmmRegister dest, float value);
608   void Load64BitValue(XmmRegister dest, double value);
609 
610   // Compare a register with a 32/64-bit value in the most efficient manner.
611   void Compare32BitValue(CpuRegister dest, int32_t value);
612   void Compare64BitValue(CpuRegister dest, int64_t value);
613 
614   // Compare int values. Supports register locations for `lhs`.
615   void GenerateIntCompare(Location lhs, Location rhs);
616   void GenerateIntCompare(CpuRegister lhs, Location rhs);
617 
618   // Compare long values. Supports only register locations for `lhs`.
619   void GenerateLongCompare(Location lhs, Location rhs);
620 
621   // Construct address for array access.
622   static Address ArrayAddress(CpuRegister obj,
623                               Location index,
624                               ScaleFactor scale,
625                               uint32_t data_offset);
626 
627   Address LiteralCaseTable(HPackedSwitch* switch_instr);
628 
629   // Store a 64 bit value into a DoubleStackSlot in the most efficient manner.
630   void Store64BitValueToStack(Location dest, int64_t value);
631 
632   void MoveFromReturnRegister(Location trg, DataType::Type type) override;
633 
634   // Assign a 64 bit constant to an address.
635   void MoveInt64ToAddress(const Address& addr_low,
636                           const Address& addr_high,
637                           int64_t v,
638                           HInstruction* instruction);
639 
640   // Ensure that prior stores complete to memory before subsequent loads.
641   // The locked add implementation will avoid serializing device memory, but will
642   // touch (but not change) the top of the stack.
643   // The 'non_temporal' parameter should be used to ensure ordering of non-temporal stores.
644   void MemoryFence(bool force_mfence = false) {
645     if (!force_mfence) {
646       assembler_.lock()->addl(Address(CpuRegister(RSP), 0), Immediate(0));
647     } else {
648       assembler_.mfence();
649     }
650   }
651 
652   void IncreaseFrame(size_t adjustment) override;
653   void DecreaseFrame(size_t adjustment) override;
654 
655   void GenerateNop() override;
656   void GenerateImplicitNullCheck(HNullCheck* instruction) override;
657   void GenerateExplicitNullCheck(HNullCheck* instruction) override;
658   void MaybeGenerateInlineCacheCheck(HInstruction* instruction, CpuRegister cls);
659 
660   void MaybeIncrementHotness(bool is_frame_entry);
661 
662   static void BlockNonVolatileXmmRegisters(LocationSummary* locations);
663 
664   // When we don't know the proper offset for the value, we use kPlaceholder32BitOffset.
665   // We will fix this up in the linker later to have the right value.
666   static constexpr int32_t kPlaceholder32BitOffset = 256;
667 
668  private:
669   template <linker::LinkerPatch (*Factory)(size_t, const DexFile*, uint32_t, uint32_t)>
670   static void EmitPcRelativeLinkerPatches(const ArenaDeque<PatchInfo<Label>>& infos,
671                                           ArenaVector<linker::LinkerPatch>* linker_patches);
672 
673   // Labels for each block that will be compiled.
674   Label* block_labels_;  // Indexed by block id.
675   Label frame_entry_label_;
676   LocationsBuilderX86_64 location_builder_;
677   InstructionCodeGeneratorX86_64 instruction_visitor_;
678   ParallelMoveResolverX86_64 move_resolver_;
679   X86_64Assembler assembler_;
680 
681   // Offset to the start of the constant area in the assembled code.
682   // Used for fixups to the constant area.
683   int constant_area_start_;
684 
685   // PC-relative method patch info for kBootImageLinkTimePcRelative.
686   ArenaDeque<PatchInfo<Label>> boot_image_method_patches_;
687   // PC-relative method patch info for kBssEntry.
688   ArenaDeque<PatchInfo<Label>> method_bss_entry_patches_;
689   // PC-relative type patch info for kBootImageLinkTimePcRelative.
690   ArenaDeque<PatchInfo<Label>> boot_image_type_patches_;
691   // PC-relative type patch info for kBssEntry.
692   ArenaDeque<PatchInfo<Label>> type_bss_entry_patches_;
693   // PC-relative public type patch info for kBssEntryPublic.
694   ArenaDeque<PatchInfo<Label>> public_type_bss_entry_patches_;
695   // PC-relative package type patch info for kBssEntryPackage.
696   ArenaDeque<PatchInfo<Label>> package_type_bss_entry_patches_;
697   // PC-relative String patch info for kBootImageLinkTimePcRelative.
698   ArenaDeque<PatchInfo<Label>> boot_image_string_patches_;
699   // PC-relative String patch info for kBssEntry.
700   ArenaDeque<PatchInfo<Label>> string_bss_entry_patches_;
701   // PC-relative method patch info for kBootImageLinkTimePcRelative+kCallCriticalNative.
702   ArenaDeque<PatchInfo<Label>> boot_image_jni_entrypoint_patches_;
703   // PC-relative patch info for IntrinsicObjects for the boot image,
704   // and for method/type/string patches for kBootImageRelRo otherwise.
705   ArenaDeque<PatchInfo<Label>> boot_image_other_patches_;
706 
707   // Patches for string literals in JIT compiled code.
708   ArenaDeque<PatchInfo<Label>> jit_string_patches_;
709   // Patches for class literals in JIT compiled code.
710   ArenaDeque<PatchInfo<Label>> jit_class_patches_;
711 
712   // Fixups for jump tables need to be handled specially.
713   ArenaVector<JumpTableRIPFixup*> fixups_to_jump_tables_;
714 
715   DISALLOW_COPY_AND_ASSIGN(CodeGeneratorX86_64);
716 };
717 
718 }  // namespace x86_64
719 }  // namespace art
720 
721 #endif  // ART_COMPILER_OPTIMIZING_CODE_GENERATOR_X86_64_H_
722