blob: b3ceefcb6300f58899b04f6dd74b53178dfee26c [file] [log] [blame]
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00001/*
2 * Copyright (C) 2013 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 "base/stl_util.h"
18#include "dex_file.h"
19#include "dex_instruction.h"
20#include "dex_instruction-inl.h"
21#include "base/mutex.h"
22#include "base/mutex-inl.h"
23#include "mirror/art_method.h"
24#include "mirror/art_method-inl.h"
25#include "mirror/class.h"
26#include "mirror/class-inl.h"
27#include "mirror/dex_cache.h"
28#include "mirror/dex_cache-inl.h"
29#include "mirror/object.h"
30#include "mirror/object-inl.h"
31#include "verified_methods_data.h"
32#include "verifier/dex_gc_map.h"
33#include "verifier/method_verifier.h"
34#include "verifier/method_verifier-inl.h"
35#include "verifier/register_line.h"
36#include "verifier/register_line-inl.h"
37
38namespace art {
39
40VerifiedMethodsData::VerifiedMethodsData()
41 : dex_gc_maps_lock_("compiler GC maps lock"),
42 dex_gc_maps_(),
43 safecast_map_lock_("compiler Cast Elision lock"),
44 safecast_map_(),
45 devirt_maps_lock_("compiler Devirtualization lock"),
46 devirt_maps_(),
47 rejected_classes_lock_("compiler rejected classes lock"),
48 rejected_classes_() {
49}
50
51VerifiedMethodsData::~VerifiedMethodsData() {
52 Thread* self = Thread::Current();
53 {
54 WriterMutexLock mu(self, dex_gc_maps_lock_);
55 STLDeleteValues(&dex_gc_maps_);
56 }
57 {
58 WriterMutexLock mu(self, safecast_map_lock_);
59 STLDeleteValues(&safecast_map_);
60 }
61 {
62 WriterMutexLock mu(self, devirt_maps_lock_);
63 STLDeleteValues(&devirt_maps_);
64 }
65}
66
67bool VerifiedMethodsData::ProcessVerifiedMethod(verifier::MethodVerifier* method_verifier) {
68 MethodReference ref = method_verifier->GetMethodReference();
69 bool compile = IsCandidateForCompilation(ref, method_verifier->GetAccessFlags());
70 if (compile) {
71 /* Generate a register map and add it to the method. */
72 const std::vector<uint8_t>* dex_gc_map = GenerateGcMap(method_verifier);
73 if (dex_gc_map == NULL) {
74 DCHECK(method_verifier->HasFailures());
75 return false; // Not a real failure, but a failure to encode
76 }
77 if (kIsDebugBuild) {
78 VerifyGcMap(method_verifier, *dex_gc_map);
79 }
80 SetDexGcMap(ref, dex_gc_map);
81 }
82
83 if (method_verifier->HasCheckCasts()) {
84 MethodSafeCastSet* method_to_safe_casts = GenerateSafeCastSet(method_verifier);
85 if (method_to_safe_casts != NULL) {
86 SetSafeCastMap(ref, method_to_safe_casts);
87 }
88 }
89
90 if (method_verifier->HasVirtualOrInterfaceInvokes()) {
91 PcToConcreteMethodMap* pc_to_concrete_method = GenerateDevirtMap(method_verifier);
92 if (pc_to_concrete_method != NULL) {
93 SetDevirtMap(ref, pc_to_concrete_method);
94 }
95 }
96 return true;
97}
98
99const std::vector<uint8_t>* VerifiedMethodsData::GetDexGcMap(MethodReference ref) {
100 ReaderMutexLock mu(Thread::Current(), dex_gc_maps_lock_);
101 DexGcMapTable::const_iterator it = dex_gc_maps_.find(ref);
102 CHECK(it != dex_gc_maps_.end())
103 << "Didn't find GC map for: " << PrettyMethod(ref.dex_method_index, *ref.dex_file);
104 CHECK(it->second != NULL);
105 return it->second;
106}
107
108const MethodReference* VerifiedMethodsData::GetDevirtMap(const MethodReference& ref,
109 uint32_t dex_pc) {
110 ReaderMutexLock mu(Thread::Current(), devirt_maps_lock_);
111 DevirtualizationMapTable::const_iterator it = devirt_maps_.find(ref);
112 if (it == devirt_maps_.end()) {
113 return NULL;
114 }
115
116 // Look up the PC in the map, get the concrete method to execute and return its reference.
117 PcToConcreteMethodMap::const_iterator pc_to_concrete_method = it->second->find(dex_pc);
118 if (pc_to_concrete_method != it->second->end()) {
119 return &(pc_to_concrete_method->second);
120 } else {
121 return NULL;
122 }
123}
124
125bool VerifiedMethodsData::IsSafeCast(MethodReference ref, uint32_t pc) {
126 ReaderMutexLock mu(Thread::Current(), safecast_map_lock_);
127 SafeCastMap::const_iterator it = safecast_map_.find(ref);
128 if (it == safecast_map_.end()) {
129 return false;
130 }
131
132 // Look up the cast address in the set of safe casts
Vladimir Markoa9faa702013-12-17 11:17:52 +0000133 // Use binary_search for lookup in the sorted vector.
134 return std::binary_search(it->second->begin(), it->second->end(), pc);
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000135}
136
137void VerifiedMethodsData::AddRejectedClass(ClassReference ref) {
138 {
139 WriterMutexLock mu(Thread::Current(), rejected_classes_lock_);
140 rejected_classes_.insert(ref);
141 }
142 DCHECK(IsClassRejected(ref));
143}
144
145bool VerifiedMethodsData::IsClassRejected(ClassReference ref) {
146 ReaderMutexLock mu(Thread::Current(), rejected_classes_lock_);
147 return (rejected_classes_.find(ref) != rejected_classes_.end());
148}
149
150bool VerifiedMethodsData::IsCandidateForCompilation(MethodReference& method_ref,
151 const uint32_t access_flags) {
152#ifdef ART_SEA_IR_MODE
153 bool use_sea = Runtime::Current()->IsSeaIRMode();
154 use_sea = use_sea && (std::string::npos != PrettyMethod(
155 method_ref.dex_method_index, *(method_ref.dex_file)).find("fibonacci"));
156 if (use_sea) return true;
157#endif
158 // Don't compile class initializers, ever.
159 if (((access_flags & kAccConstructor) != 0) && ((access_flags & kAccStatic) != 0)) {
160 return false;
161 }
162 return (Runtime::Current()->GetCompilerFilter() != Runtime::kInterpretOnly);
163}
164
165const std::vector<uint8_t>* VerifiedMethodsData::GenerateGcMap(
166 verifier::MethodVerifier* method_verifier) {
167 size_t num_entries, ref_bitmap_bits, pc_bits;
168 ComputeGcMapSizes(method_verifier, &num_entries, &ref_bitmap_bits, &pc_bits);
169 // There's a single byte to encode the size of each bitmap
170 if (ref_bitmap_bits >= (8 /* bits per byte */ * 8192 /* 13-bit size */ )) {
171 // TODO: either a better GC map format or per method failures
172 method_verifier->Fail(verifier::VERIFY_ERROR_BAD_CLASS_HARD)
173 << "Cannot encode GC map for method with " << ref_bitmap_bits << " registers";
174 return NULL;
175 }
176 size_t ref_bitmap_bytes = (ref_bitmap_bits + 7) / 8;
177 // There are 2 bytes to encode the number of entries
178 if (num_entries >= 65536) {
179 // TODO: either a better GC map format or per method failures
180 method_verifier->Fail(verifier::VERIFY_ERROR_BAD_CLASS_HARD)
181 << "Cannot encode GC map for method with " << num_entries << " entries";
182 return NULL;
183 }
184 size_t pc_bytes;
185 verifier::RegisterMapFormat format;
186 if (pc_bits <= 8) {
187 format = verifier::kRegMapFormatCompact8;
188 pc_bytes = 1;
189 } else if (pc_bits <= 16) {
190 format = verifier::kRegMapFormatCompact16;
191 pc_bytes = 2;
192 } else {
193 // TODO: either a better GC map format or per method failures
194 method_verifier->Fail(verifier::VERIFY_ERROR_BAD_CLASS_HARD)
195 << "Cannot encode GC map for method with "
196 << (1 << pc_bits) << " instructions (number is rounded up to nearest power of 2)";
197 return NULL;
198 }
199 size_t table_size = ((pc_bytes + ref_bitmap_bytes) * num_entries) + 4;
200 std::vector<uint8_t>* table = new std::vector<uint8_t>;
201 if (table == NULL) {
202 method_verifier->Fail(verifier::VERIFY_ERROR_BAD_CLASS_HARD)
203 << "Failed to encode GC map (size=" << table_size << ")";
204 return NULL;
205 }
206 table->reserve(table_size);
207 // Write table header
208 table->push_back(format | ((ref_bitmap_bytes & ~0xFF) >> 5));
209 table->push_back(ref_bitmap_bytes & 0xFF);
210 table->push_back(num_entries & 0xFF);
211 table->push_back((num_entries >> 8) & 0xFF);
212 // Write table data
213 const DexFile::CodeItem* code_item = method_verifier->CodeItem();
214 for (size_t i = 0; i < code_item->insns_size_in_code_units_; i++) {
215 if (method_verifier->GetInstructionFlags(i).IsCompileTimeInfoPoint()) {
216 table->push_back(i & 0xFF);
217 if (pc_bytes == 2) {
218 table->push_back((i >> 8) & 0xFF);
219 }
220 verifier::RegisterLine* line = method_verifier->GetRegLine(i);
221 line->WriteReferenceBitMap(*table, ref_bitmap_bytes);
222 }
223 }
224 DCHECK_EQ(table->size(), table_size);
225 return table;
226}
227
228void VerifiedMethodsData::VerifyGcMap(verifier::MethodVerifier* method_verifier,
229 const std::vector<uint8_t>& data) {
230 // Check that for every GC point there is a map entry, there aren't entries for non-GC points,
231 // that the table data is well formed and all references are marked (or not) in the bitmap
232 verifier::DexPcToReferenceMap map(&data[0]);
233 DCHECK_EQ(data.size(), map.RawSize());
234 size_t map_index = 0;
235 const DexFile::CodeItem* code_item = method_verifier->CodeItem();
236 for (size_t i = 0; i < code_item->insns_size_in_code_units_; i++) {
237 const uint8_t* reg_bitmap = map.FindBitMap(i, false);
238 if (method_verifier->GetInstructionFlags(i).IsCompileTimeInfoPoint()) {
239 CHECK_LT(map_index, map.NumEntries());
240 CHECK_EQ(map.GetDexPc(map_index), i);
241 CHECK_EQ(map.GetBitMap(map_index), reg_bitmap);
242 map_index++;
243 verifier::RegisterLine* line = method_verifier->GetRegLine(i);
244 for (size_t j = 0; j < code_item->registers_size_; j++) {
245 if (line->GetRegisterType(j).IsNonZeroReferenceTypes()) {
246 CHECK_LT(j / 8, map.RegWidth());
247 CHECK_EQ((reg_bitmap[j / 8] >> (j % 8)) & 1, 1);
248 } else if ((j / 8) < map.RegWidth()) {
249 CHECK_EQ((reg_bitmap[j / 8] >> (j % 8)) & 1, 0);
250 } else {
251 // If a register doesn't contain a reference then the bitmap may be shorter than the line
252 }
253 }
254 } else {
255 CHECK(reg_bitmap == NULL);
256 }
257 }
258}
259
260void VerifiedMethodsData::ComputeGcMapSizes(verifier::MethodVerifier* method_verifier,
261 size_t* gc_points, size_t* ref_bitmap_bits,
262 size_t* log2_max_gc_pc) {
263 size_t local_gc_points = 0;
264 size_t max_insn = 0;
265 size_t max_ref_reg = -1;
266 const DexFile::CodeItem* code_item = method_verifier->CodeItem();
267 for (size_t i = 0; i < code_item->insns_size_in_code_units_; i++) {
268 if (method_verifier->GetInstructionFlags(i).IsCompileTimeInfoPoint()) {
269 local_gc_points++;
270 max_insn = i;
271 verifier::RegisterLine* line = method_verifier->GetRegLine(i);
272 max_ref_reg = line->GetMaxNonZeroReferenceReg(max_ref_reg);
273 }
274 }
275 *gc_points = local_gc_points;
276 *ref_bitmap_bits = max_ref_reg + 1; // if max register is 0 we need 1 bit to encode (ie +1)
277 size_t i = 0;
278 while ((1U << i) <= max_insn) {
279 i++;
280 }
281 *log2_max_gc_pc = i;
282}
283
284void VerifiedMethodsData::SetDexGcMap(MethodReference ref, const std::vector<uint8_t>* gc_map) {
285 DCHECK(Runtime::Current()->IsCompiler());
286 {
287 WriterMutexLock mu(Thread::Current(), dex_gc_maps_lock_);
288 DexGcMapTable::iterator it = dex_gc_maps_.find(ref);
289 if (it != dex_gc_maps_.end()) {
290 delete it->second;
291 dex_gc_maps_.erase(it);
292 }
293 dex_gc_maps_.Put(ref, gc_map);
294 }
295 DCHECK(GetDexGcMap(ref) != NULL);
296}
297
298VerifiedMethodsData::MethodSafeCastSet* VerifiedMethodsData::GenerateSafeCastSet(
299 verifier::MethodVerifier* method_verifier) {
300 /*
301 * Walks over the method code and adds any cast instructions in which
302 * the type cast is implicit to a set, which is used in the code generation
303 * to elide these casts.
304 */
305 if (method_verifier->HasFailures()) {
306 return NULL;
307 }
308 UniquePtr<MethodSafeCastSet> mscs;
309 const DexFile::CodeItem* code_item = method_verifier->CodeItem();
310 const Instruction* inst = Instruction::At(code_item->insns_);
311 const Instruction* end = Instruction::At(code_item->insns_ +
312 code_item->insns_size_in_code_units_);
313
314 for (; inst < end; inst = inst->Next()) {
315 Instruction::Code code = inst->Opcode();
316 if ((code == Instruction::CHECK_CAST) || (code == Instruction::APUT_OBJECT)) {
317 uint32_t dex_pc = inst->GetDexPc(code_item->insns_);
318 const verifier::RegisterLine* line = method_verifier->GetRegLine(dex_pc);
319 bool is_safe_cast = false;
320 if (code == Instruction::CHECK_CAST) {
321 const verifier::RegType& reg_type(line->GetRegisterType(inst->VRegA_21c()));
322 const verifier::RegType& cast_type =
323 method_verifier->ResolveCheckedClass(inst->VRegB_21c());
324 is_safe_cast = cast_type.IsStrictlyAssignableFrom(reg_type);
325 } else {
326 const verifier::RegType& array_type(line->GetRegisterType(inst->VRegB_23x()));
327 // We only know its safe to assign to an array if the array type is precise. For example,
328 // an Object[] can have any type of object stored in it, but it may also be assigned a
329 // String[] in which case the stores need to be of Strings.
330 if (array_type.IsPreciseReference()) {
331 const verifier::RegType& value_type(line->GetRegisterType(inst->VRegA_23x()));
332 const verifier::RegType& component_type = method_verifier->GetRegTypeCache()
333 ->GetComponentType(array_type, method_verifier->GetClassLoader());
334 is_safe_cast = component_type.IsStrictlyAssignableFrom(value_type);
335 }
336 }
337 if (is_safe_cast) {
338 if (mscs.get() == nullptr) {
339 mscs.reset(new MethodSafeCastSet());
Vladimir Markoa9faa702013-12-17 11:17:52 +0000340 } else {
341 DCHECK_LT(mscs->back(), dex_pc); // Verify ordering for push_back() to the sorted vector.
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000342 }
Vladimir Markoa9faa702013-12-17 11:17:52 +0000343 mscs->push_back(dex_pc);
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000344 }
345 }
346 }
347 return mscs.release();
348}
349
350void VerifiedMethodsData::SetSafeCastMap(MethodReference ref, const MethodSafeCastSet* cast_set) {
351 WriterMutexLock mu(Thread::Current(), safecast_map_lock_);
352 SafeCastMap::iterator it = safecast_map_.find(ref);
353 if (it != safecast_map_.end()) {
354 delete it->second;
355 safecast_map_.erase(it);
356 }
357 safecast_map_.Put(ref, cast_set);
358 DCHECK(safecast_map_.find(ref) != safecast_map_.end());
359}
360
361VerifiedMethodsData::PcToConcreteMethodMap* VerifiedMethodsData::GenerateDevirtMap(
362 verifier::MethodVerifier* method_verifier) {
363 // It is risky to rely on reg_types for sharpening in cases of soft
364 // verification, we might end up sharpening to a wrong implementation. Just abort.
365 if (method_verifier->HasFailures()) {
366 return NULL;
367 }
368
369 UniquePtr<PcToConcreteMethodMap> pc_to_concrete_method_map;
370 const DexFile::CodeItem* code_item = method_verifier->CodeItem();
371 const uint16_t* insns = code_item->insns_;
372 const Instruction* inst = Instruction::At(insns);
373 const Instruction* end = Instruction::At(insns + code_item->insns_size_in_code_units_);
374
375 for (; inst < end; inst = inst->Next()) {
376 bool is_virtual = (inst->Opcode() == Instruction::INVOKE_VIRTUAL) ||
377 (inst->Opcode() == Instruction::INVOKE_VIRTUAL_RANGE);
378 bool is_interface = (inst->Opcode() == Instruction::INVOKE_INTERFACE) ||
379 (inst->Opcode() == Instruction::INVOKE_INTERFACE_RANGE);
380
381 if (!is_interface && !is_virtual) {
382 continue;
383 }
384 // Get reg type for register holding the reference to the object that will be dispatched upon.
385 uint32_t dex_pc = inst->GetDexPc(insns);
386 verifier::RegisterLine* line = method_verifier->GetRegLine(dex_pc);
387 bool is_range = (inst->Opcode() == Instruction::INVOKE_VIRTUAL_RANGE) ||
388 (inst->Opcode() == Instruction::INVOKE_INTERFACE_RANGE);
389 const verifier::RegType&
390 reg_type(line->GetRegisterType(is_range ? inst->VRegC_3rc() : inst->VRegC_35c()));
391
392 if (!reg_type.HasClass()) {
393 // We will compute devirtualization information only when we know the Class of the reg type.
394 continue;
395 }
396 mirror::Class* reg_class = reg_type.GetClass();
397 if (reg_class->IsInterface()) {
398 // We can't devirtualize when the known type of the register is an interface.
399 continue;
400 }
401 if (reg_class->IsAbstract() && !reg_class->IsArrayClass()) {
402 // We can't devirtualize abstract classes except on arrays of abstract classes.
403 continue;
404 }
405 mirror::ArtMethod* abstract_method = method_verifier->GetDexCache()->GetResolvedMethod(
406 is_range ? inst->VRegB_3rc() : inst->VRegB_35c());
407 if (abstract_method == NULL) {
408 // If the method is not found in the cache this means that it was never found
409 // by ResolveMethodAndCheckAccess() called when verifying invoke_*.
410 continue;
411 }
412 // Find the concrete method.
413 mirror::ArtMethod* concrete_method = NULL;
414 if (is_interface) {
415 concrete_method = reg_type.GetClass()->FindVirtualMethodForInterface(abstract_method);
416 }
417 if (is_virtual) {
418 concrete_method = reg_type.GetClass()->FindVirtualMethodForVirtual(abstract_method);
419 }
420 if (concrete_method == NULL || concrete_method->IsAbstract()) {
421 // In cases where concrete_method is not found, or is abstract, continue to the next invoke.
422 continue;
423 }
424 if (reg_type.IsPreciseReference() || concrete_method->IsFinal() ||
425 concrete_method->GetDeclaringClass()->IsFinal()) {
426 // If we knew exactly the class being dispatched upon, or if the target method cannot be
427 // overridden record the target to be used in the compiler driver.
428 if (pc_to_concrete_method_map.get() == NULL) {
429 pc_to_concrete_method_map.reset(new PcToConcreteMethodMap());
430 }
431 MethodReference concrete_ref(
432 concrete_method->GetDeclaringClass()->GetDexCache()->GetDexFile(),
433 concrete_method->GetDexMethodIndex());
434 pc_to_concrete_method_map->Put(dex_pc, concrete_ref);
435 }
436 }
437 return pc_to_concrete_method_map.release();
438}
439
440void VerifiedMethodsData::SetDevirtMap(MethodReference ref,
441 const PcToConcreteMethodMap* devirt_map) {
442 WriterMutexLock mu(Thread::Current(), devirt_maps_lock_);
443 DevirtualizationMapTable::iterator it = devirt_maps_.find(ref);
444 if (it != devirt_maps_.end()) {
445 delete it->second;
446 devirt_maps_.erase(it);
447 }
448
449 devirt_maps_.Put(ref, devirt_map);
450 DCHECK(devirt_maps_.find(ref) != devirt_maps_.end());
451}
452
453} // namespace art