1 /*
2 * Copyright (C) 2015 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 "intrinsics.h"
18
19 #include "art_field-inl.h"
20 #include "art_method-inl.h"
21 #include "base/utils.h"
22 #include "class_linker.h"
23 #include "class_root-inl.h"
24 #include "code_generator.h"
25 #include "dex/invoke_type.h"
26 #include "driver/compiler_options.h"
27 #include "gc/space/image_space.h"
28 #include "image-inl.h"
29 #include "intrinsic_objects.h"
30 #include "nodes.h"
31 #include "obj_ptr-inl.h"
32 #include "scoped_thread_state_change-inl.h"
33 #include "thread-current-inl.h"
34
35 namespace art {
36
operator <<(std::ostream & os,const Intrinsics & intrinsic)37 std::ostream& operator<<(std::ostream& os, const Intrinsics& intrinsic) {
38 switch (intrinsic) {
39 case Intrinsics::kNone:
40 os << "None";
41 break;
42 #define OPTIMIZING_INTRINSICS(Name, IsStatic, NeedsEnvironmentOrCache, SideEffects, Exceptions, ...) \
43 case Intrinsics::k ## Name: \
44 os << # Name; \
45 break;
46 #include "intrinsics_list.h"
47 INTRINSICS_LIST(OPTIMIZING_INTRINSICS)
48 #undef STATIC_INTRINSICS_LIST
49 #undef VIRTUAL_INTRINSICS_LIST
50 #undef OPTIMIZING_INTRINSICS
51 }
52 return os;
53 }
54
55 static const char kIntegerCacheDescriptor[] = "Ljava/lang/Integer$IntegerCache;";
56 static const char kIntegerDescriptor[] = "Ljava/lang/Integer;";
57 static const char kIntegerArrayDescriptor[] = "[Ljava/lang/Integer;";
58 static const char kLowFieldName[] = "low";
59 static const char kHighFieldName[] = "high";
60 static const char kValueFieldName[] = "value";
61
GetBootImageLiveObjects()62 static ObjPtr<mirror::ObjectArray<mirror::Object>> GetBootImageLiveObjects()
63 REQUIRES_SHARED(Locks::mutator_lock_) {
64 gc::Heap* heap = Runtime::Current()->GetHeap();
65 const std::vector<gc::space::ImageSpace*>& boot_image_spaces = heap->GetBootImageSpaces();
66 DCHECK(!boot_image_spaces.empty());
67 const ImageHeader& main_header = boot_image_spaces[0]->GetImageHeader();
68 ObjPtr<mirror::ObjectArray<mirror::Object>> boot_image_live_objects =
69 ObjPtr<mirror::ObjectArray<mirror::Object>>::DownCast(
70 main_header.GetImageRoot<kWithoutReadBarrier>(ImageHeader::kBootImageLiveObjects));
71 DCHECK(boot_image_live_objects != nullptr);
72 DCHECK(heap->ObjectIsInBootImageSpace(boot_image_live_objects));
73 return boot_image_live_objects;
74 }
75
LookupInitializedClass(Thread * self,ClassLinker * class_linker,const char * descriptor)76 static ObjPtr<mirror::Class> LookupInitializedClass(Thread* self,
77 ClassLinker* class_linker,
78 const char* descriptor)
79 REQUIRES_SHARED(Locks::mutator_lock_) {
80 ObjPtr<mirror::Class> klass =
81 class_linker->LookupClass(self, descriptor, /* class_loader= */ nullptr);
82 DCHECK(klass != nullptr);
83 DCHECK(klass->IsInitialized());
84 return klass;
85 }
86
GetIntegerCacheArray(ObjPtr<mirror::Class> cache_class)87 static ObjPtr<mirror::ObjectArray<mirror::Object>> GetIntegerCacheArray(
88 ObjPtr<mirror::Class> cache_class) REQUIRES_SHARED(Locks::mutator_lock_) {
89 ArtField* cache_field = cache_class->FindDeclaredStaticField("cache", kIntegerArrayDescriptor);
90 DCHECK(cache_field != nullptr);
91 return ObjPtr<mirror::ObjectArray<mirror::Object>>::DownCast(cache_field->GetObject(cache_class));
92 }
93
GetIntegerCacheField(ObjPtr<mirror::Class> cache_class,const char * field_name)94 static int32_t GetIntegerCacheField(ObjPtr<mirror::Class> cache_class, const char* field_name)
95 REQUIRES_SHARED(Locks::mutator_lock_) {
96 ArtField* field = cache_class->FindDeclaredStaticField(field_name, "I");
97 DCHECK(field != nullptr);
98 return field->GetInt(cache_class);
99 }
100
CheckIntegerCache(Thread * self,ClassLinker * class_linker,ObjPtr<mirror::ObjectArray<mirror::Object>> boot_image_live_objects,ObjPtr<mirror::ObjectArray<mirror::Object>> boot_image_cache)101 static bool CheckIntegerCache(Thread* self,
102 ClassLinker* class_linker,
103 ObjPtr<mirror::ObjectArray<mirror::Object>> boot_image_live_objects,
104 ObjPtr<mirror::ObjectArray<mirror::Object>> boot_image_cache)
105 REQUIRES_SHARED(Locks::mutator_lock_) {
106 DCHECK(boot_image_cache != nullptr);
107
108 // Since we have a cache in the boot image, both java.lang.Integer and
109 // java.lang.Integer$IntegerCache must be initialized in the boot image.
110 ObjPtr<mirror::Class> cache_class =
111 LookupInitializedClass(self, class_linker, kIntegerCacheDescriptor);
112 ObjPtr<mirror::Class> integer_class =
113 LookupInitializedClass(self, class_linker, kIntegerDescriptor);
114
115 // Check that the current cache is the same as the `boot_image_cache`.
116 ObjPtr<mirror::ObjectArray<mirror::Object>> current_cache = GetIntegerCacheArray(cache_class);
117 if (current_cache != boot_image_cache) {
118 return false; // Messed up IntegerCache.cache.
119 }
120
121 // Check that the range matches the boot image cache length.
122 int32_t low = GetIntegerCacheField(cache_class, kLowFieldName);
123 int32_t high = GetIntegerCacheField(cache_class, kHighFieldName);
124 if (boot_image_cache->GetLength() != high - low + 1) {
125 return false; // Messed up IntegerCache.low or IntegerCache.high.
126 }
127
128 // Check that the elements match the boot image intrinsic objects and check their values as well.
129 ArtField* value_field = integer_class->FindDeclaredInstanceField(kValueFieldName, "I");
130 DCHECK(value_field != nullptr);
131 for (int32_t i = 0, len = boot_image_cache->GetLength(); i != len; ++i) {
132 ObjPtr<mirror::Object> boot_image_object =
133 IntrinsicObjects::GetIntegerValueOfObject(boot_image_live_objects, i);
134 DCHECK(Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(boot_image_object));
135 // No need for read barrier for comparison with a boot image object.
136 ObjPtr<mirror::Object> current_object =
137 boot_image_cache->GetWithoutChecks<kVerifyNone, kWithoutReadBarrier>(i);
138 if (boot_image_object != current_object) {
139 return false; // Messed up IntegerCache.cache[i]
140 }
141 if (value_field->GetInt(boot_image_object) != low + i) {
142 return false; // Messed up IntegerCache.cache[i].value.
143 }
144 }
145
146 return true;
147 }
148
CanReferenceBootImageObjects(HInvoke * invoke,const CompilerOptions & compiler_options)149 static bool CanReferenceBootImageObjects(HInvoke* invoke, const CompilerOptions& compiler_options) {
150 // Piggyback on the method load kind to determine whether we can use PC-relative addressing
151 // for AOT. This should cover both the testing config (non-PIC boot image) and codegens that
152 // reject PC-relative load kinds and fall back to the runtime call.
153 if (compiler_options.IsAotCompiler() &&
154 !invoke->AsInvokeStaticOrDirect()->HasPcRelativeMethodLoadKind()) {
155 return false;
156 }
157 if (!compiler_options.IsBootImage() &&
158 Runtime::Current()->GetHeap()->GetBootImageSpaces().empty()) {
159 return false; // Running without boot image, cannot use required boot image objects.
160 }
161 return true;
162 }
163
ComputeIntegerValueOfLocations(HInvoke * invoke,CodeGenerator * codegen,Location return_location,Location first_argument_location)164 void IntrinsicVisitor::ComputeIntegerValueOfLocations(HInvoke* invoke,
165 CodeGenerator* codegen,
166 Location return_location,
167 Location first_argument_location) {
168 // The intrinsic will call if it needs to allocate a j.l.Integer.
169 LocationSummary::CallKind call_kind = LocationSummary::kCallOnMainOnly;
170 const CompilerOptions& compiler_options = codegen->GetCompilerOptions();
171 if (!CanReferenceBootImageObjects(invoke, compiler_options)) {
172 return;
173 }
174 if (compiler_options.IsBootImage()) {
175 if (!compiler_options.IsImageClass(kIntegerCacheDescriptor) ||
176 !compiler_options.IsImageClass(kIntegerDescriptor)) {
177 return;
178 }
179 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
180 Thread* self = Thread::Current();
181 ScopedObjectAccess soa(self);
182 ObjPtr<mirror::Class> cache_class = class_linker->LookupClass(
183 self, kIntegerCacheDescriptor, /* class_loader= */ nullptr);
184 DCHECK(cache_class != nullptr);
185 if (UNLIKELY(!cache_class->IsInitialized())) {
186 LOG(WARNING) << "Image class " << cache_class->PrettyDescriptor() << " is uninitialized.";
187 return;
188 }
189 ObjPtr<mirror::Class> integer_class =
190 class_linker->LookupClass(self, kIntegerDescriptor, /* class_loader= */ nullptr);
191 DCHECK(integer_class != nullptr);
192 if (UNLIKELY(!integer_class->IsInitialized())) {
193 LOG(WARNING) << "Image class " << integer_class->PrettyDescriptor() << " is uninitialized.";
194 return;
195 }
196 int32_t low = GetIntegerCacheField(cache_class, kLowFieldName);
197 int32_t high = GetIntegerCacheField(cache_class, kHighFieldName);
198 if (kIsDebugBuild) {
199 ObjPtr<mirror::ObjectArray<mirror::Object>> current_cache = GetIntegerCacheArray(cache_class);
200 CHECK(current_cache != nullptr);
201 CHECK_EQ(current_cache->GetLength(), high - low + 1);
202 ArtField* value_field = integer_class->FindDeclaredInstanceField(kValueFieldName, "I");
203 CHECK(value_field != nullptr);
204 for (int32_t i = 0, len = current_cache->GetLength(); i != len; ++i) {
205 ObjPtr<mirror::Object> current_object = current_cache->GetWithoutChecks(i);
206 CHECK(current_object != nullptr);
207 CHECK_EQ(value_field->GetInt(current_object), low + i);
208 }
209 }
210 if (invoke->InputAt(0)->IsIntConstant()) {
211 int32_t value = invoke->InputAt(0)->AsIntConstant()->GetValue();
212 if (static_cast<uint32_t>(value) - static_cast<uint32_t>(low) <
213 static_cast<uint32_t>(high - low + 1)) {
214 // No call, we shall use direct pointer to the Integer object.
215 call_kind = LocationSummary::kNoCall;
216 }
217 }
218 } else {
219 Runtime* runtime = Runtime::Current();
220 Thread* self = Thread::Current();
221 ScopedObjectAccess soa(self);
222 ObjPtr<mirror::ObjectArray<mirror::Object>> boot_image_live_objects = GetBootImageLiveObjects();
223 ObjPtr<mirror::ObjectArray<mirror::Object>> cache =
224 IntrinsicObjects::GetIntegerValueOfCache(boot_image_live_objects);
225 if (cache == nullptr) {
226 return; // No cache in the boot image.
227 }
228 if (compiler_options.IsJitCompiler()) {
229 if (!CheckIntegerCache(self, runtime->GetClassLinker(), boot_image_live_objects, cache)) {
230 return; // The cache was somehow messed up, probably by using reflection.
231 }
232 } else {
233 DCHECK(compiler_options.IsAotCompiler());
234 DCHECK(CheckIntegerCache(self, runtime->GetClassLinker(), boot_image_live_objects, cache));
235 if (invoke->InputAt(0)->IsIntConstant()) {
236 int32_t value = invoke->InputAt(0)->AsIntConstant()->GetValue();
237 // Retrieve the `value` from the lowest cached Integer.
238 ObjPtr<mirror::Object> low_integer =
239 IntrinsicObjects::GetIntegerValueOfObject(boot_image_live_objects, 0u);
240 ObjPtr<mirror::Class> integer_class =
241 low_integer->GetClass<kVerifyNone, kWithoutReadBarrier>();
242 ArtField* value_field = integer_class->FindDeclaredInstanceField(kValueFieldName, "I");
243 DCHECK(value_field != nullptr);
244 int32_t low = value_field->GetInt(low_integer);
245 if (static_cast<uint32_t>(value) - static_cast<uint32_t>(low) <
246 static_cast<uint32_t>(cache->GetLength())) {
247 // No call, we shall use direct pointer to the Integer object. Note that we cannot
248 // do this for JIT as the "low" can change through reflection before emitting the code.
249 call_kind = LocationSummary::kNoCall;
250 }
251 }
252 }
253 }
254
255 ArenaAllocator* allocator = codegen->GetGraph()->GetAllocator();
256 LocationSummary* locations = new (allocator) LocationSummary(invoke, call_kind, kIntrinsified);
257 if (call_kind == LocationSummary::kCallOnMainOnly) {
258 locations->SetInAt(0, Location::RegisterOrConstant(invoke->InputAt(0)));
259 locations->AddTemp(first_argument_location);
260 locations->SetOut(return_location);
261 } else {
262 locations->SetInAt(0, Location::ConstantLocation(invoke->InputAt(0)->AsConstant()));
263 locations->SetOut(Location::RequiresRegister());
264 }
265 }
266
GetIntegerCacheLowFromIntegerCache(Thread * self,ClassLinker * class_linker)267 static int32_t GetIntegerCacheLowFromIntegerCache(Thread* self, ClassLinker* class_linker)
268 REQUIRES_SHARED(Locks::mutator_lock_) {
269 ObjPtr<mirror::Class> cache_class =
270 LookupInitializedClass(self, class_linker, kIntegerCacheDescriptor);
271 return GetIntegerCacheField(cache_class, kLowFieldName);
272 }
273
IntegerValueOfInfo()274 inline IntrinsicVisitor::IntegerValueOfInfo::IntegerValueOfInfo()
275 : value_offset(0),
276 low(0),
277 length(0u),
278 value_boot_image_reference(kInvalidReference) {}
279
ComputeIntegerValueOfInfo(HInvoke * invoke,const CompilerOptions & compiler_options)280 IntrinsicVisitor::IntegerValueOfInfo IntrinsicVisitor::ComputeIntegerValueOfInfo(
281 HInvoke* invoke, const CompilerOptions& compiler_options) {
282 // Note that we could cache all of the data looked up here. but there's no good
283 // location for it. We don't want to add it to WellKnownClasses, to avoid creating global
284 // jni values. Adding it as state to the compiler singleton seems like wrong
285 // separation of concerns.
286 // The need for this data should be pretty rare though.
287
288 // Note that at this point we can no longer abort the code generation. Therefore,
289 // we need to provide data that shall not lead to a crash even if the fields were
290 // modified through reflection since ComputeIntegerValueOfLocations() when JITting.
291
292 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
293 Thread* self = Thread::Current();
294 ScopedObjectAccess soa(self);
295
296 IntegerValueOfInfo info;
297 if (compiler_options.IsBootImage()) {
298 ObjPtr<mirror::Class> integer_class = invoke->GetResolvedMethod()->GetDeclaringClass();
299 DCHECK(integer_class->DescriptorEquals(kIntegerDescriptor));
300 ArtField* value_field = integer_class->FindDeclaredInstanceField(kValueFieldName, "I");
301 DCHECK(value_field != nullptr);
302 info.value_offset = value_field->GetOffset().Uint32Value();
303 ObjPtr<mirror::Class> cache_class =
304 LookupInitializedClass(self, class_linker, kIntegerCacheDescriptor);
305 info.low = GetIntegerCacheField(cache_class, kLowFieldName);
306 int32_t high = GetIntegerCacheField(cache_class, kHighFieldName);
307 info.length = dchecked_integral_cast<uint32_t>(high - info.low + 1);
308
309 if (invoke->InputAt(0)->IsIntConstant()) {
310 int32_t input_value = invoke->InputAt(0)->AsIntConstant()->GetValue();
311 uint32_t index = static_cast<uint32_t>(input_value) - static_cast<uint32_t>(info.low);
312 if (index < static_cast<uint32_t>(info.length)) {
313 info.value_boot_image_reference = IntrinsicObjects::EncodePatch(
314 IntrinsicObjects::PatchType::kIntegerValueOfObject, index);
315 } else {
316 // Not in the cache.
317 info.value_boot_image_reference = IntegerValueOfInfo::kInvalidReference;
318 }
319 } else {
320 info.array_data_boot_image_reference =
321 IntrinsicObjects::EncodePatch(IntrinsicObjects::PatchType::kIntegerValueOfArray);
322 }
323 } else {
324 ObjPtr<mirror::ObjectArray<mirror::Object>> boot_image_live_objects = GetBootImageLiveObjects();
325 ObjPtr<mirror::Object> low_integer =
326 IntrinsicObjects::GetIntegerValueOfObject(boot_image_live_objects, 0u);
327 ObjPtr<mirror::Class> integer_class = low_integer->GetClass<kVerifyNone, kWithoutReadBarrier>();
328 ArtField* value_field = integer_class->FindDeclaredInstanceField(kValueFieldName, "I");
329 DCHECK(value_field != nullptr);
330 info.value_offset = value_field->GetOffset().Uint32Value();
331 if (compiler_options.IsJitCompiler()) {
332 // Use the current `IntegerCache.low` for JIT to avoid truly surprising behavior if the
333 // code messes up the `value` field in the lowest cached Integer using reflection.
334 info.low = GetIntegerCacheLowFromIntegerCache(self, class_linker);
335 } else {
336 // For app AOT, the `low_integer->value` should be the same as `IntegerCache.low`.
337 info.low = value_field->GetInt(low_integer);
338 DCHECK_EQ(info.low, GetIntegerCacheLowFromIntegerCache(self, class_linker));
339 }
340 // Do not look at `IntegerCache.high`, use the immutable length of the cache array instead.
341 info.length = dchecked_integral_cast<uint32_t>(
342 IntrinsicObjects::GetIntegerValueOfCache(boot_image_live_objects)->GetLength());
343
344 if (invoke->InputAt(0)->IsIntConstant()) {
345 int32_t input_value = invoke->InputAt(0)->AsIntConstant()->GetValue();
346 uint32_t index = static_cast<uint32_t>(input_value) - static_cast<uint32_t>(info.low);
347 if (index < static_cast<uint32_t>(info.length)) {
348 ObjPtr<mirror::Object> integer =
349 IntrinsicObjects::GetIntegerValueOfObject(boot_image_live_objects, index);
350 info.value_boot_image_reference = CodeGenerator::GetBootImageOffset(integer);
351 } else {
352 // Not in the cache.
353 info.value_boot_image_reference = IntegerValueOfInfo::kInvalidReference;
354 }
355 } else {
356 info.array_data_boot_image_reference =
357 CodeGenerator::GetBootImageOffset(boot_image_live_objects) +
358 IntrinsicObjects::GetIntegerValueOfArrayDataOffset(boot_image_live_objects).Uint32Value();
359 }
360 }
361
362 return info;
363 }
364
GetReferenceDisableIntrinsicOffset()365 MemberOffset IntrinsicVisitor::GetReferenceDisableIntrinsicOffset() {
366 ScopedObjectAccess soa(Thread::Current());
367 // The "disableIntrinsic" is the first static field.
368 ArtField* field = GetClassRoot<mirror::Reference>()->GetStaticField(0);
369 DCHECK_STREQ(field->GetName(), "disableIntrinsic");
370 return field->GetOffset();
371 }
372
GetReferenceSlowPathEnabledOffset()373 MemberOffset IntrinsicVisitor::GetReferenceSlowPathEnabledOffset() {
374 ScopedObjectAccess soa(Thread::Current());
375 // The "slowPathEnabled" is the second static field.
376 ArtField* field = GetClassRoot<mirror::Reference>()->GetStaticField(1);
377 DCHECK_STREQ(field->GetName(), "slowPathEnabled");
378 return field->GetOffset();
379 }
380
CreateReferenceGetReferentLocations(HInvoke * invoke,CodeGenerator * codegen)381 void IntrinsicVisitor::CreateReferenceGetReferentLocations(HInvoke* invoke,
382 CodeGenerator* codegen) {
383 if (!CanReferenceBootImageObjects(invoke, codegen->GetCompilerOptions())) {
384 return;
385 }
386
387 ArenaAllocator* allocator = codegen->GetGraph()->GetAllocator();
388 LocationSummary* locations =
389 new (allocator) LocationSummary(invoke, LocationSummary::kCallOnSlowPath, kIntrinsified);
390 locations->SetInAt(0, Location::RequiresRegister());
391 locations->SetOut(Location::RequiresRegister());
392 }
393
CreateReferenceRefersToLocations(HInvoke * invoke)394 void IntrinsicVisitor::CreateReferenceRefersToLocations(HInvoke* invoke) {
395 if (kEmitCompilerReadBarrier && !kUseBakerReadBarrier) {
396 // Unimplemented for non-Baker read barrier.
397 return;
398 }
399
400 ArenaAllocator* allocator = invoke->GetBlock()->GetGraph()->GetAllocator();
401 LocationSummary* locations =
402 new (allocator) LocationSummary(invoke, LocationSummary::kCallOnSlowPath, kIntrinsified);
403 locations->SetInAt(0, Location::RequiresRegister());
404 locations->SetInAt(1, Location::RequiresRegister());
405 locations->SetOut(Location::RequiresRegister());
406 }
407
AssertNonMovableStringClass()408 void IntrinsicVisitor::AssertNonMovableStringClass() {
409 if (kIsDebugBuild) {
410 ScopedObjectAccess soa(Thread::Current());
411 ObjPtr<mirror::Class> string_class = GetClassRoot<mirror::String>();
412 CHECK(!art::Runtime::Current()->GetHeap()->IsMovableObject(string_class));
413 }
414 }
415
416 } // namespace art
417