blob: f7331452c6f0f09df49e56b94fd6607fe89e233a [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 Geoffrayf6d46682017-02-28 17:41:45 +000049// Instruction limit to control memory.
50static constexpr size_t kMaximumNumberOfTotalInstructions = 1024;
51
52// Maximum number of instructions for considering a method small,
53// which we will always try to inline if the other non-instruction limits
54// are not reached.
55static constexpr size_t kMaximumNumberOfInstructionsForSmallMethod = 3;
Nicolas Geoffray5949fa02015-12-18 10:57:10 +000056
57// Limit the number of dex registers that we accumulate while inlining
58// to avoid creating large amount of nested environments.
59static constexpr size_t kMaximumNumberOfCumulatedDexRegisters = 64;
60
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000061// Limit recursive call inlining, which do not benefit from too
62// much inlining compared to code locality.
63static constexpr size_t kMaximumNumberOfRecursiveCalls = 4;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -070064
Calin Juravlee2492d42017-03-20 11:42:13 -070065// Controls the use of inline caches in AOT mode.
66static constexpr bool kUseAOTInlineCaches = false;
67
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000068// We check for line numbers to make sure the DepthString implementation
69// aligns the output nicely.
70#define LOG_INTERNAL(msg) \
71 static_assert(__LINE__ > 10, "Unhandled line number"); \
72 static_assert(__LINE__ < 10000, "Unhandled line number"); \
73 VLOG(compiler) << DepthString(__LINE__) << msg
74
75#define LOG_TRY() LOG_INTERNAL("Try inlinining call: ")
76#define LOG_NOTE() LOG_INTERNAL("Note: ")
77#define LOG_SUCCESS() LOG_INTERNAL("Success: ")
78#define LOG_FAIL(stat) MaybeRecordStat(stat); LOG_INTERNAL("Fail: ")
79#define LOG_FAIL_NO_STAT() LOG_INTERNAL("Fail: ")
80
81std::string HInliner::DepthString(int line) const {
82 std::string value;
83 // Indent according to the inlining depth.
84 size_t count = depth_;
85 // Line numbers get printed in the log, so add a space if the log's line is less
86 // than 1000, and two if less than 100. 10 cannot be reached as it's the copyright.
87 if (!kIsTargetBuild) {
88 if (line < 100) {
89 value += " ";
90 }
91 if (line < 1000) {
92 value += " ";
93 }
94 // Safeguard if this file reaches more than 10000 lines.
95 DCHECK_LT(line, 10000);
96 }
97 for (size_t i = 0; i < count; ++i) {
98 value += " ";
99 }
100 return value;
101}
102
103static size_t CountNumberOfInstructions(HGraph* graph) {
104 size_t number_of_instructions = 0;
105 for (HBasicBlock* block : graph->GetReversePostOrderSkipEntryBlock()) {
106 for (HInstructionIterator instr_it(block->GetInstructions());
107 !instr_it.Done();
108 instr_it.Advance()) {
109 ++number_of_instructions;
110 }
111 }
112 return number_of_instructions;
113}
114
115void HInliner::UpdateInliningBudget() {
116 if (total_number_of_instructions_ >= kMaximumNumberOfTotalInstructions) {
117 // Always try to inline small methods.
118 inlining_budget_ = kMaximumNumberOfInstructionsForSmallMethod;
119 } else {
120 inlining_budget_ = std::max(
121 kMaximumNumberOfInstructionsForSmallMethod,
122 kMaximumNumberOfTotalInstructions - total_number_of_instructions_);
123 }
124}
125
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000126void HInliner::Run() {
Nicolas Geoffraye50b8d22015-03-13 08:57:42 +0000127 if (graph_->IsDebuggable()) {
128 // For simplicity, we currently never inline when the graph is debuggable. This avoids
129 // doing some logic in the runtime to discover if a method could have been inlined.
130 return;
131 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000132
133 // Initialize the number of instructions for the method being compiled. Recursive calls
134 // to HInliner::Run have already updated the instruction count.
135 if (outermost_graph_ == graph_) {
136 total_number_of_instructions_ = CountNumberOfInstructions(graph_);
137 }
138
139 UpdateInliningBudget();
140 DCHECK_NE(total_number_of_instructions_, 0u);
141 DCHECK_NE(inlining_budget_, 0u);
142
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +0000143 // Keep a copy of all blocks when starting the visit.
144 ArenaVector<HBasicBlock*> blocks = graph_->GetReversePostOrder();
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100145 DCHECK(!blocks.empty());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +0000146 // Because we are changing the graph when inlining,
147 // we just iterate over the blocks of the outer method.
148 // This avoids doing the inlining work again on the inlined blocks.
149 for (HBasicBlock* block : blocks) {
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000150 for (HInstruction* instruction = block->GetFirstInstruction(); instruction != nullptr;) {
151 HInstruction* next = instruction->GetNext();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100152 HInvoke* call = instruction->AsInvoke();
Razvan A Lupusoru3e90a962015-03-27 13:44:44 -0700153 // As long as the call is not intrinsified, it is worth trying to inline.
154 if (call != nullptr && call->GetIntrinsic() == Intrinsics::kNone) {
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000155 if (kIsDebugBuild && IsCompilingWithCoreImage()) {
156 // Debugging case: directives in method names control or assert on inlining.
157 std::string callee_name = outer_compilation_unit_.GetDexFile()->PrettyMethod(
158 call->GetDexMethodIndex(), /* with_signature */ false);
159 // Tests prevent inlining by having $noinline$ in their method names.
160 if (callee_name.find("$noinline$") == std::string::npos) {
161 if (!TryInline(call)) {
162 bool should_have_inlined = (callee_name.find("$inline$") != std::string::npos);
163 CHECK(!should_have_inlined) << "Could not inline " << callee_name;
164 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000165 }
Guillaume "Vermeille" Sancheze918d382015-06-03 15:32:41 +0100166 } else {
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000167 // Normal case: try to inline.
168 TryInline(call);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000169 }
170 }
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000171 instruction = next;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000172 }
173 }
174}
175
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100176static bool IsMethodOrDeclaringClassFinal(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700177 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100178 return method->IsFinal() || method->GetDeclaringClass()->IsFinal();
179}
180
181/**
182 * Given the `resolved_method` looked up in the dex cache, try to find
183 * the actual runtime target of an interface or virtual call.
184 * Return nullptr if the runtime target cannot be proven.
185 */
186static ArtMethod* FindVirtualOrInterfaceTarget(HInvoke* invoke, ArtMethod* resolved_method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700187 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100188 if (IsMethodOrDeclaringClassFinal(resolved_method)) {
189 // No need to lookup further, the resolved method will be the target.
190 return resolved_method;
191 }
192
193 HInstruction* receiver = invoke->InputAt(0);
194 if (receiver->IsNullCheck()) {
195 // Due to multiple levels of inlining within the same pass, it might be that
196 // null check does not have the reference type of the actual receiver.
197 receiver = receiver->InputAt(0);
198 }
199 ReferenceTypeInfo info = receiver->GetReferenceTypeInfo();
Calin Juravle2e768302015-07-28 14:41:11 +0000200 DCHECK(info.IsValid()) << "Invalid RTI for " << receiver->DebugName();
201 if (!info.IsExact()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100202 // We currently only support inlining with known receivers.
203 // TODO: Remove this check, we should be able to inline final methods
204 // on unknown receivers.
205 return nullptr;
206 } else if (info.GetTypeHandle()->IsInterface()) {
207 // Statically knowing that the receiver has an interface type cannot
208 // help us find what is the target method.
209 return nullptr;
210 } else if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(info.GetTypeHandle().Get())) {
211 // The method that we're trying to call is not in the receiver's class or super classes.
212 return nullptr;
Nicolas Geoffrayab5327d2016-03-18 11:36:20 +0000213 } else if (info.GetTypeHandle()->IsErroneous()) {
214 // If the type is erroneous, do not go further, as we are going to query the vtable or
215 // imt table, that we can only safely do on non-erroneous classes.
216 return nullptr;
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100217 }
218
219 ClassLinker* cl = Runtime::Current()->GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700220 PointerSize pointer_size = cl->GetImagePointerSize();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100221 if (invoke->IsInvokeInterface()) {
222 resolved_method = info.GetTypeHandle()->FindVirtualMethodForInterface(
223 resolved_method, pointer_size);
224 } else {
225 DCHECK(invoke->IsInvokeVirtual());
226 resolved_method = info.GetTypeHandle()->FindVirtualMethodForVirtual(
227 resolved_method, pointer_size);
228 }
229
230 if (resolved_method == nullptr) {
231 // The information we had on the receiver was not enough to find
232 // the target method. Since we check above the exact type of the receiver,
233 // the only reason this can happen is an IncompatibleClassChangeError.
234 return nullptr;
Alex Light9139e002015-10-09 15:59:48 -0700235 } else if (!resolved_method->IsInvokable()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100236 // The information we had on the receiver was not enough to find
237 // the target method. Since we check above the exact type of the receiver,
238 // the only reason this can happen is an IncompatibleClassChangeError.
239 return nullptr;
240 } else if (IsMethodOrDeclaringClassFinal(resolved_method)) {
241 // A final method has to be the target method.
242 return resolved_method;
243 } else if (info.IsExact()) {
244 // If we found a method and the receiver's concrete type is statically
245 // known, we know for sure the target.
246 return resolved_method;
247 } else {
248 // Even if we did find a method, the receiver type was not enough to
249 // statically find the runtime target.
250 return nullptr;
251 }
252}
253
254static uint32_t FindMethodIndexIn(ArtMethod* method,
255 const DexFile& dex_file,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000256 uint32_t name_and_signature_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700257 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100258 if (IsSameDexFile(*method->GetDexFile(), dex_file)) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100259 return method->GetDexMethodIndex();
260 } else {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000261 return method->FindDexMethodIndexInOtherDexFile(dex_file, name_and_signature_index);
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100262 }
263}
264
Andreas Gampea5b09a62016-11-17 15:21:22 -0800265static dex::TypeIndex FindClassIndexIn(mirror::Class* cls,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000266 const DexCompilationUnit& compilation_unit)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700267 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000268 const DexFile& dex_file = *compilation_unit.GetDexFile();
Andreas Gampea5b09a62016-11-17 15:21:22 -0800269 dex::TypeIndex index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100270 if (cls->GetDexCache() == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700271 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000272 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800273 } else if (!cls->GetDexTypeIndex().IsValid()) {
David Sehr709b0702016-10-13 09:12:37 -0700274 DCHECK(cls->IsProxyClass()) << cls->PrettyClass();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100275 // TODO: deal with proxy classes.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100276 } else if (IsSameDexFile(cls->GetDexFile(), dex_file)) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000277 DCHECK_EQ(cls->GetDexCache(), compilation_unit.GetDexCache().Get());
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000278 index = cls->GetDexTypeIndex();
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100279 } else {
280 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000281 // We cannot guarantee the entry will resolve to the same class,
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100282 // as there may be different class loaders. So only return the index if it's
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000283 // the right class already resolved with the class loader.
284 if (index.IsValid()) {
285 ObjPtr<mirror::Class> resolved = ClassLinker::LookupResolvedType(
286 index, compilation_unit.GetDexCache().Get(), compilation_unit.GetClassLoader().Get());
287 if (resolved != cls) {
288 index = dex::TypeIndex::Invalid();
289 }
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100290 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100291 }
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000292
293 return index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100294}
295
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000296class ScopedProfilingInfoInlineUse {
297 public:
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000298 explicit ScopedProfilingInfoInlineUse(ArtMethod* method, Thread* self)
299 : method_(method),
300 self_(self),
301 // Fetch the profiling info ahead of using it. If it's null when fetching,
302 // we should not call JitCodeCache::DoneInlining.
303 profiling_info_(
304 Runtime::Current()->GetJit()->GetCodeCache()->NotifyCompilerUse(method, self)) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000305 }
306
307 ~ScopedProfilingInfoInlineUse() {
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000308 if (profiling_info_ != nullptr) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700309 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000310 DCHECK_EQ(profiling_info_, method_->GetProfilingInfo(pointer_size));
311 Runtime::Current()->GetJit()->GetCodeCache()->DoneCompilerUse(method_, self_);
312 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000313 }
314
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000315 ProfilingInfo* GetProfilingInfo() const { return profiling_info_; }
316
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000317 private:
318 ArtMethod* const method_;
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000319 Thread* const self_;
320 ProfilingInfo* const profiling_info_;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000321};
322
Calin Juravle13439f02017-02-21 01:17:21 -0800323HInliner::InlineCacheType HInliner::GetInlineCacheType(
324 const Handle<mirror::ObjectArray<mirror::Class>>& classes)
325 REQUIRES_SHARED(Locks::mutator_lock_) {
326 uint8_t number_of_types = 0;
327 for (; number_of_types < InlineCache::kIndividualCacheSize; ++number_of_types) {
328 if (classes->Get(number_of_types) == nullptr) {
329 break;
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000330 }
331 }
Calin Juravle13439f02017-02-21 01:17:21 -0800332
333 if (number_of_types == 0) {
334 return kInlineCacheUninitialized;
335 } else if (number_of_types == 1) {
336 return kInlineCacheMonomorphic;
337 } else if (number_of_types == InlineCache::kIndividualCacheSize) {
338 return kInlineCacheMegamorphic;
339 } else {
340 return kInlineCachePolymorphic;
341 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000342}
343
344static mirror::Class* GetMonomorphicType(Handle<mirror::ObjectArray<mirror::Class>> classes)
345 REQUIRES_SHARED(Locks::mutator_lock_) {
346 DCHECK(classes->Get(0) != nullptr);
347 return classes->Get(0);
348}
349
Mingyao Yang063fc772016-08-02 11:02:54 -0700350ArtMethod* HInliner::TryCHADevirtualization(ArtMethod* resolved_method) {
351 if (!resolved_method->HasSingleImplementation()) {
352 return nullptr;
353 }
354 if (Runtime::Current()->IsAotCompiler()) {
355 // No CHA-based devirtulization for AOT compiler (yet).
356 return nullptr;
357 }
358 if (outermost_graph_->IsCompilingOsr()) {
359 // We do not support HDeoptimize in OSR methods.
360 return nullptr;
361 }
Mingyao Yange8fcd012017-01-20 10:43:30 -0800362 PointerSize pointer_size = caller_compilation_unit_.GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +0000363 ArtMethod* single_impl = resolved_method->GetSingleImplementation(pointer_size);
364 if (single_impl == nullptr) {
365 return nullptr;
366 }
367 if (single_impl->IsProxyMethod()) {
368 // Proxy method is a generic invoker that's not worth
369 // devirtualizing/inlining. It also causes issues when the proxy
370 // method is in another dex file if we try to rewrite invoke-interface to
371 // invoke-virtual because a proxy method doesn't have a real dex file.
372 return nullptr;
373 }
374 return single_impl;
Mingyao Yang063fc772016-08-02 11:02:54 -0700375}
376
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700377bool HInliner::TryInline(HInvoke* invoke_instruction) {
Orion Hodsonac141392017-01-13 11:53:47 +0000378 if (invoke_instruction->IsInvokeUnresolved() ||
379 invoke_instruction->IsInvokePolymorphic()) {
380 return false; // Don't bother to move further if we know the method is unresolved or an
381 // invoke-polymorphic.
Calin Juravle175dc732015-08-25 15:42:32 +0100382 }
383
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000384 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100385 uint32_t method_index = invoke_instruction->GetDexMethodIndex();
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000386 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000387 LOG_TRY() << caller_dex_file.PrettyMethod(method_index);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000388
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100389 ArtMethod* resolved_method = invoke_instruction->GetResolvedMethod();
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100390 if (resolved_method == nullptr) {
391 DCHECK(invoke_instruction->IsInvokeStaticOrDirect());
392 DCHECK(invoke_instruction->AsInvokeStaticOrDirect()->IsStringInit());
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000393 LOG_FAIL_NO_STAT() << "Not inlining a String.<init> method";
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100394 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000395 }
396 ArtMethod* actual_method = nullptr;
397
398 if (invoke_instruction->IsInvokeStaticOrDirect()) {
Andreas Gampefd2140f2015-12-23 16:30:44 -0800399 actual_method = resolved_method;
Vladimir Marko58155012015-08-19 12:49:41 +0000400 } else {
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100401 // Check if we can statically find the method.
402 actual_method = FindVirtualOrInterfaceTarget(invoke_instruction, resolved_method);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000403 }
404
Mingyao Yang063fc772016-08-02 11:02:54 -0700405 bool cha_devirtualize = false;
406 if (actual_method == nullptr) {
407 ArtMethod* method = TryCHADevirtualization(resolved_method);
408 if (method != nullptr) {
409 cha_devirtualize = true;
410 actual_method = method;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000411 LOG_NOTE() << "Try CHA-based inlining of " << actual_method->PrettyMethod();
Mingyao Yang063fc772016-08-02 11:02:54 -0700412 }
413 }
414
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100415 if (actual_method != nullptr) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700416 bool result = TryInlineAndReplace(invoke_instruction,
417 actual_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000418 ReferenceTypeInfo::CreateInvalid(),
Mingyao Yang063fc772016-08-02 11:02:54 -0700419 /* do_rtp */ true,
420 cha_devirtualize);
Calin Juravle69158982016-03-16 11:53:41 +0000421 if (result && !invoke_instruction->IsInvokeStaticOrDirect()) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700422 if (cha_devirtualize) {
423 // Add dependency due to devirtulization. We've assumed resolved_method
424 // has single implementation.
425 outermost_graph_->AddCHASingleImplementationDependency(resolved_method);
426 MaybeRecordStat(kCHAInline);
427 } else {
428 MaybeRecordStat(kInlinedInvokeVirtualOrInterface);
429 }
Calin Juravle69158982016-03-16 11:53:41 +0000430 }
431 return result;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100432 }
Andreas Gampefd2140f2015-12-23 16:30:44 -0800433 DCHECK(!invoke_instruction->IsInvokeStaticOrDirect());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100434
Calin Juravle13439f02017-02-21 01:17:21 -0800435 // Try using inline caches.
436 return TryInlineFromInlineCache(caller_dex_file, invoke_instruction, resolved_method);
437}
438
439static Handle<mirror::ObjectArray<mirror::Class>> AllocateInlineCacheHolder(
440 const DexCompilationUnit& compilation_unit,
441 StackHandleScope<1>* hs)
442 REQUIRES_SHARED(Locks::mutator_lock_) {
443 Thread* self = Thread::Current();
444 ClassLinker* class_linker = compilation_unit.GetClassLinker();
445 Handle<mirror::ObjectArray<mirror::Class>> inline_cache = hs->NewHandle(
446 mirror::ObjectArray<mirror::Class>::Alloc(
447 self,
448 class_linker->GetClassRoot(ClassLinker::kClassArrayClass),
449 InlineCache::kIndividualCacheSize));
450 if (inline_cache == nullptr) {
451 // We got an OOME. Just clear the exception, and don't inline.
452 DCHECK(self->IsExceptionPending());
453 self->ClearException();
454 VLOG(compiler) << "Out of memory in the compiler when trying to inline";
455 }
456 return inline_cache;
457}
458
459bool HInliner::TryInlineFromInlineCache(const DexFile& caller_dex_file,
460 HInvoke* invoke_instruction,
461 ArtMethod* resolved_method)
462 REQUIRES_SHARED(Locks::mutator_lock_) {
Calin Juravlee2492d42017-03-20 11:42:13 -0700463 if (Runtime::Current()->IsAotCompiler() && !kUseAOTInlineCaches) {
464 return false;
465 }
466
Calin Juravle13439f02017-02-21 01:17:21 -0800467 StackHandleScope<1> hs(Thread::Current());
468 Handle<mirror::ObjectArray<mirror::Class>> inline_cache;
469 InlineCacheType inline_cache_type = Runtime::Current()->IsAotCompiler()
470 ? GetInlineCacheAOT(caller_dex_file, invoke_instruction, &hs, &inline_cache)
471 : GetInlineCacheJIT(invoke_instruction, &hs, &inline_cache);
472
473 switch (inline_cache_type) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000474 case kInlineCacheNoData: {
475 LOG_FAIL_NO_STAT()
476 << "Interface or virtual call to "
477 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
478 << " could not be statically determined";
Calin Juravle13439f02017-02-21 01:17:21 -0800479 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000480 }
Calin Juravle13439f02017-02-21 01:17:21 -0800481
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000482 case kInlineCacheUninitialized: {
483 LOG_FAIL_NO_STAT()
484 << "Interface or virtual call to "
485 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
486 << " is not hit and not inlined";
487 return false;
488 }
489
490 case kInlineCacheMonomorphic: {
Calin Juravle13439f02017-02-21 01:17:21 -0800491 MaybeRecordStat(kMonomorphicCall);
492 if (outermost_graph_->IsCompilingOsr()) {
493 // If we are compiling OSR, we pretend this call is polymorphic, as we may come from the
494 // interpreter and it may have seen different receiver types.
495 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000496 } else {
Calin Juravle13439f02017-02-21 01:17:21 -0800497 return TryInlineMonomorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000498 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000499 }
Calin Juravle13439f02017-02-21 01:17:21 -0800500
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000501 case kInlineCachePolymorphic: {
Calin Juravle13439f02017-02-21 01:17:21 -0800502 MaybeRecordStat(kPolymorphicCall);
503 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000504 }
Calin Juravle13439f02017-02-21 01:17:21 -0800505
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000506 case kInlineCacheMegamorphic: {
507 LOG_FAIL_NO_STAT()
508 << "Interface or virtual call to "
509 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
510 << " is megamorphic and not inlined";
Calin Juravle13439f02017-02-21 01:17:21 -0800511 MaybeRecordStat(kMegamorphicCall);
512 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000513 }
Calin Juravle13439f02017-02-21 01:17:21 -0800514
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000515 case kInlineCacheMissingTypes: {
516 LOG_FAIL_NO_STAT()
517 << "Interface or virtual call to "
518 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
519 << " is missing types and not inlined";
Calin Juravle13439f02017-02-21 01:17:21 -0800520 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000521 }
Calin Juravle13439f02017-02-21 01:17:21 -0800522 }
523 UNREACHABLE();
524}
525
526HInliner::InlineCacheType HInliner::GetInlineCacheJIT(
527 HInvoke* invoke_instruction,
528 StackHandleScope<1>* hs,
529 /*out*/Handle<mirror::ObjectArray<mirror::Class>>* inline_cache)
530 REQUIRES_SHARED(Locks::mutator_lock_) {
531 DCHECK(Runtime::Current()->UseJitCompilation());
532
533 ArtMethod* caller = graph_->GetArtMethod();
534 // Under JIT, we should always know the caller.
535 DCHECK(caller != nullptr);
536 ScopedProfilingInfoInlineUse spiis(caller, Thread::Current());
537 ProfilingInfo* profiling_info = spiis.GetProfilingInfo();
538
539 if (profiling_info == nullptr) {
540 return kInlineCacheNoData;
541 }
542
543 *inline_cache = AllocateInlineCacheHolder(caller_compilation_unit_, hs);
544 if (inline_cache->Get() == nullptr) {
545 // We can't extract any data if we failed to allocate;
546 return kInlineCacheNoData;
547 } else {
548 Runtime::Current()->GetJit()->GetCodeCache()->CopyInlineCacheInto(
549 *profiling_info->GetInlineCache(invoke_instruction->GetDexPc()),
550 *inline_cache);
551 return GetInlineCacheType(*inline_cache);
552 }
553}
554
555HInliner::InlineCacheType HInliner::GetInlineCacheAOT(
556 const DexFile& caller_dex_file,
557 HInvoke* invoke_instruction,
558 StackHandleScope<1>* hs,
559 /*out*/Handle<mirror::ObjectArray<mirror::Class>>* inline_cache)
560 REQUIRES_SHARED(Locks::mutator_lock_) {
561 DCHECK(Runtime::Current()->IsAotCompiler());
562 const ProfileCompilationInfo* pci = compiler_driver_->GetProfileCompilationInfo();
563 if (pci == nullptr) {
564 return kInlineCacheNoData;
565 }
566
567 ProfileCompilationInfo::OfflineProfileMethodInfo offline_profile;
568 bool found = pci->GetMethod(caller_dex_file.GetLocation(),
569 caller_dex_file.GetLocationChecksum(),
570 caller_compilation_unit_.GetDexMethodIndex(),
571 &offline_profile);
572 if (!found) {
573 return kInlineCacheNoData; // no profile information for this invocation.
574 }
575
576 *inline_cache = AllocateInlineCacheHolder(caller_compilation_unit_, hs);
577 if (inline_cache == nullptr) {
578 // We can't extract any data if we failed to allocate;
579 return kInlineCacheNoData;
580 } else {
581 return ExtractClassesFromOfflineProfile(invoke_instruction,
582 offline_profile,
583 *inline_cache);
584 }
585}
586
587HInliner::InlineCacheType HInliner::ExtractClassesFromOfflineProfile(
588 const HInvoke* invoke_instruction,
589 const ProfileCompilationInfo::OfflineProfileMethodInfo& offline_profile,
590 /*out*/Handle<mirror::ObjectArray<mirror::Class>> inline_cache)
591 REQUIRES_SHARED(Locks::mutator_lock_) {
592 const auto it = offline_profile.inline_caches.find(invoke_instruction->GetDexPc());
593 if (it == offline_profile.inline_caches.end()) {
594 return kInlineCacheUninitialized;
595 }
596
597 const ProfileCompilationInfo::DexPcData& dex_pc_data = it->second;
598
599 if (dex_pc_data.is_missing_types) {
600 return kInlineCacheMissingTypes;
601 }
602 if (dex_pc_data.is_megamorphic) {
603 return kInlineCacheMegamorphic;
604 }
605
606 DCHECK_LE(dex_pc_data.classes.size(), InlineCache::kIndividualCacheSize);
607 Thread* self = Thread::Current();
608 // We need to resolve the class relative to the containing dex file.
609 // So first, build a mapping from the index of dex file in the profile to
610 // its dex cache. This will avoid repeating the lookup when walking over
611 // the inline cache types.
612 std::vector<ObjPtr<mirror::DexCache>> dex_profile_index_to_dex_cache(
613 offline_profile.dex_references.size());
614 for (size_t i = 0; i < offline_profile.dex_references.size(); i++) {
615 bool found = false;
616 for (const DexFile* dex_file : compiler_driver_->GetDexFilesForOatFile()) {
617 if (offline_profile.dex_references[i].MatchesDex(dex_file)) {
618 dex_profile_index_to_dex_cache[i] =
619 caller_compilation_unit_.GetClassLinker()->FindDexCache(self, *dex_file);
620 found = true;
621 }
622 }
623 if (!found) {
624 VLOG(compiler) << "Could not find profiled dex file: "
625 << offline_profile.dex_references[i].dex_location;
626 return kInlineCacheMissingTypes;
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100627 }
628 }
629
Calin Juravle13439f02017-02-21 01:17:21 -0800630 // Walk over the classes and resolve them. If we cannot find a type we return
631 // kInlineCacheMissingTypes.
632 int ic_index = 0;
633 for (const ProfileCompilationInfo::ClassReference& class_ref : dex_pc_data.classes) {
634 ObjPtr<mirror::DexCache> dex_cache =
635 dex_profile_index_to_dex_cache[class_ref.dex_profile_index];
636 DCHECK(dex_cache != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000637 ObjPtr<mirror::Class> clazz = ClassLinker::LookupResolvedType(
638 class_ref.type_index,
639 dex_cache,
640 caller_compilation_unit_.GetClassLoader().Get());
Calin Juravle13439f02017-02-21 01:17:21 -0800641 if (clazz != nullptr) {
642 inline_cache->Set(ic_index++, clazz);
643 } else {
644 VLOG(compiler) << "Could not resolve class from inline cache in AOT mode "
645 << caller_compilation_unit_.GetDexFile()->PrettyMethod(
646 invoke_instruction->GetDexMethodIndex()) << " : "
647 << caller_compilation_unit_
648 .GetDexFile()->StringByTypeIdx(class_ref.type_index);
649 return kInlineCacheMissingTypes;
650 }
651 }
652 return GetInlineCacheType(inline_cache);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100653}
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000654
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000655HInstanceFieldGet* HInliner::BuildGetReceiverClass(ClassLinker* class_linker,
656 HInstruction* receiver,
657 uint32_t dex_pc) const {
658 ArtField* field = class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0);
659 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000660 HInstanceFieldGet* result = new (graph_->GetArena()) HInstanceFieldGet(
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000661 receiver,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000662 field,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000663 Primitive::kPrimNot,
664 field->GetOffset(),
665 field->IsVolatile(),
666 field->GetDexFieldIndex(),
667 field->GetDeclaringClass()->GetDexClassDefIndex(),
668 *field->GetDexFile(),
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000669 dex_pc);
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000670 // The class of a field is effectively final, and does not have any memory dependencies.
671 result->SetSideEffects(SideEffects::None());
672 return result;
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000673}
674
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100675bool HInliner::TryInlineMonomorphicCall(HInvoke* invoke_instruction,
676 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000677 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000678 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
679 << invoke_instruction->DebugName();
680
Andreas Gampea5b09a62016-11-17 15:21:22 -0800681 dex::TypeIndex class_index = FindClassIndexIn(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000682 GetMonomorphicType(classes), caller_compilation_unit_);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800683 if (!class_index.IsValid()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000684 LOG_FAIL(kNotInlinedDexCache)
685 << "Call to " << ArtMethod::PrettyMethod(resolved_method)
686 << " from inline cache is not inlined because its class is not"
687 << " accessible to the caller";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100688 return false;
689 }
690
691 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700692 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100693 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000694 resolved_method = GetMonomorphicType(classes)->FindVirtualMethodForInterface(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100695 resolved_method, pointer_size);
696 } else {
697 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000698 resolved_method = GetMonomorphicType(classes)->FindVirtualMethodForVirtual(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100699 resolved_method, pointer_size);
700 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000701 LOG_NOTE() << "Try inline monomorphic call to " << resolved_method->PrettyMethod();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100702 DCHECK(resolved_method != nullptr);
703 HInstruction* receiver = invoke_instruction->InputAt(0);
704 HInstruction* cursor = invoke_instruction->GetPrevious();
705 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000706 Handle<mirror::Class> monomorphic_type = handles_->NewHandle(GetMonomorphicType(classes));
Mingyao Yang063fc772016-08-02 11:02:54 -0700707 if (!TryInlineAndReplace(invoke_instruction,
708 resolved_method,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000709 ReferenceTypeInfo::Create(monomorphic_type, /* is_exact */ true),
Mingyao Yang063fc772016-08-02 11:02:54 -0700710 /* do_rtp */ false,
711 /* cha_devirtualize */ false)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100712 return false;
713 }
714
715 // We successfully inlined, now add a guard.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000716 AddTypeGuard(receiver,
717 cursor,
718 bb_cursor,
719 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000720 monomorphic_type,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000721 invoke_instruction,
722 /* with_deoptimization */ true);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100723
724 // Run type propagation to get the guard typed, and eventually propagate the
725 // type of the receiver.
Vladimir Marko456307a2016-04-19 14:12:13 +0000726 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000727 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +0000728 outer_compilation_unit_.GetDexCache(),
729 handles_,
730 /* is_first_run */ false);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100731 rtp_fixup.Run();
732
733 MaybeRecordStat(kInlinedMonomorphicCall);
734 return true;
735}
736
Mingyao Yang063fc772016-08-02 11:02:54 -0700737void HInliner::AddCHAGuard(HInstruction* invoke_instruction,
738 uint32_t dex_pc,
739 HInstruction* cursor,
740 HBasicBlock* bb_cursor) {
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800741 HShouldDeoptimizeFlag* deopt_flag = new (graph_->GetArena())
742 HShouldDeoptimizeFlag(graph_->GetArena(), dex_pc);
743 HInstruction* compare = new (graph_->GetArena()) HNotEqual(
Mingyao Yang063fc772016-08-02 11:02:54 -0700744 deopt_flag, graph_->GetIntConstant(0, dex_pc));
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800745 HInstruction* deopt = new (graph_->GetArena()) HDeoptimize(compare, dex_pc);
Mingyao Yang063fc772016-08-02 11:02:54 -0700746
747 if (cursor != nullptr) {
748 bb_cursor->InsertInstructionAfter(deopt_flag, cursor);
749 } else {
750 bb_cursor->InsertInstructionBefore(deopt_flag, bb_cursor->GetFirstInstruction());
751 }
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800752 bb_cursor->InsertInstructionAfter(compare, deopt_flag);
753 bb_cursor->InsertInstructionAfter(deopt, compare);
754
755 // Add receiver as input to aid CHA guard optimization later.
756 deopt_flag->AddInput(invoke_instruction->InputAt(0));
757 DCHECK_EQ(deopt_flag->InputCount(), 1u);
Mingyao Yang063fc772016-08-02 11:02:54 -0700758 deopt->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800759 outermost_graph_->IncrementNumberOfCHAGuards();
Mingyao Yang063fc772016-08-02 11:02:54 -0700760}
761
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000762HInstruction* HInliner::AddTypeGuard(HInstruction* receiver,
763 HInstruction* cursor,
764 HBasicBlock* bb_cursor,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800765 dex::TypeIndex class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000766 Handle<mirror::Class> klass,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000767 HInstruction* invoke_instruction,
768 bool with_deoptimization) {
769 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
770 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
771 class_linker, receiver, invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000772 if (cursor != nullptr) {
773 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
774 } else {
775 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
776 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000777
778 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000779 bool is_referrer = (klass.Get() == outermost_graph_->GetArtMethod()->GetDeclaringClass());
Nicolas Geoffray56876342016-12-16 16:09:08 +0000780 // Note that we will just compare the classes, so we don't need Java semantics access checks.
781 // Note that the type index and the dex file are relative to the method this type guard is
782 // inlined into.
783 HLoadClass* load_class = new (graph_->GetArena()) HLoadClass(graph_->GetCurrentMethod(),
784 class_index,
785 caller_dex_file,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000786 klass,
Nicolas Geoffray56876342016-12-16 16:09:08 +0000787 is_referrer,
788 invoke_instruction->GetDexPc(),
789 /* needs_access_check */ false);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000790 HLoadClass::LoadKind kind = HSharpening::ComputeLoadClassKind(
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000791 load_class, codegen_, compiler_driver_, caller_compilation_unit_);
792 DCHECK(kind != HLoadClass::LoadKind::kInvalid)
793 << "We should always be able to reference a class for inline caches";
794 // Insert before setting the kind, as setting the kind affects the inputs.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000795 bb_cursor->InsertInstructionAfter(load_class, receiver_class);
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000796 load_class->SetLoadKind(kind);
Calin Juravle13439f02017-02-21 01:17:21 -0800797 // In AOT mode, we will most likely load the class from BSS, which will involve a call
798 // to the runtime. In this case, the load instruction will need an environment so copy
799 // it from the invoke instruction.
800 if (load_class->NeedsEnvironment()) {
801 DCHECK(Runtime::Current()->IsAotCompiler());
802 load_class->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
803 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000804
Nicolas Geoffray56876342016-12-16 16:09:08 +0000805 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(load_class, receiver_class);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000806 bb_cursor->InsertInstructionAfter(compare, load_class);
807 if (with_deoptimization) {
808 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
809 compare, invoke_instruction->GetDexPc());
810 bb_cursor->InsertInstructionAfter(deoptimize, compare);
811 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
812 }
813 return compare;
814}
815
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000816bool HInliner::TryInlinePolymorphicCall(HInvoke* invoke_instruction,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100817 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000818 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000819 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
820 << invoke_instruction->DebugName();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000821
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000822 if (TryInlinePolymorphicCallToSameTarget(invoke_instruction, resolved_method, classes)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000823 return true;
824 }
825
826 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700827 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000828
829 bool all_targets_inlined = true;
830 bool one_target_inlined = false;
831 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000832 if (classes->Get(i) == nullptr) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000833 break;
834 }
835 ArtMethod* method = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000836
837 Handle<mirror::Class> handle = handles_->NewHandle(classes->Get(i));
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000838 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000839 method = handle->FindVirtualMethodForInterface(resolved_method, pointer_size);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000840 } else {
841 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000842 method = handle->FindVirtualMethodForVirtual(resolved_method, pointer_size);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000843 }
844
845 HInstruction* receiver = invoke_instruction->InputAt(0);
846 HInstruction* cursor = invoke_instruction->GetPrevious();
847 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
848
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000849 dex::TypeIndex class_index = FindClassIndexIn(handle.Get(), caller_compilation_unit_);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000850 HInstruction* return_replacement = nullptr;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000851 LOG_NOTE() << "Try inline polymorphic call to " << method->PrettyMethod();
Andreas Gampea5b09a62016-11-17 15:21:22 -0800852 if (!class_index.IsValid() ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000853 !TryBuildAndInline(invoke_instruction,
854 method,
855 ReferenceTypeInfo::Create(handle, /* is_exact */ true),
856 &return_replacement)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000857 all_targets_inlined = false;
858 } else {
859 one_target_inlined = true;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000860
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000861 LOG_SUCCESS() << "Polymorphic call to " << ArtMethod::PrettyMethod(resolved_method)
862 << " has inlined " << ArtMethod::PrettyMethod(method);
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000863
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000864 // If we have inlined all targets before, and this receiver is the last seen,
865 // we deoptimize instead of keeping the original invoke instruction.
866 bool deoptimize = all_targets_inlined &&
867 (i != InlineCache::kIndividualCacheSize - 1) &&
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000868 (classes->Get(i + 1) == nullptr);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100869
870 if (outermost_graph_->IsCompilingOsr()) {
871 // We do not support HDeoptimize in OSR methods.
872 deoptimize = false;
873 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000874 HInstruction* compare = AddTypeGuard(receiver,
875 cursor,
876 bb_cursor,
877 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000878 handle,
Nicolas Geoffray56876342016-12-16 16:09:08 +0000879 invoke_instruction,
880 deoptimize);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000881 if (deoptimize) {
882 if (return_replacement != nullptr) {
883 invoke_instruction->ReplaceWith(return_replacement);
884 }
885 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
886 // Because the inline cache data can be populated concurrently, we force the end of the
887 // iteration. Otherhwise, we could see a new receiver type.
888 break;
889 } else {
890 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
891 }
892 }
893 }
894
895 if (!one_target_inlined) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000896 LOG_FAIL_NO_STAT()
897 << "Call to " << ArtMethod::PrettyMethod(resolved_method)
898 << " from inline cache is not inlined because none"
899 << " of its targets could be inlined";
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000900 return false;
901 }
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000902
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000903 MaybeRecordStat(kInlinedPolymorphicCall);
904
905 // Run type propagation to get the guards typed.
Vladimir Marko456307a2016-04-19 14:12:13 +0000906 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000907 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +0000908 outer_compilation_unit_.GetDexCache(),
909 handles_,
910 /* is_first_run */ false);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000911 rtp_fixup.Run();
912 return true;
913}
914
915void HInliner::CreateDiamondPatternForPolymorphicInline(HInstruction* compare,
916 HInstruction* return_replacement,
917 HInstruction* invoke_instruction) {
918 uint32_t dex_pc = invoke_instruction->GetDexPc();
919 HBasicBlock* cursor_block = compare->GetBlock();
920 HBasicBlock* original_invoke_block = invoke_instruction->GetBlock();
921 ArenaAllocator* allocator = graph_->GetArena();
922
923 // Spit the block after the compare: `cursor_block` will now be the start of the diamond,
924 // and the returned block is the start of the then branch (that could contain multiple blocks).
925 HBasicBlock* then = cursor_block->SplitAfterForInlining(compare);
926
927 // Split the block containing the invoke before and after the invoke. The returned block
928 // of the split before will contain the invoke and will be the otherwise branch of
929 // the diamond. The returned block of the split after will be the merge block
930 // of the diamond.
931 HBasicBlock* end_then = invoke_instruction->GetBlock();
932 HBasicBlock* otherwise = end_then->SplitBeforeForInlining(invoke_instruction);
933 HBasicBlock* merge = otherwise->SplitAfterForInlining(invoke_instruction);
934
935 // If the methods we are inlining return a value, we create a phi in the merge block
936 // that will have the `invoke_instruction and the `return_replacement` as inputs.
937 if (return_replacement != nullptr) {
938 HPhi* phi = new (allocator) HPhi(
939 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke_instruction->GetType()), dex_pc);
940 merge->AddPhi(phi);
941 invoke_instruction->ReplaceWith(phi);
942 phi->AddInput(return_replacement);
943 phi->AddInput(invoke_instruction);
944 }
945
946 // Add the control flow instructions.
947 otherwise->AddInstruction(new (allocator) HGoto(dex_pc));
948 end_then->AddInstruction(new (allocator) HGoto(dex_pc));
949 cursor_block->AddInstruction(new (allocator) HIf(compare, dex_pc));
950
951 // Add the newly created blocks to the graph.
952 graph_->AddBlock(then);
953 graph_->AddBlock(otherwise);
954 graph_->AddBlock(merge);
955
956 // Set up successor (and implictly predecessor) relations.
957 cursor_block->AddSuccessor(otherwise);
958 cursor_block->AddSuccessor(then);
959 end_then->AddSuccessor(merge);
960 otherwise->AddSuccessor(merge);
961
962 // Set up dominance information.
963 then->SetDominator(cursor_block);
964 cursor_block->AddDominatedBlock(then);
965 otherwise->SetDominator(cursor_block);
966 cursor_block->AddDominatedBlock(otherwise);
967 merge->SetDominator(cursor_block);
968 cursor_block->AddDominatedBlock(merge);
969
970 // Update the revert post order.
971 size_t index = IndexOfElement(graph_->reverse_post_order_, cursor_block);
972 MakeRoomFor(&graph_->reverse_post_order_, 1, index);
973 graph_->reverse_post_order_[++index] = then;
974 index = IndexOfElement(graph_->reverse_post_order_, end_then);
975 MakeRoomFor(&graph_->reverse_post_order_, 2, index);
976 graph_->reverse_post_order_[++index] = otherwise;
977 graph_->reverse_post_order_[++index] = merge;
978
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000979
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +0000980 graph_->UpdateLoopAndTryInformationOfNewBlock(
981 then, original_invoke_block, /* replace_if_back_edge */ false);
982 graph_->UpdateLoopAndTryInformationOfNewBlock(
983 otherwise, original_invoke_block, /* replace_if_back_edge */ false);
984
985 // In case the original invoke location was a back edge, we need to update
986 // the loop to now have the merge block as a back edge.
987 graph_->UpdateLoopAndTryInformationOfNewBlock(
988 merge, original_invoke_block, /* replace_if_back_edge */ true);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000989}
990
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000991bool HInliner::TryInlinePolymorphicCallToSameTarget(
992 HInvoke* invoke_instruction,
993 ArtMethod* resolved_method,
994 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000995 // This optimization only works under JIT for now.
Calin Juravle13439f02017-02-21 01:17:21 -0800996 if (!Runtime::Current()->UseJitCompilation()) {
997 return false;
998 }
999
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001000 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -07001001 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001002
1003 DCHECK(resolved_method != nullptr);
1004 ArtMethod* actual_method = nullptr;
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001005 size_t method_index = invoke_instruction->IsInvokeVirtual()
1006 ? invoke_instruction->AsInvokeVirtual()->GetVTableIndex()
1007 : invoke_instruction->AsInvokeInterface()->GetImtIndex();
1008
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001009 // Check whether we are actually calling the same method among
1010 // the different types seen.
1011 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001012 if (classes->Get(i) == nullptr) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001013 break;
1014 }
1015 ArtMethod* new_method = nullptr;
1016 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001017 new_method = classes->Get(i)->GetImt(pointer_size)->Get(
Matthew Gharrity465ecc82016-07-19 21:32:52 +00001018 method_index, pointer_size);
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001019 if (new_method->IsRuntimeMethod()) {
1020 // Bail out as soon as we see a conflict trampoline in one of the target's
1021 // interface table.
1022 return false;
1023 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001024 } else {
1025 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001026 new_method = classes->Get(i)->GetEmbeddedVTableEntry(method_index, pointer_size);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001027 }
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001028 DCHECK(new_method != nullptr);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001029 if (actual_method == nullptr) {
1030 actual_method = new_method;
1031 } else if (actual_method != new_method) {
1032 // Different methods, bailout.
1033 return false;
1034 }
1035 }
1036
1037 HInstruction* receiver = invoke_instruction->InputAt(0);
1038 HInstruction* cursor = invoke_instruction->GetPrevious();
1039 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
1040
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001041 HInstruction* return_replacement = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001042 if (!TryBuildAndInline(invoke_instruction,
1043 actual_method,
1044 ReferenceTypeInfo::CreateInvalid(),
1045 &return_replacement)) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001046 return false;
1047 }
1048
1049 // We successfully inlined, now add a guard.
1050 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
1051 class_linker, receiver, invoke_instruction->GetDexPc());
1052
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001053 Primitive::Type type = Is64BitInstructionSet(graph_->GetInstructionSet())
1054 ? Primitive::kPrimLong
1055 : Primitive::kPrimInt;
1056 HClassTableGet* class_table_get = new (graph_->GetArena()) HClassTableGet(
1057 receiver_class,
1058 type,
Vladimir Markoa1de9182016-02-25 11:37:38 +00001059 invoke_instruction->IsInvokeVirtual() ? HClassTableGet::TableKind::kVTable
1060 : HClassTableGet::TableKind::kIMTable,
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001061 method_index,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001062 invoke_instruction->GetDexPc());
1063
1064 HConstant* constant;
1065 if (type == Primitive::kPrimLong) {
1066 constant = graph_->GetLongConstant(
1067 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
1068 } else {
1069 constant = graph_->GetIntConstant(
1070 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
1071 }
1072
1073 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(class_table_get, constant);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001074 if (cursor != nullptr) {
1075 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
1076 } else {
1077 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
1078 }
1079 bb_cursor->InsertInstructionAfter(class_table_get, receiver_class);
1080 bb_cursor->InsertInstructionAfter(compare, class_table_get);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001081
1082 if (outermost_graph_->IsCompilingOsr()) {
1083 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
1084 } else {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001085 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
1086 compare, invoke_instruction->GetDexPc());
1087 bb_cursor->InsertInstructionAfter(deoptimize, compare);
1088 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
1089 if (return_replacement != nullptr) {
1090 invoke_instruction->ReplaceWith(return_replacement);
1091 }
Nicolas Geoffray1be7cbd2016-04-29 13:56:01 +01001092 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001093 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001094
1095 // Run type propagation to get the guard typed.
Vladimir Marko456307a2016-04-19 14:12:13 +00001096 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001097 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +00001098 outer_compilation_unit_.GetDexCache(),
1099 handles_,
1100 /* is_first_run */ false);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001101 rtp_fixup.Run();
1102
1103 MaybeRecordStat(kInlinedPolymorphicCall);
1104
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001105 LOG_SUCCESS() << "Inlined same polymorphic target " << actual_method->PrettyMethod();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001106 return true;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001107}
1108
Mingyao Yang063fc772016-08-02 11:02:54 -07001109bool HInliner::TryInlineAndReplace(HInvoke* invoke_instruction,
1110 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001111 ReferenceTypeInfo receiver_type,
Mingyao Yang063fc772016-08-02 11:02:54 -07001112 bool do_rtp,
1113 bool cha_devirtualize) {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001114 HInstruction* return_replacement = nullptr;
Mingyao Yang063fc772016-08-02 11:02:54 -07001115 uint32_t dex_pc = invoke_instruction->GetDexPc();
1116 HInstruction* cursor = invoke_instruction->GetPrevious();
1117 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001118 if (!TryBuildAndInline(invoke_instruction, method, receiver_type, &return_replacement)) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001119 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +00001120 DCHECK(!method->IsProxyMethod());
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001121 // Turn an invoke-interface into an invoke-virtual. An invoke-virtual is always
1122 // better than an invoke-interface because:
1123 // 1) In the best case, the interface call has one more indirection (to fetch the IMT).
1124 // 2) We will not go to the conflict trampoline with an invoke-virtual.
1125 // TODO: Consider sharpening once it is not dependent on the compiler driver.
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +00001126
1127 if (method->IsDefault() && !method->IsCopied()) {
1128 // Changing to invoke-virtual cannot be done on an original default method
1129 // since it's not in any vtable. Devirtualization by exact type/inline-cache
1130 // always uses a method in the iftable which is never an original default
1131 // method.
1132 // On the other hand, inlining an original default method by CHA is fine.
1133 DCHECK(cha_devirtualize);
1134 return false;
1135 }
1136
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001137 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001138 uint32_t dex_method_index = FindMethodIndexIn(
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001139 method, caller_dex_file, invoke_instruction->GetDexMethodIndex());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001140 if (dex_method_index == DexFile::kDexNoIndex) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001141 return false;
1142 }
1143 HInvokeVirtual* new_invoke = new (graph_->GetArena()) HInvokeVirtual(
1144 graph_->GetArena(),
1145 invoke_instruction->GetNumberOfArguments(),
1146 invoke_instruction->GetType(),
1147 invoke_instruction->GetDexPc(),
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001148 dex_method_index,
1149 method,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001150 method->GetMethodIndex());
1151 HInputsRef inputs = invoke_instruction->GetInputs();
1152 for (size_t index = 0; index != inputs.size(); ++index) {
1153 new_invoke->SetArgumentAt(index, inputs[index]);
1154 }
1155 invoke_instruction->GetBlock()->InsertInstructionBefore(new_invoke, invoke_instruction);
1156 new_invoke->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
1157 if (invoke_instruction->GetType() == Primitive::kPrimNot) {
1158 new_invoke->SetReferenceTypeInfo(invoke_instruction->GetReferenceTypeInfo());
1159 }
1160 return_replacement = new_invoke;
1161 } else {
1162 // TODO: Consider sharpening an invoke virtual once it is not dependent on the
1163 // compiler driver.
1164 return false;
1165 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001166 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001167 if (cha_devirtualize) {
1168 AddCHAGuard(invoke_instruction, dex_pc, cursor, bb_cursor);
1169 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001170 if (return_replacement != nullptr) {
1171 invoke_instruction->ReplaceWith(return_replacement);
1172 }
1173 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
David Brazdil94ab38f2016-06-21 17:48:19 +01001174 FixUpReturnReferenceType(method, return_replacement);
1175 if (do_rtp && ReturnTypeMoreSpecific(invoke_instruction, return_replacement)) {
1176 // Actual return value has a more specific type than the method's declared
1177 // return type. Run RTP again on the outer graph to propagate it.
1178 ReferenceTypePropagation(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001179 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +01001180 outer_compilation_unit_.GetDexCache(),
1181 handles_,
1182 /* is_first_run */ false).Run();
1183 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001184 return true;
1185}
1186
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001187size_t HInliner::CountRecursiveCallsOf(ArtMethod* method) const {
1188 const HInliner* current = this;
1189 size_t count = 0;
1190 do {
1191 if (current->graph_->GetArtMethod() == method) {
1192 ++count;
1193 }
1194 current = current->parent_;
1195 } while (current != nullptr);
1196 return count;
1197}
1198
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001199bool HInliner::TryBuildAndInline(HInvoke* invoke_instruction,
1200 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001201 ReferenceTypeInfo receiver_type,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001202 HInstruction** return_replacement) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001203 if (method->IsProxyMethod()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001204 LOG_FAIL(kNotInlinedProxy)
1205 << "Method " << method->PrettyMethod()
1206 << " is not inlined because of unimplemented inline support for proxy methods.";
1207 return false;
1208 }
1209
1210 if (CountRecursiveCallsOf(method) > kMaximumNumberOfRecursiveCalls) {
1211 LOG_FAIL(kNotInlinedRecursiveBudget)
1212 << "Method "
1213 << method->PrettyMethod()
1214 << " is not inlined because it has reached its recursive call budget.";
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001215 return false;
1216 }
1217
Jeff Haodcdc85b2015-12-04 14:06:18 -08001218 // Check whether we're allowed to inline. The outermost compilation unit is the relevant
1219 // dex file here (though the transitivity of an inline chain would allow checking the calller).
1220 if (!compiler_driver_->MayInline(method->GetDexFile(),
1221 outer_compilation_unit_.GetDexFile())) {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001222 if (TryPatternSubstitution(invoke_instruction, method, return_replacement)) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001223 LOG_SUCCESS() << "Successfully replaced pattern of invoke "
1224 << method->PrettyMethod();
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001225 MaybeRecordStat(kReplacedInvokeWithSimplePattern);
1226 return true;
1227 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001228 LOG_FAIL(kNotInlinedWont)
1229 << "Won't inline " << method->PrettyMethod() << " in "
1230 << outer_compilation_unit_.GetDexFile()->GetLocation() << " ("
1231 << caller_compilation_unit_.GetDexFile()->GetLocation() << ") from "
1232 << method->GetDexFile()->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001233 return false;
1234 }
1235
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001236 bool same_dex_file = IsSameDexFile(*outer_compilation_unit_.GetDexFile(), *method->GetDexFile());
1237
1238 const DexFile::CodeItem* code_item = method->GetCodeItem();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001239
1240 if (code_item == nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001241 LOG_FAIL_NO_STAT()
1242 << "Method " << method->PrettyMethod() << " is not inlined because it is native";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001243 return false;
1244 }
1245
Calin Juravleec748352015-07-29 13:52:12 +01001246 size_t inline_max_code_units = compiler_driver_->GetCompilerOptions().GetInlineMaxCodeUnits();
1247 if (code_item->insns_size_in_code_units_ > inline_max_code_units) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001248 LOG_FAIL(kNotInlinedCodeItem)
1249 << "Method " << method->PrettyMethod()
1250 << " is not inlined because its code item is too big: "
1251 << code_item->insns_size_in_code_units_
1252 << " > "
1253 << inline_max_code_units;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001254 return false;
1255 }
1256
1257 if (code_item->tries_size_ != 0) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001258 LOG_FAIL(kNotInlinedTryCatch)
1259 << "Method " << method->PrettyMethod() << " is not inlined because of try block";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001260 return false;
1261 }
1262
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001263 if (!method->IsCompilable()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001264 LOG_FAIL(kNotInlinedNotVerified)
1265 << "Method " << method->PrettyMethod()
1266 << " has soft failures un-handled by the compiler, so it cannot be inlined";
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001267 }
1268
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001269 if (!method->GetDeclaringClass()->IsVerified()) {
1270 uint16_t class_def_idx = method->GetDeclaringClass()->GetDexClassDefIndex();
Calin Juravleffc87072016-04-20 14:22:09 +01001271 if (Runtime::Current()->UseJitCompilation() ||
Nicolas Geoffray5b82d332016-02-18 14:22:32 +00001272 !compiler_driver_->IsMethodVerifiedWithoutFailures(
1273 method->GetDexMethodIndex(), class_def_idx, *method->GetDexFile())) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001274 LOG_FAIL(kNotInlinedNotVerified)
1275 << "Method " << method->PrettyMethod()
1276 << " couldn't be verified, so it cannot be inlined";
Nicolas Geoffrayccc61972015-10-01 14:34:20 +01001277 return false;
1278 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001279 }
1280
Roland Levillain4c0eb422015-04-24 16:43:49 +01001281 if (invoke_instruction->IsInvokeStaticOrDirect() &&
1282 invoke_instruction->AsInvokeStaticOrDirect()->IsStaticWithImplicitClinitCheck()) {
1283 // Case of a static method that cannot be inlined because it implicitly
1284 // requires an initialization check of its declaring class.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001285 LOG_FAIL(kNotInlinedDexCache) << "Method " << method->PrettyMethod()
1286 << " is not inlined because it is static and requires a clinit"
1287 << " check that cannot be emitted due to Dex cache limitations";
Roland Levillain4c0eb422015-04-24 16:43:49 +01001288 return false;
1289 }
1290
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001291 if (!TryBuildAndInlineHelper(
1292 invoke_instruction, method, receiver_type, same_dex_file, return_replacement)) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001293 return false;
1294 }
1295
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001296 LOG_SUCCESS() << method->PrettyMethod();
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001297 MaybeRecordStat(kInlinedInvoke);
1298 return true;
1299}
1300
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001301static HInstruction* GetInvokeInputForArgVRegIndex(HInvoke* invoke_instruction,
1302 size_t arg_vreg_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001303 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001304 size_t input_index = 0;
1305 for (size_t i = 0; i < arg_vreg_index; ++i, ++input_index) {
1306 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
1307 if (Primitive::Is64BitType(invoke_instruction->InputAt(input_index)->GetType())) {
1308 ++i;
1309 DCHECK_NE(i, arg_vreg_index);
1310 }
1311 }
1312 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
1313 return invoke_instruction->InputAt(input_index);
1314}
1315
1316// Try to recognize known simple patterns and replace invoke call with appropriate instructions.
1317bool HInliner::TryPatternSubstitution(HInvoke* invoke_instruction,
1318 ArtMethod* resolved_method,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001319 HInstruction** return_replacement) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001320 InlineMethod inline_method;
1321 if (!InlineMethodAnalyser::AnalyseMethodCode(resolved_method, &inline_method)) {
1322 return false;
1323 }
1324
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001325 switch (inline_method.opcode) {
1326 case kInlineOpNop:
1327 DCHECK_EQ(invoke_instruction->GetType(), Primitive::kPrimVoid);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001328 *return_replacement = nullptr;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001329 break;
1330 case kInlineOpReturnArg:
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001331 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction,
1332 inline_method.d.return_data.arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001333 break;
1334 case kInlineOpNonWideConst:
1335 if (resolved_method->GetShorty()[0] == 'L') {
1336 DCHECK_EQ(inline_method.d.data, 0u);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001337 *return_replacement = graph_->GetNullConstant();
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001338 } else {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001339 *return_replacement = graph_->GetIntConstant(static_cast<int32_t>(inline_method.d.data));
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001340 }
1341 break;
1342 case kInlineOpIGet: {
1343 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1344 if (data.method_is_static || data.object_arg != 0u) {
1345 // TODO: Needs null check.
1346 return false;
1347 }
1348 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001349 HInstanceFieldGet* iget = CreateInstanceFieldGet(data.field_idx, resolved_method, obj);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001350 DCHECK_EQ(iget->GetFieldOffset().Uint32Value(), data.field_offset);
1351 DCHECK_EQ(iget->IsVolatile() ? 1u : 0u, data.is_volatile);
1352 invoke_instruction->GetBlock()->InsertInstructionBefore(iget, invoke_instruction);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001353 *return_replacement = iget;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001354 break;
1355 }
1356 case kInlineOpIPut: {
1357 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1358 if (data.method_is_static || data.object_arg != 0u) {
1359 // TODO: Needs null check.
1360 return false;
1361 }
1362 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
1363 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, data.src_arg);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001364 HInstanceFieldSet* iput = CreateInstanceFieldSet(data.field_idx, resolved_method, obj, value);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001365 DCHECK_EQ(iput->GetFieldOffset().Uint32Value(), data.field_offset);
1366 DCHECK_EQ(iput->IsVolatile() ? 1u : 0u, data.is_volatile);
1367 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1368 if (data.return_arg_plus1 != 0u) {
1369 size_t return_arg = data.return_arg_plus1 - 1u;
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001370 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction, return_arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001371 }
1372 break;
1373 }
Vladimir Marko354efa62016-02-04 19:46:56 +00001374 case kInlineOpConstructor: {
1375 const InlineConstructorData& data = inline_method.d.constructor_data;
1376 // Get the indexes to arrays for easier processing.
1377 uint16_t iput_field_indexes[] = {
1378 data.iput0_field_index, data.iput1_field_index, data.iput2_field_index
1379 };
1380 uint16_t iput_args[] = { data.iput0_arg, data.iput1_arg, data.iput2_arg };
1381 static_assert(arraysize(iput_args) == arraysize(iput_field_indexes), "Size mismatch");
1382 // Count valid field indexes.
1383 size_t number_of_iputs = 0u;
1384 while (number_of_iputs != arraysize(iput_field_indexes) &&
1385 iput_field_indexes[number_of_iputs] != DexFile::kDexNoIndex16) {
1386 // Check that there are no duplicate valid field indexes.
1387 DCHECK_EQ(0, std::count(iput_field_indexes + number_of_iputs + 1,
1388 iput_field_indexes + arraysize(iput_field_indexes),
1389 iput_field_indexes[number_of_iputs]));
1390 ++number_of_iputs;
1391 }
1392 // Check that there are no valid field indexes in the rest of the array.
1393 DCHECK_EQ(0, std::count_if(iput_field_indexes + number_of_iputs,
1394 iput_field_indexes + arraysize(iput_field_indexes),
1395 [](uint16_t index) { return index != DexFile::kDexNoIndex16; }));
1396
1397 // Create HInstanceFieldSet for each IPUT that stores non-zero data.
Vladimir Marko354efa62016-02-04 19:46:56 +00001398 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, /* this */ 0u);
1399 bool needs_constructor_barrier = false;
1400 for (size_t i = 0; i != number_of_iputs; ++i) {
1401 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, iput_args[i]);
Roland Levillain1a653882016-03-18 18:05:57 +00001402 if (!value->IsConstant() || !value->AsConstant()->IsZeroBitPattern()) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001403 uint16_t field_index = iput_field_indexes[i];
Vladimir Markof44d36c2017-03-14 14:18:46 +00001404 bool is_final;
1405 HInstanceFieldSet* iput =
1406 CreateInstanceFieldSet(field_index, resolved_method, obj, value, &is_final);
Vladimir Marko354efa62016-02-04 19:46:56 +00001407 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1408
1409 // Check whether the field is final. If it is, we need to add a barrier.
Vladimir Markof44d36c2017-03-14 14:18:46 +00001410 if (is_final) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001411 needs_constructor_barrier = true;
1412 }
1413 }
1414 }
1415 if (needs_constructor_barrier) {
1416 HMemoryBarrier* barrier = new (graph_->GetArena()) HMemoryBarrier(kStoreStore, kNoDexPc);
1417 invoke_instruction->GetBlock()->InsertInstructionBefore(barrier, invoke_instruction);
1418 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001419 *return_replacement = nullptr;
Vladimir Marko354efa62016-02-04 19:46:56 +00001420 break;
1421 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001422 default:
1423 LOG(FATAL) << "UNREACHABLE";
1424 UNREACHABLE();
1425 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001426 return true;
1427}
1428
Vladimir Markof44d36c2017-03-14 14:18:46 +00001429HInstanceFieldGet* HInliner::CreateInstanceFieldGet(uint32_t field_index,
1430 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001431 HInstruction* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001432 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001433 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1434 ArtField* resolved_field =
1435 class_linker->LookupResolvedField(field_index, referrer, /* is_static */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001436 DCHECK(resolved_field != nullptr);
1437 HInstanceFieldGet* iget = new (graph_->GetArena()) HInstanceFieldGet(
1438 obj,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001439 resolved_field,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001440 resolved_field->GetTypeAsPrimitiveType(),
1441 resolved_field->GetOffset(),
1442 resolved_field->IsVolatile(),
1443 field_index,
1444 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001445 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001446 // Read barrier generates a runtime call in slow path and we need a valid
1447 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1448 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001449 if (iget->GetType() == Primitive::kPrimNot) {
Vladimir Marko456307a2016-04-19 14:12:13 +00001450 // Use the same dex_cache that we used for field lookup as the hint_dex_cache.
Vladimir Markof44d36c2017-03-14 14:18:46 +00001451 Handle<mirror::DexCache> dex_cache = handles_->NewHandle(referrer->GetDexCache());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001452 ReferenceTypePropagation rtp(graph_,
1453 outer_compilation_unit_.GetClassLoader(),
1454 dex_cache,
1455 handles_,
1456 /* is_first_run */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001457 rtp.Visit(iget);
1458 }
1459 return iget;
1460}
1461
Vladimir Markof44d36c2017-03-14 14:18:46 +00001462HInstanceFieldSet* HInliner::CreateInstanceFieldSet(uint32_t field_index,
1463 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001464 HInstruction* obj,
Vladimir Markof44d36c2017-03-14 14:18:46 +00001465 HInstruction* value,
1466 bool* is_final)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001467 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001468 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1469 ArtField* resolved_field =
1470 class_linker->LookupResolvedField(field_index, referrer, /* is_static */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001471 DCHECK(resolved_field != nullptr);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001472 if (is_final != nullptr) {
1473 // This information is needed only for constructors.
1474 DCHECK(referrer->IsConstructor());
1475 *is_final = resolved_field->IsFinal();
1476 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001477 HInstanceFieldSet* iput = new (graph_->GetArena()) HInstanceFieldSet(
1478 obj,
1479 value,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001480 resolved_field,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001481 resolved_field->GetTypeAsPrimitiveType(),
1482 resolved_field->GetOffset(),
1483 resolved_field->IsVolatile(),
1484 field_index,
1485 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001486 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001487 // Read barrier generates a runtime call in slow path and we need a valid
1488 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1489 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001490 return iput;
1491}
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001492
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001493bool HInliner::TryBuildAndInlineHelper(HInvoke* invoke_instruction,
1494 ArtMethod* resolved_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001495 ReferenceTypeInfo receiver_type,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001496 bool same_dex_file,
1497 HInstruction** return_replacement) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001498 DCHECK(!(resolved_method->IsStatic() && receiver_type.IsValid()));
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001499 ScopedObjectAccess soa(Thread::Current());
1500 const DexFile::CodeItem* code_item = resolved_method->GetCodeItem();
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001501 const DexFile& callee_dex_file = *resolved_method->GetDexFile();
1502 uint32_t method_index = resolved_method->GetDexMethodIndex();
Calin Juravle2e768302015-07-28 14:41:11 +00001503 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Mathieu Chartier736b5602015-09-02 14:54:11 -07001504 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Nicolas Geoffrayf1aedb12016-07-28 03:49:14 +01001505 Handle<mirror::ClassLoader> class_loader(handles_->NewHandle(
1506 resolved_method->GetDeclaringClass()->GetClassLoader()));
1507
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001508 DexCompilationUnit dex_compilation_unit(
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001509 class_loader,
Nicolas Geoffray5b82d332016-02-18 14:22:32 +00001510 class_linker,
1511 callee_dex_file,
1512 code_item,
1513 resolved_method->GetDeclaringClass()->GetDexClassDefIndex(),
1514 method_index,
1515 resolved_method->GetAccessFlags(),
1516 /* verified_method */ nullptr,
1517 dex_cache);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001518
Calin Juravle3cd4fc82015-05-14 15:15:42 +01001519 bool requires_ctor_barrier = false;
1520
1521 if (dex_compilation_unit.IsConstructor()) {
1522 // If it's a super invocation and we already generate a barrier there's no need
1523 // to generate another one.
1524 // We identify super calls by looking at the "this" pointer. If its value is the
1525 // same as the local "this" pointer then we must have a super invocation.
1526 bool is_super_invocation = invoke_instruction->InputAt(0)->IsParameterValue()
1527 && invoke_instruction->InputAt(0)->AsParameterValue()->IsThis();
1528 if (is_super_invocation && graph_->ShouldGenerateConstructorBarrier()) {
1529 requires_ctor_barrier = false;
1530 } else {
1531 Thread* self = Thread::Current();
1532 requires_ctor_barrier = compiler_driver_->RequiresConstructorBarrier(self,
1533 dex_compilation_unit.GetDexFile(),
1534 dex_compilation_unit.GetClassDefIndex());
1535 }
1536 }
1537
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001538 InvokeType invoke_type = invoke_instruction->GetInvokeType();
Nicolas Geoffray35071052015-06-09 15:43:38 +01001539 if (invoke_type == kInterface) {
1540 // We have statically resolved the dispatch. To please the class linker
1541 // at runtime, we change this call as if it was a virtual call.
1542 invoke_type = kVirtual;
1543 }
David Brazdil3f523062016-02-29 16:53:33 +00001544
1545 const int32_t caller_instruction_counter = graph_->GetCurrentInstructionId();
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +00001546 HGraph* callee_graph = new (graph_->GetArena()) HGraph(
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001547 graph_->GetArena(),
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001548 callee_dex_file,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001549 method_index,
Calin Juravle3cd4fc82015-05-14 15:15:42 +01001550 requires_ctor_barrier,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001551 compiler_driver_->GetInstructionSet(),
Nicolas Geoffray35071052015-06-09 15:43:38 +01001552 invoke_type,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001553 graph_->IsDebuggable(),
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001554 /* osr */ false,
David Brazdil3f523062016-02-29 16:53:33 +00001555 caller_instruction_counter);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001556 callee_graph->SetArtMethod(resolved_method);
David Brazdil5e8b1372015-01-23 14:39:08 +00001557
Vladimir Marko438709f2017-02-23 18:56:13 +00001558 // When they are needed, allocate `inline_stats_` on the Arena instead
Roland Levillaina8013fd2016-04-04 15:34:31 +01001559 // of on the stack, as Clang might produce a stack frame too large
1560 // for this function, that would not fit the requirements of the
1561 // `-Wframe-larger-than` option.
Vladimir Marko438709f2017-02-23 18:56:13 +00001562 if (stats_ != nullptr) {
1563 // Reuse one object for all inline attempts from this caller to keep Arena memory usage low.
1564 if (inline_stats_ == nullptr) {
1565 void* storage = graph_->GetArena()->Alloc<OptimizingCompilerStats>(kArenaAllocMisc);
1566 inline_stats_ = new (storage) OptimizingCompilerStats;
1567 } else {
1568 inline_stats_->Reset();
1569 }
1570 }
David Brazdil5e8b1372015-01-23 14:39:08 +00001571 HGraphBuilder builder(callee_graph,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001572 &dex_compilation_unit,
1573 &outer_compilation_unit_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001574 resolved_method->GetDexFile(),
David Brazdil86ea7ee2016-02-16 09:26:07 +00001575 *code_item,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001576 compiler_driver_,
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00001577 codegen_,
Vladimir Marko438709f2017-02-23 18:56:13 +00001578 inline_stats_,
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001579 resolved_method->GetQuickenedInfo(class_linker->GetImagePointerSize()),
David Brazdildee58d62016-04-07 09:54:26 +00001580 dex_cache,
1581 handles_);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001582
David Brazdildee58d62016-04-07 09:54:26 +00001583 if (builder.BuildGraph() != kAnalysisSuccess) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001584 LOG_FAIL(kNotInlinedCannotBuild)
1585 << "Method " << callee_dex_file.PrettyMethod(method_index)
1586 << " could not be built, so cannot be inlined";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001587 return false;
1588 }
1589
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001590 if (!RegisterAllocator::CanAllocateRegistersFor(*callee_graph,
1591 compiler_driver_->GetInstructionSet())) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001592 LOG_FAIL(kNotInlinedRegisterAllocator)
1593 << "Method " << callee_dex_file.PrettyMethod(method_index)
1594 << " cannot be inlined because of the register allocator";
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001595 return false;
1596 }
1597
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001598 size_t parameter_index = 0;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001599 bool run_rtp = false;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001600 for (HInstructionIterator instructions(callee_graph->GetEntryBlock()->GetInstructions());
1601 !instructions.Done();
1602 instructions.Advance()) {
1603 HInstruction* current = instructions.Current();
1604 if (current->IsParameterValue()) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001605 HInstruction* argument = invoke_instruction->InputAt(parameter_index);
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001606 if (argument->IsNullConstant()) {
1607 current->ReplaceWith(callee_graph->GetNullConstant());
1608 } else if (argument->IsIntConstant()) {
1609 current->ReplaceWith(callee_graph->GetIntConstant(argument->AsIntConstant()->GetValue()));
1610 } else if (argument->IsLongConstant()) {
1611 current->ReplaceWith(callee_graph->GetLongConstant(argument->AsLongConstant()->GetValue()));
1612 } else if (argument->IsFloatConstant()) {
1613 current->ReplaceWith(
1614 callee_graph->GetFloatConstant(argument->AsFloatConstant()->GetValue()));
1615 } else if (argument->IsDoubleConstant()) {
1616 current->ReplaceWith(
1617 callee_graph->GetDoubleConstant(argument->AsDoubleConstant()->GetValue()));
1618 } else if (argument->GetType() == Primitive::kPrimNot) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001619 if (!resolved_method->IsStatic() && parameter_index == 0 && receiver_type.IsValid()) {
1620 run_rtp = true;
1621 current->SetReferenceTypeInfo(receiver_type);
1622 } else {
1623 current->SetReferenceTypeInfo(argument->GetReferenceTypeInfo());
1624 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001625 current->AsParameterValue()->SetCanBeNull(argument->CanBeNull());
1626 }
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001627 ++parameter_index;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001628 }
1629 }
1630
David Brazdil94ab38f2016-06-21 17:48:19 +01001631 // We have replaced formal arguments with actual arguments. If actual types
1632 // are more specific than the declared ones, run RTP again on the inner graph.
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001633 if (run_rtp || ArgumentTypesMoreSpecific(invoke_instruction, resolved_method)) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001634 ReferenceTypePropagation(callee_graph,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001635 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +01001636 dex_compilation_unit.GetDexCache(),
1637 handles_,
1638 /* is_first_run */ false).Run();
1639 }
1640
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001641 RunOptimizations(callee_graph, code_item, dex_compilation_unit);
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +00001642
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001643 HBasicBlock* exit_block = callee_graph->GetExitBlock();
1644 if (exit_block == nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001645 LOG_FAIL(kNotInlinedInfiniteLoop)
1646 << "Method " << callee_dex_file.PrettyMethod(method_index)
1647 << " could not be inlined because it has an infinite loop";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001648 return false;
1649 }
1650
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001651 bool has_one_return = false;
Vladimir Marko60584552015-09-03 13:35:12 +00001652 for (HBasicBlock* predecessor : exit_block->GetPredecessors()) {
1653 if (predecessor->GetLastInstruction()->IsThrow()) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001654 if (invoke_instruction->GetBlock()->IsTryBlock()) {
1655 // TODO(ngeoffray): Support adding HTryBoundary in Hgraph::InlineInto.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001656 LOG_FAIL(kNotInlinedTryCatch)
1657 << "Method " << callee_dex_file.PrettyMethod(method_index)
1658 << " could not be inlined because one branch always throws and"
1659 << " caller is in a try/catch block";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001660 return false;
1661 } else if (graph_->GetExitBlock() == nullptr) {
1662 // TODO(ngeoffray): Support adding HExit in the caller graph.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001663 LOG_FAIL(kNotInlinedInfiniteLoop)
1664 << "Method " << callee_dex_file.PrettyMethod(method_index)
1665 << " could not be inlined because one branch always throws and"
1666 << " caller does not have an exit block";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001667 return false;
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00001668 } else if (graph_->HasIrreducibleLoops()) {
1669 // TODO(ngeoffray): Support re-computing loop information to graphs with
1670 // irreducible loops?
1671 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1672 << " could not be inlined because one branch always throws and"
1673 << " caller has irreducible loops";
1674 return false;
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001675 }
1676 } else {
1677 has_one_return = true;
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001678 }
1679 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001680
1681 if (!has_one_return) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001682 LOG_FAIL(kNotInlinedAlwaysThrows)
1683 << "Method " << callee_dex_file.PrettyMethod(method_index)
1684 << " could not be inlined because it always throws";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001685 return false;
1686 }
1687
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001688 size_t number_of_instructions = 0;
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001689 // Skip the entry block, it does not contain instructions that prevent inlining.
1690 for (HBasicBlock* block : callee_graph->GetReversePostOrderSkipEntryBlock()) {
David Sehrc757dec2016-11-04 15:48:34 -07001691 if (block->IsLoopHeader()) {
1692 if (block->GetLoopInformation()->IsIrreducible()) {
1693 // Don't inline methods with irreducible loops, they could prevent some
1694 // optimizations to run.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001695 LOG_FAIL(kNotInlinedIrreducibleLoop)
1696 << "Method " << callee_dex_file.PrettyMethod(method_index)
1697 << " could not be inlined because it contains an irreducible loop";
David Sehrc757dec2016-11-04 15:48:34 -07001698 return false;
1699 }
1700 if (!block->GetLoopInformation()->HasExitEdge()) {
1701 // Don't inline methods with loops without exit, since they cause the
1702 // loop information to be computed incorrectly when updating after
1703 // inlining.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001704 LOG_FAIL(kNotInlinedLoopWithoutExit)
1705 << "Method " << callee_dex_file.PrettyMethod(method_index)
1706 << " could not be inlined because it contains a loop with no exit";
David Sehrc757dec2016-11-04 15:48:34 -07001707 return false;
1708 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001709 }
1710
1711 for (HInstructionIterator instr_it(block->GetInstructions());
1712 !instr_it.Done();
1713 instr_it.Advance()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001714 if (++number_of_instructions >= inlining_budget_) {
1715 LOG_FAIL(kNotInlinedInstructionBudget)
1716 << "Method " << callee_dex_file.PrettyMethod(method_index)
1717 << " is not inlined because the outer method has reached"
1718 << " its instruction budget limit.";
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001719 return false;
1720 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001721 HInstruction* current = instr_it.Current();
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001722 if (current->NeedsEnvironment() &&
1723 (total_number_of_dex_registers_ >= kMaximumNumberOfCumulatedDexRegisters)) {
1724 LOG_FAIL(kNotInlinedEnvironmentBudget)
1725 << "Method " << callee_dex_file.PrettyMethod(method_index)
1726 << " is not inlined because its caller has reached"
1727 << " its environment budget limit.";
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001728 return false;
1729 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001730
Nicolas Geoffrayfbdfa6d2017-02-03 10:43:13 +00001731 if (current->NeedsEnvironment() &&
1732 !CanEncodeInlinedMethodInStackMap(*caller_compilation_unit_.GetDexFile(),
1733 resolved_method)) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001734 LOG_FAIL(kNotInlinedStackMaps)
1735 << "Method " << callee_dex_file.PrettyMethod(method_index)
1736 << " could not be inlined because " << current->DebugName()
1737 << " needs an environment, is in a different dex file"
1738 << ", and cannot be encoded in the stack maps.";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001739 return false;
1740 }
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001741
Vladimir Markodc151b22015-10-15 18:02:30 +01001742 if (!same_dex_file && current->NeedsDexCacheOfDeclaringClass()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001743 LOG_FAIL(kNotInlinedDexCache)
1744 << "Method " << callee_dex_file.PrettyMethod(method_index)
1745 << " could not be inlined because " << current->DebugName()
1746 << " it is in a different dex file and requires access to the dex cache";
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001747 return false;
1748 }
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001749
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001750 if (current->IsUnresolvedStaticFieldGet() ||
1751 current->IsUnresolvedInstanceFieldGet() ||
1752 current->IsUnresolvedStaticFieldSet() ||
1753 current->IsUnresolvedInstanceFieldSet()) {
1754 // Entrypoint for unresolved fields does not handle inlined frames.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001755 LOG_FAIL(kNotInlinedUnresolvedEntrypoint)
1756 << "Method " << callee_dex_file.PrettyMethod(method_index)
1757 << " could not be inlined because it is using an unresolved"
1758 << " entrypoint";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001759 return false;
1760 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001761 }
1762 }
David Brazdil3f523062016-02-29 16:53:33 +00001763 DCHECK_EQ(caller_instruction_counter, graph_->GetCurrentInstructionId())
1764 << "No instructions can be added to the outer graph while inner graph is being built";
1765
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001766 // Inline the callee graph inside the caller graph.
David Brazdil3f523062016-02-29 16:53:33 +00001767 const int32_t callee_instruction_counter = callee_graph->GetCurrentInstructionId();
1768 graph_->SetCurrentInstructionId(callee_instruction_counter);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001769 *return_replacement = callee_graph->InlineInto(graph_, invoke_instruction);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001770 // Update our budget for other inlining attempts in `caller_graph`.
1771 total_number_of_instructions_ += number_of_instructions;
1772 UpdateInliningBudget();
David Brazdil3f523062016-02-29 16:53:33 +00001773
1774 DCHECK_EQ(callee_instruction_counter, callee_graph->GetCurrentInstructionId())
1775 << "No instructions can be added to the inner graph during inlining into the outer graph";
1776
Vladimir Marko438709f2017-02-23 18:56:13 +00001777 if (stats_ != nullptr) {
1778 DCHECK(inline_stats_ != nullptr);
1779 inline_stats_->AddTo(stats_);
1780 }
1781
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001782 return true;
1783}
Calin Juravle2e768302015-07-28 14:41:11 +00001784
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001785void HInliner::RunOptimizations(HGraph* callee_graph,
1786 const DexFile::CodeItem* code_item,
1787 const DexCompilationUnit& dex_compilation_unit) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001788 // Note: if the outermost_graph_ is being compiled OSR, we should not run any
1789 // optimization that could lead to a HDeoptimize. The following optimizations do not.
Vladimir Marko438709f2017-02-23 18:56:13 +00001790 HDeadCodeElimination dce(callee_graph, inline_stats_, "dead_code_elimination$inliner");
Andreas Gampeca620d72016-11-08 08:09:33 -08001791 HConstantFolding fold(callee_graph, "constant_folding$inliner");
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001792 HSharpening sharpening(callee_graph, codegen_, dex_compilation_unit, compiler_driver_, handles_);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001793 InstructionSimplifier simplify(callee_graph, codegen_, inline_stats_);
Vladimir Marko438709f2017-02-23 18:56:13 +00001794 IntrinsicsRecognizer intrinsics(callee_graph, inline_stats_);
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001795
1796 HOptimization* optimizations[] = {
1797 &intrinsics,
1798 &sharpening,
1799 &simplify,
1800 &fold,
1801 &dce,
1802 };
1803
1804 for (size_t i = 0; i < arraysize(optimizations); ++i) {
1805 HOptimization* optimization = optimizations[i];
1806 optimization->Run();
1807 }
1808
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001809 // Bail early for pathological cases on the environment (for example recursive calls,
1810 // or too large environment).
1811 if (total_number_of_dex_registers_ >= kMaximumNumberOfCumulatedDexRegisters) {
1812 LOG_NOTE() << "Calls in " << callee_graph->GetArtMethod()->PrettyMethod()
1813 << " will not be inlined because the outer method has reached"
1814 << " its environment budget limit.";
1815 return;
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001816 }
1817
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001818 // Bail early if we know we already are over the limit.
1819 size_t number_of_instructions = CountNumberOfInstructions(callee_graph);
1820 if (number_of_instructions > inlining_budget_) {
1821 LOG_NOTE() << "Calls in " << callee_graph->GetArtMethod()->PrettyMethod()
1822 << " will not be inlined because the outer method has reached"
1823 << " its instruction budget limit. " << number_of_instructions;
1824 return;
1825 }
1826
1827 HInliner inliner(callee_graph,
1828 outermost_graph_,
1829 codegen_,
1830 outer_compilation_unit_,
1831 dex_compilation_unit,
1832 compiler_driver_,
1833 handles_,
1834 inline_stats_,
1835 total_number_of_dex_registers_ + code_item->registers_size_,
1836 total_number_of_instructions_ + number_of_instructions,
1837 this,
1838 depth_ + 1);
1839 inliner.Run();
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001840}
1841
David Brazdil94ab38f2016-06-21 17:48:19 +01001842static bool IsReferenceTypeRefinement(ReferenceTypeInfo declared_rti,
1843 bool declared_can_be_null,
1844 HInstruction* actual_obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001845 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001846 if (declared_can_be_null && !actual_obj->CanBeNull()) {
1847 return true;
1848 }
1849
1850 ReferenceTypeInfo actual_rti = actual_obj->GetReferenceTypeInfo();
1851 return (actual_rti.IsExact() && !declared_rti.IsExact()) ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001852 declared_rti.IsStrictSupertypeOf(actual_rti);
David Brazdil94ab38f2016-06-21 17:48:19 +01001853}
1854
1855ReferenceTypeInfo HInliner::GetClassRTI(mirror::Class* klass) {
1856 return ReferenceTypePropagation::IsAdmissible(klass)
1857 ? ReferenceTypeInfo::Create(handles_->NewHandle(klass))
1858 : graph_->GetInexactObjectRti();
1859}
1860
1861bool HInliner::ArgumentTypesMoreSpecific(HInvoke* invoke_instruction, ArtMethod* resolved_method) {
1862 // If this is an instance call, test whether the type of the `this` argument
1863 // is more specific than the class which declares the method.
1864 if (!resolved_method->IsStatic()) {
1865 if (IsReferenceTypeRefinement(GetClassRTI(resolved_method->GetDeclaringClass()),
1866 /* declared_can_be_null */ false,
1867 invoke_instruction->InputAt(0u))) {
1868 return true;
1869 }
1870 }
1871
David Brazdil94ab38f2016-06-21 17:48:19 +01001872 // Iterate over the list of parameter types and test whether any of the
1873 // actual inputs has a more specific reference type than the type declared in
1874 // the signature.
1875 const DexFile::TypeList* param_list = resolved_method->GetParameterTypeList();
1876 for (size_t param_idx = 0,
1877 input_idx = resolved_method->IsStatic() ? 0 : 1,
1878 e = (param_list == nullptr ? 0 : param_list->Size());
1879 param_idx < e;
1880 ++param_idx, ++input_idx) {
1881 HInstruction* input = invoke_instruction->InputAt(input_idx);
1882 if (input->GetType() == Primitive::kPrimNot) {
Vladimir Marko942fd312017-01-16 20:52:19 +00001883 mirror::Class* param_cls = resolved_method->GetClassFromTypeIndex(
David Brazdil94ab38f2016-06-21 17:48:19 +01001884 param_list->GetTypeItem(param_idx).type_idx_,
Vladimir Marko942fd312017-01-16 20:52:19 +00001885 /* resolve */ false);
David Brazdil94ab38f2016-06-21 17:48:19 +01001886 if (IsReferenceTypeRefinement(GetClassRTI(param_cls),
1887 /* declared_can_be_null */ true,
1888 input)) {
1889 return true;
1890 }
1891 }
1892 }
1893
1894 return false;
1895}
1896
1897bool HInliner::ReturnTypeMoreSpecific(HInvoke* invoke_instruction,
1898 HInstruction* return_replacement) {
Alex Light68289a52015-12-15 17:30:30 -08001899 // Check the integrity of reference types and run another type propagation if needed.
David Brazdil4833f5a2015-12-16 10:37:39 +00001900 if (return_replacement != nullptr) {
1901 if (return_replacement->GetType() == Primitive::kPrimNot) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001902 // Test if the return type is a refinement of the declared return type.
1903 if (IsReferenceTypeRefinement(invoke_instruction->GetReferenceTypeInfo(),
1904 /* declared_can_be_null */ true,
1905 return_replacement)) {
1906 return true;
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001907 } else if (return_replacement->IsInstanceFieldGet()) {
1908 HInstanceFieldGet* field_get = return_replacement->AsInstanceFieldGet();
1909 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1910 if (field_get->GetFieldInfo().GetField() ==
1911 class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0)) {
1912 return true;
1913 }
David Brazdil94ab38f2016-06-21 17:48:19 +01001914 }
1915 } else if (return_replacement->IsInstanceOf()) {
1916 // Inlining InstanceOf into an If may put a tighter bound on reference types.
1917 return true;
1918 }
1919 }
1920
1921 return false;
1922}
1923
1924void HInliner::FixUpReturnReferenceType(ArtMethod* resolved_method,
1925 HInstruction* return_replacement) {
1926 if (return_replacement != nullptr) {
1927 if (return_replacement->GetType() == Primitive::kPrimNot) {
David Brazdil4833f5a2015-12-16 10:37:39 +00001928 if (!return_replacement->GetReferenceTypeInfo().IsValid()) {
1929 // Make sure that we have a valid type for the return. We may get an invalid one when
1930 // we inline invokes with multiple branches and create a Phi for the result.
1931 // TODO: we could be more precise by merging the phi inputs but that requires
1932 // some functionality from the reference type propagation.
1933 DCHECK(return_replacement->IsPhi());
Vladimir Marko942fd312017-01-16 20:52:19 +00001934 mirror::Class* cls = resolved_method->GetReturnType(false /* resolve */);
David Brazdil94ab38f2016-06-21 17:48:19 +01001935 return_replacement->SetReferenceTypeInfo(GetClassRTI(cls));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001936 }
Calin Juravlecdfed3d2015-10-26 14:05:01 +00001937 }
Calin Juravle2e768302015-07-28 14:41:11 +00001938 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001939}
1940
1941} // namespace art