blob: bae8ff339a05f91601dd2b00cdfb0fb1abd6d131 [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"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000022#include "dex/verified_methods_data.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070023#include "verifier/dex_gc_map.h"
24#include "verifier/method_verifier.h"
25
26namespace art {
27
Vladimir Marko06606b92013-12-02 15:31:08 +000028namespace {
29
30/* Dump a mapping table */
31template <typename It>
32void DumpMappingTable(const char* table_name, const char* descriptor, const char* name,
33 const Signature& signature, uint32_t size, It first) {
34 if (size != 0) {
35 std::string line(StringPrintf("\n %s %s%s_%s_table[%zu] = {", table_name,
36 descriptor, name, signature.ToString().c_str(), size));
37 std::replace(line.begin(), line.end(), ';', '_');
38 LOG(INFO) << line;
39 for (uint32_t i = 0; i != size; ++i) {
40 line = StringPrintf(" {0x%05x, 0x%04x},", first.NativePcOffset(), first.DexPc());
41 ++first;
42 LOG(INFO) << line;
43 }
44 LOG(INFO) <<" };\n\n";
45 }
46}
47
48} // anonymous namespace
49
Brian Carlstrom2ce745c2013-07-17 17:44:30 -070050bool Mir2Lir::IsInexpensiveConstant(RegLocation rl_src) {
Brian Carlstrom7940e442013-07-12 13:46:57 -070051 bool res = false;
52 if (rl_src.is_const) {
53 if (rl_src.wide) {
54 if (rl_src.fp) {
55 res = InexpensiveConstantDouble(mir_graph_->ConstantValueWide(rl_src));
56 } else {
57 res = InexpensiveConstantLong(mir_graph_->ConstantValueWide(rl_src));
58 }
59 } else {
60 if (rl_src.fp) {
61 res = InexpensiveConstantFloat(mir_graph_->ConstantValue(rl_src));
62 } else {
63 res = InexpensiveConstantInt(mir_graph_->ConstantValue(rl_src));
64 }
65 }
66 }
67 return res;
68}
69
Brian Carlstrom2ce745c2013-07-17 17:44:30 -070070void Mir2Lir::MarkSafepointPC(LIR* inst) {
buzbeeb48819d2013-09-14 16:15:25 -070071 DCHECK(!inst->flags.use_def_invalid);
72 inst->u.m.def_mask = ENCODE_ALL;
Brian Carlstrom7940e442013-07-12 13:46:57 -070073 LIR* safepoint_pc = NewLIR0(kPseudoSafepointPC);
buzbeeb48819d2013-09-14 16:15:25 -070074 DCHECK_EQ(safepoint_pc->u.m.def_mask, ENCODE_ALL);
Brian Carlstrom7940e442013-07-12 13:46:57 -070075}
76
Ian Rogers9b297bf2013-09-06 11:11:25 -070077bool Mir2Lir::FastInstance(uint32_t field_idx, bool is_put, int* field_offset, bool* is_volatile) {
Brian Carlstrom7940e442013-07-12 13:46:57 -070078 return cu_->compiler_driver->ComputeInstanceFieldInfo(
Ian Rogers9b297bf2013-09-06 11:11:25 -070079 field_idx, mir_graph_->GetCurrentDexCompilationUnit(), is_put, field_offset, is_volatile);
Brian Carlstrom7940e442013-07-12 13:46:57 -070080}
81
buzbee252254b2013-09-08 16:20:53 -070082/* Remove a LIR from the list. */
83void Mir2Lir::UnlinkLIR(LIR* lir) {
84 if (UNLIKELY(lir == first_lir_insn_)) {
85 first_lir_insn_ = lir->next;
86 if (lir->next != NULL) {
87 lir->next->prev = NULL;
88 } else {
89 DCHECK(lir->next == NULL);
90 DCHECK(lir == last_lir_insn_);
91 last_lir_insn_ = NULL;
92 }
93 } else if (lir == last_lir_insn_) {
94 last_lir_insn_ = lir->prev;
95 lir->prev->next = NULL;
96 } else if ((lir->prev != NULL) && (lir->next != NULL)) {
97 lir->prev->next = lir->next;
98 lir->next->prev = lir->prev;
99 }
100}
101
Brian Carlstrom7940e442013-07-12 13:46:57 -0700102/* Convert an instruction to a NOP */
Brian Carlstromdf629502013-07-17 22:39:56 -0700103void Mir2Lir::NopLIR(LIR* lir) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700104 lir->flags.is_nop = true;
buzbee252254b2013-09-08 16:20:53 -0700105 if (!cu_->verbose) {
106 UnlinkLIR(lir);
107 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700108}
109
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700110void Mir2Lir::SetMemRefType(LIR* lir, bool is_load, int mem_type) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700111 uint64_t *mask_ptr;
Brian Carlstromf69863b2013-07-17 21:53:13 -0700112 uint64_t mask = ENCODE_MEM;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700113 DCHECK(GetTargetInstFlags(lir->opcode) & (IS_LOAD | IS_STORE));
buzbeeb48819d2013-09-14 16:15:25 -0700114 DCHECK(!lir->flags.use_def_invalid);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700115 if (is_load) {
buzbeeb48819d2013-09-14 16:15:25 -0700116 mask_ptr = &lir->u.m.use_mask;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700117 } else {
buzbeeb48819d2013-09-14 16:15:25 -0700118 mask_ptr = &lir->u.m.def_mask;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700119 }
120 /* Clear out the memref flags */
121 *mask_ptr &= ~mask;
122 /* ..and then add back the one we need */
123 switch (mem_type) {
124 case kLiteral:
125 DCHECK(is_load);
126 *mask_ptr |= ENCODE_LITERAL;
127 break;
128 case kDalvikReg:
129 *mask_ptr |= ENCODE_DALVIK_REG;
130 break;
131 case kHeapRef:
132 *mask_ptr |= ENCODE_HEAP_REF;
133 break;
134 case kMustNotAlias:
135 /* Currently only loads can be marked as kMustNotAlias */
136 DCHECK(!(GetTargetInstFlags(lir->opcode) & IS_STORE));
137 *mask_ptr |= ENCODE_MUST_NOT_ALIAS;
138 break;
139 default:
140 LOG(FATAL) << "Oat: invalid memref kind - " << mem_type;
141 }
142}
143
144/*
145 * Mark load/store instructions that access Dalvik registers through the stack.
146 */
147void Mir2Lir::AnnotateDalvikRegAccess(LIR* lir, int reg_id, bool is_load,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700148 bool is64bit) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700149 SetMemRefType(lir, is_load, kDalvikReg);
150
151 /*
152 * Store the Dalvik register id in alias_info. Mark the MSB if it is a 64-bit
153 * access.
154 */
buzbeeb48819d2013-09-14 16:15:25 -0700155 lir->flags.alias_info = ENCODE_ALIAS_INFO(reg_id, is64bit);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700156}
157
158/*
159 * Debugging macros
160 */
161#define DUMP_RESOURCE_MASK(X)
162
163/* Pretty-print a LIR instruction */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700164void Mir2Lir::DumpLIRInsn(LIR* lir, unsigned char* base_addr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700165 int offset = lir->offset;
166 int dest = lir->operands[0];
167 const bool dump_nop = (cu_->enable_debug & (1 << kDebugShowNops));
168
169 /* Handle pseudo-ops individually, and all regular insns as a group */
170 switch (lir->opcode) {
171 case kPseudoMethodEntry:
172 LOG(INFO) << "-------- method entry "
173 << PrettyMethod(cu_->method_idx, *cu_->dex_file);
174 break;
175 case kPseudoMethodExit:
176 LOG(INFO) << "-------- Method_Exit";
177 break;
178 case kPseudoBarrier:
179 LOG(INFO) << "-------- BARRIER";
180 break;
181 case kPseudoEntryBlock:
182 LOG(INFO) << "-------- entry offset: 0x" << std::hex << dest;
183 break;
184 case kPseudoDalvikByteCodeBoundary:
185 if (lir->operands[0] == 0) {
buzbee0d829482013-10-11 15:24:55 -0700186 // NOTE: only used for debug listings.
187 lir->operands[0] = WrapPointer(ArenaStrdup("No instruction string"));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700188 }
189 LOG(INFO) << "-------- dalvik offset: 0x" << std::hex
Bill Buzbee0b1191c2013-10-28 22:11:59 +0000190 << lir->dalvik_offset << " @ "
191 << reinterpret_cast<char*>(UnwrapPointer(lir->operands[0]));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700192 break;
193 case kPseudoExitBlock:
194 LOG(INFO) << "-------- exit offset: 0x" << std::hex << dest;
195 break;
196 case kPseudoPseudoAlign4:
197 LOG(INFO) << reinterpret_cast<uintptr_t>(base_addr) + offset << " (0x" << std::hex
198 << offset << "): .align4";
199 break;
200 case kPseudoEHBlockLabel:
201 LOG(INFO) << "Exception_Handling:";
202 break;
203 case kPseudoTargetLabel:
204 case kPseudoNormalBlockLabel:
205 LOG(INFO) << "L" << reinterpret_cast<void*>(lir) << ":";
206 break;
207 case kPseudoThrowTarget:
208 LOG(INFO) << "LT" << reinterpret_cast<void*>(lir) << ":";
209 break;
210 case kPseudoIntrinsicRetry:
211 LOG(INFO) << "IR" << reinterpret_cast<void*>(lir) << ":";
212 break;
213 case kPseudoSuspendTarget:
214 LOG(INFO) << "LS" << reinterpret_cast<void*>(lir) << ":";
215 break;
216 case kPseudoSafepointPC:
217 LOG(INFO) << "LsafepointPC_0x" << std::hex << lir->offset << "_" << lir->dalvik_offset << ":";
218 break;
219 case kPseudoExportedPC:
220 LOG(INFO) << "LexportedPC_0x" << std::hex << lir->offset << "_" << lir->dalvik_offset << ":";
221 break;
222 case kPseudoCaseLabel:
223 LOG(INFO) << "LC" << reinterpret_cast<void*>(lir) << ": Case target 0x"
224 << std::hex << lir->operands[0] << "|" << std::dec <<
225 lir->operands[0];
226 break;
227 default:
228 if (lir->flags.is_nop && !dump_nop) {
229 break;
230 } else {
231 std::string op_name(BuildInsnString(GetTargetInstName(lir->opcode),
232 lir, base_addr));
233 std::string op_operands(BuildInsnString(GetTargetInstFmt(lir->opcode),
234 lir, base_addr));
235 LOG(INFO) << StringPrintf("%05x: %-9s%s%s",
236 reinterpret_cast<unsigned int>(base_addr + offset),
237 op_name.c_str(), op_operands.c_str(),
238 lir->flags.is_nop ? "(nop)" : "");
239 }
240 break;
241 }
242
buzbeeb48819d2013-09-14 16:15:25 -0700243 if (lir->u.m.use_mask && (!lir->flags.is_nop || dump_nop)) {
244 DUMP_RESOURCE_MASK(DumpResourceMask(lir, lir->u.m.use_mask, "use"));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700245 }
buzbeeb48819d2013-09-14 16:15:25 -0700246 if (lir->u.m.def_mask && (!lir->flags.is_nop || dump_nop)) {
247 DUMP_RESOURCE_MASK(DumpResourceMask(lir, lir->u.m.def_mask, "def"));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700248 }
249}
250
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700251void Mir2Lir::DumpPromotionMap() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700252 int num_regs = cu_->num_dalvik_registers + cu_->num_compiler_temps + 1;
253 for (int i = 0; i < num_regs; i++) {
254 PromotionMap v_reg_map = promotion_map_[i];
255 std::string buf;
256 if (v_reg_map.fp_location == kLocPhysReg) {
257 StringAppendF(&buf, " : s%d", v_reg_map.FpReg & FpRegMask());
258 }
259
260 std::string buf3;
261 if (i < cu_->num_dalvik_registers) {
262 StringAppendF(&buf3, "%02d", i);
263 } else if (i == mir_graph_->GetMethodSReg()) {
264 buf3 = "Method*";
265 } else {
266 StringAppendF(&buf3, "ct%d", i - cu_->num_dalvik_registers);
267 }
268
269 LOG(INFO) << StringPrintf("V[%s] -> %s%d%s", buf3.c_str(),
270 v_reg_map.core_location == kLocPhysReg ?
271 "r" : "SP+", v_reg_map.core_location == kLocPhysReg ?
272 v_reg_map.core_reg : SRegOffset(i),
273 buf.c_str());
274 }
275}
276
Brian Carlstrom7940e442013-07-12 13:46:57 -0700277/* Dump instructions and constant pool contents */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700278void Mir2Lir::CodegenDump() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700279 LOG(INFO) << "Dumping LIR insns for "
280 << PrettyMethod(cu_->method_idx, *cu_->dex_file);
281 LIR* lir_insn;
282 int insns_size = cu_->code_item->insns_size_in_code_units_;
283
284 LOG(INFO) << "Regs (excluding ins) : " << cu_->num_regs;
285 LOG(INFO) << "Ins : " << cu_->num_ins;
286 LOG(INFO) << "Outs : " << cu_->num_outs;
287 LOG(INFO) << "CoreSpills : " << num_core_spills_;
288 LOG(INFO) << "FPSpills : " << num_fp_spills_;
289 LOG(INFO) << "CompilerTemps : " << cu_->num_compiler_temps;
290 LOG(INFO) << "Frame size : " << frame_size_;
291 LOG(INFO) << "code size is " << total_size_ <<
292 " bytes, Dalvik size is " << insns_size * 2;
293 LOG(INFO) << "expansion factor: "
294 << static_cast<float>(total_size_) / static_cast<float>(insns_size * 2);
295 DumpPromotionMap();
296 for (lir_insn = first_lir_insn_; lir_insn != NULL; lir_insn = lir_insn->next) {
297 DumpLIRInsn(lir_insn, 0);
298 }
299 for (lir_insn = literal_list_; lir_insn != NULL; lir_insn = lir_insn->next) {
300 LOG(INFO) << StringPrintf("%x (%04x): .word (%#x)", lir_insn->offset, lir_insn->offset,
301 lir_insn->operands[0]);
302 }
303
304 const DexFile::MethodId& method_id =
305 cu_->dex_file->GetMethodId(cu_->method_idx);
Ian Rogersd91d6d62013-09-25 20:26:14 -0700306 const Signature signature = cu_->dex_file->GetMethodSignature(method_id);
307 const char* name = cu_->dex_file->GetMethodName(method_id);
308 const char* descriptor(cu_->dex_file->GetMethodDeclaringClassDescriptor(method_id));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700309
310 // Dump mapping tables
Vladimir Marko06606b92013-12-02 15:31:08 +0000311 if (!encoded_mapping_table_.empty()) {
312 MappingTable table(&encoded_mapping_table_[0]);
313 DumpMappingTable("PC2Dex_MappingTable", descriptor, name, signature,
314 table.PcToDexSize(), table.PcToDexBegin());
315 DumpMappingTable("Dex2PC_MappingTable", descriptor, name, signature,
316 table.DexToPcSize(), table.DexToPcBegin());
317 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700318}
319
320/*
321 * Search the existing constants in the literal pool for an exact or close match
322 * within specified delta (greater or equal to 0).
323 */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700324LIR* Mir2Lir::ScanLiteralPool(LIR* data_target, int value, unsigned int delta) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700325 while (data_target) {
326 if ((static_cast<unsigned>(value - data_target->operands[0])) <= delta)
327 return data_target;
328 data_target = data_target->next;
329 }
330 return NULL;
331}
332
333/* Search the existing constants in the literal pool for an exact wide match */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700334LIR* Mir2Lir::ScanLiteralPoolWide(LIR* data_target, int val_lo, int val_hi) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700335 bool lo_match = false;
336 LIR* lo_target = NULL;
337 while (data_target) {
338 if (lo_match && (data_target->operands[0] == val_hi)) {
339 // Record high word in case we need to expand this later.
340 lo_target->operands[1] = val_hi;
341 return lo_target;
342 }
343 lo_match = false;
344 if (data_target->operands[0] == val_lo) {
345 lo_match = true;
346 lo_target = data_target;
347 }
348 data_target = data_target->next;
349 }
350 return NULL;
351}
352
353/*
354 * The following are building blocks to insert constants into the pool or
355 * instruction streams.
356 */
357
358/* Add a 32-bit constant to the constant pool */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700359LIR* Mir2Lir::AddWordData(LIR* *constant_list_p, int value) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700360 /* Add the constant to the literal pool */
361 if (constant_list_p) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700362 LIR* new_value = static_cast<LIR*>(arena_->Alloc(sizeof(LIR), ArenaAllocator::kAllocData));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700363 new_value->operands[0] = value;
364 new_value->next = *constant_list_p;
365 *constant_list_p = new_value;
buzbeeb48819d2013-09-14 16:15:25 -0700366 estimated_native_code_size_ += sizeof(value);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700367 return new_value;
368 }
369 return NULL;
370}
371
372/* Add a 64-bit constant to the constant pool or mixed with code */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700373LIR* Mir2Lir::AddWideData(LIR* *constant_list_p, int val_lo, int val_hi) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700374 AddWordData(constant_list_p, val_hi);
375 return AddWordData(constant_list_p, val_lo);
376}
377
378static void PushWord(std::vector<uint8_t>&buf, int data) {
Brian Carlstromdf629502013-07-17 22:39:56 -0700379 buf.push_back(data & 0xff);
380 buf.push_back((data >> 8) & 0xff);
381 buf.push_back((data >> 16) & 0xff);
382 buf.push_back((data >> 24) & 0xff);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700383}
384
buzbee0d829482013-10-11 15:24:55 -0700385// Push 8 bytes on 64-bit systems; 4 on 32-bit systems.
386static void PushPointer(std::vector<uint8_t>&buf, void const* pointer) {
387 uintptr_t data = reinterpret_cast<uintptr_t>(pointer);
388 if (sizeof(void*) == sizeof(uint64_t)) {
389 PushWord(buf, (data >> (sizeof(void*) * 4)) & 0xFFFFFFFF);
390 PushWord(buf, data & 0xFFFFFFFF);
391 } else {
392 PushWord(buf, data);
393 }
394}
395
Brian Carlstrom7940e442013-07-12 13:46:57 -0700396static void AlignBuffer(std::vector<uint8_t>&buf, size_t offset) {
397 while (buf.size() < offset) {
398 buf.push_back(0);
399 }
400}
401
402/* Write the literal pool to the output stream */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700403void Mir2Lir::InstallLiteralPools() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700404 AlignBuffer(code_buffer_, data_offset_);
405 LIR* data_lir = literal_list_;
406 while (data_lir != NULL) {
407 PushWord(code_buffer_, data_lir->operands[0]);
408 data_lir = NEXT_LIR(data_lir);
409 }
410 // Push code and method literals, record offsets for the compiler to patch.
411 data_lir = code_literal_list_;
412 while (data_lir != NULL) {
413 uint32_t target = data_lir->operands[0];
414 cu_->compiler_driver->AddCodePatch(cu_->dex_file,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700415 cu_->class_def_idx,
416 cu_->method_idx,
417 cu_->invoke_type,
418 target,
419 static_cast<InvokeType>(data_lir->operands[1]),
420 code_buffer_.size());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700421 const DexFile::MethodId& id = cu_->dex_file->GetMethodId(target);
buzbee0d829482013-10-11 15:24:55 -0700422 // unique value based on target to ensure code deduplication works
423 PushPointer(code_buffer_, &id);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700424 data_lir = NEXT_LIR(data_lir);
425 }
426 data_lir = method_literal_list_;
427 while (data_lir != NULL) {
428 uint32_t target = data_lir->operands[0];
429 cu_->compiler_driver->AddMethodPatch(cu_->dex_file,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700430 cu_->class_def_idx,
431 cu_->method_idx,
432 cu_->invoke_type,
433 target,
434 static_cast<InvokeType>(data_lir->operands[1]),
435 code_buffer_.size());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700436 const DexFile::MethodId& id = cu_->dex_file->GetMethodId(target);
buzbee0d829482013-10-11 15:24:55 -0700437 // unique value based on target to ensure code deduplication works
438 PushPointer(code_buffer_, &id);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700439 data_lir = NEXT_LIR(data_lir);
440 }
441}
442
443/* Write the switch tables to the output stream */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700444void Mir2Lir::InstallSwitchTables() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700445 GrowableArray<SwitchTable*>::Iterator iterator(&switch_tables_);
446 while (true) {
447 Mir2Lir::SwitchTable* tab_rec = iterator.Next();
448 if (tab_rec == NULL) break;
449 AlignBuffer(code_buffer_, tab_rec->offset);
450 /*
451 * For Arm, our reference point is the address of the bx
452 * instruction that does the launch, so we have to subtract
453 * the auto pc-advance. For other targets the reference point
454 * is a label, so we can use the offset as-is.
455 */
456 int bx_offset = INVALID_OFFSET;
457 switch (cu_->instruction_set) {
458 case kThumb2:
buzbeeb48819d2013-09-14 16:15:25 -0700459 DCHECK(tab_rec->anchor->flags.fixup != kFixupNone);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700460 bx_offset = tab_rec->anchor->offset + 4;
461 break;
462 case kX86:
463 bx_offset = 0;
464 break;
465 case kMips:
466 bx_offset = tab_rec->anchor->offset;
467 break;
468 default: LOG(FATAL) << "Unexpected instruction set: " << cu_->instruction_set;
469 }
470 if (cu_->verbose) {
471 LOG(INFO) << "Switch table for offset 0x" << std::hex << bx_offset;
472 }
473 if (tab_rec->table[0] == Instruction::kSparseSwitchSignature) {
buzbee0d829482013-10-11 15:24:55 -0700474 const int32_t* keys = reinterpret_cast<const int32_t*>(&(tab_rec->table[2]));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700475 for (int elems = 0; elems < tab_rec->table[1]; elems++) {
476 int disp = tab_rec->targets[elems]->offset - bx_offset;
477 if (cu_->verbose) {
478 LOG(INFO) << " Case[" << elems << "] key: 0x"
479 << std::hex << keys[elems] << ", disp: 0x"
480 << std::hex << disp;
481 }
482 PushWord(code_buffer_, keys[elems]);
483 PushWord(code_buffer_,
484 tab_rec->targets[elems]->offset - bx_offset);
485 }
486 } else {
487 DCHECK_EQ(static_cast<int>(tab_rec->table[0]),
488 static_cast<int>(Instruction::kPackedSwitchSignature));
489 for (int elems = 0; elems < tab_rec->table[1]; elems++) {
490 int disp = tab_rec->targets[elems]->offset - bx_offset;
491 if (cu_->verbose) {
492 LOG(INFO) << " Case[" << elems << "] disp: 0x"
493 << std::hex << disp;
494 }
495 PushWord(code_buffer_, tab_rec->targets[elems]->offset - bx_offset);
496 }
497 }
498 }
499}
500
501/* Write the fill array dta to the output stream */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700502void Mir2Lir::InstallFillArrayData() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700503 GrowableArray<FillArrayData*>::Iterator iterator(&fill_array_data_);
504 while (true) {
505 Mir2Lir::FillArrayData *tab_rec = iterator.Next();
506 if (tab_rec == NULL) break;
507 AlignBuffer(code_buffer_, tab_rec->offset);
508 for (int i = 0; i < (tab_rec->size + 1) / 2; i++) {
Brian Carlstromdf629502013-07-17 22:39:56 -0700509 code_buffer_.push_back(tab_rec->table[i] & 0xFF);
510 code_buffer_.push_back((tab_rec->table[i] >> 8) & 0xFF);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700511 }
512 }
513}
514
buzbee0d829482013-10-11 15:24:55 -0700515static int AssignLiteralOffsetCommon(LIR* lir, CodeOffset offset) {
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700516 for (; lir != NULL; lir = lir->next) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700517 lir->offset = offset;
518 offset += 4;
519 }
520 return offset;
521}
522
buzbee0d829482013-10-11 15:24:55 -0700523static int AssignLiteralPointerOffsetCommon(LIR* lir, CodeOffset offset) {
524 unsigned int element_size = sizeof(void*);
525 // Align to natural pointer size.
526 offset = (offset + (element_size - 1)) & ~(element_size - 1);
527 for (; lir != NULL; lir = lir->next) {
528 lir->offset = offset;
529 offset += element_size;
530 }
531 return offset;
532}
533
Brian Carlstrom7940e442013-07-12 13:46:57 -0700534// Make sure we have a code address for every declared catch entry
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700535bool Mir2Lir::VerifyCatchEntries() {
Vladimir Marko06606b92013-12-02 15:31:08 +0000536 MappingTable table(&encoded_mapping_table_[0]);
537 std::vector<uint32_t> dex_pcs;
538 dex_pcs.reserve(table.DexToPcSize());
539 for (auto it = table.DexToPcBegin(), end = table.DexToPcEnd(); it != end; ++it) {
540 dex_pcs.push_back(it.DexPc());
541 }
542 // Sort dex_pcs, so that we can quickly check it against the ordered mir_graph_->catches_.
543 std::sort(dex_pcs.begin(), dex_pcs.end());
544
Brian Carlstrom7940e442013-07-12 13:46:57 -0700545 bool success = true;
Vladimir Marko06606b92013-12-02 15:31:08 +0000546 auto it = dex_pcs.begin(), end = dex_pcs.end();
547 for (uint32_t dex_pc : mir_graph_->catches_) {
548 while (it != end && *it < dex_pc) {
549 LOG(INFO) << "Unexpected catch entry @ dex pc 0x" << std::hex << *it;
550 ++it;
551 success = false;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700552 }
Vladimir Marko06606b92013-12-02 15:31:08 +0000553 if (it == end || *it > dex_pc) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700554 LOG(INFO) << "Missing native PC for catch entry @ 0x" << std::hex << dex_pc;
555 success = false;
Vladimir Marko06606b92013-12-02 15:31:08 +0000556 } else {
557 ++it;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700558 }
559 }
560 if (!success) {
561 LOG(INFO) << "Bad dex2pcMapping table in " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
562 LOG(INFO) << "Entries @ decode: " << mir_graph_->catches_.size() << ", Entries in table: "
Vladimir Marko06606b92013-12-02 15:31:08 +0000563 << table.DexToPcSize();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700564 }
565 return success;
566}
567
568
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700569void Mir2Lir::CreateMappingTables() {
Vladimir Marko1e6cb632013-11-28 16:27:29 +0000570 uint32_t pc2dex_data_size = 0u;
571 uint32_t pc2dex_entries = 0u;
572 uint32_t pc2dex_offset = 0u;
573 uint32_t pc2dex_dalvik_offset = 0u;
574 uint32_t dex2pc_data_size = 0u;
575 uint32_t dex2pc_entries = 0u;
576 uint32_t dex2pc_offset = 0u;
577 uint32_t dex2pc_dalvik_offset = 0u;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700578 for (LIR* tgt_lir = first_lir_insn_; tgt_lir != NULL; tgt_lir = NEXT_LIR(tgt_lir)) {
579 if (!tgt_lir->flags.is_nop && (tgt_lir->opcode == kPseudoSafepointPC)) {
Vladimir Marko1e6cb632013-11-28 16:27:29 +0000580 pc2dex_entries += 1;
581 DCHECK(pc2dex_offset <= tgt_lir->offset);
582 pc2dex_data_size += UnsignedLeb128Size(tgt_lir->offset - pc2dex_offset);
583 pc2dex_data_size += SignedLeb128Size(static_cast<int32_t>(tgt_lir->dalvik_offset) -
584 static_cast<int32_t>(pc2dex_dalvik_offset));
585 pc2dex_offset = tgt_lir->offset;
586 pc2dex_dalvik_offset = tgt_lir->dalvik_offset;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700587 }
588 if (!tgt_lir->flags.is_nop && (tgt_lir->opcode == kPseudoExportedPC)) {
Vladimir Marko1e6cb632013-11-28 16:27:29 +0000589 dex2pc_entries += 1;
590 DCHECK(dex2pc_offset <= tgt_lir->offset);
591 dex2pc_data_size += UnsignedLeb128Size(tgt_lir->offset - dex2pc_offset);
592 dex2pc_data_size += SignedLeb128Size(static_cast<int32_t>(tgt_lir->dalvik_offset) -
593 static_cast<int32_t>(dex2pc_dalvik_offset));
594 dex2pc_offset = tgt_lir->offset;
595 dex2pc_dalvik_offset = tgt_lir->dalvik_offset;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700596 }
597 }
Vladimir Marko1e6cb632013-11-28 16:27:29 +0000598
599 uint32_t total_entries = pc2dex_entries + dex2pc_entries;
600 uint32_t hdr_data_size = UnsignedLeb128Size(total_entries) + UnsignedLeb128Size(pc2dex_entries);
601 uint32_t data_size = hdr_data_size + pc2dex_data_size + dex2pc_data_size;
Vladimir Marko06606b92013-12-02 15:31:08 +0000602 encoded_mapping_table_.resize(data_size);
603 uint8_t* write_pos = &encoded_mapping_table_[0];
604 write_pos = EncodeUnsignedLeb128(write_pos, total_entries);
605 write_pos = EncodeUnsignedLeb128(write_pos, pc2dex_entries);
606 DCHECK_EQ(static_cast<size_t>(write_pos - &encoded_mapping_table_[0]), hdr_data_size);
607 uint8_t* write_pos2 = write_pos + pc2dex_data_size;
Vladimir Marko1e6cb632013-11-28 16:27:29 +0000608
Vladimir Marko1e6cb632013-11-28 16:27:29 +0000609 pc2dex_offset = 0u;
610 pc2dex_dalvik_offset = 0u;
Vladimir Marko06606b92013-12-02 15:31:08 +0000611 dex2pc_offset = 0u;
612 dex2pc_dalvik_offset = 0u;
613 for (LIR* tgt_lir = first_lir_insn_; tgt_lir != NULL; tgt_lir = NEXT_LIR(tgt_lir)) {
614 if (!tgt_lir->flags.is_nop && (tgt_lir->opcode == kPseudoSafepointPC)) {
615 DCHECK(pc2dex_offset <= tgt_lir->offset);
616 write_pos = EncodeUnsignedLeb128(write_pos, tgt_lir->offset - pc2dex_offset);
617 write_pos = EncodeSignedLeb128(write_pos, static_cast<int32_t>(tgt_lir->dalvik_offset) -
618 static_cast<int32_t>(pc2dex_dalvik_offset));
619 pc2dex_offset = tgt_lir->offset;
620 pc2dex_dalvik_offset = tgt_lir->dalvik_offset;
621 }
622 if (!tgt_lir->flags.is_nop && (tgt_lir->opcode == kPseudoExportedPC)) {
623 DCHECK(dex2pc_offset <= tgt_lir->offset);
624 write_pos2 = EncodeUnsignedLeb128(write_pos2, tgt_lir->offset - dex2pc_offset);
625 write_pos2 = EncodeSignedLeb128(write_pos2, static_cast<int32_t>(tgt_lir->dalvik_offset) -
626 static_cast<int32_t>(dex2pc_dalvik_offset));
627 dex2pc_offset = tgt_lir->offset;
628 dex2pc_dalvik_offset = tgt_lir->dalvik_offset;
629 }
Vladimir Marko1e6cb632013-11-28 16:27:29 +0000630 }
Vladimir Marko06606b92013-12-02 15:31:08 +0000631 DCHECK_EQ(static_cast<size_t>(write_pos - &encoded_mapping_table_[0]),
632 hdr_data_size + pc2dex_data_size);
633 DCHECK_EQ(static_cast<size_t>(write_pos2 - &encoded_mapping_table_[0]), data_size);
Vladimir Marko1e6cb632013-11-28 16:27:29 +0000634
Ian Rogers96faf5b2013-08-09 22:05:32 -0700635 if (kIsDebugBuild) {
Vladimir Marko06606b92013-12-02 15:31:08 +0000636 CHECK(VerifyCatchEntries());
637
Ian Rogers96faf5b2013-08-09 22:05:32 -0700638 // Verify the encoded table holds the expected data.
Vladimir Marko06606b92013-12-02 15:31:08 +0000639 MappingTable table(&encoded_mapping_table_[0]);
Ian Rogers96faf5b2013-08-09 22:05:32 -0700640 CHECK_EQ(table.TotalSize(), total_entries);
641 CHECK_EQ(table.PcToDexSize(), pc2dex_entries);
Vladimir Marko1e6cb632013-11-28 16:27:29 +0000642 auto it = table.PcToDexBegin();
Vladimir Marko06606b92013-12-02 15:31:08 +0000643 auto it2 = table.DexToPcBegin();
644 for (LIR* tgt_lir = first_lir_insn_; tgt_lir != NULL; tgt_lir = NEXT_LIR(tgt_lir)) {
645 if (!tgt_lir->flags.is_nop && (tgt_lir->opcode == kPseudoSafepointPC)) {
646 CHECK_EQ(tgt_lir->offset, it.NativePcOffset());
647 CHECK_EQ(tgt_lir->dalvik_offset, it.DexPc());
648 ++it;
649 }
650 if (!tgt_lir->flags.is_nop && (tgt_lir->opcode == kPseudoExportedPC)) {
651 CHECK_EQ(tgt_lir->offset, it2.NativePcOffset());
652 CHECK_EQ(tgt_lir->dalvik_offset, it2.DexPc());
653 ++it2;
654 }
Ian Rogers96faf5b2013-08-09 22:05:32 -0700655 }
Vladimir Marko1e6cb632013-11-28 16:27:29 +0000656 CHECK(it == table.PcToDexEnd());
Vladimir Marko1e6cb632013-11-28 16:27:29 +0000657 CHECK(it2 == table.DexToPcEnd());
Ian Rogers96faf5b2013-08-09 22:05:32 -0700658 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700659}
660
661class NativePcToReferenceMapBuilder {
662 public:
663 NativePcToReferenceMapBuilder(std::vector<uint8_t>* table,
664 size_t entries, uint32_t max_native_offset,
665 size_t references_width) : entries_(entries),
666 references_width_(references_width), in_use_(entries),
667 table_(table) {
668 // Compute width in bytes needed to hold max_native_offset.
669 native_offset_width_ = 0;
670 while (max_native_offset != 0) {
671 native_offset_width_++;
672 max_native_offset >>= 8;
673 }
674 // Resize table and set up header.
675 table->resize((EntryWidth() * entries) + sizeof(uint32_t));
676 CHECK_LT(native_offset_width_, 1U << 3);
677 (*table)[0] = native_offset_width_ & 7;
678 CHECK_LT(references_width_, 1U << 13);
679 (*table)[0] |= (references_width_ << 3) & 0xFF;
680 (*table)[1] = (references_width_ >> 5) & 0xFF;
681 CHECK_LT(entries, 1U << 16);
682 (*table)[2] = entries & 0xFF;
683 (*table)[3] = (entries >> 8) & 0xFF;
684 }
685
686 void AddEntry(uint32_t native_offset, const uint8_t* references) {
687 size_t table_index = TableIndex(native_offset);
688 while (in_use_[table_index]) {
689 table_index = (table_index + 1) % entries_;
690 }
691 in_use_[table_index] = true;
buzbee0d829482013-10-11 15:24:55 -0700692 SetCodeOffset(table_index, native_offset);
693 DCHECK_EQ(native_offset, GetCodeOffset(table_index));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700694 SetReferences(table_index, references);
695 }
696
697 private:
698 size_t TableIndex(uint32_t native_offset) {
699 return NativePcOffsetToReferenceMap::Hash(native_offset) % entries_;
700 }
701
buzbee0d829482013-10-11 15:24:55 -0700702 uint32_t GetCodeOffset(size_t table_index) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700703 uint32_t native_offset = 0;
704 size_t table_offset = (table_index * EntryWidth()) + sizeof(uint32_t);
705 for (size_t i = 0; i < native_offset_width_; i++) {
706 native_offset |= (*table_)[table_offset + i] << (i * 8);
707 }
708 return native_offset;
709 }
710
buzbee0d829482013-10-11 15:24:55 -0700711 void SetCodeOffset(size_t table_index, uint32_t native_offset) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700712 size_t table_offset = (table_index * EntryWidth()) + sizeof(uint32_t);
713 for (size_t i = 0; i < native_offset_width_; i++) {
714 (*table_)[table_offset + i] = (native_offset >> (i * 8)) & 0xFF;
715 }
716 }
717
718 void SetReferences(size_t table_index, const uint8_t* references) {
719 size_t table_offset = (table_index * EntryWidth()) + sizeof(uint32_t);
720 memcpy(&(*table_)[table_offset + native_offset_width_], references, references_width_);
721 }
722
723 size_t EntryWidth() const {
724 return native_offset_width_ + references_width_;
725 }
726
727 // Number of entries in the table.
728 const size_t entries_;
729 // Number of bytes used to encode the reference bitmap.
730 const size_t references_width_;
731 // Number of bytes used to encode a native offset.
732 size_t native_offset_width_;
733 // Entries that are in use.
734 std::vector<bool> in_use_;
735 // The table we're building.
736 std::vector<uint8_t>* const table_;
737};
738
739void Mir2Lir::CreateNativeGcMap() {
Vladimir Marko06606b92013-12-02 15:31:08 +0000740 DCHECK(!encoded_mapping_table_.empty());
741 MappingTable mapping_table(&encoded_mapping_table_[0]);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700742 uint32_t max_native_offset = 0;
Vladimir Marko06606b92013-12-02 15:31:08 +0000743 for (auto it = mapping_table.PcToDexBegin(), end = mapping_table.PcToDexEnd(); it != end; ++it) {
744 uint32_t native_offset = it.NativePcOffset();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700745 if (native_offset > max_native_offset) {
746 max_native_offset = native_offset;
747 }
748 }
749 MethodReference method_ref(cu_->dex_file, cu_->method_idx);
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000750 const std::vector<uint8_t>* gc_map_raw =
751 cu_->compiler_driver->GetVerifiedMethodsData()->GetDexGcMap(method_ref);
Vladimir Marko8171fc32013-11-26 17:05:58 +0000752 verifier::DexPcToReferenceMap dex_gc_map(&(*gc_map_raw)[0]);
753 DCHECK_EQ(gc_map_raw->size(), dex_gc_map.RawSize());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700754 // Compute native offset to references size.
755 NativePcToReferenceMapBuilder native_gc_map_builder(&native_gc_map_,
Vladimir Marko06606b92013-12-02 15:31:08 +0000756 mapping_table.PcToDexSize(),
757 max_native_offset, dex_gc_map.RegWidth());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700758
Vladimir Marko06606b92013-12-02 15:31:08 +0000759 for (auto it = mapping_table.PcToDexBegin(), end = mapping_table.PcToDexEnd(); it != end; ++it) {
760 uint32_t native_offset = it.NativePcOffset();
761 uint32_t dex_pc = it.DexPc();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700762 const uint8_t* references = dex_gc_map.FindBitMap(dex_pc, false);
763 CHECK(references != NULL) << "Missing ref for dex pc 0x" << std::hex << dex_pc;
764 native_gc_map_builder.AddEntry(native_offset, references);
765 }
766}
767
768/* Determine the offset of each literal field */
buzbee0d829482013-10-11 15:24:55 -0700769int Mir2Lir::AssignLiteralOffset(CodeOffset offset) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700770 offset = AssignLiteralOffsetCommon(literal_list_, offset);
buzbee0d829482013-10-11 15:24:55 -0700771 offset = AssignLiteralPointerOffsetCommon(code_literal_list_, offset);
772 offset = AssignLiteralPointerOffsetCommon(method_literal_list_, offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700773 return offset;
774}
775
buzbee0d829482013-10-11 15:24:55 -0700776int Mir2Lir::AssignSwitchTablesOffset(CodeOffset offset) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700777 GrowableArray<SwitchTable*>::Iterator iterator(&switch_tables_);
778 while (true) {
buzbee0d829482013-10-11 15:24:55 -0700779 Mir2Lir::SwitchTable* tab_rec = iterator.Next();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700780 if (tab_rec == NULL) break;
781 tab_rec->offset = offset;
782 if (tab_rec->table[0] == Instruction::kSparseSwitchSignature) {
783 offset += tab_rec->table[1] * (sizeof(int) * 2);
784 } else {
785 DCHECK_EQ(static_cast<int>(tab_rec->table[0]),
786 static_cast<int>(Instruction::kPackedSwitchSignature));
787 offset += tab_rec->table[1] * sizeof(int);
788 }
789 }
790 return offset;
791}
792
buzbee0d829482013-10-11 15:24:55 -0700793int Mir2Lir::AssignFillArrayDataOffset(CodeOffset offset) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700794 GrowableArray<FillArrayData*>::Iterator iterator(&fill_array_data_);
795 while (true) {
796 Mir2Lir::FillArrayData *tab_rec = iterator.Next();
797 if (tab_rec == NULL) break;
798 tab_rec->offset = offset;
799 offset += tab_rec->size;
800 // word align
801 offset = (offset + 3) & ~3;
802 }
803 return offset;
804}
805
Brian Carlstrom7940e442013-07-12 13:46:57 -0700806/*
807 * Insert a kPseudoCaseLabel at the beginning of the Dalvik
buzbeeb48819d2013-09-14 16:15:25 -0700808 * offset vaddr if pretty-printing, otherise use the standard block
809 * label. The selected label will be used to fix up the case
buzbee252254b2013-09-08 16:20:53 -0700810 * branch table during the assembly phase. All resource flags
811 * are set to prevent code motion. KeyVal is just there for debugging.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700812 */
buzbee0d829482013-10-11 15:24:55 -0700813LIR* Mir2Lir::InsertCaseLabel(DexOffset vaddr, int keyVal) {
buzbee252254b2013-09-08 16:20:53 -0700814 LIR* boundary_lir = &block_label_list_[mir_graph_->FindBlock(vaddr)->id];
buzbeeb48819d2013-09-14 16:15:25 -0700815 LIR* res = boundary_lir;
816 if (cu_->verbose) {
817 // Only pay the expense if we're pretty-printing.
818 LIR* new_label = static_cast<LIR*>(arena_->Alloc(sizeof(LIR), ArenaAllocator::kAllocLIR));
819 new_label->dalvik_offset = vaddr;
820 new_label->opcode = kPseudoCaseLabel;
821 new_label->operands[0] = keyVal;
822 new_label->flags.fixup = kFixupLabel;
823 DCHECK(!new_label->flags.use_def_invalid);
824 new_label->u.m.def_mask = ENCODE_ALL;
825 InsertLIRAfter(boundary_lir, new_label);
826 res = new_label;
827 }
828 return res;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700829}
830
buzbee0d829482013-10-11 15:24:55 -0700831void Mir2Lir::MarkPackedCaseLabels(Mir2Lir::SwitchTable* tab_rec) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700832 const uint16_t* table = tab_rec->table;
buzbee0d829482013-10-11 15:24:55 -0700833 DexOffset base_vaddr = tab_rec->vaddr;
834 const int32_t *targets = reinterpret_cast<const int32_t*>(&table[4]);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700835 int entries = table[1];
836 int low_key = s4FromSwitchData(&table[2]);
837 for (int i = 0; i < entries; i++) {
838 tab_rec->targets[i] = InsertCaseLabel(base_vaddr + targets[i], i + low_key);
839 }
840}
841
buzbee0d829482013-10-11 15:24:55 -0700842void Mir2Lir::MarkSparseCaseLabels(Mir2Lir::SwitchTable* tab_rec) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700843 const uint16_t* table = tab_rec->table;
buzbee0d829482013-10-11 15:24:55 -0700844 DexOffset base_vaddr = tab_rec->vaddr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700845 int entries = table[1];
buzbee0d829482013-10-11 15:24:55 -0700846 const int32_t* keys = reinterpret_cast<const int32_t*>(&table[2]);
847 const int32_t* targets = &keys[entries];
Brian Carlstrom7940e442013-07-12 13:46:57 -0700848 for (int i = 0; i < entries; i++) {
849 tab_rec->targets[i] = InsertCaseLabel(base_vaddr + targets[i], keys[i]);
850 }
851}
852
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700853void Mir2Lir::ProcessSwitchTables() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700854 GrowableArray<SwitchTable*>::Iterator iterator(&switch_tables_);
855 while (true) {
856 Mir2Lir::SwitchTable *tab_rec = iterator.Next();
857 if (tab_rec == NULL) break;
858 if (tab_rec->table[0] == Instruction::kPackedSwitchSignature) {
859 MarkPackedCaseLabels(tab_rec);
860 } else if (tab_rec->table[0] == Instruction::kSparseSwitchSignature) {
861 MarkSparseCaseLabels(tab_rec);
862 } else {
863 LOG(FATAL) << "Invalid switch table";
864 }
865 }
866}
867
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700868void Mir2Lir::DumpSparseSwitchTable(const uint16_t* table) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700869 /*
870 * Sparse switch data format:
871 * ushort ident = 0x0200 magic value
872 * ushort size number of entries in the table; > 0
873 * int keys[size] keys, sorted low-to-high; 32-bit aligned
874 * int targets[size] branch targets, relative to switch opcode
875 *
876 * Total size is (2+size*4) 16-bit code units.
877 */
Brian Carlstrom7940e442013-07-12 13:46:57 -0700878 uint16_t ident = table[0];
879 int entries = table[1];
buzbee0d829482013-10-11 15:24:55 -0700880 const int32_t* keys = reinterpret_cast<const int32_t*>(&table[2]);
881 const int32_t* targets = &keys[entries];
Brian Carlstrom7940e442013-07-12 13:46:57 -0700882 LOG(INFO) << "Sparse switch table - ident:0x" << std::hex << ident
883 << ", entries: " << std::dec << entries;
884 for (int i = 0; i < entries; i++) {
885 LOG(INFO) << " Key[" << keys[i] << "] -> 0x" << std::hex << targets[i];
886 }
887}
888
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700889void Mir2Lir::DumpPackedSwitchTable(const uint16_t* table) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700890 /*
891 * Packed switch data format:
892 * ushort ident = 0x0100 magic value
893 * ushort size number of entries in the table
894 * int first_key first (and lowest) switch case value
895 * int targets[size] branch targets, relative to switch opcode
896 *
897 * Total size is (4+size*2) 16-bit code units.
898 */
Brian Carlstrom7940e442013-07-12 13:46:57 -0700899 uint16_t ident = table[0];
buzbee0d829482013-10-11 15:24:55 -0700900 const int32_t* targets = reinterpret_cast<const int32_t*>(&table[4]);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700901 int entries = table[1];
902 int low_key = s4FromSwitchData(&table[2]);
903 LOG(INFO) << "Packed switch table - ident:0x" << std::hex << ident
904 << ", entries: " << std::dec << entries << ", low_key: " << low_key;
905 for (int i = 0; i < entries; i++) {
906 LOG(INFO) << " Key[" << (i + low_key) << "] -> 0x" << std::hex
907 << targets[i];
908 }
909}
910
buzbee252254b2013-09-08 16:20:53 -0700911/* Set up special LIR to mark a Dalvik byte-code instruction start for pretty printing */
buzbee0d829482013-10-11 15:24:55 -0700912void Mir2Lir::MarkBoundary(DexOffset offset, const char* inst_str) {
913 // NOTE: only used for debug listings.
914 NewLIR1(kPseudoDalvikByteCodeBoundary, WrapPointer(ArenaStrdup(inst_str)));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700915}
916
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700917bool Mir2Lir::EvaluateBranch(Instruction::Code opcode, int32_t src1, int32_t src2) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700918 bool is_taken;
919 switch (opcode) {
920 case Instruction::IF_EQ: is_taken = (src1 == src2); break;
921 case Instruction::IF_NE: is_taken = (src1 != src2); break;
922 case Instruction::IF_LT: is_taken = (src1 < src2); break;
923 case Instruction::IF_GE: is_taken = (src1 >= src2); break;
924 case Instruction::IF_GT: is_taken = (src1 > src2); break;
925 case Instruction::IF_LE: is_taken = (src1 <= src2); break;
926 case Instruction::IF_EQZ: is_taken = (src1 == 0); break;
927 case Instruction::IF_NEZ: is_taken = (src1 != 0); break;
928 case Instruction::IF_LTZ: is_taken = (src1 < 0); break;
929 case Instruction::IF_GEZ: is_taken = (src1 >= 0); break;
930 case Instruction::IF_GTZ: is_taken = (src1 > 0); break;
931 case Instruction::IF_LEZ: is_taken = (src1 <= 0); break;
932 default:
933 LOG(FATAL) << "Unexpected opcode " << opcode;
934 is_taken = false;
935 }
936 return is_taken;
937}
938
939// Convert relation of src1/src2 to src2/src1
940ConditionCode Mir2Lir::FlipComparisonOrder(ConditionCode before) {
941 ConditionCode res;
942 switch (before) {
943 case kCondEq: res = kCondEq; break;
944 case kCondNe: res = kCondNe; break;
945 case kCondLt: res = kCondGt; break;
946 case kCondGt: res = kCondLt; break;
947 case kCondLe: res = kCondGe; break;
948 case kCondGe: res = kCondLe; break;
949 default:
950 res = static_cast<ConditionCode>(0);
951 LOG(FATAL) << "Unexpected ccode " << before;
952 }
953 return res;
954}
955
956// TODO: move to mir_to_lir.cc
957Mir2Lir::Mir2Lir(CompilationUnit* cu, MIRGraph* mir_graph, ArenaAllocator* arena)
958 : Backend(arena),
959 literal_list_(NULL),
960 method_literal_list_(NULL),
961 code_literal_list_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700962 first_fixup_(NULL),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700963 cu_(cu),
964 mir_graph_(mir_graph),
965 switch_tables_(arena, 4, kGrowableArraySwitchTables),
966 fill_array_data_(arena, 4, kGrowableArrayFillArrayData),
967 throw_launchpads_(arena, 2048, kGrowableArrayThrowLaunchPads),
968 suspend_launchpads_(arena, 4, kGrowableArraySuspendLaunchPads),
969 intrinsic_launchpads_(arena, 2048, kGrowableArrayMisc),
buzbeebd663de2013-09-10 15:41:31 -0700970 tempreg_info_(arena, 20, kGrowableArrayMisc),
971 reginfo_map_(arena, 64, kGrowableArrayMisc),
buzbee0d829482013-10-11 15:24:55 -0700972 pointer_storage_(arena, 128, kGrowableArrayMisc),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700973 data_offset_(0),
974 total_size_(0),
975 block_label_list_(NULL),
976 current_dalvik_offset_(0),
buzbeeb48819d2013-09-14 16:15:25 -0700977 estimated_native_code_size_(0),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700978 reg_pool_(NULL),
979 live_sreg_(0),
980 num_core_spills_(0),
981 num_fp_spills_(0),
982 frame_size_(0),
983 core_spill_mask_(0),
984 fp_spill_mask_(0),
985 first_lir_insn_(NULL),
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000986 last_lir_insn_(NULL),
987 inliner_(nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700988 promotion_map_ = static_cast<PromotionMap*>
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700989 (arena_->Alloc((cu_->num_dalvik_registers + cu_->num_compiler_temps + 1) *
990 sizeof(promotion_map_[0]), ArenaAllocator::kAllocRegAlloc));
buzbee0d829482013-10-11 15:24:55 -0700991 // Reserve pointer id 0 for NULL.
992 size_t null_idx = WrapPointer(NULL);
993 DCHECK_EQ(null_idx, 0U);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700994}
995
996void Mir2Lir::Materialize() {
buzbeea61f4952013-08-23 14:27:06 -0700997 cu_->NewTimingSplit("RegisterAllocation");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700998 CompilerInitializeRegAlloc(); // Needs to happen after SSA naming
999
1000 /* Allocate Registers using simple local allocation scheme */
1001 SimpleRegAlloc();
1002
buzbee479f83c2013-07-19 10:58:21 -07001003 if (mir_graph_->IsSpecialCase()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001004 /*
1005 * Custom codegen for special cases. If for any reason the
1006 * special codegen doesn't succeed, first_lir_insn_ will
1007 * set to NULL;
1008 */
buzbeea61f4952013-08-23 14:27:06 -07001009 cu_->NewTimingSplit("SpecialMIR2LIR");
buzbee479f83c2013-07-19 10:58:21 -07001010 SpecialMIR2LIR(mir_graph_->GetSpecialCase());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001011 }
1012
1013 /* Convert MIR to LIR, etc. */
1014 if (first_lir_insn_ == NULL) {
1015 MethodMIR2LIR();
1016 }
1017
1018 /* Method is not empty */
1019 if (first_lir_insn_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001020 // mark the targets of switch statement case labels
1021 ProcessSwitchTables();
1022
1023 /* Convert LIR into machine code. */
1024 AssembleLIR();
1025
1026 if (cu_->verbose) {
1027 CodegenDump();
1028 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001029 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001030}
1031
1032CompiledMethod* Mir2Lir::GetCompiledMethod() {
1033 // Combine vmap tables - core regs, then fp regs - into vmap_table
Ian Rogers96faf5b2013-08-09 22:05:32 -07001034 std::vector<uint16_t> raw_vmap_table;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001035 // Core regs may have been inserted out of order - sort first
1036 std::sort(core_vmap_table_.begin(), core_vmap_table_.end());
Mathieu Chartier193bad92013-08-29 18:46:00 -07001037 for (size_t i = 0 ; i < core_vmap_table_.size(); ++i) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001038 // Copy, stripping out the phys register sort key
Ian Rogers96faf5b2013-08-09 22:05:32 -07001039 raw_vmap_table.push_back(~(-1 << VREG_NUM_WIDTH) & core_vmap_table_[i]);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001040 }
1041 // If we have a frame, push a marker to take place of lr
1042 if (frame_size_ > 0) {
Ian Rogers96faf5b2013-08-09 22:05:32 -07001043 raw_vmap_table.push_back(INVALID_VREG);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001044 } else {
1045 DCHECK_EQ(__builtin_popcount(core_spill_mask_), 0);
1046 DCHECK_EQ(__builtin_popcount(fp_spill_mask_), 0);
1047 }
1048 // Combine vmap tables - core regs, then fp regs. fp regs already sorted
1049 for (uint32_t i = 0; i < fp_vmap_table_.size(); i++) {
Ian Rogers96faf5b2013-08-09 22:05:32 -07001050 raw_vmap_table.push_back(fp_vmap_table_[i]);
1051 }
Vladimir Marko1e6cb632013-11-28 16:27:29 +00001052 Leb128EncodingVector vmap_encoder;
Ian Rogers96faf5b2013-08-09 22:05:32 -07001053 // Prefix the encoded data with its size.
Vladimir Marko1e6cb632013-11-28 16:27:29 +00001054 vmap_encoder.PushBackUnsigned(raw_vmap_table.size());
Mathieu Chartier193bad92013-08-29 18:46:00 -07001055 for (uint16_t cur : raw_vmap_table) {
Vladimir Marko1e6cb632013-11-28 16:27:29 +00001056 vmap_encoder.PushBackUnsigned(cur);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001057 }
1058 CompiledMethod* result =
Mathieu Chartier193bad92013-08-29 18:46:00 -07001059 new CompiledMethod(*cu_->compiler_driver, cu_->instruction_set, code_buffer_, frame_size_,
Vladimir Marko06606b92013-12-02 15:31:08 +00001060 core_spill_mask_, fp_spill_mask_, encoded_mapping_table_,
Mathieu Chartier193bad92013-08-29 18:46:00 -07001061 vmap_encoder.GetData(), native_gc_map_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001062 return result;
1063}
1064
1065int Mir2Lir::ComputeFrameSize() {
1066 /* Figure out the frame size */
1067 static const uint32_t kAlignMask = kStackAlignment - 1;
1068 uint32_t size = (num_core_spills_ + num_fp_spills_ +
1069 1 /* filler word */ + cu_->num_regs + cu_->num_outs +
1070 cu_->num_compiler_temps + 1 /* cur_method* */)
1071 * sizeof(uint32_t);
1072 /* Align and set */
1073 return (size + kAlignMask) & ~(kAlignMask);
1074}
1075
1076/*
1077 * Append an LIR instruction to the LIR list maintained by a compilation
1078 * unit
1079 */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001080void Mir2Lir::AppendLIR(LIR* lir) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001081 if (first_lir_insn_ == NULL) {
1082 DCHECK(last_lir_insn_ == NULL);
1083 last_lir_insn_ = first_lir_insn_ = lir;
1084 lir->prev = lir->next = NULL;
1085 } else {
1086 last_lir_insn_->next = lir;
1087 lir->prev = last_lir_insn_;
1088 lir->next = NULL;
1089 last_lir_insn_ = lir;
1090 }
1091}
1092
1093/*
1094 * Insert an LIR instruction before the current instruction, which cannot be the
1095 * first instruction.
1096 *
1097 * prev_lir <-> new_lir <-> current_lir
1098 */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001099void Mir2Lir::InsertLIRBefore(LIR* current_lir, LIR* new_lir) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001100 DCHECK(current_lir->prev != NULL);
1101 LIR *prev_lir = current_lir->prev;
1102
1103 prev_lir->next = new_lir;
1104 new_lir->prev = prev_lir;
1105 new_lir->next = current_lir;
1106 current_lir->prev = new_lir;
1107}
1108
1109/*
1110 * Insert an LIR instruction after the current instruction, which cannot be the
1111 * first instruction.
1112 *
1113 * current_lir -> new_lir -> old_next
1114 */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001115void Mir2Lir::InsertLIRAfter(LIR* current_lir, LIR* new_lir) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001116 new_lir->prev = current_lir;
1117 new_lir->next = current_lir->next;
1118 current_lir->next = new_lir;
1119 new_lir->next->prev = new_lir;
1120}
1121
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001122} // namespace art