blob: d85bfd5564c3189ce2f267cf5582abca906fd48d [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"
Vladimir Markob4eb1b12018-05-24 11:09:38 +010023#include "class_root.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000024#include "constant_folding.h"
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010025#include "data_type-inl.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000026#include "dead_code_elimination.h"
Andreas Gampeb95c74b2017-04-20 19:43:21 -070027#include "dex/inline_method_analyser.h"
Vladimir Markobe10e8e2016-01-22 12:09:44 +000028#include "dex/verification_results.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070029#include "dex/verified_method.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000030#include "driver/compiler_driver-inl.h"
Calin Juravleec748352015-07-29 13:52:12 +010031#include "driver/compiler_options.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000032#include "driver/dex_compilation_unit.h"
33#include "instruction_simplifier.h"
Scott Wakelingd60a1af2015-07-22 14:32:44 +010034#include "intrinsics.h"
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +000035#include "jit/jit.h"
36#include "jit/jit_code_cache.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000037#include "mirror/class_loader.h"
38#include "mirror/dex_cache.h"
Andreas Gampe52ecb652018-10-24 15:18:21 -070039#include "mirror/object_array-alloc-inl.h"
40#include "mirror/object_array-inl.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000041#include "nodes.h"
Nicolas Geoffray454a4812015-06-09 10:37:32 +010042#include "reference_type_propagation.h"
Matthew Gharritye9288852016-07-14 14:08:16 -070043#include "register_allocator_linear_scan.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070044#include "scoped_thread_state_change-inl.h"
Vladimir Markodc151b22015-10-15 18:02:30 +010045#include "sharpening.h"
David Brazdil4833f5a2015-12-16 10:37:39 +000046#include "ssa_builder.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000047#include "ssa_phi_elimination.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000048#include "thread.h"
49
50namespace art {
51
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000052// Instruction limit to control memory.
53static constexpr size_t kMaximumNumberOfTotalInstructions = 1024;
54
55// Maximum number of instructions for considering a method small,
56// which we will always try to inline if the other non-instruction limits
57// are not reached.
58static constexpr size_t kMaximumNumberOfInstructionsForSmallMethod = 3;
Nicolas Geoffray5949fa02015-12-18 10:57:10 +000059
60// Limit the number of dex registers that we accumulate while inlining
61// to avoid creating large amount of nested environments.
Nicolas Geoffrayf81621e2017-06-07 13:18:03 +010062static constexpr size_t kMaximumNumberOfCumulatedDexRegisters = 32;
Nicolas Geoffray5949fa02015-12-18 10:57:10 +000063
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000064// Limit recursive call inlining, which do not benefit from too
65// much inlining compared to code locality.
66static constexpr size_t kMaximumNumberOfRecursiveCalls = 4;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -070067
Calin Juravlee2492d42017-03-20 11:42:13 -070068// Controls the use of inline caches in AOT mode.
Calin Juravle8af70892017-03-28 15:31:44 -070069static constexpr bool kUseAOTInlineCaches = true;
Calin Juravlee2492d42017-03-20 11:42:13 -070070
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000071// We check for line numbers to make sure the DepthString implementation
72// aligns the output nicely.
73#define LOG_INTERNAL(msg) \
74 static_assert(__LINE__ > 10, "Unhandled line number"); \
75 static_assert(__LINE__ < 10000, "Unhandled line number"); \
76 VLOG(compiler) << DepthString(__LINE__) << msg
77
78#define LOG_TRY() LOG_INTERNAL("Try inlinining call: ")
79#define LOG_NOTE() LOG_INTERNAL("Note: ")
80#define LOG_SUCCESS() LOG_INTERNAL("Success: ")
Igor Murashkin1e065a52017-08-09 13:20:34 -070081#define LOG_FAIL(stats_ptr, stat) MaybeRecordStat(stats_ptr, stat); LOG_INTERNAL("Fail: ")
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000082#define LOG_FAIL_NO_STAT() LOG_INTERNAL("Fail: ")
83
84std::string HInliner::DepthString(int line) const {
85 std::string value;
86 // Indent according to the inlining depth.
87 size_t count = depth_;
88 // Line numbers get printed in the log, so add a space if the log's line is less
89 // than 1000, and two if less than 100. 10 cannot be reached as it's the copyright.
90 if (!kIsTargetBuild) {
91 if (line < 100) {
92 value += " ";
93 }
94 if (line < 1000) {
95 value += " ";
96 }
97 // Safeguard if this file reaches more than 10000 lines.
98 DCHECK_LT(line, 10000);
99 }
100 for (size_t i = 0; i < count; ++i) {
101 value += " ";
102 }
103 return value;
104}
105
106static size_t CountNumberOfInstructions(HGraph* graph) {
107 size_t number_of_instructions = 0;
108 for (HBasicBlock* block : graph->GetReversePostOrderSkipEntryBlock()) {
109 for (HInstructionIterator instr_it(block->GetInstructions());
110 !instr_it.Done();
111 instr_it.Advance()) {
112 ++number_of_instructions;
113 }
114 }
115 return number_of_instructions;
116}
117
118void HInliner::UpdateInliningBudget() {
119 if (total_number_of_instructions_ >= kMaximumNumberOfTotalInstructions) {
120 // Always try to inline small methods.
121 inlining_budget_ = kMaximumNumberOfInstructionsForSmallMethod;
122 } else {
123 inlining_budget_ = std::max(
124 kMaximumNumberOfInstructionsForSmallMethod,
125 kMaximumNumberOfTotalInstructions - total_number_of_instructions_);
126 }
127}
128
Aart Bik24773202018-04-26 10:28:51 -0700129bool HInliner::Run() {
Vladimir Marko213ee2d2018-06-22 11:56:34 +0100130 if (codegen_->GetCompilerOptions().GetInlineMaxCodeUnits() == 0) {
Aart Bik24773202018-04-26 10:28:51 -0700131 // Inlining effectively disabled.
132 return false;
133 } else if (graph_->IsDebuggable()) {
Nicolas Geoffraye50b8d22015-03-13 08:57:42 +0000134 // For simplicity, we currently never inline when the graph is debuggable. This avoids
135 // doing some logic in the runtime to discover if a method could have been inlined.
Aart Bik24773202018-04-26 10:28:51 -0700136 return false;
Nicolas Geoffraye50b8d22015-03-13 08:57:42 +0000137 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000138
Aart Bik24773202018-04-26 10:28:51 -0700139 bool didInline = false;
140
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000141 // Initialize the number of instructions for the method being compiled. Recursive calls
142 // to HInliner::Run have already updated the instruction count.
143 if (outermost_graph_ == graph_) {
144 total_number_of_instructions_ = CountNumberOfInstructions(graph_);
145 }
146
147 UpdateInliningBudget();
148 DCHECK_NE(total_number_of_instructions_, 0u);
149 DCHECK_NE(inlining_budget_, 0u);
150
Roland Levillain6c3af162017-04-27 11:18:56 +0100151 // If we're compiling with a core image (which is only used for
152 // test purposes), honor inlining directives in method names:
Roland Levillain6c3af162017-04-27 11:18:56 +0100153 // - if a method's name contains the substring "$noinline$", do not
Vladimir Marko6be1dbd2018-11-13 13:09:51 +0000154 // inline that method;
155 // - if a method's name contains the substring "$inline$", ensure
156 // that this method is actually inlined.
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000157 // We limit the latter to AOT compilation, as the JIT may or may not inline
Nicolas Geoffray08490b82017-07-18 12:58:10 +0100158 // depending on the state of classes at runtime.
Vladimir Marko6be1dbd2018-11-13 13:09:51 +0000159 const bool honor_noinline_directives = codegen_->GetCompilerOptions().CompilingWithCoreImage();
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000160 const bool honor_inline_directives =
161 honor_noinline_directives && Runtime::Current()->IsAotCompiler();
Roland Levillain6c3af162017-04-27 11:18:56 +0100162
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +0000163 // Keep a copy of all blocks when starting the visit.
164 ArenaVector<HBasicBlock*> blocks = graph_->GetReversePostOrder();
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100165 DCHECK(!blocks.empty());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +0000166 // Because we are changing the graph when inlining,
167 // we just iterate over the blocks of the outer method.
168 // This avoids doing the inlining work again on the inlined blocks.
169 for (HBasicBlock* block : blocks) {
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000170 for (HInstruction* instruction = block->GetFirstInstruction(); instruction != nullptr;) {
171 HInstruction* next = instruction->GetNext();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100172 HInvoke* call = instruction->AsInvoke();
Razvan A Lupusoru3e90a962015-03-27 13:44:44 -0700173 // As long as the call is not intrinsified, it is worth trying to inline.
174 if (call != nullptr && call->GetIntrinsic() == Intrinsics::kNone) {
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000175 if (honor_noinline_directives) {
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000176 // Debugging case: directives in method names control or assert on inlining.
177 std::string callee_name = outer_compilation_unit_.GetDexFile()->PrettyMethod(
178 call->GetDexMethodIndex(), /* with_signature */ false);
179 // Tests prevent inlining by having $noinline$ in their method names.
180 if (callee_name.find("$noinline$") == std::string::npos) {
Aart Bik24773202018-04-26 10:28:51 -0700181 if (TryInline(call)) {
182 didInline = true;
Aart Bik54e45c52018-04-27 13:57:21 -0700183 } else if (honor_inline_directives) {
Nicolas Geoffray1949baf2017-10-17 12:14:53 +0000184 bool should_have_inlined = (callee_name.find("$inline$") != std::string::npos);
185 CHECK(!should_have_inlined) << "Could not inline " << callee_name;
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000186 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000187 }
Guillaume "Vermeille" Sancheze918d382015-06-03 15:32:41 +0100188 } else {
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000189 DCHECK(!honor_inline_directives);
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000190 // Normal case: try to inline.
Aart Bik24773202018-04-26 10:28:51 -0700191 if (TryInline(call)) {
192 didInline = true;
193 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000194 }
195 }
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000196 instruction = next;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000197 }
198 }
Aart Bik24773202018-04-26 10:28:51 -0700199
200 return didInline;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000201}
202
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100203static bool IsMethodOrDeclaringClassFinal(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700204 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100205 return method->IsFinal() || method->GetDeclaringClass()->IsFinal();
206}
207
208/**
209 * Given the `resolved_method` looked up in the dex cache, try to find
210 * the actual runtime target of an interface or virtual call.
211 * Return nullptr if the runtime target cannot be proven.
212 */
213static ArtMethod* FindVirtualOrInterfaceTarget(HInvoke* invoke, ArtMethod* resolved_method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700214 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100215 if (IsMethodOrDeclaringClassFinal(resolved_method)) {
216 // No need to lookup further, the resolved method will be the target.
217 return resolved_method;
218 }
219
220 HInstruction* receiver = invoke->InputAt(0);
221 if (receiver->IsNullCheck()) {
222 // Due to multiple levels of inlining within the same pass, it might be that
223 // null check does not have the reference type of the actual receiver.
224 receiver = receiver->InputAt(0);
225 }
226 ReferenceTypeInfo info = receiver->GetReferenceTypeInfo();
Calin Juravle2e768302015-07-28 14:41:11 +0000227 DCHECK(info.IsValid()) << "Invalid RTI for " << receiver->DebugName();
228 if (!info.IsExact()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100229 // We currently only support inlining with known receivers.
230 // TODO: Remove this check, we should be able to inline final methods
231 // on unknown receivers.
232 return nullptr;
233 } else if (info.GetTypeHandle()->IsInterface()) {
234 // Statically knowing that the receiver has an interface type cannot
235 // help us find what is the target method.
236 return nullptr;
237 } else if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(info.GetTypeHandle().Get())) {
238 // The method that we're trying to call is not in the receiver's class or super classes.
239 return nullptr;
Nicolas Geoffrayab5327d2016-03-18 11:36:20 +0000240 } else if (info.GetTypeHandle()->IsErroneous()) {
241 // If the type is erroneous, do not go further, as we are going to query the vtable or
242 // imt table, that we can only safely do on non-erroneous classes.
243 return nullptr;
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100244 }
245
246 ClassLinker* cl = Runtime::Current()->GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700247 PointerSize pointer_size = cl->GetImagePointerSize();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100248 if (invoke->IsInvokeInterface()) {
249 resolved_method = info.GetTypeHandle()->FindVirtualMethodForInterface(
250 resolved_method, pointer_size);
251 } else {
252 DCHECK(invoke->IsInvokeVirtual());
253 resolved_method = info.GetTypeHandle()->FindVirtualMethodForVirtual(
254 resolved_method, pointer_size);
255 }
256
257 if (resolved_method == nullptr) {
258 // The information we had on the receiver was not enough to find
259 // the target method. Since we check above the exact type of the receiver,
260 // the only reason this can happen is an IncompatibleClassChangeError.
261 return nullptr;
Alex Light9139e002015-10-09 15:59:48 -0700262 } else if (!resolved_method->IsInvokable()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100263 // The information we had on the receiver was not enough to find
264 // the target method. Since we check above the exact type of the receiver,
265 // the only reason this can happen is an IncompatibleClassChangeError.
266 return nullptr;
267 } else if (IsMethodOrDeclaringClassFinal(resolved_method)) {
268 // A final method has to be the target method.
269 return resolved_method;
270 } else if (info.IsExact()) {
271 // If we found a method and the receiver's concrete type is statically
272 // known, we know for sure the target.
273 return resolved_method;
274 } else {
275 // Even if we did find a method, the receiver type was not enough to
276 // statically find the runtime target.
277 return nullptr;
278 }
279}
280
281static uint32_t FindMethodIndexIn(ArtMethod* method,
282 const DexFile& dex_file,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000283 uint32_t name_and_signature_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700284 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100285 if (IsSameDexFile(*method->GetDexFile(), dex_file)) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100286 return method->GetDexMethodIndex();
287 } else {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000288 return method->FindDexMethodIndexInOtherDexFile(dex_file, name_and_signature_index);
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100289 }
290}
291
Andreas Gampea5b09a62016-11-17 15:21:22 -0800292static dex::TypeIndex FindClassIndexIn(mirror::Class* cls,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000293 const DexCompilationUnit& compilation_unit)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700294 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000295 const DexFile& dex_file = *compilation_unit.GetDexFile();
Andreas Gampea5b09a62016-11-17 15:21:22 -0800296 dex::TypeIndex index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100297 if (cls->GetDexCache() == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700298 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000299 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800300 } else if (!cls->GetDexTypeIndex().IsValid()) {
David Sehr709b0702016-10-13 09:12:37 -0700301 DCHECK(cls->IsProxyClass()) << cls->PrettyClass();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100302 // TODO: deal with proxy classes.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100303 } else if (IsSameDexFile(cls->GetDexFile(), dex_file)) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000304 DCHECK_EQ(cls->GetDexCache(), compilation_unit.GetDexCache().Get());
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000305 index = cls->GetDexTypeIndex();
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100306 } else {
307 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000308 // We cannot guarantee the entry will resolve to the same class,
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100309 // as there may be different class loaders. So only return the index if it's
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000310 // the right class already resolved with the class loader.
311 if (index.IsValid()) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +0000312 ObjPtr<mirror::Class> resolved = compilation_unit.GetClassLinker()->LookupResolvedType(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000313 index, compilation_unit.GetDexCache().Get(), compilation_unit.GetClassLoader().Get());
314 if (resolved != cls) {
315 index = dex::TypeIndex::Invalid();
316 }
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100317 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100318 }
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000319
320 return index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100321}
322
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000323class ScopedProfilingInfoInlineUse {
324 public:
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000325 explicit ScopedProfilingInfoInlineUse(ArtMethod* method, Thread* self)
326 : method_(method),
327 self_(self),
328 // Fetch the profiling info ahead of using it. If it's null when fetching,
329 // we should not call JitCodeCache::DoneInlining.
330 profiling_info_(
331 Runtime::Current()->GetJit()->GetCodeCache()->NotifyCompilerUse(method, self)) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000332 }
333
334 ~ScopedProfilingInfoInlineUse() {
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000335 if (profiling_info_ != nullptr) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700336 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000337 DCHECK_EQ(profiling_info_, method_->GetProfilingInfo(pointer_size));
338 Runtime::Current()->GetJit()->GetCodeCache()->DoneCompilerUse(method_, self_);
339 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000340 }
341
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000342 ProfilingInfo* GetProfilingInfo() const { return profiling_info_; }
343
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000344 private:
345 ArtMethod* const method_;
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000346 Thread* const self_;
347 ProfilingInfo* const profiling_info_;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000348};
349
Calin Juravle13439f02017-02-21 01:17:21 -0800350HInliner::InlineCacheType HInliner::GetInlineCacheType(
351 const Handle<mirror::ObjectArray<mirror::Class>>& classes)
352 REQUIRES_SHARED(Locks::mutator_lock_) {
353 uint8_t number_of_types = 0;
354 for (; number_of_types < InlineCache::kIndividualCacheSize; ++number_of_types) {
355 if (classes->Get(number_of_types) == nullptr) {
356 break;
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000357 }
358 }
Calin Juravle13439f02017-02-21 01:17:21 -0800359
360 if (number_of_types == 0) {
361 return kInlineCacheUninitialized;
362 } else if (number_of_types == 1) {
363 return kInlineCacheMonomorphic;
364 } else if (number_of_types == InlineCache::kIndividualCacheSize) {
365 return kInlineCacheMegamorphic;
366 } else {
367 return kInlineCachePolymorphic;
368 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000369}
370
371static mirror::Class* GetMonomorphicType(Handle<mirror::ObjectArray<mirror::Class>> classes)
372 REQUIRES_SHARED(Locks::mutator_lock_) {
373 DCHECK(classes->Get(0) != nullptr);
374 return classes->Get(0);
375}
376
Mingyao Yang063fc772016-08-02 11:02:54 -0700377ArtMethod* HInliner::TryCHADevirtualization(ArtMethod* resolved_method) {
378 if (!resolved_method->HasSingleImplementation()) {
379 return nullptr;
380 }
381 if (Runtime::Current()->IsAotCompiler()) {
382 // No CHA-based devirtulization for AOT compiler (yet).
383 return nullptr;
384 }
385 if (outermost_graph_->IsCompilingOsr()) {
386 // We do not support HDeoptimize in OSR methods.
387 return nullptr;
388 }
Mingyao Yange8fcd012017-01-20 10:43:30 -0800389 PointerSize pointer_size = caller_compilation_unit_.GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +0000390 ArtMethod* single_impl = resolved_method->GetSingleImplementation(pointer_size);
391 if (single_impl == nullptr) {
392 return nullptr;
393 }
394 if (single_impl->IsProxyMethod()) {
395 // Proxy method is a generic invoker that's not worth
396 // devirtualizing/inlining. It also causes issues when the proxy
397 // method is in another dex file if we try to rewrite invoke-interface to
398 // invoke-virtual because a proxy method doesn't have a real dex file.
399 return nullptr;
400 }
Nicolas Geoffray8e33e842017-04-03 16:55:16 +0100401 if (!single_impl->GetDeclaringClass()->IsResolved()) {
402 // There's a race with the class loading, which updates the CHA info
403 // before setting the class to resolved. So we just bail for this
404 // rare occurence.
405 return nullptr;
406 }
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +0000407 return single_impl;
Mingyao Yang063fc772016-08-02 11:02:54 -0700408}
409
Aart Bik2c148f02018-02-02 14:30:35 -0800410static bool IsMethodUnverified(CompilerDriver* const compiler_driver, ArtMethod* method)
David Sehr0225f8e2018-01-31 08:52:24 +0000411 REQUIRES_SHARED(Locks::mutator_lock_) {
Aart Bik2c148f02018-02-02 14:30:35 -0800412 if (!method->GetDeclaringClass()->IsVerified()) {
413 if (Runtime::Current()->UseJitCompilation()) {
414 // We're at runtime, we know this is cold code if the class
415 // is not verified, so don't bother analyzing.
416 return true;
417 }
418 uint16_t class_def_idx = method->GetDeclaringClass()->GetDexClassDefIndex();
419 if (!compiler_driver->IsMethodVerifiedWithoutFailures(
420 method->GetDexMethodIndex(), class_def_idx, *method->GetDexFile())) {
421 // Method has soft or hard failures, don't analyze.
422 return true;
423 }
424 }
425 return false;
426}
427
428static bool AlwaysThrows(CompilerDriver* const compiler_driver, ArtMethod* method)
429 REQUIRES_SHARED(Locks::mutator_lock_) {
430 DCHECK(method != nullptr);
431 // Skip non-compilable and unverified methods.
432 if (!method->IsCompilable() || IsMethodUnverified(compiler_driver, method)) {
433 return false;
434 }
Aart Bika8b8e9b2018-01-09 11:01:02 -0800435 // Skip native methods, methods with try blocks, and methods that are too large.
Aart Bik2c148f02018-02-02 14:30:35 -0800436 CodeItemDataAccessor accessor(method->DexInstructionData());
Aart Bika8b8e9b2018-01-09 11:01:02 -0800437 if (!accessor.HasCodeItem() ||
438 accessor.TriesSize() != 0 ||
439 accessor.InsnsSizeInCodeUnits() > kMaximumNumberOfTotalInstructions) {
440 return false;
441 }
442 // Scan for exits.
443 bool throw_seen = false;
444 for (const DexInstructionPcPair& pair : accessor) {
445 switch (pair.Inst().Opcode()) {
446 case Instruction::RETURN:
447 case Instruction::RETURN_VOID:
448 case Instruction::RETURN_WIDE:
449 case Instruction::RETURN_OBJECT:
450 case Instruction::RETURN_VOID_NO_BARRIER:
451 return false; // found regular control flow back
452 case Instruction::THROW:
453 throw_seen = true;
454 break;
455 default:
456 break;
457 }
458 }
459 return throw_seen;
460}
461
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700462bool HInliner::TryInline(HInvoke* invoke_instruction) {
Orion Hodsonac141392017-01-13 11:53:47 +0000463 if (invoke_instruction->IsInvokeUnresolved() ||
Orion Hodson4c8e12e2018-05-18 08:33:20 +0100464 invoke_instruction->IsInvokePolymorphic() ||
465 invoke_instruction->IsInvokeCustom()) {
466 return false; // Don't bother to move further if we know the method is unresolved or the
467 // invocation is polymorphic (invoke-{polymorphic,custom}).
Calin Juravle175dc732015-08-25 15:42:32 +0100468 }
469
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000470 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100471 uint32_t method_index = invoke_instruction->GetDexMethodIndex();
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000472 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000473 LOG_TRY() << caller_dex_file.PrettyMethod(method_index);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000474
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100475 ArtMethod* resolved_method = invoke_instruction->GetResolvedMethod();
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100476 if (resolved_method == nullptr) {
477 DCHECK(invoke_instruction->IsInvokeStaticOrDirect());
478 DCHECK(invoke_instruction->AsInvokeStaticOrDirect()->IsStringInit());
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000479 LOG_FAIL_NO_STAT() << "Not inlining a String.<init> method";
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100480 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000481 }
482 ArtMethod* actual_method = nullptr;
483
484 if (invoke_instruction->IsInvokeStaticOrDirect()) {
Andreas Gampefd2140f2015-12-23 16:30:44 -0800485 actual_method = resolved_method;
Vladimir Marko58155012015-08-19 12:49:41 +0000486 } else {
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100487 // Check if we can statically find the method.
488 actual_method = FindVirtualOrInterfaceTarget(invoke_instruction, resolved_method);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000489 }
490
Mingyao Yang063fc772016-08-02 11:02:54 -0700491 bool cha_devirtualize = false;
492 if (actual_method == nullptr) {
493 ArtMethod* method = TryCHADevirtualization(resolved_method);
494 if (method != nullptr) {
495 cha_devirtualize = true;
496 actual_method = method;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000497 LOG_NOTE() << "Try CHA-based inlining of " << actual_method->PrettyMethod();
Mingyao Yang063fc772016-08-02 11:02:54 -0700498 }
499 }
500
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100501 if (actual_method != nullptr) {
Aart Bikd4e328f2018-01-16 14:14:34 -0800502 // Single target.
Mingyao Yang063fc772016-08-02 11:02:54 -0700503 bool result = TryInlineAndReplace(invoke_instruction,
504 actual_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000505 ReferenceTypeInfo::CreateInvalid(),
Mingyao Yang063fc772016-08-02 11:02:54 -0700506 /* do_rtp */ true,
507 cha_devirtualize);
Aart Bikd4e328f2018-01-16 14:14:34 -0800508 if (result) {
509 // Successfully inlined.
510 if (!invoke_instruction->IsInvokeStaticOrDirect()) {
511 if (cha_devirtualize) {
512 // Add dependency due to devirtualization. We've assumed resolved_method
513 // has single implementation.
514 outermost_graph_->AddCHASingleImplementationDependency(resolved_method);
515 MaybeRecordStat(stats_, MethodCompilationStat::kCHAInline);
516 } else {
517 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedInvokeVirtualOrInterface);
518 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700519 }
Aart Bik2c148f02018-02-02 14:30:35 -0800520 } else if (!cha_devirtualize && AlwaysThrows(compiler_driver_, actual_method)) {
Aart Bikd4e328f2018-01-16 14:14:34 -0800521 // Set always throws property for non-inlined method call with single target
522 // (unless it was obtained through CHA, because that would imply we have
523 // to add the CHA dependency, which seems not worth it).
524 invoke_instruction->SetAlwaysThrows(true);
Calin Juravle69158982016-03-16 11:53:41 +0000525 }
526 return result;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100527 }
Andreas Gampefd2140f2015-12-23 16:30:44 -0800528 DCHECK(!invoke_instruction->IsInvokeStaticOrDirect());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100529
Calin Juravle13439f02017-02-21 01:17:21 -0800530 // Try using inline caches.
531 return TryInlineFromInlineCache(caller_dex_file, invoke_instruction, resolved_method);
532}
533
534static Handle<mirror::ObjectArray<mirror::Class>> AllocateInlineCacheHolder(
535 const DexCompilationUnit& compilation_unit,
536 StackHandleScope<1>* hs)
537 REQUIRES_SHARED(Locks::mutator_lock_) {
538 Thread* self = Thread::Current();
539 ClassLinker* class_linker = compilation_unit.GetClassLinker();
540 Handle<mirror::ObjectArray<mirror::Class>> inline_cache = hs->NewHandle(
541 mirror::ObjectArray<mirror::Class>::Alloc(
542 self,
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100543 GetClassRoot<mirror::ObjectArray<mirror::Class>>(class_linker),
Calin Juravle13439f02017-02-21 01:17:21 -0800544 InlineCache::kIndividualCacheSize));
545 if (inline_cache == nullptr) {
546 // We got an OOME. Just clear the exception, and don't inline.
547 DCHECK(self->IsExceptionPending());
548 self->ClearException();
549 VLOG(compiler) << "Out of memory in the compiler when trying to inline";
550 }
551 return inline_cache;
552}
553
Calin Juravleaf44e6c2017-05-23 14:24:55 -0700554bool HInliner::UseOnlyPolymorphicInliningWithNoDeopt() {
555 // If we are compiling AOT or OSR, pretend the call using inline caches is polymorphic and
556 // do not generate a deopt.
557 //
558 // For AOT:
559 // Generating a deopt does not ensure that we will actually capture the new types;
560 // and the danger is that we could be stuck in a loop with "forever" deoptimizations.
561 // Take for example the following scenario:
562 // - we capture the inline cache in one run
563 // - the next run, we deoptimize because we miss a type check, but the method
564 // never becomes hot again
565 // In this case, the inline cache will not be updated in the profile and the AOT code
566 // will keep deoptimizing.
567 // Another scenario is if we use profile compilation for a process which is not allowed
568 // to JIT (e.g. system server). If we deoptimize we will run interpreted code for the
569 // rest of the lifetime.
570 // TODO(calin):
571 // This is a compromise because we will most likely never update the inline cache
572 // in the profile (unless there's another reason to deopt). So we might be stuck with
573 // a sub-optimal inline cache.
574 // We could be smarter when capturing inline caches to mitigate this.
575 // (e.g. by having different thresholds for new and old methods).
576 //
577 // For OSR:
578 // We may come from the interpreter and it may have seen different receiver types.
579 return Runtime::Current()->IsAotCompiler() || outermost_graph_->IsCompilingOsr();
580}
Calin Juravle13439f02017-02-21 01:17:21 -0800581bool HInliner::TryInlineFromInlineCache(const DexFile& caller_dex_file,
582 HInvoke* invoke_instruction,
583 ArtMethod* resolved_method)
584 REQUIRES_SHARED(Locks::mutator_lock_) {
Calin Juravlee2492d42017-03-20 11:42:13 -0700585 if (Runtime::Current()->IsAotCompiler() && !kUseAOTInlineCaches) {
586 return false;
587 }
588
Calin Juravle13439f02017-02-21 01:17:21 -0800589 StackHandleScope<1> hs(Thread::Current());
590 Handle<mirror::ObjectArray<mirror::Class>> inline_cache;
591 InlineCacheType inline_cache_type = Runtime::Current()->IsAotCompiler()
592 ? GetInlineCacheAOT(caller_dex_file, invoke_instruction, &hs, &inline_cache)
593 : GetInlineCacheJIT(invoke_instruction, &hs, &inline_cache);
594
595 switch (inline_cache_type) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000596 case kInlineCacheNoData: {
597 LOG_FAIL_NO_STAT()
598 << "Interface or virtual call to "
599 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
600 << " could not be statically determined";
Calin Juravle13439f02017-02-21 01:17:21 -0800601 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000602 }
Calin Juravle13439f02017-02-21 01:17:21 -0800603
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000604 case kInlineCacheUninitialized: {
605 LOG_FAIL_NO_STAT()
606 << "Interface or virtual call to "
607 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
608 << " is not hit and not inlined";
609 return false;
610 }
611
612 case kInlineCacheMonomorphic: {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000613 MaybeRecordStat(stats_, MethodCompilationStat::kMonomorphicCall);
Calin Juravleaf44e6c2017-05-23 14:24:55 -0700614 if (UseOnlyPolymorphicInliningWithNoDeopt()) {
Calin Juravle13439f02017-02-21 01:17:21 -0800615 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000616 } else {
Calin Juravle13439f02017-02-21 01:17:21 -0800617 return TryInlineMonomorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000618 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000619 }
Calin Juravle13439f02017-02-21 01:17:21 -0800620
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000621 case kInlineCachePolymorphic: {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000622 MaybeRecordStat(stats_, MethodCompilationStat::kPolymorphicCall);
Calin Juravle13439f02017-02-21 01:17:21 -0800623 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000624 }
Calin Juravle13439f02017-02-21 01:17:21 -0800625
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000626 case kInlineCacheMegamorphic: {
627 LOG_FAIL_NO_STAT()
628 << "Interface or virtual call to "
629 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
630 << " is megamorphic and not inlined";
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000631 MaybeRecordStat(stats_, MethodCompilationStat::kMegamorphicCall);
Calin Juravle13439f02017-02-21 01:17:21 -0800632 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000633 }
Calin Juravle13439f02017-02-21 01:17:21 -0800634
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000635 case kInlineCacheMissingTypes: {
636 LOG_FAIL_NO_STAT()
637 << "Interface or virtual call to "
638 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
639 << " is missing types and not inlined";
Calin Juravle13439f02017-02-21 01:17:21 -0800640 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000641 }
Calin Juravle13439f02017-02-21 01:17:21 -0800642 }
643 UNREACHABLE();
644}
645
646HInliner::InlineCacheType HInliner::GetInlineCacheJIT(
647 HInvoke* invoke_instruction,
648 StackHandleScope<1>* hs,
649 /*out*/Handle<mirror::ObjectArray<mirror::Class>>* inline_cache)
650 REQUIRES_SHARED(Locks::mutator_lock_) {
651 DCHECK(Runtime::Current()->UseJitCompilation());
652
653 ArtMethod* caller = graph_->GetArtMethod();
654 // Under JIT, we should always know the caller.
655 DCHECK(caller != nullptr);
656 ScopedProfilingInfoInlineUse spiis(caller, Thread::Current());
657 ProfilingInfo* profiling_info = spiis.GetProfilingInfo();
658
659 if (profiling_info == nullptr) {
660 return kInlineCacheNoData;
661 }
662
663 *inline_cache = AllocateInlineCacheHolder(caller_compilation_unit_, hs);
664 if (inline_cache->Get() == nullptr) {
665 // We can't extract any data if we failed to allocate;
666 return kInlineCacheNoData;
667 } else {
668 Runtime::Current()->GetJit()->GetCodeCache()->CopyInlineCacheInto(
669 *profiling_info->GetInlineCache(invoke_instruction->GetDexPc()),
670 *inline_cache);
671 return GetInlineCacheType(*inline_cache);
672 }
673}
674
675HInliner::InlineCacheType HInliner::GetInlineCacheAOT(
676 const DexFile& caller_dex_file,
677 HInvoke* invoke_instruction,
678 StackHandleScope<1>* hs,
679 /*out*/Handle<mirror::ObjectArray<mirror::Class>>* inline_cache)
680 REQUIRES_SHARED(Locks::mutator_lock_) {
681 DCHECK(Runtime::Current()->IsAotCompiler());
Vladimir Marko1a2a5cd2018-11-07 15:39:48 +0000682 const ProfileCompilationInfo* pci = codegen_->GetCompilerOptions().GetProfileCompilationInfo();
Calin Juravle13439f02017-02-21 01:17:21 -0800683 if (pci == nullptr) {
684 return kInlineCacheNoData;
685 }
686
Calin Juravlecc3171a2017-05-19 16:47:53 -0700687 std::unique_ptr<ProfileCompilationInfo::OfflineProfileMethodInfo> offline_profile =
688 pci->GetMethod(caller_dex_file.GetLocation(),
689 caller_dex_file.GetLocationChecksum(),
690 caller_compilation_unit_.GetDexMethodIndex());
691 if (offline_profile == nullptr) {
Calin Juravle13439f02017-02-21 01:17:21 -0800692 return kInlineCacheNoData; // no profile information for this invocation.
693 }
694
695 *inline_cache = AllocateInlineCacheHolder(caller_compilation_unit_, hs);
696 if (inline_cache == nullptr) {
697 // We can't extract any data if we failed to allocate;
698 return kInlineCacheNoData;
699 } else {
700 return ExtractClassesFromOfflineProfile(invoke_instruction,
Calin Juravlecc3171a2017-05-19 16:47:53 -0700701 *(offline_profile.get()),
Calin Juravle13439f02017-02-21 01:17:21 -0800702 *inline_cache);
703 }
704}
705
706HInliner::InlineCacheType HInliner::ExtractClassesFromOfflineProfile(
707 const HInvoke* invoke_instruction,
708 const ProfileCompilationInfo::OfflineProfileMethodInfo& offline_profile,
709 /*out*/Handle<mirror::ObjectArray<mirror::Class>> inline_cache)
710 REQUIRES_SHARED(Locks::mutator_lock_) {
Calin Juravlee6f87cc2017-05-24 17:41:05 -0700711 const auto it = offline_profile.inline_caches->find(invoke_instruction->GetDexPc());
712 if (it == offline_profile.inline_caches->end()) {
Calin Juravle13439f02017-02-21 01:17:21 -0800713 return kInlineCacheUninitialized;
714 }
715
716 const ProfileCompilationInfo::DexPcData& dex_pc_data = it->second;
717
718 if (dex_pc_data.is_missing_types) {
719 return kInlineCacheMissingTypes;
720 }
721 if (dex_pc_data.is_megamorphic) {
722 return kInlineCacheMegamorphic;
723 }
724
725 DCHECK_LE(dex_pc_data.classes.size(), InlineCache::kIndividualCacheSize);
726 Thread* self = Thread::Current();
727 // We need to resolve the class relative to the containing dex file.
728 // So first, build a mapping from the index of dex file in the profile to
729 // its dex cache. This will avoid repeating the lookup when walking over
730 // the inline cache types.
731 std::vector<ObjPtr<mirror::DexCache>> dex_profile_index_to_dex_cache(
732 offline_profile.dex_references.size());
733 for (size_t i = 0; i < offline_profile.dex_references.size(); i++) {
734 bool found = false;
Vladimir Marko213ee2d2018-06-22 11:56:34 +0100735 for (const DexFile* dex_file : codegen_->GetCompilerOptions().GetDexFilesForOatFile()) {
Calin Juravle13439f02017-02-21 01:17:21 -0800736 if (offline_profile.dex_references[i].MatchesDex(dex_file)) {
737 dex_profile_index_to_dex_cache[i] =
738 caller_compilation_unit_.GetClassLinker()->FindDexCache(self, *dex_file);
739 found = true;
740 }
741 }
742 if (!found) {
743 VLOG(compiler) << "Could not find profiled dex file: "
744 << offline_profile.dex_references[i].dex_location;
745 return kInlineCacheMissingTypes;
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100746 }
747 }
748
Calin Juravle13439f02017-02-21 01:17:21 -0800749 // Walk over the classes and resolve them. If we cannot find a type we return
750 // kInlineCacheMissingTypes.
751 int ic_index = 0;
752 for (const ProfileCompilationInfo::ClassReference& class_ref : dex_pc_data.classes) {
753 ObjPtr<mirror::DexCache> dex_cache =
754 dex_profile_index_to_dex_cache[class_ref.dex_profile_index];
755 DCHECK(dex_cache != nullptr);
Calin Juravle08556882017-05-26 16:40:45 -0700756
757 if (!dex_cache->GetDexFile()->IsTypeIndexValid(class_ref.type_index)) {
758 VLOG(compiler) << "Profile data corrupt: type index " << class_ref.type_index
759 << "is invalid in location" << dex_cache->GetDexFile()->GetLocation();
760 return kInlineCacheNoData;
761 }
Vladimir Marko666ee3d2017-12-11 18:37:36 +0000762 ObjPtr<mirror::Class> clazz = caller_compilation_unit_.GetClassLinker()->LookupResolvedType(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000763 class_ref.type_index,
764 dex_cache,
765 caller_compilation_unit_.GetClassLoader().Get());
Calin Juravle13439f02017-02-21 01:17:21 -0800766 if (clazz != nullptr) {
767 inline_cache->Set(ic_index++, clazz);
768 } else {
769 VLOG(compiler) << "Could not resolve class from inline cache in AOT mode "
770 << caller_compilation_unit_.GetDexFile()->PrettyMethod(
771 invoke_instruction->GetDexMethodIndex()) << " : "
772 << caller_compilation_unit_
773 .GetDexFile()->StringByTypeIdx(class_ref.type_index);
774 return kInlineCacheMissingTypes;
775 }
776 }
777 return GetInlineCacheType(inline_cache);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100778}
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000779
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000780HInstanceFieldGet* HInliner::BuildGetReceiverClass(ClassLinker* class_linker,
781 HInstruction* receiver,
782 uint32_t dex_pc) const {
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100783 ArtField* field = GetClassRoot<mirror::Object>(class_linker)->GetInstanceField(0);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000784 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
Vladimir Markoca6fff82017-10-03 14:49:14 +0100785 HInstanceFieldGet* result = new (graph_->GetAllocator()) HInstanceFieldGet(
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000786 receiver,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000787 field,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100788 DataType::Type::kReference,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000789 field->GetOffset(),
790 field->IsVolatile(),
791 field->GetDexFieldIndex(),
792 field->GetDeclaringClass()->GetDexClassDefIndex(),
793 *field->GetDexFile(),
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000794 dex_pc);
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000795 // The class of a field is effectively final, and does not have any memory dependencies.
796 result->SetSideEffects(SideEffects::None());
797 return result;
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000798}
799
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000800static ArtMethod* ResolveMethodFromInlineCache(Handle<mirror::Class> klass,
801 ArtMethod* resolved_method,
802 HInstruction* invoke_instruction,
803 PointerSize pointer_size)
804 REQUIRES_SHARED(Locks::mutator_lock_) {
805 if (Runtime::Current()->IsAotCompiler()) {
806 // We can get unrelated types when working with profiles (corruption,
807 // systme updates, or anyone can write to it). So first check if the class
808 // actually implements the declaring class of the method that is being
809 // called in bytecode.
810 // Note: the lookup methods used below require to have assignable types.
811 if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(klass.Get())) {
812 return nullptr;
813 }
814 }
815
816 if (invoke_instruction->IsInvokeInterface()) {
817 resolved_method = klass->FindVirtualMethodForInterface(resolved_method, pointer_size);
818 } else {
819 DCHECK(invoke_instruction->IsInvokeVirtual());
820 resolved_method = klass->FindVirtualMethodForVirtual(resolved_method, pointer_size);
821 }
822 DCHECK(resolved_method != nullptr);
823 return resolved_method;
824}
825
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100826bool HInliner::TryInlineMonomorphicCall(HInvoke* invoke_instruction,
827 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000828 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000829 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
830 << invoke_instruction->DebugName();
831
Andreas Gampea5b09a62016-11-17 15:21:22 -0800832 dex::TypeIndex class_index = FindClassIndexIn(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000833 GetMonomorphicType(classes), caller_compilation_unit_);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800834 if (!class_index.IsValid()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000835 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedDexCache)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000836 << "Call to " << ArtMethod::PrettyMethod(resolved_method)
837 << " from inline cache is not inlined because its class is not"
838 << " accessible to the caller";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100839 return false;
840 }
841
842 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700843 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000844 Handle<mirror::Class> monomorphic_type = handles_->NewHandle(GetMonomorphicType(classes));
845 resolved_method = ResolveMethodFromInlineCache(
846 monomorphic_type, resolved_method, invoke_instruction, pointer_size);
847
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000848 LOG_NOTE() << "Try inline monomorphic call to " << resolved_method->PrettyMethod();
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000849 if (resolved_method == nullptr) {
850 // Bogus AOT profile, bail.
851 DCHECK(Runtime::Current()->IsAotCompiler());
852 return false;
853 }
854
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100855 HInstruction* receiver = invoke_instruction->InputAt(0);
856 HInstruction* cursor = invoke_instruction->GetPrevious();
857 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Mingyao Yang063fc772016-08-02 11:02:54 -0700858 if (!TryInlineAndReplace(invoke_instruction,
859 resolved_method,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000860 ReferenceTypeInfo::Create(monomorphic_type, /* is_exact */ true),
Mingyao Yang063fc772016-08-02 11:02:54 -0700861 /* do_rtp */ false,
862 /* cha_devirtualize */ false)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100863 return false;
864 }
865
866 // We successfully inlined, now add a guard.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000867 AddTypeGuard(receiver,
868 cursor,
869 bb_cursor,
870 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000871 monomorphic_type,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000872 invoke_instruction,
873 /* with_deoptimization */ true);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100874
875 // Run type propagation to get the guard typed, and eventually propagate the
876 // type of the receiver.
Vladimir Marko456307a2016-04-19 14:12:13 +0000877 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000878 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +0000879 outer_compilation_unit_.GetDexCache(),
880 handles_,
881 /* is_first_run */ false);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100882 rtp_fixup.Run();
883
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000884 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedMonomorphicCall);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100885 return true;
886}
887
Mingyao Yang063fc772016-08-02 11:02:54 -0700888void HInliner::AddCHAGuard(HInstruction* invoke_instruction,
889 uint32_t dex_pc,
890 HInstruction* cursor,
891 HBasicBlock* bb_cursor) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100892 HShouldDeoptimizeFlag* deopt_flag = new (graph_->GetAllocator())
893 HShouldDeoptimizeFlag(graph_->GetAllocator(), dex_pc);
894 HInstruction* compare = new (graph_->GetAllocator()) HNotEqual(
Mingyao Yang063fc772016-08-02 11:02:54 -0700895 deopt_flag, graph_->GetIntConstant(0, dex_pc));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100896 HInstruction* deopt = new (graph_->GetAllocator()) HDeoptimize(
897 graph_->GetAllocator(), compare, DeoptimizationKind::kCHA, dex_pc);
Mingyao Yang063fc772016-08-02 11:02:54 -0700898
899 if (cursor != nullptr) {
900 bb_cursor->InsertInstructionAfter(deopt_flag, cursor);
901 } else {
902 bb_cursor->InsertInstructionBefore(deopt_flag, bb_cursor->GetFirstInstruction());
903 }
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800904 bb_cursor->InsertInstructionAfter(compare, deopt_flag);
905 bb_cursor->InsertInstructionAfter(deopt, compare);
906
907 // Add receiver as input to aid CHA guard optimization later.
908 deopt_flag->AddInput(invoke_instruction->InputAt(0));
909 DCHECK_EQ(deopt_flag->InputCount(), 1u);
Mingyao Yang063fc772016-08-02 11:02:54 -0700910 deopt->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800911 outermost_graph_->IncrementNumberOfCHAGuards();
Mingyao Yang063fc772016-08-02 11:02:54 -0700912}
913
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000914HInstruction* HInliner::AddTypeGuard(HInstruction* receiver,
915 HInstruction* cursor,
916 HBasicBlock* bb_cursor,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800917 dex::TypeIndex class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000918 Handle<mirror::Class> klass,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000919 HInstruction* invoke_instruction,
920 bool with_deoptimization) {
921 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
922 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
923 class_linker, receiver, invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000924 if (cursor != nullptr) {
925 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
926 } else {
927 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
928 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000929
930 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Calin Juravle07f01df2017-04-28 19:58:01 -0700931 bool is_referrer;
932 ArtMethod* outermost_art_method = outermost_graph_->GetArtMethod();
933 if (outermost_art_method == nullptr) {
934 DCHECK(Runtime::Current()->IsAotCompiler());
935 // We are in AOT mode and we don't have an ART method to determine
936 // if the inlined method belongs to the referrer. Assume it doesn't.
937 is_referrer = false;
938 } else {
939 is_referrer = klass.Get() == outermost_art_method->GetDeclaringClass();
940 }
941
Nicolas Geoffray56876342016-12-16 16:09:08 +0000942 // Note that we will just compare the classes, so we don't need Java semantics access checks.
943 // Note that the type index and the dex file are relative to the method this type guard is
944 // inlined into.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100945 HLoadClass* load_class = new (graph_->GetAllocator()) HLoadClass(graph_->GetCurrentMethod(),
946 class_index,
947 caller_dex_file,
948 klass,
949 is_referrer,
950 invoke_instruction->GetDexPc(),
951 /* needs_access_check */ false);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000952 HLoadClass::LoadKind kind = HSharpening::ComputeLoadClassKind(
Vladimir Markobb089b62018-06-28 17:30:16 +0100953 load_class, codegen_, caller_compilation_unit_);
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000954 DCHECK(kind != HLoadClass::LoadKind::kInvalid)
955 << "We should always be able to reference a class for inline caches";
Vladimir Marko28e012a2017-12-07 11:22:59 +0000956 // Load kind must be set before inserting the instruction into the graph.
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000957 load_class->SetLoadKind(kind);
Vladimir Marko28e012a2017-12-07 11:22:59 +0000958 bb_cursor->InsertInstructionAfter(load_class, receiver_class);
Calin Juravle13439f02017-02-21 01:17:21 -0800959 // In AOT mode, we will most likely load the class from BSS, which will involve a call
960 // to the runtime. In this case, the load instruction will need an environment so copy
961 // it from the invoke instruction.
962 if (load_class->NeedsEnvironment()) {
963 DCHECK(Runtime::Current()->IsAotCompiler());
964 load_class->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
965 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000966
Vladimir Markoca6fff82017-10-03 14:49:14 +0100967 HNotEqual* compare = new (graph_->GetAllocator()) HNotEqual(load_class, receiver_class);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000968 bb_cursor->InsertInstructionAfter(compare, load_class);
969 if (with_deoptimization) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100970 HDeoptimize* deoptimize = new (graph_->GetAllocator()) HDeoptimize(
971 graph_->GetAllocator(),
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000972 compare,
973 receiver,
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +0100974 Runtime::Current()->IsAotCompiler()
975 ? DeoptimizationKind::kAotInlineCache
976 : DeoptimizationKind::kJitInlineCache,
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000977 invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000978 bb_cursor->InsertInstructionAfter(deoptimize, compare);
979 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000980 DCHECK_EQ(invoke_instruction->InputAt(0), receiver);
981 receiver->ReplaceUsesDominatedBy(deoptimize, deoptimize);
982 deoptimize->SetReferenceTypeInfo(receiver->GetReferenceTypeInfo());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000983 }
984 return compare;
985}
986
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000987bool HInliner::TryInlinePolymorphicCall(HInvoke* invoke_instruction,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100988 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000989 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000990 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
991 << invoke_instruction->DebugName();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000992
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000993 if (TryInlinePolymorphicCallToSameTarget(invoke_instruction, resolved_method, classes)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000994 return true;
995 }
996
997 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700998 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000999
1000 bool all_targets_inlined = true;
1001 bool one_target_inlined = false;
1002 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001003 if (classes->Get(i) == nullptr) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001004 break;
1005 }
1006 ArtMethod* method = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001007
1008 Handle<mirror::Class> handle = handles_->NewHandle(classes->Get(i));
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +00001009 method = ResolveMethodFromInlineCache(
1010 handle, resolved_method, invoke_instruction, pointer_size);
1011 if (method == nullptr) {
1012 DCHECK(Runtime::Current()->IsAotCompiler());
1013 // AOT profile is bogus. This loop expects to iterate over all entries,
1014 // so just just continue.
1015 all_targets_inlined = false;
1016 continue;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001017 }
1018
1019 HInstruction* receiver = invoke_instruction->InputAt(0);
1020 HInstruction* cursor = invoke_instruction->GetPrevious();
1021 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
1022
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001023 dex::TypeIndex class_index = FindClassIndexIn(handle.Get(), caller_compilation_unit_);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001024 HInstruction* return_replacement = nullptr;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001025 LOG_NOTE() << "Try inline polymorphic call to " << method->PrettyMethod();
Andreas Gampea5b09a62016-11-17 15:21:22 -08001026 if (!class_index.IsValid() ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001027 !TryBuildAndInline(invoke_instruction,
1028 method,
1029 ReferenceTypeInfo::Create(handle, /* is_exact */ true),
1030 &return_replacement)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001031 all_targets_inlined = false;
1032 } else {
1033 one_target_inlined = true;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001034
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001035 LOG_SUCCESS() << "Polymorphic call to " << ArtMethod::PrettyMethod(resolved_method)
1036 << " has inlined " << ArtMethod::PrettyMethod(method);
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001037
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001038 // If we have inlined all targets before, and this receiver is the last seen,
1039 // we deoptimize instead of keeping the original invoke instruction.
Calin Juravleaf44e6c2017-05-23 14:24:55 -07001040 bool deoptimize = !UseOnlyPolymorphicInliningWithNoDeopt() &&
1041 all_targets_inlined &&
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001042 (i != InlineCache::kIndividualCacheSize - 1) &&
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001043 (classes->Get(i + 1) == nullptr);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001044
Nicolas Geoffray56876342016-12-16 16:09:08 +00001045 HInstruction* compare = AddTypeGuard(receiver,
1046 cursor,
1047 bb_cursor,
1048 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +00001049 handle,
Nicolas Geoffray56876342016-12-16 16:09:08 +00001050 invoke_instruction,
1051 deoptimize);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001052 if (deoptimize) {
1053 if (return_replacement != nullptr) {
1054 invoke_instruction->ReplaceWith(return_replacement);
1055 }
1056 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
1057 // Because the inline cache data can be populated concurrently, we force the end of the
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +00001058 // iteration. Otherwise, we could see a new receiver type.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001059 break;
1060 } else {
1061 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
1062 }
1063 }
1064 }
1065
1066 if (!one_target_inlined) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001067 LOG_FAIL_NO_STAT()
1068 << "Call to " << ArtMethod::PrettyMethod(resolved_method)
1069 << " from inline cache is not inlined because none"
1070 << " of its targets could be inlined";
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001071 return false;
1072 }
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001073
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001074 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedPolymorphicCall);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001075
1076 // Run type propagation to get the guards typed.
Vladimir Marko456307a2016-04-19 14:12:13 +00001077 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001078 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +00001079 outer_compilation_unit_.GetDexCache(),
1080 handles_,
1081 /* is_first_run */ false);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001082 rtp_fixup.Run();
1083 return true;
1084}
1085
1086void HInliner::CreateDiamondPatternForPolymorphicInline(HInstruction* compare,
1087 HInstruction* return_replacement,
1088 HInstruction* invoke_instruction) {
1089 uint32_t dex_pc = invoke_instruction->GetDexPc();
1090 HBasicBlock* cursor_block = compare->GetBlock();
1091 HBasicBlock* original_invoke_block = invoke_instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001092 ArenaAllocator* allocator = graph_->GetAllocator();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001093
1094 // Spit the block after the compare: `cursor_block` will now be the start of the diamond,
1095 // and the returned block is the start of the then branch (that could contain multiple blocks).
1096 HBasicBlock* then = cursor_block->SplitAfterForInlining(compare);
1097
1098 // Split the block containing the invoke before and after the invoke. The returned block
1099 // of the split before will contain the invoke and will be the otherwise branch of
1100 // the diamond. The returned block of the split after will be the merge block
1101 // of the diamond.
1102 HBasicBlock* end_then = invoke_instruction->GetBlock();
1103 HBasicBlock* otherwise = end_then->SplitBeforeForInlining(invoke_instruction);
1104 HBasicBlock* merge = otherwise->SplitAfterForInlining(invoke_instruction);
1105
1106 // If the methods we are inlining return a value, we create a phi in the merge block
1107 // that will have the `invoke_instruction and the `return_replacement` as inputs.
1108 if (return_replacement != nullptr) {
1109 HPhi* phi = new (allocator) HPhi(
1110 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke_instruction->GetType()), dex_pc);
1111 merge->AddPhi(phi);
1112 invoke_instruction->ReplaceWith(phi);
1113 phi->AddInput(return_replacement);
1114 phi->AddInput(invoke_instruction);
1115 }
1116
1117 // Add the control flow instructions.
1118 otherwise->AddInstruction(new (allocator) HGoto(dex_pc));
1119 end_then->AddInstruction(new (allocator) HGoto(dex_pc));
1120 cursor_block->AddInstruction(new (allocator) HIf(compare, dex_pc));
1121
1122 // Add the newly created blocks to the graph.
1123 graph_->AddBlock(then);
1124 graph_->AddBlock(otherwise);
1125 graph_->AddBlock(merge);
1126
1127 // Set up successor (and implictly predecessor) relations.
1128 cursor_block->AddSuccessor(otherwise);
1129 cursor_block->AddSuccessor(then);
1130 end_then->AddSuccessor(merge);
1131 otherwise->AddSuccessor(merge);
1132
1133 // Set up dominance information.
1134 then->SetDominator(cursor_block);
1135 cursor_block->AddDominatedBlock(then);
1136 otherwise->SetDominator(cursor_block);
1137 cursor_block->AddDominatedBlock(otherwise);
1138 merge->SetDominator(cursor_block);
1139 cursor_block->AddDominatedBlock(merge);
1140
1141 // Update the revert post order.
1142 size_t index = IndexOfElement(graph_->reverse_post_order_, cursor_block);
1143 MakeRoomFor(&graph_->reverse_post_order_, 1, index);
1144 graph_->reverse_post_order_[++index] = then;
1145 index = IndexOfElement(graph_->reverse_post_order_, end_then);
1146 MakeRoomFor(&graph_->reverse_post_order_, 2, index);
1147 graph_->reverse_post_order_[++index] = otherwise;
1148 graph_->reverse_post_order_[++index] = merge;
1149
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001150
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001151 graph_->UpdateLoopAndTryInformationOfNewBlock(
1152 then, original_invoke_block, /* replace_if_back_edge */ false);
1153 graph_->UpdateLoopAndTryInformationOfNewBlock(
1154 otherwise, original_invoke_block, /* replace_if_back_edge */ false);
1155
1156 // In case the original invoke location was a back edge, we need to update
1157 // the loop to now have the merge block as a back edge.
1158 graph_->UpdateLoopAndTryInformationOfNewBlock(
1159 merge, original_invoke_block, /* replace_if_back_edge */ true);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001160}
1161
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001162bool HInliner::TryInlinePolymorphicCallToSameTarget(
1163 HInvoke* invoke_instruction,
1164 ArtMethod* resolved_method,
1165 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001166 // This optimization only works under JIT for now.
Calin Juravle13439f02017-02-21 01:17:21 -08001167 if (!Runtime::Current()->UseJitCompilation()) {
1168 return false;
1169 }
1170
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001171 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -07001172 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001173
1174 DCHECK(resolved_method != nullptr);
1175 ArtMethod* actual_method = nullptr;
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001176 size_t method_index = invoke_instruction->IsInvokeVirtual()
1177 ? invoke_instruction->AsInvokeVirtual()->GetVTableIndex()
1178 : invoke_instruction->AsInvokeInterface()->GetImtIndex();
1179
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001180 // Check whether we are actually calling the same method among
1181 // the different types seen.
1182 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001183 if (classes->Get(i) == nullptr) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001184 break;
1185 }
1186 ArtMethod* new_method = nullptr;
1187 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001188 new_method = classes->Get(i)->GetImt(pointer_size)->Get(
Matthew Gharrity465ecc82016-07-19 21:32:52 +00001189 method_index, pointer_size);
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001190 if (new_method->IsRuntimeMethod()) {
1191 // Bail out as soon as we see a conflict trampoline in one of the target's
1192 // interface table.
1193 return false;
1194 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001195 } else {
1196 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001197 new_method = classes->Get(i)->GetEmbeddedVTableEntry(method_index, pointer_size);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001198 }
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001199 DCHECK(new_method != nullptr);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001200 if (actual_method == nullptr) {
1201 actual_method = new_method;
1202 } else if (actual_method != new_method) {
1203 // Different methods, bailout.
1204 return false;
1205 }
1206 }
1207
1208 HInstruction* receiver = invoke_instruction->InputAt(0);
1209 HInstruction* cursor = invoke_instruction->GetPrevious();
1210 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
1211
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001212 HInstruction* return_replacement = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001213 if (!TryBuildAndInline(invoke_instruction,
1214 actual_method,
1215 ReferenceTypeInfo::CreateInvalid(),
1216 &return_replacement)) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001217 return false;
1218 }
1219
1220 // We successfully inlined, now add a guard.
1221 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
1222 class_linker, receiver, invoke_instruction->GetDexPc());
1223
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001224 DataType::Type type = Is64BitInstructionSet(graph_->GetInstructionSet())
1225 ? DataType::Type::kInt64
1226 : DataType::Type::kInt32;
Vladimir Markoca6fff82017-10-03 14:49:14 +01001227 HClassTableGet* class_table_get = new (graph_->GetAllocator()) HClassTableGet(
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001228 receiver_class,
1229 type,
Vladimir Markoa1de9182016-02-25 11:37:38 +00001230 invoke_instruction->IsInvokeVirtual() ? HClassTableGet::TableKind::kVTable
1231 : HClassTableGet::TableKind::kIMTable,
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001232 method_index,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001233 invoke_instruction->GetDexPc());
1234
1235 HConstant* constant;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001236 if (type == DataType::Type::kInt64) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001237 constant = graph_->GetLongConstant(
1238 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
1239 } else {
1240 constant = graph_->GetIntConstant(
1241 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
1242 }
1243
Vladimir Markoca6fff82017-10-03 14:49:14 +01001244 HNotEqual* compare = new (graph_->GetAllocator()) HNotEqual(class_table_get, constant);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001245 if (cursor != nullptr) {
1246 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
1247 } else {
1248 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
1249 }
1250 bb_cursor->InsertInstructionAfter(class_table_get, receiver_class);
1251 bb_cursor->InsertInstructionAfter(compare, class_table_get);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001252
1253 if (outermost_graph_->IsCompilingOsr()) {
1254 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
1255 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +01001256 HDeoptimize* deoptimize = new (graph_->GetAllocator()) HDeoptimize(
1257 graph_->GetAllocator(),
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001258 compare,
1259 receiver,
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +01001260 DeoptimizationKind::kJitSameTarget,
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001261 invoke_instruction->GetDexPc());
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001262 bb_cursor->InsertInstructionAfter(deoptimize, compare);
1263 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
1264 if (return_replacement != nullptr) {
1265 invoke_instruction->ReplaceWith(return_replacement);
1266 }
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001267 receiver->ReplaceUsesDominatedBy(deoptimize, deoptimize);
Nicolas Geoffray1be7cbd2016-04-29 13:56:01 +01001268 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001269 deoptimize->SetReferenceTypeInfo(receiver->GetReferenceTypeInfo());
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001270 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001271
1272 // Run type propagation to get the guard typed.
Vladimir Marko456307a2016-04-19 14:12:13 +00001273 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001274 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +00001275 outer_compilation_unit_.GetDexCache(),
1276 handles_,
1277 /* is_first_run */ false);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001278 rtp_fixup.Run();
1279
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001280 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedPolymorphicCall);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001281
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001282 LOG_SUCCESS() << "Inlined same polymorphic target " << actual_method->PrettyMethod();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001283 return true;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001284}
1285
Mingyao Yang063fc772016-08-02 11:02:54 -07001286bool HInliner::TryInlineAndReplace(HInvoke* invoke_instruction,
1287 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001288 ReferenceTypeInfo receiver_type,
Mingyao Yang063fc772016-08-02 11:02:54 -07001289 bool do_rtp,
1290 bool cha_devirtualize) {
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001291 DCHECK(!invoke_instruction->IsIntrinsic());
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001292 HInstruction* return_replacement = nullptr;
Mingyao Yang063fc772016-08-02 11:02:54 -07001293 uint32_t dex_pc = invoke_instruction->GetDexPc();
1294 HInstruction* cursor = invoke_instruction->GetPrevious();
1295 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001296 bool should_remove_invoke_instruction = false;
1297
1298 // If invoke_instruction is devirtualized to a different method, give intrinsics
1299 // another chance before we try to inline it.
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01001300 if (invoke_instruction->GetResolvedMethod() != method && method->IsIntrinsic()) {
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001301 MaybeRecordStat(stats_, MethodCompilationStat::kIntrinsicRecognized);
1302 if (invoke_instruction->IsInvokeInterface()) {
1303 // We don't intrinsify an invoke-interface directly.
1304 // Replace the invoke-interface with an invoke-virtual.
1305 HInvokeVirtual* new_invoke = new (graph_->GetAllocator()) HInvokeVirtual(
1306 graph_->GetAllocator(),
1307 invoke_instruction->GetNumberOfArguments(),
1308 invoke_instruction->GetType(),
1309 invoke_instruction->GetDexPc(),
1310 invoke_instruction->GetDexMethodIndex(), // Use interface method's dex method index.
1311 method,
1312 method->GetMethodIndex());
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01001313 DCHECK_NE(new_invoke->GetIntrinsic(), Intrinsics::kNone);
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001314 HInputsRef inputs = invoke_instruction->GetInputs();
1315 for (size_t index = 0; index != inputs.size(); ++index) {
1316 new_invoke->SetArgumentAt(index, inputs[index]);
1317 }
1318 invoke_instruction->GetBlock()->InsertInstructionBefore(new_invoke, invoke_instruction);
1319 new_invoke->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
1320 if (invoke_instruction->GetType() == DataType::Type::kReference) {
1321 new_invoke->SetReferenceTypeInfo(invoke_instruction->GetReferenceTypeInfo());
1322 }
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001323 return_replacement = new_invoke;
1324 // invoke_instruction is replaced with new_invoke.
1325 should_remove_invoke_instruction = true;
1326 } else {
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01001327 invoke_instruction->SetResolvedMethod(method);
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001328 }
1329 } else if (!TryBuildAndInline(invoke_instruction, method, receiver_type, &return_replacement)) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001330 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +00001331 DCHECK(!method->IsProxyMethod());
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001332 // Turn an invoke-interface into an invoke-virtual. An invoke-virtual is always
1333 // better than an invoke-interface because:
1334 // 1) In the best case, the interface call has one more indirection (to fetch the IMT).
1335 // 2) We will not go to the conflict trampoline with an invoke-virtual.
1336 // TODO: Consider sharpening once it is not dependent on the compiler driver.
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +00001337
1338 if (method->IsDefault() && !method->IsCopied()) {
1339 // Changing to invoke-virtual cannot be done on an original default method
1340 // since it's not in any vtable. Devirtualization by exact type/inline-cache
1341 // always uses a method in the iftable which is never an original default
1342 // method.
1343 // On the other hand, inlining an original default method by CHA is fine.
1344 DCHECK(cha_devirtualize);
1345 return false;
1346 }
1347
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001348 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001349 uint32_t dex_method_index = FindMethodIndexIn(
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001350 method, caller_dex_file, invoke_instruction->GetDexMethodIndex());
Andreas Gampee2abbc62017-09-15 11:59:26 -07001351 if (dex_method_index == dex::kDexNoIndex) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001352 return false;
1353 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01001354 HInvokeVirtual* new_invoke = new (graph_->GetAllocator()) HInvokeVirtual(
1355 graph_->GetAllocator(),
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001356 invoke_instruction->GetNumberOfArguments(),
1357 invoke_instruction->GetType(),
1358 invoke_instruction->GetDexPc(),
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001359 dex_method_index,
1360 method,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001361 method->GetMethodIndex());
1362 HInputsRef inputs = invoke_instruction->GetInputs();
1363 for (size_t index = 0; index != inputs.size(); ++index) {
1364 new_invoke->SetArgumentAt(index, inputs[index]);
1365 }
1366 invoke_instruction->GetBlock()->InsertInstructionBefore(new_invoke, invoke_instruction);
1367 new_invoke->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001368 if (invoke_instruction->GetType() == DataType::Type::kReference) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001369 new_invoke->SetReferenceTypeInfo(invoke_instruction->GetReferenceTypeInfo());
1370 }
1371 return_replacement = new_invoke;
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001372 // invoke_instruction is replaced with new_invoke.
1373 should_remove_invoke_instruction = true;
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001374 } else {
1375 // TODO: Consider sharpening an invoke virtual once it is not dependent on the
1376 // compiler driver.
1377 return false;
1378 }
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001379 } else {
1380 // invoke_instruction is inlined.
1381 should_remove_invoke_instruction = true;
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001382 }
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001383
Mingyao Yang063fc772016-08-02 11:02:54 -07001384 if (cha_devirtualize) {
1385 AddCHAGuard(invoke_instruction, dex_pc, cursor, bb_cursor);
1386 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001387 if (return_replacement != nullptr) {
1388 invoke_instruction->ReplaceWith(return_replacement);
1389 }
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001390 if (should_remove_invoke_instruction) {
1391 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
1392 }
David Brazdil94ab38f2016-06-21 17:48:19 +01001393 FixUpReturnReferenceType(method, return_replacement);
1394 if (do_rtp && ReturnTypeMoreSpecific(invoke_instruction, return_replacement)) {
1395 // Actual return value has a more specific type than the method's declared
1396 // return type. Run RTP again on the outer graph to propagate it.
1397 ReferenceTypePropagation(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001398 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +01001399 outer_compilation_unit_.GetDexCache(),
1400 handles_,
1401 /* is_first_run */ false).Run();
1402 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001403 return true;
1404}
1405
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001406size_t HInliner::CountRecursiveCallsOf(ArtMethod* method) const {
1407 const HInliner* current = this;
1408 size_t count = 0;
1409 do {
1410 if (current->graph_->GetArtMethod() == method) {
1411 ++count;
1412 }
1413 current = current->parent_;
1414 } while (current != nullptr);
1415 return count;
1416}
1417
Vladimir Marko213ee2d2018-06-22 11:56:34 +01001418static inline bool MayInline(const CompilerOptions& compiler_options,
1419 const DexFile& inlined_from,
1420 const DexFile& inlined_into) {
1421 if (kIsTargetBuild) {
1422 return true;
1423 }
1424
1425 // We're not allowed to inline across dex files if we're the no-inline-from dex file.
1426 if (!IsSameDexFile(inlined_from, inlined_into) &&
1427 ContainsElement(compiler_options.GetNoInlineFromDexFile(), &inlined_from)) {
1428 return false;
1429 }
1430
1431 return true;
1432}
1433
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001434bool HInliner::TryBuildAndInline(HInvoke* invoke_instruction,
1435 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001436 ReferenceTypeInfo receiver_type,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001437 HInstruction** return_replacement) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001438 if (method->IsProxyMethod()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001439 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedProxy)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001440 << "Method " << method->PrettyMethod()
1441 << " is not inlined because of unimplemented inline support for proxy methods.";
1442 return false;
1443 }
1444
1445 if (CountRecursiveCallsOf(method) > kMaximumNumberOfRecursiveCalls) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001446 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedRecursiveBudget)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001447 << "Method "
1448 << method->PrettyMethod()
1449 << " is not inlined because it has reached its recursive call budget.";
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001450 return false;
1451 }
1452
Jeff Haodcdc85b2015-12-04 14:06:18 -08001453 // Check whether we're allowed to inline. The outermost compilation unit is the relevant
1454 // dex file here (though the transitivity of an inline chain would allow checking the calller).
Vladimir Marko213ee2d2018-06-22 11:56:34 +01001455 if (!MayInline(codegen_->GetCompilerOptions(),
1456 *method->GetDexFile(),
1457 *outer_compilation_unit_.GetDexFile())) {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001458 if (TryPatternSubstitution(invoke_instruction, method, return_replacement)) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001459 LOG_SUCCESS() << "Successfully replaced pattern of invoke "
1460 << method->PrettyMethod();
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001461 MaybeRecordStat(stats_, MethodCompilationStat::kReplacedInvokeWithSimplePattern);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001462 return true;
1463 }
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001464 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedWont)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001465 << "Won't inline " << method->PrettyMethod() << " in "
1466 << outer_compilation_unit_.GetDexFile()->GetLocation() << " ("
1467 << caller_compilation_unit_.GetDexFile()->GetLocation() << ") from "
1468 << method->GetDexFile()->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001469 return false;
1470 }
1471
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001472 bool same_dex_file = IsSameDexFile(*outer_compilation_unit_.GetDexFile(), *method->GetDexFile());
1473
David Sehr0225f8e2018-01-31 08:52:24 +00001474 CodeItemDataAccessor accessor(method->DexInstructionData());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001475
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001476 if (!accessor.HasCodeItem()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001477 LOG_FAIL_NO_STAT()
1478 << "Method " << method->PrettyMethod() << " is not inlined because it is native";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001479 return false;
1480 }
1481
Vladimir Marko213ee2d2018-06-22 11:56:34 +01001482 size_t inline_max_code_units = codegen_->GetCompilerOptions().GetInlineMaxCodeUnits();
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001483 if (accessor.InsnsSizeInCodeUnits() > inline_max_code_units) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001484 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedCodeItem)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001485 << "Method " << method->PrettyMethod()
1486 << " is not inlined because its code item is too big: "
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001487 << accessor.InsnsSizeInCodeUnits()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001488 << " > "
1489 << inline_max_code_units;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001490 return false;
1491 }
1492
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001493 if (accessor.TriesSize() != 0) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001494 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedTryCatch)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001495 << "Method " << method->PrettyMethod() << " is not inlined because of try block";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001496 return false;
1497 }
1498
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001499 if (!method->IsCompilable()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001500 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedNotVerified)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001501 << "Method " << method->PrettyMethod()
1502 << " has soft failures un-handled by the compiler, so it cannot be inlined";
Aart Bik897df032018-02-07 13:29:11 -08001503 return false;
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001504 }
1505
Aart Bik2c148f02018-02-02 14:30:35 -08001506 if (IsMethodUnverified(compiler_driver_, method)) {
1507 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedNotVerified)
1508 << "Method " << method->PrettyMethod()
1509 << " couldn't be verified, so it cannot be inlined";
1510 return false;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001511 }
1512
Roland Levillain4c0eb422015-04-24 16:43:49 +01001513 if (invoke_instruction->IsInvokeStaticOrDirect() &&
1514 invoke_instruction->AsInvokeStaticOrDirect()->IsStaticWithImplicitClinitCheck()) {
1515 // Case of a static method that cannot be inlined because it implicitly
1516 // requires an initialization check of its declaring class.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001517 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedDexCache)
1518 << "Method " << method->PrettyMethod()
1519 << " is not inlined because it is static and requires a clinit"
1520 << " check that cannot be emitted due to Dex cache limitations";
Roland Levillain4c0eb422015-04-24 16:43:49 +01001521 return false;
1522 }
1523
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001524 if (!TryBuildAndInlineHelper(
1525 invoke_instruction, method, receiver_type, same_dex_file, return_replacement)) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001526 return false;
1527 }
1528
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001529 LOG_SUCCESS() << method->PrettyMethod();
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001530 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedInvoke);
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001531 return true;
1532}
1533
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001534static HInstruction* GetInvokeInputForArgVRegIndex(HInvoke* invoke_instruction,
1535 size_t arg_vreg_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001536 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001537 size_t input_index = 0;
1538 for (size_t i = 0; i < arg_vreg_index; ++i, ++input_index) {
1539 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001540 if (DataType::Is64BitType(invoke_instruction->InputAt(input_index)->GetType())) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001541 ++i;
1542 DCHECK_NE(i, arg_vreg_index);
1543 }
1544 }
1545 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
1546 return invoke_instruction->InputAt(input_index);
1547}
1548
1549// Try to recognize known simple patterns and replace invoke call with appropriate instructions.
1550bool HInliner::TryPatternSubstitution(HInvoke* invoke_instruction,
1551 ArtMethod* resolved_method,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001552 HInstruction** return_replacement) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001553 InlineMethod inline_method;
1554 if (!InlineMethodAnalyser::AnalyseMethodCode(resolved_method, &inline_method)) {
1555 return false;
1556 }
1557
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001558 switch (inline_method.opcode) {
1559 case kInlineOpNop:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001560 DCHECK_EQ(invoke_instruction->GetType(), DataType::Type::kVoid);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001561 *return_replacement = nullptr;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001562 break;
1563 case kInlineOpReturnArg:
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001564 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction,
1565 inline_method.d.return_data.arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001566 break;
1567 case kInlineOpNonWideConst:
1568 if (resolved_method->GetShorty()[0] == 'L') {
1569 DCHECK_EQ(inline_method.d.data, 0u);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001570 *return_replacement = graph_->GetNullConstant();
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001571 } else {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001572 *return_replacement = graph_->GetIntConstant(static_cast<int32_t>(inline_method.d.data));
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001573 }
1574 break;
1575 case kInlineOpIGet: {
1576 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1577 if (data.method_is_static || data.object_arg != 0u) {
1578 // TODO: Needs null check.
1579 return false;
1580 }
1581 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001582 HInstanceFieldGet* iget = CreateInstanceFieldGet(data.field_idx, resolved_method, obj);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001583 DCHECK_EQ(iget->GetFieldOffset().Uint32Value(), data.field_offset);
1584 DCHECK_EQ(iget->IsVolatile() ? 1u : 0u, data.is_volatile);
1585 invoke_instruction->GetBlock()->InsertInstructionBefore(iget, invoke_instruction);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001586 *return_replacement = iget;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001587 break;
1588 }
1589 case kInlineOpIPut: {
1590 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1591 if (data.method_is_static || data.object_arg != 0u) {
1592 // TODO: Needs null check.
1593 return false;
1594 }
1595 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
1596 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, data.src_arg);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001597 HInstanceFieldSet* iput = CreateInstanceFieldSet(data.field_idx, resolved_method, obj, value);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001598 DCHECK_EQ(iput->GetFieldOffset().Uint32Value(), data.field_offset);
1599 DCHECK_EQ(iput->IsVolatile() ? 1u : 0u, data.is_volatile);
1600 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1601 if (data.return_arg_plus1 != 0u) {
1602 size_t return_arg = data.return_arg_plus1 - 1u;
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001603 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction, return_arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001604 }
1605 break;
1606 }
Vladimir Marko354efa62016-02-04 19:46:56 +00001607 case kInlineOpConstructor: {
1608 const InlineConstructorData& data = inline_method.d.constructor_data;
1609 // Get the indexes to arrays for easier processing.
1610 uint16_t iput_field_indexes[] = {
1611 data.iput0_field_index, data.iput1_field_index, data.iput2_field_index
1612 };
1613 uint16_t iput_args[] = { data.iput0_arg, data.iput1_arg, data.iput2_arg };
1614 static_assert(arraysize(iput_args) == arraysize(iput_field_indexes), "Size mismatch");
1615 // Count valid field indexes.
1616 size_t number_of_iputs = 0u;
1617 while (number_of_iputs != arraysize(iput_field_indexes) &&
1618 iput_field_indexes[number_of_iputs] != DexFile::kDexNoIndex16) {
1619 // Check that there are no duplicate valid field indexes.
1620 DCHECK_EQ(0, std::count(iput_field_indexes + number_of_iputs + 1,
1621 iput_field_indexes + arraysize(iput_field_indexes),
1622 iput_field_indexes[number_of_iputs]));
1623 ++number_of_iputs;
1624 }
1625 // Check that there are no valid field indexes in the rest of the array.
1626 DCHECK_EQ(0, std::count_if(iput_field_indexes + number_of_iputs,
1627 iput_field_indexes + arraysize(iput_field_indexes),
1628 [](uint16_t index) { return index != DexFile::kDexNoIndex16; }));
1629
1630 // Create HInstanceFieldSet for each IPUT that stores non-zero data.
Vladimir Marko354efa62016-02-04 19:46:56 +00001631 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, /* this */ 0u);
1632 bool needs_constructor_barrier = false;
1633 for (size_t i = 0; i != number_of_iputs; ++i) {
1634 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, iput_args[i]);
Roland Levillain1a653882016-03-18 18:05:57 +00001635 if (!value->IsConstant() || !value->AsConstant()->IsZeroBitPattern()) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001636 uint16_t field_index = iput_field_indexes[i];
Vladimir Markof44d36c2017-03-14 14:18:46 +00001637 bool is_final;
1638 HInstanceFieldSet* iput =
1639 CreateInstanceFieldSet(field_index, resolved_method, obj, value, &is_final);
Vladimir Marko354efa62016-02-04 19:46:56 +00001640 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1641
1642 // Check whether the field is final. If it is, we need to add a barrier.
Vladimir Markof44d36c2017-03-14 14:18:46 +00001643 if (is_final) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001644 needs_constructor_barrier = true;
1645 }
1646 }
1647 }
1648 if (needs_constructor_barrier) {
Vladimir Marko1a2a5cd2018-11-07 15:39:48 +00001649 // See DexCompilationUnit::RequiresConstructorBarrier for more details.
Igor Murashkind01745e2017-04-05 16:40:31 -07001650 DCHECK(obj != nullptr) << "only non-static methods can have a constructor fence";
1651
1652 HConstructorFence* constructor_fence =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001653 new (graph_->GetAllocator()) HConstructorFence(obj, kNoDexPc, graph_->GetAllocator());
Igor Murashkind01745e2017-04-05 16:40:31 -07001654 invoke_instruction->GetBlock()->InsertInstructionBefore(constructor_fence,
1655 invoke_instruction);
Vladimir Marko354efa62016-02-04 19:46:56 +00001656 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001657 *return_replacement = nullptr;
Vladimir Marko354efa62016-02-04 19:46:56 +00001658 break;
1659 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001660 default:
1661 LOG(FATAL) << "UNREACHABLE";
1662 UNREACHABLE();
1663 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001664 return true;
1665}
1666
Vladimir Markof44d36c2017-03-14 14:18:46 +00001667HInstanceFieldGet* HInliner::CreateInstanceFieldGet(uint32_t field_index,
1668 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001669 HInstruction* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001670 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001671 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1672 ArtField* resolved_field =
1673 class_linker->LookupResolvedField(field_index, referrer, /* is_static */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001674 DCHECK(resolved_field != nullptr);
Vladimir Markoca6fff82017-10-03 14:49:14 +01001675 HInstanceFieldGet* iget = new (graph_->GetAllocator()) HInstanceFieldGet(
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001676 obj,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001677 resolved_field,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001678 DataType::FromShorty(resolved_field->GetTypeDescriptor()[0]),
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001679 resolved_field->GetOffset(),
1680 resolved_field->IsVolatile(),
1681 field_index,
1682 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001683 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001684 // Read barrier generates a runtime call in slow path and we need a valid
1685 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1686 /* dex_pc */ 0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001687 if (iget->GetType() == DataType::Type::kReference) {
Vladimir Marko456307a2016-04-19 14:12:13 +00001688 // Use the same dex_cache that we used for field lookup as the hint_dex_cache.
Vladimir Markof44d36c2017-03-14 14:18:46 +00001689 Handle<mirror::DexCache> dex_cache = handles_->NewHandle(referrer->GetDexCache());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001690 ReferenceTypePropagation rtp(graph_,
1691 outer_compilation_unit_.GetClassLoader(),
1692 dex_cache,
1693 handles_,
1694 /* is_first_run */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001695 rtp.Visit(iget);
1696 }
1697 return iget;
1698}
1699
Vladimir Markof44d36c2017-03-14 14:18:46 +00001700HInstanceFieldSet* HInliner::CreateInstanceFieldSet(uint32_t field_index,
1701 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001702 HInstruction* obj,
Vladimir Markof44d36c2017-03-14 14:18:46 +00001703 HInstruction* value,
1704 bool* is_final)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001705 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001706 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1707 ArtField* resolved_field =
1708 class_linker->LookupResolvedField(field_index, referrer, /* is_static */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001709 DCHECK(resolved_field != nullptr);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001710 if (is_final != nullptr) {
1711 // This information is needed only for constructors.
1712 DCHECK(referrer->IsConstructor());
1713 *is_final = resolved_field->IsFinal();
1714 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01001715 HInstanceFieldSet* iput = new (graph_->GetAllocator()) HInstanceFieldSet(
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001716 obj,
1717 value,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001718 resolved_field,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001719 DataType::FromShorty(resolved_field->GetTypeDescriptor()[0]),
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001720 resolved_field->GetOffset(),
1721 resolved_field->IsVolatile(),
1722 field_index,
1723 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001724 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001725 // Read barrier generates a runtime call in slow path and we need a valid
1726 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1727 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001728 return iput;
1729}
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001730
Vladimir Markob1d0ee12017-04-20 19:50:32 +01001731template <typename T>
1732static inline Handle<T> NewHandleIfDifferent(T* object,
1733 Handle<T> hint,
1734 VariableSizedHandleScope* handles)
1735 REQUIRES_SHARED(Locks::mutator_lock_) {
1736 return (object != hint.Get()) ? handles->NewHandle(object) : hint;
1737}
1738
Vladimir Marko6be1dbd2018-11-13 13:09:51 +00001739static bool CanEncodeInlinedMethodInStackMap(const DexFile& caller_dex_file, ArtMethod* callee)
1740 REQUIRES_SHARED(Locks::mutator_lock_) {
1741 if (!Runtime::Current()->IsAotCompiler()) {
1742 // JIT can always encode methods in stack maps.
1743 return true;
1744 }
1745 if (IsSameDexFile(caller_dex_file, *callee->GetDexFile())) {
1746 return true;
1747 }
1748 // TODO(ngeoffray): Support more AOT cases for inlining:
1749 // - methods in multidex
1750 // - methods in boot image for on-device non-PIC compilation.
1751 return false;
1752}
1753
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001754bool HInliner::TryBuildAndInlineHelper(HInvoke* invoke_instruction,
1755 ArtMethod* resolved_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001756 ReferenceTypeInfo receiver_type,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001757 bool same_dex_file,
1758 HInstruction** return_replacement) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001759 DCHECK(!(resolved_method->IsStatic() && receiver_type.IsValid()));
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001760 ScopedObjectAccess soa(Thread::Current());
1761 const DexFile::CodeItem* code_item = resolved_method->GetCodeItem();
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001762 const DexFile& callee_dex_file = *resolved_method->GetDexFile();
1763 uint32_t method_index = resolved_method->GetDexMethodIndex();
David Sehr0225f8e2018-01-31 08:52:24 +00001764 CodeItemDebugInfoAccessor code_item_accessor(resolved_method->DexInstructionDebugInfo());
Calin Juravle2e768302015-07-28 14:41:11 +00001765 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Vladimir Markob1d0ee12017-04-20 19:50:32 +01001766 Handle<mirror::DexCache> dex_cache = NewHandleIfDifferent(resolved_method->GetDexCache(),
1767 caller_compilation_unit_.GetDexCache(),
1768 handles_);
1769 Handle<mirror::ClassLoader> class_loader =
1770 NewHandleIfDifferent(resolved_method->GetDeclaringClass()->GetClassLoader(),
1771 caller_compilation_unit_.GetClassLoader(),
1772 handles_);
Nicolas Geoffrayf1aedb12016-07-28 03:49:14 +01001773
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001774 Handle<mirror::Class> compiling_class = handles_->NewHandle(resolved_method->GetDeclaringClass());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001775 DexCompilationUnit dex_compilation_unit(
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001776 class_loader,
Nicolas Geoffray5b82d332016-02-18 14:22:32 +00001777 class_linker,
1778 callee_dex_file,
1779 code_item,
1780 resolved_method->GetDeclaringClass()->GetDexClassDefIndex(),
1781 method_index,
1782 resolved_method->GetAccessFlags(),
1783 /* verified_method */ nullptr,
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001784 dex_cache,
1785 compiling_class);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001786
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001787 InvokeType invoke_type = invoke_instruction->GetInvokeType();
Nicolas Geoffray35071052015-06-09 15:43:38 +01001788 if (invoke_type == kInterface) {
1789 // We have statically resolved the dispatch. To please the class linker
1790 // at runtime, we change this call as if it was a virtual call.
1791 invoke_type = kVirtual;
1792 }
David Brazdil3f523062016-02-29 16:53:33 +00001793
1794 const int32_t caller_instruction_counter = graph_->GetCurrentInstructionId();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001795 HGraph* callee_graph = new (graph_->GetAllocator()) HGraph(
1796 graph_->GetAllocator(),
1797 graph_->GetArenaStack(),
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001798 callee_dex_file,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001799 method_index,
Vladimir Markoa0431112018-06-25 09:32:54 +01001800 codegen_->GetCompilerOptions().GetInstructionSet(),
Nicolas Geoffray35071052015-06-09 15:43:38 +01001801 invoke_type,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001802 graph_->IsDebuggable(),
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001803 /* osr */ false,
David Brazdil3f523062016-02-29 16:53:33 +00001804 caller_instruction_counter);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001805 callee_graph->SetArtMethod(resolved_method);
David Brazdil5e8b1372015-01-23 14:39:08 +00001806
Vladimir Marko438709f2017-02-23 18:56:13 +00001807 // When they are needed, allocate `inline_stats_` on the Arena instead
Roland Levillaina8013fd2016-04-04 15:34:31 +01001808 // of on the stack, as Clang might produce a stack frame too large
1809 // for this function, that would not fit the requirements of the
1810 // `-Wframe-larger-than` option.
Vladimir Marko438709f2017-02-23 18:56:13 +00001811 if (stats_ != nullptr) {
1812 // Reuse one object for all inline attempts from this caller to keep Arena memory usage low.
1813 if (inline_stats_ == nullptr) {
Vladimir Markoca6fff82017-10-03 14:49:14 +01001814 void* storage = graph_->GetAllocator()->Alloc<OptimizingCompilerStats>(kArenaAllocMisc);
Vladimir Marko438709f2017-02-23 18:56:13 +00001815 inline_stats_ = new (storage) OptimizingCompilerStats;
1816 } else {
1817 inline_stats_->Reset();
1818 }
1819 }
David Brazdil5e8b1372015-01-23 14:39:08 +00001820 HGraphBuilder builder(callee_graph,
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001821 code_item_accessor,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001822 &dex_compilation_unit,
1823 &outer_compilation_unit_,
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00001824 codegen_,
Vladimir Marko438709f2017-02-23 18:56:13 +00001825 inline_stats_,
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001826 resolved_method->GetQuickenedInfo(),
David Brazdildee58d62016-04-07 09:54:26 +00001827 handles_);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001828
David Brazdildee58d62016-04-07 09:54:26 +00001829 if (builder.BuildGraph() != kAnalysisSuccess) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001830 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedCannotBuild)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001831 << "Method " << callee_dex_file.PrettyMethod(method_index)
1832 << " could not be built, so cannot be inlined";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001833 return false;
1834 }
1835
Vladimir Markoa0431112018-06-25 09:32:54 +01001836 if (!RegisterAllocator::CanAllocateRegistersFor(
1837 *callee_graph, codegen_->GetCompilerOptions().GetInstructionSet())) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001838 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedRegisterAllocator)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001839 << "Method " << callee_dex_file.PrettyMethod(method_index)
1840 << " cannot be inlined because of the register allocator";
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001841 return false;
1842 }
1843
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001844 size_t parameter_index = 0;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001845 bool run_rtp = false;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001846 for (HInstructionIterator instructions(callee_graph->GetEntryBlock()->GetInstructions());
1847 !instructions.Done();
1848 instructions.Advance()) {
1849 HInstruction* current = instructions.Current();
1850 if (current->IsParameterValue()) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001851 HInstruction* argument = invoke_instruction->InputAt(parameter_index);
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001852 if (argument->IsNullConstant()) {
1853 current->ReplaceWith(callee_graph->GetNullConstant());
1854 } else if (argument->IsIntConstant()) {
1855 current->ReplaceWith(callee_graph->GetIntConstant(argument->AsIntConstant()->GetValue()));
1856 } else if (argument->IsLongConstant()) {
1857 current->ReplaceWith(callee_graph->GetLongConstant(argument->AsLongConstant()->GetValue()));
1858 } else if (argument->IsFloatConstant()) {
1859 current->ReplaceWith(
1860 callee_graph->GetFloatConstant(argument->AsFloatConstant()->GetValue()));
1861 } else if (argument->IsDoubleConstant()) {
1862 current->ReplaceWith(
1863 callee_graph->GetDoubleConstant(argument->AsDoubleConstant()->GetValue()));
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001864 } else if (argument->GetType() == DataType::Type::kReference) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001865 if (!resolved_method->IsStatic() && parameter_index == 0 && receiver_type.IsValid()) {
1866 run_rtp = true;
1867 current->SetReferenceTypeInfo(receiver_type);
1868 } else {
1869 current->SetReferenceTypeInfo(argument->GetReferenceTypeInfo());
1870 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001871 current->AsParameterValue()->SetCanBeNull(argument->CanBeNull());
1872 }
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001873 ++parameter_index;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001874 }
1875 }
1876
David Brazdil94ab38f2016-06-21 17:48:19 +01001877 // We have replaced formal arguments with actual arguments. If actual types
1878 // are more specific than the declared ones, run RTP again on the inner graph.
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001879 if (run_rtp || ArgumentTypesMoreSpecific(invoke_instruction, resolved_method)) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001880 ReferenceTypePropagation(callee_graph,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001881 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +01001882 dex_compilation_unit.GetDexCache(),
1883 handles_,
1884 /* is_first_run */ false).Run();
1885 }
1886
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001887 RunOptimizations(callee_graph, code_item, dex_compilation_unit);
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +00001888
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001889 HBasicBlock* exit_block = callee_graph->GetExitBlock();
1890 if (exit_block == nullptr) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001891 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedInfiniteLoop)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001892 << "Method " << callee_dex_file.PrettyMethod(method_index)
1893 << " could not be inlined because it has an infinite loop";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001894 return false;
1895 }
1896
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001897 bool has_one_return = false;
Vladimir Marko60584552015-09-03 13:35:12 +00001898 for (HBasicBlock* predecessor : exit_block->GetPredecessors()) {
1899 if (predecessor->GetLastInstruction()->IsThrow()) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001900 if (invoke_instruction->GetBlock()->IsTryBlock()) {
1901 // TODO(ngeoffray): Support adding HTryBoundary in Hgraph::InlineInto.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001902 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedTryCatch)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001903 << "Method " << callee_dex_file.PrettyMethod(method_index)
1904 << " could not be inlined because one branch always throws and"
1905 << " caller is in a try/catch block";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001906 return false;
1907 } else if (graph_->GetExitBlock() == nullptr) {
1908 // TODO(ngeoffray): Support adding HExit in the caller graph.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001909 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedInfiniteLoop)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001910 << "Method " << callee_dex_file.PrettyMethod(method_index)
1911 << " could not be inlined because one branch always throws and"
1912 << " caller does not have an exit block";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001913 return false;
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00001914 } else if (graph_->HasIrreducibleLoops()) {
1915 // TODO(ngeoffray): Support re-computing loop information to graphs with
1916 // irreducible loops?
1917 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1918 << " could not be inlined because one branch always throws and"
1919 << " caller has irreducible loops";
1920 return false;
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001921 }
1922 } else {
1923 has_one_return = true;
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001924 }
1925 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001926
1927 if (!has_one_return) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001928 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedAlwaysThrows)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001929 << "Method " << callee_dex_file.PrettyMethod(method_index)
1930 << " could not be inlined because it always throws";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001931 return false;
1932 }
1933
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001934 size_t number_of_instructions = 0;
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001935 // Skip the entry block, it does not contain instructions that prevent inlining.
1936 for (HBasicBlock* block : callee_graph->GetReversePostOrderSkipEntryBlock()) {
David Sehrc757dec2016-11-04 15:48:34 -07001937 if (block->IsLoopHeader()) {
1938 if (block->GetLoopInformation()->IsIrreducible()) {
1939 // Don't inline methods with irreducible loops, they could prevent some
1940 // optimizations to run.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001941 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedIrreducibleLoop)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001942 << "Method " << callee_dex_file.PrettyMethod(method_index)
1943 << " could not be inlined because it contains an irreducible loop";
David Sehrc757dec2016-11-04 15:48:34 -07001944 return false;
1945 }
1946 if (!block->GetLoopInformation()->HasExitEdge()) {
1947 // Don't inline methods with loops without exit, since they cause the
1948 // loop information to be computed incorrectly when updating after
1949 // inlining.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001950 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedLoopWithoutExit)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001951 << "Method " << callee_dex_file.PrettyMethod(method_index)
1952 << " could not be inlined because it contains a loop with no exit";
David Sehrc757dec2016-11-04 15:48:34 -07001953 return false;
1954 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001955 }
1956
1957 for (HInstructionIterator instr_it(block->GetInstructions());
1958 !instr_it.Done();
1959 instr_it.Advance()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001960 if (++number_of_instructions >= inlining_budget_) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001961 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedInstructionBudget)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001962 << "Method " << callee_dex_file.PrettyMethod(method_index)
1963 << " is not inlined because the outer method has reached"
1964 << " its instruction budget limit.";
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001965 return false;
1966 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001967 HInstruction* current = instr_it.Current();
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001968 if (current->NeedsEnvironment() &&
1969 (total_number_of_dex_registers_ >= kMaximumNumberOfCumulatedDexRegisters)) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001970 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedEnvironmentBudget)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001971 << "Method " << callee_dex_file.PrettyMethod(method_index)
1972 << " is not inlined because its caller has reached"
1973 << " its environment budget limit.";
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001974 return false;
1975 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001976
Nicolas Geoffrayfbdfa6d2017-02-03 10:43:13 +00001977 if (current->NeedsEnvironment() &&
1978 !CanEncodeInlinedMethodInStackMap(*caller_compilation_unit_.GetDexFile(),
1979 resolved_method)) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001980 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedStackMaps)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001981 << "Method " << callee_dex_file.PrettyMethod(method_index)
1982 << " could not be inlined because " << current->DebugName()
1983 << " needs an environment, is in a different dex file"
1984 << ", and cannot be encoded in the stack maps.";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001985 return false;
1986 }
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001987
Vladimir Markodc151b22015-10-15 18:02:30 +01001988 if (!same_dex_file && current->NeedsDexCacheOfDeclaringClass()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001989 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedDexCache)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001990 << "Method " << callee_dex_file.PrettyMethod(method_index)
1991 << " could not be inlined because " << current->DebugName()
1992 << " it is in a different dex file and requires access to the dex cache";
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001993 return false;
1994 }
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001995
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001996 if (current->IsUnresolvedStaticFieldGet() ||
1997 current->IsUnresolvedInstanceFieldGet() ||
1998 current->IsUnresolvedStaticFieldSet() ||
1999 current->IsUnresolvedInstanceFieldSet()) {
2000 // Entrypoint for unresolved fields does not handle inlined frames.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00002001 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedUnresolvedEntrypoint)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002002 << "Method " << callee_dex_file.PrettyMethod(method_index)
2003 << " could not be inlined because it is using an unresolved"
2004 << " entrypoint";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00002005 return false;
2006 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002007 }
2008 }
David Brazdil3f523062016-02-29 16:53:33 +00002009 DCHECK_EQ(caller_instruction_counter, graph_->GetCurrentInstructionId())
2010 << "No instructions can be added to the outer graph while inner graph is being built";
2011
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002012 // Inline the callee graph inside the caller graph.
David Brazdil3f523062016-02-29 16:53:33 +00002013 const int32_t callee_instruction_counter = callee_graph->GetCurrentInstructionId();
2014 graph_->SetCurrentInstructionId(callee_instruction_counter);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00002015 *return_replacement = callee_graph->InlineInto(graph_, invoke_instruction);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002016 // Update our budget for other inlining attempts in `caller_graph`.
2017 total_number_of_instructions_ += number_of_instructions;
2018 UpdateInliningBudget();
David Brazdil3f523062016-02-29 16:53:33 +00002019
2020 DCHECK_EQ(callee_instruction_counter, callee_graph->GetCurrentInstructionId())
2021 << "No instructions can be added to the inner graph during inlining into the outer graph";
2022
Vladimir Marko438709f2017-02-23 18:56:13 +00002023 if (stats_ != nullptr) {
2024 DCHECK(inline_stats_ != nullptr);
2025 inline_stats_->AddTo(stats_);
2026 }
2027
Vladimir Markobe10e8e2016-01-22 12:09:44 +00002028 return true;
2029}
Calin Juravle2e768302015-07-28 14:41:11 +00002030
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002031void HInliner::RunOptimizations(HGraph* callee_graph,
2032 const DexFile::CodeItem* code_item,
2033 const DexCompilationUnit& dex_compilation_unit) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01002034 // Note: if the outermost_graph_ is being compiled OSR, we should not run any
2035 // optimization that could lead to a HDeoptimize. The following optimizations do not.
Vladimir Marko438709f2017-02-23 18:56:13 +00002036 HDeadCodeElimination dce(callee_graph, inline_stats_, "dead_code_elimination$inliner");
Andreas Gampeca620d72016-11-08 08:09:33 -08002037 HConstantFolding fold(callee_graph, "constant_folding$inliner");
Vladimir Markobb089b62018-06-28 17:30:16 +01002038 InstructionSimplifier simplify(callee_graph, codegen_, inline_stats_);
Roland Levillaina3aef2e2016-04-06 17:45:58 +01002039
2040 HOptimization* optimizations[] = {
Roland Levillaina3aef2e2016-04-06 17:45:58 +01002041 &simplify,
2042 &fold,
2043 &dce,
2044 };
2045
2046 for (size_t i = 0; i < arraysize(optimizations); ++i) {
2047 HOptimization* optimization = optimizations[i];
2048 optimization->Run();
2049 }
2050
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002051 // Bail early for pathological cases on the environment (for example recursive calls,
2052 // or too large environment).
2053 if (total_number_of_dex_registers_ >= kMaximumNumberOfCumulatedDexRegisters) {
2054 LOG_NOTE() << "Calls in " << callee_graph->GetArtMethod()->PrettyMethod()
2055 << " will not be inlined because the outer method has reached"
2056 << " its environment budget limit.";
2057 return;
Roland Levillaina3aef2e2016-04-06 17:45:58 +01002058 }
2059
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002060 // Bail early if we know we already are over the limit.
2061 size_t number_of_instructions = CountNumberOfInstructions(callee_graph);
2062 if (number_of_instructions > inlining_budget_) {
2063 LOG_NOTE() << "Calls in " << callee_graph->GetArtMethod()->PrettyMethod()
2064 << " will not be inlined because the outer method has reached"
2065 << " its instruction budget limit. " << number_of_instructions;
2066 return;
2067 }
2068
Mathieu Chartier698ebbc2018-01-05 11:00:42 -08002069 CodeItemDataAccessor accessor(callee_graph->GetDexFile(), code_item);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002070 HInliner inliner(callee_graph,
2071 outermost_graph_,
2072 codegen_,
2073 outer_compilation_unit_,
2074 dex_compilation_unit,
2075 compiler_driver_,
2076 handles_,
2077 inline_stats_,
Mathieu Chartier808c7a52017-12-15 11:19:33 -08002078 total_number_of_dex_registers_ + accessor.RegistersSize(),
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002079 total_number_of_instructions_ + number_of_instructions,
2080 this,
2081 depth_ + 1);
2082 inliner.Run();
Roland Levillaina3aef2e2016-04-06 17:45:58 +01002083}
2084
David Brazdil94ab38f2016-06-21 17:48:19 +01002085static bool IsReferenceTypeRefinement(ReferenceTypeInfo declared_rti,
2086 bool declared_can_be_null,
2087 HInstruction* actual_obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002088 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdil94ab38f2016-06-21 17:48:19 +01002089 if (declared_can_be_null && !actual_obj->CanBeNull()) {
2090 return true;
2091 }
2092
2093 ReferenceTypeInfo actual_rti = actual_obj->GetReferenceTypeInfo();
2094 return (actual_rti.IsExact() && !declared_rti.IsExact()) ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00002095 declared_rti.IsStrictSupertypeOf(actual_rti);
David Brazdil94ab38f2016-06-21 17:48:19 +01002096}
2097
Vladimir Markob45528c2017-07-27 14:14:28 +01002098ReferenceTypeInfo HInliner::GetClassRTI(ObjPtr<mirror::Class> klass) {
David Brazdil94ab38f2016-06-21 17:48:19 +01002099 return ReferenceTypePropagation::IsAdmissible(klass)
2100 ? ReferenceTypeInfo::Create(handles_->NewHandle(klass))
2101 : graph_->GetInexactObjectRti();
2102}
2103
2104bool HInliner::ArgumentTypesMoreSpecific(HInvoke* invoke_instruction, ArtMethod* resolved_method) {
2105 // If this is an instance call, test whether the type of the `this` argument
2106 // is more specific than the class which declares the method.
2107 if (!resolved_method->IsStatic()) {
2108 if (IsReferenceTypeRefinement(GetClassRTI(resolved_method->GetDeclaringClass()),
2109 /* declared_can_be_null */ false,
2110 invoke_instruction->InputAt(0u))) {
2111 return true;
2112 }
2113 }
2114
David Brazdil94ab38f2016-06-21 17:48:19 +01002115 // Iterate over the list of parameter types and test whether any of the
2116 // actual inputs has a more specific reference type than the type declared in
2117 // the signature.
2118 const DexFile::TypeList* param_list = resolved_method->GetParameterTypeList();
2119 for (size_t param_idx = 0,
2120 input_idx = resolved_method->IsStatic() ? 0 : 1,
2121 e = (param_list == nullptr ? 0 : param_list->Size());
2122 param_idx < e;
2123 ++param_idx, ++input_idx) {
2124 HInstruction* input = invoke_instruction->InputAt(input_idx);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002125 if (input->GetType() == DataType::Type::kReference) {
Vladimir Markob45528c2017-07-27 14:14:28 +01002126 ObjPtr<mirror::Class> param_cls = resolved_method->LookupResolvedClassFromTypeIndex(
2127 param_list->GetTypeItem(param_idx).type_idx_);
David Brazdil94ab38f2016-06-21 17:48:19 +01002128 if (IsReferenceTypeRefinement(GetClassRTI(param_cls),
2129 /* declared_can_be_null */ true,
2130 input)) {
2131 return true;
2132 }
2133 }
2134 }
2135
2136 return false;
2137}
2138
2139bool HInliner::ReturnTypeMoreSpecific(HInvoke* invoke_instruction,
2140 HInstruction* return_replacement) {
Alex Light68289a52015-12-15 17:30:30 -08002141 // Check the integrity of reference types and run another type propagation if needed.
David Brazdil4833f5a2015-12-16 10:37:39 +00002142 if (return_replacement != nullptr) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002143 if (return_replacement->GetType() == DataType::Type::kReference) {
David Brazdil94ab38f2016-06-21 17:48:19 +01002144 // Test if the return type is a refinement of the declared return type.
2145 if (IsReferenceTypeRefinement(invoke_instruction->GetReferenceTypeInfo(),
2146 /* declared_can_be_null */ true,
2147 return_replacement)) {
2148 return true;
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00002149 } else if (return_replacement->IsInstanceFieldGet()) {
2150 HInstanceFieldGet* field_get = return_replacement->AsInstanceFieldGet();
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00002151 if (field_get->GetFieldInfo().GetField() ==
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002152 GetClassRoot<mirror::Object>()->GetInstanceField(0)) {
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00002153 return true;
2154 }
David Brazdil94ab38f2016-06-21 17:48:19 +01002155 }
2156 } else if (return_replacement->IsInstanceOf()) {
2157 // Inlining InstanceOf into an If may put a tighter bound on reference types.
2158 return true;
2159 }
2160 }
2161
2162 return false;
2163}
2164
2165void HInliner::FixUpReturnReferenceType(ArtMethod* resolved_method,
2166 HInstruction* return_replacement) {
2167 if (return_replacement != nullptr) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002168 if (return_replacement->GetType() == DataType::Type::kReference) {
David Brazdil4833f5a2015-12-16 10:37:39 +00002169 if (!return_replacement->GetReferenceTypeInfo().IsValid()) {
2170 // Make sure that we have a valid type for the return. We may get an invalid one when
2171 // we inline invokes with multiple branches and create a Phi for the result.
2172 // TODO: we could be more precise by merging the phi inputs but that requires
2173 // some functionality from the reference type propagation.
2174 DCHECK(return_replacement->IsPhi());
Vladimir Markob45528c2017-07-27 14:14:28 +01002175 ObjPtr<mirror::Class> cls = resolved_method->LookupResolvedReturnType();
David Brazdil94ab38f2016-06-21 17:48:19 +01002176 return_replacement->SetReferenceTypeInfo(GetClassRTI(cls));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01002177 }
Calin Juravlecdfed3d2015-10-26 14:05:01 +00002178 }
Calin Juravle2e768302015-07-28 14:41:11 +00002179 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002180}
2181
2182} // namespace art