mir_to_lir.h revision 306f017dd883c0bf806d239d97e0bca3194afbd7
1/*
2 * Copyright (C) 2012 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_DEX_QUICK_MIR_TO_LIR_H_
18#define ART_COMPILER_DEX_QUICK_MIR_TO_LIR_H_
19
20#include "invoke_type.h"
21#include "compiled_method.h"
22#include "dex/compiler_enums.h"
23#include "dex/compiler_ir.h"
24#include "dex/reg_storage.h"
25#include "dex/backend.h"
26#include "driver/compiler_driver.h"
27#include "leb128.h"
28#include "safe_map.h"
29#include "utils/arena_allocator.h"
30#include "utils/growable_array.h"
31
32namespace art {
33
34/*
35 * TODO: refactoring pass to move these (and other) typdefs towards usage style of runtime to
36 * add type safety (see runtime/offsets.h).
37 */
38typedef uint32_t DexOffset;          // Dex offset in code units.
39typedef uint16_t NarrowDexOffset;    // For use in structs, Dex offsets range from 0 .. 0xffff.
40typedef uint32_t CodeOffset;         // Native code offset in bytes.
41
42// Set to 1 to measure cost of suspend check.
43#define NO_SUSPEND 0
44
45#define IS_BINARY_OP         (1ULL << kIsBinaryOp)
46#define IS_BRANCH            (1ULL << kIsBranch)
47#define IS_IT                (1ULL << kIsIT)
48#define IS_LOAD              (1ULL << kMemLoad)
49#define IS_QUAD_OP           (1ULL << kIsQuadOp)
50#define IS_QUIN_OP           (1ULL << kIsQuinOp)
51#define IS_SEXTUPLE_OP       (1ULL << kIsSextupleOp)
52#define IS_STORE             (1ULL << kMemStore)
53#define IS_TERTIARY_OP       (1ULL << kIsTertiaryOp)
54#define IS_UNARY_OP          (1ULL << kIsUnaryOp)
55#define NEEDS_FIXUP          (1ULL << kPCRelFixup)
56#define NO_OPERAND           (1ULL << kNoOperand)
57#define REG_DEF0             (1ULL << kRegDef0)
58#define REG_DEF1             (1ULL << kRegDef1)
59#define REG_DEF2             (1ULL << kRegDef2)
60#define REG_DEFA             (1ULL << kRegDefA)
61#define REG_DEFD             (1ULL << kRegDefD)
62#define REG_DEF_FPCS_LIST0   (1ULL << kRegDefFPCSList0)
63#define REG_DEF_FPCS_LIST2   (1ULL << kRegDefFPCSList2)
64#define REG_DEF_LIST0        (1ULL << kRegDefList0)
65#define REG_DEF_LIST1        (1ULL << kRegDefList1)
66#define REG_DEF_LR           (1ULL << kRegDefLR)
67#define REG_DEF_SP           (1ULL << kRegDefSP)
68#define REG_USE0             (1ULL << kRegUse0)
69#define REG_USE1             (1ULL << kRegUse1)
70#define REG_USE2             (1ULL << kRegUse2)
71#define REG_USE3             (1ULL << kRegUse3)
72#define REG_USE4             (1ULL << kRegUse4)
73#define REG_USEA             (1ULL << kRegUseA)
74#define REG_USEC             (1ULL << kRegUseC)
75#define REG_USED             (1ULL << kRegUseD)
76#define REG_USEB             (1ULL << kRegUseB)
77#define REG_USE_FPCS_LIST0   (1ULL << kRegUseFPCSList0)
78#define REG_USE_FPCS_LIST2   (1ULL << kRegUseFPCSList2)
79#define REG_USE_LIST0        (1ULL << kRegUseList0)
80#define REG_USE_LIST1        (1ULL << kRegUseList1)
81#define REG_USE_LR           (1ULL << kRegUseLR)
82#define REG_USE_PC           (1ULL << kRegUsePC)
83#define REG_USE_SP           (1ULL << kRegUseSP)
84#define SETS_CCODES          (1ULL << kSetsCCodes)
85#define USES_CCODES          (1ULL << kUsesCCodes)
86#define USE_FP_STACK         (1ULL << kUseFpStack)
87
88// Common combo register usage patterns.
89#define REG_DEF01            (REG_DEF0 | REG_DEF1)
90#define REG_DEF01_USE2       (REG_DEF0 | REG_DEF1 | REG_USE2)
91#define REG_DEF0_USE01       (REG_DEF0 | REG_USE01)
92#define REG_DEF0_USE0        (REG_DEF0 | REG_USE0)
93#define REG_DEF0_USE12       (REG_DEF0 | REG_USE12)
94#define REG_DEF0_USE123      (REG_DEF0 | REG_USE123)
95#define REG_DEF0_USE1        (REG_DEF0 | REG_USE1)
96#define REG_DEF0_USE2        (REG_DEF0 | REG_USE2)
97#define REG_DEFAD_USEAD      (REG_DEFAD_USEA | REG_USED)
98#define REG_DEFAD_USEA       (REG_DEFA_USEA | REG_DEFD)
99#define REG_DEFA_USEA        (REG_DEFA | REG_USEA)
100#define REG_USE012           (REG_USE01 | REG_USE2)
101#define REG_USE014           (REG_USE01 | REG_USE4)
102#define REG_USE01            (REG_USE0 | REG_USE1)
103#define REG_USE02            (REG_USE0 | REG_USE2)
104#define REG_USE12            (REG_USE1 | REG_USE2)
105#define REG_USE23            (REG_USE2 | REG_USE3)
106#define REG_USE123           (REG_USE1 | REG_USE2 | REG_USE3)
107
108struct BasicBlock;
109struct CallInfo;
110struct CompilationUnit;
111struct InlineMethod;
112struct MIR;
113struct LIR;
114struct RegLocation;
115struct RegisterInfo;
116class DexFileMethodInliner;
117class MIRGraph;
118class Mir2Lir;
119
120typedef int (*NextCallInsn)(CompilationUnit*, CallInfo*, int,
121                            const MethodReference& target_method,
122                            uint32_t method_idx, uintptr_t direct_code,
123                            uintptr_t direct_method, InvokeType type);
124
125typedef std::vector<uint8_t> CodeBuffer;
126
127struct UseDefMasks {
128  uint64_t use_mask;        // Resource mask for use.
129  uint64_t def_mask;        // Resource mask for def.
130};
131
132struct AssemblyInfo {
133  LIR* pcrel_next;           // Chain of LIR nodes needing pc relative fixups.
134};
135
136struct LIR {
137  CodeOffset offset;             // Offset of this instruction.
138  NarrowDexOffset dalvik_offset;   // Offset of Dalvik opcode in code units (16-bit words).
139  int16_t opcode;
140  LIR* next;
141  LIR* prev;
142  LIR* target;
143  struct {
144    unsigned int alias_info:17;  // For Dalvik register disambiguation.
145    bool is_nop:1;               // LIR is optimized away.
146    unsigned int size:4;         // Note: size of encoded instruction is in bytes.
147    bool use_def_invalid:1;      // If true, masks should not be used.
148    unsigned int generation:1;   // Used to track visitation state during fixup pass.
149    unsigned int fixup:8;        // Fixup kind.
150  } flags;
151  union {
152    UseDefMasks m;               // Use & Def masks used during optimization.
153    AssemblyInfo a;              // Instruction info used during assembly phase.
154  } u;
155  int32_t operands[5];           // [0..4] = [dest, src1, src2, extra, extra2].
156};
157
158// Target-specific initialization.
159Mir2Lir* ArmCodeGenerator(CompilationUnit* const cu, MIRGraph* const mir_graph,
160                          ArenaAllocator* const arena);
161Mir2Lir* MipsCodeGenerator(CompilationUnit* const cu, MIRGraph* const mir_graph,
162                          ArenaAllocator* const arena);
163Mir2Lir* X86CodeGenerator(CompilationUnit* const cu, MIRGraph* const mir_graph,
164                          ArenaAllocator* const arena);
165
166// Utility macros to traverse the LIR list.
167#define NEXT_LIR(lir) (lir->next)
168#define PREV_LIR(lir) (lir->prev)
169
170// Defines for alias_info (tracks Dalvik register references).
171#define DECODE_ALIAS_INFO_REG(X)        (X & 0xffff)
172#define DECODE_ALIAS_INFO_WIDE_FLAG     (0x10000)
173#define DECODE_ALIAS_INFO_WIDE(X)       ((X & DECODE_ALIAS_INFO_WIDE_FLAG) ? 1 : 0)
174#define ENCODE_ALIAS_INFO(REG, ISWIDE)  (REG | (ISWIDE ? DECODE_ALIAS_INFO_WIDE_FLAG : 0))
175
176// Common resource macros.
177#define ENCODE_CCODE            (1ULL << kCCode)
178#define ENCODE_FP_STATUS        (1ULL << kFPStatus)
179
180// Abstract memory locations.
181#define ENCODE_DALVIK_REG       (1ULL << kDalvikReg)
182#define ENCODE_LITERAL          (1ULL << kLiteral)
183#define ENCODE_HEAP_REF         (1ULL << kHeapRef)
184#define ENCODE_MUST_NOT_ALIAS   (1ULL << kMustNotAlias)
185
186#define ENCODE_ALL              (~0ULL)
187#define ENCODE_MEM              (ENCODE_DALVIK_REG | ENCODE_LITERAL | \
188                                 ENCODE_HEAP_REF | ENCODE_MUST_NOT_ALIAS)
189
190#define ENCODE_REG_PAIR(low_reg, high_reg) ((low_reg & 0xff) | ((high_reg & 0xff) << 8))
191#define DECODE_REG_PAIR(both_regs, low_reg, high_reg) \
192  do { \
193    low_reg = both_regs & 0xff; \
194    high_reg = (both_regs >> 8) & 0xff; \
195  } while (false)
196
197// Mask to denote sreg as the start of a double.  Must not interfere with low 16 bits.
198#define STARTING_DOUBLE_SREG 0x10000
199
200// TODO: replace these macros
201#define SLOW_FIELD_PATH (cu_->enable_debug & (1 << kDebugSlowFieldPath))
202#define SLOW_INVOKE_PATH (cu_->enable_debug & (1 << kDebugSlowInvokePath))
203#define SLOW_STRING_PATH (cu_->enable_debug & (1 << kDebugSlowStringPath))
204#define SLOW_TYPE_PATH (cu_->enable_debug & (1 << kDebugSlowTypePath))
205#define EXERCISE_SLOWEST_STRING_PATH (cu_->enable_debug & (1 << kDebugSlowestStringPath))
206
207class Mir2Lir : public Backend {
208  public:
209    /*
210     * Auxiliary information describing the location of data embedded in the Dalvik
211     * byte code stream.
212     */
213    struct EmbeddedData {
214      CodeOffset offset;        // Code offset of data block.
215      const uint16_t* table;      // Original dex data.
216      DexOffset vaddr;            // Dalvik offset of parent opcode.
217    };
218
219    struct FillArrayData : EmbeddedData {
220      int32_t size;
221    };
222
223    struct SwitchTable : EmbeddedData {
224      LIR* anchor;                // Reference instruction for relative offsets.
225      LIR** targets;              // Array of case targets.
226    };
227
228    /* Static register use counts */
229    struct RefCounts {
230      int count;
231      int s_reg;
232    };
233
234    /*
235     * Data structure tracking the mapping between a Dalvik register (pair) and a
236     * native register (pair). The idea is to reuse the previously loaded value
237     * if possible, otherwise to keep the value in a native register as long as
238     * possible.
239     */
240    struct RegisterInfo {
241      int reg;                    // Reg number
242      bool in_use;                // Has it been allocated?
243      bool is_temp;               // Can allocate as temp?
244      bool pair;                  // Part of a register pair?
245      int partner;                // If pair, other reg of pair.
246      bool live;                  // Is there an associated SSA name?
247      bool dirty;                 // If live, is it dirty?
248      int s_reg;                  // Name of live value.
249      LIR *def_start;             // Starting inst in last def sequence.
250      LIR *def_end;               // Ending inst in last def sequence.
251    };
252
253    struct RegisterPool {
254       int num_core_regs;
255       RegisterInfo *core_regs;
256       int next_core_reg;
257       int num_fp_regs;
258       RegisterInfo *FPRegs;
259       int next_fp_reg;
260     };
261
262    struct PromotionMap {
263      RegLocationType core_location:3;
264      uint8_t core_reg;
265      RegLocationType fp_location:3;
266      uint8_t FpReg;
267      bool first_in_pair;
268    };
269
270    //
271    // Slow paths.  This object is used generate a sequence of code that is executed in the
272    // slow path.  For example, resolving a string or class is slow as it will only be executed
273    // once (after that it is resolved and doesn't need to be done again).  We want slow paths
274    // to be placed out-of-line, and not require a (mispredicted, probably) conditional forward
275    // branch over them.
276    //
277    // If you want to create a slow path, declare a class derived from LIRSlowPath and provide
278    // the Compile() function that will be called near the end of the code generated by the
279    // method.
280    //
281    // The basic flow for a slow path is:
282    //
283    //     CMP reg, #value
284    //     BEQ fromfast
285    //   cont:
286    //     ...
287    //     fast path code
288    //     ...
289    //     more code
290    //     ...
291    //     RETURN
292    ///
293    //   fromfast:
294    //     ...
295    //     slow path code
296    //     ...
297    //     B cont
298    //
299    // So you see we need two labels and two branches.  The first branch (called fromfast) is
300    // the conditional branch to the slow path code.  The second label (called cont) is used
301    // as an unconditional branch target for getting back to the code after the slow path
302    // has completed.
303    //
304
305    class LIRSlowPath {
306     public:
307      LIRSlowPath(Mir2Lir* m2l, const DexOffset dexpc, LIR* fromfast,
308                  LIR* cont = nullptr) :
309        m2l_(m2l), current_dex_pc_(dexpc), fromfast_(fromfast), cont_(cont) {
310      }
311      virtual ~LIRSlowPath() {}
312      virtual void Compile() = 0;
313
314      static void* operator new(size_t size, ArenaAllocator* arena) {
315        return arena->Alloc(size, kArenaAllocData);
316      }
317
318     protected:
319      LIR* GenerateTargetLabel();
320
321      Mir2Lir* const m2l_;
322      const DexOffset current_dex_pc_;
323      LIR* const fromfast_;
324      LIR* const cont_;
325    };
326
327    virtual ~Mir2Lir() {}
328
329    int32_t s4FromSwitchData(const void* switch_data) {
330      return *reinterpret_cast<const int32_t*>(switch_data);
331    }
332
333    RegisterClass oat_reg_class_by_size(OpSize size) {
334      return (size == kUnsignedHalf || size == kSignedHalf || size == kUnsignedByte ||
335              size == kSignedByte) ? kCoreReg : kAnyReg;
336    }
337
338    size_t CodeBufferSizeInBytes() {
339      return code_buffer_.size() / sizeof(code_buffer_[0]);
340    }
341
342    static bool IsPseudoLirOp(int opcode) {
343      return (opcode < 0);
344    }
345
346    /*
347     * LIR operands are 32-bit integers.  Sometimes, (especially for managing
348     * instructions which require PC-relative fixups), we need the operands to carry
349     * pointers.  To do this, we assign these pointers an index in pointer_storage_, and
350     * hold that index in the operand array.
351     * TUNING: If use of these utilities becomes more common on 32-bit builds, it
352     * may be worth conditionally-compiling a set of identity functions here.
353     */
354    uint32_t WrapPointer(void* pointer) {
355      uint32_t res = pointer_storage_.Size();
356      pointer_storage_.Insert(pointer);
357      return res;
358    }
359
360    void* UnwrapPointer(size_t index) {
361      return pointer_storage_.Get(index);
362    }
363
364    // strdup(), but allocates from the arena.
365    char* ArenaStrdup(const char* str) {
366      size_t len = strlen(str) + 1;
367      char* res = reinterpret_cast<char*>(arena_->Alloc(len, kArenaAllocMisc));
368      if (res != NULL) {
369        strncpy(res, str, len);
370      }
371      return res;
372    }
373
374    // Shared by all targets - implemented in codegen_util.cc
375    void AppendLIR(LIR* lir);
376    void InsertLIRBefore(LIR* current_lir, LIR* new_lir);
377    void InsertLIRAfter(LIR* current_lir, LIR* new_lir);
378
379    /**
380     * @brief Provides the maximum number of compiler temporaries that the backend can/wants
381     * to place in a frame.
382     * @return Returns the maximum number of compiler temporaries.
383     */
384    size_t GetMaxPossibleCompilerTemps() const;
385
386    /**
387     * @brief Provides the number of bytes needed in frame for spilling of compiler temporaries.
388     * @return Returns the size in bytes for space needed for compiler temporary spill region.
389     */
390    size_t GetNumBytesForCompilerTempSpillRegion();
391
392    DexOffset GetCurrentDexPc() const {
393      return current_dalvik_offset_;
394    }
395
396    int ComputeFrameSize();
397    virtual void Materialize();
398    virtual CompiledMethod* GetCompiledMethod();
399    void MarkSafepointPC(LIR* inst);
400    void SetupResourceMasks(LIR* lir);
401    void SetMemRefType(LIR* lir, bool is_load, int mem_type);
402    void AnnotateDalvikRegAccess(LIR* lir, int reg_id, bool is_load, bool is64bit);
403    void SetupRegMask(uint64_t* mask, int reg);
404    void DumpLIRInsn(LIR* arg, unsigned char* base_addr);
405    void DumpPromotionMap();
406    void CodegenDump();
407    LIR* RawLIR(DexOffset dalvik_offset, int opcode, int op0 = 0, int op1 = 0,
408                int op2 = 0, int op3 = 0, int op4 = 0, LIR* target = NULL);
409    LIR* NewLIR0(int opcode);
410    LIR* NewLIR1(int opcode, int dest);
411    LIR* NewLIR2(int opcode, int dest, int src1);
412    LIR* NewLIR2NoDest(int opcode, int src, int info);
413    LIR* NewLIR3(int opcode, int dest, int src1, int src2);
414    LIR* NewLIR4(int opcode, int dest, int src1, int src2, int info);
415    LIR* NewLIR5(int opcode, int dest, int src1, int src2, int info1, int info2);
416    LIR* ScanLiteralPool(LIR* data_target, int value, unsigned int delta);
417    LIR* ScanLiteralPoolWide(LIR* data_target, int val_lo, int val_hi);
418    LIR* AddWordData(LIR* *constant_list_p, int value);
419    LIR* AddWideData(LIR* *constant_list_p, int val_lo, int val_hi);
420    void ProcessSwitchTables();
421    void DumpSparseSwitchTable(const uint16_t* table);
422    void DumpPackedSwitchTable(const uint16_t* table);
423    void MarkBoundary(DexOffset offset, const char* inst_str);
424    void NopLIR(LIR* lir);
425    void UnlinkLIR(LIR* lir);
426    bool EvaluateBranch(Instruction::Code opcode, int src1, int src2);
427    bool IsInexpensiveConstant(RegLocation rl_src);
428    ConditionCode FlipComparisonOrder(ConditionCode before);
429    ConditionCode NegateComparison(ConditionCode before);
430    virtual void InstallLiteralPools();
431    void InstallSwitchTables();
432    void InstallFillArrayData();
433    bool VerifyCatchEntries();
434    void CreateMappingTables();
435    void CreateNativeGcMap();
436    int AssignLiteralOffset(CodeOffset offset);
437    int AssignSwitchTablesOffset(CodeOffset offset);
438    int AssignFillArrayDataOffset(CodeOffset offset);
439    LIR* InsertCaseLabel(DexOffset vaddr, int keyVal);
440    void MarkPackedCaseLabels(Mir2Lir::SwitchTable* tab_rec);
441    void MarkSparseCaseLabels(Mir2Lir::SwitchTable* tab_rec);
442    // Handle bookkeeping to convert a wide RegLocation to a narow RegLocation.  No code generated.
443    RegLocation NarrowRegLoc(RegLocation loc);
444
445    // Shared by all targets - implemented in local_optimizations.cc
446    void ConvertMemOpIntoMove(LIR* orig_lir, RegStorage dest, RegStorage src);
447    void ApplyLoadStoreElimination(LIR* head_lir, LIR* tail_lir);
448    void ApplyLoadHoisting(LIR* head_lir, LIR* tail_lir);
449    void ApplyLocalOptimizations(LIR* head_lir, LIR* tail_lir);
450
451    // Shared by all targets - implemented in ralloc_util.cc
452    int GetSRegHi(int lowSreg);
453    bool oat_live_out(int s_reg);
454    int oatSSASrc(MIR* mir, int num);
455    void SimpleRegAlloc();
456    void ResetRegPool();
457    void CompilerInitPool(RegisterInfo* regs, int* reg_nums, int num);
458    void DumpRegPool(RegisterInfo* p, int num_regs);
459    void DumpCoreRegPool();
460    void DumpFpRegPool();
461    /* Mark a temp register as dead.  Does not affect allocation state. */
462    void Clobber(int reg) {
463      ClobberBody(GetRegInfo(reg));
464    }
465    void Clobber(RegStorage reg);
466    void ClobberSRegBody(RegisterInfo* p, int num_regs, int s_reg);
467    void ClobberSReg(int s_reg);
468    int SRegToPMap(int s_reg);
469    void RecordCorePromotion(RegStorage reg, int s_reg);
470    RegStorage AllocPreservedCoreReg(int s_reg);
471    void RecordFpPromotion(RegStorage reg, int s_reg);
472    RegStorage AllocPreservedSingle(int s_reg);
473    RegStorage AllocPreservedDouble(int s_reg);
474    RegStorage AllocTempBody(RegisterInfo* p, int num_regs, int* next_temp, bool required);
475    virtual RegStorage AllocTempDouble();
476    RegStorage AllocFreeTemp();
477    RegStorage AllocTemp();
478    RegStorage AllocTempFloat();
479    RegisterInfo* AllocLiveBody(RegisterInfo* p, int num_regs, int s_reg);
480    RegisterInfo* AllocLive(int s_reg, int reg_class);
481    void FreeTemp(int reg);
482    void FreeTemp(RegStorage reg);
483    RegisterInfo* IsLive(int reg);
484    bool IsLive(RegStorage reg);
485    RegisterInfo* IsTemp(int reg);
486    bool IsTemp(RegStorage reg);
487    RegisterInfo* IsPromoted(int reg);
488    bool IsPromoted(RegStorage reg);
489    bool IsDirty(int reg);
490    bool IsDirty(RegStorage reg);
491    void LockTemp(int reg);
492    void LockTemp(RegStorage reg);
493    void ResetDef(int reg);
494    void ResetDef(RegStorage reg);
495    void NullifyRange(LIR *start, LIR *finish, int s_reg1, int s_reg2);
496    void MarkDef(RegLocation rl, LIR *start, LIR *finish);
497    void MarkDefWide(RegLocation rl, LIR *start, LIR *finish);
498    RegLocation WideToNarrow(RegLocation rl);
499    void ResetDefLoc(RegLocation rl);
500    virtual void ResetDefLocWide(RegLocation rl);
501    void ResetDefTracking();
502    void ClobberAllRegs();
503    void FlushSpecificReg(RegisterInfo* info);
504    void FlushAllRegsBody(RegisterInfo* info, int num_regs);
505    void FlushAllRegs();
506    bool RegClassMatches(int reg_class, RegStorage reg);
507    void MarkLive(RegStorage reg, int s_reg);
508    void MarkTemp(int reg);
509    void MarkTemp(RegStorage reg);
510    void UnmarkTemp(int reg);
511    void UnmarkTemp(RegStorage reg);
512    void MarkPair(int low_reg, int high_reg);
513    void MarkClean(RegLocation loc);
514    void MarkDirty(RegLocation loc);
515    void MarkInUse(int reg);
516    void MarkInUse(RegStorage reg);
517    void CopyRegInfo(int new_reg, int old_reg);
518    void CopyRegInfo(RegStorage new_reg, RegStorage old_reg);
519    bool CheckCorePoolSanity();
520    RegLocation UpdateLoc(RegLocation loc);
521    virtual RegLocation UpdateLocWide(RegLocation loc);
522    RegLocation UpdateRawLoc(RegLocation loc);
523
524    /**
525     * @brief Used to load register location into a typed temporary or pair of temporaries.
526     * @see EvalLoc
527     * @param loc The register location to load from.
528     * @param reg_class Type of register needed.
529     * @param update Whether the liveness information should be updated.
530     * @return Returns the properly typed temporary in physical register pairs.
531     */
532    virtual RegLocation EvalLocWide(RegLocation loc, int reg_class, bool update);
533
534    /**
535     * @brief Used to load register location into a typed temporary.
536     * @param loc The register location to load from.
537     * @param reg_class Type of register needed.
538     * @param update Whether the liveness information should be updated.
539     * @return Returns the properly typed temporary in physical register.
540     */
541    virtual RegLocation EvalLoc(RegLocation loc, int reg_class, bool update);
542
543    void CountRefs(RefCounts* core_counts, RefCounts* fp_counts, size_t num_regs);
544    void DumpCounts(const RefCounts* arr, int size, const char* msg);
545    void DoPromotion();
546    int VRegOffset(int v_reg);
547    int SRegOffset(int s_reg);
548    RegLocation GetReturnWide(bool is_double);
549    RegLocation GetReturn(bool is_float);
550    RegisterInfo* GetRegInfo(int reg);
551
552    // Shared by all targets - implemented in gen_common.cc.
553    void AddIntrinsicLaunchpad(CallInfo* info, LIR* branch, LIR* resume = nullptr);
554    bool HandleEasyDivRem(Instruction::Code dalvik_opcode, bool is_div,
555                          RegLocation rl_src, RegLocation rl_dest, int lit);
556    bool HandleEasyMultiply(RegLocation rl_src, RegLocation rl_dest, int lit);
557    void HandleSuspendLaunchPads();
558    void HandleThrowLaunchPads();
559    void HandleSlowPaths();
560    void GenBarrier();
561    LIR* GenCheck(ConditionCode c_code, ThrowKind kind);
562    void MarkPossibleNullPointerException(int opt_flags);
563    void MarkPossibleStackOverflowException();
564    void ForceImplicitNullCheck(RegStorage reg, int opt_flags);
565    LIR* GenImmedCheck(ConditionCode c_code, RegStorage reg, int imm_val, ThrowKind kind);
566    LIR* GenNullCheck(RegStorage m_reg, int opt_flags);
567    LIR* GenRegRegCheck(ConditionCode c_code, RegStorage reg1, RegStorage reg2, ThrowKind kind);
568    void GenCompareAndBranch(Instruction::Code opcode, RegLocation rl_src1,
569                             RegLocation rl_src2, LIR* taken, LIR* fall_through);
570    void GenCompareZeroAndBranch(Instruction::Code opcode, RegLocation rl_src,
571                                 LIR* taken, LIR* fall_through);
572    void GenIntToLong(RegLocation rl_dest, RegLocation rl_src);
573    void GenIntNarrowing(Instruction::Code opcode, RegLocation rl_dest,
574                         RegLocation rl_src);
575    void GenNewArray(uint32_t type_idx, RegLocation rl_dest,
576                     RegLocation rl_src);
577    void GenFilledNewArray(CallInfo* info);
578    void GenSput(MIR* mir, RegLocation rl_src,
579                 bool is_long_or_double, bool is_object);
580    void GenSget(MIR* mir, RegLocation rl_dest,
581                 bool is_long_or_double, bool is_object);
582    void GenIGet(MIR* mir, int opt_flags, OpSize size,
583                 RegLocation rl_dest, RegLocation rl_obj, bool is_long_or_double, bool is_object);
584    void GenIPut(MIR* mir, int opt_flags, OpSize size,
585                 RegLocation rl_src, RegLocation rl_obj, bool is_long_or_double, bool is_object);
586    void GenArrayObjPut(int opt_flags, RegLocation rl_array, RegLocation rl_index,
587                        RegLocation rl_src);
588
589    void GenConstClass(uint32_t type_idx, RegLocation rl_dest);
590    void GenConstString(uint32_t string_idx, RegLocation rl_dest);
591    void GenNewInstance(uint32_t type_idx, RegLocation rl_dest);
592    void GenThrow(RegLocation rl_src);
593    void GenInstanceof(uint32_t type_idx, RegLocation rl_dest, RegLocation rl_src);
594    void GenCheckCast(uint32_t insn_idx, uint32_t type_idx, RegLocation rl_src);
595    void GenLong3Addr(OpKind first_op, OpKind second_op, RegLocation rl_dest,
596                      RegLocation rl_src1, RegLocation rl_src2);
597    void GenShiftOpLong(Instruction::Code opcode, RegLocation rl_dest,
598                        RegLocation rl_src1, RegLocation rl_shift);
599    void GenArithOpIntLit(Instruction::Code opcode, RegLocation rl_dest,
600                          RegLocation rl_src, int lit);
601    void GenArithOpLong(Instruction::Code opcode, RegLocation rl_dest,
602                        RegLocation rl_src1, RegLocation rl_src2);
603    void GenConversionCall(ThreadOffset func_offset, RegLocation rl_dest,
604                           RegLocation rl_src);
605    void GenSuspendTest(int opt_flags);
606    void GenSuspendTestAndBranch(int opt_flags, LIR* target);
607
608    // This will be overridden by x86 implementation.
609    virtual void GenConstWide(RegLocation rl_dest, int64_t value);
610    virtual void GenArithOpInt(Instruction::Code opcode, RegLocation rl_dest,
611                       RegLocation rl_src1, RegLocation rl_src2);
612
613    // Shared by all targets - implemented in gen_invoke.cc.
614    LIR* CallHelper(RegStorage r_tgt, ThreadOffset helper_offset, bool safepoint_pc,
615                    bool use_link = true);
616    RegStorage CallHelperSetup(ThreadOffset helper_offset);
617    void CallRuntimeHelperImm(ThreadOffset helper_offset, int arg0, bool safepoint_pc);
618    void CallRuntimeHelperReg(ThreadOffset helper_offset, RegStorage arg0, bool safepoint_pc);
619    void CallRuntimeHelperRegLocation(ThreadOffset helper_offset, RegLocation arg0,
620                                      bool safepoint_pc);
621    void CallRuntimeHelperImmImm(ThreadOffset helper_offset, int arg0, int arg1,
622                                 bool safepoint_pc);
623    void CallRuntimeHelperImmRegLocation(ThreadOffset helper_offset, int arg0,
624                                         RegLocation arg1, bool safepoint_pc);
625    void CallRuntimeHelperRegLocationImm(ThreadOffset helper_offset, RegLocation arg0,
626                                         int arg1, bool safepoint_pc);
627    void CallRuntimeHelperImmReg(ThreadOffset helper_offset, int arg0, RegStorage arg1,
628                                 bool safepoint_pc);
629    void CallRuntimeHelperRegImm(ThreadOffset helper_offset, RegStorage arg0, int arg1,
630                                 bool safepoint_pc);
631    void CallRuntimeHelperImmMethod(ThreadOffset helper_offset, int arg0,
632                                    bool safepoint_pc);
633    void CallRuntimeHelperRegMethod(ThreadOffset helper_offset, RegStorage arg0, bool safepoint_pc);
634    void CallRuntimeHelperRegMethodRegLocation(ThreadOffset helper_offset, RegStorage arg0,
635                                               RegLocation arg2, bool safepoint_pc);
636    void CallRuntimeHelperRegLocationRegLocation(ThreadOffset helper_offset,
637                                                 RegLocation arg0, RegLocation arg1,
638                                                 bool safepoint_pc);
639    void CallRuntimeHelperRegReg(ThreadOffset helper_offset, RegStorage arg0, RegStorage arg1,
640                                 bool safepoint_pc);
641    void CallRuntimeHelperRegRegImm(ThreadOffset helper_offset, RegStorage arg0, RegStorage arg1,
642                                    int arg2, bool safepoint_pc);
643    void CallRuntimeHelperImmMethodRegLocation(ThreadOffset helper_offset, int arg0,
644                                               RegLocation arg2, bool safepoint_pc);
645    void CallRuntimeHelperImmMethodImm(ThreadOffset helper_offset, int arg0, int arg2,
646                                       bool safepoint_pc);
647    void CallRuntimeHelperImmRegLocationRegLocation(ThreadOffset helper_offset,
648                                                    int arg0, RegLocation arg1, RegLocation arg2,
649                                                    bool safepoint_pc);
650    void CallRuntimeHelperRegLocationRegLocationRegLocation(ThreadOffset helper_offset,
651                                                            RegLocation arg0, RegLocation arg1,
652                                                            RegLocation arg2,
653                                                            bool safepoint_pc);
654    void GenInvoke(CallInfo* info);
655    void GenInvokeNoInline(CallInfo* info);
656    void FlushIns(RegLocation* ArgLocs, RegLocation rl_method);
657    int GenDalvikArgsNoRange(CallInfo* info, int call_state, LIR** pcrLabel,
658                             NextCallInsn next_call_insn,
659                             const MethodReference& target_method,
660                             uint32_t vtable_idx,
661                             uintptr_t direct_code, uintptr_t direct_method, InvokeType type,
662                             bool skip_this);
663    int GenDalvikArgsRange(CallInfo* info, int call_state, LIR** pcrLabel,
664                           NextCallInsn next_call_insn,
665                           const MethodReference& target_method,
666                           uint32_t vtable_idx,
667                           uintptr_t direct_code, uintptr_t direct_method, InvokeType type,
668                           bool skip_this);
669
670    /**
671     * @brief Used to determine the register location of destination.
672     * @details This is needed during generation of inline intrinsics because it finds destination of return,
673     * either the physical register or the target of move-result.
674     * @param info Information about the invoke.
675     * @return Returns the destination location.
676     */
677    RegLocation InlineTarget(CallInfo* info);
678
679    /**
680     * @brief Used to determine the wide register location of destination.
681     * @see InlineTarget
682     * @param info Information about the invoke.
683     * @return Returns the destination location.
684     */
685    RegLocation InlineTargetWide(CallInfo* info);
686
687    bool GenInlinedCharAt(CallInfo* info);
688    bool GenInlinedStringIsEmptyOrLength(CallInfo* info, bool is_empty);
689    bool GenInlinedReverseBytes(CallInfo* info, OpSize size);
690    bool GenInlinedAbsInt(CallInfo* info);
691    bool GenInlinedAbsLong(CallInfo* info);
692    bool GenInlinedAbsFloat(CallInfo* info);
693    bool GenInlinedAbsDouble(CallInfo* info);
694    bool GenInlinedFloatCvt(CallInfo* info);
695    bool GenInlinedDoubleCvt(CallInfo* info);
696    virtual bool GenInlinedIndexOf(CallInfo* info, bool zero_based);
697    bool GenInlinedStringCompareTo(CallInfo* info);
698    bool GenInlinedCurrentThread(CallInfo* info);
699    bool GenInlinedUnsafeGet(CallInfo* info, bool is_long, bool is_volatile);
700    bool GenInlinedUnsafePut(CallInfo* info, bool is_long, bool is_object,
701                             bool is_volatile, bool is_ordered);
702    int LoadArgRegs(CallInfo* info, int call_state,
703                    NextCallInsn next_call_insn,
704                    const MethodReference& target_method,
705                    uint32_t vtable_idx,
706                    uintptr_t direct_code, uintptr_t direct_method, InvokeType type,
707                    bool skip_this);
708
709    // Shared by all targets - implemented in gen_loadstore.cc.
710    RegLocation LoadCurrMethod();
711    void LoadCurrMethodDirect(RegStorage r_tgt);
712    LIR* LoadConstant(RegStorage r_dest, int value);
713    LIR* LoadWordDisp(RegStorage r_base, int displacement, RegStorage r_dest);
714    RegLocation LoadValue(RegLocation rl_src, RegisterClass op_kind);
715    RegLocation LoadValueWide(RegLocation rl_src, RegisterClass op_kind);
716    void LoadValueDirect(RegLocation rl_src, RegStorage r_dest);
717    void LoadValueDirectFixed(RegLocation rl_src, RegStorage r_dest);
718    void LoadValueDirectWide(RegLocation rl_src, RegStorage r_dest);
719    void LoadValueDirectWideFixed(RegLocation rl_src, RegStorage r_dest);
720    LIR* StoreWordDisp(RegStorage r_base, int displacement, RegStorage r_src);
721
722    /**
723     * @brief Used to do the final store in the destination as per bytecode semantics.
724     * @param rl_dest The destination dalvik register location.
725     * @param rl_src The source register location. Can be either physical register or dalvik register.
726     */
727    void StoreValue(RegLocation rl_dest, RegLocation rl_src);
728
729    /**
730     * @brief Used to do the final store in a wide destination as per bytecode semantics.
731     * @see StoreValue
732     * @param rl_dest The destination dalvik register location.
733     * @param rl_src The source register location. Can be either physical register or dalvik register.
734     */
735    void StoreValueWide(RegLocation rl_dest, RegLocation rl_src);
736
737    /**
738     * @brief Used to do the final store to a destination as per bytecode semantics.
739     * @see StoreValue
740     * @param rl_dest The destination dalvik register location.
741     * @param rl_src The source register location. It must be kLocPhysReg
742     *
743     * This is used for x86 two operand computations, where we have computed the correct
744     * register value that now needs to be properly registered.  This is used to avoid an
745     * extra register copy that would result if StoreValue was called.
746     */
747    void StoreFinalValue(RegLocation rl_dest, RegLocation rl_src);
748
749    /**
750     * @brief Used to do the final store in a wide destination as per bytecode semantics.
751     * @see StoreValueWide
752     * @param rl_dest The destination dalvik register location.
753     * @param rl_src The source register location. It must be kLocPhysReg
754     *
755     * This is used for x86 two operand computations, where we have computed the correct
756     * register values that now need to be properly registered.  This is used to avoid an
757     * extra pair of register copies that would result if StoreValueWide was called.
758     */
759    void StoreFinalValueWide(RegLocation rl_dest, RegLocation rl_src);
760
761    // Shared by all targets - implemented in mir_to_lir.cc.
762    void CompileDalvikInstruction(MIR* mir, BasicBlock* bb, LIR* label_list);
763    void HandleExtendedMethodMIR(BasicBlock* bb, MIR* mir);
764    bool MethodBlockCodeGen(BasicBlock* bb);
765    bool SpecialMIR2LIR(const InlineMethod& special);
766    void MethodMIR2LIR();
767
768    /*
769     * @brief Load the address of the dex method into the register.
770     * @param target_method The MethodReference of the method to be invoked.
771     * @param type How the method will be invoked.
772     * @param register that will contain the code address.
773     * @note register will be passed to TargetReg to get physical register.
774     */
775    void LoadCodeAddress(const MethodReference& target_method, InvokeType type,
776                         SpecialTargetRegister symbolic_reg);
777
778    /*
779     * @brief Load the Method* of a dex method into the register.
780     * @param target_method The MethodReference of the method to be invoked.
781     * @param type How the method will be invoked.
782     * @param register that will contain the code address.
783     * @note register will be passed to TargetReg to get physical register.
784     */
785    virtual void LoadMethodAddress(const MethodReference& target_method, InvokeType type,
786                                   SpecialTargetRegister symbolic_reg);
787
788    /*
789     * @brief Load the Class* of a Dex Class type into the register.
790     * @param type How the method will be invoked.
791     * @param register that will contain the code address.
792     * @note register will be passed to TargetReg to get physical register.
793     */
794    virtual void LoadClassType(uint32_t type_idx, SpecialTargetRegister symbolic_reg);
795
796    // Routines that work for the generic case, but may be overriden by target.
797    /*
798     * @brief Compare memory to immediate, and branch if condition true.
799     * @param cond The condition code that when true will branch to the target.
800     * @param temp_reg A temporary register that can be used if compare to memory is not
801     * supported by the architecture.
802     * @param base_reg The register holding the base address.
803     * @param offset The offset from the base.
804     * @param check_value The immediate to compare to.
805     * @returns The branch instruction that was generated.
806     */
807    virtual LIR* OpCmpMemImmBranch(ConditionCode cond, RegStorage temp_reg, RegStorage base_reg,
808                                   int offset, int check_value, LIR* target);
809
810    // Required for target - codegen helpers.
811    virtual bool SmallLiteralDivRem(Instruction::Code dalvik_opcode, bool is_div,
812                                    RegLocation rl_src, RegLocation rl_dest, int lit) = 0;
813    virtual LIR* CheckSuspendUsingLoad() = 0;
814    virtual RegStorage LoadHelper(ThreadOffset offset) = 0;
815    virtual LIR* LoadBaseDisp(RegStorage r_base, int displacement, RegStorage r_dest, OpSize size,
816                              int s_reg) = 0;
817    virtual LIR* LoadBaseDispWide(RegStorage r_base, int displacement, RegStorage r_dest,
818                                  int s_reg) = 0;
819    virtual LIR* LoadBaseIndexed(RegStorage r_base, RegStorage r_index, RegStorage r_dest,
820                                 int scale, OpSize size) = 0;
821    virtual LIR* LoadBaseIndexedDisp(RegStorage r_base, RegStorage r_index, int scale,
822                                     int displacement, RegStorage r_dest, RegStorage r_dest_hi,
823                                     OpSize size, int s_reg) = 0;
824    virtual LIR* LoadConstantNoClobber(RegStorage r_dest, int value) = 0;
825    virtual LIR* LoadConstantWide(RegStorage r_dest, int64_t value) = 0;
826    virtual LIR* StoreBaseDisp(RegStorage r_base, int displacement, RegStorage r_src,
827                               OpSize size) = 0;
828    virtual LIR* StoreBaseDispWide(RegStorage r_base, int displacement, RegStorage r_src) = 0;
829    virtual LIR* StoreBaseIndexed(RegStorage r_base, RegStorage r_index, RegStorage r_src,
830                                  int scale, OpSize size) = 0;
831    virtual LIR* StoreBaseIndexedDisp(RegStorage r_base, RegStorage r_index, int scale,
832                                      int displacement, RegStorage r_src, RegStorage r_src_hi,
833                                      OpSize size, int s_reg) = 0;
834    virtual void MarkGCCard(RegStorage val_reg, RegStorage tgt_addr_reg) = 0;
835
836    // Required for target - register utilities.
837    virtual bool IsFpReg(int reg) = 0;
838    virtual bool IsFpReg(RegStorage reg) = 0;
839    virtual bool SameRegType(int reg1, int reg2) = 0;
840    virtual RegStorage AllocTypedTemp(bool fp_hint, int reg_class) = 0;
841    virtual RegStorage AllocTypedTempWide(bool fp_hint, int reg_class) = 0;
842    // TODO: elminate S2d.
843    virtual int S2d(int low_reg, int high_reg) = 0;
844    virtual RegStorage TargetReg(SpecialTargetRegister reg) = 0;
845    virtual RegStorage GetArgMappingToPhysicalReg(int arg_num) = 0;
846    virtual RegLocation GetReturnAlt() = 0;
847    virtual RegLocation GetReturnWideAlt() = 0;
848    virtual RegLocation LocCReturn() = 0;
849    virtual RegLocation LocCReturnDouble() = 0;
850    virtual RegLocation LocCReturnFloat() = 0;
851    virtual RegLocation LocCReturnWide() = 0;
852    // TODO: use to reduce/eliminate xx_FPREG() macro use.
853    virtual uint32_t FpRegMask() = 0;
854    virtual uint64_t GetRegMaskCommon(int reg) = 0;
855    virtual void AdjustSpillMask() = 0;
856    virtual void ClobberCallerSave() = 0;
857    virtual void FlushReg(RegStorage reg) = 0;
858    virtual void FlushRegWide(RegStorage reg) = 0;
859    virtual void FreeCallTemps() = 0;
860    virtual void FreeRegLocTemps(RegLocation rl_keep, RegLocation rl_free) = 0;
861    virtual void LockCallTemps() = 0;
862    virtual void MarkPreservedSingle(int v_reg, int reg) = 0;
863    virtual void CompilerInitializeRegAlloc() = 0;
864
865    // Required for target - miscellaneous.
866    virtual void AssembleLIR() = 0;
867    virtual void DumpResourceMask(LIR* lir, uint64_t mask, const char* prefix) = 0;
868    virtual void SetupTargetResourceMasks(LIR* lir, uint64_t flags) = 0;
869    virtual const char* GetTargetInstFmt(int opcode) = 0;
870    virtual const char* GetTargetInstName(int opcode) = 0;
871    virtual std::string BuildInsnString(const char* fmt, LIR* lir, unsigned char* base_addr) = 0;
872    virtual uint64_t GetPCUseDefEncoding() = 0;
873    virtual uint64_t GetTargetInstFlags(int opcode) = 0;
874    virtual int GetInsnSize(LIR* lir) = 0;
875    virtual bool IsUnconditionalBranch(LIR* lir) = 0;
876
877    // Required for target - Dalvik-level generators.
878    virtual void GenArithImmOpLong(Instruction::Code opcode, RegLocation rl_dest,
879                                   RegLocation rl_src1, RegLocation rl_src2) = 0;
880    virtual void GenMulLong(Instruction::Code,
881                            RegLocation rl_dest, RegLocation rl_src1,
882                            RegLocation rl_src2) = 0;
883    virtual void GenAddLong(Instruction::Code,
884                            RegLocation rl_dest, RegLocation rl_src1,
885                            RegLocation rl_src2) = 0;
886    virtual void GenAndLong(Instruction::Code,
887                            RegLocation rl_dest, RegLocation rl_src1,
888                            RegLocation rl_src2) = 0;
889    virtual void GenArithOpDouble(Instruction::Code opcode,
890                                  RegLocation rl_dest, RegLocation rl_src1,
891                                  RegLocation rl_src2) = 0;
892    virtual void GenArithOpFloat(Instruction::Code opcode, RegLocation rl_dest,
893                                 RegLocation rl_src1, RegLocation rl_src2) = 0;
894    virtual void GenCmpFP(Instruction::Code opcode, RegLocation rl_dest,
895                          RegLocation rl_src1, RegLocation rl_src2) = 0;
896    virtual void GenConversion(Instruction::Code opcode, RegLocation rl_dest,
897                               RegLocation rl_src) = 0;
898    virtual bool GenInlinedCas(CallInfo* info, bool is_long, bool is_object) = 0;
899
900    /**
901     * @brief Used to generate code for intrinsic java\.lang\.Math methods min and max.
902     * @details This is also applicable for java\.lang\.StrictMath since it is a simple algorithm
903     * that applies on integers. The generated code will write the smallest or largest value
904     * directly into the destination register as specified by the invoke information.
905     * @param info Information about the invoke.
906     * @param is_min If true generates code that computes minimum. Otherwise computes maximum.
907     * @return Returns true if successfully generated
908     */
909    virtual bool GenInlinedMinMaxInt(CallInfo* info, bool is_min) = 0;
910
911    virtual bool GenInlinedSqrt(CallInfo* info) = 0;
912    virtual bool GenInlinedPeek(CallInfo* info, OpSize size) = 0;
913    virtual bool GenInlinedPoke(CallInfo* info, OpSize size) = 0;
914    virtual void GenNegLong(RegLocation rl_dest, RegLocation rl_src) = 0;
915    virtual void GenOrLong(Instruction::Code, RegLocation rl_dest, RegLocation rl_src1,
916                           RegLocation rl_src2) = 0;
917    virtual void GenSubLong(Instruction::Code, RegLocation rl_dest, RegLocation rl_src1,
918                            RegLocation rl_src2) = 0;
919    virtual void GenXorLong(Instruction::Code, RegLocation rl_dest, RegLocation rl_src1,
920                            RegLocation rl_src2) = 0;
921    virtual LIR* GenRegMemCheck(ConditionCode c_code, RegStorage reg1, RegStorage base,
922                                int offset, ThrowKind kind) = 0;
923    virtual RegLocation GenDivRem(RegLocation rl_dest, RegStorage reg_lo, RegStorage reg_hi,
924                                  bool is_div) = 0;
925    virtual RegLocation GenDivRemLit(RegLocation rl_dest, RegStorage reg_lo, int lit,
926                                     bool is_div) = 0;
927    /*
928     * @brief Generate an integer div or rem operation by a literal.
929     * @param rl_dest Destination Location.
930     * @param rl_src1 Numerator Location.
931     * @param rl_src2 Divisor Location.
932     * @param is_div 'true' if this is a division, 'false' for a remainder.
933     * @param check_zero 'true' if an exception should be generated if the divisor is 0.
934     */
935    virtual RegLocation GenDivRem(RegLocation rl_dest, RegLocation rl_src1,
936                                  RegLocation rl_src2, bool is_div, bool check_zero) = 0;
937    /*
938     * @brief Generate an integer div or rem operation by a literal.
939     * @param rl_dest Destination Location.
940     * @param rl_src Numerator Location.
941     * @param lit Divisor.
942     * @param is_div 'true' if this is a division, 'false' for a remainder.
943     */
944    virtual RegLocation GenDivRemLit(RegLocation rl_dest, RegLocation rl_src1, int lit,
945                                     bool is_div) = 0;
946    virtual void GenCmpLong(RegLocation rl_dest, RegLocation rl_src1, RegLocation rl_src2) = 0;
947
948    /**
949     * @brief Used for generating code that throws ArithmeticException if both registers are zero.
950     * @details This is used for generating DivideByZero checks when divisor is held in two separate registers.
951     * @param reg_lo The register holding the lower 32-bits.
952     * @param reg_hi The register holding the upper 32-bits.
953     */
954    virtual void GenDivZeroCheck(RegStorage reg) = 0;
955
956    virtual void GenEntrySequence(RegLocation* ArgLocs, RegLocation rl_method) = 0;
957    virtual void GenExitSequence() = 0;
958    virtual void GenFillArrayData(DexOffset table_offset, RegLocation rl_src) = 0;
959    virtual void GenFusedFPCmpBranch(BasicBlock* bb, MIR* mir, bool gt_bias, bool is_double) = 0;
960    virtual void GenFusedLongCmpBranch(BasicBlock* bb, MIR* mir) = 0;
961
962    /**
963     * @brief Lowers the kMirOpSelect MIR into LIR.
964     * @param bb The basic block in which the MIR is from.
965     * @param mir The MIR whose opcode is kMirOpSelect.
966     */
967    virtual void GenSelect(BasicBlock* bb, MIR* mir) = 0;
968
969    /**
970     * @brief Used to generate a memory barrier in an architecture specific way.
971     * @details The last generated LIR will be considered for use as barrier. Namely,
972     * if the last LIR can be updated in a way where it will serve the semantics of
973     * barrier, then it will be used as such. Otherwise, a new LIR will be generated
974     * that can keep the semantics.
975     * @param barrier_kind The kind of memory barrier to generate.
976     */
977    virtual void GenMemBarrier(MemBarrierKind barrier_kind) = 0;
978
979    virtual void GenMoveException(RegLocation rl_dest) = 0;
980    virtual void GenMultiplyByTwoBitMultiplier(RegLocation rl_src, RegLocation rl_result, int lit,
981                                               int first_bit, int second_bit) = 0;
982    virtual void GenNegDouble(RegLocation rl_dest, RegLocation rl_src) = 0;
983    virtual void GenNegFloat(RegLocation rl_dest, RegLocation rl_src) = 0;
984    virtual void GenPackedSwitch(MIR* mir, DexOffset table_offset, RegLocation rl_src) = 0;
985    virtual void GenSparseSwitch(MIR* mir, DexOffset table_offset, RegLocation rl_src) = 0;
986    virtual void GenArrayGet(int opt_flags, OpSize size, RegLocation rl_array,
987                             RegLocation rl_index, RegLocation rl_dest, int scale) = 0;
988    virtual void GenArrayPut(int opt_flags, OpSize size, RegLocation rl_array,
989                             RegLocation rl_index, RegLocation rl_src, int scale,
990                             bool card_mark) = 0;
991    virtual void GenShiftImmOpLong(Instruction::Code opcode, RegLocation rl_dest,
992                                   RegLocation rl_src1, RegLocation rl_shift) = 0;
993
994    // Required for target - single operation generators.
995    virtual LIR* OpUnconditionalBranch(LIR* target) = 0;
996    virtual LIR* OpCmpBranch(ConditionCode cond, RegStorage src1, RegStorage src2, LIR* target) = 0;
997    virtual LIR* OpCmpImmBranch(ConditionCode cond, RegStorage reg, int check_value,
998                                LIR* target) = 0;
999    virtual LIR* OpCondBranch(ConditionCode cc, LIR* target) = 0;
1000    virtual LIR* OpDecAndBranch(ConditionCode c_code, RegStorage reg, LIR* target) = 0;
1001    virtual LIR* OpFpRegCopy(RegStorage r_dest, RegStorage r_src) = 0;
1002    virtual LIR* OpIT(ConditionCode cond, const char* guide) = 0;
1003    virtual LIR* OpMem(OpKind op, RegStorage r_base, int disp) = 0;
1004    virtual LIR* OpPcRelLoad(RegStorage reg, LIR* target) = 0;
1005    virtual LIR* OpReg(OpKind op, RegStorage r_dest_src) = 0;
1006    virtual LIR* OpRegCopy(RegStorage r_dest, RegStorage r_src) = 0;
1007    virtual LIR* OpRegCopyNoInsert(RegStorage r_dest, RegStorage r_src) = 0;
1008    virtual LIR* OpRegImm(OpKind op, RegStorage r_dest_src1, int value) = 0;
1009    virtual LIR* OpRegMem(OpKind op, RegStorage r_dest, RegStorage r_base, int offset) = 0;
1010    virtual LIR* OpRegReg(OpKind op, RegStorage r_dest_src1, RegStorage r_src2) = 0;
1011
1012    /**
1013     * @brief Used to generate an LIR that does a load from mem to reg.
1014     * @param r_dest The destination physical register.
1015     * @param r_base The base physical register for memory operand.
1016     * @param offset The displacement for memory operand.
1017     * @param move_type Specification on the move desired (size, alignment, register kind).
1018     * @return Returns the generate move LIR.
1019     */
1020    virtual LIR* OpMovRegMem(RegStorage r_dest, RegStorage r_base, int offset,
1021                             MoveType move_type) = 0;
1022
1023    /**
1024     * @brief Used to generate an LIR that does a store from reg to mem.
1025     * @param r_base The base physical register for memory operand.
1026     * @param offset The displacement for memory operand.
1027     * @param r_src The destination physical register.
1028     * @param bytes_to_move The number of bytes to move.
1029     * @param is_aligned Whether the memory location is known to be aligned.
1030     * @return Returns the generate move LIR.
1031     */
1032    virtual LIR* OpMovMemReg(RegStorage r_base, int offset, RegStorage r_src,
1033                             MoveType move_type) = 0;
1034
1035    /**
1036     * @brief Used for generating a conditional register to register operation.
1037     * @param op The opcode kind.
1038     * @param cc The condition code that when true will perform the opcode.
1039     * @param r_dest The destination physical register.
1040     * @param r_src The source physical register.
1041     * @return Returns the newly created LIR or null in case of creation failure.
1042     */
1043    virtual LIR* OpCondRegReg(OpKind op, ConditionCode cc, RegStorage r_dest, RegStorage r_src) = 0;
1044
1045    virtual LIR* OpRegRegImm(OpKind op, RegStorage r_dest, RegStorage r_src1, int value) = 0;
1046    virtual LIR* OpRegRegReg(OpKind op, RegStorage r_dest, RegStorage r_src1,
1047                             RegStorage r_src2) = 0;
1048    virtual LIR* OpTestSuspend(LIR* target) = 0;
1049    virtual LIR* OpThreadMem(OpKind op, ThreadOffset thread_offset) = 0;
1050    virtual LIR* OpVldm(RegStorage r_base, int count) = 0;
1051    virtual LIR* OpVstm(RegStorage r_base, int count) = 0;
1052    virtual void OpLea(RegStorage r_base, RegStorage reg1, RegStorage reg2, int scale,
1053                       int offset) = 0;
1054    virtual void OpRegCopyWide(RegStorage dest, RegStorage src) = 0;
1055    virtual void OpTlsCmp(ThreadOffset offset, int val) = 0;
1056    virtual bool InexpensiveConstantInt(int32_t value) = 0;
1057    virtual bool InexpensiveConstantFloat(int32_t value) = 0;
1058    virtual bool InexpensiveConstantLong(int64_t value) = 0;
1059    virtual bool InexpensiveConstantDouble(int64_t value) = 0;
1060
1061    // May be optimized by targets.
1062    virtual void GenMonitorEnter(int opt_flags, RegLocation rl_src);
1063    virtual void GenMonitorExit(int opt_flags, RegLocation rl_src);
1064
1065    // Temp workaround
1066    void Workaround7250540(RegLocation rl_dest, RegStorage zero_reg);
1067
1068  protected:
1069    Mir2Lir(CompilationUnit* cu, MIRGraph* mir_graph, ArenaAllocator* arena);
1070
1071    CompilationUnit* GetCompilationUnit() {
1072      return cu_;
1073    }
1074    /*
1075     * @brief Returns the index of the lowest set bit in 'x'.
1076     * @param x Value to be examined.
1077     * @returns The bit number of the lowest bit set in the value.
1078     */
1079    int32_t LowestSetBit(uint64_t x);
1080    /*
1081     * @brief Is this value a power of two?
1082     * @param x Value to be examined.
1083     * @returns 'true' if only 1 bit is set in the value.
1084     */
1085    bool IsPowerOfTwo(uint64_t x);
1086    /*
1087     * @brief Do these SRs overlap?
1088     * @param rl_op1 One RegLocation
1089     * @param rl_op2 The other RegLocation
1090     * @return 'true' if the VR pairs overlap
1091     *
1092     * Check to see if a result pair has a misaligned overlap with an operand pair.  This
1093     * is not usual for dx to generate, but it is legal (for now).  In a future rev of
1094     * dex, we'll want to make this case illegal.
1095     */
1096    bool BadOverlap(RegLocation rl_op1, RegLocation rl_op2);
1097
1098    /*
1099     * @brief Force a location (in a register) into a temporary register
1100     * @param loc location of result
1101     * @returns update location
1102     */
1103    RegLocation ForceTemp(RegLocation loc);
1104
1105    /*
1106     * @brief Force a wide location (in registers) into temporary registers
1107     * @param loc location of result
1108     * @returns update location
1109     */
1110    RegLocation ForceTempWide(RegLocation loc);
1111
1112    virtual void GenInstanceofFinal(bool use_declaring_class, uint32_t type_idx,
1113                                    RegLocation rl_dest, RegLocation rl_src);
1114
1115    void AddSlowPath(LIRSlowPath* slowpath);
1116
1117    virtual void GenInstanceofCallingHelper(bool needs_access_check, bool type_known_final,
1118                                            bool type_known_abstract, bool use_declaring_class,
1119                                            bool can_assume_type_is_in_dex_cache,
1120                                            uint32_t type_idx, RegLocation rl_dest,
1121                                            RegLocation rl_src);
1122    /*
1123     * @brief Generate the debug_frame FDE information if possible.
1124     * @returns pointer to vector containg CFE information, or NULL.
1125     */
1126    virtual std::vector<uint8_t>* ReturnCallFrameInformation();
1127
1128    /**
1129     * @brief Used to insert marker that can be used to associate MIR with LIR.
1130     * @details Only inserts marker if verbosity is enabled.
1131     * @param mir The mir that is currently being generated.
1132     */
1133    void GenPrintLabel(MIR* mir);
1134
1135    /**
1136     * @brief Used to generate return sequence when there is no frame.
1137     * @details Assumes that the return registers have already been populated.
1138     */
1139    virtual void GenSpecialExitSequence() = 0;
1140
1141    /**
1142     * @brief Used to generate code for special methods that are known to be
1143     * small enough to work in frameless mode.
1144     * @param bb The basic block of the first MIR.
1145     * @param mir The first MIR of the special method.
1146     * @param special Information about the special method.
1147     * @return Returns whether or not this was handled successfully. Returns false
1148     * if caller should punt to normal MIR2LIR conversion.
1149     */
1150    virtual bool GenSpecialCase(BasicBlock* bb, MIR* mir, const InlineMethod& special);
1151
1152  private:
1153    void ClobberBody(RegisterInfo* p);
1154    void ResetDefBody(RegisterInfo* p) {
1155      p->def_start = NULL;
1156      p->def_end = NULL;
1157    }
1158
1159    void SetCurrentDexPc(DexOffset dexpc) {
1160      current_dalvik_offset_ = dexpc;
1161    }
1162
1163    /**
1164     * @brief Used to lock register if argument at in_position was passed that way.
1165     * @details Does nothing if the argument is passed via stack.
1166     * @param in_position The argument number whose register to lock.
1167     * @param wide Whether the argument is wide.
1168     */
1169    void LockArg(int in_position, bool wide = false);
1170
1171    /**
1172     * @brief Used to load VR argument to a physical register.
1173     * @details The load is only done if the argument is not already in physical register.
1174     * LockArg must have been previously called.
1175     * @param in_position The argument number to load.
1176     * @param wide Whether the argument is 64-bit or not.
1177     * @return Returns the register (or register pair) for the loaded argument.
1178     */
1179    RegStorage LoadArg(int in_position, bool wide = false);
1180
1181    /**
1182     * @brief Used to load a VR argument directly to a specified register location.
1183     * @param in_position The argument number to place in register.
1184     * @param rl_dest The register location where to place argument.
1185     */
1186    void LoadArgDirect(int in_position, RegLocation rl_dest);
1187
1188    /**
1189     * @brief Used to generate LIR for special getter method.
1190     * @param mir The mir that represents the iget.
1191     * @param special Information about the special getter method.
1192     * @return Returns whether LIR was successfully generated.
1193     */
1194    bool GenSpecialIGet(MIR* mir, const InlineMethod& special);
1195
1196    /**
1197     * @brief Used to generate LIR for special setter method.
1198     * @param mir The mir that represents the iput.
1199     * @param special Information about the special setter method.
1200     * @return Returns whether LIR was successfully generated.
1201     */
1202    bool GenSpecialIPut(MIR* mir, const InlineMethod& special);
1203
1204    /**
1205     * @brief Used to generate LIR for special return-args method.
1206     * @param mir The mir that represents the return of argument.
1207     * @param special Information about the special return-args method.
1208     * @return Returns whether LIR was successfully generated.
1209     */
1210    bool GenSpecialIdentity(MIR* mir, const InlineMethod& special);
1211
1212
1213  public:
1214    // TODO: add accessors for these.
1215    LIR* literal_list_;                        // Constants.
1216    LIR* method_literal_list_;                 // Method literals requiring patching.
1217    LIR* class_literal_list_;                  // Class literals requiring patching.
1218    LIR* code_literal_list_;                   // Code literals requiring patching.
1219    LIR* first_fixup_;                         // Doubly-linked list of LIR nodes requiring fixups.
1220
1221  protected:
1222    CompilationUnit* const cu_;
1223    MIRGraph* const mir_graph_;
1224    GrowableArray<SwitchTable*> switch_tables_;
1225    GrowableArray<FillArrayData*> fill_array_data_;
1226    GrowableArray<LIR*> throw_launchpads_;
1227    GrowableArray<LIR*> suspend_launchpads_;
1228    GrowableArray<RegisterInfo*> tempreg_info_;
1229    GrowableArray<RegisterInfo*> reginfo_map_;
1230    GrowableArray<void*> pointer_storage_;
1231    CodeOffset current_code_offset_;    // Working byte offset of machine instructons.
1232    CodeOffset data_offset_;            // starting offset of literal pool.
1233    size_t total_size_;                   // header + code size.
1234    LIR* block_label_list_;
1235    PromotionMap* promotion_map_;
1236    /*
1237     * TODO: The code generation utilities don't have a built-in
1238     * mechanism to propagate the original Dalvik opcode address to the
1239     * associated generated instructions.  For the trace compiler, this wasn't
1240     * necessary because the interpreter handled all throws and debugging
1241     * requests.  For now we'll handle this by placing the Dalvik offset
1242     * in the CompilationUnit struct before codegen for each instruction.
1243     * The low-level LIR creation utilites will pull it from here.  Rework this.
1244     */
1245    DexOffset current_dalvik_offset_;
1246    size_t estimated_native_code_size_;     // Just an estimate; used to reserve code_buffer_ size.
1247    RegisterPool* reg_pool_;
1248    /*
1249     * Sanity checking for the register temp tracking.  The same ssa
1250     * name should never be associated with one temp register per
1251     * instruction compilation.
1252     */
1253    int live_sreg_;
1254    CodeBuffer code_buffer_;
1255    // The encoding mapping table data (dex -> pc offset and pc offset -> dex) with a size prefix.
1256    std::vector<uint8_t> encoded_mapping_table_;
1257    std::vector<uint32_t> core_vmap_table_;
1258    std::vector<uint32_t> fp_vmap_table_;
1259    std::vector<uint8_t> native_gc_map_;
1260    int num_core_spills_;
1261    int num_fp_spills_;
1262    int frame_size_;
1263    unsigned int core_spill_mask_;
1264    unsigned int fp_spill_mask_;
1265    LIR* first_lir_insn_;
1266    LIR* last_lir_insn_;
1267
1268    GrowableArray<LIRSlowPath*> slow_paths_;
1269};  // Class Mir2Lir
1270
1271}  // namespace art
1272
1273#endif  // ART_COMPILER_DEX_QUICK_MIR_TO_LIR_H_
1274