target_x86.cc revision 02ff2d4187249d26fabe8e5eacc27b99984ee353
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#include <string>
18#include <inttypes.h>
19
20#include "codegen_x86.h"
21#include "dex/compiler_internals.h"
22#include "dex/quick/mir_to_lir-inl.h"
23#include "dex/reg_storage_eq.h"
24#include "mirror/array.h"
25#include "mirror/string.h"
26#include "x86_lir.h"
27
28namespace art {
29
30static constexpr RegStorage core_regs_arr_32[] = {
31    rs_rAX, rs_rCX, rs_rDX, rs_rBX, rs_rX86_SP_32, rs_rBP, rs_rSI, rs_rDI,
32};
33static constexpr RegStorage core_regs_arr_64[] = {
34    rs_rAX, rs_rCX, rs_rDX, rs_rBX, rs_rX86_SP_32, rs_rBP, rs_rSI, rs_rDI,
35    rs_r8, rs_r9, rs_r10, rs_r11, rs_r12, rs_r13, rs_r14, rs_r15
36};
37static constexpr RegStorage core_regs_arr_64q[] = {
38    rs_r0q, rs_r1q, rs_r2q, rs_r3q, rs_rX86_SP_64, rs_r5q, rs_r6q, rs_r7q,
39    rs_r8q, rs_r9q, rs_r10q, rs_r11q, rs_r12q, rs_r13q, rs_r14q, rs_r15q
40};
41static constexpr RegStorage sp_regs_arr_32[] = {
42    rs_fr0, rs_fr1, rs_fr2, rs_fr3, rs_fr4, rs_fr5, rs_fr6, rs_fr7,
43};
44static constexpr RegStorage sp_regs_arr_64[] = {
45    rs_fr0, rs_fr1, rs_fr2, rs_fr3, rs_fr4, rs_fr5, rs_fr6, rs_fr7,
46    rs_fr8, rs_fr9, rs_fr10, rs_fr11, rs_fr12, rs_fr13, rs_fr14, rs_fr15
47};
48static constexpr RegStorage dp_regs_arr_32[] = {
49    rs_dr0, rs_dr1, rs_dr2, rs_dr3, rs_dr4, rs_dr5, rs_dr6, rs_dr7,
50};
51static constexpr RegStorage dp_regs_arr_64[] = {
52    rs_dr0, rs_dr1, rs_dr2, rs_dr3, rs_dr4, rs_dr5, rs_dr6, rs_dr7,
53    rs_dr8, rs_dr9, rs_dr10, rs_dr11, rs_dr12, rs_dr13, rs_dr14, rs_dr15
54};
55static constexpr RegStorage xp_regs_arr_32[] = {
56    rs_xr0, rs_xr1, rs_xr2, rs_xr3, rs_xr4, rs_xr5, rs_xr6, rs_xr7,
57};
58static constexpr RegStorage xp_regs_arr_64[] = {
59    rs_xr0, rs_xr1, rs_xr2, rs_xr3, rs_xr4, rs_xr5, rs_xr6, rs_xr7,
60    rs_xr8, rs_xr9, rs_xr10, rs_xr11, rs_xr12, rs_xr13, rs_xr14, rs_xr15
61};
62static constexpr RegStorage reserved_regs_arr_32[] = {rs_rX86_SP_32};
63static constexpr RegStorage reserved_regs_arr_64[] = {rs_rX86_SP_32};
64static constexpr RegStorage reserved_regs_arr_64q[] = {rs_rX86_SP_64};
65static constexpr RegStorage core_temps_arr_32[] = {rs_rAX, rs_rCX, rs_rDX, rs_rBX};
66static constexpr RegStorage core_temps_arr_64[] = {
67    rs_rAX, rs_rCX, rs_rDX, rs_rSI, rs_rDI,
68    rs_r8, rs_r9, rs_r10, rs_r11
69};
70
71// How to add register to be available for promotion:
72// 1) Remove register from array defining temp
73// 2) Update ClobberCallerSave
74// 3) Update JNI compiler ABI:
75// 3.1) add reg in JniCallingConvention method
76// 3.2) update CoreSpillMask/FpSpillMask
77// 4) Update entrypoints
78// 4.1) Update constants in asm_support_x86_64.h for new frame size
79// 4.2) Remove entry in SmashCallerSaves
80// 4.3) Update jni_entrypoints to spill/unspill new callee save reg
81// 4.4) Update quick_entrypoints to spill/unspill new callee save reg
82// 5) Update runtime ABI
83// 5.1) Update quick_method_frame_info with new required spills
84// 5.2) Update QuickArgumentVisitor with new offsets to gprs and xmms
85// Note that you cannot use register corresponding to incoming args
86// according to ABI and QCG needs one additional XMM temp for
87// bulk copy in preparation to call.
88static constexpr RegStorage core_temps_arr_64q[] = {
89    rs_r0q, rs_r1q, rs_r2q, rs_r6q, rs_r7q,
90    rs_r8q, rs_r9q, rs_r10q, rs_r11q
91};
92static constexpr RegStorage sp_temps_arr_32[] = {
93    rs_fr0, rs_fr1, rs_fr2, rs_fr3, rs_fr4, rs_fr5, rs_fr6, rs_fr7,
94};
95static constexpr RegStorage sp_temps_arr_64[] = {
96    rs_fr0, rs_fr1, rs_fr2, rs_fr3, rs_fr4, rs_fr5, rs_fr6, rs_fr7,
97    rs_fr8, rs_fr9, rs_fr10, rs_fr11
98};
99static constexpr RegStorage dp_temps_arr_32[] = {
100    rs_dr0, rs_dr1, rs_dr2, rs_dr3, rs_dr4, rs_dr5, rs_dr6, rs_dr7,
101};
102static constexpr RegStorage dp_temps_arr_64[] = {
103    rs_dr0, rs_dr1, rs_dr2, rs_dr3, rs_dr4, rs_dr5, rs_dr6, rs_dr7,
104    rs_dr8, rs_dr9, rs_dr10, rs_dr11
105};
106
107static constexpr RegStorage xp_temps_arr_32[] = {
108    rs_xr0, rs_xr1, rs_xr2, rs_xr3, rs_xr4, rs_xr5, rs_xr6, rs_xr7,
109};
110static constexpr RegStorage xp_temps_arr_64[] = {
111    rs_xr0, rs_xr1, rs_xr2, rs_xr3, rs_xr4, rs_xr5, rs_xr6, rs_xr7,
112    rs_xr8, rs_xr9, rs_xr10, rs_xr11
113};
114
115static constexpr ArrayRef<const RegStorage> empty_pool;
116static constexpr ArrayRef<const RegStorage> core_regs_32(core_regs_arr_32);
117static constexpr ArrayRef<const RegStorage> core_regs_64(core_regs_arr_64);
118static constexpr ArrayRef<const RegStorage> core_regs_64q(core_regs_arr_64q);
119static constexpr ArrayRef<const RegStorage> sp_regs_32(sp_regs_arr_32);
120static constexpr ArrayRef<const RegStorage> sp_regs_64(sp_regs_arr_64);
121static constexpr ArrayRef<const RegStorage> dp_regs_32(dp_regs_arr_32);
122static constexpr ArrayRef<const RegStorage> dp_regs_64(dp_regs_arr_64);
123static constexpr ArrayRef<const RegStorage> xp_regs_32(xp_regs_arr_32);
124static constexpr ArrayRef<const RegStorage> xp_regs_64(xp_regs_arr_64);
125static constexpr ArrayRef<const RegStorage> reserved_regs_32(reserved_regs_arr_32);
126static constexpr ArrayRef<const RegStorage> reserved_regs_64(reserved_regs_arr_64);
127static constexpr ArrayRef<const RegStorage> reserved_regs_64q(reserved_regs_arr_64q);
128static constexpr ArrayRef<const RegStorage> core_temps_32(core_temps_arr_32);
129static constexpr ArrayRef<const RegStorage> core_temps_64(core_temps_arr_64);
130static constexpr ArrayRef<const RegStorage> core_temps_64q(core_temps_arr_64q);
131static constexpr ArrayRef<const RegStorage> sp_temps_32(sp_temps_arr_32);
132static constexpr ArrayRef<const RegStorage> sp_temps_64(sp_temps_arr_64);
133static constexpr ArrayRef<const RegStorage> dp_temps_32(dp_temps_arr_32);
134static constexpr ArrayRef<const RegStorage> dp_temps_64(dp_temps_arr_64);
135
136static constexpr ArrayRef<const RegStorage> xp_temps_32(xp_temps_arr_32);
137static constexpr ArrayRef<const RegStorage> xp_temps_64(xp_temps_arr_64);
138
139RegStorage rs_rX86_SP;
140
141X86NativeRegisterPool rX86_ARG0;
142X86NativeRegisterPool rX86_ARG1;
143X86NativeRegisterPool rX86_ARG2;
144X86NativeRegisterPool rX86_ARG3;
145X86NativeRegisterPool rX86_ARG4;
146X86NativeRegisterPool rX86_ARG5;
147X86NativeRegisterPool rX86_FARG0;
148X86NativeRegisterPool rX86_FARG1;
149X86NativeRegisterPool rX86_FARG2;
150X86NativeRegisterPool rX86_FARG3;
151X86NativeRegisterPool rX86_FARG4;
152X86NativeRegisterPool rX86_FARG5;
153X86NativeRegisterPool rX86_FARG6;
154X86NativeRegisterPool rX86_FARG7;
155X86NativeRegisterPool rX86_RET0;
156X86NativeRegisterPool rX86_RET1;
157X86NativeRegisterPool rX86_INVOKE_TGT;
158X86NativeRegisterPool rX86_COUNT;
159
160RegStorage rs_rX86_ARG0;
161RegStorage rs_rX86_ARG1;
162RegStorage rs_rX86_ARG2;
163RegStorage rs_rX86_ARG3;
164RegStorage rs_rX86_ARG4;
165RegStorage rs_rX86_ARG5;
166RegStorage rs_rX86_FARG0;
167RegStorage rs_rX86_FARG1;
168RegStorage rs_rX86_FARG2;
169RegStorage rs_rX86_FARG3;
170RegStorage rs_rX86_FARG4;
171RegStorage rs_rX86_FARG5;
172RegStorage rs_rX86_FARG6;
173RegStorage rs_rX86_FARG7;
174RegStorage rs_rX86_RET0;
175RegStorage rs_rX86_RET1;
176RegStorage rs_rX86_INVOKE_TGT;
177RegStorage rs_rX86_COUNT;
178
179RegLocation X86Mir2Lir::LocCReturn() {
180  return x86_loc_c_return;
181}
182
183RegLocation X86Mir2Lir::LocCReturnRef() {
184  return cu_->target64 ? x86_64_loc_c_return_ref : x86_loc_c_return_ref;
185}
186
187RegLocation X86Mir2Lir::LocCReturnWide() {
188  return cu_->target64 ? x86_64_loc_c_return_wide : x86_loc_c_return_wide;
189}
190
191RegLocation X86Mir2Lir::LocCReturnFloat() {
192  return x86_loc_c_return_float;
193}
194
195RegLocation X86Mir2Lir::LocCReturnDouble() {
196  return x86_loc_c_return_double;
197}
198
199// Return a target-dependent special register for 32-bit.
200RegStorage X86Mir2Lir::TargetReg32(SpecialTargetRegister reg) {
201  RegStorage res_reg = RegStorage::InvalidReg();
202  switch (reg) {
203    case kSelf: res_reg = RegStorage::InvalidReg(); break;
204    case kSuspend: res_reg =  RegStorage::InvalidReg(); break;
205    case kLr: res_reg =  RegStorage::InvalidReg(); break;
206    case kPc: res_reg =  RegStorage::InvalidReg(); break;
207    case kSp: res_reg =  rs_rX86_SP_32; break;  // This must be the concrete one, as _SP is target-
208                                                // specific size.
209    case kArg0: res_reg = rs_rX86_ARG0; break;
210    case kArg1: res_reg = rs_rX86_ARG1; break;
211    case kArg2: res_reg = rs_rX86_ARG2; break;
212    case kArg3: res_reg = rs_rX86_ARG3; break;
213    case kArg4: res_reg = rs_rX86_ARG4; break;
214    case kArg5: res_reg = rs_rX86_ARG5; break;
215    case kFArg0: res_reg = rs_rX86_FARG0; break;
216    case kFArg1: res_reg = rs_rX86_FARG1; break;
217    case kFArg2: res_reg = rs_rX86_FARG2; break;
218    case kFArg3: res_reg = rs_rX86_FARG3; break;
219    case kFArg4: res_reg = rs_rX86_FARG4; break;
220    case kFArg5: res_reg = rs_rX86_FARG5; break;
221    case kFArg6: res_reg = rs_rX86_FARG6; break;
222    case kFArg7: res_reg = rs_rX86_FARG7; break;
223    case kRet0: res_reg = rs_rX86_RET0; break;
224    case kRet1: res_reg = rs_rX86_RET1; break;
225    case kInvokeTgt: res_reg = rs_rX86_INVOKE_TGT; break;
226    case kHiddenArg: res_reg = rs_rAX; break;
227    case kHiddenFpArg: DCHECK(!cu_->target64); res_reg = rs_fr0; break;
228    case kCount: res_reg = rs_rX86_COUNT; break;
229    default: res_reg = RegStorage::InvalidReg();
230  }
231  return res_reg;
232}
233
234RegStorage X86Mir2Lir::TargetReg(SpecialTargetRegister reg) {
235  LOG(FATAL) << "Do not use this function!!!";
236  return RegStorage::InvalidReg();
237}
238
239/*
240 * Decode the register id.
241 */
242ResourceMask X86Mir2Lir::GetRegMaskCommon(const RegStorage& reg) const {
243  /* Double registers in x86 are just a single FP register. This is always just a single bit. */
244  return ResourceMask::Bit(
245      /* FP register starts at bit position 16 */
246      ((reg.IsFloat() || reg.StorageSize() > 8) ? kX86FPReg0 : 0) + reg.GetRegNum());
247}
248
249ResourceMask X86Mir2Lir::GetPCUseDefEncoding() const {
250  return kEncodeNone;
251}
252
253void X86Mir2Lir::SetupTargetResourceMasks(LIR* lir, uint64_t flags,
254                                          ResourceMask* use_mask, ResourceMask* def_mask) {
255  DCHECK(cu_->instruction_set == kX86 || cu_->instruction_set == kX86_64);
256  DCHECK(!lir->flags.use_def_invalid);
257
258  // X86-specific resource map setup here.
259  if (flags & REG_USE_SP) {
260    use_mask->SetBit(kX86RegSP);
261  }
262
263  if (flags & REG_DEF_SP) {
264    def_mask->SetBit(kX86RegSP);
265  }
266
267  if (flags & REG_DEFA) {
268    SetupRegMask(def_mask, rs_rAX.GetReg());
269  }
270
271  if (flags & REG_DEFD) {
272    SetupRegMask(def_mask, rs_rDX.GetReg());
273  }
274  if (flags & REG_USEA) {
275    SetupRegMask(use_mask, rs_rAX.GetReg());
276  }
277
278  if (flags & REG_USEC) {
279    SetupRegMask(use_mask, rs_rCX.GetReg());
280  }
281
282  if (flags & REG_USED) {
283    SetupRegMask(use_mask, rs_rDX.GetReg());
284  }
285
286  if (flags & REG_USEB) {
287    SetupRegMask(use_mask, rs_rBX.GetReg());
288  }
289
290  // Fixup hard to describe instruction: Uses rAX, rCX, rDI; sets rDI.
291  if (lir->opcode == kX86RepneScasw) {
292    SetupRegMask(use_mask, rs_rAX.GetReg());
293    SetupRegMask(use_mask, rs_rCX.GetReg());
294    SetupRegMask(use_mask, rs_rDI.GetReg());
295    SetupRegMask(def_mask, rs_rDI.GetReg());
296  }
297
298  if (flags & USE_FP_STACK) {
299    use_mask->SetBit(kX86FPStack);
300    def_mask->SetBit(kX86FPStack);
301  }
302}
303
304/* For dumping instructions */
305static const char* x86RegName[] = {
306  "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi",
307  "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
308};
309
310static const char* x86CondName[] = {
311  "O",
312  "NO",
313  "B/NAE/C",
314  "NB/AE/NC",
315  "Z/EQ",
316  "NZ/NE",
317  "BE/NA",
318  "NBE/A",
319  "S",
320  "NS",
321  "P/PE",
322  "NP/PO",
323  "L/NGE",
324  "NL/GE",
325  "LE/NG",
326  "NLE/G"
327};
328
329/*
330 * Interpret a format string and build a string no longer than size
331 * See format key in Assemble.cc.
332 */
333std::string X86Mir2Lir::BuildInsnString(const char *fmt, LIR *lir, unsigned char* base_addr) {
334  std::string buf;
335  size_t i = 0;
336  size_t fmt_len = strlen(fmt);
337  while (i < fmt_len) {
338    if (fmt[i] != '!') {
339      buf += fmt[i];
340      i++;
341    } else {
342      i++;
343      DCHECK_LT(i, fmt_len);
344      char operand_number_ch = fmt[i];
345      i++;
346      if (operand_number_ch == '!') {
347        buf += "!";
348      } else {
349        int operand_number = operand_number_ch - '0';
350        DCHECK_LT(operand_number, 6);  // Expect upto 6 LIR operands.
351        DCHECK_LT(i, fmt_len);
352        int operand = lir->operands[operand_number];
353        switch (fmt[i]) {
354          case 'c':
355            DCHECK_LT(static_cast<size_t>(operand), sizeof(x86CondName));
356            buf += x86CondName[operand];
357            break;
358          case 'd':
359            buf += StringPrintf("%d", operand);
360            break;
361          case 'q': {
362             int64_t value = static_cast<int64_t>(static_cast<int64_t>(operand) << 32 |
363                             static_cast<uint32_t>(lir->operands[operand_number+1]));
364             buf +=StringPrintf("%" PRId64, value);
365          }
366          case 'p': {
367            EmbeddedData *tab_rec = reinterpret_cast<EmbeddedData*>(UnwrapPointer(operand));
368            buf += StringPrintf("0x%08x", tab_rec->offset);
369            break;
370          }
371          case 'r':
372            if (RegStorage::IsFloat(operand)) {
373              int fp_reg = RegStorage::RegNum(operand);
374              buf += StringPrintf("xmm%d", fp_reg);
375            } else {
376              int reg_num = RegStorage::RegNum(operand);
377              DCHECK_LT(static_cast<size_t>(reg_num), sizeof(x86RegName));
378              buf += x86RegName[reg_num];
379            }
380            break;
381          case 't':
382            buf += StringPrintf("0x%08" PRIxPTR " (L%p)",
383                                reinterpret_cast<uintptr_t>(base_addr) + lir->offset + operand,
384                                lir->target);
385            break;
386          default:
387            buf += StringPrintf("DecodeError '%c'", fmt[i]);
388            break;
389        }
390        i++;
391      }
392    }
393  }
394  return buf;
395}
396
397void X86Mir2Lir::DumpResourceMask(LIR *x86LIR, const ResourceMask& mask, const char *prefix) {
398  char buf[256];
399  buf[0] = 0;
400
401  if (mask.Equals(kEncodeAll)) {
402    strcpy(buf, "all");
403  } else {
404    char num[8];
405    int i;
406
407    for (i = 0; i < kX86RegEnd; i++) {
408      if (mask.HasBit(i)) {
409        snprintf(num, arraysize(num), "%d ", i);
410        strcat(buf, num);
411      }
412    }
413
414    if (mask.HasBit(ResourceMask::kCCode)) {
415      strcat(buf, "cc ");
416    }
417    /* Memory bits */
418    if (x86LIR && (mask.HasBit(ResourceMask::kDalvikReg))) {
419      snprintf(buf + strlen(buf), arraysize(buf) - strlen(buf), "dr%d%s",
420               DECODE_ALIAS_INFO_REG(x86LIR->flags.alias_info),
421               (DECODE_ALIAS_INFO_WIDE(x86LIR->flags.alias_info)) ? "(+1)" : "");
422    }
423    if (mask.HasBit(ResourceMask::kLiteral)) {
424      strcat(buf, "lit ");
425    }
426
427    if (mask.HasBit(ResourceMask::kHeapRef)) {
428      strcat(buf, "heap ");
429    }
430    if (mask.HasBit(ResourceMask::kMustNotAlias)) {
431      strcat(buf, "noalias ");
432    }
433  }
434  if (buf[0]) {
435    LOG(INFO) << prefix << ": " <<  buf;
436  }
437}
438
439void X86Mir2Lir::AdjustSpillMask() {
440  // Adjustment for LR spilling, x86 has no LR so nothing to do here
441  core_spill_mask_ |= (1 << rs_rRET.GetRegNum());
442  num_core_spills_++;
443}
444
445RegStorage X86Mir2Lir::AllocateByteRegister() {
446  RegStorage reg = AllocTypedTemp(false, kCoreReg);
447  if (!cu_->target64) {
448    DCHECK_LT(reg.GetRegNum(), rs_rX86_SP.GetRegNum());
449  }
450  return reg;
451}
452
453RegStorage X86Mir2Lir::Get128BitRegister(RegStorage reg) {
454  return GetRegInfo(reg)->FindMatchingView(RegisterInfo::k128SoloStorageMask)->GetReg();
455}
456
457bool X86Mir2Lir::IsByteRegister(RegStorage reg) {
458  return cu_->target64 || reg.GetRegNum() < rs_rX86_SP.GetRegNum();
459}
460
461/* Clobber all regs that might be used by an external C call */
462void X86Mir2Lir::ClobberCallerSave() {
463  if (cu_->target64) {
464    Clobber(rs_rAX);
465    Clobber(rs_rCX);
466    Clobber(rs_rDX);
467    Clobber(rs_rSI);
468    Clobber(rs_rDI);
469
470    Clobber(rs_r8);
471    Clobber(rs_r9);
472    Clobber(rs_r10);
473    Clobber(rs_r11);
474
475    Clobber(rs_fr8);
476    Clobber(rs_fr9);
477    Clobber(rs_fr10);
478    Clobber(rs_fr11);
479  } else {
480    Clobber(rs_rAX);
481    Clobber(rs_rCX);
482    Clobber(rs_rDX);
483    Clobber(rs_rBX);
484  }
485
486  Clobber(rs_fr0);
487  Clobber(rs_fr1);
488  Clobber(rs_fr2);
489  Clobber(rs_fr3);
490  Clobber(rs_fr4);
491  Clobber(rs_fr5);
492  Clobber(rs_fr6);
493  Clobber(rs_fr7);
494}
495
496RegLocation X86Mir2Lir::GetReturnWideAlt() {
497  RegLocation res = LocCReturnWide();
498  DCHECK(res.reg.GetLowReg() == rs_rAX.GetReg());
499  DCHECK(res.reg.GetHighReg() == rs_rDX.GetReg());
500  Clobber(rs_rAX);
501  Clobber(rs_rDX);
502  MarkInUse(rs_rAX);
503  MarkInUse(rs_rDX);
504  MarkWide(res.reg);
505  return res;
506}
507
508RegLocation X86Mir2Lir::GetReturnAlt() {
509  RegLocation res = LocCReturn();
510  res.reg.SetReg(rs_rDX.GetReg());
511  Clobber(rs_rDX);
512  MarkInUse(rs_rDX);
513  return res;
514}
515
516/* To be used when explicitly managing register use */
517void X86Mir2Lir::LockCallTemps() {
518  LockTemp(rs_rX86_ARG0);
519  LockTemp(rs_rX86_ARG1);
520  LockTemp(rs_rX86_ARG2);
521  LockTemp(rs_rX86_ARG3);
522  if (cu_->target64) {
523    LockTemp(rs_rX86_ARG4);
524    LockTemp(rs_rX86_ARG5);
525    LockTemp(rs_rX86_FARG0);
526    LockTemp(rs_rX86_FARG1);
527    LockTemp(rs_rX86_FARG2);
528    LockTemp(rs_rX86_FARG3);
529    LockTemp(rs_rX86_FARG4);
530    LockTemp(rs_rX86_FARG5);
531    LockTemp(rs_rX86_FARG6);
532    LockTemp(rs_rX86_FARG7);
533  }
534}
535
536/* To be used when explicitly managing register use */
537void X86Mir2Lir::FreeCallTemps() {
538  FreeTemp(rs_rX86_ARG0);
539  FreeTemp(rs_rX86_ARG1);
540  FreeTemp(rs_rX86_ARG2);
541  FreeTemp(rs_rX86_ARG3);
542  if (cu_->target64) {
543    FreeTemp(rs_rX86_ARG4);
544    FreeTemp(rs_rX86_ARG5);
545    FreeTemp(rs_rX86_FARG0);
546    FreeTemp(rs_rX86_FARG1);
547    FreeTemp(rs_rX86_FARG2);
548    FreeTemp(rs_rX86_FARG3);
549    FreeTemp(rs_rX86_FARG4);
550    FreeTemp(rs_rX86_FARG5);
551    FreeTemp(rs_rX86_FARG6);
552    FreeTemp(rs_rX86_FARG7);
553  }
554}
555
556bool X86Mir2Lir::ProvidesFullMemoryBarrier(X86OpCode opcode) {
557    switch (opcode) {
558      case kX86LockCmpxchgMR:
559      case kX86LockCmpxchgAR:
560      case kX86LockCmpxchg64M:
561      case kX86LockCmpxchg64A:
562      case kX86XchgMR:
563      case kX86Mfence:
564        // Atomic memory instructions provide full barrier.
565        return true;
566      default:
567        break;
568    }
569
570    // Conservative if cannot prove it provides full barrier.
571    return false;
572}
573
574bool X86Mir2Lir::GenMemBarrier(MemBarrierKind barrier_kind) {
575#if ANDROID_SMP != 0
576  // Start off with using the last LIR as the barrier. If it is not enough, then we will update it.
577  LIR* mem_barrier = last_lir_insn_;
578
579  bool ret = false;
580  /*
581   * According to the JSR-133 Cookbook, for x86 only StoreLoad/AnyAny barriers need memory fence.
582   * All other barriers (LoadAny, AnyStore, StoreStore) are nops due to the x86 memory model.
583   * For those cases, all we need to ensure is that there is a scheduling barrier in place.
584   */
585  if (barrier_kind == kAnyAny) {
586    // If no LIR exists already that can be used a barrier, then generate an mfence.
587    if (mem_barrier == nullptr) {
588      mem_barrier = NewLIR0(kX86Mfence);
589      ret = true;
590    }
591
592    // If last instruction does not provide full barrier, then insert an mfence.
593    if (ProvidesFullMemoryBarrier(static_cast<X86OpCode>(mem_barrier->opcode)) == false) {
594      mem_barrier = NewLIR0(kX86Mfence);
595      ret = true;
596    }
597  }
598
599  // Now ensure that a scheduling barrier is in place.
600  if (mem_barrier == nullptr) {
601    GenBarrier();
602  } else {
603    // Mark as a scheduling barrier.
604    DCHECK(!mem_barrier->flags.use_def_invalid);
605    mem_barrier->u.m.def_mask = &kEncodeAll;
606  }
607  return ret;
608#else
609  return false;
610#endif
611}
612
613void X86Mir2Lir::CompilerInitializeRegAlloc() {
614  if (cu_->target64) {
615    reg_pool_ = new (arena_) RegisterPool(this, arena_, core_regs_64, core_regs_64q, sp_regs_64,
616                                          dp_regs_64, reserved_regs_64, reserved_regs_64q,
617                                          core_temps_64, core_temps_64q, sp_temps_64, dp_temps_64);
618  } else {
619    reg_pool_ = new (arena_) RegisterPool(this, arena_, core_regs_32, empty_pool, sp_regs_32,
620                                          dp_regs_32, reserved_regs_32, empty_pool,
621                                          core_temps_32, empty_pool, sp_temps_32, dp_temps_32);
622  }
623
624  // Target-specific adjustments.
625
626  // Add in XMM registers.
627  const ArrayRef<const RegStorage> *xp_regs = cu_->target64 ? &xp_regs_64 : &xp_regs_32;
628  for (RegStorage reg : *xp_regs) {
629    RegisterInfo* info = new (arena_) RegisterInfo(reg, GetRegMaskCommon(reg));
630    reginfo_map_.Put(reg.GetReg(), info);
631  }
632  const ArrayRef<const RegStorage> *xp_temps = cu_->target64 ? &xp_temps_64 : &xp_temps_32;
633  for (RegStorage reg : *xp_temps) {
634    RegisterInfo* xp_reg_info = GetRegInfo(reg);
635    xp_reg_info->SetIsTemp(true);
636  }
637
638  // Alias single precision xmm to double xmms.
639  // TODO: as needed, add larger vector sizes - alias all to the largest.
640  GrowableArray<RegisterInfo*>::Iterator it(&reg_pool_->sp_regs_);
641  for (RegisterInfo* info = it.Next(); info != nullptr; info = it.Next()) {
642    int sp_reg_num = info->GetReg().GetRegNum();
643    RegStorage xp_reg = RegStorage::Solo128(sp_reg_num);
644    RegisterInfo* xp_reg_info = GetRegInfo(xp_reg);
645    // 128-bit xmm vector register's master storage should refer to itself.
646    DCHECK_EQ(xp_reg_info, xp_reg_info->Master());
647
648    // Redirect 32-bit vector's master storage to 128-bit vector.
649    info->SetMaster(xp_reg_info);
650
651    RegStorage dp_reg = RegStorage::FloatSolo64(sp_reg_num);
652    RegisterInfo* dp_reg_info = GetRegInfo(dp_reg);
653    // Redirect 64-bit vector's master storage to 128-bit vector.
654    dp_reg_info->SetMaster(xp_reg_info);
655    // Singles should show a single 32-bit mask bit, at first referring to the low half.
656    DCHECK_EQ(info->StorageMask(), 0x1U);
657  }
658
659  if (cu_->target64) {
660    // Alias 32bit W registers to corresponding 64bit X registers.
661    GrowableArray<RegisterInfo*>::Iterator w_it(&reg_pool_->core_regs_);
662    for (RegisterInfo* info = w_it.Next(); info != nullptr; info = w_it.Next()) {
663      int x_reg_num = info->GetReg().GetRegNum();
664      RegStorage x_reg = RegStorage::Solo64(x_reg_num);
665      RegisterInfo* x_reg_info = GetRegInfo(x_reg);
666      // 64bit X register's master storage should refer to itself.
667      DCHECK_EQ(x_reg_info, x_reg_info->Master());
668      // Redirect 32bit W master storage to 64bit X.
669      info->SetMaster(x_reg_info);
670      // 32bit W should show a single 32-bit mask bit, at first referring to the low half.
671      DCHECK_EQ(info->StorageMask(), 0x1U);
672    }
673  }
674
675  // Don't start allocating temps at r0/s0/d0 or you may clobber return regs in early-exit methods.
676  // TODO: adjust for x86/hard float calling convention.
677  reg_pool_->next_core_reg_ = 2;
678  reg_pool_->next_sp_reg_ = 2;
679  reg_pool_->next_dp_reg_ = 1;
680}
681
682int X86Mir2Lir::VectorRegisterSize() {
683  return 128;
684}
685
686int X86Mir2Lir::NumReservableVectorRegisters(bool fp_used) {
687  return fp_used ? 5 : 7;
688}
689
690void X86Mir2Lir::SpillCoreRegs() {
691  if (num_core_spills_ == 0) {
692    return;
693  }
694  // Spill mask not including fake return address register
695  uint32_t mask = core_spill_mask_ & ~(1 << rs_rRET.GetRegNum());
696  int offset = frame_size_ - (GetInstructionSetPointerSize(cu_->instruction_set) * num_core_spills_);
697  OpSize size = cu_->target64 ? k64 : k32;
698  for (int reg = 0; mask; mask >>= 1, reg++) {
699    if (mask & 0x1) {
700      StoreBaseDisp(rs_rX86_SP, offset, cu_->target64 ? RegStorage::Solo64(reg) :  RegStorage::Solo32(reg),
701                   size, kNotVolatile);
702      offset += GetInstructionSetPointerSize(cu_->instruction_set);
703    }
704  }
705}
706
707void X86Mir2Lir::UnSpillCoreRegs() {
708  if (num_core_spills_ == 0) {
709    return;
710  }
711  // Spill mask not including fake return address register
712  uint32_t mask = core_spill_mask_ & ~(1 << rs_rRET.GetRegNum());
713  int offset = frame_size_ - (GetInstructionSetPointerSize(cu_->instruction_set) * num_core_spills_);
714  OpSize size = cu_->target64 ? k64 : k32;
715  for (int reg = 0; mask; mask >>= 1, reg++) {
716    if (mask & 0x1) {
717      LoadBaseDisp(rs_rX86_SP, offset, cu_->target64 ? RegStorage::Solo64(reg) :  RegStorage::Solo32(reg),
718                   size, kNotVolatile);
719      offset += GetInstructionSetPointerSize(cu_->instruction_set);
720    }
721  }
722}
723
724void X86Mir2Lir::SpillFPRegs() {
725  if (num_fp_spills_ == 0) {
726    return;
727  }
728  uint32_t mask = fp_spill_mask_;
729  int offset = frame_size_ - (GetInstructionSetPointerSize(cu_->instruction_set) * (num_fp_spills_ + num_core_spills_));
730  for (int reg = 0; mask; mask >>= 1, reg++) {
731    if (mask & 0x1) {
732      StoreBaseDisp(rs_rX86_SP, offset, RegStorage::FloatSolo64(reg),
733                   k64, kNotVolatile);
734      offset += sizeof(double);
735    }
736  }
737}
738void X86Mir2Lir::UnSpillFPRegs() {
739  if (num_fp_spills_ == 0) {
740    return;
741  }
742  uint32_t mask = fp_spill_mask_;
743  int offset = frame_size_ - (GetInstructionSetPointerSize(cu_->instruction_set) * (num_fp_spills_ + num_core_spills_));
744  for (int reg = 0; mask; mask >>= 1, reg++) {
745    if (mask & 0x1) {
746      LoadBaseDisp(rs_rX86_SP, offset, RegStorage::FloatSolo64(reg),
747                   k64, kNotVolatile);
748      offset += sizeof(double);
749    }
750  }
751}
752
753
754bool X86Mir2Lir::IsUnconditionalBranch(LIR* lir) {
755  return (lir->opcode == kX86Jmp8 || lir->opcode == kX86Jmp32);
756}
757
758RegisterClass X86Mir2Lir::RegClassForFieldLoadStore(OpSize size, bool is_volatile) {
759  // X86_64 can handle any size.
760  if (cu_->target64) {
761    if (size == kReference) {
762      return kRefReg;
763    }
764    return kCoreReg;
765  }
766
767  if (UNLIKELY(is_volatile)) {
768    // On x86, atomic 64-bit load/store requires an fp register.
769    // Smaller aligned load/store is atomic for both core and fp registers.
770    if (size == k64 || size == kDouble) {
771      return kFPReg;
772    }
773  }
774  return RegClassBySize(size);
775}
776
777X86Mir2Lir::X86Mir2Lir(CompilationUnit* cu, MIRGraph* mir_graph, ArenaAllocator* arena)
778    : Mir2Lir(cu, mir_graph, arena),
779      base_of_code_(nullptr), store_method_addr_(false), store_method_addr_used_(false),
780      method_address_insns_(arena, 100, kGrowableArrayMisc),
781      class_type_address_insns_(arena, 100, kGrowableArrayMisc),
782      call_method_insns_(arena, 100, kGrowableArrayMisc),
783      stack_decrement_(nullptr), stack_increment_(nullptr),
784      const_vectors_(nullptr) {
785  store_method_addr_used_ = false;
786  if (kIsDebugBuild) {
787    for (int i = 0; i < kX86Last; i++) {
788      if (X86Mir2Lir::EncodingMap[i].opcode != i) {
789        LOG(FATAL) << "Encoding order for " << X86Mir2Lir::EncodingMap[i].name
790                   << " is wrong: expecting " << i << ", seeing "
791                   << static_cast<int>(X86Mir2Lir::EncodingMap[i].opcode);
792      }
793    }
794  }
795  if (cu_->target64) {
796    rs_rX86_SP = rs_rX86_SP_64;
797
798    rs_rX86_ARG0 = rs_rDI;
799    rs_rX86_ARG1 = rs_rSI;
800    rs_rX86_ARG2 = rs_rDX;
801    rs_rX86_ARG3 = rs_rCX;
802    rs_rX86_ARG4 = rs_r8;
803    rs_rX86_ARG5 = rs_r9;
804    rs_rX86_FARG0 = rs_fr0;
805    rs_rX86_FARG1 = rs_fr1;
806    rs_rX86_FARG2 = rs_fr2;
807    rs_rX86_FARG3 = rs_fr3;
808    rs_rX86_FARG4 = rs_fr4;
809    rs_rX86_FARG5 = rs_fr5;
810    rs_rX86_FARG6 = rs_fr6;
811    rs_rX86_FARG7 = rs_fr7;
812    rX86_ARG0 = rDI;
813    rX86_ARG1 = rSI;
814    rX86_ARG2 = rDX;
815    rX86_ARG3 = rCX;
816    rX86_ARG4 = r8;
817    rX86_ARG5 = r9;
818    rX86_FARG0 = fr0;
819    rX86_FARG1 = fr1;
820    rX86_FARG2 = fr2;
821    rX86_FARG3 = fr3;
822    rX86_FARG4 = fr4;
823    rX86_FARG5 = fr5;
824    rX86_FARG6 = fr6;
825    rX86_FARG7 = fr7;
826    rs_rX86_INVOKE_TGT = rs_rDI;
827  } else {
828    rs_rX86_SP = rs_rX86_SP_32;
829
830    rs_rX86_ARG0 = rs_rAX;
831    rs_rX86_ARG1 = rs_rCX;
832    rs_rX86_ARG2 = rs_rDX;
833    rs_rX86_ARG3 = rs_rBX;
834    rs_rX86_ARG4 = RegStorage::InvalidReg();
835    rs_rX86_ARG5 = RegStorage::InvalidReg();
836    rs_rX86_FARG0 = rs_rAX;
837    rs_rX86_FARG1 = rs_rCX;
838    rs_rX86_FARG2 = rs_rDX;
839    rs_rX86_FARG3 = rs_rBX;
840    rs_rX86_FARG4 = RegStorage::InvalidReg();
841    rs_rX86_FARG5 = RegStorage::InvalidReg();
842    rs_rX86_FARG6 = RegStorage::InvalidReg();
843    rs_rX86_FARG7 = RegStorage::InvalidReg();
844    rX86_ARG0 = rAX;
845    rX86_ARG1 = rCX;
846    rX86_ARG2 = rDX;
847    rX86_ARG3 = rBX;
848    rX86_FARG0 = rAX;
849    rX86_FARG1 = rCX;
850    rX86_FARG2 = rDX;
851    rX86_FARG3 = rBX;
852    rs_rX86_INVOKE_TGT = rs_rAX;
853    // TODO(64): Initialize with invalid reg
854//    rX86_ARG4 = RegStorage::InvalidReg();
855//    rX86_ARG5 = RegStorage::InvalidReg();
856  }
857  rs_rX86_RET0 = rs_rAX;
858  rs_rX86_RET1 = rs_rDX;
859  rs_rX86_COUNT = rs_rCX;
860  rX86_RET0 = rAX;
861  rX86_RET1 = rDX;
862  rX86_INVOKE_TGT = rAX;
863  rX86_COUNT = rCX;
864
865  // Initialize the number of reserved vector registers
866  num_reserved_vector_regs_ = -1;
867}
868
869Mir2Lir* X86CodeGenerator(CompilationUnit* const cu, MIRGraph* const mir_graph,
870                          ArenaAllocator* const arena) {
871  return new X86Mir2Lir(cu, mir_graph, arena);
872}
873
874// Not used in x86(-64)
875RegStorage X86Mir2Lir::LoadHelper(QuickEntrypointEnum trampoline) {
876  LOG(FATAL) << "Unexpected use of LoadHelper in x86";
877  return RegStorage::InvalidReg();
878}
879
880LIR* X86Mir2Lir::CheckSuspendUsingLoad() {
881  // First load the pointer in fs:[suspend-trigger] into eax
882  // Then use a test instruction to indirect via that address.
883  if (cu_->target64) {
884    NewLIR2(kX86Mov64RT, rs_rAX.GetReg(),
885        Thread::ThreadSuspendTriggerOffset<8>().Int32Value());
886  } else {
887    NewLIR2(kX86Mov32RT, rs_rAX.GetReg(),
888        Thread::ThreadSuspendTriggerOffset<4>().Int32Value());
889  }
890  return NewLIR3(kX86Test32RM, rs_rAX.GetReg(), rs_rAX.GetReg(), 0);
891}
892
893uint64_t X86Mir2Lir::GetTargetInstFlags(int opcode) {
894  DCHECK(!IsPseudoLirOp(opcode));
895  return X86Mir2Lir::EncodingMap[opcode].flags;
896}
897
898const char* X86Mir2Lir::GetTargetInstName(int opcode) {
899  DCHECK(!IsPseudoLirOp(opcode));
900  return X86Mir2Lir::EncodingMap[opcode].name;
901}
902
903const char* X86Mir2Lir::GetTargetInstFmt(int opcode) {
904  DCHECK(!IsPseudoLirOp(opcode));
905  return X86Mir2Lir::EncodingMap[opcode].fmt;
906}
907
908void X86Mir2Lir::GenConstWide(RegLocation rl_dest, int64_t value) {
909  // Can we do this directly to memory?
910  rl_dest = UpdateLocWide(rl_dest);
911  if ((rl_dest.location == kLocDalvikFrame) ||
912      (rl_dest.location == kLocCompilerTemp)) {
913    int32_t val_lo = Low32Bits(value);
914    int32_t val_hi = High32Bits(value);
915    int r_base = rs_rX86_SP.GetReg();
916    int displacement = SRegOffset(rl_dest.s_reg_low);
917
918    ScopedMemRefType mem_ref_type(this, ResourceMask::kDalvikReg);
919    LIR * store = NewLIR3(kX86Mov32MI, r_base, displacement + LOWORD_OFFSET, val_lo);
920    AnnotateDalvikRegAccess(store, (displacement + LOWORD_OFFSET) >> 2,
921                              false /* is_load */, true /* is64bit */);
922    store = NewLIR3(kX86Mov32MI, r_base, displacement + HIWORD_OFFSET, val_hi);
923    AnnotateDalvikRegAccess(store, (displacement + HIWORD_OFFSET) >> 2,
924                              false /* is_load */, true /* is64bit */);
925    return;
926  }
927
928  // Just use the standard code to do the generation.
929  Mir2Lir::GenConstWide(rl_dest, value);
930}
931
932// TODO: Merge with existing RegLocation dumper in vreg_analysis.cc
933void X86Mir2Lir::DumpRegLocation(RegLocation loc) {
934  LOG(INFO)  << "location: " << loc.location << ','
935             << (loc.wide ? " w" : "  ")
936             << (loc.defined ? " D" : "  ")
937             << (loc.is_const ? " c" : "  ")
938             << (loc.fp ? " F" : "  ")
939             << (loc.core ? " C" : "  ")
940             << (loc.ref ? " r" : "  ")
941             << (loc.high_word ? " h" : "  ")
942             << (loc.home ? " H" : "  ")
943             << ", low: " << static_cast<int>(loc.reg.GetLowReg())
944             << ", high: " << static_cast<int>(loc.reg.GetHighReg())
945             << ", s_reg: " << loc.s_reg_low
946             << ", orig: " << loc.orig_sreg;
947}
948
949void X86Mir2Lir::Materialize() {
950  // A good place to put the analysis before starting.
951  AnalyzeMIR();
952
953  // Now continue with regular code generation.
954  Mir2Lir::Materialize();
955}
956
957void X86Mir2Lir::LoadMethodAddress(const MethodReference& target_method, InvokeType type,
958                                   SpecialTargetRegister symbolic_reg) {
959  /*
960   * For x86, just generate a 32 bit move immediate instruction, that will be filled
961   * in at 'link time'.  For now, put a unique value based on target to ensure that
962   * code deduplication works.
963   */
964  int target_method_idx = target_method.dex_method_index;
965  const DexFile* target_dex_file = target_method.dex_file;
966  const DexFile::MethodId& target_method_id = target_dex_file->GetMethodId(target_method_idx);
967  uintptr_t target_method_id_ptr = reinterpret_cast<uintptr_t>(&target_method_id);
968
969  // Generate the move instruction with the unique pointer and save index, dex_file, and type.
970  LIR *move = RawLIR(current_dalvik_offset_, kX86Mov32RI,
971                     TargetReg(symbolic_reg, kNotWide).GetReg(),
972                     static_cast<int>(target_method_id_ptr), target_method_idx,
973                     WrapPointer(const_cast<DexFile*>(target_dex_file)), type);
974  AppendLIR(move);
975  method_address_insns_.Insert(move);
976}
977
978void X86Mir2Lir::LoadClassType(uint32_t type_idx, SpecialTargetRegister symbolic_reg) {
979  /*
980   * For x86, just generate a 32 bit move immediate instruction, that will be filled
981   * in at 'link time'.  For now, put a unique value based on target to ensure that
982   * code deduplication works.
983   */
984  const DexFile::TypeId& id = cu_->dex_file->GetTypeId(type_idx);
985  uintptr_t ptr = reinterpret_cast<uintptr_t>(&id);
986
987  // Generate the move instruction with the unique pointer and save index and type.
988  LIR *move = RawLIR(current_dalvik_offset_, kX86Mov32RI,
989                     TargetReg(symbolic_reg, kNotWide).GetReg(),
990                     static_cast<int>(ptr), type_idx);
991  AppendLIR(move);
992  class_type_address_insns_.Insert(move);
993}
994
995LIR *X86Mir2Lir::CallWithLinkerFixup(const MethodReference& target_method, InvokeType type) {
996  /*
997   * For x86, just generate a 32 bit call relative instruction, that will be filled
998   * in at 'link time'.  For now, put a unique value based on target to ensure that
999   * code deduplication works.
1000   */
1001  int target_method_idx = target_method.dex_method_index;
1002  const DexFile* target_dex_file = target_method.dex_file;
1003  const DexFile::MethodId& target_method_id = target_dex_file->GetMethodId(target_method_idx);
1004  uintptr_t target_method_id_ptr = reinterpret_cast<uintptr_t>(&target_method_id);
1005
1006  // Generate the call instruction with the unique pointer and save index, dex_file, and type.
1007  LIR *call = RawLIR(current_dalvik_offset_, kX86CallI, static_cast<int>(target_method_id_ptr),
1008                     target_method_idx, WrapPointer(const_cast<DexFile*>(target_dex_file)), type);
1009  AppendLIR(call);
1010  call_method_insns_.Insert(call);
1011  return call;
1012}
1013
1014/*
1015 * @brief Enter a 32 bit quantity into a buffer
1016 * @param buf buffer.
1017 * @param data Data value.
1018 */
1019
1020static void PushWord(std::vector<uint8_t>&buf, int32_t data) {
1021  buf.push_back(data & 0xff);
1022  buf.push_back((data >> 8) & 0xff);
1023  buf.push_back((data >> 16) & 0xff);
1024  buf.push_back((data >> 24) & 0xff);
1025}
1026
1027void X86Mir2Lir::InstallLiteralPools() {
1028  // These are handled differently for x86.
1029  DCHECK(code_literal_list_ == nullptr);
1030  DCHECK(method_literal_list_ == nullptr);
1031  DCHECK(class_literal_list_ == nullptr);
1032
1033  // Align to 16 byte boundary.  We have implicit knowledge that the start of the method is
1034  // on a 4 byte boundary.   How can I check this if it changes (other than aligned loads
1035  // will fail at runtime)?
1036  if (const_vectors_ != nullptr) {
1037    int align_size = (16-4) - (code_buffer_.size() & 0xF);
1038    if (align_size < 0) {
1039      align_size += 16;
1040    }
1041
1042    while (align_size > 0) {
1043      code_buffer_.push_back(0);
1044      align_size--;
1045    }
1046    for (LIR *p = const_vectors_; p != nullptr; p = p->next) {
1047      PushWord(code_buffer_, p->operands[0]);
1048      PushWord(code_buffer_, p->operands[1]);
1049      PushWord(code_buffer_, p->operands[2]);
1050      PushWord(code_buffer_, p->operands[3]);
1051    }
1052  }
1053
1054  // Handle the fixups for methods.
1055  for (uint32_t i = 0; i < method_address_insns_.Size(); i++) {
1056      LIR* p = method_address_insns_.Get(i);
1057      DCHECK_EQ(p->opcode, kX86Mov32RI);
1058      uint32_t target_method_idx = p->operands[2];
1059      const DexFile* target_dex_file =
1060          reinterpret_cast<const DexFile*>(UnwrapPointer(p->operands[3]));
1061
1062      // The offset to patch is the last 4 bytes of the instruction.
1063      int patch_offset = p->offset + p->flags.size - 4;
1064      cu_->compiler_driver->AddMethodPatch(cu_->dex_file, cu_->class_def_idx,
1065                                           cu_->method_idx, cu_->invoke_type,
1066                                           target_method_idx, target_dex_file,
1067                                           static_cast<InvokeType>(p->operands[4]),
1068                                           patch_offset);
1069  }
1070
1071  // Handle the fixups for class types.
1072  for (uint32_t i = 0; i < class_type_address_insns_.Size(); i++) {
1073      LIR* p = class_type_address_insns_.Get(i);
1074      DCHECK_EQ(p->opcode, kX86Mov32RI);
1075      uint32_t target_method_idx = p->operands[2];
1076
1077      // The offset to patch is the last 4 bytes of the instruction.
1078      int patch_offset = p->offset + p->flags.size - 4;
1079      cu_->compiler_driver->AddClassPatch(cu_->dex_file, cu_->class_def_idx,
1080                                          cu_->method_idx, target_method_idx, patch_offset);
1081  }
1082
1083  // And now the PC-relative calls to methods.
1084  for (uint32_t i = 0; i < call_method_insns_.Size(); i++) {
1085      LIR* p = call_method_insns_.Get(i);
1086      DCHECK_EQ(p->opcode, kX86CallI);
1087      uint32_t target_method_idx = p->operands[1];
1088      const DexFile* target_dex_file =
1089          reinterpret_cast<const DexFile*>(UnwrapPointer(p->operands[2]));
1090
1091      // The offset to patch is the last 4 bytes of the instruction.
1092      int patch_offset = p->offset + p->flags.size - 4;
1093      cu_->compiler_driver->AddRelativeCodePatch(cu_->dex_file, cu_->class_def_idx,
1094                                                 cu_->method_idx, cu_->invoke_type,
1095                                                 target_method_idx, target_dex_file,
1096                                                 static_cast<InvokeType>(p->operands[3]),
1097                                                 patch_offset, -4 /* offset */);
1098  }
1099
1100  // And do the normal processing.
1101  Mir2Lir::InstallLiteralPools();
1102}
1103
1104bool X86Mir2Lir::GenInlinedArrayCopyCharArray(CallInfo* info) {
1105  RegLocation rl_src = info->args[0];
1106  RegLocation rl_srcPos = info->args[1];
1107  RegLocation rl_dst = info->args[2];
1108  RegLocation rl_dstPos = info->args[3];
1109  RegLocation rl_length = info->args[4];
1110  if (rl_srcPos.is_const && (mir_graph_->ConstantValue(rl_srcPos) < 0)) {
1111    return false;
1112  }
1113  if (rl_dstPos.is_const && (mir_graph_->ConstantValue(rl_dstPos) < 0)) {
1114    return false;
1115  }
1116  ClobberCallerSave();
1117  LockCallTemps();  // Using fixed registers.
1118  RegStorage tmp_reg = cu_->target64 ? rs_r11 : rs_rBX;
1119  LoadValueDirectFixed(rl_src, rs_rAX);
1120  LoadValueDirectFixed(rl_dst, rs_rCX);
1121  LIR* src_dst_same  = OpCmpBranch(kCondEq, rs_rAX, rs_rCX, nullptr);
1122  LIR* src_null_branch = OpCmpImmBranch(kCondEq, rs_rAX, 0, nullptr);
1123  LIR* dst_null_branch = OpCmpImmBranch(kCondEq, rs_rCX, 0, nullptr);
1124  LoadValueDirectFixed(rl_length, rs_rDX);
1125  // If the length of the copy is > 128 characters (256 bytes) or negative then go slow path.
1126  LIR* len_too_big  = OpCmpImmBranch(kCondHi, rs_rDX, 128, nullptr);
1127  LoadValueDirectFixed(rl_src, rs_rAX);
1128  LoadWordDisp(rs_rAX, mirror::Array::LengthOffset().Int32Value(), rs_rAX);
1129  LIR* src_bad_len  = nullptr;
1130  LIR* srcPos_negative  = nullptr;
1131  if (!rl_srcPos.is_const) {
1132    LoadValueDirectFixed(rl_srcPos, tmp_reg);
1133    srcPos_negative  = OpCmpImmBranch(kCondLt, tmp_reg, 0, nullptr);
1134    OpRegReg(kOpAdd, tmp_reg, rs_rDX);
1135    src_bad_len  = OpCmpBranch(kCondLt, rs_rAX, tmp_reg, nullptr);
1136  } else {
1137    int32_t pos_val = mir_graph_->ConstantValue(rl_srcPos.orig_sreg);
1138    if (pos_val == 0) {
1139      src_bad_len  = OpCmpBranch(kCondLt, rs_rAX, rs_rDX, nullptr);
1140    } else {
1141      OpRegRegImm(kOpAdd, tmp_reg,  rs_rDX, pos_val);
1142      src_bad_len  = OpCmpBranch(kCondLt, rs_rAX, tmp_reg, nullptr);
1143    }
1144  }
1145  LIR* dstPos_negative = nullptr;
1146  LIR* dst_bad_len = nullptr;
1147  LoadValueDirectFixed(rl_dst, rs_rAX);
1148  LoadWordDisp(rs_rAX, mirror::Array::LengthOffset().Int32Value(), rs_rAX);
1149  if (!rl_dstPos.is_const) {
1150    LoadValueDirectFixed(rl_dstPos, tmp_reg);
1151    dstPos_negative = OpCmpImmBranch(kCondLt, tmp_reg, 0, nullptr);
1152    OpRegRegReg(kOpAdd, tmp_reg, tmp_reg, rs_rDX);
1153    dst_bad_len = OpCmpBranch(kCondLt, rs_rAX, tmp_reg, nullptr);
1154  } else {
1155    int32_t pos_val = mir_graph_->ConstantValue(rl_dstPos.orig_sreg);
1156    if (pos_val == 0) {
1157      dst_bad_len = OpCmpBranch(kCondLt, rs_rAX, rs_rDX, nullptr);
1158    } else {
1159      OpRegRegImm(kOpAdd, tmp_reg,  rs_rDX, pos_val);
1160      dst_bad_len = OpCmpBranch(kCondLt, rs_rAX, tmp_reg, nullptr);
1161    }
1162  }
1163  // Everything is checked now.
1164  LoadValueDirectFixed(rl_src, rs_rAX);
1165  LoadValueDirectFixed(rl_dst, tmp_reg);
1166  LoadValueDirectFixed(rl_srcPos, rs_rCX);
1167  NewLIR5(kX86Lea32RA, rs_rAX.GetReg(), rs_rAX.GetReg(),
1168       rs_rCX.GetReg(), 1, mirror::Array::DataOffset(2).Int32Value());
1169  // RAX now holds the address of the first src element to be copied.
1170
1171  LoadValueDirectFixed(rl_dstPos, rs_rCX);
1172  NewLIR5(kX86Lea32RA, tmp_reg.GetReg(), tmp_reg.GetReg(),
1173       rs_rCX.GetReg(), 1, mirror::Array::DataOffset(2).Int32Value() );
1174  // RBX now holds the address of the first dst element to be copied.
1175
1176  // Check if the number of elements to be copied is odd or even. If odd
1177  // then copy the first element (so that the remaining number of elements
1178  // is even).
1179  LoadValueDirectFixed(rl_length, rs_rCX);
1180  OpRegImm(kOpAnd, rs_rCX, 1);
1181  LIR* jmp_to_begin_loop  = OpCmpImmBranch(kCondEq, rs_rCX, 0, nullptr);
1182  OpRegImm(kOpSub, rs_rDX, 1);
1183  LoadBaseIndexedDisp(rs_rAX, rs_rDX, 1, 0, rs_rCX, kSignedHalf);
1184  StoreBaseIndexedDisp(tmp_reg, rs_rDX, 1, 0, rs_rCX, kSignedHalf);
1185
1186  // Since the remaining number of elements is even, we will copy by
1187  // two elements at a time.
1188  LIR* beginLoop = NewLIR0(kPseudoTargetLabel);
1189  LIR* jmp_to_ret  = OpCmpImmBranch(kCondEq, rs_rDX, 0, nullptr);
1190  OpRegImm(kOpSub, rs_rDX, 2);
1191  LoadBaseIndexedDisp(rs_rAX, rs_rDX, 1, 0, rs_rCX, kSingle);
1192  StoreBaseIndexedDisp(tmp_reg, rs_rDX, 1, 0, rs_rCX, kSingle);
1193  OpUnconditionalBranch(beginLoop);
1194  LIR *check_failed = NewLIR0(kPseudoTargetLabel);
1195  LIR* launchpad_branch  = OpUnconditionalBranch(nullptr);
1196  LIR *return_point = NewLIR0(kPseudoTargetLabel);
1197  jmp_to_ret->target = return_point;
1198  jmp_to_begin_loop->target = beginLoop;
1199  src_dst_same->target = check_failed;
1200  len_too_big->target = check_failed;
1201  src_null_branch->target = check_failed;
1202  if (srcPos_negative != nullptr)
1203    srcPos_negative ->target = check_failed;
1204  if (src_bad_len != nullptr)
1205    src_bad_len->target = check_failed;
1206  dst_null_branch->target = check_failed;
1207  if (dstPos_negative != nullptr)
1208    dstPos_negative->target = check_failed;
1209  if (dst_bad_len != nullptr)
1210    dst_bad_len->target = check_failed;
1211  AddIntrinsicSlowPath(info, launchpad_branch, return_point);
1212  ClobberCallerSave();  // We must clobber everything because slow path will return here
1213  return true;
1214}
1215
1216
1217/*
1218 * Fast string.index_of(I) & (II).  Inline check for simple case of char <= 0xffff,
1219 * otherwise bails to standard library code.
1220 */
1221bool X86Mir2Lir::GenInlinedIndexOf(CallInfo* info, bool zero_based) {
1222  RegLocation rl_obj = info->args[0];
1223  RegLocation rl_char = info->args[1];
1224  RegLocation rl_start;  // Note: only present in III flavor or IndexOf.
1225  // RBX is callee-save register in 64-bit mode.
1226  RegStorage rs_tmp = cu_->target64 ? rs_r11 : rs_rBX;
1227  int start_value = -1;
1228
1229  uint32_t char_value =
1230    rl_char.is_const ? mir_graph_->ConstantValue(rl_char.orig_sreg) : 0;
1231
1232  if (char_value > 0xFFFF) {
1233    // We have to punt to the real String.indexOf.
1234    return false;
1235  }
1236
1237  // Okay, we are commited to inlining this.
1238  // EAX: 16 bit character being searched.
1239  // ECX: count: number of words to be searched.
1240  // EDI: String being searched.
1241  // EDX: temporary during execution.
1242  // EBX or R11: temporary during execution (depending on mode).
1243  // REP SCASW: search instruction.
1244
1245  FlushReg(rs_rAX);
1246  Clobber(rs_rAX);
1247  LockTemp(rs_rAX);
1248  FlushReg(rs_rCX);
1249  Clobber(rs_rCX);
1250  LockTemp(rs_rCX);
1251  FlushReg(rs_rDX);
1252  Clobber(rs_rDX);
1253  LockTemp(rs_rDX);
1254  FlushReg(rs_tmp);
1255  Clobber(rs_tmp);
1256  LockTemp(rs_tmp);
1257  if (cu_->target64) {
1258    FlushReg(rs_rDI);
1259    Clobber(rs_rDI);
1260    LockTemp(rs_rDI);
1261  }
1262
1263  RegLocation rl_return = GetReturn(kCoreReg);
1264  RegLocation rl_dest = InlineTarget(info);
1265
1266  // Is the string non-NULL?
1267  LoadValueDirectFixed(rl_obj, rs_rDX);
1268  GenNullCheck(rs_rDX, info->opt_flags);
1269  info->opt_flags |= MIR_IGNORE_NULL_CHECK;  // Record that we've null checked.
1270
1271  LIR *slowpath_branch = nullptr, *length_compare = nullptr;
1272
1273  // We need the value in EAX.
1274  if (rl_char.is_const) {
1275    LoadConstantNoClobber(rs_rAX, char_value);
1276  } else {
1277    // Does the character fit in 16 bits? Compare it at runtime.
1278    LoadValueDirectFixed(rl_char, rs_rAX);
1279    slowpath_branch = OpCmpImmBranch(kCondGt, rs_rAX, 0xFFFF, nullptr);
1280  }
1281
1282  // From here down, we know that we are looking for a char that fits in 16 bits.
1283  // Location of reference to data array within the String object.
1284  int value_offset = mirror::String::ValueOffset().Int32Value();
1285  // Location of count within the String object.
1286  int count_offset = mirror::String::CountOffset().Int32Value();
1287  // Starting offset within data array.
1288  int offset_offset = mirror::String::OffsetOffset().Int32Value();
1289  // Start of char data with array_.
1290  int data_offset = mirror::Array::DataOffset(sizeof(uint16_t)).Int32Value();
1291
1292  // Compute the number of words to search in to rCX.
1293  Load32Disp(rs_rDX, count_offset, rs_rCX);
1294
1295  // Possible signal here due to null pointer dereference.
1296  // Note that the signal handler will expect the top word of
1297  // the stack to be the ArtMethod*.  If the PUSH edi instruction
1298  // below is ahead of the load above then this will not be true
1299  // and the signal handler will not work.
1300  MarkPossibleNullPointerException(0);
1301
1302  if (!cu_->target64) {
1303    // EDI is callee-save register in 32-bit mode.
1304    NewLIR1(kX86Push32R, rs_rDI.GetReg());
1305  }
1306
1307  if (zero_based) {
1308    // Start index is not present.
1309    // We have to handle an empty string.  Use special instruction JECXZ.
1310    length_compare = NewLIR0(kX86Jecxz8);
1311
1312    // Copy the number of words to search in a temporary register.
1313    // We will use the register at the end to calculate result.
1314    OpRegReg(kOpMov, rs_tmp, rs_rCX);
1315  } else {
1316    // Start index is present.
1317    rl_start = info->args[2];
1318
1319    // We have to offset by the start index.
1320    if (rl_start.is_const) {
1321      start_value = mir_graph_->ConstantValue(rl_start.orig_sreg);
1322      start_value = std::max(start_value, 0);
1323
1324      // Is the start > count?
1325      length_compare = OpCmpImmBranch(kCondLe, rs_rCX, start_value, nullptr);
1326      OpRegImm(kOpMov, rs_rDI, start_value);
1327
1328      // Copy the number of words to search in a temporary register.
1329      // We will use the register at the end to calculate result.
1330      OpRegReg(kOpMov, rs_tmp, rs_rCX);
1331
1332      if (start_value != 0) {
1333        // Decrease the number of words to search by the start index.
1334        OpRegImm(kOpSub, rs_rCX, start_value);
1335      }
1336    } else {
1337      // Handle "start index < 0" case.
1338      if (!cu_->target64 && rl_start.location != kLocPhysReg) {
1339        // Load the start index from stack, remembering that we pushed EDI.
1340        int displacement = SRegOffset(rl_start.s_reg_low) + sizeof(uint32_t);
1341        ScopedMemRefType mem_ref_type(this, ResourceMask::kDalvikReg);
1342        Load32Disp(rs_rX86_SP, displacement, rs_rDI);
1343        // Dalvik register annotation in LoadBaseIndexedDisp() used wrong offset. Fix it.
1344        DCHECK(!DECODE_ALIAS_INFO_WIDE(last_lir_insn_->flags.alias_info));
1345        int reg_id = DECODE_ALIAS_INFO_REG(last_lir_insn_->flags.alias_info) - 1;
1346        AnnotateDalvikRegAccess(last_lir_insn_, reg_id, true, false);
1347      } else {
1348        LoadValueDirectFixed(rl_start, rs_rDI);
1349      }
1350      OpRegReg(kOpXor, rs_tmp, rs_tmp);
1351      OpRegReg(kOpCmp, rs_rDI, rs_tmp);
1352      OpCondRegReg(kOpCmov, kCondLt, rs_rDI, rs_tmp);
1353
1354      // The length of the string should be greater than the start index.
1355      length_compare = OpCmpBranch(kCondLe, rs_rCX, rs_rDI, nullptr);
1356
1357      // Copy the number of words to search in a temporary register.
1358      // We will use the register at the end to calculate result.
1359      OpRegReg(kOpMov, rs_tmp, rs_rCX);
1360
1361      // Decrease the number of words to search by the start index.
1362      OpRegReg(kOpSub, rs_rCX, rs_rDI);
1363    }
1364  }
1365
1366  // Load the address of the string into EDI.
1367  // In case of start index we have to add the address to existing value in EDI.
1368  // The string starts at VALUE(String) + 2 * OFFSET(String) + DATA_OFFSET.
1369  if (zero_based || (!zero_based && rl_start.is_const && start_value == 0)) {
1370    Load32Disp(rs_rDX, offset_offset, rs_rDI);
1371  } else {
1372    OpRegMem(kOpAdd, rs_rDI, rs_rDX, offset_offset);
1373  }
1374  OpRegImm(kOpLsl, rs_rDI, 1);
1375  OpRegMem(kOpAdd, rs_rDI, rs_rDX, value_offset);
1376  OpRegImm(kOpAdd, rs_rDI, data_offset);
1377
1378  // EDI now contains the start of the string to be searched.
1379  // We are all prepared to do the search for the character.
1380  NewLIR0(kX86RepneScasw);
1381
1382  // Did we find a match?
1383  LIR* failed_branch = OpCondBranch(kCondNe, nullptr);
1384
1385  // yes, we matched.  Compute the index of the result.
1386  OpRegReg(kOpSub, rs_tmp, rs_rCX);
1387  NewLIR3(kX86Lea32RM, rl_return.reg.GetReg(), rs_tmp.GetReg(), -1);
1388
1389  LIR *all_done = NewLIR1(kX86Jmp8, 0);
1390
1391  // Failed to match; return -1.
1392  LIR *not_found = NewLIR0(kPseudoTargetLabel);
1393  length_compare->target = not_found;
1394  failed_branch->target = not_found;
1395  LoadConstantNoClobber(rl_return.reg, -1);
1396
1397  // And join up at the end.
1398  all_done->target = NewLIR0(kPseudoTargetLabel);
1399
1400  if (!cu_->target64)
1401    NewLIR1(kX86Pop32R, rs_rDI.GetReg());
1402
1403  // Out of line code returns here.
1404  if (slowpath_branch != nullptr) {
1405    LIR *return_point = NewLIR0(kPseudoTargetLabel);
1406    AddIntrinsicSlowPath(info, slowpath_branch, return_point);
1407    ClobberCallerSave();  // We must clobber everything because slow path will return here
1408  }
1409
1410  StoreValue(rl_dest, rl_return);
1411
1412  FreeTemp(rs_rAX);
1413  FreeTemp(rs_rCX);
1414  FreeTemp(rs_rDX);
1415  FreeTemp(rs_tmp);
1416  if (cu_->target64) {
1417    FreeTemp(rs_rDI);
1418  }
1419
1420  return true;
1421}
1422
1423/*
1424 * @brief Enter an 'advance LOC' into the FDE buffer
1425 * @param buf FDE buffer.
1426 * @param increment Amount by which to increase the current location.
1427 */
1428static void AdvanceLoc(std::vector<uint8_t>&buf, uint32_t increment) {
1429  if (increment < 64) {
1430    // Encoding in opcode.
1431    buf.push_back(0x1 << 6 | increment);
1432  } else if (increment < 256) {
1433    // Single byte delta.
1434    buf.push_back(0x02);
1435    buf.push_back(increment);
1436  } else if (increment < 256 * 256) {
1437    // Two byte delta.
1438    buf.push_back(0x03);
1439    buf.push_back(increment & 0xff);
1440    buf.push_back((increment >> 8) & 0xff);
1441  } else {
1442    // Four byte delta.
1443    buf.push_back(0x04);
1444    PushWord(buf, increment);
1445  }
1446}
1447
1448
1449std::vector<uint8_t>* X86CFIInitialization(bool is_x86_64) {
1450  return X86Mir2Lir::ReturnCommonCallFrameInformation(is_x86_64);
1451}
1452
1453static void EncodeUnsignedLeb128(std::vector<uint8_t>& buf, uint32_t value) {
1454  uint8_t buffer[12];
1455  uint8_t *ptr = EncodeUnsignedLeb128(buffer, value);
1456  for (uint8_t *p = buffer; p < ptr; p++) {
1457    buf.push_back(*p);
1458  }
1459}
1460
1461static void EncodeSignedLeb128(std::vector<uint8_t>& buf, int32_t value) {
1462  uint8_t buffer[12];
1463  uint8_t *ptr = EncodeSignedLeb128(buffer, value);
1464  for (uint8_t *p = buffer; p < ptr; p++) {
1465    buf.push_back(*p);
1466  }
1467}
1468
1469std::vector<uint8_t>* X86Mir2Lir::ReturnCommonCallFrameInformation(bool is_x86_64) {
1470  std::vector<uint8_t>*cfi_info = new std::vector<uint8_t>;
1471
1472  // Length (will be filled in later in this routine).
1473  PushWord(*cfi_info, 0);
1474
1475  // CIE id: always 0.
1476  PushWord(*cfi_info, 0);
1477
1478  // Version: always 1.
1479  cfi_info->push_back(0x01);
1480
1481  // Augmentation: 'zR\0'
1482  cfi_info->push_back(0x7a);
1483  cfi_info->push_back(0x52);
1484  cfi_info->push_back(0x0);
1485
1486  // Code alignment: 1.
1487  EncodeUnsignedLeb128(*cfi_info, 1);
1488
1489  // Data alignment.
1490  if (is_x86_64) {
1491    EncodeSignedLeb128(*cfi_info, -8);
1492  } else {
1493    EncodeSignedLeb128(*cfi_info, -4);
1494  }
1495
1496  // Return address register.
1497  if (is_x86_64) {
1498    // R16(RIP)
1499    cfi_info->push_back(0x10);
1500  } else {
1501    // R8(EIP)
1502    cfi_info->push_back(0x08);
1503  }
1504
1505  // Augmentation length: 1.
1506  cfi_info->push_back(1);
1507
1508  // Augmentation data: 0x03 ((DW_EH_PE_absptr << 4) | DW_EH_PE_udata4).
1509  cfi_info->push_back(0x03);
1510
1511  // Initial instructions.
1512  if (is_x86_64) {
1513    // DW_CFA_def_cfa R7(RSP) 8.
1514    cfi_info->push_back(0x0c);
1515    cfi_info->push_back(0x07);
1516    cfi_info->push_back(0x08);
1517
1518    // DW_CFA_offset R16(RIP) 1 (* -8).
1519    cfi_info->push_back(0x90);
1520    cfi_info->push_back(0x01);
1521  } else {
1522    // DW_CFA_def_cfa R4(ESP) 4.
1523    cfi_info->push_back(0x0c);
1524    cfi_info->push_back(0x04);
1525    cfi_info->push_back(0x04);
1526
1527    // DW_CFA_offset R8(EIP) 1 (* -4).
1528    cfi_info->push_back(0x88);
1529    cfi_info->push_back(0x01);
1530  }
1531
1532  // Padding to a multiple of 4
1533  while ((cfi_info->size() & 3) != 0) {
1534    // DW_CFA_nop is encoded as 0.
1535    cfi_info->push_back(0);
1536  }
1537
1538  // Set the length of the CIE inside the generated bytes.
1539  uint32_t length = cfi_info->size() - 4;
1540  (*cfi_info)[0] = length;
1541  (*cfi_info)[1] = length >> 8;
1542  (*cfi_info)[2] = length >> 16;
1543  (*cfi_info)[3] = length >> 24;
1544  return cfi_info;
1545}
1546
1547static bool ARTRegIDToDWARFRegID(bool is_x86_64, int art_reg_id, int* dwarf_reg_id) {
1548  if (is_x86_64) {
1549    switch (art_reg_id) {
1550    case 3 : *dwarf_reg_id =  3; return true;  // %rbx
1551    // This is the only discrepancy between ART & DWARF register numbering.
1552    case 5 : *dwarf_reg_id =  6; return true;  // %rbp
1553    case 12: *dwarf_reg_id = 12; return true;  // %r12
1554    case 13: *dwarf_reg_id = 13; return true;  // %r13
1555    case 14: *dwarf_reg_id = 14; return true;  // %r14
1556    case 15: *dwarf_reg_id = 15; return true;  // %r15
1557    default: return false;  // Should not get here
1558    }
1559  } else {
1560    switch (art_reg_id) {
1561    case 5: *dwarf_reg_id = 5; return true;  // %ebp
1562    case 6: *dwarf_reg_id = 6; return true;  // %esi
1563    case 7: *dwarf_reg_id = 7; return true;  // %edi
1564    default: return false;  // Should not get here
1565    }
1566  }
1567}
1568
1569std::vector<uint8_t>* X86Mir2Lir::ReturnCallFrameInformation() {
1570  std::vector<uint8_t>*cfi_info = new std::vector<uint8_t>;
1571
1572  // Generate the FDE for the method.
1573  DCHECK_NE(data_offset_, 0U);
1574
1575  // Length (will be filled in later in this routine).
1576  PushWord(*cfi_info, 0);
1577
1578  // 'CIE_pointer' (filled in by linker).
1579  PushWord(*cfi_info, 0);
1580
1581  // 'initial_location' (filled in by linker).
1582  PushWord(*cfi_info, 0);
1583
1584  // 'address_range' (number of bytes in the method).
1585  PushWord(*cfi_info, data_offset_);
1586
1587  // Augmentation length: 0
1588  cfi_info->push_back(0);
1589
1590  // The instructions in the FDE.
1591  if (stack_decrement_ != nullptr) {
1592    // Advance LOC to just past the stack decrement.
1593    uint32_t pc = NEXT_LIR(stack_decrement_)->offset;
1594    AdvanceLoc(*cfi_info, pc);
1595
1596    // Now update the offset to the call frame: DW_CFA_def_cfa_offset frame_size.
1597    cfi_info->push_back(0x0e);
1598    EncodeUnsignedLeb128(*cfi_info, frame_size_);
1599
1600    // Handle register spills
1601    const uint32_t kSpillInstLen = (cu_->target64) ? 5 : 4;
1602    const int kDataAlignmentFactor = (cu_->target64) ? -8 : -4;
1603    uint32_t mask = core_spill_mask_ & ~(1 << rs_rRET.GetRegNum());
1604    int offset = -(GetInstructionSetPointerSize(cu_->instruction_set) * num_core_spills_);
1605    for (int reg = 0; mask; mask >>= 1, reg++) {
1606      if (mask & 0x1) {
1607        pc += kSpillInstLen;
1608
1609        // Advance LOC to pass this instruction
1610        AdvanceLoc(*cfi_info, kSpillInstLen);
1611
1612        int dwarf_reg_id;
1613        if (ARTRegIDToDWARFRegID(cu_->target64, reg, &dwarf_reg_id)) {
1614          // DW_CFA_offset_extended_sf reg_no offset
1615          cfi_info->push_back(0x11);
1616          EncodeUnsignedLeb128(*cfi_info, dwarf_reg_id);
1617          EncodeSignedLeb128(*cfi_info, offset / kDataAlignmentFactor);
1618        }
1619
1620        offset += GetInstructionSetPointerSize(cu_->instruction_set);
1621      }
1622    }
1623
1624    // We continue with that stack until the epilogue.
1625    if (stack_increment_ != nullptr) {
1626      uint32_t new_pc = NEXT_LIR(stack_increment_)->offset;
1627      AdvanceLoc(*cfi_info, new_pc - pc);
1628
1629      // We probably have code snippets after the epilogue, so save the
1630      // current state: DW_CFA_remember_state.
1631      cfi_info->push_back(0x0a);
1632
1633      // We have now popped the stack: DW_CFA_def_cfa_offset 4/8.
1634      // There is only the return PC on the stack now.
1635      cfi_info->push_back(0x0e);
1636      EncodeUnsignedLeb128(*cfi_info, GetInstructionSetPointerSize(cu_->instruction_set));
1637
1638      // Everything after that is the same as before the epilogue.
1639      // Stack bump was followed by RET instruction.
1640      LIR *post_ret_insn = NEXT_LIR(NEXT_LIR(stack_increment_));
1641      if (post_ret_insn != nullptr) {
1642        pc = new_pc;
1643        new_pc = post_ret_insn->offset;
1644        AdvanceLoc(*cfi_info, new_pc - pc);
1645        // Restore the state: DW_CFA_restore_state.
1646        cfi_info->push_back(0x0b);
1647      }
1648    }
1649  }
1650
1651  // Padding to a multiple of 4
1652  while ((cfi_info->size() & 3) != 0) {
1653    // DW_CFA_nop is encoded as 0.
1654    cfi_info->push_back(0);
1655  }
1656
1657  // Set the length of the FDE inside the generated bytes.
1658  uint32_t length = cfi_info->size() - 4;
1659  (*cfi_info)[0] = length;
1660  (*cfi_info)[1] = length >> 8;
1661  (*cfi_info)[2] = length >> 16;
1662  (*cfi_info)[3] = length >> 24;
1663  return cfi_info;
1664}
1665
1666void X86Mir2Lir::GenMachineSpecificExtendedMethodMIR(BasicBlock* bb, MIR* mir) {
1667  switch (static_cast<ExtendedMIROpcode>(mir->dalvikInsn.opcode)) {
1668    case kMirOpReserveVectorRegisters:
1669      ReserveVectorRegisters(mir);
1670      break;
1671    case kMirOpReturnVectorRegisters:
1672      ReturnVectorRegisters();
1673      break;
1674    case kMirOpConstVector:
1675      GenConst128(bb, mir);
1676      break;
1677    case kMirOpMoveVector:
1678      GenMoveVector(bb, mir);
1679      break;
1680    case kMirOpPackedMultiply:
1681      GenMultiplyVector(bb, mir);
1682      break;
1683    case kMirOpPackedAddition:
1684      GenAddVector(bb, mir);
1685      break;
1686    case kMirOpPackedSubtract:
1687      GenSubtractVector(bb, mir);
1688      break;
1689    case kMirOpPackedShiftLeft:
1690      GenShiftLeftVector(bb, mir);
1691      break;
1692    case kMirOpPackedSignedShiftRight:
1693      GenSignedShiftRightVector(bb, mir);
1694      break;
1695    case kMirOpPackedUnsignedShiftRight:
1696      GenUnsignedShiftRightVector(bb, mir);
1697      break;
1698    case kMirOpPackedAnd:
1699      GenAndVector(bb, mir);
1700      break;
1701    case kMirOpPackedOr:
1702      GenOrVector(bb, mir);
1703      break;
1704    case kMirOpPackedXor:
1705      GenXorVector(bb, mir);
1706      break;
1707    case kMirOpPackedAddReduce:
1708      GenAddReduceVector(bb, mir);
1709      break;
1710    case kMirOpPackedReduce:
1711      GenReduceVector(bb, mir);
1712      break;
1713    case kMirOpPackedSet:
1714      GenSetVector(bb, mir);
1715      break;
1716    default:
1717      break;
1718  }
1719}
1720
1721void X86Mir2Lir::ReserveVectorRegisters(MIR* mir) {
1722  // We should not try to reserve twice without returning the registers
1723  DCHECK_NE(num_reserved_vector_regs_, -1);
1724
1725  int num_vector_reg = mir->dalvikInsn.vA;
1726  for (int i = 0; i < num_vector_reg; i++) {
1727    RegStorage xp_reg = RegStorage::Solo128(i);
1728    RegisterInfo *xp_reg_info = GetRegInfo(xp_reg);
1729    Clobber(xp_reg);
1730
1731    for (RegisterInfo *info = xp_reg_info->GetAliasChain();
1732                       info != nullptr;
1733                       info = info->GetAliasChain()) {
1734      if (info->GetReg().IsSingle()) {
1735        reg_pool_->sp_regs_.Delete(info);
1736      } else {
1737        reg_pool_->dp_regs_.Delete(info);
1738      }
1739    }
1740  }
1741
1742  num_reserved_vector_regs_ = num_vector_reg;
1743}
1744
1745void X86Mir2Lir::ReturnVectorRegisters() {
1746  // Return all the reserved registers
1747  for (int i = 0; i < num_reserved_vector_regs_; i++) {
1748    RegStorage xp_reg = RegStorage::Solo128(i);
1749    RegisterInfo *xp_reg_info = GetRegInfo(xp_reg);
1750
1751    for (RegisterInfo *info = xp_reg_info->GetAliasChain();
1752                       info != nullptr;
1753                       info = info->GetAliasChain()) {
1754      if (info->GetReg().IsSingle()) {
1755        reg_pool_->sp_regs_.Insert(info);
1756      } else {
1757        reg_pool_->dp_regs_.Insert(info);
1758      }
1759    }
1760  }
1761
1762  // We don't have anymore reserved vector registers
1763  num_reserved_vector_regs_ = -1;
1764}
1765
1766void X86Mir2Lir::GenConst128(BasicBlock* bb, MIR* mir) {
1767  store_method_addr_used_ = true;
1768  int type_size = mir->dalvikInsn.vB;
1769  // We support 128 bit vectors.
1770  DCHECK_EQ(type_size & 0xFFFF, 128);
1771  RegStorage rs_dest = RegStorage::Solo128(mir->dalvikInsn.vA);
1772  uint32_t *args = mir->dalvikInsn.arg;
1773  int reg = rs_dest.GetReg();
1774  // Check for all 0 case.
1775  if (args[0] == 0 && args[1] == 0 && args[2] == 0 && args[3] == 0) {
1776    NewLIR2(kX86XorpsRR, reg, reg);
1777    return;
1778  }
1779
1780  // Append the mov const vector to reg opcode.
1781  AppendOpcodeWithConst(kX86MovupsRM, reg, mir);
1782}
1783
1784void X86Mir2Lir::AppendOpcodeWithConst(X86OpCode opcode, int reg, MIR* mir) {
1785  // Okay, load it from the constant vector area.
1786  LIR *data_target = ScanVectorLiteral(mir);
1787  if (data_target == nullptr) {
1788    data_target = AddVectorLiteral(mir);
1789  }
1790
1791  // Address the start of the method.
1792  RegLocation rl_method = mir_graph_->GetRegLocation(base_of_code_->s_reg_low);
1793  if (rl_method.wide) {
1794    rl_method = LoadValueWide(rl_method, kCoreReg);
1795  } else {
1796    rl_method = LoadValue(rl_method, kCoreReg);
1797  }
1798
1799  // Load the proper value from the literal area.
1800  // We don't know the proper offset for the value, so pick one that will force
1801  // 4 byte offset.  We will fix this up in the assembler later to have the right
1802  // value.
1803  ScopedMemRefType mem_ref_type(this, ResourceMask::kLiteral);
1804  LIR *load = NewLIR2(opcode, reg, rl_method.reg.GetReg());
1805  load->flags.fixup = kFixupLoad;
1806  load->target = data_target;
1807}
1808
1809void X86Mir2Lir::GenMoveVector(BasicBlock *bb, MIR *mir) {
1810  // We only support 128 bit registers.
1811  DCHECK_EQ(mir->dalvikInsn.vC & 0xFFFF, 128U);
1812  RegStorage rs_dest = RegStorage::Solo128(mir->dalvikInsn.vA);
1813  RegStorage rs_src = RegStorage::Solo128(mir->dalvikInsn.vB);
1814  NewLIR2(kX86Mova128RR, rs_dest.GetReg(), rs_src.GetReg());
1815}
1816
1817void X86Mir2Lir::GenMultiplyVectorSignedByte(BasicBlock *bb, MIR *mir) {
1818  const int BYTE_SIZE = 8;
1819  RegStorage rs_dest_src1 = RegStorage::Solo128(mir->dalvikInsn.vA);
1820  RegStorage rs_src2 = RegStorage::Solo128(mir->dalvikInsn.vB);
1821  RegStorage rs_src1_high_tmp = Get128BitRegister(AllocTempWide());
1822
1823  /*
1824   * Emulate the behavior of a kSignedByte by separating out the 16 values in the two XMM
1825   * and multiplying 8 at a time before recombining back into one XMM register.
1826   *
1827   *   let xmm1, xmm2 be real srcs (keep low bits of 16bit lanes)
1828   *       xmm3 is tmp             (operate on high bits of 16bit lanes)
1829   *
1830   *    xmm3 = xmm1
1831   *    xmm1 = xmm1 .* xmm2
1832   *    xmm1 = xmm1 & 0x00ff00ff00ff00ff00ff00ff00ff00ff  // xmm1 now has low bits
1833   *    xmm3 = xmm3 .>> 8
1834   *    xmm2 = xmm2 & 0xff00ff00ff00ff00ff00ff00ff00ff00
1835   *    xmm2 = xmm2 .* xmm3                               // xmm2 now has high bits
1836   *    xmm1 = xmm1 | xmm2                                // combine results
1837   */
1838
1839  // Copy xmm1.
1840  NewLIR2(kX86Mova128RR, rs_src1_high_tmp.GetReg(), rs_dest_src1.GetReg());
1841
1842  // Multiply low bits.
1843  NewLIR2(kX86PmullwRR, rs_dest_src1.GetReg(), rs_src2.GetReg());
1844
1845  // xmm1 now has low bits.
1846  AndMaskVectorRegister(rs_dest_src1, 0x00FF00FF, 0x00FF00FF, 0x00FF00FF, 0x00FF00FF);
1847
1848  // Prepare high bits for multiplication.
1849  NewLIR2(kX86PsrlwRI, rs_src1_high_tmp.GetReg(), BYTE_SIZE);
1850  AndMaskVectorRegister(rs_src2, 0xFF00FF00, 0xFF00FF00, 0xFF00FF00, 0xFF00FF00);
1851
1852  // Multiply high bits and xmm2 now has high bits.
1853  NewLIR2(kX86PmullwRR, rs_src2.GetReg(), rs_src1_high_tmp.GetReg());
1854
1855  // Combine back into dest XMM register.
1856  NewLIR2(kX86PorRR, rs_dest_src1.GetReg(), rs_src2.GetReg());
1857}
1858
1859void X86Mir2Lir::GenMultiplyVector(BasicBlock *bb, MIR *mir) {
1860  DCHECK_EQ(mir->dalvikInsn.vC & 0xFFFF, 128U);
1861  OpSize opsize = static_cast<OpSize>(mir->dalvikInsn.vC >> 16);
1862  RegStorage rs_dest_src1 = RegStorage::Solo128(mir->dalvikInsn.vA);
1863  RegStorage rs_src2 = RegStorage::Solo128(mir->dalvikInsn.vB);
1864  int opcode = 0;
1865  switch (opsize) {
1866    case k32:
1867      opcode = kX86PmulldRR;
1868      break;
1869    case kSignedHalf:
1870      opcode = kX86PmullwRR;
1871      break;
1872    case kSingle:
1873      opcode = kX86MulpsRR;
1874      break;
1875    case kDouble:
1876      opcode = kX86MulpdRR;
1877      break;
1878    case kSignedByte:
1879      // HW doesn't support 16x16 byte multiplication so emulate it.
1880      GenMultiplyVectorSignedByte(bb, mir);
1881      return;
1882    default:
1883      LOG(FATAL) << "Unsupported vector multiply " << opsize;
1884      break;
1885  }
1886  NewLIR2(opcode, rs_dest_src1.GetReg(), rs_src2.GetReg());
1887}
1888
1889void X86Mir2Lir::GenAddVector(BasicBlock *bb, MIR *mir) {
1890  DCHECK_EQ(mir->dalvikInsn.vC & 0xFFFF, 128U);
1891  OpSize opsize = static_cast<OpSize>(mir->dalvikInsn.vC >> 16);
1892  RegStorage rs_dest_src1 = RegStorage::Solo128(mir->dalvikInsn.vA);
1893  RegStorage rs_src2 = RegStorage::Solo128(mir->dalvikInsn.vB);
1894  int opcode = 0;
1895  switch (opsize) {
1896    case k32:
1897      opcode = kX86PadddRR;
1898      break;
1899    case kSignedHalf:
1900    case kUnsignedHalf:
1901      opcode = kX86PaddwRR;
1902      break;
1903    case kUnsignedByte:
1904    case kSignedByte:
1905      opcode = kX86PaddbRR;
1906      break;
1907    case kSingle:
1908      opcode = kX86AddpsRR;
1909      break;
1910    case kDouble:
1911      opcode = kX86AddpdRR;
1912      break;
1913    default:
1914      LOG(FATAL) << "Unsupported vector addition " << opsize;
1915      break;
1916  }
1917  NewLIR2(opcode, rs_dest_src1.GetReg(), rs_src2.GetReg());
1918}
1919
1920void X86Mir2Lir::GenSubtractVector(BasicBlock *bb, MIR *mir) {
1921  DCHECK_EQ(mir->dalvikInsn.vC & 0xFFFF, 128U);
1922  OpSize opsize = static_cast<OpSize>(mir->dalvikInsn.vC >> 16);
1923  RegStorage rs_dest_src1 = RegStorage::Solo128(mir->dalvikInsn.vA);
1924  RegStorage rs_src2 = RegStorage::Solo128(mir->dalvikInsn.vB);
1925  int opcode = 0;
1926  switch (opsize) {
1927    case k32:
1928      opcode = kX86PsubdRR;
1929      break;
1930    case kSignedHalf:
1931    case kUnsignedHalf:
1932      opcode = kX86PsubwRR;
1933      break;
1934    case kUnsignedByte:
1935    case kSignedByte:
1936      opcode = kX86PsubbRR;
1937      break;
1938    case kSingle:
1939      opcode = kX86SubpsRR;
1940      break;
1941    case kDouble:
1942      opcode = kX86SubpdRR;
1943      break;
1944    default:
1945      LOG(FATAL) << "Unsupported vector subtraction " << opsize;
1946      break;
1947  }
1948  NewLIR2(opcode, rs_dest_src1.GetReg(), rs_src2.GetReg());
1949}
1950
1951void X86Mir2Lir::GenShiftByteVector(BasicBlock *bb, MIR *mir) {
1952  RegStorage rs_dest_src1 = RegStorage::Solo128(mir->dalvikInsn.vA);
1953  RegStorage rs_tmp = Get128BitRegister(AllocTempWide());
1954
1955  int opcode = 0;
1956  int imm = mir->dalvikInsn.vB;
1957
1958  switch (static_cast<ExtendedMIROpcode>(mir->dalvikInsn.opcode)) {
1959    case kMirOpPackedShiftLeft:
1960      opcode = kX86PsllwRI;
1961      break;
1962    case kMirOpPackedSignedShiftRight:
1963      opcode = kX86PsrawRI;
1964      break;
1965    case kMirOpPackedUnsignedShiftRight:
1966      opcode = kX86PsrlwRI;
1967      break;
1968    default:
1969      LOG(FATAL) << "Unsupported shift operation on byte vector " << opcode;
1970      break;
1971  }
1972
1973  /*
1974   * xmm1 will have low bits
1975   * xmm2 will have high bits
1976   *
1977   * xmm2 = xmm1
1978   * xmm1 = xmm1 .<< N
1979   * xmm2 = xmm2 && 0xFF00FF00FF00FF00FF00FF00FF00FF00
1980   * xmm2 = xmm2 .<< N
1981   * xmm1 = xmm1 | xmm2
1982   */
1983
1984  // Copy xmm1.
1985  NewLIR2(kX86Mova128RR, rs_tmp.GetReg(), rs_dest_src1.GetReg());
1986
1987  // Shift lower values.
1988  NewLIR2(opcode, rs_dest_src1.GetReg(), imm);
1989
1990  // Mask bottom bits.
1991  AndMaskVectorRegister(rs_tmp, 0xFF00FF00, 0xFF00FF00, 0xFF00FF00, 0xFF00FF00);
1992
1993  // Shift higher values.
1994  NewLIR2(opcode, rs_tmp.GetReg(), imm);
1995
1996  // Combine back into dest XMM register.
1997  NewLIR2(kX86PorRR, rs_dest_src1.GetReg(), rs_tmp.GetReg());
1998}
1999
2000void X86Mir2Lir::GenShiftLeftVector(BasicBlock *bb, MIR *mir) {
2001  DCHECK_EQ(mir->dalvikInsn.vC & 0xFFFF, 128U);
2002  OpSize opsize = static_cast<OpSize>(mir->dalvikInsn.vC >> 16);
2003  RegStorage rs_dest_src1 = RegStorage::Solo128(mir->dalvikInsn.vA);
2004  int imm = mir->dalvikInsn.vB;
2005  int opcode = 0;
2006  switch (opsize) {
2007    case k32:
2008      opcode = kX86PslldRI;
2009      break;
2010    case k64:
2011      opcode = kX86PsllqRI;
2012      break;
2013    case kSignedHalf:
2014    case kUnsignedHalf:
2015      opcode = kX86PsllwRI;
2016      break;
2017    case kSignedByte:
2018    case kUnsignedByte:
2019      GenShiftByteVector(bb, mir);
2020      return;
2021    default:
2022      LOG(FATAL) << "Unsupported vector shift left " << opsize;
2023      break;
2024  }
2025  NewLIR2(opcode, rs_dest_src1.GetReg(), imm);
2026}
2027
2028void X86Mir2Lir::GenSignedShiftRightVector(BasicBlock *bb, MIR *mir) {
2029  DCHECK_EQ(mir->dalvikInsn.vC & 0xFFFF, 128U);
2030  OpSize opsize = static_cast<OpSize>(mir->dalvikInsn.vC >> 16);
2031  RegStorage rs_dest_src1 = RegStorage::Solo128(mir->dalvikInsn.vA);
2032  int imm = mir->dalvikInsn.vB;
2033  int opcode = 0;
2034  switch (opsize) {
2035    case k32:
2036      opcode = kX86PsradRI;
2037      break;
2038    case kSignedHalf:
2039    case kUnsignedHalf:
2040      opcode = kX86PsrawRI;
2041      break;
2042    case kSignedByte:
2043    case kUnsignedByte:
2044      GenShiftByteVector(bb, mir);
2045      return;
2046    default:
2047      LOG(FATAL) << "Unsupported vector signed shift right " << opsize;
2048      break;
2049  }
2050  NewLIR2(opcode, rs_dest_src1.GetReg(), imm);
2051}
2052
2053void X86Mir2Lir::GenUnsignedShiftRightVector(BasicBlock *bb, MIR *mir) {
2054  DCHECK_EQ(mir->dalvikInsn.vC & 0xFFFF, 128U);
2055  OpSize opsize = static_cast<OpSize>(mir->dalvikInsn.vC >> 16);
2056  RegStorage rs_dest_src1 = RegStorage::Solo128(mir->dalvikInsn.vA);
2057  int imm = mir->dalvikInsn.vB;
2058  int opcode = 0;
2059  switch (opsize) {
2060    case k32:
2061      opcode = kX86PsrldRI;
2062      break;
2063    case k64:
2064      opcode = kX86PsrlqRI;
2065      break;
2066    case kSignedHalf:
2067    case kUnsignedHalf:
2068      opcode = kX86PsrlwRI;
2069      break;
2070    case kSignedByte:
2071    case kUnsignedByte:
2072      GenShiftByteVector(bb, mir);
2073      return;
2074    default:
2075      LOG(FATAL) << "Unsupported vector unsigned shift right " << opsize;
2076      break;
2077  }
2078  NewLIR2(opcode, rs_dest_src1.GetReg(), imm);
2079}
2080
2081void X86Mir2Lir::GenAndVector(BasicBlock *bb, MIR *mir) {
2082  // We only support 128 bit registers.
2083  DCHECK_EQ(mir->dalvikInsn.vC & 0xFFFF, 128U);
2084  RegStorage rs_dest_src1 = RegStorage::Solo128(mir->dalvikInsn.vA);
2085  RegStorage rs_src2 = RegStorage::Solo128(mir->dalvikInsn.vB);
2086  NewLIR2(kX86PandRR, rs_dest_src1.GetReg(), rs_src2.GetReg());
2087}
2088
2089void X86Mir2Lir::GenOrVector(BasicBlock *bb, MIR *mir) {
2090  // We only support 128 bit registers.
2091  DCHECK_EQ(mir->dalvikInsn.vC & 0xFFFF, 128U);
2092  RegStorage rs_dest_src1 = RegStorage::Solo128(mir->dalvikInsn.vA);
2093  RegStorage rs_src2 = RegStorage::Solo128(mir->dalvikInsn.vB);
2094  NewLIR2(kX86PorRR, rs_dest_src1.GetReg(), rs_src2.GetReg());
2095}
2096
2097void X86Mir2Lir::GenXorVector(BasicBlock *bb, MIR *mir) {
2098  // We only support 128 bit registers.
2099  DCHECK_EQ(mir->dalvikInsn.vC & 0xFFFF, 128U);
2100  RegStorage rs_dest_src1 = RegStorage::Solo128(mir->dalvikInsn.vA);
2101  RegStorage rs_src2 = RegStorage::Solo128(mir->dalvikInsn.vB);
2102  NewLIR2(kX86PxorRR, rs_dest_src1.GetReg(), rs_src2.GetReg());
2103}
2104
2105void X86Mir2Lir::AndMaskVectorRegister(RegStorage rs_src1, uint32_t m1, uint32_t m2, uint32_t m3, uint32_t m4) {
2106  MaskVectorRegister(kX86PandRM, rs_src1, m1, m2, m3, m4);
2107}
2108
2109void X86Mir2Lir::MaskVectorRegister(X86OpCode opcode, RegStorage rs_src1, uint32_t m0, uint32_t m1, uint32_t m2, uint32_t m3) {
2110  // Create temporary MIR as container for 128-bit binary mask.
2111  MIR const_mir;
2112  MIR* const_mirp = &const_mir;
2113  const_mirp->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpConstVector);
2114  const_mirp->dalvikInsn.arg[0] = m0;
2115  const_mirp->dalvikInsn.arg[1] = m1;
2116  const_mirp->dalvikInsn.arg[2] = m2;
2117  const_mirp->dalvikInsn.arg[3] = m3;
2118
2119  // Mask vector with const from literal pool.
2120  AppendOpcodeWithConst(opcode, rs_src1.GetReg(), const_mirp);
2121}
2122
2123void X86Mir2Lir::GenAddReduceVector(BasicBlock *bb, MIR *mir) {
2124  OpSize opsize = static_cast<OpSize>(mir->dalvikInsn.vC >> 16);
2125  RegStorage rs_src1 = RegStorage::Solo128(mir->dalvikInsn.vB);
2126  RegLocation rl_dest = mir_graph_->GetDest(mir);
2127  RegStorage rs_tmp;
2128
2129  int vec_bytes = (mir->dalvikInsn.vC & 0xFFFF) / 8;
2130  int vec_unit_size = 0;
2131  int opcode = 0;
2132  int extr_opcode = 0;
2133  RegLocation rl_result;
2134
2135  switch (opsize) {
2136    case k32:
2137      extr_opcode = kX86PextrdRRI;
2138      opcode = kX86PhadddRR;
2139      vec_unit_size = 4;
2140      break;
2141    case kSignedByte:
2142    case kUnsignedByte:
2143      extr_opcode = kX86PextrbRRI;
2144      opcode = kX86PhaddwRR;
2145      vec_unit_size = 2;
2146      break;
2147    case kSignedHalf:
2148    case kUnsignedHalf:
2149      extr_opcode = kX86PextrwRRI;
2150      opcode = kX86PhaddwRR;
2151      vec_unit_size = 2;
2152      break;
2153    case kSingle:
2154      rl_result = EvalLoc(rl_dest, kFPReg, true);
2155      vec_unit_size = 4;
2156      for (int i = 0; i < 3; i++) {
2157        NewLIR2(kX86AddssRR, rl_result.reg.GetReg(), rs_src1.GetReg());
2158        NewLIR3(kX86ShufpsRRI, rs_src1.GetReg(), rs_src1.GetReg(), 0x39);
2159      }
2160      NewLIR2(kX86AddssRR, rl_result.reg.GetReg(), rs_src1.GetReg());
2161      StoreValue(rl_dest, rl_result);
2162
2163      // For single-precision floats, we are done here
2164      return;
2165    default:
2166      LOG(FATAL) << "Unsupported vector add reduce " << opsize;
2167      break;
2168  }
2169
2170  int elems = vec_bytes / vec_unit_size;
2171
2172  // Emulate horizontal add instruction by reducing 2 vectors with 8 values before adding them again
2173  // TODO is overflow handled correctly?
2174  if (opsize == kSignedByte || opsize == kUnsignedByte) {
2175    rs_tmp = Get128BitRegister(AllocTempWide());
2176
2177    // tmp = xmm1 .>> 8.
2178    NewLIR2(kX86Mova128RR, rs_tmp.GetReg(), rs_src1.GetReg());
2179    NewLIR2(kX86PsrlwRI, rs_tmp.GetReg(), 8);
2180
2181    // Zero extend low bits in xmm1.
2182    AndMaskVectorRegister(rs_src1, 0x00FF00FF, 0x00FF00FF, 0x00FF00FF, 0x00FF00FF);
2183  }
2184
2185  while (elems > 1) {
2186    if (opsize == kSignedByte || opsize == kUnsignedByte) {
2187      NewLIR2(opcode, rs_tmp.GetReg(), rs_tmp.GetReg());
2188    }
2189    NewLIR2(opcode, rs_src1.GetReg(), rs_src1.GetReg());
2190    elems >>= 1;
2191  }
2192
2193  // Combine the results if we separated them.
2194  if (opsize == kSignedByte || opsize == kUnsignedByte) {
2195    NewLIR2(kX86PaddbRR, rs_src1.GetReg(), rs_tmp.GetReg());
2196  }
2197
2198  // We need to extract to a GPR.
2199  RegStorage temp = AllocTemp();
2200  NewLIR3(extr_opcode, temp.GetReg(), rs_src1.GetReg(), 0);
2201
2202  // Can we do this directly into memory?
2203  rl_result = UpdateLocTyped(rl_dest, kCoreReg);
2204  if (rl_result.location == kLocPhysReg) {
2205    // Ensure res is in a core reg
2206    rl_result = EvalLoc(rl_dest, kCoreReg, true);
2207    OpRegReg(kOpAdd, rl_result.reg, temp);
2208    StoreFinalValue(rl_dest, rl_result);
2209  } else {
2210    OpMemReg(kOpAdd, rl_result, temp.GetReg());
2211  }
2212
2213  FreeTemp(temp);
2214}
2215
2216void X86Mir2Lir::GenReduceVector(BasicBlock *bb, MIR *mir) {
2217  OpSize opsize = static_cast<OpSize>(mir->dalvikInsn.vC >> 16);
2218  RegLocation rl_dest = mir_graph_->GetDest(mir);
2219  RegStorage rs_src1 = RegStorage::Solo128(mir->dalvikInsn.vB);
2220  int extract_index = mir->dalvikInsn.arg[0];
2221  int extr_opcode = 0;
2222  RegLocation rl_result;
2223  bool is_wide = false;
2224
2225  switch (opsize) {
2226    case k32:
2227      rl_result = UpdateLocTyped(rl_dest, kCoreReg);
2228      extr_opcode = (rl_result.location == kLocPhysReg) ? kX86PextrdMRI : kX86PextrdRRI;
2229      break;
2230    case kSignedHalf:
2231    case kUnsignedHalf:
2232      rl_result= UpdateLocTyped(rl_dest, kCoreReg);
2233      extr_opcode = (rl_result.location == kLocPhysReg) ? kX86PextrwMRI : kX86PextrwRRI;
2234      break;
2235    default:
2236      LOG(FATAL) << "Unsupported vector add reduce " << opsize;
2237      return;
2238      break;
2239  }
2240
2241  if (rl_result.location == kLocPhysReg) {
2242    NewLIR3(extr_opcode, rl_result.reg.GetReg(), rs_src1.GetReg(), extract_index);
2243    if (is_wide == true) {
2244      StoreFinalValue(rl_dest, rl_result);
2245    } else {
2246      StoreFinalValueWide(rl_dest, rl_result);
2247    }
2248  } else {
2249    int displacement = SRegOffset(rl_result.s_reg_low);
2250    LIR *l = NewLIR3(extr_opcode, rs_rX86_SP.GetReg(), displacement, rs_src1.GetReg());
2251    AnnotateDalvikRegAccess(l, displacement >> 2, true /* is_load */, is_wide /* is_64bit */);
2252    AnnotateDalvikRegAccess(l, displacement >> 2, false /* is_load */, is_wide /* is_64bit */);
2253  }
2254}
2255
2256void X86Mir2Lir::GenSetVector(BasicBlock *bb, MIR *mir) {
2257  DCHECK_EQ(mir->dalvikInsn.vC & 0xFFFF, 128U);
2258  OpSize opsize = static_cast<OpSize>(mir->dalvikInsn.vC >> 16);
2259  RegStorage rs_dest = RegStorage::Solo128(mir->dalvikInsn.vA);
2260  int op_low = 0, op_high = 0, imm = 0, op_mov = kX86MovdxrRR;
2261  RegisterClass reg_type = kCoreReg;
2262
2263  switch (opsize) {
2264    case k32:
2265      op_low = kX86PshufdRRI;
2266      break;
2267    case kSingle:
2268      op_low = kX86PshufdRRI;
2269      op_mov = kX86Mova128RR;
2270      reg_type = kFPReg;
2271      break;
2272    case k64:
2273      op_low = kX86PshufdRRI;
2274      imm = 0x44;
2275      break;
2276    case kDouble:
2277      op_low = kX86PshufdRRI;
2278      op_mov = kX86Mova128RR;
2279      reg_type = kFPReg;
2280      imm = 0x44;
2281      break;
2282    case kSignedByte:
2283    case kUnsignedByte:
2284      // Shuffle 8 bit value into 16 bit word.
2285      // We set val = val + (val << 8) below and use 16 bit shuffle.
2286    case kSignedHalf:
2287    case kUnsignedHalf:
2288      // Handles low quadword.
2289      op_low = kX86PshuflwRRI;
2290      // Handles upper quadword.
2291      op_high = kX86PshufdRRI;
2292      break;
2293    default:
2294      LOG(FATAL) << "Unsupported vector set " << opsize;
2295      break;
2296  }
2297
2298  RegLocation rl_src = mir_graph_->GetSrc(mir, 0);
2299
2300  // Load the value from the VR into the reg.
2301  if (rl_src.wide == 0) {
2302    rl_src = LoadValue(rl_src, reg_type);
2303  } else {
2304    rl_src = LoadValueWide(rl_src, reg_type);
2305  }
2306
2307  // If opsize is 8 bits wide then double value and use 16 bit shuffle instead.
2308  if (opsize == kSignedByte || opsize == kUnsignedByte) {
2309    RegStorage temp = AllocTemp();
2310    // val = val + (val << 8).
2311    NewLIR2(kX86Mov32RR, temp.GetReg(), rl_src.reg.GetReg());
2312    NewLIR2(kX86Sal32RI, temp.GetReg(), 8);
2313    NewLIR2(kX86Or32RR, rl_src.reg.GetReg(), temp.GetReg());
2314    FreeTemp(temp);
2315  }
2316
2317  // Load the value into the XMM register.
2318  NewLIR2(op_mov, rs_dest.GetReg(), rl_src.reg.GetReg());
2319
2320  // Now shuffle the value across the destination.
2321  NewLIR3(op_low, rs_dest.GetReg(), rs_dest.GetReg(), imm);
2322
2323  // And then repeat as needed.
2324  if (op_high != 0) {
2325    NewLIR3(op_high, rs_dest.GetReg(), rs_dest.GetReg(), imm);
2326  }
2327}
2328
2329LIR *X86Mir2Lir::ScanVectorLiteral(MIR *mir) {
2330  int *args = reinterpret_cast<int*>(mir->dalvikInsn.arg);
2331  for (LIR *p = const_vectors_; p != nullptr; p = p->next) {
2332    if (args[0] == p->operands[0] && args[1] == p->operands[1] &&
2333        args[2] == p->operands[2] && args[3] == p->operands[3]) {
2334      return p;
2335    }
2336  }
2337  return nullptr;
2338}
2339
2340LIR *X86Mir2Lir::AddVectorLiteral(MIR *mir) {
2341  LIR* new_value = static_cast<LIR*>(arena_->Alloc(sizeof(LIR), kArenaAllocData));
2342  int *args = reinterpret_cast<int*>(mir->dalvikInsn.arg);
2343  new_value->operands[0] = args[0];
2344  new_value->operands[1] = args[1];
2345  new_value->operands[2] = args[2];
2346  new_value->operands[3] = args[3];
2347  new_value->next = const_vectors_;
2348  if (const_vectors_ == nullptr) {
2349    estimated_native_code_size_ += 12;  // Amount needed to align to 16 byte boundary.
2350  }
2351  estimated_native_code_size_ += 16;  // Space for one vector.
2352  const_vectors_ = new_value;
2353  return new_value;
2354}
2355
2356// ------------ ABI support: mapping of args to physical registers -------------
2357RegStorage X86Mir2Lir::InToRegStorageX86_64Mapper::GetNextReg(bool is_double_or_float, bool is_wide,
2358                                                              bool is_ref) {
2359  const SpecialTargetRegister coreArgMappingToPhysicalReg[] = {kArg1, kArg2, kArg3, kArg4, kArg5};
2360  const int coreArgMappingToPhysicalRegSize = sizeof(coreArgMappingToPhysicalReg) /
2361      sizeof(SpecialTargetRegister);
2362  const SpecialTargetRegister fpArgMappingToPhysicalReg[] = {kFArg0, kFArg1, kFArg2, kFArg3,
2363                                                             kFArg4, kFArg5, kFArg6, kFArg7};
2364  const int fpArgMappingToPhysicalRegSize = sizeof(fpArgMappingToPhysicalReg) /
2365      sizeof(SpecialTargetRegister);
2366
2367  if (is_double_or_float) {
2368    if (cur_fp_reg_ < fpArgMappingToPhysicalRegSize) {
2369      return ml_->TargetReg(fpArgMappingToPhysicalReg[cur_fp_reg_++], is_wide ? kWide : kNotWide);
2370    }
2371  } else {
2372    if (cur_core_reg_ < coreArgMappingToPhysicalRegSize) {
2373      return ml_->TargetReg(coreArgMappingToPhysicalReg[cur_core_reg_++],
2374                            is_ref ? kRef : (is_wide ? kWide : kNotWide));
2375    }
2376  }
2377  return RegStorage::InvalidReg();
2378}
2379
2380RegStorage X86Mir2Lir::InToRegStorageMapping::Get(int in_position) {
2381  DCHECK(IsInitialized());
2382  auto res = mapping_.find(in_position);
2383  return res != mapping_.end() ? res->second : RegStorage::InvalidReg();
2384}
2385
2386void X86Mir2Lir::InToRegStorageMapping::Initialize(RegLocation* arg_locs, int count,
2387                                                   InToRegStorageMapper* mapper) {
2388  DCHECK(mapper != nullptr);
2389  max_mapped_in_ = -1;
2390  is_there_stack_mapped_ = false;
2391  for (int in_position = 0; in_position < count; in_position++) {
2392     RegStorage reg = mapper->GetNextReg(arg_locs[in_position].fp,
2393             arg_locs[in_position].wide, arg_locs[in_position].ref);
2394     if (reg.Valid()) {
2395       mapping_[in_position] = reg;
2396       max_mapped_in_ = std::max(max_mapped_in_, in_position);
2397       if (arg_locs[in_position].wide) {
2398         // We covered 2 args, so skip the next one
2399         in_position++;
2400       }
2401     } else {
2402       is_there_stack_mapped_ = true;
2403     }
2404  }
2405  initialized_ = true;
2406}
2407
2408RegStorage X86Mir2Lir::GetArgMappingToPhysicalReg(int arg_num) {
2409  if (!cu_->target64) {
2410    return GetCoreArgMappingToPhysicalReg(arg_num);
2411  }
2412
2413  if (!in_to_reg_storage_mapping_.IsInitialized()) {
2414    int start_vreg = cu_->num_dalvik_registers - cu_->num_ins;
2415    RegLocation* arg_locs = &mir_graph_->reg_location_[start_vreg];
2416
2417    InToRegStorageX86_64Mapper mapper(this);
2418    in_to_reg_storage_mapping_.Initialize(arg_locs, cu_->num_ins, &mapper);
2419  }
2420  return in_to_reg_storage_mapping_.Get(arg_num);
2421}
2422
2423RegStorage X86Mir2Lir::GetCoreArgMappingToPhysicalReg(int core_arg_num) {
2424  // For the 32-bit internal ABI, the first 3 arguments are passed in registers.
2425  // Not used for 64-bit, TODO: Move X86_32 to the same framework
2426  switch (core_arg_num) {
2427    case 0:
2428      return rs_rX86_ARG1;
2429    case 1:
2430      return rs_rX86_ARG2;
2431    case 2:
2432      return rs_rX86_ARG3;
2433    default:
2434      return RegStorage::InvalidReg();
2435  }
2436}
2437
2438// ---------End of ABI support: mapping of args to physical registers -------------
2439
2440/*
2441 * If there are any ins passed in registers that have not been promoted
2442 * to a callee-save register, flush them to the frame.  Perform initial
2443 * assignment of promoted arguments.
2444 *
2445 * ArgLocs is an array of location records describing the incoming arguments
2446 * with one location record per word of argument.
2447 */
2448void X86Mir2Lir::FlushIns(RegLocation* ArgLocs, RegLocation rl_method) {
2449  if (!cu_->target64) return Mir2Lir::FlushIns(ArgLocs, rl_method);
2450  /*
2451   * Dummy up a RegLocation for the incoming Method*
2452   * It will attempt to keep kArg0 live (or copy it to home location
2453   * if promoted).
2454   */
2455
2456  RegLocation rl_src = rl_method;
2457  rl_src.location = kLocPhysReg;
2458  rl_src.reg = TargetReg(kArg0, kRef);
2459  rl_src.home = false;
2460  MarkLive(rl_src);
2461  StoreValue(rl_method, rl_src);
2462  // If Method* has been promoted, explicitly flush
2463  if (rl_method.location == kLocPhysReg) {
2464    StoreRefDisp(rs_rX86_SP, 0, As32BitReg(TargetReg(kArg0, kRef)), kNotVolatile);
2465  }
2466
2467  if (cu_->num_ins == 0) {
2468    return;
2469  }
2470
2471  int start_vreg = cu_->num_dalvik_registers - cu_->num_ins;
2472  /*
2473   * Copy incoming arguments to their proper home locations.
2474   * NOTE: an older version of dx had an issue in which
2475   * it would reuse static method argument registers.
2476   * This could result in the same Dalvik virtual register
2477   * being promoted to both core and fp regs. To account for this,
2478   * we only copy to the corresponding promoted physical register
2479   * if it matches the type of the SSA name for the incoming
2480   * argument.  It is also possible that long and double arguments
2481   * end up half-promoted.  In those cases, we must flush the promoted
2482   * half to memory as well.
2483   */
2484  ScopedMemRefType mem_ref_type(this, ResourceMask::kDalvikReg);
2485  for (int i = 0; i < cu_->num_ins; i++) {
2486    // get reg corresponding to input
2487    RegStorage reg = GetArgMappingToPhysicalReg(i);
2488
2489    RegLocation* t_loc = &ArgLocs[i];
2490    if (reg.Valid()) {
2491      // If arriving in register.
2492
2493      // We have already updated the arg location with promoted info
2494      // so we can be based on it.
2495      if (t_loc->location == kLocPhysReg) {
2496        // Just copy it.
2497        OpRegCopy(t_loc->reg, reg);
2498      } else {
2499        // Needs flush.
2500        if (t_loc->ref) {
2501          StoreRefDisp(rs_rX86_SP, SRegOffset(start_vreg + i), reg, kNotVolatile);
2502        } else {
2503          StoreBaseDisp(rs_rX86_SP, SRegOffset(start_vreg + i), reg, t_loc->wide ? k64 : k32,
2504                        kNotVolatile);
2505        }
2506      }
2507    } else {
2508      // If arriving in frame & promoted.
2509      if (t_loc->location == kLocPhysReg) {
2510        if (t_loc->ref) {
2511          LoadRefDisp(rs_rX86_SP, SRegOffset(start_vreg + i), t_loc->reg, kNotVolatile);
2512        } else {
2513          LoadBaseDisp(rs_rX86_SP, SRegOffset(start_vreg + i), t_loc->reg,
2514                       t_loc->wide ? k64 : k32, kNotVolatile);
2515        }
2516      }
2517    }
2518    if (t_loc->wide) {
2519      // Increment i to skip the next one.
2520      i++;
2521    }
2522  }
2523}
2524
2525/*
2526 * Load up to 5 arguments, the first three of which will be in
2527 * kArg1 .. kArg3.  On entry kArg0 contains the current method pointer,
2528 * and as part of the load sequence, it must be replaced with
2529 * the target method pointer.  Note, this may also be called
2530 * for "range" variants if the number of arguments is 5 or fewer.
2531 */
2532int X86Mir2Lir::GenDalvikArgsNoRange(CallInfo* info,
2533                                  int call_state, LIR** pcrLabel, NextCallInsn next_call_insn,
2534                                  const MethodReference& target_method,
2535                                  uint32_t vtable_idx, uintptr_t direct_code,
2536                                  uintptr_t direct_method, InvokeType type, bool skip_this) {
2537  if (!cu_->target64) {
2538    return Mir2Lir::GenDalvikArgsNoRange(info,
2539                                  call_state, pcrLabel, next_call_insn,
2540                                  target_method,
2541                                  vtable_idx, direct_code,
2542                                  direct_method, type, skip_this);
2543  }
2544  return GenDalvikArgsRange(info,
2545                       call_state, pcrLabel, next_call_insn,
2546                       target_method,
2547                       vtable_idx, direct_code,
2548                       direct_method, type, skip_this);
2549}
2550
2551/*
2552 * May have 0+ arguments (also used for jumbo).  Note that
2553 * source virtual registers may be in physical registers, so may
2554 * need to be flushed to home location before copying.  This
2555 * applies to arg3 and above (see below).
2556 *
2557 * Two general strategies:
2558 *    If < 20 arguments
2559 *       Pass args 3-18 using vldm/vstm block copy
2560 *       Pass arg0, arg1 & arg2 in kArg1-kArg3
2561 *    If 20+ arguments
2562 *       Pass args arg19+ using memcpy block copy
2563 *       Pass arg0, arg1 & arg2 in kArg1-kArg3
2564 *
2565 */
2566int X86Mir2Lir::GenDalvikArgsRange(CallInfo* info, int call_state,
2567                                LIR** pcrLabel, NextCallInsn next_call_insn,
2568                                const MethodReference& target_method,
2569                                uint32_t vtable_idx, uintptr_t direct_code, uintptr_t direct_method,
2570                                InvokeType type, bool skip_this) {
2571  if (!cu_->target64) {
2572    return Mir2Lir::GenDalvikArgsRange(info, call_state,
2573                                pcrLabel, next_call_insn,
2574                                target_method,
2575                                vtable_idx, direct_code, direct_method,
2576                                type, skip_this);
2577  }
2578
2579  /* If no arguments, just return */
2580  if (info->num_arg_words == 0)
2581    return call_state;
2582
2583  const int start_index = skip_this ? 1 : 0;
2584
2585  InToRegStorageX86_64Mapper mapper(this);
2586  InToRegStorageMapping in_to_reg_storage_mapping;
2587  in_to_reg_storage_mapping.Initialize(info->args, info->num_arg_words, &mapper);
2588  const int last_mapped_in = in_to_reg_storage_mapping.GetMaxMappedIn();
2589  const int size_of_the_last_mapped = last_mapped_in == -1 ? 1 :
2590          info->args[last_mapped_in].wide ? 2 : 1;
2591  int regs_left_to_pass_via_stack = info->num_arg_words - (last_mapped_in + size_of_the_last_mapped);
2592
2593  // Fisrt of all, check whether it make sense to use bulk copying
2594  // Optimization is aplicable only for range case
2595  // TODO: make a constant instead of 2
2596  if (info->is_range && regs_left_to_pass_via_stack >= 2) {
2597    // Scan the rest of the args - if in phys_reg flush to memory
2598    for (int next_arg = last_mapped_in + size_of_the_last_mapped; next_arg < info->num_arg_words;) {
2599      RegLocation loc = info->args[next_arg];
2600      if (loc.wide) {
2601        loc = UpdateLocWide(loc);
2602        if (loc.location == kLocPhysReg) {
2603          ScopedMemRefType mem_ref_type(this, ResourceMask::kDalvikReg);
2604          StoreBaseDisp(rs_rX86_SP, SRegOffset(loc.s_reg_low), loc.reg, k64, kNotVolatile);
2605        }
2606        next_arg += 2;
2607      } else {
2608        loc = UpdateLoc(loc);
2609        if (loc.location == kLocPhysReg) {
2610          ScopedMemRefType mem_ref_type(this, ResourceMask::kDalvikReg);
2611          StoreBaseDisp(rs_rX86_SP, SRegOffset(loc.s_reg_low), loc.reg, k32, kNotVolatile);
2612        }
2613        next_arg++;
2614      }
2615    }
2616
2617    // Logic below assumes that Method pointer is at offset zero from SP.
2618    DCHECK_EQ(VRegOffset(static_cast<int>(kVRegMethodPtrBaseReg)), 0);
2619
2620    // The rest can be copied together
2621    int start_offset = SRegOffset(info->args[last_mapped_in + size_of_the_last_mapped].s_reg_low);
2622    int outs_offset = StackVisitor::GetOutVROffset(last_mapped_in + size_of_the_last_mapped,
2623                                                   cu_->instruction_set);
2624
2625    int current_src_offset = start_offset;
2626    int current_dest_offset = outs_offset;
2627
2628    // Only davik regs are accessed in this loop; no next_call_insn() calls.
2629    ScopedMemRefType mem_ref_type(this, ResourceMask::kDalvikReg);
2630    while (regs_left_to_pass_via_stack > 0) {
2631      // This is based on the knowledge that the stack itself is 16-byte aligned.
2632      bool src_is_16b_aligned = (current_src_offset & 0xF) == 0;
2633      bool dest_is_16b_aligned = (current_dest_offset & 0xF) == 0;
2634      size_t bytes_to_move;
2635
2636      /*
2637       * The amount to move defaults to 32-bit. If there are 4 registers left to move, then do a
2638       * a 128-bit move because we won't get the chance to try to aligned. If there are more than
2639       * 4 registers left to move, consider doing a 128-bit only if either src or dest are aligned.
2640       * We do this because we could potentially do a smaller move to align.
2641       */
2642      if (regs_left_to_pass_via_stack == 4 ||
2643          (regs_left_to_pass_via_stack > 4 && (src_is_16b_aligned || dest_is_16b_aligned))) {
2644        // Moving 128-bits via xmm register.
2645        bytes_to_move = sizeof(uint32_t) * 4;
2646
2647        // Allocate a free xmm temp. Since we are working through the calling sequence,
2648        // we expect to have an xmm temporary available.  AllocTempDouble will abort if
2649        // there are no free registers.
2650        RegStorage temp = AllocTempDouble();
2651
2652        LIR* ld1 = nullptr;
2653        LIR* ld2 = nullptr;
2654        LIR* st1 = nullptr;
2655        LIR* st2 = nullptr;
2656
2657        /*
2658         * The logic is similar for both loads and stores. If we have 16-byte alignment,
2659         * do an aligned move. If we have 8-byte alignment, then do the move in two
2660         * parts. This approach prevents possible cache line splits. Finally, fall back
2661         * to doing an unaligned move. In most cases we likely won't split the cache
2662         * line but we cannot prove it and thus take a conservative approach.
2663         */
2664        bool src_is_8b_aligned = (current_src_offset & 0x7) == 0;
2665        bool dest_is_8b_aligned = (current_dest_offset & 0x7) == 0;
2666
2667        ScopedMemRefType mem_ref_type(this, ResourceMask::kDalvikReg);
2668        if (src_is_16b_aligned) {
2669          ld1 = OpMovRegMem(temp, rs_rX86_SP, current_src_offset, kMovA128FP);
2670        } else if (src_is_8b_aligned) {
2671          ld1 = OpMovRegMem(temp, rs_rX86_SP, current_src_offset, kMovLo128FP);
2672          ld2 = OpMovRegMem(temp, rs_rX86_SP, current_src_offset + (bytes_to_move >> 1),
2673                            kMovHi128FP);
2674        } else {
2675          ld1 = OpMovRegMem(temp, rs_rX86_SP, current_src_offset, kMovU128FP);
2676        }
2677
2678        if (dest_is_16b_aligned) {
2679          st1 = OpMovMemReg(rs_rX86_SP, current_dest_offset, temp, kMovA128FP);
2680        } else if (dest_is_8b_aligned) {
2681          st1 = OpMovMemReg(rs_rX86_SP, current_dest_offset, temp, kMovLo128FP);
2682          st2 = OpMovMemReg(rs_rX86_SP, current_dest_offset + (bytes_to_move >> 1),
2683                            temp, kMovHi128FP);
2684        } else {
2685          st1 = OpMovMemReg(rs_rX86_SP, current_dest_offset, temp, kMovU128FP);
2686        }
2687
2688        // TODO If we could keep track of aliasing information for memory accesses that are wider
2689        // than 64-bit, we wouldn't need to set up a barrier.
2690        if (ld1 != nullptr) {
2691          if (ld2 != nullptr) {
2692            // For 64-bit load we can actually set up the aliasing information.
2693            AnnotateDalvikRegAccess(ld1, current_src_offset >> 2, true, true);
2694            AnnotateDalvikRegAccess(ld2, (current_src_offset + (bytes_to_move >> 1)) >> 2, true, true);
2695          } else {
2696            // Set barrier for 128-bit load.
2697            ld1->u.m.def_mask = &kEncodeAll;
2698          }
2699        }
2700        if (st1 != nullptr) {
2701          if (st2 != nullptr) {
2702            // For 64-bit store we can actually set up the aliasing information.
2703            AnnotateDalvikRegAccess(st1, current_dest_offset >> 2, false, true);
2704            AnnotateDalvikRegAccess(st2, (current_dest_offset + (bytes_to_move >> 1)) >> 2, false, true);
2705          } else {
2706            // Set barrier for 128-bit store.
2707            st1->u.m.def_mask = &kEncodeAll;
2708          }
2709        }
2710
2711        // Free the temporary used for the data movement.
2712        FreeTemp(temp);
2713      } else {
2714        // Moving 32-bits via general purpose register.
2715        bytes_to_move = sizeof(uint32_t);
2716
2717        // Instead of allocating a new temp, simply reuse one of the registers being used
2718        // for argument passing.
2719        RegStorage temp = TargetReg(kArg3, kNotWide);
2720
2721        // Now load the argument VR and store to the outs.
2722        Load32Disp(rs_rX86_SP, current_src_offset, temp);
2723        Store32Disp(rs_rX86_SP, current_dest_offset, temp);
2724      }
2725
2726      current_src_offset += bytes_to_move;
2727      current_dest_offset += bytes_to_move;
2728      regs_left_to_pass_via_stack -= (bytes_to_move >> 2);
2729    }
2730    DCHECK_EQ(regs_left_to_pass_via_stack, 0);
2731  }
2732
2733  // Now handle rest not registers if they are
2734  if (in_to_reg_storage_mapping.IsThereStackMapped()) {
2735    RegStorage regSingle = TargetReg(kArg2, kNotWide);
2736    RegStorage regWide = TargetReg(kArg3, kWide);
2737    for (int i = start_index;
2738         i < last_mapped_in + size_of_the_last_mapped + regs_left_to_pass_via_stack; i++) {
2739      RegLocation rl_arg = info->args[i];
2740      rl_arg = UpdateRawLoc(rl_arg);
2741      RegStorage reg = in_to_reg_storage_mapping.Get(i);
2742      if (!reg.Valid()) {
2743        int out_offset = StackVisitor::GetOutVROffset(i, cu_->instruction_set);
2744
2745        {
2746          ScopedMemRefType mem_ref_type(this, ResourceMask::kDalvikReg);
2747          if (rl_arg.wide) {
2748            if (rl_arg.location == kLocPhysReg) {
2749              StoreBaseDisp(rs_rX86_SP, out_offset, rl_arg.reg, k64, kNotVolatile);
2750            } else {
2751              LoadValueDirectWideFixed(rl_arg, regWide);
2752              StoreBaseDisp(rs_rX86_SP, out_offset, regWide, k64, kNotVolatile);
2753            }
2754          } else {
2755            if (rl_arg.location == kLocPhysReg) {
2756              StoreBaseDisp(rs_rX86_SP, out_offset, rl_arg.reg, k32, kNotVolatile);
2757            } else {
2758              LoadValueDirectFixed(rl_arg, regSingle);
2759              StoreBaseDisp(rs_rX86_SP, out_offset, regSingle, k32, kNotVolatile);
2760            }
2761          }
2762        }
2763        call_state = next_call_insn(cu_, info, call_state, target_method,
2764                                    vtable_idx, direct_code, direct_method, type);
2765      }
2766      if (rl_arg.wide) {
2767        i++;
2768      }
2769    }
2770  }
2771
2772  // Finish with mapped registers
2773  for (int i = start_index; i <= last_mapped_in; i++) {
2774    RegLocation rl_arg = info->args[i];
2775    rl_arg = UpdateRawLoc(rl_arg);
2776    RegStorage reg = in_to_reg_storage_mapping.Get(i);
2777    if (reg.Valid()) {
2778      if (rl_arg.wide) {
2779        LoadValueDirectWideFixed(rl_arg, reg);
2780      } else {
2781        LoadValueDirectFixed(rl_arg, reg);
2782      }
2783      call_state = next_call_insn(cu_, info, call_state, target_method, vtable_idx,
2784                               direct_code, direct_method, type);
2785    }
2786    if (rl_arg.wide) {
2787      i++;
2788    }
2789  }
2790
2791  call_state = next_call_insn(cu_, info, call_state, target_method, vtable_idx,
2792                           direct_code, direct_method, type);
2793  if (pcrLabel) {
2794    if (!cu_->compiler_driver->GetCompilerOptions().GetImplicitNullChecks()) {
2795      *pcrLabel = GenExplicitNullCheck(TargetReg(kArg1, kRef), info->opt_flags);
2796    } else {
2797      *pcrLabel = nullptr;
2798      // In lieu of generating a check for kArg1 being null, we need to
2799      // perform a load when doing implicit checks.
2800      RegStorage tmp = AllocTemp();
2801      Load32Disp(TargetReg(kArg1, kRef), 0, tmp);
2802      MarkPossibleNullPointerException(info->opt_flags);
2803      FreeTemp(tmp);
2804    }
2805  }
2806  return call_state;
2807}
2808
2809bool X86Mir2Lir::GenInlinedCharAt(CallInfo* info) {
2810  // Location of reference to data array
2811  int value_offset = mirror::String::ValueOffset().Int32Value();
2812  // Location of count
2813  int count_offset = mirror::String::CountOffset().Int32Value();
2814  // Starting offset within data array
2815  int offset_offset = mirror::String::OffsetOffset().Int32Value();
2816  // Start of char data with array_
2817  int data_offset = mirror::Array::DataOffset(sizeof(uint16_t)).Int32Value();
2818
2819  RegLocation rl_obj = info->args[0];
2820  RegLocation rl_idx = info->args[1];
2821  rl_obj = LoadValue(rl_obj, kRefReg);
2822  // X86 wants to avoid putting a constant index into a register.
2823  if (!rl_idx.is_const) {
2824    rl_idx = LoadValue(rl_idx, kCoreReg);
2825  }
2826  RegStorage reg_max;
2827  GenNullCheck(rl_obj.reg, info->opt_flags);
2828  bool range_check = (!(info->opt_flags & MIR_IGNORE_RANGE_CHECK));
2829  LIR* range_check_branch = nullptr;
2830  RegStorage reg_off;
2831  RegStorage reg_ptr;
2832  if (range_check) {
2833    // On x86, we can compare to memory directly
2834    // Set up a launch pad to allow retry in case of bounds violation */
2835    if (rl_idx.is_const) {
2836      LIR* comparison;
2837      range_check_branch = OpCmpMemImmBranch(
2838          kCondUlt, RegStorage::InvalidReg(), rl_obj.reg, count_offset,
2839          mir_graph_->ConstantValue(rl_idx.orig_sreg), nullptr, &comparison);
2840      MarkPossibleNullPointerExceptionAfter(0, comparison);
2841    } else {
2842      OpRegMem(kOpCmp, rl_idx.reg, rl_obj.reg, count_offset);
2843      MarkPossibleNullPointerException(0);
2844      range_check_branch = OpCondBranch(kCondUge, nullptr);
2845    }
2846  }
2847  reg_off = AllocTemp();
2848  reg_ptr = AllocTempRef();
2849  Load32Disp(rl_obj.reg, offset_offset, reg_off);
2850  LoadRefDisp(rl_obj.reg, value_offset, reg_ptr, kNotVolatile);
2851  if (rl_idx.is_const) {
2852    OpRegImm(kOpAdd, reg_off, mir_graph_->ConstantValue(rl_idx.orig_sreg));
2853  } else {
2854    OpRegReg(kOpAdd, reg_off, rl_idx.reg);
2855  }
2856  FreeTemp(rl_obj.reg);
2857  if (rl_idx.location == kLocPhysReg) {
2858    FreeTemp(rl_idx.reg);
2859  }
2860  RegLocation rl_dest = InlineTarget(info);
2861  RegLocation rl_result = EvalLoc(rl_dest, kCoreReg, true);
2862  LoadBaseIndexedDisp(reg_ptr, reg_off, 1, data_offset, rl_result.reg, kUnsignedHalf);
2863  FreeTemp(reg_off);
2864  FreeTemp(reg_ptr);
2865  StoreValue(rl_dest, rl_result);
2866  if (range_check) {
2867    DCHECK(range_check_branch != nullptr);
2868    info->opt_flags |= MIR_IGNORE_NULL_CHECK;  // Record that we've already null checked.
2869    AddIntrinsicSlowPath(info, range_check_branch);
2870  }
2871  return true;
2872}
2873
2874bool X86Mir2Lir::GenInlinedCurrentThread(CallInfo* info) {
2875  RegLocation rl_dest = InlineTarget(info);
2876
2877  // Early exit if the result is unused.
2878  if (rl_dest.orig_sreg < 0) {
2879    return true;
2880  }
2881
2882  RegLocation rl_result = EvalLoc(rl_dest, kRefReg, true);
2883
2884  if (cu_->target64) {
2885    OpRegThreadMem(kOpMov, rl_result.reg, Thread::PeerOffset<8>());
2886  } else {
2887    OpRegThreadMem(kOpMov, rl_result.reg, Thread::PeerOffset<4>());
2888  }
2889
2890  StoreValue(rl_dest, rl_result);
2891  return true;
2892}
2893
2894}  // namespace art
2895