blob: 583008bbe8c5d9c8cd6382cf26fe89f144974158 [file] [log] [blame]
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001/*
2 * Copyright (C) 2014 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 "inliner.h"
18
Mathieu Chartiere401d142015-04-22 13:56:20 -070019#include "art_method-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070020#include "base/enums.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000021#include "builder.h"
22#include "class_linker.h"
23#include "constant_folding.h"
24#include "dead_code_elimination.h"
Vladimir Markobe10e8e2016-01-22 12:09:44 +000025#include "dex/verified_method.h"
26#include "dex/verification_results.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000027#include "driver/compiler_driver-inl.h"
Calin Juravleec748352015-07-29 13:52:12 +010028#include "driver/compiler_options.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000029#include "driver/dex_compilation_unit.h"
30#include "instruction_simplifier.h"
Scott Wakelingd60a1af2015-07-22 14:32:44 +010031#include "intrinsics.h"
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +000032#include "jit/jit.h"
33#include "jit/jit_code_cache.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000034#include "mirror/class_loader.h"
35#include "mirror/dex_cache.h"
36#include "nodes.h"
Nicolas Geoffray335005e2015-06-25 10:01:47 +010037#include "optimizing_compiler.h"
Nicolas Geoffray454a4812015-06-09 10:37:32 +010038#include "reference_type_propagation.h"
Matthew Gharritye9288852016-07-14 14:08:16 -070039#include "register_allocator_linear_scan.h"
Vladimir Markobe10e8e2016-01-22 12:09:44 +000040#include "quick/inline_method_analyser.h"
Vladimir Markodc151b22015-10-15 18:02:30 +010041#include "sharpening.h"
David Brazdil4833f5a2015-12-16 10:37:39 +000042#include "ssa_builder.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000043#include "ssa_phi_elimination.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070044#include "scoped_thread_state_change-inl.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000045#include "thread.h"
46
47namespace art {
48
Nicolas Geoffray5949fa02015-12-18 10:57:10 +000049static constexpr size_t kMaximumNumberOfHInstructions = 32;
50
51// Limit the number of dex registers that we accumulate while inlining
52// to avoid creating large amount of nested environments.
53static constexpr size_t kMaximumNumberOfCumulatedDexRegisters = 64;
54
55// Avoid inlining within a huge method due to memory pressure.
56static constexpr size_t kMaximumCodeUnitSize = 4096;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -070057
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000058void HInliner::Run() {
Calin Juravle8f96df82015-07-29 15:58:48 +010059 const CompilerOptions& compiler_options = compiler_driver_->GetCompilerOptions();
60 if ((compiler_options.GetInlineDepthLimit() == 0)
61 || (compiler_options.GetInlineMaxCodeUnits() == 0)) {
62 return;
63 }
Nicolas Geoffray5949fa02015-12-18 10:57:10 +000064 if (caller_compilation_unit_.GetCodeItem()->insns_size_in_code_units_ > kMaximumCodeUnitSize) {
65 return;
66 }
Nicolas Geoffraye50b8d22015-03-13 08:57:42 +000067 if (graph_->IsDebuggable()) {
68 // For simplicity, we currently never inline when the graph is debuggable. This avoids
69 // doing some logic in the runtime to discover if a method could have been inlined.
70 return;
71 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +000072 // Keep a copy of all blocks when starting the visit.
73 ArenaVector<HBasicBlock*> blocks = graph_->GetReversePostOrder();
Vladimir Markofa6b93c2015-09-15 10:15:55 +010074 DCHECK(!blocks.empty());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +000075 // Because we are changing the graph when inlining,
76 // we just iterate over the blocks of the outer method.
77 // This avoids doing the inlining work again on the inlined blocks.
78 for (HBasicBlock* block : blocks) {
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +000079 for (HInstruction* instruction = block->GetFirstInstruction(); instruction != nullptr;) {
80 HInstruction* next = instruction->GetNext();
Nicolas Geoffray454a4812015-06-09 10:37:32 +010081 HInvoke* call = instruction->AsInvoke();
Razvan A Lupusoru3e90a962015-03-27 13:44:44 -070082 // As long as the call is not intrinsified, it is worth trying to inline.
83 if (call != nullptr && call->GetIntrinsic() == Intrinsics::kNone) {
Nicolas Geoffrayb703d182017-02-14 18:05:28 +000084 if (kIsDebugBuild && IsCompilingWithCoreImage()) {
85 // Debugging case: directives in method names control or assert on inlining.
86 std::string callee_name = outer_compilation_unit_.GetDexFile()->PrettyMethod(
87 call->GetDexMethodIndex(), /* with_signature */ false);
88 // Tests prevent inlining by having $noinline$ in their method names.
89 if (callee_name.find("$noinline$") == std::string::npos) {
90 if (!TryInline(call)) {
91 bool should_have_inlined = (callee_name.find("$inline$") != std::string::npos);
92 CHECK(!should_have_inlined) << "Could not inline " << callee_name;
93 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000094 }
Guillaume "Vermeille" Sancheze918d382015-06-03 15:32:41 +010095 } else {
Nicolas Geoffrayb703d182017-02-14 18:05:28 +000096 // Normal case: try to inline.
97 TryInline(call);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000098 }
99 }
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000100 instruction = next;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000101 }
102 }
103}
104
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100105static bool IsMethodOrDeclaringClassFinal(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700106 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100107 return method->IsFinal() || method->GetDeclaringClass()->IsFinal();
108}
109
110/**
111 * Given the `resolved_method` looked up in the dex cache, try to find
112 * the actual runtime target of an interface or virtual call.
113 * Return nullptr if the runtime target cannot be proven.
114 */
115static ArtMethod* FindVirtualOrInterfaceTarget(HInvoke* invoke, ArtMethod* resolved_method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700116 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100117 if (IsMethodOrDeclaringClassFinal(resolved_method)) {
118 // No need to lookup further, the resolved method will be the target.
119 return resolved_method;
120 }
121
122 HInstruction* receiver = invoke->InputAt(0);
123 if (receiver->IsNullCheck()) {
124 // Due to multiple levels of inlining within the same pass, it might be that
125 // null check does not have the reference type of the actual receiver.
126 receiver = receiver->InputAt(0);
127 }
128 ReferenceTypeInfo info = receiver->GetReferenceTypeInfo();
Calin Juravle2e768302015-07-28 14:41:11 +0000129 DCHECK(info.IsValid()) << "Invalid RTI for " << receiver->DebugName();
130 if (!info.IsExact()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100131 // We currently only support inlining with known receivers.
132 // TODO: Remove this check, we should be able to inline final methods
133 // on unknown receivers.
134 return nullptr;
135 } else if (info.GetTypeHandle()->IsInterface()) {
136 // Statically knowing that the receiver has an interface type cannot
137 // help us find what is the target method.
138 return nullptr;
139 } else if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(info.GetTypeHandle().Get())) {
140 // The method that we're trying to call is not in the receiver's class or super classes.
141 return nullptr;
Nicolas Geoffrayab5327d2016-03-18 11:36:20 +0000142 } else if (info.GetTypeHandle()->IsErroneous()) {
143 // If the type is erroneous, do not go further, as we are going to query the vtable or
144 // imt table, that we can only safely do on non-erroneous classes.
145 return nullptr;
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100146 }
147
148 ClassLinker* cl = Runtime::Current()->GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700149 PointerSize pointer_size = cl->GetImagePointerSize();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100150 if (invoke->IsInvokeInterface()) {
151 resolved_method = info.GetTypeHandle()->FindVirtualMethodForInterface(
152 resolved_method, pointer_size);
153 } else {
154 DCHECK(invoke->IsInvokeVirtual());
155 resolved_method = info.GetTypeHandle()->FindVirtualMethodForVirtual(
156 resolved_method, pointer_size);
157 }
158
159 if (resolved_method == nullptr) {
160 // The information we had on the receiver was not enough to find
161 // the target method. Since we check above the exact type of the receiver,
162 // the only reason this can happen is an IncompatibleClassChangeError.
163 return nullptr;
Alex Light9139e002015-10-09 15:59:48 -0700164 } else if (!resolved_method->IsInvokable()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100165 // The information we had on the receiver was not enough to find
166 // the target method. Since we check above the exact type of the receiver,
167 // the only reason this can happen is an IncompatibleClassChangeError.
168 return nullptr;
169 } else if (IsMethodOrDeclaringClassFinal(resolved_method)) {
170 // A final method has to be the target method.
171 return resolved_method;
172 } else if (info.IsExact()) {
173 // If we found a method and the receiver's concrete type is statically
174 // known, we know for sure the target.
175 return resolved_method;
176 } else {
177 // Even if we did find a method, the receiver type was not enough to
178 // statically find the runtime target.
179 return nullptr;
180 }
181}
182
183static uint32_t FindMethodIndexIn(ArtMethod* method,
184 const DexFile& dex_file,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000185 uint32_t name_and_signature_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700186 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100187 if (IsSameDexFile(*method->GetDexFile(), dex_file)) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100188 return method->GetDexMethodIndex();
189 } else {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000190 return method->FindDexMethodIndexInOtherDexFile(dex_file, name_and_signature_index);
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100191 }
192}
193
Andreas Gampea5b09a62016-11-17 15:21:22 -0800194static dex::TypeIndex FindClassIndexIn(mirror::Class* cls,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000195 const DexCompilationUnit& compilation_unit)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700196 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000197 const DexFile& dex_file = *compilation_unit.GetDexFile();
Andreas Gampea5b09a62016-11-17 15:21:22 -0800198 dex::TypeIndex index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100199 if (cls->GetDexCache() == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700200 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000201 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800202 } else if (!cls->GetDexTypeIndex().IsValid()) {
David Sehr709b0702016-10-13 09:12:37 -0700203 DCHECK(cls->IsProxyClass()) << cls->PrettyClass();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100204 // TODO: deal with proxy classes.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100205 } else if (IsSameDexFile(cls->GetDexFile(), dex_file)) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000206 DCHECK_EQ(cls->GetDexCache(), compilation_unit.GetDexCache().Get());
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000207 index = cls->GetDexTypeIndex();
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100208 } else {
209 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000210 // We cannot guarantee the entry will resolve to the same class,
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100211 // as there may be different class loaders. So only return the index if it's
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000212 // the right class already resolved with the class loader.
213 if (index.IsValid()) {
214 ObjPtr<mirror::Class> resolved = ClassLinker::LookupResolvedType(
215 index, compilation_unit.GetDexCache().Get(), compilation_unit.GetClassLoader().Get());
216 if (resolved != cls) {
217 index = dex::TypeIndex::Invalid();
218 }
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100219 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100220 }
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000221
222 return index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100223}
224
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000225class ScopedProfilingInfoInlineUse {
226 public:
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000227 explicit ScopedProfilingInfoInlineUse(ArtMethod* method, Thread* self)
228 : method_(method),
229 self_(self),
230 // Fetch the profiling info ahead of using it. If it's null when fetching,
231 // we should not call JitCodeCache::DoneInlining.
232 profiling_info_(
233 Runtime::Current()->GetJit()->GetCodeCache()->NotifyCompilerUse(method, self)) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000234 }
235
236 ~ScopedProfilingInfoInlineUse() {
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000237 if (profiling_info_ != nullptr) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700238 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000239 DCHECK_EQ(profiling_info_, method_->GetProfilingInfo(pointer_size));
240 Runtime::Current()->GetJit()->GetCodeCache()->DoneCompilerUse(method_, self_);
241 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000242 }
243
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000244 ProfilingInfo* GetProfilingInfo() const { return profiling_info_; }
245
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000246 private:
247 ArtMethod* const method_;
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000248 Thread* const self_;
249 ProfilingInfo* const profiling_info_;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000250};
251
Calin Juravle13439f02017-02-21 01:17:21 -0800252HInliner::InlineCacheType HInliner::GetInlineCacheType(
253 const Handle<mirror::ObjectArray<mirror::Class>>& classes)
254 REQUIRES_SHARED(Locks::mutator_lock_) {
255 uint8_t number_of_types = 0;
256 for (; number_of_types < InlineCache::kIndividualCacheSize; ++number_of_types) {
257 if (classes->Get(number_of_types) == nullptr) {
258 break;
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000259 }
260 }
Calin Juravle13439f02017-02-21 01:17:21 -0800261
262 if (number_of_types == 0) {
263 return kInlineCacheUninitialized;
264 } else if (number_of_types == 1) {
265 return kInlineCacheMonomorphic;
266 } else if (number_of_types == InlineCache::kIndividualCacheSize) {
267 return kInlineCacheMegamorphic;
268 } else {
269 return kInlineCachePolymorphic;
270 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000271}
272
273static mirror::Class* GetMonomorphicType(Handle<mirror::ObjectArray<mirror::Class>> classes)
274 REQUIRES_SHARED(Locks::mutator_lock_) {
275 DCHECK(classes->Get(0) != nullptr);
276 return classes->Get(0);
277}
278
Mingyao Yang063fc772016-08-02 11:02:54 -0700279ArtMethod* HInliner::TryCHADevirtualization(ArtMethod* resolved_method) {
280 if (!resolved_method->HasSingleImplementation()) {
281 return nullptr;
282 }
283 if (Runtime::Current()->IsAotCompiler()) {
284 // No CHA-based devirtulization for AOT compiler (yet).
285 return nullptr;
286 }
287 if (outermost_graph_->IsCompilingOsr()) {
288 // We do not support HDeoptimize in OSR methods.
289 return nullptr;
290 }
Mingyao Yange8fcd012017-01-20 10:43:30 -0800291 PointerSize pointer_size = caller_compilation_unit_.GetClassLinker()->GetImagePointerSize();
292 return resolved_method->GetSingleImplementation(pointer_size);
Mingyao Yang063fc772016-08-02 11:02:54 -0700293}
294
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700295bool HInliner::TryInline(HInvoke* invoke_instruction) {
Orion Hodsonac141392017-01-13 11:53:47 +0000296 if (invoke_instruction->IsInvokeUnresolved() ||
297 invoke_instruction->IsInvokePolymorphic()) {
298 return false; // Don't bother to move further if we know the method is unresolved or an
299 // invoke-polymorphic.
Calin Juravle175dc732015-08-25 15:42:32 +0100300 }
301
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000302 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100303 uint32_t method_index = invoke_instruction->GetDexMethodIndex();
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000304 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -0700305 VLOG(compiler) << "Try inlining " << caller_dex_file.PrettyMethod(method_index);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000306
Nicolas Geoffray35071052015-06-09 15:43:38 +0100307 // We can query the dex cache directly. The verifier has populated it already.
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100308 ArtMethod* resolved_method = invoke_instruction->GetResolvedMethod();
Andreas Gampefd2140f2015-12-23 16:30:44 -0800309 ArtMethod* actual_method = nullptr;
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100310 if (resolved_method == nullptr) {
311 DCHECK(invoke_instruction->IsInvokeStaticOrDirect());
312 DCHECK(invoke_instruction->AsInvokeStaticOrDirect()->IsStringInit());
313 VLOG(compiler) << "Not inlining a String.<init> method";
314 return false;
315 } else if (invoke_instruction->IsInvokeStaticOrDirect()) {
Andreas Gampefd2140f2015-12-23 16:30:44 -0800316 actual_method = resolved_method;
Vladimir Marko58155012015-08-19 12:49:41 +0000317 } else {
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100318 // Check if we can statically find the method.
319 actual_method = FindVirtualOrInterfaceTarget(invoke_instruction, resolved_method);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000320 }
321
Mingyao Yang063fc772016-08-02 11:02:54 -0700322 bool cha_devirtualize = false;
323 if (actual_method == nullptr) {
324 ArtMethod* method = TryCHADevirtualization(resolved_method);
325 if (method != nullptr) {
326 cha_devirtualize = true;
327 actual_method = method;
328 }
329 }
330
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100331 if (actual_method != nullptr) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700332 bool result = TryInlineAndReplace(invoke_instruction,
333 actual_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000334 ReferenceTypeInfo::CreateInvalid(),
Mingyao Yang063fc772016-08-02 11:02:54 -0700335 /* do_rtp */ true,
336 cha_devirtualize);
Calin Juravle69158982016-03-16 11:53:41 +0000337 if (result && !invoke_instruction->IsInvokeStaticOrDirect()) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700338 if (cha_devirtualize) {
339 // Add dependency due to devirtulization. We've assumed resolved_method
340 // has single implementation.
341 outermost_graph_->AddCHASingleImplementationDependency(resolved_method);
342 MaybeRecordStat(kCHAInline);
343 } else {
344 MaybeRecordStat(kInlinedInvokeVirtualOrInterface);
345 }
Calin Juravle69158982016-03-16 11:53:41 +0000346 }
347 return result;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100348 }
Andreas Gampefd2140f2015-12-23 16:30:44 -0800349 DCHECK(!invoke_instruction->IsInvokeStaticOrDirect());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100350
Calin Juravle13439f02017-02-21 01:17:21 -0800351 // Try using inline caches.
352 return TryInlineFromInlineCache(caller_dex_file, invoke_instruction, resolved_method);
353}
354
355static Handle<mirror::ObjectArray<mirror::Class>> AllocateInlineCacheHolder(
356 const DexCompilationUnit& compilation_unit,
357 StackHandleScope<1>* hs)
358 REQUIRES_SHARED(Locks::mutator_lock_) {
359 Thread* self = Thread::Current();
360 ClassLinker* class_linker = compilation_unit.GetClassLinker();
361 Handle<mirror::ObjectArray<mirror::Class>> inline_cache = hs->NewHandle(
362 mirror::ObjectArray<mirror::Class>::Alloc(
363 self,
364 class_linker->GetClassRoot(ClassLinker::kClassArrayClass),
365 InlineCache::kIndividualCacheSize));
366 if (inline_cache == nullptr) {
367 // We got an OOME. Just clear the exception, and don't inline.
368 DCHECK(self->IsExceptionPending());
369 self->ClearException();
370 VLOG(compiler) << "Out of memory in the compiler when trying to inline";
371 }
372 return inline_cache;
373}
374
375bool HInliner::TryInlineFromInlineCache(const DexFile& caller_dex_file,
376 HInvoke* invoke_instruction,
377 ArtMethod* resolved_method)
378 REQUIRES_SHARED(Locks::mutator_lock_) {
379 StackHandleScope<1> hs(Thread::Current());
380 Handle<mirror::ObjectArray<mirror::Class>> inline_cache;
381 InlineCacheType inline_cache_type = Runtime::Current()->IsAotCompiler()
382 ? GetInlineCacheAOT(caller_dex_file, invoke_instruction, &hs, &inline_cache)
383 : GetInlineCacheJIT(invoke_instruction, &hs, &inline_cache);
384
385 switch (inline_cache_type) {
386 case kInlineCacheNoData:
387 break;
388
389 case kInlineCacheUninitialized:
390 VLOG(compiler) << "Interface or virtual call to "
391 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
392 << " is not hit and not inlined";
393 return false;
394
395 case kInlineCacheMonomorphic:
396 MaybeRecordStat(kMonomorphicCall);
397 if (outermost_graph_->IsCompilingOsr()) {
398 // If we are compiling OSR, we pretend this call is polymorphic, as we may come from the
399 // interpreter and it may have seen different receiver types.
400 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000401 } else {
Calin Juravle13439f02017-02-21 01:17:21 -0800402 return TryInlineMonomorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000403 }
Calin Juravle13439f02017-02-21 01:17:21 -0800404
405 case kInlineCachePolymorphic:
406 MaybeRecordStat(kPolymorphicCall);
407 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
408
409 case kInlineCacheMegamorphic:
410 VLOG(compiler) << "Interface or virtual call to "
411 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
412 << " is megamorphic and not inlined";
413 MaybeRecordStat(kMegamorphicCall);
414 return false;
415
416 case kInlineCacheMissingTypes:
417 VLOG(compiler) << "Interface or virtual call to "
418 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
419 << " is missing types and not inlined";
420 return false;
421 }
422 UNREACHABLE();
423}
424
425HInliner::InlineCacheType HInliner::GetInlineCacheJIT(
426 HInvoke* invoke_instruction,
427 StackHandleScope<1>* hs,
428 /*out*/Handle<mirror::ObjectArray<mirror::Class>>* inline_cache)
429 REQUIRES_SHARED(Locks::mutator_lock_) {
430 DCHECK(Runtime::Current()->UseJitCompilation());
431
432 ArtMethod* caller = graph_->GetArtMethod();
433 // Under JIT, we should always know the caller.
434 DCHECK(caller != nullptr);
435 ScopedProfilingInfoInlineUse spiis(caller, Thread::Current());
436 ProfilingInfo* profiling_info = spiis.GetProfilingInfo();
437
438 if (profiling_info == nullptr) {
439 return kInlineCacheNoData;
440 }
441
442 *inline_cache = AllocateInlineCacheHolder(caller_compilation_unit_, hs);
443 if (inline_cache->Get() == nullptr) {
444 // We can't extract any data if we failed to allocate;
445 return kInlineCacheNoData;
446 } else {
447 Runtime::Current()->GetJit()->GetCodeCache()->CopyInlineCacheInto(
448 *profiling_info->GetInlineCache(invoke_instruction->GetDexPc()),
449 *inline_cache);
450 return GetInlineCacheType(*inline_cache);
451 }
452}
453
454HInliner::InlineCacheType HInliner::GetInlineCacheAOT(
455 const DexFile& caller_dex_file,
456 HInvoke* invoke_instruction,
457 StackHandleScope<1>* hs,
458 /*out*/Handle<mirror::ObjectArray<mirror::Class>>* inline_cache)
459 REQUIRES_SHARED(Locks::mutator_lock_) {
460 DCHECK(Runtime::Current()->IsAotCompiler());
461 const ProfileCompilationInfo* pci = compiler_driver_->GetProfileCompilationInfo();
462 if (pci == nullptr) {
463 return kInlineCacheNoData;
464 }
465
466 ProfileCompilationInfo::OfflineProfileMethodInfo offline_profile;
467 bool found = pci->GetMethod(caller_dex_file.GetLocation(),
468 caller_dex_file.GetLocationChecksum(),
469 caller_compilation_unit_.GetDexMethodIndex(),
470 &offline_profile);
471 if (!found) {
472 return kInlineCacheNoData; // no profile information for this invocation.
473 }
474
475 *inline_cache = AllocateInlineCacheHolder(caller_compilation_unit_, hs);
476 if (inline_cache == nullptr) {
477 // We can't extract any data if we failed to allocate;
478 return kInlineCacheNoData;
479 } else {
480 return ExtractClassesFromOfflineProfile(invoke_instruction,
481 offline_profile,
482 *inline_cache);
483 }
484}
485
486HInliner::InlineCacheType HInliner::ExtractClassesFromOfflineProfile(
487 const HInvoke* invoke_instruction,
488 const ProfileCompilationInfo::OfflineProfileMethodInfo& offline_profile,
489 /*out*/Handle<mirror::ObjectArray<mirror::Class>> inline_cache)
490 REQUIRES_SHARED(Locks::mutator_lock_) {
491 const auto it = offline_profile.inline_caches.find(invoke_instruction->GetDexPc());
492 if (it == offline_profile.inline_caches.end()) {
493 return kInlineCacheUninitialized;
494 }
495
496 const ProfileCompilationInfo::DexPcData& dex_pc_data = it->second;
497
498 if (dex_pc_data.is_missing_types) {
499 return kInlineCacheMissingTypes;
500 }
501 if (dex_pc_data.is_megamorphic) {
502 return kInlineCacheMegamorphic;
503 }
504
505 DCHECK_LE(dex_pc_data.classes.size(), InlineCache::kIndividualCacheSize);
506 Thread* self = Thread::Current();
507 // We need to resolve the class relative to the containing dex file.
508 // So first, build a mapping from the index of dex file in the profile to
509 // its dex cache. This will avoid repeating the lookup when walking over
510 // the inline cache types.
511 std::vector<ObjPtr<mirror::DexCache>> dex_profile_index_to_dex_cache(
512 offline_profile.dex_references.size());
513 for (size_t i = 0; i < offline_profile.dex_references.size(); i++) {
514 bool found = false;
515 for (const DexFile* dex_file : compiler_driver_->GetDexFilesForOatFile()) {
516 if (offline_profile.dex_references[i].MatchesDex(dex_file)) {
517 dex_profile_index_to_dex_cache[i] =
518 caller_compilation_unit_.GetClassLinker()->FindDexCache(self, *dex_file);
519 found = true;
520 }
521 }
522 if (!found) {
523 VLOG(compiler) << "Could not find profiled dex file: "
524 << offline_profile.dex_references[i].dex_location;
525 return kInlineCacheMissingTypes;
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100526 }
527 }
528
Calin Juravle13439f02017-02-21 01:17:21 -0800529 // Walk over the classes and resolve them. If we cannot find a type we return
530 // kInlineCacheMissingTypes.
531 int ic_index = 0;
532 for (const ProfileCompilationInfo::ClassReference& class_ref : dex_pc_data.classes) {
533 ObjPtr<mirror::DexCache> dex_cache =
534 dex_profile_index_to_dex_cache[class_ref.dex_profile_index];
535 DCHECK(dex_cache != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000536 ObjPtr<mirror::Class> clazz = ClassLinker::LookupResolvedType(
537 class_ref.type_index,
538 dex_cache,
539 caller_compilation_unit_.GetClassLoader().Get());
Calin Juravle13439f02017-02-21 01:17:21 -0800540 if (clazz != nullptr) {
541 inline_cache->Set(ic_index++, clazz);
542 } else {
543 VLOG(compiler) << "Could not resolve class from inline cache in AOT mode "
544 << caller_compilation_unit_.GetDexFile()->PrettyMethod(
545 invoke_instruction->GetDexMethodIndex()) << " : "
546 << caller_compilation_unit_
547 .GetDexFile()->StringByTypeIdx(class_ref.type_index);
548 return kInlineCacheMissingTypes;
549 }
550 }
551 return GetInlineCacheType(inline_cache);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100552}
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000553
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000554HInstanceFieldGet* HInliner::BuildGetReceiverClass(ClassLinker* class_linker,
555 HInstruction* receiver,
556 uint32_t dex_pc) const {
557 ArtField* field = class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0);
558 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000559 HInstanceFieldGet* result = new (graph_->GetArena()) HInstanceFieldGet(
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000560 receiver,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000561 field,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000562 Primitive::kPrimNot,
563 field->GetOffset(),
564 field->IsVolatile(),
565 field->GetDexFieldIndex(),
566 field->GetDeclaringClass()->GetDexClassDefIndex(),
567 *field->GetDexFile(),
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000568 dex_pc);
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000569 // The class of a field is effectively final, and does not have any memory dependencies.
570 result->SetSideEffects(SideEffects::None());
571 return result;
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000572}
573
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100574bool HInliner::TryInlineMonomorphicCall(HInvoke* invoke_instruction,
575 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000576 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000577 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
578 << invoke_instruction->DebugName();
579
Andreas Gampea5b09a62016-11-17 15:21:22 -0800580 dex::TypeIndex class_index = FindClassIndexIn(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000581 GetMonomorphicType(classes), caller_compilation_unit_);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800582 if (!class_index.IsValid()) {
David Sehr709b0702016-10-13 09:12:37 -0700583 VLOG(compiler) << "Call to " << ArtMethod::PrettyMethod(resolved_method)
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100584 << " from inline cache is not inlined because its class is not"
585 << " accessible to the caller";
586 return false;
587 }
588
589 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700590 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100591 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000592 resolved_method = GetMonomorphicType(classes)->FindVirtualMethodForInterface(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100593 resolved_method, pointer_size);
594 } else {
595 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000596 resolved_method = GetMonomorphicType(classes)->FindVirtualMethodForVirtual(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100597 resolved_method, pointer_size);
598 }
599 DCHECK(resolved_method != nullptr);
600 HInstruction* receiver = invoke_instruction->InputAt(0);
601 HInstruction* cursor = invoke_instruction->GetPrevious();
602 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000603 Handle<mirror::Class> monomorphic_type = handles_->NewHandle(GetMonomorphicType(classes));
Mingyao Yang063fc772016-08-02 11:02:54 -0700604 if (!TryInlineAndReplace(invoke_instruction,
605 resolved_method,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000606 ReferenceTypeInfo::Create(monomorphic_type, /* is_exact */ true),
Mingyao Yang063fc772016-08-02 11:02:54 -0700607 /* do_rtp */ false,
608 /* cha_devirtualize */ false)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100609 return false;
610 }
611
612 // We successfully inlined, now add a guard.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000613 AddTypeGuard(receiver,
614 cursor,
615 bb_cursor,
616 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000617 monomorphic_type,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000618 invoke_instruction,
619 /* with_deoptimization */ true);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100620
621 // Run type propagation to get the guard typed, and eventually propagate the
622 // type of the receiver.
Vladimir Marko456307a2016-04-19 14:12:13 +0000623 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000624 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +0000625 outer_compilation_unit_.GetDexCache(),
626 handles_,
627 /* is_first_run */ false);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100628 rtp_fixup.Run();
629
630 MaybeRecordStat(kInlinedMonomorphicCall);
631 return true;
632}
633
Mingyao Yang063fc772016-08-02 11:02:54 -0700634void HInliner::AddCHAGuard(HInstruction* invoke_instruction,
635 uint32_t dex_pc,
636 HInstruction* cursor,
637 HBasicBlock* bb_cursor) {
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800638 HShouldDeoptimizeFlag* deopt_flag = new (graph_->GetArena())
639 HShouldDeoptimizeFlag(graph_->GetArena(), dex_pc);
640 HInstruction* compare = new (graph_->GetArena()) HNotEqual(
Mingyao Yang063fc772016-08-02 11:02:54 -0700641 deopt_flag, graph_->GetIntConstant(0, dex_pc));
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800642 HInstruction* deopt = new (graph_->GetArena()) HDeoptimize(compare, dex_pc);
Mingyao Yang063fc772016-08-02 11:02:54 -0700643
644 if (cursor != nullptr) {
645 bb_cursor->InsertInstructionAfter(deopt_flag, cursor);
646 } else {
647 bb_cursor->InsertInstructionBefore(deopt_flag, bb_cursor->GetFirstInstruction());
648 }
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800649 bb_cursor->InsertInstructionAfter(compare, deopt_flag);
650 bb_cursor->InsertInstructionAfter(deopt, compare);
651
652 // Add receiver as input to aid CHA guard optimization later.
653 deopt_flag->AddInput(invoke_instruction->InputAt(0));
654 DCHECK_EQ(deopt_flag->InputCount(), 1u);
Mingyao Yang063fc772016-08-02 11:02:54 -0700655 deopt->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800656 outermost_graph_->IncrementNumberOfCHAGuards();
Mingyao Yang063fc772016-08-02 11:02:54 -0700657}
658
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000659HInstruction* HInliner::AddTypeGuard(HInstruction* receiver,
660 HInstruction* cursor,
661 HBasicBlock* bb_cursor,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800662 dex::TypeIndex class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000663 Handle<mirror::Class> klass,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000664 HInstruction* invoke_instruction,
665 bool with_deoptimization) {
666 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
667 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
668 class_linker, receiver, invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000669 if (cursor != nullptr) {
670 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
671 } else {
672 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
673 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000674
675 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000676 bool is_referrer = (klass.Get() == outermost_graph_->GetArtMethod()->GetDeclaringClass());
Nicolas Geoffray56876342016-12-16 16:09:08 +0000677 // Note that we will just compare the classes, so we don't need Java semantics access checks.
678 // Note that the type index and the dex file are relative to the method this type guard is
679 // inlined into.
680 HLoadClass* load_class = new (graph_->GetArena()) HLoadClass(graph_->GetCurrentMethod(),
681 class_index,
682 caller_dex_file,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000683 klass,
Nicolas Geoffray56876342016-12-16 16:09:08 +0000684 is_referrer,
685 invoke_instruction->GetDexPc(),
686 /* needs_access_check */ false);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000687 HLoadClass::LoadKind kind = HSharpening::ComputeLoadClassKind(
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000688 load_class, codegen_, compiler_driver_, caller_compilation_unit_);
689 DCHECK(kind != HLoadClass::LoadKind::kInvalid)
690 << "We should always be able to reference a class for inline caches";
691 // Insert before setting the kind, as setting the kind affects the inputs.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000692 bb_cursor->InsertInstructionAfter(load_class, receiver_class);
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000693 load_class->SetLoadKind(kind);
Calin Juravle13439f02017-02-21 01:17:21 -0800694 // In AOT mode, we will most likely load the class from BSS, which will involve a call
695 // to the runtime. In this case, the load instruction will need an environment so copy
696 // it from the invoke instruction.
697 if (load_class->NeedsEnvironment()) {
698 DCHECK(Runtime::Current()->IsAotCompiler());
699 load_class->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
700 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000701
Nicolas Geoffray56876342016-12-16 16:09:08 +0000702 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(load_class, receiver_class);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000703 bb_cursor->InsertInstructionAfter(compare, load_class);
704 if (with_deoptimization) {
705 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
706 compare, invoke_instruction->GetDexPc());
707 bb_cursor->InsertInstructionAfter(deoptimize, compare);
708 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
709 }
710 return compare;
711}
712
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000713bool HInliner::TryInlinePolymorphicCall(HInvoke* invoke_instruction,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100714 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000715 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000716 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
717 << invoke_instruction->DebugName();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000718
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000719 if (TryInlinePolymorphicCallToSameTarget(invoke_instruction, resolved_method, classes)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000720 return true;
721 }
722
723 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700724 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000725
726 bool all_targets_inlined = true;
727 bool one_target_inlined = false;
728 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000729 if (classes->Get(i) == nullptr) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000730 break;
731 }
732 ArtMethod* method = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000733
734 Handle<mirror::Class> handle = handles_->NewHandle(classes->Get(i));
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000735 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000736 method = handle->FindVirtualMethodForInterface(resolved_method, pointer_size);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000737 } else {
738 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000739 method = handle->FindVirtualMethodForVirtual(resolved_method, pointer_size);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000740 }
741
742 HInstruction* receiver = invoke_instruction->InputAt(0);
743 HInstruction* cursor = invoke_instruction->GetPrevious();
744 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
745
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000746 dex::TypeIndex class_index = FindClassIndexIn(handle.Get(), caller_compilation_unit_);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000747 HInstruction* return_replacement = nullptr;
Andreas Gampea5b09a62016-11-17 15:21:22 -0800748 if (!class_index.IsValid() ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000749 !TryBuildAndInline(invoke_instruction,
750 method,
751 ReferenceTypeInfo::Create(handle, /* is_exact */ true),
752 &return_replacement)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000753 all_targets_inlined = false;
754 } else {
755 one_target_inlined = true;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000756
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000757 VLOG(compiler) << "Polymorphic call to " << ArtMethod::PrettyMethod(resolved_method)
758 << " has inlined " << ArtMethod::PrettyMethod(method);
759
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000760 // If we have inlined all targets before, and this receiver is the last seen,
761 // we deoptimize instead of keeping the original invoke instruction.
762 bool deoptimize = all_targets_inlined &&
763 (i != InlineCache::kIndividualCacheSize - 1) &&
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000764 (classes->Get(i + 1) == nullptr);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100765
766 if (outermost_graph_->IsCompilingOsr()) {
767 // We do not support HDeoptimize in OSR methods.
768 deoptimize = false;
769 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000770 HInstruction* compare = AddTypeGuard(receiver,
771 cursor,
772 bb_cursor,
773 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000774 handle,
Nicolas Geoffray56876342016-12-16 16:09:08 +0000775 invoke_instruction,
776 deoptimize);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000777 if (deoptimize) {
778 if (return_replacement != nullptr) {
779 invoke_instruction->ReplaceWith(return_replacement);
780 }
781 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
782 // Because the inline cache data can be populated concurrently, we force the end of the
783 // iteration. Otherhwise, we could see a new receiver type.
784 break;
785 } else {
786 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
787 }
788 }
789 }
790
791 if (!one_target_inlined) {
David Sehr709b0702016-10-13 09:12:37 -0700792 VLOG(compiler) << "Call to " << ArtMethod::PrettyMethod(resolved_method)
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000793 << " from inline cache is not inlined because none"
794 << " of its targets could be inlined";
795 return false;
796 }
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000797
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000798 MaybeRecordStat(kInlinedPolymorphicCall);
799
800 // Run type propagation to get the guards typed.
Vladimir Marko456307a2016-04-19 14:12:13 +0000801 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000802 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +0000803 outer_compilation_unit_.GetDexCache(),
804 handles_,
805 /* is_first_run */ false);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000806 rtp_fixup.Run();
807 return true;
808}
809
810void HInliner::CreateDiamondPatternForPolymorphicInline(HInstruction* compare,
811 HInstruction* return_replacement,
812 HInstruction* invoke_instruction) {
813 uint32_t dex_pc = invoke_instruction->GetDexPc();
814 HBasicBlock* cursor_block = compare->GetBlock();
815 HBasicBlock* original_invoke_block = invoke_instruction->GetBlock();
816 ArenaAllocator* allocator = graph_->GetArena();
817
818 // Spit the block after the compare: `cursor_block` will now be the start of the diamond,
819 // and the returned block is the start of the then branch (that could contain multiple blocks).
820 HBasicBlock* then = cursor_block->SplitAfterForInlining(compare);
821
822 // Split the block containing the invoke before and after the invoke. The returned block
823 // of the split before will contain the invoke and will be the otherwise branch of
824 // the diamond. The returned block of the split after will be the merge block
825 // of the diamond.
826 HBasicBlock* end_then = invoke_instruction->GetBlock();
827 HBasicBlock* otherwise = end_then->SplitBeforeForInlining(invoke_instruction);
828 HBasicBlock* merge = otherwise->SplitAfterForInlining(invoke_instruction);
829
830 // If the methods we are inlining return a value, we create a phi in the merge block
831 // that will have the `invoke_instruction and the `return_replacement` as inputs.
832 if (return_replacement != nullptr) {
833 HPhi* phi = new (allocator) HPhi(
834 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke_instruction->GetType()), dex_pc);
835 merge->AddPhi(phi);
836 invoke_instruction->ReplaceWith(phi);
837 phi->AddInput(return_replacement);
838 phi->AddInput(invoke_instruction);
839 }
840
841 // Add the control flow instructions.
842 otherwise->AddInstruction(new (allocator) HGoto(dex_pc));
843 end_then->AddInstruction(new (allocator) HGoto(dex_pc));
844 cursor_block->AddInstruction(new (allocator) HIf(compare, dex_pc));
845
846 // Add the newly created blocks to the graph.
847 graph_->AddBlock(then);
848 graph_->AddBlock(otherwise);
849 graph_->AddBlock(merge);
850
851 // Set up successor (and implictly predecessor) relations.
852 cursor_block->AddSuccessor(otherwise);
853 cursor_block->AddSuccessor(then);
854 end_then->AddSuccessor(merge);
855 otherwise->AddSuccessor(merge);
856
857 // Set up dominance information.
858 then->SetDominator(cursor_block);
859 cursor_block->AddDominatedBlock(then);
860 otherwise->SetDominator(cursor_block);
861 cursor_block->AddDominatedBlock(otherwise);
862 merge->SetDominator(cursor_block);
863 cursor_block->AddDominatedBlock(merge);
864
865 // Update the revert post order.
866 size_t index = IndexOfElement(graph_->reverse_post_order_, cursor_block);
867 MakeRoomFor(&graph_->reverse_post_order_, 1, index);
868 graph_->reverse_post_order_[++index] = then;
869 index = IndexOfElement(graph_->reverse_post_order_, end_then);
870 MakeRoomFor(&graph_->reverse_post_order_, 2, index);
871 graph_->reverse_post_order_[++index] = otherwise;
872 graph_->reverse_post_order_[++index] = merge;
873
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000874
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +0000875 graph_->UpdateLoopAndTryInformationOfNewBlock(
876 then, original_invoke_block, /* replace_if_back_edge */ false);
877 graph_->UpdateLoopAndTryInformationOfNewBlock(
878 otherwise, original_invoke_block, /* replace_if_back_edge */ false);
879
880 // In case the original invoke location was a back edge, we need to update
881 // the loop to now have the merge block as a back edge.
882 graph_->UpdateLoopAndTryInformationOfNewBlock(
883 merge, original_invoke_block, /* replace_if_back_edge */ true);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000884}
885
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000886bool HInliner::TryInlinePolymorphicCallToSameTarget(
887 HInvoke* invoke_instruction,
888 ArtMethod* resolved_method,
889 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000890 // This optimization only works under JIT for now.
Calin Juravle13439f02017-02-21 01:17:21 -0800891 if (!Runtime::Current()->UseJitCompilation()) {
892 return false;
893 }
894
Roland Levillain2aba7cd2016-02-03 12:27:20 +0000895 if (graph_->GetInstructionSet() == kMips64) {
896 // TODO: Support HClassTableGet for mips64.
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000897 return false;
898 }
899 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700900 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000901
902 DCHECK(resolved_method != nullptr);
903 ArtMethod* actual_method = nullptr;
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000904 size_t method_index = invoke_instruction->IsInvokeVirtual()
905 ? invoke_instruction->AsInvokeVirtual()->GetVTableIndex()
906 : invoke_instruction->AsInvokeInterface()->GetImtIndex();
907
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000908 // Check whether we are actually calling the same method among
909 // the different types seen.
910 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000911 if (classes->Get(i) == nullptr) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000912 break;
913 }
914 ArtMethod* new_method = nullptr;
915 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000916 new_method = classes->Get(i)->GetImt(pointer_size)->Get(
Matthew Gharrity465ecc82016-07-19 21:32:52 +0000917 method_index, pointer_size);
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000918 if (new_method->IsRuntimeMethod()) {
919 // Bail out as soon as we see a conflict trampoline in one of the target's
920 // interface table.
921 return false;
922 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000923 } else {
924 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000925 new_method = classes->Get(i)->GetEmbeddedVTableEntry(method_index, pointer_size);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000926 }
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000927 DCHECK(new_method != nullptr);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000928 if (actual_method == nullptr) {
929 actual_method = new_method;
930 } else if (actual_method != new_method) {
931 // Different methods, bailout.
David Sehr709b0702016-10-13 09:12:37 -0700932 VLOG(compiler) << "Call to " << ArtMethod::PrettyMethod(resolved_method)
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000933 << " from inline cache is not inlined because it resolves"
934 << " to different methods";
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000935 return false;
936 }
937 }
938
939 HInstruction* receiver = invoke_instruction->InputAt(0);
940 HInstruction* cursor = invoke_instruction->GetPrevious();
941 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
942
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100943 HInstruction* return_replacement = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000944 if (!TryBuildAndInline(invoke_instruction,
945 actual_method,
946 ReferenceTypeInfo::CreateInvalid(),
947 &return_replacement)) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000948 return false;
949 }
950
951 // We successfully inlined, now add a guard.
952 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
953 class_linker, receiver, invoke_instruction->GetDexPc());
954
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000955 Primitive::Type type = Is64BitInstructionSet(graph_->GetInstructionSet())
956 ? Primitive::kPrimLong
957 : Primitive::kPrimInt;
958 HClassTableGet* class_table_get = new (graph_->GetArena()) HClassTableGet(
959 receiver_class,
960 type,
Vladimir Markoa1de9182016-02-25 11:37:38 +0000961 invoke_instruction->IsInvokeVirtual() ? HClassTableGet::TableKind::kVTable
962 : HClassTableGet::TableKind::kIMTable,
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000963 method_index,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000964 invoke_instruction->GetDexPc());
965
966 HConstant* constant;
967 if (type == Primitive::kPrimLong) {
968 constant = graph_->GetLongConstant(
969 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
970 } else {
971 constant = graph_->GetIntConstant(
972 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
973 }
974
975 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(class_table_get, constant);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000976 if (cursor != nullptr) {
977 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
978 } else {
979 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
980 }
981 bb_cursor->InsertInstructionAfter(class_table_get, receiver_class);
982 bb_cursor->InsertInstructionAfter(compare, class_table_get);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100983
984 if (outermost_graph_->IsCompilingOsr()) {
985 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
986 } else {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100987 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
988 compare, invoke_instruction->GetDexPc());
989 bb_cursor->InsertInstructionAfter(deoptimize, compare);
990 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
991 if (return_replacement != nullptr) {
992 invoke_instruction->ReplaceWith(return_replacement);
993 }
Nicolas Geoffray1be7cbd2016-04-29 13:56:01 +0100994 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100995 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000996
997 // Run type propagation to get the guard typed.
Vladimir Marko456307a2016-04-19 14:12:13 +0000998 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000999 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +00001000 outer_compilation_unit_.GetDexCache(),
1001 handles_,
1002 /* is_first_run */ false);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001003 rtp_fixup.Run();
1004
1005 MaybeRecordStat(kInlinedPolymorphicCall);
1006
1007 return true;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001008}
1009
Mingyao Yang063fc772016-08-02 11:02:54 -07001010bool HInliner::TryInlineAndReplace(HInvoke* invoke_instruction,
1011 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001012 ReferenceTypeInfo receiver_type,
Mingyao Yang063fc772016-08-02 11:02:54 -07001013 bool do_rtp,
1014 bool cha_devirtualize) {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001015 HInstruction* return_replacement = nullptr;
Mingyao Yang063fc772016-08-02 11:02:54 -07001016 uint32_t dex_pc = invoke_instruction->GetDexPc();
1017 HInstruction* cursor = invoke_instruction->GetPrevious();
1018 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001019 if (!TryBuildAndInline(invoke_instruction, method, receiver_type, &return_replacement)) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001020 if (invoke_instruction->IsInvokeInterface()) {
1021 // Turn an invoke-interface into an invoke-virtual. An invoke-virtual is always
1022 // better than an invoke-interface because:
1023 // 1) In the best case, the interface call has one more indirection (to fetch the IMT).
1024 // 2) We will not go to the conflict trampoline with an invoke-virtual.
1025 // TODO: Consider sharpening once it is not dependent on the compiler driver.
1026 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001027 uint32_t dex_method_index = FindMethodIndexIn(
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001028 method, caller_dex_file, invoke_instruction->GetDexMethodIndex());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001029 if (dex_method_index == DexFile::kDexNoIndex) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001030 return false;
1031 }
1032 HInvokeVirtual* new_invoke = new (graph_->GetArena()) HInvokeVirtual(
1033 graph_->GetArena(),
1034 invoke_instruction->GetNumberOfArguments(),
1035 invoke_instruction->GetType(),
1036 invoke_instruction->GetDexPc(),
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001037 dex_method_index,
1038 method,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001039 method->GetMethodIndex());
1040 HInputsRef inputs = invoke_instruction->GetInputs();
1041 for (size_t index = 0; index != inputs.size(); ++index) {
1042 new_invoke->SetArgumentAt(index, inputs[index]);
1043 }
1044 invoke_instruction->GetBlock()->InsertInstructionBefore(new_invoke, invoke_instruction);
1045 new_invoke->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
1046 if (invoke_instruction->GetType() == Primitive::kPrimNot) {
1047 new_invoke->SetReferenceTypeInfo(invoke_instruction->GetReferenceTypeInfo());
1048 }
1049 return_replacement = new_invoke;
1050 } else {
1051 // TODO: Consider sharpening an invoke virtual once it is not dependent on the
1052 // compiler driver.
1053 return false;
1054 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001055 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001056 if (cha_devirtualize) {
1057 AddCHAGuard(invoke_instruction, dex_pc, cursor, bb_cursor);
1058 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001059 if (return_replacement != nullptr) {
1060 invoke_instruction->ReplaceWith(return_replacement);
1061 }
1062 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
David Brazdil94ab38f2016-06-21 17:48:19 +01001063 FixUpReturnReferenceType(method, return_replacement);
1064 if (do_rtp && ReturnTypeMoreSpecific(invoke_instruction, return_replacement)) {
1065 // Actual return value has a more specific type than the method's declared
1066 // return type. Run RTP again on the outer graph to propagate it.
1067 ReferenceTypePropagation(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001068 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +01001069 outer_compilation_unit_.GetDexCache(),
1070 handles_,
1071 /* is_first_run */ false).Run();
1072 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001073 return true;
1074}
1075
1076bool HInliner::TryBuildAndInline(HInvoke* invoke_instruction,
1077 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001078 ReferenceTypeInfo receiver_type,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001079 HInstruction** return_replacement) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001080 if (method->IsProxyMethod()) {
David Sehr709b0702016-10-13 09:12:37 -07001081 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001082 << " is not inlined because of unimplemented inline support for proxy methods.";
1083 return false;
1084 }
1085
Jeff Haodcdc85b2015-12-04 14:06:18 -08001086 // Check whether we're allowed to inline. The outermost compilation unit is the relevant
1087 // dex file here (though the transitivity of an inline chain would allow checking the calller).
1088 if (!compiler_driver_->MayInline(method->GetDexFile(),
1089 outer_compilation_unit_.GetDexFile())) {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001090 if (TryPatternSubstitution(invoke_instruction, method, return_replacement)) {
David Sehr709b0702016-10-13 09:12:37 -07001091 VLOG(compiler) << "Successfully replaced pattern of invoke "
1092 << method->PrettyMethod();
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001093 MaybeRecordStat(kReplacedInvokeWithSimplePattern);
1094 return true;
1095 }
David Sehr709b0702016-10-13 09:12:37 -07001096 VLOG(compiler) << "Won't inline " << method->PrettyMethod() << " in "
Jeff Haodcdc85b2015-12-04 14:06:18 -08001097 << outer_compilation_unit_.GetDexFile()->GetLocation() << " ("
1098 << caller_compilation_unit_.GetDexFile()->GetLocation() << ") from "
1099 << method->GetDexFile()->GetLocation();
1100 return false;
1101 }
1102
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001103 bool same_dex_file = IsSameDexFile(*outer_compilation_unit_.GetDexFile(), *method->GetDexFile());
1104
1105 const DexFile::CodeItem* code_item = method->GetCodeItem();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001106
1107 if (code_item == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07001108 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001109 << " is not inlined because it is native";
1110 return false;
1111 }
1112
Calin Juravleec748352015-07-29 13:52:12 +01001113 size_t inline_max_code_units = compiler_driver_->GetCompilerOptions().GetInlineMaxCodeUnits();
1114 if (code_item->insns_size_in_code_units_ > inline_max_code_units) {
David Sehr709b0702016-10-13 09:12:37 -07001115 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001116 << " is too big to inline: "
1117 << code_item->insns_size_in_code_units_
1118 << " > "
1119 << inline_max_code_units;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001120 return false;
1121 }
1122
1123 if (code_item->tries_size_ != 0) {
David Sehr709b0702016-10-13 09:12:37 -07001124 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001125 << " is not inlined because of try block";
1126 return false;
1127 }
1128
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001129 if (!method->IsCompilable()) {
David Sehr709b0702016-10-13 09:12:37 -07001130 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001131 << " has soft failures un-handled by the compiler, so it cannot be inlined";
1132 }
1133
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001134 if (!method->GetDeclaringClass()->IsVerified()) {
1135 uint16_t class_def_idx = method->GetDeclaringClass()->GetDexClassDefIndex();
Calin Juravleffc87072016-04-20 14:22:09 +01001136 if (Runtime::Current()->UseJitCompilation() ||
Nicolas Geoffray5b82d332016-02-18 14:22:32 +00001137 !compiler_driver_->IsMethodVerifiedWithoutFailures(
1138 method->GetDexMethodIndex(), class_def_idx, *method->GetDexFile())) {
David Sehr709b0702016-10-13 09:12:37 -07001139 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffrayccc61972015-10-01 14:34:20 +01001140 << " couldn't be verified, so it cannot be inlined";
1141 return false;
1142 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001143 }
1144
Roland Levillain4c0eb422015-04-24 16:43:49 +01001145 if (invoke_instruction->IsInvokeStaticOrDirect() &&
1146 invoke_instruction->AsInvokeStaticOrDirect()->IsStaticWithImplicitClinitCheck()) {
1147 // Case of a static method that cannot be inlined because it implicitly
1148 // requires an initialization check of its declaring class.
David Sehr709b0702016-10-13 09:12:37 -07001149 VLOG(compiler) << "Method " << method->PrettyMethod()
Roland Levillain4c0eb422015-04-24 16:43:49 +01001150 << " is not inlined because it is static and requires a clinit"
1151 << " check that cannot be emitted due to Dex cache limitations";
1152 return false;
1153 }
1154
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001155 if (!TryBuildAndInlineHelper(
1156 invoke_instruction, method, receiver_type, same_dex_file, return_replacement)) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001157 return false;
1158 }
1159
David Sehr709b0702016-10-13 09:12:37 -07001160 VLOG(compiler) << "Successfully inlined " << method->PrettyMethod();
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001161 MaybeRecordStat(kInlinedInvoke);
1162 return true;
1163}
1164
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001165static HInstruction* GetInvokeInputForArgVRegIndex(HInvoke* invoke_instruction,
1166 size_t arg_vreg_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001167 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001168 size_t input_index = 0;
1169 for (size_t i = 0; i < arg_vreg_index; ++i, ++input_index) {
1170 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
1171 if (Primitive::Is64BitType(invoke_instruction->InputAt(input_index)->GetType())) {
1172 ++i;
1173 DCHECK_NE(i, arg_vreg_index);
1174 }
1175 }
1176 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
1177 return invoke_instruction->InputAt(input_index);
1178}
1179
1180// Try to recognize known simple patterns and replace invoke call with appropriate instructions.
1181bool HInliner::TryPatternSubstitution(HInvoke* invoke_instruction,
1182 ArtMethod* resolved_method,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001183 HInstruction** return_replacement) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001184 InlineMethod inline_method;
1185 if (!InlineMethodAnalyser::AnalyseMethodCode(resolved_method, &inline_method)) {
1186 return false;
1187 }
1188
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001189 switch (inline_method.opcode) {
1190 case kInlineOpNop:
1191 DCHECK_EQ(invoke_instruction->GetType(), Primitive::kPrimVoid);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001192 *return_replacement = nullptr;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001193 break;
1194 case kInlineOpReturnArg:
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001195 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction,
1196 inline_method.d.return_data.arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001197 break;
1198 case kInlineOpNonWideConst:
1199 if (resolved_method->GetShorty()[0] == 'L') {
1200 DCHECK_EQ(inline_method.d.data, 0u);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001201 *return_replacement = graph_->GetNullConstant();
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001202 } else {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001203 *return_replacement = graph_->GetIntConstant(static_cast<int32_t>(inline_method.d.data));
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001204 }
1205 break;
1206 case kInlineOpIGet: {
1207 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1208 if (data.method_is_static || data.object_arg != 0u) {
1209 // TODO: Needs null check.
1210 return false;
1211 }
1212 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001213 HInstanceFieldGet* iget = CreateInstanceFieldGet(data.field_idx, resolved_method, obj);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001214 DCHECK_EQ(iget->GetFieldOffset().Uint32Value(), data.field_offset);
1215 DCHECK_EQ(iget->IsVolatile() ? 1u : 0u, data.is_volatile);
1216 invoke_instruction->GetBlock()->InsertInstructionBefore(iget, invoke_instruction);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001217 *return_replacement = iget;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001218 break;
1219 }
1220 case kInlineOpIPut: {
1221 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1222 if (data.method_is_static || data.object_arg != 0u) {
1223 // TODO: Needs null check.
1224 return false;
1225 }
1226 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
1227 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, data.src_arg);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001228 HInstanceFieldSet* iput = CreateInstanceFieldSet(data.field_idx, resolved_method, obj, value);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001229 DCHECK_EQ(iput->GetFieldOffset().Uint32Value(), data.field_offset);
1230 DCHECK_EQ(iput->IsVolatile() ? 1u : 0u, data.is_volatile);
1231 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1232 if (data.return_arg_plus1 != 0u) {
1233 size_t return_arg = data.return_arg_plus1 - 1u;
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001234 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction, return_arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001235 }
1236 break;
1237 }
Vladimir Marko354efa62016-02-04 19:46:56 +00001238 case kInlineOpConstructor: {
1239 const InlineConstructorData& data = inline_method.d.constructor_data;
1240 // Get the indexes to arrays for easier processing.
1241 uint16_t iput_field_indexes[] = {
1242 data.iput0_field_index, data.iput1_field_index, data.iput2_field_index
1243 };
1244 uint16_t iput_args[] = { data.iput0_arg, data.iput1_arg, data.iput2_arg };
1245 static_assert(arraysize(iput_args) == arraysize(iput_field_indexes), "Size mismatch");
1246 // Count valid field indexes.
1247 size_t number_of_iputs = 0u;
1248 while (number_of_iputs != arraysize(iput_field_indexes) &&
1249 iput_field_indexes[number_of_iputs] != DexFile::kDexNoIndex16) {
1250 // Check that there are no duplicate valid field indexes.
1251 DCHECK_EQ(0, std::count(iput_field_indexes + number_of_iputs + 1,
1252 iput_field_indexes + arraysize(iput_field_indexes),
1253 iput_field_indexes[number_of_iputs]));
1254 ++number_of_iputs;
1255 }
1256 // Check that there are no valid field indexes in the rest of the array.
1257 DCHECK_EQ(0, std::count_if(iput_field_indexes + number_of_iputs,
1258 iput_field_indexes + arraysize(iput_field_indexes),
1259 [](uint16_t index) { return index != DexFile::kDexNoIndex16; }));
1260
1261 // Create HInstanceFieldSet for each IPUT that stores non-zero data.
Vladimir Marko354efa62016-02-04 19:46:56 +00001262 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, /* this */ 0u);
1263 bool needs_constructor_barrier = false;
1264 for (size_t i = 0; i != number_of_iputs; ++i) {
1265 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, iput_args[i]);
Roland Levillain1a653882016-03-18 18:05:57 +00001266 if (!value->IsConstant() || !value->AsConstant()->IsZeroBitPattern()) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001267 uint16_t field_index = iput_field_indexes[i];
Vladimir Markof44d36c2017-03-14 14:18:46 +00001268 bool is_final;
1269 HInstanceFieldSet* iput =
1270 CreateInstanceFieldSet(field_index, resolved_method, obj, value, &is_final);
Vladimir Marko354efa62016-02-04 19:46:56 +00001271 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1272
1273 // Check whether the field is final. If it is, we need to add a barrier.
Vladimir Markof44d36c2017-03-14 14:18:46 +00001274 if (is_final) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001275 needs_constructor_barrier = true;
1276 }
1277 }
1278 }
1279 if (needs_constructor_barrier) {
1280 HMemoryBarrier* barrier = new (graph_->GetArena()) HMemoryBarrier(kStoreStore, kNoDexPc);
1281 invoke_instruction->GetBlock()->InsertInstructionBefore(barrier, invoke_instruction);
1282 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001283 *return_replacement = nullptr;
Vladimir Marko354efa62016-02-04 19:46:56 +00001284 break;
1285 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001286 default:
1287 LOG(FATAL) << "UNREACHABLE";
1288 UNREACHABLE();
1289 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001290 return true;
1291}
1292
Vladimir Markof44d36c2017-03-14 14:18:46 +00001293HInstanceFieldGet* HInliner::CreateInstanceFieldGet(uint32_t field_index,
1294 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001295 HInstruction* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001296 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001297 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1298 ArtField* resolved_field =
1299 class_linker->LookupResolvedField(field_index, referrer, /* is_static */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001300 DCHECK(resolved_field != nullptr);
1301 HInstanceFieldGet* iget = new (graph_->GetArena()) HInstanceFieldGet(
1302 obj,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001303 resolved_field,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001304 resolved_field->GetTypeAsPrimitiveType(),
1305 resolved_field->GetOffset(),
1306 resolved_field->IsVolatile(),
1307 field_index,
1308 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001309 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001310 // Read barrier generates a runtime call in slow path and we need a valid
1311 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1312 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001313 if (iget->GetType() == Primitive::kPrimNot) {
Vladimir Marko456307a2016-04-19 14:12:13 +00001314 // Use the same dex_cache that we used for field lookup as the hint_dex_cache.
Vladimir Markof44d36c2017-03-14 14:18:46 +00001315 Handle<mirror::DexCache> dex_cache = handles_->NewHandle(referrer->GetDexCache());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001316 ReferenceTypePropagation rtp(graph_,
1317 outer_compilation_unit_.GetClassLoader(),
1318 dex_cache,
1319 handles_,
1320 /* is_first_run */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001321 rtp.Visit(iget);
1322 }
1323 return iget;
1324}
1325
Vladimir Markof44d36c2017-03-14 14:18:46 +00001326HInstanceFieldSet* HInliner::CreateInstanceFieldSet(uint32_t field_index,
1327 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001328 HInstruction* obj,
Vladimir Markof44d36c2017-03-14 14:18:46 +00001329 HInstruction* value,
1330 bool* is_final)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001331 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001332 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1333 ArtField* resolved_field =
1334 class_linker->LookupResolvedField(field_index, referrer, /* is_static */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001335 DCHECK(resolved_field != nullptr);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001336 if (is_final != nullptr) {
1337 // This information is needed only for constructors.
1338 DCHECK(referrer->IsConstructor());
1339 *is_final = resolved_field->IsFinal();
1340 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001341 HInstanceFieldSet* iput = new (graph_->GetArena()) HInstanceFieldSet(
1342 obj,
1343 value,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001344 resolved_field,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001345 resolved_field->GetTypeAsPrimitiveType(),
1346 resolved_field->GetOffset(),
1347 resolved_field->IsVolatile(),
1348 field_index,
1349 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001350 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001351 // Read barrier generates a runtime call in slow path and we need a valid
1352 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1353 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001354 return iput;
1355}
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001356
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001357bool HInliner::TryBuildAndInlineHelper(HInvoke* invoke_instruction,
1358 ArtMethod* resolved_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001359 ReferenceTypeInfo receiver_type,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001360 bool same_dex_file,
1361 HInstruction** return_replacement) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001362 DCHECK(!(resolved_method->IsStatic() && receiver_type.IsValid()));
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001363 ScopedObjectAccess soa(Thread::Current());
1364 const DexFile::CodeItem* code_item = resolved_method->GetCodeItem();
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001365 const DexFile& callee_dex_file = *resolved_method->GetDexFile();
1366 uint32_t method_index = resolved_method->GetDexMethodIndex();
Calin Juravle2e768302015-07-28 14:41:11 +00001367 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Mathieu Chartier736b5602015-09-02 14:54:11 -07001368 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Nicolas Geoffrayf1aedb12016-07-28 03:49:14 +01001369 Handle<mirror::ClassLoader> class_loader(handles_->NewHandle(
1370 resolved_method->GetDeclaringClass()->GetClassLoader()));
1371
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001372 DexCompilationUnit dex_compilation_unit(
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001373 class_loader,
Nicolas Geoffray5b82d332016-02-18 14:22:32 +00001374 class_linker,
1375 callee_dex_file,
1376 code_item,
1377 resolved_method->GetDeclaringClass()->GetDexClassDefIndex(),
1378 method_index,
1379 resolved_method->GetAccessFlags(),
1380 /* verified_method */ nullptr,
1381 dex_cache);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001382
Calin Juravle3cd4fc82015-05-14 15:15:42 +01001383 bool requires_ctor_barrier = false;
1384
1385 if (dex_compilation_unit.IsConstructor()) {
1386 // If it's a super invocation and we already generate a barrier there's no need
1387 // to generate another one.
1388 // We identify super calls by looking at the "this" pointer. If its value is the
1389 // same as the local "this" pointer then we must have a super invocation.
1390 bool is_super_invocation = invoke_instruction->InputAt(0)->IsParameterValue()
1391 && invoke_instruction->InputAt(0)->AsParameterValue()->IsThis();
1392 if (is_super_invocation && graph_->ShouldGenerateConstructorBarrier()) {
1393 requires_ctor_barrier = false;
1394 } else {
1395 Thread* self = Thread::Current();
1396 requires_ctor_barrier = compiler_driver_->RequiresConstructorBarrier(self,
1397 dex_compilation_unit.GetDexFile(),
1398 dex_compilation_unit.GetClassDefIndex());
1399 }
1400 }
1401
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001402 InvokeType invoke_type = invoke_instruction->GetInvokeType();
Nicolas Geoffray35071052015-06-09 15:43:38 +01001403 if (invoke_type == kInterface) {
1404 // We have statically resolved the dispatch. To please the class linker
1405 // at runtime, we change this call as if it was a virtual call.
1406 invoke_type = kVirtual;
1407 }
David Brazdil3f523062016-02-29 16:53:33 +00001408
1409 const int32_t caller_instruction_counter = graph_->GetCurrentInstructionId();
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +00001410 HGraph* callee_graph = new (graph_->GetArena()) HGraph(
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001411 graph_->GetArena(),
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001412 callee_dex_file,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001413 method_index,
Calin Juravle3cd4fc82015-05-14 15:15:42 +01001414 requires_ctor_barrier,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001415 compiler_driver_->GetInstructionSet(),
Nicolas Geoffray35071052015-06-09 15:43:38 +01001416 invoke_type,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001417 graph_->IsDebuggable(),
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001418 /* osr */ false,
David Brazdil3f523062016-02-29 16:53:33 +00001419 caller_instruction_counter);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001420 callee_graph->SetArtMethod(resolved_method);
David Brazdil5e8b1372015-01-23 14:39:08 +00001421
Vladimir Marko438709f2017-02-23 18:56:13 +00001422 // When they are needed, allocate `inline_stats_` on the Arena instead
Roland Levillaina8013fd2016-04-04 15:34:31 +01001423 // of on the stack, as Clang might produce a stack frame too large
1424 // for this function, that would not fit the requirements of the
1425 // `-Wframe-larger-than` option.
Vladimir Marko438709f2017-02-23 18:56:13 +00001426 if (stats_ != nullptr) {
1427 // Reuse one object for all inline attempts from this caller to keep Arena memory usage low.
1428 if (inline_stats_ == nullptr) {
1429 void* storage = graph_->GetArena()->Alloc<OptimizingCompilerStats>(kArenaAllocMisc);
1430 inline_stats_ = new (storage) OptimizingCompilerStats;
1431 } else {
1432 inline_stats_->Reset();
1433 }
1434 }
David Brazdil5e8b1372015-01-23 14:39:08 +00001435 HGraphBuilder builder(callee_graph,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001436 &dex_compilation_unit,
1437 &outer_compilation_unit_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001438 resolved_method->GetDexFile(),
David Brazdil86ea7ee2016-02-16 09:26:07 +00001439 *code_item,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001440 compiler_driver_,
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00001441 codegen_,
Vladimir Marko438709f2017-02-23 18:56:13 +00001442 inline_stats_,
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001443 resolved_method->GetQuickenedInfo(class_linker->GetImagePointerSize()),
David Brazdildee58d62016-04-07 09:54:26 +00001444 dex_cache,
1445 handles_);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001446
David Brazdildee58d62016-04-07 09:54:26 +00001447 if (builder.BuildGraph() != kAnalysisSuccess) {
David Sehr709b0702016-10-13 09:12:37 -07001448 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001449 << " could not be built, so cannot be inlined";
1450 return false;
1451 }
1452
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001453 if (!RegisterAllocator::CanAllocateRegistersFor(*callee_graph,
1454 compiler_driver_->GetInstructionSet())) {
David Sehr709b0702016-10-13 09:12:37 -07001455 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001456 << " cannot be inlined because of the register allocator";
1457 return false;
1458 }
1459
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001460 size_t parameter_index = 0;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001461 bool run_rtp = false;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001462 for (HInstructionIterator instructions(callee_graph->GetEntryBlock()->GetInstructions());
1463 !instructions.Done();
1464 instructions.Advance()) {
1465 HInstruction* current = instructions.Current();
1466 if (current->IsParameterValue()) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001467 HInstruction* argument = invoke_instruction->InputAt(parameter_index);
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001468 if (argument->IsNullConstant()) {
1469 current->ReplaceWith(callee_graph->GetNullConstant());
1470 } else if (argument->IsIntConstant()) {
1471 current->ReplaceWith(callee_graph->GetIntConstant(argument->AsIntConstant()->GetValue()));
1472 } else if (argument->IsLongConstant()) {
1473 current->ReplaceWith(callee_graph->GetLongConstant(argument->AsLongConstant()->GetValue()));
1474 } else if (argument->IsFloatConstant()) {
1475 current->ReplaceWith(
1476 callee_graph->GetFloatConstant(argument->AsFloatConstant()->GetValue()));
1477 } else if (argument->IsDoubleConstant()) {
1478 current->ReplaceWith(
1479 callee_graph->GetDoubleConstant(argument->AsDoubleConstant()->GetValue()));
1480 } else if (argument->GetType() == Primitive::kPrimNot) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001481 if (!resolved_method->IsStatic() && parameter_index == 0 && receiver_type.IsValid()) {
1482 run_rtp = true;
1483 current->SetReferenceTypeInfo(receiver_type);
1484 } else {
1485 current->SetReferenceTypeInfo(argument->GetReferenceTypeInfo());
1486 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001487 current->AsParameterValue()->SetCanBeNull(argument->CanBeNull());
1488 }
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001489 ++parameter_index;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001490 }
1491 }
1492
David Brazdil94ab38f2016-06-21 17:48:19 +01001493 // We have replaced formal arguments with actual arguments. If actual types
1494 // are more specific than the declared ones, run RTP again on the inner graph.
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001495 if (run_rtp || ArgumentTypesMoreSpecific(invoke_instruction, resolved_method)) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001496 ReferenceTypePropagation(callee_graph,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001497 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +01001498 dex_compilation_unit.GetDexCache(),
1499 handles_,
1500 /* is_first_run */ false).Run();
1501 }
1502
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001503 size_t number_of_instructions_budget = kMaximumNumberOfHInstructions;
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001504 size_t number_of_inlined_instructions =
1505 RunOptimizations(callee_graph, code_item, dex_compilation_unit);
1506 number_of_instructions_budget += number_of_inlined_instructions;
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +00001507
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001508 HBasicBlock* exit_block = callee_graph->GetExitBlock();
1509 if (exit_block == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07001510 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001511 << " could not be inlined because it has an infinite loop";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001512 return false;
1513 }
1514
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001515 bool has_one_return = false;
Vladimir Marko60584552015-09-03 13:35:12 +00001516 for (HBasicBlock* predecessor : exit_block->GetPredecessors()) {
1517 if (predecessor->GetLastInstruction()->IsThrow()) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001518 if (invoke_instruction->GetBlock()->IsTryBlock()) {
1519 // TODO(ngeoffray): Support adding HTryBoundary in Hgraph::InlineInto.
1520 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1521 << " could not be inlined because one branch always throws and"
1522 << " caller is in a try/catch block";
1523 return false;
1524 } else if (graph_->GetExitBlock() == nullptr) {
1525 // TODO(ngeoffray): Support adding HExit in the caller graph.
1526 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1527 << " could not be inlined because one branch always throws and"
1528 << " caller does not have an exit block";
1529 return false;
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00001530 } else if (graph_->HasIrreducibleLoops()) {
1531 // TODO(ngeoffray): Support re-computing loop information to graphs with
1532 // irreducible loops?
1533 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1534 << " could not be inlined because one branch always throws and"
1535 << " caller has irreducible loops";
1536 return false;
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001537 }
1538 } else {
1539 has_one_return = true;
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001540 }
1541 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001542
1543 if (!has_one_return) {
David Sehr709b0702016-10-13 09:12:37 -07001544 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001545 << " could not be inlined because it always throws";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001546 return false;
1547 }
1548
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001549 size_t number_of_instructions = 0;
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001550
1551 bool can_inline_environment =
1552 total_number_of_dex_registers_ < kMaximumNumberOfCumulatedDexRegisters;
1553
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001554 // Skip the entry block, it does not contain instructions that prevent inlining.
1555 for (HBasicBlock* block : callee_graph->GetReversePostOrderSkipEntryBlock()) {
David Sehrc757dec2016-11-04 15:48:34 -07001556 if (block->IsLoopHeader()) {
1557 if (block->GetLoopInformation()->IsIrreducible()) {
1558 // Don't inline methods with irreducible loops, they could prevent some
1559 // optimizations to run.
1560 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1561 << " could not be inlined because it contains an irreducible loop";
1562 return false;
1563 }
1564 if (!block->GetLoopInformation()->HasExitEdge()) {
1565 // Don't inline methods with loops without exit, since they cause the
1566 // loop information to be computed incorrectly when updating after
1567 // inlining.
1568 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1569 << " could not be inlined because it contains a loop with no exit";
1570 return false;
1571 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001572 }
1573
1574 for (HInstructionIterator instr_it(block->GetInstructions());
1575 !instr_it.Done();
1576 instr_it.Advance()) {
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001577 if (number_of_instructions++ == number_of_instructions_budget) {
David Sehr709b0702016-10-13 09:12:37 -07001578 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001579 << " is not inlined because its caller has reached"
1580 << " its instruction budget limit.";
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001581 return false;
1582 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001583 HInstruction* current = instr_it.Current();
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001584 if (!can_inline_environment && current->NeedsEnvironment()) {
David Sehr709b0702016-10-13 09:12:37 -07001585 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001586 << " is not inlined because its caller has reached"
1587 << " its environment budget limit.";
1588 return false;
1589 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001590
Nicolas Geoffrayfbdfa6d2017-02-03 10:43:13 +00001591 if (current->NeedsEnvironment() &&
1592 !CanEncodeInlinedMethodInStackMap(*caller_compilation_unit_.GetDexFile(),
1593 resolved_method)) {
David Sehr709b0702016-10-13 09:12:37 -07001594 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001595 << " could not be inlined because " << current->DebugName()
Nicolas Geoffrayfbdfa6d2017-02-03 10:43:13 +00001596 << " needs an environment, is in a different dex file"
1597 << ", and cannot be encoded in the stack maps.";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001598 return false;
1599 }
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001600
Vladimir Markodc151b22015-10-15 18:02:30 +01001601 if (!same_dex_file && current->NeedsDexCacheOfDeclaringClass()) {
David Sehr709b0702016-10-13 09:12:37 -07001602 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001603 << " could not be inlined because " << current->DebugName()
1604 << " it is in a different dex file and requires access to the dex cache";
1605 return false;
1606 }
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001607
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001608 if (current->IsUnresolvedStaticFieldGet() ||
1609 current->IsUnresolvedInstanceFieldGet() ||
1610 current->IsUnresolvedStaticFieldSet() ||
1611 current->IsUnresolvedInstanceFieldSet()) {
1612 // Entrypoint for unresolved fields does not handle inlined frames.
David Sehr709b0702016-10-13 09:12:37 -07001613 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001614 << " could not be inlined because it is using an unresolved"
1615 << " entrypoint";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001616 return false;
1617 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001618 }
1619 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001620 number_of_inlined_instructions_ += number_of_instructions;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001621
David Brazdil3f523062016-02-29 16:53:33 +00001622 DCHECK_EQ(caller_instruction_counter, graph_->GetCurrentInstructionId())
1623 << "No instructions can be added to the outer graph while inner graph is being built";
1624
1625 const int32_t callee_instruction_counter = callee_graph->GetCurrentInstructionId();
1626 graph_->SetCurrentInstructionId(callee_instruction_counter);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001627 *return_replacement = callee_graph->InlineInto(graph_, invoke_instruction);
David Brazdil3f523062016-02-29 16:53:33 +00001628
1629 DCHECK_EQ(callee_instruction_counter, callee_graph->GetCurrentInstructionId())
1630 << "No instructions can be added to the inner graph during inlining into the outer graph";
1631
Vladimir Marko438709f2017-02-23 18:56:13 +00001632 if (stats_ != nullptr) {
1633 DCHECK(inline_stats_ != nullptr);
1634 inline_stats_->AddTo(stats_);
1635 }
1636
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001637 return true;
1638}
Calin Juravle2e768302015-07-28 14:41:11 +00001639
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001640size_t HInliner::RunOptimizations(HGraph* callee_graph,
1641 const DexFile::CodeItem* code_item,
1642 const DexCompilationUnit& dex_compilation_unit) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001643 // Note: if the outermost_graph_ is being compiled OSR, we should not run any
1644 // optimization that could lead to a HDeoptimize. The following optimizations do not.
Vladimir Marko438709f2017-02-23 18:56:13 +00001645 HDeadCodeElimination dce(callee_graph, inline_stats_, "dead_code_elimination$inliner");
Andreas Gampeca620d72016-11-08 08:09:33 -08001646 HConstantFolding fold(callee_graph, "constant_folding$inliner");
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001647 HSharpening sharpening(callee_graph, codegen_, dex_compilation_unit, compiler_driver_, handles_);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001648 InstructionSimplifier simplify(callee_graph, codegen_, inline_stats_);
Vladimir Marko438709f2017-02-23 18:56:13 +00001649 IntrinsicsRecognizer intrinsics(callee_graph, inline_stats_);
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001650
1651 HOptimization* optimizations[] = {
1652 &intrinsics,
1653 &sharpening,
1654 &simplify,
1655 &fold,
1656 &dce,
1657 };
1658
1659 for (size_t i = 0; i < arraysize(optimizations); ++i) {
1660 HOptimization* optimization = optimizations[i];
1661 optimization->Run();
1662 }
1663
1664 size_t number_of_inlined_instructions = 0u;
1665 if (depth_ + 1 < compiler_driver_->GetCompilerOptions().GetInlineDepthLimit()) {
1666 HInliner inliner(callee_graph,
1667 outermost_graph_,
1668 codegen_,
1669 outer_compilation_unit_,
1670 dex_compilation_unit,
1671 compiler_driver_,
1672 handles_,
Vladimir Marko438709f2017-02-23 18:56:13 +00001673 inline_stats_,
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001674 total_number_of_dex_registers_ + code_item->registers_size_,
1675 depth_ + 1);
1676 inliner.Run();
1677 number_of_inlined_instructions += inliner.number_of_inlined_instructions_;
1678 }
1679
1680 return number_of_inlined_instructions;
1681}
1682
David Brazdil94ab38f2016-06-21 17:48:19 +01001683static bool IsReferenceTypeRefinement(ReferenceTypeInfo declared_rti,
1684 bool declared_can_be_null,
1685 HInstruction* actual_obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001686 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001687 if (declared_can_be_null && !actual_obj->CanBeNull()) {
1688 return true;
1689 }
1690
1691 ReferenceTypeInfo actual_rti = actual_obj->GetReferenceTypeInfo();
1692 return (actual_rti.IsExact() && !declared_rti.IsExact()) ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001693 declared_rti.IsStrictSupertypeOf(actual_rti);
David Brazdil94ab38f2016-06-21 17:48:19 +01001694}
1695
1696ReferenceTypeInfo HInliner::GetClassRTI(mirror::Class* klass) {
1697 return ReferenceTypePropagation::IsAdmissible(klass)
1698 ? ReferenceTypeInfo::Create(handles_->NewHandle(klass))
1699 : graph_->GetInexactObjectRti();
1700}
1701
1702bool HInliner::ArgumentTypesMoreSpecific(HInvoke* invoke_instruction, ArtMethod* resolved_method) {
1703 // If this is an instance call, test whether the type of the `this` argument
1704 // is more specific than the class which declares the method.
1705 if (!resolved_method->IsStatic()) {
1706 if (IsReferenceTypeRefinement(GetClassRTI(resolved_method->GetDeclaringClass()),
1707 /* declared_can_be_null */ false,
1708 invoke_instruction->InputAt(0u))) {
1709 return true;
1710 }
1711 }
1712
David Brazdil94ab38f2016-06-21 17:48:19 +01001713 // Iterate over the list of parameter types and test whether any of the
1714 // actual inputs has a more specific reference type than the type declared in
1715 // the signature.
1716 const DexFile::TypeList* param_list = resolved_method->GetParameterTypeList();
1717 for (size_t param_idx = 0,
1718 input_idx = resolved_method->IsStatic() ? 0 : 1,
1719 e = (param_list == nullptr ? 0 : param_list->Size());
1720 param_idx < e;
1721 ++param_idx, ++input_idx) {
1722 HInstruction* input = invoke_instruction->InputAt(input_idx);
1723 if (input->GetType() == Primitive::kPrimNot) {
Vladimir Marko942fd312017-01-16 20:52:19 +00001724 mirror::Class* param_cls = resolved_method->GetClassFromTypeIndex(
David Brazdil94ab38f2016-06-21 17:48:19 +01001725 param_list->GetTypeItem(param_idx).type_idx_,
Vladimir Marko942fd312017-01-16 20:52:19 +00001726 /* resolve */ false);
David Brazdil94ab38f2016-06-21 17:48:19 +01001727 if (IsReferenceTypeRefinement(GetClassRTI(param_cls),
1728 /* declared_can_be_null */ true,
1729 input)) {
1730 return true;
1731 }
1732 }
1733 }
1734
1735 return false;
1736}
1737
1738bool HInliner::ReturnTypeMoreSpecific(HInvoke* invoke_instruction,
1739 HInstruction* return_replacement) {
Alex Light68289a52015-12-15 17:30:30 -08001740 // Check the integrity of reference types and run another type propagation if needed.
David Brazdil4833f5a2015-12-16 10:37:39 +00001741 if (return_replacement != nullptr) {
1742 if (return_replacement->GetType() == Primitive::kPrimNot) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001743 // Test if the return type is a refinement of the declared return type.
1744 if (IsReferenceTypeRefinement(invoke_instruction->GetReferenceTypeInfo(),
1745 /* declared_can_be_null */ true,
1746 return_replacement)) {
1747 return true;
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001748 } else if (return_replacement->IsInstanceFieldGet()) {
1749 HInstanceFieldGet* field_get = return_replacement->AsInstanceFieldGet();
1750 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1751 if (field_get->GetFieldInfo().GetField() ==
1752 class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0)) {
1753 return true;
1754 }
David Brazdil94ab38f2016-06-21 17:48:19 +01001755 }
1756 } else if (return_replacement->IsInstanceOf()) {
1757 // Inlining InstanceOf into an If may put a tighter bound on reference types.
1758 return true;
1759 }
1760 }
1761
1762 return false;
1763}
1764
1765void HInliner::FixUpReturnReferenceType(ArtMethod* resolved_method,
1766 HInstruction* return_replacement) {
1767 if (return_replacement != nullptr) {
1768 if (return_replacement->GetType() == Primitive::kPrimNot) {
David Brazdil4833f5a2015-12-16 10:37:39 +00001769 if (!return_replacement->GetReferenceTypeInfo().IsValid()) {
1770 // Make sure that we have a valid type for the return. We may get an invalid one when
1771 // we inline invokes with multiple branches and create a Phi for the result.
1772 // TODO: we could be more precise by merging the phi inputs but that requires
1773 // some functionality from the reference type propagation.
1774 DCHECK(return_replacement->IsPhi());
Vladimir Marko942fd312017-01-16 20:52:19 +00001775 mirror::Class* cls = resolved_method->GetReturnType(false /* resolve */);
David Brazdil94ab38f2016-06-21 17:48:19 +01001776 return_replacement->SetReferenceTypeInfo(GetClassRTI(cls));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001777 }
Calin Juravlecdfed3d2015-10-26 14:05:01 +00001778 }
Calin Juravle2e768302015-07-28 14:41:11 +00001779 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001780}
1781
1782} // namespace art