blob: 5d78ed584863131cfefbb1c3c4978cf3ad06e083 [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
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#include "dex/compiler_internals.h"
18#include "dex_file-inl.h"
19#include "gc_map.h"
Ian Rogers96faf5b2013-08-09 22:05:32 -070020#include "mapping_table.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070021#include "mir_to_lir-inl.h"
22#include "verifier/dex_gc_map.h"
23#include "verifier/method_verifier.h"
24
25namespace art {
26
Vladimir Marko06606b92013-12-02 15:31:08 +000027namespace {
28
29/* Dump a mapping table */
30template <typename It>
31void DumpMappingTable(const char* table_name, const char* descriptor, const char* name,
32 const Signature& signature, uint32_t size, It first) {
33 if (size != 0) {
34 std::string line(StringPrintf("\n %s %s%s_%s_table[%zu] = {", table_name,
35 descriptor, name, signature.ToString().c_str(), size));
36 std::replace(line.begin(), line.end(), ';', '_');
37 LOG(INFO) << line;
38 for (uint32_t i = 0; i != size; ++i) {
39 line = StringPrintf(" {0x%05x, 0x%04x},", first.NativePcOffset(), first.DexPc());
40 ++first;
41 LOG(INFO) << line;
42 }
43 LOG(INFO) <<" };\n\n";
44 }
45}
46
47} // anonymous namespace
48
Brian Carlstrom2ce745c2013-07-17 17:44:30 -070049bool Mir2Lir::IsInexpensiveConstant(RegLocation rl_src) {
Brian Carlstrom7940e442013-07-12 13:46:57 -070050 bool res = false;
51 if (rl_src.is_const) {
52 if (rl_src.wide) {
53 if (rl_src.fp) {
54 res = InexpensiveConstantDouble(mir_graph_->ConstantValueWide(rl_src));
55 } else {
56 res = InexpensiveConstantLong(mir_graph_->ConstantValueWide(rl_src));
57 }
58 } else {
59 if (rl_src.fp) {
60 res = InexpensiveConstantFloat(mir_graph_->ConstantValue(rl_src));
61 } else {
62 res = InexpensiveConstantInt(mir_graph_->ConstantValue(rl_src));
63 }
64 }
65 }
66 return res;
67}
68
Brian Carlstrom2ce745c2013-07-17 17:44:30 -070069void Mir2Lir::MarkSafepointPC(LIR* inst) {
buzbeeb48819d2013-09-14 16:15:25 -070070 DCHECK(!inst->flags.use_def_invalid);
71 inst->u.m.def_mask = ENCODE_ALL;
Brian Carlstrom7940e442013-07-12 13:46:57 -070072 LIR* safepoint_pc = NewLIR0(kPseudoSafepointPC);
buzbeeb48819d2013-09-14 16:15:25 -070073 DCHECK_EQ(safepoint_pc->u.m.def_mask, ENCODE_ALL);
Brian Carlstrom7940e442013-07-12 13:46:57 -070074}
75
Ian Rogers9b297bf2013-09-06 11:11:25 -070076bool Mir2Lir::FastInstance(uint32_t field_idx, bool is_put, int* field_offset, bool* is_volatile) {
Brian Carlstrom7940e442013-07-12 13:46:57 -070077 return cu_->compiler_driver->ComputeInstanceFieldInfo(
Ian Rogers9b297bf2013-09-06 11:11:25 -070078 field_idx, mir_graph_->GetCurrentDexCompilationUnit(), is_put, field_offset, is_volatile);
Brian Carlstrom7940e442013-07-12 13:46:57 -070079}
80
buzbee252254b2013-09-08 16:20:53 -070081/* Remove a LIR from the list. */
82void Mir2Lir::UnlinkLIR(LIR* lir) {
83 if (UNLIKELY(lir == first_lir_insn_)) {
84 first_lir_insn_ = lir->next;
85 if (lir->next != NULL) {
86 lir->next->prev = NULL;
87 } else {
88 DCHECK(lir->next == NULL);
89 DCHECK(lir == last_lir_insn_);
90 last_lir_insn_ = NULL;
91 }
92 } else if (lir == last_lir_insn_) {
93 last_lir_insn_ = lir->prev;
94 lir->prev->next = NULL;
95 } else if ((lir->prev != NULL) && (lir->next != NULL)) {
96 lir->prev->next = lir->next;
97 lir->next->prev = lir->prev;
98 }
99}
100
Brian Carlstrom7940e442013-07-12 13:46:57 -0700101/* Convert an instruction to a NOP */
Brian Carlstromdf629502013-07-17 22:39:56 -0700102void Mir2Lir::NopLIR(LIR* lir) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700103 lir->flags.is_nop = true;
buzbee252254b2013-09-08 16:20:53 -0700104 if (!cu_->verbose) {
105 UnlinkLIR(lir);
106 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700107}
108
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700109void Mir2Lir::SetMemRefType(LIR* lir, bool is_load, int mem_type) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700110 uint64_t *mask_ptr;
Brian Carlstromf69863b2013-07-17 21:53:13 -0700111 uint64_t mask = ENCODE_MEM;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700112 DCHECK(GetTargetInstFlags(lir->opcode) & (IS_LOAD | IS_STORE));
buzbeeb48819d2013-09-14 16:15:25 -0700113 DCHECK(!lir->flags.use_def_invalid);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700114 if (is_load) {
buzbeeb48819d2013-09-14 16:15:25 -0700115 mask_ptr = &lir->u.m.use_mask;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700116 } else {
buzbeeb48819d2013-09-14 16:15:25 -0700117 mask_ptr = &lir->u.m.def_mask;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700118 }
119 /* Clear out the memref flags */
120 *mask_ptr &= ~mask;
121 /* ..and then add back the one we need */
122 switch (mem_type) {
123 case kLiteral:
124 DCHECK(is_load);
125 *mask_ptr |= ENCODE_LITERAL;
126 break;
127 case kDalvikReg:
128 *mask_ptr |= ENCODE_DALVIK_REG;
129 break;
130 case kHeapRef:
131 *mask_ptr |= ENCODE_HEAP_REF;
132 break;
133 case kMustNotAlias:
134 /* Currently only loads can be marked as kMustNotAlias */
135 DCHECK(!(GetTargetInstFlags(lir->opcode) & IS_STORE));
136 *mask_ptr |= ENCODE_MUST_NOT_ALIAS;
137 break;
138 default:
139 LOG(FATAL) << "Oat: invalid memref kind - " << mem_type;
140 }
141}
142
143/*
144 * Mark load/store instructions that access Dalvik registers through the stack.
145 */
146void Mir2Lir::AnnotateDalvikRegAccess(LIR* lir, int reg_id, bool is_load,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700147 bool is64bit) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700148 SetMemRefType(lir, is_load, kDalvikReg);
149
150 /*
151 * Store the Dalvik register id in alias_info. Mark the MSB if it is a 64-bit
152 * access.
153 */
buzbeeb48819d2013-09-14 16:15:25 -0700154 lir->flags.alias_info = ENCODE_ALIAS_INFO(reg_id, is64bit);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700155}
156
157/*
158 * Debugging macros
159 */
160#define DUMP_RESOURCE_MASK(X)
161
162/* Pretty-print a LIR instruction */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700163void Mir2Lir::DumpLIRInsn(LIR* lir, unsigned char* base_addr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700164 int offset = lir->offset;
165 int dest = lir->operands[0];
166 const bool dump_nop = (cu_->enable_debug & (1 << kDebugShowNops));
167
168 /* Handle pseudo-ops individually, and all regular insns as a group */
169 switch (lir->opcode) {
170 case kPseudoMethodEntry:
171 LOG(INFO) << "-------- method entry "
172 << PrettyMethod(cu_->method_idx, *cu_->dex_file);
173 break;
174 case kPseudoMethodExit:
175 LOG(INFO) << "-------- Method_Exit";
176 break;
177 case kPseudoBarrier:
178 LOG(INFO) << "-------- BARRIER";
179 break;
180 case kPseudoEntryBlock:
181 LOG(INFO) << "-------- entry offset: 0x" << std::hex << dest;
182 break;
183 case kPseudoDalvikByteCodeBoundary:
184 if (lir->operands[0] == 0) {
buzbee0d829482013-10-11 15:24:55 -0700185 // NOTE: only used for debug listings.
186 lir->operands[0] = WrapPointer(ArenaStrdup("No instruction string"));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700187 }
188 LOG(INFO) << "-------- dalvik offset: 0x" << std::hex
Bill Buzbee0b1191c2013-10-28 22:11:59 +0000189 << lir->dalvik_offset << " @ "
190 << reinterpret_cast<char*>(UnwrapPointer(lir->operands[0]));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700191 break;
192 case kPseudoExitBlock:
193 LOG(INFO) << "-------- exit offset: 0x" << std::hex << dest;
194 break;
195 case kPseudoPseudoAlign4:
196 LOG(INFO) << reinterpret_cast<uintptr_t>(base_addr) + offset << " (0x" << std::hex
197 << offset << "): .align4";
198 break;
199 case kPseudoEHBlockLabel:
200 LOG(INFO) << "Exception_Handling:";
201 break;
202 case kPseudoTargetLabel:
203 case kPseudoNormalBlockLabel:
204 LOG(INFO) << "L" << reinterpret_cast<void*>(lir) << ":";
205 break;
206 case kPseudoThrowTarget:
207 LOG(INFO) << "LT" << reinterpret_cast<void*>(lir) << ":";
208 break;
209 case kPseudoIntrinsicRetry:
210 LOG(INFO) << "IR" << reinterpret_cast<void*>(lir) << ":";
211 break;
212 case kPseudoSuspendTarget:
213 LOG(INFO) << "LS" << reinterpret_cast<void*>(lir) << ":";
214 break;
215 case kPseudoSafepointPC:
216 LOG(INFO) << "LsafepointPC_0x" << std::hex << lir->offset << "_" << lir->dalvik_offset << ":";
217 break;
218 case kPseudoExportedPC:
219 LOG(INFO) << "LexportedPC_0x" << std::hex << lir->offset << "_" << lir->dalvik_offset << ":";
220 break;
221 case kPseudoCaseLabel:
222 LOG(INFO) << "LC" << reinterpret_cast<void*>(lir) << ": Case target 0x"
223 << std::hex << lir->operands[0] << "|" << std::dec <<
224 lir->operands[0];
225 break;
226 default:
227 if (lir->flags.is_nop && !dump_nop) {
228 break;
229 } else {
230 std::string op_name(BuildInsnString(GetTargetInstName(lir->opcode),
231 lir, base_addr));
232 std::string op_operands(BuildInsnString(GetTargetInstFmt(lir->opcode),
233 lir, base_addr));
234 LOG(INFO) << StringPrintf("%05x: %-9s%s%s",
235 reinterpret_cast<unsigned int>(base_addr + offset),
236 op_name.c_str(), op_operands.c_str(),
237 lir->flags.is_nop ? "(nop)" : "");
238 }
239 break;
240 }
241
buzbeeb48819d2013-09-14 16:15:25 -0700242 if (lir->u.m.use_mask && (!lir->flags.is_nop || dump_nop)) {
243 DUMP_RESOURCE_MASK(DumpResourceMask(lir, lir->u.m.use_mask, "use"));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700244 }
buzbeeb48819d2013-09-14 16:15:25 -0700245 if (lir->u.m.def_mask && (!lir->flags.is_nop || dump_nop)) {
246 DUMP_RESOURCE_MASK(DumpResourceMask(lir, lir->u.m.def_mask, "def"));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700247 }
248}
249
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700250void Mir2Lir::DumpPromotionMap() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700251 int num_regs = cu_->num_dalvik_registers + cu_->num_compiler_temps + 1;
252 for (int i = 0; i < num_regs; i++) {
253 PromotionMap v_reg_map = promotion_map_[i];
254 std::string buf;
255 if (v_reg_map.fp_location == kLocPhysReg) {
256 StringAppendF(&buf, " : s%d", v_reg_map.FpReg & FpRegMask());
257 }
258
259 std::string buf3;
260 if (i < cu_->num_dalvik_registers) {
261 StringAppendF(&buf3, "%02d", i);
262 } else if (i == mir_graph_->GetMethodSReg()) {
263 buf3 = "Method*";
264 } else {
265 StringAppendF(&buf3, "ct%d", i - cu_->num_dalvik_registers);
266 }
267
268 LOG(INFO) << StringPrintf("V[%s] -> %s%d%s", buf3.c_str(),
269 v_reg_map.core_location == kLocPhysReg ?
270 "r" : "SP+", v_reg_map.core_location == kLocPhysReg ?
271 v_reg_map.core_reg : SRegOffset(i),
272 buf.c_str());
273 }
274}
275
Brian Carlstrom7940e442013-07-12 13:46:57 -0700276/* Dump instructions and constant pool contents */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700277void Mir2Lir::CodegenDump() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700278 LOG(INFO) << "Dumping LIR insns for "
279 << PrettyMethod(cu_->method_idx, *cu_->dex_file);
280 LIR* lir_insn;
281 int insns_size = cu_->code_item->insns_size_in_code_units_;
282
283 LOG(INFO) << "Regs (excluding ins) : " << cu_->num_regs;
284 LOG(INFO) << "Ins : " << cu_->num_ins;
285 LOG(INFO) << "Outs : " << cu_->num_outs;
286 LOG(INFO) << "CoreSpills : " << num_core_spills_;
287 LOG(INFO) << "FPSpills : " << num_fp_spills_;
288 LOG(INFO) << "CompilerTemps : " << cu_->num_compiler_temps;
289 LOG(INFO) << "Frame size : " << frame_size_;
290 LOG(INFO) << "code size is " << total_size_ <<
291 " bytes, Dalvik size is " << insns_size * 2;
292 LOG(INFO) << "expansion factor: "
293 << static_cast<float>(total_size_) / static_cast<float>(insns_size * 2);
294 DumpPromotionMap();
295 for (lir_insn = first_lir_insn_; lir_insn != NULL; lir_insn = lir_insn->next) {
296 DumpLIRInsn(lir_insn, 0);
297 }
298 for (lir_insn = literal_list_; lir_insn != NULL; lir_insn = lir_insn->next) {
299 LOG(INFO) << StringPrintf("%x (%04x): .word (%#x)", lir_insn->offset, lir_insn->offset,
300 lir_insn->operands[0]);
301 }
302
303 const DexFile::MethodId& method_id =
304 cu_->dex_file->GetMethodId(cu_->method_idx);
Ian Rogersd91d6d62013-09-25 20:26:14 -0700305 const Signature signature = cu_->dex_file->GetMethodSignature(method_id);
306 const char* name = cu_->dex_file->GetMethodName(method_id);
307 const char* descriptor(cu_->dex_file->GetMethodDeclaringClassDescriptor(method_id));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700308
309 // Dump mapping tables
Vladimir Marko06606b92013-12-02 15:31:08 +0000310 if (!encoded_mapping_table_.empty()) {
311 MappingTable table(&encoded_mapping_table_[0]);
312 DumpMappingTable("PC2Dex_MappingTable", descriptor, name, signature,
313 table.PcToDexSize(), table.PcToDexBegin());
314 DumpMappingTable("Dex2PC_MappingTable", descriptor, name, signature,
315 table.DexToPcSize(), table.DexToPcBegin());
316 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700317}
318
319/*
320 * Search the existing constants in the literal pool for an exact or close match
321 * within specified delta (greater or equal to 0).
322 */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700323LIR* Mir2Lir::ScanLiteralPool(LIR* data_target, int value, unsigned int delta) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700324 while (data_target) {
325 if ((static_cast<unsigned>(value - data_target->operands[0])) <= delta)
326 return data_target;
327 data_target = data_target->next;
328 }
329 return NULL;
330}
331
332/* Search the existing constants in the literal pool for an exact wide match */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700333LIR* Mir2Lir::ScanLiteralPoolWide(LIR* data_target, int val_lo, int val_hi) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700334 bool lo_match = false;
335 LIR* lo_target = NULL;
336 while (data_target) {
337 if (lo_match && (data_target->operands[0] == val_hi)) {
338 // Record high word in case we need to expand this later.
339 lo_target->operands[1] = val_hi;
340 return lo_target;
341 }
342 lo_match = false;
343 if (data_target->operands[0] == val_lo) {
344 lo_match = true;
345 lo_target = data_target;
346 }
347 data_target = data_target->next;
348 }
349 return NULL;
350}
351
352/*
353 * The following are building blocks to insert constants into the pool or
354 * instruction streams.
355 */
356
357/* Add a 32-bit constant to the constant pool */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700358LIR* Mir2Lir::AddWordData(LIR* *constant_list_p, int value) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700359 /* Add the constant to the literal pool */
360 if (constant_list_p) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700361 LIR* new_value = static_cast<LIR*>(arena_->Alloc(sizeof(LIR), ArenaAllocator::kAllocData));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700362 new_value->operands[0] = value;
363 new_value->next = *constant_list_p;
364 *constant_list_p = new_value;
buzbeeb48819d2013-09-14 16:15:25 -0700365 estimated_native_code_size_ += sizeof(value);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700366 return new_value;
367 }
368 return NULL;
369}
370
371/* Add a 64-bit constant to the constant pool or mixed with code */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700372LIR* Mir2Lir::AddWideData(LIR* *constant_list_p, int val_lo, int val_hi) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700373 AddWordData(constant_list_p, val_hi);
374 return AddWordData(constant_list_p, val_lo);
375}
376
377static void PushWord(std::vector<uint8_t>&buf, int data) {
Brian Carlstromdf629502013-07-17 22:39:56 -0700378 buf.push_back(data & 0xff);
379 buf.push_back((data >> 8) & 0xff);
380 buf.push_back((data >> 16) & 0xff);
381 buf.push_back((data >> 24) & 0xff);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700382}
383
buzbee0d829482013-10-11 15:24:55 -0700384// Push 8 bytes on 64-bit systems; 4 on 32-bit systems.
385static void PushPointer(std::vector<uint8_t>&buf, void const* pointer) {
386 uintptr_t data = reinterpret_cast<uintptr_t>(pointer);
387 if (sizeof(void*) == sizeof(uint64_t)) {
388 PushWord(buf, (data >> (sizeof(void*) * 4)) & 0xFFFFFFFF);
389 PushWord(buf, data & 0xFFFFFFFF);
390 } else {
391 PushWord(buf, data);
392 }
393}
394
Brian Carlstrom7940e442013-07-12 13:46:57 -0700395static void AlignBuffer(std::vector<uint8_t>&buf, size_t offset) {
396 while (buf.size() < offset) {
397 buf.push_back(0);
398 }
399}
400
401/* Write the literal pool to the output stream */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700402void Mir2Lir::InstallLiteralPools() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700403 AlignBuffer(code_buffer_, data_offset_);
404 LIR* data_lir = literal_list_;
405 while (data_lir != NULL) {
406 PushWord(code_buffer_, data_lir->operands[0]);
407 data_lir = NEXT_LIR(data_lir);
408 }
409 // Push code and method literals, record offsets for the compiler to patch.
410 data_lir = code_literal_list_;
411 while (data_lir != NULL) {
412 uint32_t target = data_lir->operands[0];
413 cu_->compiler_driver->AddCodePatch(cu_->dex_file,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700414 cu_->class_def_idx,
415 cu_->method_idx,
416 cu_->invoke_type,
417 target,
418 static_cast<InvokeType>(data_lir->operands[1]),
419 code_buffer_.size());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700420 const DexFile::MethodId& id = cu_->dex_file->GetMethodId(target);
buzbee0d829482013-10-11 15:24:55 -0700421 // unique value based on target to ensure code deduplication works
422 PushPointer(code_buffer_, &id);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700423 data_lir = NEXT_LIR(data_lir);
424 }
425 data_lir = method_literal_list_;
426 while (data_lir != NULL) {
427 uint32_t target = data_lir->operands[0];
428 cu_->compiler_driver->AddMethodPatch(cu_->dex_file,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700429 cu_->class_def_idx,
430 cu_->method_idx,
431 cu_->invoke_type,
432 target,
433 static_cast<InvokeType>(data_lir->operands[1]),
434 code_buffer_.size());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700435 const DexFile::MethodId& id = cu_->dex_file->GetMethodId(target);
buzbee0d829482013-10-11 15:24:55 -0700436 // unique value based on target to ensure code deduplication works
437 PushPointer(code_buffer_, &id);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700438 data_lir = NEXT_LIR(data_lir);
439 }
440}
441
442/* Write the switch tables to the output stream */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700443void Mir2Lir::InstallSwitchTables() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700444 GrowableArray<SwitchTable*>::Iterator iterator(&switch_tables_);
445 while (true) {
446 Mir2Lir::SwitchTable* tab_rec = iterator.Next();
447 if (tab_rec == NULL) break;
448 AlignBuffer(code_buffer_, tab_rec->offset);
449 /*
450 * For Arm, our reference point is the address of the bx
451 * instruction that does the launch, so we have to subtract
452 * the auto pc-advance. For other targets the reference point
453 * is a label, so we can use the offset as-is.
454 */
455 int bx_offset = INVALID_OFFSET;
456 switch (cu_->instruction_set) {
457 case kThumb2:
buzbeeb48819d2013-09-14 16:15:25 -0700458 DCHECK(tab_rec->anchor->flags.fixup != kFixupNone);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700459 bx_offset = tab_rec->anchor->offset + 4;
460 break;
461 case kX86:
462 bx_offset = 0;
463 break;
464 case kMips:
465 bx_offset = tab_rec->anchor->offset;
466 break;
467 default: LOG(FATAL) << "Unexpected instruction set: " << cu_->instruction_set;
468 }
469 if (cu_->verbose) {
470 LOG(INFO) << "Switch table for offset 0x" << std::hex << bx_offset;
471 }
472 if (tab_rec->table[0] == Instruction::kSparseSwitchSignature) {
buzbee0d829482013-10-11 15:24:55 -0700473 const int32_t* keys = reinterpret_cast<const int32_t*>(&(tab_rec->table[2]));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700474 for (int elems = 0; elems < tab_rec->table[1]; elems++) {
475 int disp = tab_rec->targets[elems]->offset - bx_offset;
476 if (cu_->verbose) {
477 LOG(INFO) << " Case[" << elems << "] key: 0x"
478 << std::hex << keys[elems] << ", disp: 0x"
479 << std::hex << disp;
480 }
481 PushWord(code_buffer_, keys[elems]);
482 PushWord(code_buffer_,
483 tab_rec->targets[elems]->offset - bx_offset);
484 }
485 } else {
486 DCHECK_EQ(static_cast<int>(tab_rec->table[0]),
487 static_cast<int>(Instruction::kPackedSwitchSignature));
488 for (int elems = 0; elems < tab_rec->table[1]; elems++) {
489 int disp = tab_rec->targets[elems]->offset - bx_offset;
490 if (cu_->verbose) {
491 LOG(INFO) << " Case[" << elems << "] disp: 0x"
492 << std::hex << disp;
493 }
494 PushWord(code_buffer_, tab_rec->targets[elems]->offset - bx_offset);
495 }
496 }
497 }
498}
499
500/* Write the fill array dta to the output stream */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700501void Mir2Lir::InstallFillArrayData() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700502 GrowableArray<FillArrayData*>::Iterator iterator(&fill_array_data_);
503 while (true) {
504 Mir2Lir::FillArrayData *tab_rec = iterator.Next();
505 if (tab_rec == NULL) break;
506 AlignBuffer(code_buffer_, tab_rec->offset);
507 for (int i = 0; i < (tab_rec->size + 1) / 2; i++) {
Brian Carlstromdf629502013-07-17 22:39:56 -0700508 code_buffer_.push_back(tab_rec->table[i] & 0xFF);
509 code_buffer_.push_back((tab_rec->table[i] >> 8) & 0xFF);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700510 }
511 }
512}
513
buzbee0d829482013-10-11 15:24:55 -0700514static int AssignLiteralOffsetCommon(LIR* lir, CodeOffset offset) {
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700515 for (; lir != NULL; lir = lir->next) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700516 lir->offset = offset;
517 offset += 4;
518 }
519 return offset;
520}
521
buzbee0d829482013-10-11 15:24:55 -0700522static int AssignLiteralPointerOffsetCommon(LIR* lir, CodeOffset offset) {
523 unsigned int element_size = sizeof(void*);
524 // Align to natural pointer size.
525 offset = (offset + (element_size - 1)) & ~(element_size - 1);
526 for (; lir != NULL; lir = lir->next) {
527 lir->offset = offset;
528 offset += element_size;
529 }
530 return offset;
531}
532
Brian Carlstrom7940e442013-07-12 13:46:57 -0700533// Make sure we have a code address for every declared catch entry
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700534bool Mir2Lir::VerifyCatchEntries() {
Vladimir Marko06606b92013-12-02 15:31:08 +0000535 MappingTable table(&encoded_mapping_table_[0]);
536 std::vector<uint32_t> dex_pcs;
537 dex_pcs.reserve(table.DexToPcSize());
538 for (auto it = table.DexToPcBegin(), end = table.DexToPcEnd(); it != end; ++it) {
539 dex_pcs.push_back(it.DexPc());
540 }
541 // Sort dex_pcs, so that we can quickly check it against the ordered mir_graph_->catches_.
542 std::sort(dex_pcs.begin(), dex_pcs.end());
543
Brian Carlstrom7940e442013-07-12 13:46:57 -0700544 bool success = true;
Vladimir Marko06606b92013-12-02 15:31:08 +0000545 auto it = dex_pcs.begin(), end = dex_pcs.end();
546 for (uint32_t dex_pc : mir_graph_->catches_) {
547 while (it != end && *it < dex_pc) {
548 LOG(INFO) << "Unexpected catch entry @ dex pc 0x" << std::hex << *it;
549 ++it;
550 success = false;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700551 }
Vladimir Marko06606b92013-12-02 15:31:08 +0000552 if (it == end || *it > dex_pc) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700553 LOG(INFO) << "Missing native PC for catch entry @ 0x" << std::hex << dex_pc;
554 success = false;
Vladimir Marko06606b92013-12-02 15:31:08 +0000555 } else {
556 ++it;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700557 }
558 }
559 if (!success) {
560 LOG(INFO) << "Bad dex2pcMapping table in " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
561 LOG(INFO) << "Entries @ decode: " << mir_graph_->catches_.size() << ", Entries in table: "
Vladimir Marko06606b92013-12-02 15:31:08 +0000562 << table.DexToPcSize();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700563 }
564 return success;
565}
566
567
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700568void Mir2Lir::CreateMappingTables() {
Vladimir Marko1e6cb632013-11-28 16:27:29 +0000569 uint32_t pc2dex_data_size = 0u;
570 uint32_t pc2dex_entries = 0u;
571 uint32_t pc2dex_offset = 0u;
572 uint32_t pc2dex_dalvik_offset = 0u;
573 uint32_t dex2pc_data_size = 0u;
574 uint32_t dex2pc_entries = 0u;
575 uint32_t dex2pc_offset = 0u;
576 uint32_t dex2pc_dalvik_offset = 0u;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700577 for (LIR* tgt_lir = first_lir_insn_; tgt_lir != NULL; tgt_lir = NEXT_LIR(tgt_lir)) {
578 if (!tgt_lir->flags.is_nop && (tgt_lir->opcode == kPseudoSafepointPC)) {
Vladimir Marko1e6cb632013-11-28 16:27:29 +0000579 pc2dex_entries += 1;
580 DCHECK(pc2dex_offset <= tgt_lir->offset);
581 pc2dex_data_size += UnsignedLeb128Size(tgt_lir->offset - pc2dex_offset);
582 pc2dex_data_size += SignedLeb128Size(static_cast<int32_t>(tgt_lir->dalvik_offset) -
583 static_cast<int32_t>(pc2dex_dalvik_offset));
584 pc2dex_offset = tgt_lir->offset;
585 pc2dex_dalvik_offset = tgt_lir->dalvik_offset;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700586 }
587 if (!tgt_lir->flags.is_nop && (tgt_lir->opcode == kPseudoExportedPC)) {
Vladimir Marko1e6cb632013-11-28 16:27:29 +0000588 dex2pc_entries += 1;
589 DCHECK(dex2pc_offset <= tgt_lir->offset);
590 dex2pc_data_size += UnsignedLeb128Size(tgt_lir->offset - dex2pc_offset);
591 dex2pc_data_size += SignedLeb128Size(static_cast<int32_t>(tgt_lir->dalvik_offset) -
592 static_cast<int32_t>(dex2pc_dalvik_offset));
593 dex2pc_offset = tgt_lir->offset;
594 dex2pc_dalvik_offset = tgt_lir->dalvik_offset;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700595 }
596 }
Vladimir Marko1e6cb632013-11-28 16:27:29 +0000597
598 uint32_t total_entries = pc2dex_entries + dex2pc_entries;
599 uint32_t hdr_data_size = UnsignedLeb128Size(total_entries) + UnsignedLeb128Size(pc2dex_entries);
600 uint32_t data_size = hdr_data_size + pc2dex_data_size + dex2pc_data_size;
Vladimir Marko06606b92013-12-02 15:31:08 +0000601 encoded_mapping_table_.resize(data_size);
602 uint8_t* write_pos = &encoded_mapping_table_[0];
603 write_pos = EncodeUnsignedLeb128(write_pos, total_entries);
604 write_pos = EncodeUnsignedLeb128(write_pos, pc2dex_entries);
605 DCHECK_EQ(static_cast<size_t>(write_pos - &encoded_mapping_table_[0]), hdr_data_size);
606 uint8_t* write_pos2 = write_pos + pc2dex_data_size;
Vladimir Marko1e6cb632013-11-28 16:27:29 +0000607
Vladimir Marko1e6cb632013-11-28 16:27:29 +0000608 pc2dex_offset = 0u;
609 pc2dex_dalvik_offset = 0u;
Vladimir Marko06606b92013-12-02 15:31:08 +0000610 dex2pc_offset = 0u;
611 dex2pc_dalvik_offset = 0u;
612 for (LIR* tgt_lir = first_lir_insn_; tgt_lir != NULL; tgt_lir = NEXT_LIR(tgt_lir)) {
613 if (!tgt_lir->flags.is_nop && (tgt_lir->opcode == kPseudoSafepointPC)) {
614 DCHECK(pc2dex_offset <= tgt_lir->offset);
615 write_pos = EncodeUnsignedLeb128(write_pos, tgt_lir->offset - pc2dex_offset);
616 write_pos = EncodeSignedLeb128(write_pos, static_cast<int32_t>(tgt_lir->dalvik_offset) -
617 static_cast<int32_t>(pc2dex_dalvik_offset));
618 pc2dex_offset = tgt_lir->offset;
619 pc2dex_dalvik_offset = tgt_lir->dalvik_offset;
620 }
621 if (!tgt_lir->flags.is_nop && (tgt_lir->opcode == kPseudoExportedPC)) {
622 DCHECK(dex2pc_offset <= tgt_lir->offset);
623 write_pos2 = EncodeUnsignedLeb128(write_pos2, tgt_lir->offset - dex2pc_offset);
624 write_pos2 = EncodeSignedLeb128(write_pos2, static_cast<int32_t>(tgt_lir->dalvik_offset) -
625 static_cast<int32_t>(dex2pc_dalvik_offset));
626 dex2pc_offset = tgt_lir->offset;
627 dex2pc_dalvik_offset = tgt_lir->dalvik_offset;
628 }
Vladimir Marko1e6cb632013-11-28 16:27:29 +0000629 }
Vladimir Marko06606b92013-12-02 15:31:08 +0000630 DCHECK_EQ(static_cast<size_t>(write_pos - &encoded_mapping_table_[0]),
631 hdr_data_size + pc2dex_data_size);
632 DCHECK_EQ(static_cast<size_t>(write_pos2 - &encoded_mapping_table_[0]), data_size);
Vladimir Marko1e6cb632013-11-28 16:27:29 +0000633
Ian Rogers96faf5b2013-08-09 22:05:32 -0700634 if (kIsDebugBuild) {
Vladimir Marko06606b92013-12-02 15:31:08 +0000635 CHECK(VerifyCatchEntries());
636
Ian Rogers96faf5b2013-08-09 22:05:32 -0700637 // Verify the encoded table holds the expected data.
Vladimir Marko06606b92013-12-02 15:31:08 +0000638 MappingTable table(&encoded_mapping_table_[0]);
Ian Rogers96faf5b2013-08-09 22:05:32 -0700639 CHECK_EQ(table.TotalSize(), total_entries);
640 CHECK_EQ(table.PcToDexSize(), pc2dex_entries);
Vladimir Marko1e6cb632013-11-28 16:27:29 +0000641 auto it = table.PcToDexBegin();
Vladimir Marko06606b92013-12-02 15:31:08 +0000642 auto it2 = table.DexToPcBegin();
643 for (LIR* tgt_lir = first_lir_insn_; tgt_lir != NULL; tgt_lir = NEXT_LIR(tgt_lir)) {
644 if (!tgt_lir->flags.is_nop && (tgt_lir->opcode == kPseudoSafepointPC)) {
645 CHECK_EQ(tgt_lir->offset, it.NativePcOffset());
646 CHECK_EQ(tgt_lir->dalvik_offset, it.DexPc());
647 ++it;
648 }
649 if (!tgt_lir->flags.is_nop && (tgt_lir->opcode == kPseudoExportedPC)) {
650 CHECK_EQ(tgt_lir->offset, it2.NativePcOffset());
651 CHECK_EQ(tgt_lir->dalvik_offset, it2.DexPc());
652 ++it2;
653 }
Ian Rogers96faf5b2013-08-09 22:05:32 -0700654 }
Vladimir Marko1e6cb632013-11-28 16:27:29 +0000655 CHECK(it == table.PcToDexEnd());
Vladimir Marko1e6cb632013-11-28 16:27:29 +0000656 CHECK(it2 == table.DexToPcEnd());
Ian Rogers96faf5b2013-08-09 22:05:32 -0700657 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700658}
659
660class NativePcToReferenceMapBuilder {
661 public:
662 NativePcToReferenceMapBuilder(std::vector<uint8_t>* table,
663 size_t entries, uint32_t max_native_offset,
664 size_t references_width) : entries_(entries),
665 references_width_(references_width), in_use_(entries),
666 table_(table) {
667 // Compute width in bytes needed to hold max_native_offset.
668 native_offset_width_ = 0;
669 while (max_native_offset != 0) {
670 native_offset_width_++;
671 max_native_offset >>= 8;
672 }
673 // Resize table and set up header.
674 table->resize((EntryWidth() * entries) + sizeof(uint32_t));
675 CHECK_LT(native_offset_width_, 1U << 3);
676 (*table)[0] = native_offset_width_ & 7;
677 CHECK_LT(references_width_, 1U << 13);
678 (*table)[0] |= (references_width_ << 3) & 0xFF;
679 (*table)[1] = (references_width_ >> 5) & 0xFF;
680 CHECK_LT(entries, 1U << 16);
681 (*table)[2] = entries & 0xFF;
682 (*table)[3] = (entries >> 8) & 0xFF;
683 }
684
685 void AddEntry(uint32_t native_offset, const uint8_t* references) {
686 size_t table_index = TableIndex(native_offset);
687 while (in_use_[table_index]) {
688 table_index = (table_index + 1) % entries_;
689 }
690 in_use_[table_index] = true;
buzbee0d829482013-10-11 15:24:55 -0700691 SetCodeOffset(table_index, native_offset);
692 DCHECK_EQ(native_offset, GetCodeOffset(table_index));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700693 SetReferences(table_index, references);
694 }
695
696 private:
697 size_t TableIndex(uint32_t native_offset) {
698 return NativePcOffsetToReferenceMap::Hash(native_offset) % entries_;
699 }
700
buzbee0d829482013-10-11 15:24:55 -0700701 uint32_t GetCodeOffset(size_t table_index) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700702 uint32_t native_offset = 0;
703 size_t table_offset = (table_index * EntryWidth()) + sizeof(uint32_t);
704 for (size_t i = 0; i < native_offset_width_; i++) {
705 native_offset |= (*table_)[table_offset + i] << (i * 8);
706 }
707 return native_offset;
708 }
709
buzbee0d829482013-10-11 15:24:55 -0700710 void SetCodeOffset(size_t table_index, uint32_t native_offset) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700711 size_t table_offset = (table_index * EntryWidth()) + sizeof(uint32_t);
712 for (size_t i = 0; i < native_offset_width_; i++) {
713 (*table_)[table_offset + i] = (native_offset >> (i * 8)) & 0xFF;
714 }
715 }
716
717 void SetReferences(size_t table_index, const uint8_t* references) {
718 size_t table_offset = (table_index * EntryWidth()) + sizeof(uint32_t);
719 memcpy(&(*table_)[table_offset + native_offset_width_], references, references_width_);
720 }
721
722 size_t EntryWidth() const {
723 return native_offset_width_ + references_width_;
724 }
725
726 // Number of entries in the table.
727 const size_t entries_;
728 // Number of bytes used to encode the reference bitmap.
729 const size_t references_width_;
730 // Number of bytes used to encode a native offset.
731 size_t native_offset_width_;
732 // Entries that are in use.
733 std::vector<bool> in_use_;
734 // The table we're building.
735 std::vector<uint8_t>* const table_;
736};
737
738void Mir2Lir::CreateNativeGcMap() {
Vladimir Marko06606b92013-12-02 15:31:08 +0000739 DCHECK(!encoded_mapping_table_.empty());
740 MappingTable mapping_table(&encoded_mapping_table_[0]);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700741 uint32_t max_native_offset = 0;
Vladimir Marko06606b92013-12-02 15:31:08 +0000742 for (auto it = mapping_table.PcToDexBegin(), end = mapping_table.PcToDexEnd(); it != end; ++it) {
743 uint32_t native_offset = it.NativePcOffset();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700744 if (native_offset > max_native_offset) {
745 max_native_offset = native_offset;
746 }
747 }
748 MethodReference method_ref(cu_->dex_file, cu_->method_idx);
749 const std::vector<uint8_t>* gc_map_raw = verifier::MethodVerifier::GetDexGcMap(method_ref);
Vladimir Marko8171fc32013-11-26 17:05:58 +0000750 verifier::DexPcToReferenceMap dex_gc_map(&(*gc_map_raw)[0]);
751 DCHECK_EQ(gc_map_raw->size(), dex_gc_map.RawSize());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700752 // Compute native offset to references size.
753 NativePcToReferenceMapBuilder native_gc_map_builder(&native_gc_map_,
Vladimir Marko06606b92013-12-02 15:31:08 +0000754 mapping_table.PcToDexSize(),
755 max_native_offset, dex_gc_map.RegWidth());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700756
Vladimir Marko06606b92013-12-02 15:31:08 +0000757 for (auto it = mapping_table.PcToDexBegin(), end = mapping_table.PcToDexEnd(); it != end; ++it) {
758 uint32_t native_offset = it.NativePcOffset();
759 uint32_t dex_pc = it.DexPc();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700760 const uint8_t* references = dex_gc_map.FindBitMap(dex_pc, false);
761 CHECK(references != NULL) << "Missing ref for dex pc 0x" << std::hex << dex_pc;
762 native_gc_map_builder.AddEntry(native_offset, references);
763 }
764}
765
766/* Determine the offset of each literal field */
buzbee0d829482013-10-11 15:24:55 -0700767int Mir2Lir::AssignLiteralOffset(CodeOffset offset) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700768 offset = AssignLiteralOffsetCommon(literal_list_, offset);
buzbee0d829482013-10-11 15:24:55 -0700769 offset = AssignLiteralPointerOffsetCommon(code_literal_list_, offset);
770 offset = AssignLiteralPointerOffsetCommon(method_literal_list_, offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700771 return offset;
772}
773
buzbee0d829482013-10-11 15:24:55 -0700774int Mir2Lir::AssignSwitchTablesOffset(CodeOffset offset) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700775 GrowableArray<SwitchTable*>::Iterator iterator(&switch_tables_);
776 while (true) {
buzbee0d829482013-10-11 15:24:55 -0700777 Mir2Lir::SwitchTable* tab_rec = iterator.Next();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700778 if (tab_rec == NULL) break;
779 tab_rec->offset = offset;
780 if (tab_rec->table[0] == Instruction::kSparseSwitchSignature) {
781 offset += tab_rec->table[1] * (sizeof(int) * 2);
782 } else {
783 DCHECK_EQ(static_cast<int>(tab_rec->table[0]),
784 static_cast<int>(Instruction::kPackedSwitchSignature));
785 offset += tab_rec->table[1] * sizeof(int);
786 }
787 }
788 return offset;
789}
790
buzbee0d829482013-10-11 15:24:55 -0700791int Mir2Lir::AssignFillArrayDataOffset(CodeOffset offset) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700792 GrowableArray<FillArrayData*>::Iterator iterator(&fill_array_data_);
793 while (true) {
794 Mir2Lir::FillArrayData *tab_rec = iterator.Next();
795 if (tab_rec == NULL) break;
796 tab_rec->offset = offset;
797 offset += tab_rec->size;
798 // word align
799 offset = (offset + 3) & ~3;
800 }
801 return offset;
802}
803
Brian Carlstrom7940e442013-07-12 13:46:57 -0700804/*
805 * Insert a kPseudoCaseLabel at the beginning of the Dalvik
buzbeeb48819d2013-09-14 16:15:25 -0700806 * offset vaddr if pretty-printing, otherise use the standard block
807 * label. The selected label will be used to fix up the case
buzbee252254b2013-09-08 16:20:53 -0700808 * branch table during the assembly phase. All resource flags
809 * are set to prevent code motion. KeyVal is just there for debugging.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700810 */
buzbee0d829482013-10-11 15:24:55 -0700811LIR* Mir2Lir::InsertCaseLabel(DexOffset vaddr, int keyVal) {
buzbee252254b2013-09-08 16:20:53 -0700812 LIR* boundary_lir = &block_label_list_[mir_graph_->FindBlock(vaddr)->id];
buzbeeb48819d2013-09-14 16:15:25 -0700813 LIR* res = boundary_lir;
814 if (cu_->verbose) {
815 // Only pay the expense if we're pretty-printing.
816 LIR* new_label = static_cast<LIR*>(arena_->Alloc(sizeof(LIR), ArenaAllocator::kAllocLIR));
817 new_label->dalvik_offset = vaddr;
818 new_label->opcode = kPseudoCaseLabel;
819 new_label->operands[0] = keyVal;
820 new_label->flags.fixup = kFixupLabel;
821 DCHECK(!new_label->flags.use_def_invalid);
822 new_label->u.m.def_mask = ENCODE_ALL;
823 InsertLIRAfter(boundary_lir, new_label);
824 res = new_label;
825 }
826 return res;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700827}
828
buzbee0d829482013-10-11 15:24:55 -0700829void Mir2Lir::MarkPackedCaseLabels(Mir2Lir::SwitchTable* tab_rec) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700830 const uint16_t* table = tab_rec->table;
buzbee0d829482013-10-11 15:24:55 -0700831 DexOffset base_vaddr = tab_rec->vaddr;
832 const int32_t *targets = reinterpret_cast<const int32_t*>(&table[4]);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700833 int entries = table[1];
834 int low_key = s4FromSwitchData(&table[2]);
835 for (int i = 0; i < entries; i++) {
836 tab_rec->targets[i] = InsertCaseLabel(base_vaddr + targets[i], i + low_key);
837 }
838}
839
buzbee0d829482013-10-11 15:24:55 -0700840void Mir2Lir::MarkSparseCaseLabels(Mir2Lir::SwitchTable* tab_rec) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700841 const uint16_t* table = tab_rec->table;
buzbee0d829482013-10-11 15:24:55 -0700842 DexOffset base_vaddr = tab_rec->vaddr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700843 int entries = table[1];
buzbee0d829482013-10-11 15:24:55 -0700844 const int32_t* keys = reinterpret_cast<const int32_t*>(&table[2]);
845 const int32_t* targets = &keys[entries];
Brian Carlstrom7940e442013-07-12 13:46:57 -0700846 for (int i = 0; i < entries; i++) {
847 tab_rec->targets[i] = InsertCaseLabel(base_vaddr + targets[i], keys[i]);
848 }
849}
850
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700851void Mir2Lir::ProcessSwitchTables() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700852 GrowableArray<SwitchTable*>::Iterator iterator(&switch_tables_);
853 while (true) {
854 Mir2Lir::SwitchTable *tab_rec = iterator.Next();
855 if (tab_rec == NULL) break;
856 if (tab_rec->table[0] == Instruction::kPackedSwitchSignature) {
857 MarkPackedCaseLabels(tab_rec);
858 } else if (tab_rec->table[0] == Instruction::kSparseSwitchSignature) {
859 MarkSparseCaseLabels(tab_rec);
860 } else {
861 LOG(FATAL) << "Invalid switch table";
862 }
863 }
864}
865
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700866void Mir2Lir::DumpSparseSwitchTable(const uint16_t* table) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700867 /*
868 * Sparse switch data format:
869 * ushort ident = 0x0200 magic value
870 * ushort size number of entries in the table; > 0
871 * int keys[size] keys, sorted low-to-high; 32-bit aligned
872 * int targets[size] branch targets, relative to switch opcode
873 *
874 * Total size is (2+size*4) 16-bit code units.
875 */
Brian Carlstrom7940e442013-07-12 13:46:57 -0700876 uint16_t ident = table[0];
877 int entries = table[1];
buzbee0d829482013-10-11 15:24:55 -0700878 const int32_t* keys = reinterpret_cast<const int32_t*>(&table[2]);
879 const int32_t* targets = &keys[entries];
Brian Carlstrom7940e442013-07-12 13:46:57 -0700880 LOG(INFO) << "Sparse switch table - ident:0x" << std::hex << ident
881 << ", entries: " << std::dec << entries;
882 for (int i = 0; i < entries; i++) {
883 LOG(INFO) << " Key[" << keys[i] << "] -> 0x" << std::hex << targets[i];
884 }
885}
886
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700887void Mir2Lir::DumpPackedSwitchTable(const uint16_t* table) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700888 /*
889 * Packed switch data format:
890 * ushort ident = 0x0100 magic value
891 * ushort size number of entries in the table
892 * int first_key first (and lowest) switch case value
893 * int targets[size] branch targets, relative to switch opcode
894 *
895 * Total size is (4+size*2) 16-bit code units.
896 */
Brian Carlstrom7940e442013-07-12 13:46:57 -0700897 uint16_t ident = table[0];
buzbee0d829482013-10-11 15:24:55 -0700898 const int32_t* targets = reinterpret_cast<const int32_t*>(&table[4]);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700899 int entries = table[1];
900 int low_key = s4FromSwitchData(&table[2]);
901 LOG(INFO) << "Packed switch table - ident:0x" << std::hex << ident
902 << ", entries: " << std::dec << entries << ", low_key: " << low_key;
903 for (int i = 0; i < entries; i++) {
904 LOG(INFO) << " Key[" << (i + low_key) << "] -> 0x" << std::hex
905 << targets[i];
906 }
907}
908
buzbee252254b2013-09-08 16:20:53 -0700909/* Set up special LIR to mark a Dalvik byte-code instruction start for pretty printing */
buzbee0d829482013-10-11 15:24:55 -0700910void Mir2Lir::MarkBoundary(DexOffset offset, const char* inst_str) {
911 // NOTE: only used for debug listings.
912 NewLIR1(kPseudoDalvikByteCodeBoundary, WrapPointer(ArenaStrdup(inst_str)));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700913}
914
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700915bool Mir2Lir::EvaluateBranch(Instruction::Code opcode, int32_t src1, int32_t src2) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700916 bool is_taken;
917 switch (opcode) {
918 case Instruction::IF_EQ: is_taken = (src1 == src2); break;
919 case Instruction::IF_NE: is_taken = (src1 != src2); break;
920 case Instruction::IF_LT: is_taken = (src1 < src2); break;
921 case Instruction::IF_GE: is_taken = (src1 >= src2); break;
922 case Instruction::IF_GT: is_taken = (src1 > src2); break;
923 case Instruction::IF_LE: is_taken = (src1 <= src2); break;
924 case Instruction::IF_EQZ: is_taken = (src1 == 0); break;
925 case Instruction::IF_NEZ: is_taken = (src1 != 0); break;
926 case Instruction::IF_LTZ: is_taken = (src1 < 0); break;
927 case Instruction::IF_GEZ: is_taken = (src1 >= 0); break;
928 case Instruction::IF_GTZ: is_taken = (src1 > 0); break;
929 case Instruction::IF_LEZ: is_taken = (src1 <= 0); break;
930 default:
931 LOG(FATAL) << "Unexpected opcode " << opcode;
932 is_taken = false;
933 }
934 return is_taken;
935}
936
937// Convert relation of src1/src2 to src2/src1
938ConditionCode Mir2Lir::FlipComparisonOrder(ConditionCode before) {
939 ConditionCode res;
940 switch (before) {
941 case kCondEq: res = kCondEq; break;
942 case kCondNe: res = kCondNe; break;
943 case kCondLt: res = kCondGt; break;
944 case kCondGt: res = kCondLt; break;
945 case kCondLe: res = kCondGe; break;
946 case kCondGe: res = kCondLe; break;
947 default:
948 res = static_cast<ConditionCode>(0);
949 LOG(FATAL) << "Unexpected ccode " << before;
950 }
951 return res;
952}
953
954// TODO: move to mir_to_lir.cc
955Mir2Lir::Mir2Lir(CompilationUnit* cu, MIRGraph* mir_graph, ArenaAllocator* arena)
956 : Backend(arena),
957 literal_list_(NULL),
958 method_literal_list_(NULL),
959 code_literal_list_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700960 first_fixup_(NULL),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700961 cu_(cu),
962 mir_graph_(mir_graph),
963 switch_tables_(arena, 4, kGrowableArraySwitchTables),
964 fill_array_data_(arena, 4, kGrowableArrayFillArrayData),
965 throw_launchpads_(arena, 2048, kGrowableArrayThrowLaunchPads),
966 suspend_launchpads_(arena, 4, kGrowableArraySuspendLaunchPads),
967 intrinsic_launchpads_(arena, 2048, kGrowableArrayMisc),
buzbeebd663de2013-09-10 15:41:31 -0700968 tempreg_info_(arena, 20, kGrowableArrayMisc),
969 reginfo_map_(arena, 64, kGrowableArrayMisc),
buzbee0d829482013-10-11 15:24:55 -0700970 pointer_storage_(arena, 128, kGrowableArrayMisc),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700971 data_offset_(0),
972 total_size_(0),
973 block_label_list_(NULL),
974 current_dalvik_offset_(0),
buzbeeb48819d2013-09-14 16:15:25 -0700975 estimated_native_code_size_(0),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700976 reg_pool_(NULL),
977 live_sreg_(0),
978 num_core_spills_(0),
979 num_fp_spills_(0),
980 frame_size_(0),
981 core_spill_mask_(0),
982 fp_spill_mask_(0),
983 first_lir_insn_(NULL),
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000984 last_lir_insn_(NULL),
985 inliner_(nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700986 promotion_map_ = static_cast<PromotionMap*>
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700987 (arena_->Alloc((cu_->num_dalvik_registers + cu_->num_compiler_temps + 1) *
988 sizeof(promotion_map_[0]), ArenaAllocator::kAllocRegAlloc));
buzbee0d829482013-10-11 15:24:55 -0700989 // Reserve pointer id 0 for NULL.
990 size_t null_idx = WrapPointer(NULL);
991 DCHECK_EQ(null_idx, 0U);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700992}
993
994void Mir2Lir::Materialize() {
buzbeea61f4952013-08-23 14:27:06 -0700995 cu_->NewTimingSplit("RegisterAllocation");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700996 CompilerInitializeRegAlloc(); // Needs to happen after SSA naming
997
998 /* Allocate Registers using simple local allocation scheme */
999 SimpleRegAlloc();
1000
buzbee479f83c2013-07-19 10:58:21 -07001001 if (mir_graph_->IsSpecialCase()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001002 /*
1003 * Custom codegen for special cases. If for any reason the
1004 * special codegen doesn't succeed, first_lir_insn_ will
1005 * set to NULL;
1006 */
buzbeea61f4952013-08-23 14:27:06 -07001007 cu_->NewTimingSplit("SpecialMIR2LIR");
buzbee479f83c2013-07-19 10:58:21 -07001008 SpecialMIR2LIR(mir_graph_->GetSpecialCase());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001009 }
1010
1011 /* Convert MIR to LIR, etc. */
1012 if (first_lir_insn_ == NULL) {
1013 MethodMIR2LIR();
1014 }
1015
1016 /* Method is not empty */
1017 if (first_lir_insn_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001018 // mark the targets of switch statement case labels
1019 ProcessSwitchTables();
1020
1021 /* Convert LIR into machine code. */
1022 AssembleLIR();
1023
1024 if (cu_->verbose) {
1025 CodegenDump();
1026 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001027 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001028}
1029
1030CompiledMethod* Mir2Lir::GetCompiledMethod() {
1031 // Combine vmap tables - core regs, then fp regs - into vmap_table
Ian Rogers96faf5b2013-08-09 22:05:32 -07001032 std::vector<uint16_t> raw_vmap_table;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001033 // Core regs may have been inserted out of order - sort first
1034 std::sort(core_vmap_table_.begin(), core_vmap_table_.end());
Mathieu Chartier193bad92013-08-29 18:46:00 -07001035 for (size_t i = 0 ; i < core_vmap_table_.size(); ++i) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001036 // Copy, stripping out the phys register sort key
Ian Rogers96faf5b2013-08-09 22:05:32 -07001037 raw_vmap_table.push_back(~(-1 << VREG_NUM_WIDTH) & core_vmap_table_[i]);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001038 }
1039 // If we have a frame, push a marker to take place of lr
1040 if (frame_size_ > 0) {
Ian Rogers96faf5b2013-08-09 22:05:32 -07001041 raw_vmap_table.push_back(INVALID_VREG);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001042 } else {
1043 DCHECK_EQ(__builtin_popcount(core_spill_mask_), 0);
1044 DCHECK_EQ(__builtin_popcount(fp_spill_mask_), 0);
1045 }
1046 // Combine vmap tables - core regs, then fp regs. fp regs already sorted
1047 for (uint32_t i = 0; i < fp_vmap_table_.size(); i++) {
Ian Rogers96faf5b2013-08-09 22:05:32 -07001048 raw_vmap_table.push_back(fp_vmap_table_[i]);
1049 }
Vladimir Marko1e6cb632013-11-28 16:27:29 +00001050 Leb128EncodingVector vmap_encoder;
Ian Rogers96faf5b2013-08-09 22:05:32 -07001051 // Prefix the encoded data with its size.
Vladimir Marko1e6cb632013-11-28 16:27:29 +00001052 vmap_encoder.PushBackUnsigned(raw_vmap_table.size());
Mathieu Chartier193bad92013-08-29 18:46:00 -07001053 for (uint16_t cur : raw_vmap_table) {
Vladimir Marko1e6cb632013-11-28 16:27:29 +00001054 vmap_encoder.PushBackUnsigned(cur);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001055 }
1056 CompiledMethod* result =
Mathieu Chartier193bad92013-08-29 18:46:00 -07001057 new CompiledMethod(*cu_->compiler_driver, cu_->instruction_set, code_buffer_, frame_size_,
Vladimir Marko06606b92013-12-02 15:31:08 +00001058 core_spill_mask_, fp_spill_mask_, encoded_mapping_table_,
Mathieu Chartier193bad92013-08-29 18:46:00 -07001059 vmap_encoder.GetData(), native_gc_map_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001060 return result;
1061}
1062
1063int Mir2Lir::ComputeFrameSize() {
1064 /* Figure out the frame size */
1065 static const uint32_t kAlignMask = kStackAlignment - 1;
1066 uint32_t size = (num_core_spills_ + num_fp_spills_ +
1067 1 /* filler word */ + cu_->num_regs + cu_->num_outs +
1068 cu_->num_compiler_temps + 1 /* cur_method* */)
1069 * sizeof(uint32_t);
1070 /* Align and set */
1071 return (size + kAlignMask) & ~(kAlignMask);
1072}
1073
1074/*
1075 * Append an LIR instruction to the LIR list maintained by a compilation
1076 * unit
1077 */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001078void Mir2Lir::AppendLIR(LIR* lir) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001079 if (first_lir_insn_ == NULL) {
1080 DCHECK(last_lir_insn_ == NULL);
1081 last_lir_insn_ = first_lir_insn_ = lir;
1082 lir->prev = lir->next = NULL;
1083 } else {
1084 last_lir_insn_->next = lir;
1085 lir->prev = last_lir_insn_;
1086 lir->next = NULL;
1087 last_lir_insn_ = lir;
1088 }
1089}
1090
1091/*
1092 * Insert an LIR instruction before the current instruction, which cannot be the
1093 * first instruction.
1094 *
1095 * prev_lir <-> new_lir <-> current_lir
1096 */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001097void Mir2Lir::InsertLIRBefore(LIR* current_lir, LIR* new_lir) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001098 DCHECK(current_lir->prev != NULL);
1099 LIR *prev_lir = current_lir->prev;
1100
1101 prev_lir->next = new_lir;
1102 new_lir->prev = prev_lir;
1103 new_lir->next = current_lir;
1104 current_lir->prev = new_lir;
1105}
1106
1107/*
1108 * Insert an LIR instruction after the current instruction, which cannot be the
1109 * first instruction.
1110 *
1111 * current_lir -> new_lir -> old_next
1112 */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001113void Mir2Lir::InsertLIRAfter(LIR* current_lir, LIR* new_lir) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001114 new_lir->prev = current_lir;
1115 new_lir->next = current_lir->next;
1116 current_lir->next = new_lir;
1117 new_lir->next->prev = new_lir;
1118}
1119
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001120} // namespace art