1 /*
2 * Copyright (C) 2011 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 /* This file contains codegen for the Thumb2 ISA. */
18
19 #include "codegen_arm.h"
20
21 #include "arm_lir.h"
22 #include "art_method.h"
23 #include "base/bit_utils.h"
24 #include "base/logging.h"
25 #include "dex/mir_graph.h"
26 #include "dex/quick/dex_file_to_method_inliner_map.h"
27 #include "dex/quick/mir_to_lir-inl.h"
28 #include "driver/compiler_driver.h"
29 #include "driver/compiler_options.h"
30 #include "gc/accounting/card_table.h"
31 #include "mirror/object_array-inl.h"
32 #include "entrypoints/quick/quick_entrypoints.h"
33 #include "utils/dex_cache_arrays_layout-inl.h"
34
35 namespace art {
36
37 /*
38 * The sparse table in the literal pool is an array of <key,displacement>
39 * pairs. For each set, we'll load them as a pair using ldmia.
40 * This means that the register number of the temp we use for the key
41 * must be lower than the reg for the displacement.
42 *
43 * The test loop will look something like:
44 *
45 * adr r_base, <table>
46 * ldr r_val, [rARM_SP, v_reg_off]
47 * mov r_idx, #table_size
48 * lp:
49 * ldmia r_base!, {r_key, r_disp}
50 * sub r_idx, #1
51 * cmp r_val, r_key
52 * ifeq
53 * add rARM_PC, r_disp ; This is the branch from which we compute displacement
54 * cbnz r_idx, lp
55 */
GenLargeSparseSwitch(MIR * mir,uint32_t table_offset,RegLocation rl_src)56 void ArmMir2Lir::GenLargeSparseSwitch(MIR* mir, uint32_t table_offset, RegLocation rl_src) {
57 const uint16_t* table = mir_graph_->GetTable(mir, table_offset);
58 // Add the table to the list - we'll process it later
59 SwitchTable *tab_rec =
60 static_cast<SwitchTable*>(arena_->Alloc(sizeof(SwitchTable), kArenaAllocData));
61 tab_rec->switch_mir = mir;
62 tab_rec->table = table;
63 tab_rec->vaddr = current_dalvik_offset_;
64 uint32_t size = table[1];
65 switch_tables_.push_back(tab_rec);
66
67 // Get the switch value
68 rl_src = LoadValue(rl_src, kCoreReg);
69 RegStorage r_base = AllocTemp();
70 /* Allocate key and disp temps */
71 RegStorage r_key = AllocTemp();
72 RegStorage r_disp = AllocTemp();
73 // Make sure r_key's register number is less than r_disp's number for ldmia
74 if (r_key.GetReg() > r_disp.GetReg()) {
75 RegStorage tmp = r_disp;
76 r_disp = r_key;
77 r_key = tmp;
78 }
79 // Materialize a pointer to the switch table
80 NewLIR3(kThumb2Adr, r_base.GetReg(), 0, WrapPointer(tab_rec));
81 // Set up r_idx
82 RegStorage r_idx = AllocTemp();
83 LoadConstant(r_idx, size);
84 // Establish loop branch target
85 LIR* target = NewLIR0(kPseudoTargetLabel);
86 // Load next key/disp
87 NewLIR2(kThumb2LdmiaWB, r_base.GetReg(), (1 << r_key.GetRegNum()) | (1 << r_disp.GetRegNum()));
88 OpRegReg(kOpCmp, r_key, rl_src.reg);
89 // Go if match. NOTE: No instruction set switch here - must stay Thumb2
90 LIR* it = OpIT(kCondEq, "");
91 LIR* switch_branch = NewLIR1(kThumb2AddPCR, r_disp.GetReg());
92 OpEndIT(it);
93 tab_rec->anchor = switch_branch;
94 // Needs to use setflags encoding here
95 OpRegRegImm(kOpSub, r_idx, r_idx, 1); // For value == 1, this should set flags.
96 DCHECK(last_lir_insn_->u.m.def_mask->HasBit(ResourceMask::kCCode));
97 OpCondBranch(kCondNe, target);
98 }
99
100
GenLargePackedSwitch(MIR * mir,uint32_t table_offset,RegLocation rl_src)101 void ArmMir2Lir::GenLargePackedSwitch(MIR* mir, uint32_t table_offset, RegLocation rl_src) {
102 const uint16_t* table = mir_graph_->GetTable(mir, table_offset);
103 // Add the table to the list - we'll process it later
104 SwitchTable *tab_rec =
105 static_cast<SwitchTable*>(arena_->Alloc(sizeof(SwitchTable), kArenaAllocData));
106 tab_rec->switch_mir = mir;
107 tab_rec->table = table;
108 tab_rec->vaddr = current_dalvik_offset_;
109 uint32_t size = table[1];
110 switch_tables_.push_back(tab_rec);
111
112 // Get the switch value
113 rl_src = LoadValue(rl_src, kCoreReg);
114 RegStorage table_base = AllocTemp();
115 // Materialize a pointer to the switch table
116 NewLIR3(kThumb2Adr, table_base.GetReg(), 0, WrapPointer(tab_rec));
117 int low_key = s4FromSwitchData(&table[2]);
118 RegStorage keyReg;
119 // Remove the bias, if necessary
120 if (low_key == 0) {
121 keyReg = rl_src.reg;
122 } else {
123 keyReg = AllocTemp();
124 OpRegRegImm(kOpSub, keyReg, rl_src.reg, low_key);
125 }
126 // Bounds check - if < 0 or >= size continue following switch
127 OpRegImm(kOpCmp, keyReg, size-1);
128 LIR* branch_over = OpCondBranch(kCondHi, nullptr);
129
130 // Load the displacement from the switch table
131 RegStorage disp_reg = AllocTemp();
132 LoadBaseIndexed(table_base, keyReg, disp_reg, 2, k32);
133
134 // ..and go! NOTE: No instruction set switch here - must stay Thumb2
135 LIR* switch_branch = NewLIR1(kThumb2AddPCR, disp_reg.GetReg());
136 tab_rec->anchor = switch_branch;
137
138 /* branch_over target here */
139 LIR* target = NewLIR0(kPseudoTargetLabel);
140 branch_over->target = target;
141 }
142
143 /*
144 * Handle unlocked -> thin locked transition inline or else call out to quick entrypoint. For more
145 * details see monitor.cc.
146 */
GenMonitorEnter(int opt_flags,RegLocation rl_src)147 void ArmMir2Lir::GenMonitorEnter(int opt_flags, RegLocation rl_src) {
148 FlushAllRegs();
149 // FIXME: need separate LoadValues for object references.
150 LoadValueDirectFixed(rl_src, rs_r0); // Get obj
151 LockCallTemps(); // Prepare for explicit register usage
152 constexpr bool kArchVariantHasGoodBranchPredictor = false; // TODO: true if cortex-A15.
153 if (kArchVariantHasGoodBranchPredictor) {
154 LIR* null_check_branch = nullptr;
155 if ((opt_flags & MIR_IGNORE_NULL_CHECK) && !(cu_->disable_opt & (1 << kNullCheckElimination))) {
156 null_check_branch = nullptr; // No null check.
157 } else {
158 // If the null-check fails its handled by the slow-path to reduce exception related meta-data.
159 if (!cu_->compiler_driver->GetCompilerOptions().GetImplicitNullChecks()) {
160 null_check_branch = OpCmpImmBranch(kCondEq, rs_r0, 0, nullptr);
161 }
162 }
163 Load32Disp(rs_rARM_SELF, Thread::ThinLockIdOffset<4>().Int32Value(), rs_r2);
164 NewLIR3(kThumb2Ldrex, rs_r1.GetReg(), rs_r0.GetReg(),
165 mirror::Object::MonitorOffset().Int32Value() >> 2);
166 MarkPossibleNullPointerException(opt_flags);
167 // Zero out the read barrier bits.
168 OpRegRegImm(kOpAnd, rs_r3, rs_r1, LockWord::kReadBarrierStateMaskShiftedToggled);
169 LIR* not_unlocked_branch = OpCmpImmBranch(kCondNe, rs_r3, 0, nullptr);
170 // r1 is zero except for the rb bits here. Copy the read barrier bits into r2.
171 OpRegRegReg(kOpOr, rs_r2, rs_r2, rs_r1);
172 NewLIR4(kThumb2Strex, rs_r1.GetReg(), rs_r2.GetReg(), rs_r0.GetReg(),
173 mirror::Object::MonitorOffset().Int32Value() >> 2);
174 LIR* lock_success_branch = OpCmpImmBranch(kCondEq, rs_r1, 0, nullptr);
175
176
177 LIR* slow_path_target = NewLIR0(kPseudoTargetLabel);
178 not_unlocked_branch->target = slow_path_target;
179 if (null_check_branch != nullptr) {
180 null_check_branch->target = slow_path_target;
181 }
182 // TODO: move to a slow path.
183 // Go expensive route - artLockObjectFromCode(obj);
184 LoadWordDisp(rs_rARM_SELF, QUICK_ENTRYPOINT_OFFSET(4, pLockObject).Int32Value(), rs_rARM_LR);
185 ClobberCallerSave();
186 LIR* call_inst = OpReg(kOpBlx, rs_rARM_LR);
187 MarkSafepointPC(call_inst);
188
189 LIR* success_target = NewLIR0(kPseudoTargetLabel);
190 lock_success_branch->target = success_target;
191 GenMemBarrier(kLoadAny);
192 } else {
193 // Explicit null-check as slow-path is entered using an IT.
194 GenNullCheck(rs_r0, opt_flags);
195 Load32Disp(rs_rARM_SELF, Thread::ThinLockIdOffset<4>().Int32Value(), rs_r2);
196 NewLIR3(kThumb2Ldrex, rs_r1.GetReg(), rs_r0.GetReg(),
197 mirror::Object::MonitorOffset().Int32Value() >> 2);
198 MarkPossibleNullPointerException(opt_flags);
199 // Zero out the read barrier bits.
200 OpRegRegImm(kOpAnd, rs_r3, rs_r1, LockWord::kReadBarrierStateMaskShiftedToggled);
201 // r1 will be zero except for the rb bits if the following
202 // cmp-and-branch branches to eq where r2 will be used. Copy the
203 // read barrier bits into r2.
204 OpRegRegReg(kOpOr, rs_r2, rs_r2, rs_r1);
205 OpRegImm(kOpCmp, rs_r3, 0);
206
207 LIR* it = OpIT(kCondEq, "");
208 NewLIR4(kThumb2Strex/*eq*/, rs_r1.GetReg(), rs_r2.GetReg(), rs_r0.GetReg(),
209 mirror::Object::MonitorOffset().Int32Value() >> 2);
210 OpEndIT(it);
211 OpRegImm(kOpCmp, rs_r1, 0);
212 it = OpIT(kCondNe, "T");
213 // Go expensive route - artLockObjectFromCode(self, obj);
214 LoadWordDisp/*ne*/(rs_rARM_SELF, QUICK_ENTRYPOINT_OFFSET(4, pLockObject).Int32Value(),
215 rs_rARM_LR);
216 ClobberCallerSave();
217 LIR* call_inst = OpReg(kOpBlx/*ne*/, rs_rARM_LR);
218 OpEndIT(it);
219 MarkSafepointPC(call_inst);
220 GenMemBarrier(kLoadAny);
221 }
222 }
223
224 /*
225 * Handle thin locked -> unlocked transition inline or else call out to quick entrypoint. For more
226 * details see monitor.cc. Note the code below doesn't use ldrex/strex as the code holds the lock
227 * and can only give away ownership if its suspended.
228 */
GenMonitorExit(int opt_flags,RegLocation rl_src)229 void ArmMir2Lir::GenMonitorExit(int opt_flags, RegLocation rl_src) {
230 FlushAllRegs();
231 LoadValueDirectFixed(rl_src, rs_r0); // Get obj
232 LockCallTemps(); // Prepare for explicit register usage
233 LIR* null_check_branch = nullptr;
234 Load32Disp(rs_rARM_SELF, Thread::ThinLockIdOffset<4>().Int32Value(), rs_r2);
235 constexpr bool kArchVariantHasGoodBranchPredictor = false; // TODO: true if cortex-A15.
236 if (kArchVariantHasGoodBranchPredictor) {
237 if ((opt_flags & MIR_IGNORE_NULL_CHECK) && !(cu_->disable_opt & (1 << kNullCheckElimination))) {
238 null_check_branch = nullptr; // No null check.
239 } else {
240 // If the null-check fails its handled by the slow-path to reduce exception related meta-data.
241 if (!cu_->compiler_driver->GetCompilerOptions().GetImplicitNullChecks()) {
242 null_check_branch = OpCmpImmBranch(kCondEq, rs_r0, 0, nullptr);
243 }
244 }
245 if (!kUseReadBarrier) {
246 Load32Disp(rs_r0, mirror::Object::MonitorOffset().Int32Value(), rs_r1); // Get lock
247 } else {
248 NewLIR3(kThumb2Ldrex, rs_r1.GetReg(), rs_r0.GetReg(),
249 mirror::Object::MonitorOffset().Int32Value() >> 2);
250 }
251 MarkPossibleNullPointerException(opt_flags);
252 // Zero out the read barrier bits.
253 OpRegRegImm(kOpAnd, rs_r3, rs_r1, LockWord::kReadBarrierStateMaskShiftedToggled);
254 // Zero out except the read barrier bits.
255 OpRegRegImm(kOpAnd, rs_r1, rs_r1, LockWord::kReadBarrierStateMaskShifted);
256 LIR* slow_unlock_branch = OpCmpBranch(kCondNe, rs_r3, rs_r2, nullptr);
257 GenMemBarrier(kAnyStore);
258 LIR* unlock_success_branch;
259 if (!kUseReadBarrier) {
260 Store32Disp(rs_r0, mirror::Object::MonitorOffset().Int32Value(), rs_r1);
261 unlock_success_branch = OpUnconditionalBranch(nullptr);
262 } else {
263 NewLIR4(kThumb2Strex, rs_r2.GetReg(), rs_r1.GetReg(), rs_r0.GetReg(),
264 mirror::Object::MonitorOffset().Int32Value() >> 2);
265 unlock_success_branch = OpCmpImmBranch(kCondEq, rs_r2, 0, nullptr);
266 }
267 LIR* slow_path_target = NewLIR0(kPseudoTargetLabel);
268 slow_unlock_branch->target = slow_path_target;
269 if (null_check_branch != nullptr) {
270 null_check_branch->target = slow_path_target;
271 }
272 // TODO: move to a slow path.
273 // Go expensive route - artUnlockObjectFromCode(obj);
274 LoadWordDisp(rs_rARM_SELF, QUICK_ENTRYPOINT_OFFSET(4, pUnlockObject).Int32Value(), rs_rARM_LR);
275 ClobberCallerSave();
276 LIR* call_inst = OpReg(kOpBlx, rs_rARM_LR);
277 MarkSafepointPC(call_inst);
278
279 LIR* success_target = NewLIR0(kPseudoTargetLabel);
280 unlock_success_branch->target = success_target;
281 } else {
282 // Explicit null-check as slow-path is entered using an IT.
283 GenNullCheck(rs_r0, opt_flags);
284 if (!kUseReadBarrier) {
285 Load32Disp(rs_r0, mirror::Object::MonitorOffset().Int32Value(), rs_r1); // Get lock
286 } else {
287 // If we use read barriers, we need to use atomic instructions.
288 NewLIR3(kThumb2Ldrex, rs_r1.GetReg(), rs_r0.GetReg(),
289 mirror::Object::MonitorOffset().Int32Value() >> 2);
290 }
291 MarkPossibleNullPointerException(opt_flags);
292 Load32Disp(rs_rARM_SELF, Thread::ThinLockIdOffset<4>().Int32Value(), rs_r2);
293 // Zero out the read barrier bits.
294 OpRegRegImm(kOpAnd, rs_r3, rs_r1, LockWord::kReadBarrierStateMaskShiftedToggled);
295 // Zero out except the read barrier bits.
296 OpRegRegImm(kOpAnd, rs_r1, rs_r1, LockWord::kReadBarrierStateMaskShifted);
297 // Is lock unheld on lock or held by us (==thread_id) on unlock?
298 OpRegReg(kOpCmp, rs_r3, rs_r2);
299 if (!kUseReadBarrier) {
300 LIR* it = OpIT(kCondEq, "EE");
301 if (GenMemBarrier(kAnyStore)) {
302 UpdateIT(it, "TEE");
303 }
304 Store32Disp/*eq*/(rs_r0, mirror::Object::MonitorOffset().Int32Value(), rs_r1);
305 // Go expensive route - UnlockObjectFromCode(obj);
306 LoadWordDisp/*ne*/(rs_rARM_SELF, QUICK_ENTRYPOINT_OFFSET(4, pUnlockObject).Int32Value(),
307 rs_rARM_LR);
308 ClobberCallerSave();
309 LIR* call_inst = OpReg(kOpBlx/*ne*/, rs_rARM_LR);
310 OpEndIT(it);
311 MarkSafepointPC(call_inst);
312 } else {
313 // If we use read barriers, we need to use atomic instructions.
314 LIR* it = OpIT(kCondEq, "");
315 if (GenMemBarrier(kAnyStore)) {
316 UpdateIT(it, "T");
317 }
318 NewLIR4/*eq*/(kThumb2Strex, rs_r2.GetReg(), rs_r1.GetReg(), rs_r0.GetReg(),
319 mirror::Object::MonitorOffset().Int32Value() >> 2);
320 OpEndIT(it);
321 // Since we know r2 wasn't zero before the above it instruction,
322 // if r2 is zero here, we know r3 was equal to r2 and the strex
323 // suceeded (we're done). Otherwise (either r3 wasn't equal to r2
324 // or the strex failed), call the entrypoint.
325 OpRegImm(kOpCmp, rs_r2, 0);
326 LIR* it2 = OpIT(kCondNe, "T");
327 // Go expensive route - UnlockObjectFromCode(obj);
328 LoadWordDisp/*ne*/(rs_rARM_SELF, QUICK_ENTRYPOINT_OFFSET(4, pUnlockObject).Int32Value(),
329 rs_rARM_LR);
330 ClobberCallerSave();
331 LIR* call_inst = OpReg(kOpBlx/*ne*/, rs_rARM_LR);
332 OpEndIT(it2);
333 MarkSafepointPC(call_inst);
334 }
335 }
336 }
337
GenMoveException(RegLocation rl_dest)338 void ArmMir2Lir::GenMoveException(RegLocation rl_dest) {
339 int ex_offset = Thread::ExceptionOffset<4>().Int32Value();
340 RegLocation rl_result = EvalLoc(rl_dest, kRefReg, true);
341 RegStorage reset_reg = AllocTempRef();
342 LoadRefDisp(rs_rARM_SELF, ex_offset, rl_result.reg, kNotVolatile);
343 LoadConstant(reset_reg, 0);
344 StoreRefDisp(rs_rARM_SELF, ex_offset, reset_reg, kNotVolatile);
345 FreeTemp(reset_reg);
346 StoreValue(rl_dest, rl_result);
347 }
348
UnconditionallyMarkGCCard(RegStorage tgt_addr_reg)349 void ArmMir2Lir::UnconditionallyMarkGCCard(RegStorage tgt_addr_reg) {
350 RegStorage reg_card_base = AllocTemp();
351 RegStorage reg_card_no = AllocTemp();
352 LoadWordDisp(rs_rARM_SELF, Thread::CardTableOffset<4>().Int32Value(), reg_card_base);
353 OpRegRegImm(kOpLsr, reg_card_no, tgt_addr_reg, gc::accounting::CardTable::kCardShift);
354 StoreBaseIndexed(reg_card_base, reg_card_no, reg_card_base, 0, kUnsignedByte);
355 FreeTemp(reg_card_base);
356 FreeTemp(reg_card_no);
357 }
358
DwarfCoreReg(int num)359 static dwarf::Reg DwarfCoreReg(int num) {
360 return dwarf::Reg::ArmCore(num);
361 }
362
DwarfFpReg(int num)363 static dwarf::Reg DwarfFpReg(int num) {
364 return dwarf::Reg::ArmFp(num);
365 }
366
GenEntrySequence(RegLocation * ArgLocs,RegLocation rl_method)367 void ArmMir2Lir::GenEntrySequence(RegLocation* ArgLocs, RegLocation rl_method) {
368 DCHECK_EQ(cfi_.GetCurrentCFAOffset(), 0); // empty stack.
369 int spill_count = num_core_spills_ + num_fp_spills_;
370 /*
371 * On entry, r0, r1, r2 & r3 are live. Let the register allocation
372 * mechanism know so it doesn't try to use any of them when
373 * expanding the frame or flushing. This leaves the utility
374 * code with a single temp: r12. This should be enough.
375 */
376 LockTemp(rs_r0);
377 LockTemp(rs_r1);
378 LockTemp(rs_r2);
379 LockTemp(rs_r3);
380
381 /*
382 * We can safely skip the stack overflow check if we're
383 * a leaf *and* our frame size < fudge factor.
384 */
385 bool skip_overflow_check = mir_graph_->MethodIsLeaf() && !FrameNeedsStackCheck(frame_size_, kArm);
386 const size_t kStackOverflowReservedUsableBytes = GetStackOverflowReservedBytes(kArm);
387 bool large_frame = (static_cast<size_t>(frame_size_) > kStackOverflowReservedUsableBytes);
388 bool generate_explicit_stack_overflow_check = large_frame ||
389 !cu_->compiler_driver->GetCompilerOptions().GetImplicitStackOverflowChecks();
390 if (!skip_overflow_check) {
391 if (generate_explicit_stack_overflow_check) {
392 if (!large_frame) {
393 /* Load stack limit */
394 LockTemp(rs_r12);
395 Load32Disp(rs_rARM_SELF, Thread::StackEndOffset<4>().Int32Value(), rs_r12);
396 }
397 } else {
398 // Implicit stack overflow check.
399 // Generate a load from [sp, #-overflowsize]. If this is in the stack
400 // redzone we will get a segmentation fault.
401 //
402 // Caveat coder: if someone changes the kStackOverflowReservedBytes value
403 // we need to make sure that it's loadable in an immediate field of
404 // a sub instruction. Otherwise we will get a temp allocation and the
405 // code size will increase.
406 //
407 // This is done before the callee save instructions to avoid any possibility
408 // of these overflowing. This uses r12 and that's never saved in a callee
409 // save.
410 OpRegRegImm(kOpSub, rs_r12, rs_rARM_SP, GetStackOverflowReservedBytes(kArm));
411 Load32Disp(rs_r12, 0, rs_r12);
412 MarkPossibleStackOverflowException();
413 }
414 }
415 /* Spill core callee saves */
416 if (core_spill_mask_ != 0u) {
417 if ((core_spill_mask_ & ~(0xffu | (1u << rs_rARM_LR.GetRegNum()))) == 0u) {
418 // Spilling only low regs and/or LR, use 16-bit PUSH.
419 constexpr int lr_bit_shift = rs_rARM_LR.GetRegNum() - 8;
420 NewLIR1(kThumbPush,
421 (core_spill_mask_ & ~(1u << rs_rARM_LR.GetRegNum())) |
422 ((core_spill_mask_ & (1u << rs_rARM_LR.GetRegNum())) >> lr_bit_shift));
423 } else if (IsPowerOfTwo(core_spill_mask_)) {
424 // kThumb2Push cannot be used to spill a single register.
425 NewLIR1(kThumb2Push1, CTZ(core_spill_mask_));
426 } else {
427 NewLIR1(kThumb2Push, core_spill_mask_);
428 }
429 cfi_.AdjustCFAOffset(num_core_spills_ * kArmPointerSize);
430 cfi_.RelOffsetForMany(DwarfCoreReg(0), 0, core_spill_mask_, kArmPointerSize);
431 }
432 /* Need to spill any FP regs? */
433 if (num_fp_spills_ != 0u) {
434 /*
435 * NOTE: fp spills are a little different from core spills in that
436 * they are pushed as a contiguous block. When promoting from
437 * the fp set, we must allocate all singles from s16..highest-promoted
438 */
439 NewLIR1(kThumb2VPushCS, num_fp_spills_);
440 cfi_.AdjustCFAOffset(num_fp_spills_ * kArmPointerSize);
441 cfi_.RelOffsetForMany(DwarfFpReg(0), 0, fp_spill_mask_, kArmPointerSize);
442 }
443
444 const int spill_size = spill_count * 4;
445 const int frame_size_without_spills = frame_size_ - spill_size;
446 if (!skip_overflow_check) {
447 if (generate_explicit_stack_overflow_check) {
448 class StackOverflowSlowPath : public LIRSlowPath {
449 public:
450 StackOverflowSlowPath(Mir2Lir* m2l, LIR* branch, bool restore_lr, size_t sp_displace)
451 : LIRSlowPath(m2l, branch), restore_lr_(restore_lr),
452 sp_displace_(sp_displace) {
453 }
454 void Compile() OVERRIDE {
455 m2l_->ResetRegPool();
456 m2l_->ResetDefTracking();
457 GenerateTargetLabel(kPseudoThrowTarget);
458 if (restore_lr_) {
459 m2l_->LoadWordDisp(rs_rARM_SP, sp_displace_ - 4, rs_rARM_LR);
460 }
461 m2l_->OpRegImm(kOpAdd, rs_rARM_SP, sp_displace_);
462 m2l_->cfi().AdjustCFAOffset(-sp_displace_);
463 m2l_->ClobberCallerSave();
464 ThreadOffset<4> func_offset = QUICK_ENTRYPOINT_OFFSET(4, pThrowStackOverflow);
465 // Load the entrypoint directly into the pc instead of doing a load + branch. Assumes
466 // codegen and target are in thumb2 mode.
467 // NOTE: native pointer.
468 m2l_->LoadWordDisp(rs_rARM_SELF, func_offset.Int32Value(), rs_rARM_PC);
469 m2l_->cfi().AdjustCFAOffset(sp_displace_);
470 }
471
472 private:
473 const bool restore_lr_;
474 const size_t sp_displace_;
475 };
476 if (large_frame) {
477 // Note: may need a temp reg, and we only have r12 free at this point.
478 OpRegRegImm(kOpSub, rs_rARM_LR, rs_rARM_SP, frame_size_without_spills);
479 Load32Disp(rs_rARM_SELF, Thread::StackEndOffset<4>().Int32Value(), rs_r12);
480 LIR* branch = OpCmpBranch(kCondUlt, rs_rARM_LR, rs_r12, nullptr);
481 // Need to restore LR since we used it as a temp.
482 AddSlowPath(new(arena_)StackOverflowSlowPath(this, branch, true, spill_size));
483 OpRegCopy(rs_rARM_SP, rs_rARM_LR); // Establish stack
484 cfi_.AdjustCFAOffset(frame_size_without_spills);
485 } else {
486 /*
487 * If the frame is small enough we are guaranteed to have enough space that remains to
488 * handle signals on the user stack. However, we may not have any free temp
489 * registers at this point, so we'll temporarily add LR to the temp pool.
490 */
491 DCHECK(!GetRegInfo(rs_rARM_LR)->IsTemp());
492 MarkTemp(rs_rARM_LR);
493 FreeTemp(rs_rARM_LR);
494 OpRegRegImm(kOpSub, rs_rARM_SP, rs_rARM_SP, frame_size_without_spills);
495 cfi_.AdjustCFAOffset(frame_size_without_spills);
496 Clobber(rs_rARM_LR);
497 UnmarkTemp(rs_rARM_LR);
498 LIR* branch = OpCmpBranch(kCondUlt, rs_rARM_SP, rs_r12, nullptr);
499 AddSlowPath(new(arena_)StackOverflowSlowPath(this, branch, false, frame_size_));
500 }
501 } else {
502 // Implicit stack overflow check has already been done. Just make room on the
503 // stack for the frame now.
504 OpRegImm(kOpSub, rs_rARM_SP, frame_size_without_spills);
505 cfi_.AdjustCFAOffset(frame_size_without_spills);
506 }
507 } else {
508 OpRegImm(kOpSub, rs_rARM_SP, frame_size_without_spills);
509 cfi_.AdjustCFAOffset(frame_size_without_spills);
510 }
511
512 FlushIns(ArgLocs, rl_method);
513
514 // We can promote a PC-relative reference to dex cache arrays to a register
515 // if it's used at least twice. Without investigating where we should lazily
516 // load the reference, we conveniently load it after flushing inputs.
517 if (dex_cache_arrays_base_reg_.Valid()) {
518 OpPcRelDexCacheArrayAddr(cu_->dex_file, dex_cache_arrays_min_offset_,
519 dex_cache_arrays_base_reg_);
520 }
521
522 FreeTemp(rs_r0);
523 FreeTemp(rs_r1);
524 FreeTemp(rs_r2);
525 FreeTemp(rs_r3);
526 FreeTemp(rs_r12);
527 }
528
GenExitSequence()529 void ArmMir2Lir::GenExitSequence() {
530 cfi_.RememberState();
531 int spill_count = num_core_spills_ + num_fp_spills_;
532
533 /*
534 * In the exit path, r0/r1 are live - make sure they aren't
535 * allocated by the register utilities as temps.
536 */
537 LockTemp(rs_r0);
538 LockTemp(rs_r1);
539
540 int adjust = frame_size_ - (spill_count * kArmPointerSize);
541 OpRegImm(kOpAdd, rs_rARM_SP, adjust);
542 cfi_.AdjustCFAOffset(-adjust);
543 /* Need to restore any FP callee saves? */
544 if (num_fp_spills_) {
545 NewLIR1(kThumb2VPopCS, num_fp_spills_);
546 cfi_.AdjustCFAOffset(-num_fp_spills_ * kArmPointerSize);
547 cfi_.RestoreMany(DwarfFpReg(0), fp_spill_mask_);
548 }
549 bool unspill_LR_to_PC = (core_spill_mask_ & (1 << rs_rARM_LR.GetRegNum())) != 0;
550 if (unspill_LR_to_PC) {
551 core_spill_mask_ &= ~(1 << rs_rARM_LR.GetRegNum());
552 core_spill_mask_ |= (1 << rs_rARM_PC.GetRegNum());
553 }
554 if (core_spill_mask_ != 0u) {
555 if ((core_spill_mask_ & ~(0xffu | (1u << rs_rARM_PC.GetRegNum()))) == 0u) {
556 // Unspilling only low regs and/or PC, use 16-bit POP.
557 constexpr int pc_bit_shift = rs_rARM_PC.GetRegNum() - 8;
558 NewLIR1(kThumbPop,
559 (core_spill_mask_ & ~(1u << rs_rARM_PC.GetRegNum())) |
560 ((core_spill_mask_ & (1u << rs_rARM_PC.GetRegNum())) >> pc_bit_shift));
561 } else if (IsPowerOfTwo(core_spill_mask_)) {
562 // kThumb2Pop cannot be used to unspill a single register.
563 NewLIR1(kThumb2Pop1, CTZ(core_spill_mask_));
564 } else {
565 NewLIR1(kThumb2Pop, core_spill_mask_);
566 }
567 // If we pop to PC, there is no further epilogue code.
568 if (!unspill_LR_to_PC) {
569 cfi_.AdjustCFAOffset(-num_core_spills_ * kArmPointerSize);
570 cfi_.RestoreMany(DwarfCoreReg(0), core_spill_mask_);
571 DCHECK_EQ(cfi_.GetCurrentCFAOffset(), 0); // empty stack.
572 }
573 }
574 if (!unspill_LR_to_PC) {
575 /* We didn't pop to rARM_PC, so must do a bv rARM_LR */
576 NewLIR1(kThumbBx, rs_rARM_LR.GetReg());
577 }
578 // The CFI should be restored for any code that follows the exit block.
579 cfi_.RestoreState();
580 cfi_.DefCFAOffset(frame_size_);
581 }
582
GenSpecialExitSequence()583 void ArmMir2Lir::GenSpecialExitSequence() {
584 NewLIR1(kThumbBx, rs_rARM_LR.GetReg());
585 }
586
GenSpecialEntryForSuspend()587 void ArmMir2Lir::GenSpecialEntryForSuspend() {
588 // Keep 16-byte stack alignment - push r0, i.e. ArtMethod*, r5, r6, lr.
589 DCHECK(!IsTemp(rs_r5));
590 DCHECK(!IsTemp(rs_r6));
591 core_spill_mask_ =
592 (1u << rs_r5.GetRegNum()) | (1u << rs_r6.GetRegNum()) | (1u << rs_rARM_LR.GetRegNum());
593 num_core_spills_ = 3u;
594 fp_spill_mask_ = 0u;
595 num_fp_spills_ = 0u;
596 frame_size_ = 16u;
597 core_vmap_table_.clear();
598 fp_vmap_table_.clear();
599 NewLIR1(kThumbPush, (1u << rs_r0.GetRegNum()) | // ArtMethod*
600 (core_spill_mask_ & ~(1u << rs_rARM_LR.GetRegNum())) | // Spills other than LR.
601 (1u << 8)); // LR encoded for 16-bit push.
602 cfi_.AdjustCFAOffset(frame_size_);
603 // Do not generate CFI for scratch register r0.
604 cfi_.RelOffsetForMany(DwarfCoreReg(0), 4, core_spill_mask_, kArmPointerSize);
605 }
606
GenSpecialExitForSuspend()607 void ArmMir2Lir::GenSpecialExitForSuspend() {
608 // Pop the frame. (ArtMethod* no longer needed but restore it anyway.)
609 NewLIR1(kThumb2Pop, (1u << rs_r0.GetRegNum()) | core_spill_mask_); // 32-bit because of LR.
610 cfi_.AdjustCFAOffset(-frame_size_);
611 cfi_.RestoreMany(DwarfCoreReg(0), core_spill_mask_);
612 }
613
ArmUseRelativeCall(CompilationUnit * cu,const MethodReference & target_method)614 static bool ArmUseRelativeCall(CompilationUnit* cu, const MethodReference& target_method) {
615 // Emit relative calls only within a dex file due to the limited range of the BL insn.
616 return cu->dex_file == target_method.dex_file;
617 }
618
619 /*
620 * Bit of a hack here - in the absence of a real scheduling pass,
621 * emit the next instruction in static & direct invoke sequences.
622 */
ArmNextSDCallInsn(CompilationUnit * cu,CallInfo * info,int state,const MethodReference & target_method,uint32_t unused_idx ATTRIBUTE_UNUSED,uintptr_t direct_code,uintptr_t direct_method,InvokeType type)623 int ArmMir2Lir::ArmNextSDCallInsn(CompilationUnit* cu, CallInfo* info,
624 int state, const MethodReference& target_method,
625 uint32_t unused_idx ATTRIBUTE_UNUSED,
626 uintptr_t direct_code, uintptr_t direct_method,
627 InvokeType type) {
628 ArmMir2Lir* cg = static_cast<ArmMir2Lir*>(cu->cg.get());
629 if (info->string_init_offset != 0) {
630 RegStorage arg0_ref = cg->TargetReg(kArg0, kRef);
631 switch (state) {
632 case 0: { // Grab target method* from thread pointer
633 cg->LoadRefDisp(rs_rARM_SELF, info->string_init_offset, arg0_ref, kNotVolatile);
634 break;
635 }
636 case 1: // Grab the code from the method*
637 if (direct_code == 0) {
638 // kInvokeTgt := arg0_ref->entrypoint
639 cg->LoadWordDisp(arg0_ref,
640 ArtMethod::EntryPointFromQuickCompiledCodeOffset(
641 kArmPointerSize).Int32Value(), cg->TargetPtrReg(kInvokeTgt));
642 }
643 break;
644 default:
645 return -1;
646 }
647 } else if (direct_code != 0 && direct_method != 0) {
648 switch (state) {
649 case 0: // Get the current Method* [sets kArg0]
650 if (direct_code != static_cast<uintptr_t>(-1)) {
651 cg->LoadConstant(cg->TargetPtrReg(kInvokeTgt), direct_code);
652 } else if (ArmUseRelativeCall(cu, target_method)) {
653 // Defer to linker patch.
654 } else {
655 cg->LoadCodeAddress(target_method, type, kInvokeTgt);
656 }
657 if (direct_method != static_cast<uintptr_t>(-1)) {
658 cg->LoadConstant(cg->TargetReg(kArg0, kRef), direct_method);
659 } else {
660 cg->LoadMethodAddress(target_method, type, kArg0);
661 }
662 break;
663 default:
664 return -1;
665 }
666 } else {
667 bool use_pc_rel = cg->CanUseOpPcRelDexCacheArrayLoad();
668 RegStorage arg0_ref = cg->TargetReg(kArg0, kRef);
669 switch (state) {
670 case 0: // Get the current Method* [sets kArg0]
671 // TUNING: we can save a reg copy if Method* has been promoted.
672 if (!use_pc_rel) {
673 cg->LoadCurrMethodDirect(arg0_ref);
674 break;
675 }
676 ++state;
677 FALLTHROUGH_INTENDED;
678 case 1: // Get method->dex_cache_resolved_methods_
679 if (!use_pc_rel) {
680 cg->LoadRefDisp(arg0_ref,
681 ArtMethod::DexCacheResolvedMethodsOffset().Int32Value(),
682 arg0_ref,
683 kNotVolatile);
684 }
685 // Set up direct code if known.
686 if (direct_code != 0) {
687 if (direct_code != static_cast<uintptr_t>(-1)) {
688 cg->LoadConstant(cg->TargetPtrReg(kInvokeTgt), direct_code);
689 } else if (ArmUseRelativeCall(cu, target_method)) {
690 // Defer to linker patch.
691 } else {
692 CHECK_LT(target_method.dex_method_index, target_method.dex_file->NumMethodIds());
693 cg->LoadCodeAddress(target_method, type, kInvokeTgt);
694 }
695 }
696 if (!use_pc_rel || direct_code != 0) {
697 break;
698 }
699 ++state;
700 FALLTHROUGH_INTENDED;
701 case 2: // Grab target method*
702 CHECK_EQ(cu->dex_file, target_method.dex_file);
703 if (!use_pc_rel) {
704 cg->LoadRefDisp(arg0_ref,
705 mirror::ObjectArray<mirror::Object>::OffsetOfElement(
706 target_method.dex_method_index).Int32Value(),
707 arg0_ref,
708 kNotVolatile);
709 } else {
710 size_t offset = cg->dex_cache_arrays_layout_.MethodOffset(target_method.dex_method_index);
711 cg->OpPcRelDexCacheArrayLoad(cu->dex_file, offset, arg0_ref, false);
712 }
713 break;
714 case 3: // Grab the code from the method*
715 if (direct_code == 0) {
716 // kInvokeTgt := arg0_ref->entrypoint
717 cg->LoadWordDisp(arg0_ref,
718 ArtMethod::EntryPointFromQuickCompiledCodeOffset(
719 kArmPointerSize).Int32Value(), cg->TargetPtrReg(kInvokeTgt));
720 }
721 break;
722 default:
723 return -1;
724 }
725 }
726 return state + 1;
727 }
728
GetNextSDCallInsn()729 NextCallInsn ArmMir2Lir::GetNextSDCallInsn() {
730 return ArmNextSDCallInsn;
731 }
732
CallWithLinkerFixup(const MethodReference & target_method,InvokeType type)733 LIR* ArmMir2Lir::CallWithLinkerFixup(const MethodReference& target_method, InvokeType type) {
734 // For ARM, just generate a relative BL instruction that will be filled in at 'link time'.
735 // If the target turns out to be too far, the linker will generate a thunk for dispatch.
736 int target_method_idx = target_method.dex_method_index;
737 const DexFile* target_dex_file = target_method.dex_file;
738
739 // Generate the call instruction and save index, dex_file, and type.
740 // NOTE: Method deduplication takes linker patches into account, so we can just pass 0
741 // as a placeholder for the offset.
742 LIR* call = RawLIR(current_dalvik_offset_, kThumb2Bl, 0,
743 target_method_idx, WrapPointer(target_dex_file), type);
744 AppendLIR(call);
745 call_method_insns_.push_back(call);
746 return call;
747 }
748
GenCallInsn(const MirMethodLoweringInfo & method_info)749 LIR* ArmMir2Lir::GenCallInsn(const MirMethodLoweringInfo& method_info) {
750 LIR* call_insn;
751 if (method_info.FastPath() && ArmUseRelativeCall(cu_, method_info.GetTargetMethod()) &&
752 (method_info.GetSharpType() == kDirect || method_info.GetSharpType() == kStatic) &&
753 method_info.DirectCode() == static_cast<uintptr_t>(-1)) {
754 call_insn = CallWithLinkerFixup(method_info.GetTargetMethod(), method_info.GetSharpType());
755 } else {
756 call_insn = OpReg(kOpBlx, TargetPtrReg(kInvokeTgt));
757 }
758 return call_insn;
759 }
760
761 } // namespace art
762