blob: 5920f78270b51d49ae398c403c0efa25d4c6b7fd [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"
Andreas Gampe85f1c572018-11-21 13:52:48 -080021#include "base/logging.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000022#include "builder.h"
23#include "class_linker.h"
Vladimir Marko5868ada2020-05-12 11:50:34 +010024#include "class_root-inl.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000025#include "constant_folding.h"
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010026#include "data_type-inl.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000027#include "dead_code_elimination.h"
Andreas Gampeb95c74b2017-04-20 19:43:21 -070028#include "dex/inline_method_analyser.h"
Vladimir Markobe10e8e2016-01-22 12:09:44 +000029#include "dex/verification_results.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070030#include "dex/verified_method.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
Vladimir Marko0a516052019-10-14 13:00:44 +000050namespace art {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000051
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
David Srbecky4fa07a52020-03-31 20:52:09 +0100151 // If we're compiling tests, honor inlining directives in method names:
Roland Levillain6c3af162017-04-27 11:18:56 +0100152 // - if a method's name contains the substring "$noinline$", do not
Vladimir Marko6be1dbd2018-11-13 13:09:51 +0000153 // inline that method;
154 // - if a method's name contains the substring "$inline$", ensure
155 // that this method is actually inlined.
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000156 // We limit the latter to AOT compilation, as the JIT may or may not inline
Nicolas Geoffray08490b82017-07-18 12:58:10 +0100157 // depending on the state of classes at runtime.
David Srbecky4fa07a52020-03-31 20:52:09 +0100158 const bool honor_noinline_directives = codegen_->GetCompilerOptions().CompileArtTest();
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000159 const bool honor_inline_directives =
160 honor_noinline_directives && Runtime::Current()->IsAotCompiler();
Roland Levillain6c3af162017-04-27 11:18:56 +0100161
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +0000162 // Keep a copy of all blocks when starting the visit.
163 ArenaVector<HBasicBlock*> blocks = graph_->GetReversePostOrder();
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100164 DCHECK(!blocks.empty());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +0000165 // Because we are changing the graph when inlining,
166 // we just iterate over the blocks of the outer method.
167 // This avoids doing the inlining work again on the inlined blocks.
168 for (HBasicBlock* block : blocks) {
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000169 for (HInstruction* instruction = block->GetFirstInstruction(); instruction != nullptr;) {
170 HInstruction* next = instruction->GetNext();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100171 HInvoke* call = instruction->AsInvoke();
Razvan A Lupusoru3e90a962015-03-27 13:44:44 -0700172 // As long as the call is not intrinsified, it is worth trying to inline.
173 if (call != nullptr && call->GetIntrinsic() == Intrinsics::kNone) {
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000174 if (honor_noinline_directives) {
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000175 // Debugging case: directives in method names control or assert on inlining.
176 std::string callee_name = outer_compilation_unit_.GetDexFile()->PrettyMethod(
Andreas Gampe3db70682018-12-26 15:12:03 -0800177 call->GetDexMethodIndex(), /* with_signature= */ false);
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000178 // Tests prevent inlining by having $noinline$ in their method names.
179 if (callee_name.find("$noinline$") == std::string::npos) {
Aart Bik24773202018-04-26 10:28:51 -0700180 if (TryInline(call)) {
181 didInline = true;
Aart Bik54e45c52018-04-27 13:57:21 -0700182 } else if (honor_inline_directives) {
Nicolas Geoffray1949baf2017-10-17 12:14:53 +0000183 bool should_have_inlined = (callee_name.find("$inline$") != std::string::npos);
184 CHECK(!should_have_inlined) << "Could not inline " << callee_name;
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000185 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000186 }
Guillaume "Vermeille" Sancheze918d382015-06-03 15:32:41 +0100187 } else {
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000188 DCHECK(!honor_inline_directives);
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000189 // Normal case: try to inline.
Aart Bik24773202018-04-26 10:28:51 -0700190 if (TryInline(call)) {
191 didInline = true;
192 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000193 }
194 }
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000195 instruction = next;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000196 }
197 }
Aart Bik24773202018-04-26 10:28:51 -0700198
199 return didInline;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000200}
201
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100202static bool IsMethodOrDeclaringClassFinal(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700203 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100204 return method->IsFinal() || method->GetDeclaringClass()->IsFinal();
205}
206
207/**
208 * Given the `resolved_method` looked up in the dex cache, try to find
209 * the actual runtime target of an interface or virtual call.
210 * Return nullptr if the runtime target cannot be proven.
211 */
212static ArtMethod* FindVirtualOrInterfaceTarget(HInvoke* invoke, ArtMethod* resolved_method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700213 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100214 if (IsMethodOrDeclaringClassFinal(resolved_method)) {
215 // No need to lookup further, the resolved method will be the target.
216 return resolved_method;
217 }
218
219 HInstruction* receiver = invoke->InputAt(0);
220 if (receiver->IsNullCheck()) {
221 // Due to multiple levels of inlining within the same pass, it might be that
222 // null check does not have the reference type of the actual receiver.
223 receiver = receiver->InputAt(0);
224 }
225 ReferenceTypeInfo info = receiver->GetReferenceTypeInfo();
Calin Juravle2e768302015-07-28 14:41:11 +0000226 DCHECK(info.IsValid()) << "Invalid RTI for " << receiver->DebugName();
227 if (!info.IsExact()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100228 // We currently only support inlining with known receivers.
229 // TODO: Remove this check, we should be able to inline final methods
230 // on unknown receivers.
231 return nullptr;
232 } else if (info.GetTypeHandle()->IsInterface()) {
233 // Statically knowing that the receiver has an interface type cannot
234 // help us find what is the target method.
235 return nullptr;
236 } else if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(info.GetTypeHandle().Get())) {
237 // The method that we're trying to call is not in the receiver's class or super classes.
238 return nullptr;
Nicolas Geoffrayab5327d2016-03-18 11:36:20 +0000239 } else if (info.GetTypeHandle()->IsErroneous()) {
240 // If the type is erroneous, do not go further, as we are going to query the vtable or
241 // imt table, that we can only safely do on non-erroneous classes.
242 return nullptr;
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100243 }
244
245 ClassLinker* cl = Runtime::Current()->GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700246 PointerSize pointer_size = cl->GetImagePointerSize();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100247 if (invoke->IsInvokeInterface()) {
248 resolved_method = info.GetTypeHandle()->FindVirtualMethodForInterface(
249 resolved_method, pointer_size);
250 } else {
251 DCHECK(invoke->IsInvokeVirtual());
252 resolved_method = info.GetTypeHandle()->FindVirtualMethodForVirtual(
253 resolved_method, pointer_size);
254 }
255
256 if (resolved_method == nullptr) {
257 // The information we had on the receiver was not enough to find
258 // the target method. Since we check above the exact type of the receiver,
259 // the only reason this can happen is an IncompatibleClassChangeError.
260 return nullptr;
Alex Light9139e002015-10-09 15:59:48 -0700261 } else if (!resolved_method->IsInvokable()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100262 // The information we had on the receiver was not enough to find
263 // the target method. Since we check above the exact type of the receiver,
264 // the only reason this can happen is an IncompatibleClassChangeError.
265 return nullptr;
266 } else if (IsMethodOrDeclaringClassFinal(resolved_method)) {
267 // A final method has to be the target method.
268 return resolved_method;
269 } else if (info.IsExact()) {
270 // If we found a method and the receiver's concrete type is statically
271 // known, we know for sure the target.
272 return resolved_method;
273 } else {
274 // Even if we did find a method, the receiver type was not enough to
275 // statically find the runtime target.
276 return nullptr;
277 }
278}
279
280static uint32_t FindMethodIndexIn(ArtMethod* method,
281 const DexFile& dex_file,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000282 uint32_t name_and_signature_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700283 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100284 if (IsSameDexFile(*method->GetDexFile(), dex_file)) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100285 return method->GetDexMethodIndex();
286 } else {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000287 return method->FindDexMethodIndexInOtherDexFile(dex_file, name_and_signature_index);
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100288 }
289}
290
Vladimir Marko423bebb2019-03-26 15:17:21 +0000291static dex::TypeIndex FindClassIndexIn(ObjPtr<mirror::Class> cls,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000292 const DexCompilationUnit& compilation_unit)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700293 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000294 const DexFile& dex_file = *compilation_unit.GetDexFile();
Andreas Gampea5b09a62016-11-17 15:21:22 -0800295 dex::TypeIndex index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100296 if (cls->GetDexCache() == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700297 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000298 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800299 } else if (!cls->GetDexTypeIndex().IsValid()) {
David Sehr709b0702016-10-13 09:12:37 -0700300 DCHECK(cls->IsProxyClass()) << cls->PrettyClass();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100301 // TODO: deal with proxy classes.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100302 } else if (IsSameDexFile(cls->GetDexFile(), dex_file)) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000303 DCHECK_EQ(cls->GetDexCache(), compilation_unit.GetDexCache().Get());
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000304 index = cls->GetDexTypeIndex();
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100305 } else {
306 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000307 // We cannot guarantee the entry will resolve to the same class,
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100308 // as there may be different class loaders. So only return the index if it's
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000309 // the right class already resolved with the class loader.
310 if (index.IsValid()) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +0000311 ObjPtr<mirror::Class> resolved = compilation_unit.GetClassLinker()->LookupResolvedType(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000312 index, compilation_unit.GetDexCache().Get(), compilation_unit.GetClassLoader().Get());
313 if (resolved != cls) {
314 index = dex::TypeIndex::Invalid();
315 }
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100316 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100317 }
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000318
319 return index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100320}
321
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000322class ScopedProfilingInfoInlineUse {
323 public:
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000324 explicit ScopedProfilingInfoInlineUse(ArtMethod* method, Thread* self)
325 : method_(method),
326 self_(self),
327 // Fetch the profiling info ahead of using it. If it's null when fetching,
328 // we should not call JitCodeCache::DoneInlining.
329 profiling_info_(
330 Runtime::Current()->GetJit()->GetCodeCache()->NotifyCompilerUse(method, self)) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000331 }
332
333 ~ScopedProfilingInfoInlineUse() {
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000334 if (profiling_info_ != nullptr) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700335 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000336 DCHECK_EQ(profiling_info_, method_->GetProfilingInfo(pointer_size));
337 Runtime::Current()->GetJit()->GetCodeCache()->DoneCompilerUse(method_, self_);
338 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000339 }
340
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000341 ProfilingInfo* GetProfilingInfo() const { return profiling_info_; }
342
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000343 private:
344 ArtMethod* const method_;
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000345 Thread* const self_;
346 ProfilingInfo* const profiling_info_;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000347};
348
Calin Juravle13439f02017-02-21 01:17:21 -0800349HInliner::InlineCacheType HInliner::GetInlineCacheType(
350 const Handle<mirror::ObjectArray<mirror::Class>>& classes)
351 REQUIRES_SHARED(Locks::mutator_lock_) {
352 uint8_t number_of_types = 0;
353 for (; number_of_types < InlineCache::kIndividualCacheSize; ++number_of_types) {
354 if (classes->Get(number_of_types) == nullptr) {
355 break;
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000356 }
357 }
Calin Juravle13439f02017-02-21 01:17:21 -0800358
359 if (number_of_types == 0) {
360 return kInlineCacheUninitialized;
361 } else if (number_of_types == 1) {
362 return kInlineCacheMonomorphic;
363 } else if (number_of_types == InlineCache::kIndividualCacheSize) {
364 return kInlineCacheMegamorphic;
365 } else {
366 return kInlineCachePolymorphic;
367 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000368}
369
Vladimir Marko423bebb2019-03-26 15:17:21 +0000370static ObjPtr<mirror::Class> GetMonomorphicType(Handle<mirror::ObjectArray<mirror::Class>> classes)
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000371 REQUIRES_SHARED(Locks::mutator_lock_) {
372 DCHECK(classes->Get(0) != nullptr);
373 return classes->Get(0);
374}
375
Mingyao Yang063fc772016-08-02 11:02:54 -0700376ArtMethod* HInliner::TryCHADevirtualization(ArtMethod* resolved_method) {
377 if (!resolved_method->HasSingleImplementation()) {
378 return nullptr;
379 }
380 if (Runtime::Current()->IsAotCompiler()) {
381 // No CHA-based devirtulization for AOT compiler (yet).
382 return nullptr;
383 }
Nicolas Geoffray141b63c2019-02-27 14:28:46 +0000384 if (Runtime::Current()->IsZygote()) {
385 // No CHA-based devirtulization for Zygote, as it compiles with
386 // offline information.
387 return nullptr;
388 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700389 if (outermost_graph_->IsCompilingOsr()) {
390 // We do not support HDeoptimize in OSR methods.
391 return nullptr;
392 }
Mingyao Yange8fcd012017-01-20 10:43:30 -0800393 PointerSize pointer_size = caller_compilation_unit_.GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +0000394 ArtMethod* single_impl = resolved_method->GetSingleImplementation(pointer_size);
395 if (single_impl == nullptr) {
396 return nullptr;
397 }
398 if (single_impl->IsProxyMethod()) {
399 // Proxy method is a generic invoker that's not worth
400 // devirtualizing/inlining. It also causes issues when the proxy
401 // method is in another dex file if we try to rewrite invoke-interface to
402 // invoke-virtual because a proxy method doesn't have a real dex file.
403 return nullptr;
404 }
Nicolas Geoffray8e33e842017-04-03 16:55:16 +0100405 if (!single_impl->GetDeclaringClass()->IsResolved()) {
406 // There's a race with the class loading, which updates the CHA info
407 // before setting the class to resolved. So we just bail for this
408 // rare occurence.
409 return nullptr;
410 }
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +0000411 return single_impl;
Mingyao Yang063fc772016-08-02 11:02:54 -0700412}
413
Vladimir Marko2afaff72018-11-30 17:01:50 +0000414static bool IsMethodUnverified(const CompilerOptions& compiler_options, ArtMethod* method)
David Sehr0225f8e2018-01-31 08:52:24 +0000415 REQUIRES_SHARED(Locks::mutator_lock_) {
Aart Bik2c148f02018-02-02 14:30:35 -0800416 if (!method->GetDeclaringClass()->IsVerified()) {
417 if (Runtime::Current()->UseJitCompilation()) {
418 // We're at runtime, we know this is cold code if the class
419 // is not verified, so don't bother analyzing.
420 return true;
421 }
422 uint16_t class_def_idx = method->GetDeclaringClass()->GetDexClassDefIndex();
Vladimir Marko2afaff72018-11-30 17:01:50 +0000423 if (!compiler_options.IsMethodVerifiedWithoutFailures(method->GetDexMethodIndex(),
424 class_def_idx,
425 *method->GetDexFile())) {
Aart Bik2c148f02018-02-02 14:30:35 -0800426 // Method has soft or hard failures, don't analyze.
427 return true;
428 }
429 }
430 return false;
431}
432
Vladimir Marko2afaff72018-11-30 17:01:50 +0000433static bool AlwaysThrows(const CompilerOptions& compiler_options, ArtMethod* method)
Aart Bik2c148f02018-02-02 14:30:35 -0800434 REQUIRES_SHARED(Locks::mutator_lock_) {
435 DCHECK(method != nullptr);
436 // Skip non-compilable and unverified methods.
Vladimir Marko2afaff72018-11-30 17:01:50 +0000437 if (!method->IsCompilable() || IsMethodUnverified(compiler_options, method)) {
Aart Bik2c148f02018-02-02 14:30:35 -0800438 return false;
439 }
Aart Bika8b8e9b2018-01-09 11:01:02 -0800440 // Skip native methods, methods with try blocks, and methods that are too large.
Aart Bik2c148f02018-02-02 14:30:35 -0800441 CodeItemDataAccessor accessor(method->DexInstructionData());
Aart Bika8b8e9b2018-01-09 11:01:02 -0800442 if (!accessor.HasCodeItem() ||
443 accessor.TriesSize() != 0 ||
444 accessor.InsnsSizeInCodeUnits() > kMaximumNumberOfTotalInstructions) {
445 return false;
446 }
447 // Scan for exits.
448 bool throw_seen = false;
449 for (const DexInstructionPcPair& pair : accessor) {
450 switch (pair.Inst().Opcode()) {
451 case Instruction::RETURN:
452 case Instruction::RETURN_VOID:
453 case Instruction::RETURN_WIDE:
454 case Instruction::RETURN_OBJECT:
455 case Instruction::RETURN_VOID_NO_BARRIER:
456 return false; // found regular control flow back
457 case Instruction::THROW:
458 throw_seen = true;
459 break;
460 default:
461 break;
462 }
463 }
464 return throw_seen;
465}
466
Eric Holk1868de92020-02-12 09:10:21 -0800467ArtMethod* HInliner::FindActualCallTarget(HInvoke* invoke_instruction, bool* cha_devirtualize) {
468 ArtMethod* resolved_method = invoke_instruction->GetResolvedMethod();
469 DCHECK(resolved_method != nullptr);
470
471 ArtMethod* actual_method = nullptr;
472 if (invoke_instruction->IsInvokeStaticOrDirect()) {
473 actual_method = resolved_method;
474 } else {
475 // Check if we can statically find the method.
476 actual_method = FindVirtualOrInterfaceTarget(invoke_instruction, resolved_method);
477 }
478
479 if (actual_method == nullptr) {
480 ArtMethod* method = TryCHADevirtualization(resolved_method);
481 if (method != nullptr) {
482 *cha_devirtualize = true;
483 actual_method = method;
484 LOG_NOTE() << "Try CHA-based inlining of " << actual_method->PrettyMethod();
485 }
486 }
487
488 return actual_method;
489}
490
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700491bool HInliner::TryInline(HInvoke* invoke_instruction) {
Orion Hodsonac141392017-01-13 11:53:47 +0000492 if (invoke_instruction->IsInvokeUnresolved() ||
Orion Hodson4c8e12e2018-05-18 08:33:20 +0100493 invoke_instruction->IsInvokePolymorphic() ||
494 invoke_instruction->IsInvokeCustom()) {
495 return false; // Don't bother to move further if we know the method is unresolved or the
496 // invocation is polymorphic (invoke-{polymorphic,custom}).
Calin Juravle175dc732015-08-25 15:42:32 +0100497 }
498
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000499 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100500 uint32_t method_index = invoke_instruction->GetDexMethodIndex();
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000501 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000502 LOG_TRY() << caller_dex_file.PrettyMethod(method_index);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000503
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100504 ArtMethod* resolved_method = invoke_instruction->GetResolvedMethod();
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100505 if (resolved_method == nullptr) {
506 DCHECK(invoke_instruction->IsInvokeStaticOrDirect());
507 DCHECK(invoke_instruction->AsInvokeStaticOrDirect()->IsStringInit());
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000508 LOG_FAIL_NO_STAT() << "Not inlining a String.<init> method";
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100509 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000510 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000511
Mingyao Yang063fc772016-08-02 11:02:54 -0700512 bool cha_devirtualize = false;
Eric Holk1868de92020-02-12 09:10:21 -0800513 ArtMethod* actual_method = FindActualCallTarget(invoke_instruction, &cha_devirtualize);
514
515 // If we didn't find a method, see if we can inline from the inline caches.
Mingyao Yang063fc772016-08-02 11:02:54 -0700516 if (actual_method == nullptr) {
Eric Holk1868de92020-02-12 09:10:21 -0800517 DCHECK(!invoke_instruction->IsInvokeStaticOrDirect());
518
519 return TryInlineFromInlineCache(caller_dex_file, invoke_instruction, resolved_method);
Mingyao Yang063fc772016-08-02 11:02:54 -0700520 }
521
Eric Holk1868de92020-02-12 09:10:21 -0800522 // Single target.
523 bool result = TryInlineAndReplace(invoke_instruction,
524 actual_method,
525 ReferenceTypeInfo::CreateInvalid(),
526 /* do_rtp= */ true,
527 cha_devirtualize);
528 if (result) {
529 // Successfully inlined.
530 if (!invoke_instruction->IsInvokeStaticOrDirect()) {
531 if (cha_devirtualize) {
532 // Add dependency due to devirtualization. We've assumed resolved_method
533 // has single implementation.
534 outermost_graph_->AddCHASingleImplementationDependency(resolved_method);
535 MaybeRecordStat(stats_, MethodCompilationStat::kCHAInline);
536 } else {
537 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedInvokeVirtualOrInterface);
Mingyao Yang063fc772016-08-02 11:02:54 -0700538 }
Calin Juravle69158982016-03-16 11:53:41 +0000539 }
Eric Holk1868de92020-02-12 09:10:21 -0800540 } else if (!cha_devirtualize && AlwaysThrows(codegen_->GetCompilerOptions(), actual_method)) {
541 // Set always throws property for non-inlined method call with single target
542 // (unless it was obtained through CHA, because that would imply we have
543 // to add the CHA dependency, which seems not worth it).
544 invoke_instruction->SetAlwaysThrows(true);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100545 }
Eric Holk1868de92020-02-12 09:10:21 -0800546 return result;
Calin Juravle13439f02017-02-21 01:17:21 -0800547}
548
549static Handle<mirror::ObjectArray<mirror::Class>> AllocateInlineCacheHolder(
550 const DexCompilationUnit& compilation_unit,
551 StackHandleScope<1>* hs)
552 REQUIRES_SHARED(Locks::mutator_lock_) {
553 Thread* self = Thread::Current();
554 ClassLinker* class_linker = compilation_unit.GetClassLinker();
555 Handle<mirror::ObjectArray<mirror::Class>> inline_cache = hs->NewHandle(
556 mirror::ObjectArray<mirror::Class>::Alloc(
557 self,
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100558 GetClassRoot<mirror::ObjectArray<mirror::Class>>(class_linker),
Calin Juravle13439f02017-02-21 01:17:21 -0800559 InlineCache::kIndividualCacheSize));
560 if (inline_cache == nullptr) {
561 // We got an OOME. Just clear the exception, and don't inline.
562 DCHECK(self->IsExceptionPending());
563 self->ClearException();
564 VLOG(compiler) << "Out of memory in the compiler when trying to inline";
565 }
566 return inline_cache;
567}
568
Calin Juravleaf44e6c2017-05-23 14:24:55 -0700569bool HInliner::UseOnlyPolymorphicInliningWithNoDeopt() {
570 // If we are compiling AOT or OSR, pretend the call using inline caches is polymorphic and
571 // do not generate a deopt.
572 //
573 // For AOT:
574 // Generating a deopt does not ensure that we will actually capture the new types;
575 // and the danger is that we could be stuck in a loop with "forever" deoptimizations.
576 // Take for example the following scenario:
577 // - we capture the inline cache in one run
578 // - the next run, we deoptimize because we miss a type check, but the method
579 // never becomes hot again
580 // In this case, the inline cache will not be updated in the profile and the AOT code
581 // will keep deoptimizing.
582 // Another scenario is if we use profile compilation for a process which is not allowed
583 // to JIT (e.g. system server). If we deoptimize we will run interpreted code for the
584 // rest of the lifetime.
585 // TODO(calin):
586 // This is a compromise because we will most likely never update the inline cache
587 // in the profile (unless there's another reason to deopt). So we might be stuck with
588 // a sub-optimal inline cache.
589 // We could be smarter when capturing inline caches to mitigate this.
590 // (e.g. by having different thresholds for new and old methods).
591 //
592 // For OSR:
593 // We may come from the interpreter and it may have seen different receiver types.
594 return Runtime::Current()->IsAotCompiler() || outermost_graph_->IsCompilingOsr();
595}
Calin Juravle13439f02017-02-21 01:17:21 -0800596bool HInliner::TryInlineFromInlineCache(const DexFile& caller_dex_file,
597 HInvoke* invoke_instruction,
598 ArtMethod* resolved_method)
599 REQUIRES_SHARED(Locks::mutator_lock_) {
Calin Juravlee2492d42017-03-20 11:42:13 -0700600 if (Runtime::Current()->IsAotCompiler() && !kUseAOTInlineCaches) {
601 return false;
602 }
603
Calin Juravle13439f02017-02-21 01:17:21 -0800604 StackHandleScope<1> hs(Thread::Current());
605 Handle<mirror::ObjectArray<mirror::Class>> inline_cache;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000606 // The Zygote JIT compiles based on a profile, so we shouldn't use runtime inline caches
607 // for it.
608 InlineCacheType inline_cache_type =
609 (Runtime::Current()->IsAotCompiler() || Runtime::Current()->IsZygote())
610 ? GetInlineCacheAOT(caller_dex_file, invoke_instruction, &hs, &inline_cache)
611 : GetInlineCacheJIT(invoke_instruction, &hs, &inline_cache);
Calin Juravle13439f02017-02-21 01:17:21 -0800612
613 switch (inline_cache_type) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000614 case kInlineCacheNoData: {
615 LOG_FAIL_NO_STAT()
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100616 << "No inline cache information for call to "
617 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex());
Calin Juravle13439f02017-02-21 01:17:21 -0800618 return false;
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 kInlineCacheUninitialized: {
622 LOG_FAIL_NO_STAT()
623 << "Interface or virtual call to "
624 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
625 << " is not hit and not inlined";
626 return false;
627 }
628
629 case kInlineCacheMonomorphic: {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000630 MaybeRecordStat(stats_, MethodCompilationStat::kMonomorphicCall);
Calin Juravleaf44e6c2017-05-23 14:24:55 -0700631 if (UseOnlyPolymorphicInliningWithNoDeopt()) {
Calin Juravle13439f02017-02-21 01:17:21 -0800632 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000633 } else {
Calin Juravle13439f02017-02-21 01:17:21 -0800634 return TryInlineMonomorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000635 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000636 }
Calin Juravle13439f02017-02-21 01:17:21 -0800637
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000638 case kInlineCachePolymorphic: {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000639 MaybeRecordStat(stats_, MethodCompilationStat::kPolymorphicCall);
Calin Juravle13439f02017-02-21 01:17:21 -0800640 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000641 }
Calin Juravle13439f02017-02-21 01:17:21 -0800642
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000643 case kInlineCacheMegamorphic: {
644 LOG_FAIL_NO_STAT()
645 << "Interface or virtual call to "
646 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
647 << " is megamorphic and not inlined";
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000648 MaybeRecordStat(stats_, MethodCompilationStat::kMegamorphicCall);
Calin Juravle13439f02017-02-21 01:17:21 -0800649 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000650 }
Calin Juravle13439f02017-02-21 01:17:21 -0800651
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000652 case kInlineCacheMissingTypes: {
653 LOG_FAIL_NO_STAT()
654 << "Interface or virtual call to "
655 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
656 << " is missing types and not inlined";
Calin Juravle13439f02017-02-21 01:17:21 -0800657 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000658 }
Calin Juravle13439f02017-02-21 01:17:21 -0800659 }
660 UNREACHABLE();
661}
662
663HInliner::InlineCacheType HInliner::GetInlineCacheJIT(
664 HInvoke* invoke_instruction,
665 StackHandleScope<1>* hs,
666 /*out*/Handle<mirror::ObjectArray<mirror::Class>>* inline_cache)
667 REQUIRES_SHARED(Locks::mutator_lock_) {
668 DCHECK(Runtime::Current()->UseJitCompilation());
669
670 ArtMethod* caller = graph_->GetArtMethod();
671 // Under JIT, we should always know the caller.
672 DCHECK(caller != nullptr);
673 ScopedProfilingInfoInlineUse spiis(caller, Thread::Current());
674 ProfilingInfo* profiling_info = spiis.GetProfilingInfo();
675
676 if (profiling_info == nullptr) {
677 return kInlineCacheNoData;
678 }
679
680 *inline_cache = AllocateInlineCacheHolder(caller_compilation_unit_, hs);
681 if (inline_cache->Get() == nullptr) {
682 // We can't extract any data if we failed to allocate;
683 return kInlineCacheNoData;
684 } else {
685 Runtime::Current()->GetJit()->GetCodeCache()->CopyInlineCacheInto(
686 *profiling_info->GetInlineCache(invoke_instruction->GetDexPc()),
687 *inline_cache);
688 return GetInlineCacheType(*inline_cache);
689 }
690}
691
692HInliner::InlineCacheType HInliner::GetInlineCacheAOT(
693 const DexFile& caller_dex_file,
694 HInvoke* invoke_instruction,
695 StackHandleScope<1>* hs,
696 /*out*/Handle<mirror::ObjectArray<mirror::Class>>* inline_cache)
697 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko1a2a5cd2018-11-07 15:39:48 +0000698 const ProfileCompilationInfo* pci = codegen_->GetCompilerOptions().GetProfileCompilationInfo();
Calin Juravle13439f02017-02-21 01:17:21 -0800699 if (pci == nullptr) {
700 return kInlineCacheNoData;
701 }
702
Calin Juravlecc3171a2017-05-19 16:47:53 -0700703 std::unique_ptr<ProfileCompilationInfo::OfflineProfileMethodInfo> offline_profile =
Calin Juravle4ad95212019-09-23 23:39:41 -0400704 pci->GetHotMethodInfo(MethodReference(
705 &caller_dex_file, caller_compilation_unit_.GetDexMethodIndex()));
Calin Juravlecc3171a2017-05-19 16:47:53 -0700706 if (offline_profile == nullptr) {
Calin Juravle13439f02017-02-21 01:17:21 -0800707 return kInlineCacheNoData; // no profile information for this invocation.
708 }
709
710 *inline_cache = AllocateInlineCacheHolder(caller_compilation_unit_, hs);
711 if (inline_cache == nullptr) {
712 // We can't extract any data if we failed to allocate;
713 return kInlineCacheNoData;
714 } else {
715 return ExtractClassesFromOfflineProfile(invoke_instruction,
Calin Juravlecc3171a2017-05-19 16:47:53 -0700716 *(offline_profile.get()),
Calin Juravle13439f02017-02-21 01:17:21 -0800717 *inline_cache);
718 }
719}
720
721HInliner::InlineCacheType HInliner::ExtractClassesFromOfflineProfile(
722 const HInvoke* invoke_instruction,
723 const ProfileCompilationInfo::OfflineProfileMethodInfo& offline_profile,
724 /*out*/Handle<mirror::ObjectArray<mirror::Class>> inline_cache)
725 REQUIRES_SHARED(Locks::mutator_lock_) {
Calin Juravlee6f87cc2017-05-24 17:41:05 -0700726 const auto it = offline_profile.inline_caches->find(invoke_instruction->GetDexPc());
727 if (it == offline_profile.inline_caches->end()) {
Calin Juravle13439f02017-02-21 01:17:21 -0800728 return kInlineCacheUninitialized;
729 }
730
731 const ProfileCompilationInfo::DexPcData& dex_pc_data = it->second;
732
733 if (dex_pc_data.is_missing_types) {
734 return kInlineCacheMissingTypes;
735 }
736 if (dex_pc_data.is_megamorphic) {
737 return kInlineCacheMegamorphic;
738 }
739
740 DCHECK_LE(dex_pc_data.classes.size(), InlineCache::kIndividualCacheSize);
741 Thread* self = Thread::Current();
742 // We need to resolve the class relative to the containing dex file.
743 // So first, build a mapping from the index of dex file in the profile to
744 // its dex cache. This will avoid repeating the lookup when walking over
745 // the inline cache types.
746 std::vector<ObjPtr<mirror::DexCache>> dex_profile_index_to_dex_cache(
747 offline_profile.dex_references.size());
748 for (size_t i = 0; i < offline_profile.dex_references.size(); i++) {
749 bool found = false;
Vladimir Marko213ee2d2018-06-22 11:56:34 +0100750 for (const DexFile* dex_file : codegen_->GetCompilerOptions().GetDexFilesForOatFile()) {
Calin Juravle13439f02017-02-21 01:17:21 -0800751 if (offline_profile.dex_references[i].MatchesDex(dex_file)) {
752 dex_profile_index_to_dex_cache[i] =
753 caller_compilation_unit_.GetClassLinker()->FindDexCache(self, *dex_file);
754 found = true;
755 }
756 }
757 if (!found) {
Calin Juravlef84ef312019-09-24 19:30:44 -0700758 VLOG(compiler) << "Could not find profiled dex file: " << offline_profile.dex_references[i];
Calin Juravle13439f02017-02-21 01:17:21 -0800759 return kInlineCacheMissingTypes;
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100760 }
761 }
762
Calin Juravle13439f02017-02-21 01:17:21 -0800763 // Walk over the classes and resolve them. If we cannot find a type we return
764 // kInlineCacheMissingTypes.
765 int ic_index = 0;
766 for (const ProfileCompilationInfo::ClassReference& class_ref : dex_pc_data.classes) {
767 ObjPtr<mirror::DexCache> dex_cache =
768 dex_profile_index_to_dex_cache[class_ref.dex_profile_index];
769 DCHECK(dex_cache != nullptr);
Calin Juravle08556882017-05-26 16:40:45 -0700770
771 if (!dex_cache->GetDexFile()->IsTypeIndexValid(class_ref.type_index)) {
772 VLOG(compiler) << "Profile data corrupt: type index " << class_ref.type_index
773 << "is invalid in location" << dex_cache->GetDexFile()->GetLocation();
774 return kInlineCacheNoData;
775 }
Vladimir Marko666ee3d2017-12-11 18:37:36 +0000776 ObjPtr<mirror::Class> clazz = caller_compilation_unit_.GetClassLinker()->LookupResolvedType(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000777 class_ref.type_index,
778 dex_cache,
779 caller_compilation_unit_.GetClassLoader().Get());
Calin Juravle13439f02017-02-21 01:17:21 -0800780 if (clazz != nullptr) {
781 inline_cache->Set(ic_index++, clazz);
782 } else {
783 VLOG(compiler) << "Could not resolve class from inline cache in AOT mode "
784 << caller_compilation_unit_.GetDexFile()->PrettyMethod(
785 invoke_instruction->GetDexMethodIndex()) << " : "
786 << caller_compilation_unit_
787 .GetDexFile()->StringByTypeIdx(class_ref.type_index);
788 return kInlineCacheMissingTypes;
789 }
790 }
791 return GetInlineCacheType(inline_cache);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100792}
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000793
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000794HInstanceFieldGet* HInliner::BuildGetReceiverClass(ClassLinker* class_linker,
795 HInstruction* receiver,
796 uint32_t dex_pc) const {
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100797 ArtField* field = GetClassRoot<mirror::Object>(class_linker)->GetInstanceField(0);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000798 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
Vladimir Markoca6fff82017-10-03 14:49:14 +0100799 HInstanceFieldGet* result = new (graph_->GetAllocator()) HInstanceFieldGet(
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000800 receiver,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000801 field,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100802 DataType::Type::kReference,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000803 field->GetOffset(),
804 field->IsVolatile(),
805 field->GetDexFieldIndex(),
806 field->GetDeclaringClass()->GetDexClassDefIndex(),
807 *field->GetDexFile(),
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000808 dex_pc);
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000809 // The class of a field is effectively final, and does not have any memory dependencies.
810 result->SetSideEffects(SideEffects::None());
811 return result;
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000812}
813
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000814static ArtMethod* ResolveMethodFromInlineCache(Handle<mirror::Class> klass,
815 ArtMethod* resolved_method,
816 HInstruction* invoke_instruction,
817 PointerSize pointer_size)
818 REQUIRES_SHARED(Locks::mutator_lock_) {
819 if (Runtime::Current()->IsAotCompiler()) {
820 // We can get unrelated types when working with profiles (corruption,
821 // systme updates, or anyone can write to it). So first check if the class
822 // actually implements the declaring class of the method that is being
823 // called in bytecode.
824 // Note: the lookup methods used below require to have assignable types.
825 if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(klass.Get())) {
826 return nullptr;
827 }
828 }
829
830 if (invoke_instruction->IsInvokeInterface()) {
831 resolved_method = klass->FindVirtualMethodForInterface(resolved_method, pointer_size);
832 } else {
833 DCHECK(invoke_instruction->IsInvokeVirtual());
834 resolved_method = klass->FindVirtualMethodForVirtual(resolved_method, pointer_size);
835 }
836 DCHECK(resolved_method != nullptr);
837 return resolved_method;
838}
839
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100840bool HInliner::TryInlineMonomorphicCall(HInvoke* invoke_instruction,
841 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000842 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000843 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
844 << invoke_instruction->DebugName();
845
Andreas Gampea5b09a62016-11-17 15:21:22 -0800846 dex::TypeIndex class_index = FindClassIndexIn(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000847 GetMonomorphicType(classes), caller_compilation_unit_);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800848 if (!class_index.IsValid()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000849 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedDexCache)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000850 << "Call to " << ArtMethod::PrettyMethod(resolved_method)
851 << " from inline cache is not inlined because its class is not"
852 << " accessible to the caller";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100853 return false;
854 }
855
856 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700857 PointerSize pointer_size = class_linker->GetImagePointerSize();
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100858 Handle<mirror::Class> monomorphic_type =
859 graph_->GetHandleCache()->NewHandle(GetMonomorphicType(classes));
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000860 resolved_method = ResolveMethodFromInlineCache(
861 monomorphic_type, resolved_method, invoke_instruction, pointer_size);
862
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000863 LOG_NOTE() << "Try inline monomorphic call to " << resolved_method->PrettyMethod();
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000864 if (resolved_method == nullptr) {
865 // Bogus AOT profile, bail.
866 DCHECK(Runtime::Current()->IsAotCompiler());
867 return false;
868 }
869
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100870 HInstruction* receiver = invoke_instruction->InputAt(0);
871 HInstruction* cursor = invoke_instruction->GetPrevious();
872 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Mingyao Yang063fc772016-08-02 11:02:54 -0700873 if (!TryInlineAndReplace(invoke_instruction,
874 resolved_method,
Andreas Gampe3db70682018-12-26 15:12:03 -0800875 ReferenceTypeInfo::Create(monomorphic_type, /* is_exact= */ true),
876 /* do_rtp= */ false,
877 /* cha_devirtualize= */ false)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100878 return false;
879 }
880
881 // We successfully inlined, now add a guard.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000882 AddTypeGuard(receiver,
883 cursor,
884 bb_cursor,
885 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000886 monomorphic_type,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000887 invoke_instruction,
Andreas Gampe3db70682018-12-26 15:12:03 -0800888 /* with_deoptimization= */ true);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100889
890 // Run type propagation to get the guard typed, and eventually propagate the
891 // type of the receiver.
Vladimir Marko456307a2016-04-19 14:12:13 +0000892 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000893 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +0000894 outer_compilation_unit_.GetDexCache(),
Andreas Gampe3db70682018-12-26 15:12:03 -0800895 /* is_first_run= */ false);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100896 rtp_fixup.Run();
897
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000898 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedMonomorphicCall);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100899 return true;
900}
901
Mingyao Yang063fc772016-08-02 11:02:54 -0700902void HInliner::AddCHAGuard(HInstruction* invoke_instruction,
903 uint32_t dex_pc,
904 HInstruction* cursor,
905 HBasicBlock* bb_cursor) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100906 HShouldDeoptimizeFlag* deopt_flag = new (graph_->GetAllocator())
907 HShouldDeoptimizeFlag(graph_->GetAllocator(), dex_pc);
908 HInstruction* compare = new (graph_->GetAllocator()) HNotEqual(
Mingyao Yang063fc772016-08-02 11:02:54 -0700909 deopt_flag, graph_->GetIntConstant(0, dex_pc));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100910 HInstruction* deopt = new (graph_->GetAllocator()) HDeoptimize(
911 graph_->GetAllocator(), compare, DeoptimizationKind::kCHA, dex_pc);
Mingyao Yang063fc772016-08-02 11:02:54 -0700912
913 if (cursor != nullptr) {
914 bb_cursor->InsertInstructionAfter(deopt_flag, cursor);
915 } else {
916 bb_cursor->InsertInstructionBefore(deopt_flag, bb_cursor->GetFirstInstruction());
917 }
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800918 bb_cursor->InsertInstructionAfter(compare, deopt_flag);
919 bb_cursor->InsertInstructionAfter(deopt, compare);
920
921 // Add receiver as input to aid CHA guard optimization later.
922 deopt_flag->AddInput(invoke_instruction->InputAt(0));
923 DCHECK_EQ(deopt_flag->InputCount(), 1u);
Mingyao Yang063fc772016-08-02 11:02:54 -0700924 deopt->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800925 outermost_graph_->IncrementNumberOfCHAGuards();
Mingyao Yang063fc772016-08-02 11:02:54 -0700926}
927
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000928HInstruction* HInliner::AddTypeGuard(HInstruction* receiver,
929 HInstruction* cursor,
930 HBasicBlock* bb_cursor,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800931 dex::TypeIndex class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000932 Handle<mirror::Class> klass,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000933 HInstruction* invoke_instruction,
934 bool with_deoptimization) {
935 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
936 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
937 class_linker, receiver, invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000938 if (cursor != nullptr) {
939 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
940 } else {
941 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
942 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000943
944 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Calin Juravle07f01df2017-04-28 19:58:01 -0700945 bool is_referrer;
946 ArtMethod* outermost_art_method = outermost_graph_->GetArtMethod();
947 if (outermost_art_method == nullptr) {
948 DCHECK(Runtime::Current()->IsAotCompiler());
949 // We are in AOT mode and we don't have an ART method to determine
950 // if the inlined method belongs to the referrer. Assume it doesn't.
951 is_referrer = false;
952 } else {
953 is_referrer = klass.Get() == outermost_art_method->GetDeclaringClass();
954 }
955
Nicolas Geoffray56876342016-12-16 16:09:08 +0000956 // Note that we will just compare the classes, so we don't need Java semantics access checks.
957 // Note that the type index and the dex file are relative to the method this type guard is
958 // inlined into.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100959 HLoadClass* load_class = new (graph_->GetAllocator()) HLoadClass(graph_->GetCurrentMethod(),
960 class_index,
961 caller_dex_file,
962 klass,
963 is_referrer,
964 invoke_instruction->GetDexPc(),
Andreas Gampe3db70682018-12-26 15:12:03 -0800965 /* needs_access_check= */ false);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000966 HLoadClass::LoadKind kind = HSharpening::ComputeLoadClassKind(
Vladimir Markobb089b62018-06-28 17:30:16 +0100967 load_class, codegen_, caller_compilation_unit_);
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000968 DCHECK(kind != HLoadClass::LoadKind::kInvalid)
969 << "We should always be able to reference a class for inline caches";
Vladimir Marko28e012a2017-12-07 11:22:59 +0000970 // Load kind must be set before inserting the instruction into the graph.
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000971 load_class->SetLoadKind(kind);
Vladimir Marko28e012a2017-12-07 11:22:59 +0000972 bb_cursor->InsertInstructionAfter(load_class, receiver_class);
Calin Juravle13439f02017-02-21 01:17:21 -0800973 // In AOT mode, we will most likely load the class from BSS, which will involve a call
974 // to the runtime. In this case, the load instruction will need an environment so copy
975 // it from the invoke instruction.
976 if (load_class->NeedsEnvironment()) {
977 DCHECK(Runtime::Current()->IsAotCompiler());
978 load_class->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
979 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000980
Vladimir Markoca6fff82017-10-03 14:49:14 +0100981 HNotEqual* compare = new (graph_->GetAllocator()) HNotEqual(load_class, receiver_class);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000982 bb_cursor->InsertInstructionAfter(compare, load_class);
983 if (with_deoptimization) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100984 HDeoptimize* deoptimize = new (graph_->GetAllocator()) HDeoptimize(
985 graph_->GetAllocator(),
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000986 compare,
987 receiver,
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +0100988 Runtime::Current()->IsAotCompiler()
989 ? DeoptimizationKind::kAotInlineCache
990 : DeoptimizationKind::kJitInlineCache,
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000991 invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000992 bb_cursor->InsertInstructionAfter(deoptimize, compare);
993 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000994 DCHECK_EQ(invoke_instruction->InputAt(0), receiver);
995 receiver->ReplaceUsesDominatedBy(deoptimize, deoptimize);
996 deoptimize->SetReferenceTypeInfo(receiver->GetReferenceTypeInfo());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000997 }
998 return compare;
999}
1000
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001001bool HInliner::TryInlinePolymorphicCall(HInvoke* invoke_instruction,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001002 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001003 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001004 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
1005 << invoke_instruction->DebugName();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001006
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001007 if (TryInlinePolymorphicCallToSameTarget(invoke_instruction, resolved_method, classes)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001008 return true;
1009 }
1010
1011 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -07001012 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001013
1014 bool all_targets_inlined = true;
1015 bool one_target_inlined = false;
1016 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001017 if (classes->Get(i) == nullptr) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001018 break;
1019 }
1020 ArtMethod* method = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001021
Vladimir Marko02ca05a2020-05-12 13:58:51 +01001022 Handle<mirror::Class> handle = graph_->GetHandleCache()->NewHandle(classes->Get(i));
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +00001023 method = ResolveMethodFromInlineCache(
1024 handle, resolved_method, invoke_instruction, pointer_size);
1025 if (method == nullptr) {
1026 DCHECK(Runtime::Current()->IsAotCompiler());
1027 // AOT profile is bogus. This loop expects to iterate over all entries,
1028 // so just just continue.
1029 all_targets_inlined = false;
1030 continue;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001031 }
1032
1033 HInstruction* receiver = invoke_instruction->InputAt(0);
1034 HInstruction* cursor = invoke_instruction->GetPrevious();
1035 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
1036
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001037 dex::TypeIndex class_index = FindClassIndexIn(handle.Get(), caller_compilation_unit_);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001038 HInstruction* return_replacement = nullptr;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001039 LOG_NOTE() << "Try inline polymorphic call to " << method->PrettyMethod();
Andreas Gampea5b09a62016-11-17 15:21:22 -08001040 if (!class_index.IsValid() ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001041 !TryBuildAndInline(invoke_instruction,
1042 method,
Andreas Gampe3db70682018-12-26 15:12:03 -08001043 ReferenceTypeInfo::Create(handle, /* is_exact= */ true),
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001044 &return_replacement)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001045 all_targets_inlined = false;
1046 } else {
1047 one_target_inlined = true;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001048
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001049 LOG_SUCCESS() << "Polymorphic call to " << ArtMethod::PrettyMethod(resolved_method)
1050 << " has inlined " << ArtMethod::PrettyMethod(method);
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001051
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001052 // If we have inlined all targets before, and this receiver is the last seen,
1053 // we deoptimize instead of keeping the original invoke instruction.
Calin Juravleaf44e6c2017-05-23 14:24:55 -07001054 bool deoptimize = !UseOnlyPolymorphicInliningWithNoDeopt() &&
1055 all_targets_inlined &&
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001056 (i != InlineCache::kIndividualCacheSize - 1) &&
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001057 (classes->Get(i + 1) == nullptr);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001058
Nicolas Geoffray56876342016-12-16 16:09:08 +00001059 HInstruction* compare = AddTypeGuard(receiver,
1060 cursor,
1061 bb_cursor,
1062 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +00001063 handle,
Nicolas Geoffray56876342016-12-16 16:09:08 +00001064 invoke_instruction,
1065 deoptimize);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001066 if (deoptimize) {
1067 if (return_replacement != nullptr) {
1068 invoke_instruction->ReplaceWith(return_replacement);
1069 }
1070 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
1071 // Because the inline cache data can be populated concurrently, we force the end of the
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +00001072 // iteration. Otherwise, we could see a new receiver type.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001073 break;
1074 } else {
1075 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
1076 }
1077 }
1078 }
1079
1080 if (!one_target_inlined) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001081 LOG_FAIL_NO_STAT()
1082 << "Call to " << ArtMethod::PrettyMethod(resolved_method)
1083 << " from inline cache is not inlined because none"
1084 << " of its targets could be inlined";
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001085 return false;
1086 }
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001087
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001088 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedPolymorphicCall);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001089
1090 // Run type propagation to get the guards typed.
Vladimir Marko456307a2016-04-19 14:12:13 +00001091 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001092 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +00001093 outer_compilation_unit_.GetDexCache(),
Andreas Gampe3db70682018-12-26 15:12:03 -08001094 /* is_first_run= */ false);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001095 rtp_fixup.Run();
1096 return true;
1097}
1098
1099void HInliner::CreateDiamondPatternForPolymorphicInline(HInstruction* compare,
1100 HInstruction* return_replacement,
1101 HInstruction* invoke_instruction) {
1102 uint32_t dex_pc = invoke_instruction->GetDexPc();
1103 HBasicBlock* cursor_block = compare->GetBlock();
1104 HBasicBlock* original_invoke_block = invoke_instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001105 ArenaAllocator* allocator = graph_->GetAllocator();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001106
1107 // Spit the block after the compare: `cursor_block` will now be the start of the diamond,
1108 // and the returned block is the start of the then branch (that could contain multiple blocks).
1109 HBasicBlock* then = cursor_block->SplitAfterForInlining(compare);
1110
1111 // Split the block containing the invoke before and after the invoke. The returned block
1112 // of the split before will contain the invoke and will be the otherwise branch of
1113 // the diamond. The returned block of the split after will be the merge block
1114 // of the diamond.
1115 HBasicBlock* end_then = invoke_instruction->GetBlock();
1116 HBasicBlock* otherwise = end_then->SplitBeforeForInlining(invoke_instruction);
1117 HBasicBlock* merge = otherwise->SplitAfterForInlining(invoke_instruction);
1118
1119 // If the methods we are inlining return a value, we create a phi in the merge block
1120 // that will have the `invoke_instruction and the `return_replacement` as inputs.
1121 if (return_replacement != nullptr) {
1122 HPhi* phi = new (allocator) HPhi(
1123 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke_instruction->GetType()), dex_pc);
1124 merge->AddPhi(phi);
1125 invoke_instruction->ReplaceWith(phi);
1126 phi->AddInput(return_replacement);
1127 phi->AddInput(invoke_instruction);
1128 }
1129
1130 // Add the control flow instructions.
1131 otherwise->AddInstruction(new (allocator) HGoto(dex_pc));
1132 end_then->AddInstruction(new (allocator) HGoto(dex_pc));
1133 cursor_block->AddInstruction(new (allocator) HIf(compare, dex_pc));
1134
1135 // Add the newly created blocks to the graph.
1136 graph_->AddBlock(then);
1137 graph_->AddBlock(otherwise);
1138 graph_->AddBlock(merge);
1139
1140 // Set up successor (and implictly predecessor) relations.
1141 cursor_block->AddSuccessor(otherwise);
1142 cursor_block->AddSuccessor(then);
1143 end_then->AddSuccessor(merge);
1144 otherwise->AddSuccessor(merge);
1145
1146 // Set up dominance information.
1147 then->SetDominator(cursor_block);
1148 cursor_block->AddDominatedBlock(then);
1149 otherwise->SetDominator(cursor_block);
1150 cursor_block->AddDominatedBlock(otherwise);
1151 merge->SetDominator(cursor_block);
1152 cursor_block->AddDominatedBlock(merge);
1153
1154 // Update the revert post order.
1155 size_t index = IndexOfElement(graph_->reverse_post_order_, cursor_block);
1156 MakeRoomFor(&graph_->reverse_post_order_, 1, index);
1157 graph_->reverse_post_order_[++index] = then;
1158 index = IndexOfElement(graph_->reverse_post_order_, end_then);
1159 MakeRoomFor(&graph_->reverse_post_order_, 2, index);
1160 graph_->reverse_post_order_[++index] = otherwise;
1161 graph_->reverse_post_order_[++index] = merge;
1162
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001163
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001164 graph_->UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08001165 then, original_invoke_block, /* replace_if_back_edge= */ false);
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001166 graph_->UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08001167 otherwise, original_invoke_block, /* replace_if_back_edge= */ false);
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001168
1169 // In case the original invoke location was a back edge, we need to update
1170 // the loop to now have the merge block as a back edge.
1171 graph_->UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08001172 merge, original_invoke_block, /* replace_if_back_edge= */ true);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001173}
1174
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001175bool HInliner::TryInlinePolymorphicCallToSameTarget(
1176 HInvoke* invoke_instruction,
1177 ArtMethod* resolved_method,
1178 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001179 // This optimization only works under JIT for now.
Calin Juravle13439f02017-02-21 01:17:21 -08001180 if (!Runtime::Current()->UseJitCompilation()) {
1181 return false;
1182 }
1183
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001184 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -07001185 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001186
1187 DCHECK(resolved_method != nullptr);
1188 ArtMethod* actual_method = nullptr;
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001189 size_t method_index = invoke_instruction->IsInvokeVirtual()
1190 ? invoke_instruction->AsInvokeVirtual()->GetVTableIndex()
1191 : invoke_instruction->AsInvokeInterface()->GetImtIndex();
1192
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001193 // Check whether we are actually calling the same method among
1194 // the different types seen.
1195 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001196 if (classes->Get(i) == nullptr) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001197 break;
1198 }
1199 ArtMethod* new_method = nullptr;
1200 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001201 new_method = classes->Get(i)->GetImt(pointer_size)->Get(
Matthew Gharrity465ecc82016-07-19 21:32:52 +00001202 method_index, pointer_size);
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001203 if (new_method->IsRuntimeMethod()) {
1204 // Bail out as soon as we see a conflict trampoline in one of the target's
1205 // interface table.
1206 return false;
1207 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001208 } else {
1209 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001210 new_method = classes->Get(i)->GetEmbeddedVTableEntry(method_index, pointer_size);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001211 }
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001212 DCHECK(new_method != nullptr);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001213 if (actual_method == nullptr) {
1214 actual_method = new_method;
1215 } else if (actual_method != new_method) {
1216 // Different methods, bailout.
1217 return false;
1218 }
1219 }
1220
1221 HInstruction* receiver = invoke_instruction->InputAt(0);
1222 HInstruction* cursor = invoke_instruction->GetPrevious();
1223 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
1224
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001225 HInstruction* return_replacement = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001226 if (!TryBuildAndInline(invoke_instruction,
1227 actual_method,
1228 ReferenceTypeInfo::CreateInvalid(),
1229 &return_replacement)) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001230 return false;
1231 }
1232
1233 // We successfully inlined, now add a guard.
1234 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
1235 class_linker, receiver, invoke_instruction->GetDexPc());
1236
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001237 DataType::Type type = Is64BitInstructionSet(graph_->GetInstructionSet())
1238 ? DataType::Type::kInt64
1239 : DataType::Type::kInt32;
Vladimir Markoca6fff82017-10-03 14:49:14 +01001240 HClassTableGet* class_table_get = new (graph_->GetAllocator()) HClassTableGet(
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001241 receiver_class,
1242 type,
Vladimir Markoa1de9182016-02-25 11:37:38 +00001243 invoke_instruction->IsInvokeVirtual() ? HClassTableGet::TableKind::kVTable
1244 : HClassTableGet::TableKind::kIMTable,
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001245 method_index,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001246 invoke_instruction->GetDexPc());
1247
1248 HConstant* constant;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001249 if (type == DataType::Type::kInt64) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001250 constant = graph_->GetLongConstant(
1251 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
1252 } else {
1253 constant = graph_->GetIntConstant(
1254 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
1255 }
1256
Vladimir Markoca6fff82017-10-03 14:49:14 +01001257 HNotEqual* compare = new (graph_->GetAllocator()) HNotEqual(class_table_get, constant);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001258 if (cursor != nullptr) {
1259 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
1260 } else {
1261 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
1262 }
1263 bb_cursor->InsertInstructionAfter(class_table_get, receiver_class);
1264 bb_cursor->InsertInstructionAfter(compare, class_table_get);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001265
1266 if (outermost_graph_->IsCompilingOsr()) {
1267 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
1268 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +01001269 HDeoptimize* deoptimize = new (graph_->GetAllocator()) HDeoptimize(
1270 graph_->GetAllocator(),
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001271 compare,
1272 receiver,
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +01001273 DeoptimizationKind::kJitSameTarget,
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001274 invoke_instruction->GetDexPc());
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001275 bb_cursor->InsertInstructionAfter(deoptimize, compare);
1276 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
1277 if (return_replacement != nullptr) {
1278 invoke_instruction->ReplaceWith(return_replacement);
1279 }
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001280 receiver->ReplaceUsesDominatedBy(deoptimize, deoptimize);
Nicolas Geoffray1be7cbd2016-04-29 13:56:01 +01001281 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001282 deoptimize->SetReferenceTypeInfo(receiver->GetReferenceTypeInfo());
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001283 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001284
1285 // Run type propagation to get the guard typed.
Vladimir Marko456307a2016-04-19 14:12:13 +00001286 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001287 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +00001288 outer_compilation_unit_.GetDexCache(),
Andreas Gampe3db70682018-12-26 15:12:03 -08001289 /* is_first_run= */ false);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001290 rtp_fixup.Run();
1291
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001292 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedPolymorphicCall);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001293
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001294 LOG_SUCCESS() << "Inlined same polymorphic target " << actual_method->PrettyMethod();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001295 return true;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001296}
1297
Mingyao Yang063fc772016-08-02 11:02:54 -07001298bool HInliner::TryInlineAndReplace(HInvoke* invoke_instruction,
1299 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001300 ReferenceTypeInfo receiver_type,
Mingyao Yang063fc772016-08-02 11:02:54 -07001301 bool do_rtp,
1302 bool cha_devirtualize) {
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001303 DCHECK(!invoke_instruction->IsIntrinsic());
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001304 HInstruction* return_replacement = nullptr;
Mingyao Yang063fc772016-08-02 11:02:54 -07001305 uint32_t dex_pc = invoke_instruction->GetDexPc();
1306 HInstruction* cursor = invoke_instruction->GetPrevious();
1307 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001308 bool should_remove_invoke_instruction = false;
1309
1310 // If invoke_instruction is devirtualized to a different method, give intrinsics
1311 // another chance before we try to inline it.
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01001312 if (invoke_instruction->GetResolvedMethod() != method && method->IsIntrinsic()) {
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001313 MaybeRecordStat(stats_, MethodCompilationStat::kIntrinsicRecognized);
1314 if (invoke_instruction->IsInvokeInterface()) {
1315 // We don't intrinsify an invoke-interface directly.
1316 // Replace the invoke-interface with an invoke-virtual.
1317 HInvokeVirtual* new_invoke = new (graph_->GetAllocator()) HInvokeVirtual(
1318 graph_->GetAllocator(),
1319 invoke_instruction->GetNumberOfArguments(),
1320 invoke_instruction->GetType(),
1321 invoke_instruction->GetDexPc(),
1322 invoke_instruction->GetDexMethodIndex(), // Use interface method's dex method index.
1323 method,
1324 method->GetMethodIndex());
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01001325 DCHECK_NE(new_invoke->GetIntrinsic(), Intrinsics::kNone);
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001326 HInputsRef inputs = invoke_instruction->GetInputs();
1327 for (size_t index = 0; index != inputs.size(); ++index) {
1328 new_invoke->SetArgumentAt(index, inputs[index]);
1329 }
1330 invoke_instruction->GetBlock()->InsertInstructionBefore(new_invoke, invoke_instruction);
1331 new_invoke->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
1332 if (invoke_instruction->GetType() == DataType::Type::kReference) {
1333 new_invoke->SetReferenceTypeInfo(invoke_instruction->GetReferenceTypeInfo());
1334 }
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001335 return_replacement = new_invoke;
1336 // invoke_instruction is replaced with new_invoke.
1337 should_remove_invoke_instruction = true;
1338 } else {
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01001339 invoke_instruction->SetResolvedMethod(method);
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001340 }
1341 } else if (!TryBuildAndInline(invoke_instruction, method, receiver_type, &return_replacement)) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001342 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +00001343 DCHECK(!method->IsProxyMethod());
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001344 // Turn an invoke-interface into an invoke-virtual. An invoke-virtual is always
1345 // better than an invoke-interface because:
1346 // 1) In the best case, the interface call has one more indirection (to fetch the IMT).
1347 // 2) We will not go to the conflict trampoline with an invoke-virtual.
1348 // TODO: Consider sharpening once it is not dependent on the compiler driver.
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +00001349
1350 if (method->IsDefault() && !method->IsCopied()) {
1351 // Changing to invoke-virtual cannot be done on an original default method
1352 // since it's not in any vtable. Devirtualization by exact type/inline-cache
1353 // always uses a method in the iftable which is never an original default
1354 // method.
1355 // On the other hand, inlining an original default method by CHA is fine.
1356 DCHECK(cha_devirtualize);
1357 return false;
1358 }
1359
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001360 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001361 uint32_t dex_method_index = FindMethodIndexIn(
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001362 method, caller_dex_file, invoke_instruction->GetDexMethodIndex());
Andreas Gampee2abbc62017-09-15 11:59:26 -07001363 if (dex_method_index == dex::kDexNoIndex) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001364 return false;
1365 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01001366 HInvokeVirtual* new_invoke = new (graph_->GetAllocator()) HInvokeVirtual(
1367 graph_->GetAllocator(),
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001368 invoke_instruction->GetNumberOfArguments(),
1369 invoke_instruction->GetType(),
1370 invoke_instruction->GetDexPc(),
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001371 dex_method_index,
1372 method,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001373 method->GetMethodIndex());
1374 HInputsRef inputs = invoke_instruction->GetInputs();
1375 for (size_t index = 0; index != inputs.size(); ++index) {
1376 new_invoke->SetArgumentAt(index, inputs[index]);
1377 }
1378 invoke_instruction->GetBlock()->InsertInstructionBefore(new_invoke, invoke_instruction);
1379 new_invoke->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001380 if (invoke_instruction->GetType() == DataType::Type::kReference) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001381 new_invoke->SetReferenceTypeInfo(invoke_instruction->GetReferenceTypeInfo());
1382 }
1383 return_replacement = new_invoke;
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001384 // invoke_instruction is replaced with new_invoke.
1385 should_remove_invoke_instruction = true;
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001386 } else {
1387 // TODO: Consider sharpening an invoke virtual once it is not dependent on the
1388 // compiler driver.
1389 return false;
1390 }
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001391 } else {
1392 // invoke_instruction is inlined.
1393 should_remove_invoke_instruction = true;
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001394 }
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001395
Mingyao Yang063fc772016-08-02 11:02:54 -07001396 if (cha_devirtualize) {
1397 AddCHAGuard(invoke_instruction, dex_pc, cursor, bb_cursor);
1398 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001399 if (return_replacement != nullptr) {
1400 invoke_instruction->ReplaceWith(return_replacement);
1401 }
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001402 if (should_remove_invoke_instruction) {
1403 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
1404 }
David Brazdil94ab38f2016-06-21 17:48:19 +01001405 FixUpReturnReferenceType(method, return_replacement);
1406 if (do_rtp && ReturnTypeMoreSpecific(invoke_instruction, return_replacement)) {
1407 // Actual return value has a more specific type than the method's declared
1408 // return type. Run RTP again on the outer graph to propagate it.
1409 ReferenceTypePropagation(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001410 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +01001411 outer_compilation_unit_.GetDexCache(),
Andreas Gampe3db70682018-12-26 15:12:03 -08001412 /* is_first_run= */ false).Run();
David Brazdil94ab38f2016-06-21 17:48:19 +01001413 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001414 return true;
1415}
1416
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001417size_t HInliner::CountRecursiveCallsOf(ArtMethod* method) const {
1418 const HInliner* current = this;
1419 size_t count = 0;
1420 do {
1421 if (current->graph_->GetArtMethod() == method) {
1422 ++count;
1423 }
1424 current = current->parent_;
1425 } while (current != nullptr);
1426 return count;
1427}
1428
Vladimir Marko213ee2d2018-06-22 11:56:34 +01001429static inline bool MayInline(const CompilerOptions& compiler_options,
1430 const DexFile& inlined_from,
1431 const DexFile& inlined_into) {
Vladimir Marko213ee2d2018-06-22 11:56:34 +01001432 // We're not allowed to inline across dex files if we're the no-inline-from dex file.
1433 if (!IsSameDexFile(inlined_from, inlined_into) &&
1434 ContainsElement(compiler_options.GetNoInlineFromDexFile(), &inlined_from)) {
1435 return false;
1436 }
1437
1438 return true;
1439}
1440
Eric Holk1868de92020-02-12 09:10:21 -08001441// Returns whether inlining is allowed based on ART semantics.
1442bool HInliner::IsInliningAllowed(ArtMethod* method, const CodeItemDataAccessor& accessor) const {
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001443 if (!accessor.HasCodeItem()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001444 LOG_FAIL_NO_STAT()
1445 << "Method " << method->PrettyMethod() << " is not inlined because it is native";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001446 return false;
1447 }
1448
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001449 if (!method->IsCompilable()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001450 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedNotVerified)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001451 << "Method " << method->PrettyMethod()
1452 << " has soft failures un-handled by the compiler, so it cannot be inlined";
Aart Bik897df032018-02-07 13:29:11 -08001453 return false;
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001454 }
1455
Vladimir Marko2afaff72018-11-30 17:01:50 +00001456 if (IsMethodUnverified(codegen_->GetCompilerOptions(), method)) {
Aart Bik2c148f02018-02-02 14:30:35 -08001457 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedNotVerified)
1458 << "Method " << method->PrettyMethod()
1459 << " couldn't be verified, so it cannot be inlined";
1460 return false;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001461 }
1462
Eric Holk1868de92020-02-12 09:10:21 -08001463 return true;
1464}
1465
1466// Returns whether ART supports inlining this method.
1467//
1468// Some methods are not supported because they have features for which inlining
1469// is not implemented. For example, we do not currently support inlining throw
1470// instructions into a try block.
1471bool HInliner::IsInliningSupported(const HInvoke* invoke_instruction,
1472 ArtMethod* method,
1473 const CodeItemDataAccessor& accessor) const {
1474 if (method->IsProxyMethod()) {
1475 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedProxy)
1476 << "Method " << method->PrettyMethod()
1477 << " is not inlined because of unimplemented inline support for proxy methods.";
1478 return false;
1479 }
1480
1481 if (accessor.TriesSize() != 0) {
1482 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedTryCatch)
1483 << "Method " << method->PrettyMethod() << " is not inlined because of try block";
1484 return false;
1485 }
1486
Roland Levillain4c0eb422015-04-24 16:43:49 +01001487 if (invoke_instruction->IsInvokeStaticOrDirect() &&
1488 invoke_instruction->AsInvokeStaticOrDirect()->IsStaticWithImplicitClinitCheck()) {
1489 // Case of a static method that cannot be inlined because it implicitly
1490 // requires an initialization check of its declaring class.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001491 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedDexCache)
1492 << "Method " << method->PrettyMethod()
1493 << " is not inlined because it is static and requires a clinit"
1494 << " check that cannot be emitted due to Dex cache limitations";
Roland Levillain4c0eb422015-04-24 16:43:49 +01001495 return false;
1496 }
1497
Eric Holk1868de92020-02-12 09:10:21 -08001498 return true;
1499}
1500
1501// Returns whether our resource limits allow inlining this method.
1502bool HInliner::IsInliningBudgetAvailable(ArtMethod* method,
1503 const CodeItemDataAccessor& accessor) const {
1504 if (CountRecursiveCallsOf(method) > kMaximumNumberOfRecursiveCalls) {
1505 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedRecursiveBudget)
1506 << "Method "
1507 << method->PrettyMethod()
1508 << " is not inlined because it has reached its recursive call budget.";
1509 return false;
1510 }
1511
1512 size_t inline_max_code_units = codegen_->GetCompilerOptions().GetInlineMaxCodeUnits();
1513 if (accessor.InsnsSizeInCodeUnits() > inline_max_code_units) {
1514 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedCodeItem)
1515 << "Method " << method->PrettyMethod()
1516 << " is not inlined because its code item is too big: "
1517 << accessor.InsnsSizeInCodeUnits()
1518 << " > "
1519 << inline_max_code_units;
1520 return false;
1521 }
1522
1523 return true;
1524}
1525
1526bool HInliner::TryBuildAndInline(HInvoke* invoke_instruction,
1527 ArtMethod* method,
1528 ReferenceTypeInfo receiver_type,
1529 HInstruction** return_replacement) {
1530 // Check whether we're allowed to inline. The outermost compilation unit is the relevant
1531 // dex file here (though the transitivity of an inline chain would allow checking the caller).
1532 if (!MayInline(codegen_->GetCompilerOptions(),
1533 *method->GetDexFile(),
1534 *outer_compilation_unit_.GetDexFile())) {
1535 if (TryPatternSubstitution(invoke_instruction, method, return_replacement)) {
1536 LOG_SUCCESS() << "Successfully replaced pattern of invoke "
1537 << method->PrettyMethod();
1538 MaybeRecordStat(stats_, MethodCompilationStat::kReplacedInvokeWithSimplePattern);
1539 return true;
1540 }
1541 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedWont)
1542 << "Won't inline " << method->PrettyMethod() << " in "
1543 << outer_compilation_unit_.GetDexFile()->GetLocation() << " ("
1544 << caller_compilation_unit_.GetDexFile()->GetLocation() << ") from "
1545 << method->GetDexFile()->GetLocation();
1546 return false;
1547 }
1548
1549 CodeItemDataAccessor accessor(method->DexInstructionData());
1550
1551 if (!IsInliningAllowed(method, accessor)) {
1552 return false;
1553 }
1554
1555 if (!IsInliningSupported(invoke_instruction, method, accessor)) {
1556 return false;
1557 }
1558
1559 if (!IsInliningBudgetAvailable(method, accessor)) {
1560 return false;
1561 }
1562
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001563 if (!TryBuildAndInlineHelper(
Eric Holk1868de92020-02-12 09:10:21 -08001564 invoke_instruction, method, receiver_type, return_replacement)) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001565 return false;
1566 }
1567
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001568 LOG_SUCCESS() << method->PrettyMethod();
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001569 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedInvoke);
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001570 return true;
1571}
1572
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001573static HInstruction* GetInvokeInputForArgVRegIndex(HInvoke* invoke_instruction,
1574 size_t arg_vreg_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001575 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001576 size_t input_index = 0;
1577 for (size_t i = 0; i < arg_vreg_index; ++i, ++input_index) {
1578 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001579 if (DataType::Is64BitType(invoke_instruction->InputAt(input_index)->GetType())) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001580 ++i;
1581 DCHECK_NE(i, arg_vreg_index);
1582 }
1583 }
1584 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
1585 return invoke_instruction->InputAt(input_index);
1586}
1587
1588// Try to recognize known simple patterns and replace invoke call with appropriate instructions.
1589bool HInliner::TryPatternSubstitution(HInvoke* invoke_instruction,
1590 ArtMethod* resolved_method,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001591 HInstruction** return_replacement) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001592 InlineMethod inline_method;
1593 if (!InlineMethodAnalyser::AnalyseMethodCode(resolved_method, &inline_method)) {
1594 return false;
1595 }
1596
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001597 switch (inline_method.opcode) {
1598 case kInlineOpNop:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001599 DCHECK_EQ(invoke_instruction->GetType(), DataType::Type::kVoid);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001600 *return_replacement = nullptr;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001601 break;
1602 case kInlineOpReturnArg:
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001603 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction,
1604 inline_method.d.return_data.arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001605 break;
1606 case kInlineOpNonWideConst:
1607 if (resolved_method->GetShorty()[0] == 'L') {
1608 DCHECK_EQ(inline_method.d.data, 0u);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001609 *return_replacement = graph_->GetNullConstant();
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001610 } else {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001611 *return_replacement = graph_->GetIntConstant(static_cast<int32_t>(inline_method.d.data));
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001612 }
1613 break;
1614 case kInlineOpIGet: {
1615 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1616 if (data.method_is_static || data.object_arg != 0u) {
1617 // TODO: Needs null check.
1618 return false;
1619 }
1620 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001621 HInstanceFieldGet* iget = CreateInstanceFieldGet(data.field_idx, resolved_method, obj);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001622 DCHECK_EQ(iget->GetFieldOffset().Uint32Value(), data.field_offset);
1623 DCHECK_EQ(iget->IsVolatile() ? 1u : 0u, data.is_volatile);
1624 invoke_instruction->GetBlock()->InsertInstructionBefore(iget, invoke_instruction);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001625 *return_replacement = iget;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001626 break;
1627 }
1628 case kInlineOpIPut: {
1629 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1630 if (data.method_is_static || data.object_arg != 0u) {
1631 // TODO: Needs null check.
1632 return false;
1633 }
1634 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
1635 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, data.src_arg);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001636 HInstanceFieldSet* iput = CreateInstanceFieldSet(data.field_idx, resolved_method, obj, value);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001637 DCHECK_EQ(iput->GetFieldOffset().Uint32Value(), data.field_offset);
1638 DCHECK_EQ(iput->IsVolatile() ? 1u : 0u, data.is_volatile);
1639 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1640 if (data.return_arg_plus1 != 0u) {
1641 size_t return_arg = data.return_arg_plus1 - 1u;
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001642 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction, return_arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001643 }
1644 break;
1645 }
Vladimir Marko354efa62016-02-04 19:46:56 +00001646 case kInlineOpConstructor: {
1647 const InlineConstructorData& data = inline_method.d.constructor_data;
1648 // Get the indexes to arrays for easier processing.
1649 uint16_t iput_field_indexes[] = {
1650 data.iput0_field_index, data.iput1_field_index, data.iput2_field_index
1651 };
1652 uint16_t iput_args[] = { data.iput0_arg, data.iput1_arg, data.iput2_arg };
1653 static_assert(arraysize(iput_args) == arraysize(iput_field_indexes), "Size mismatch");
1654 // Count valid field indexes.
1655 size_t number_of_iputs = 0u;
1656 while (number_of_iputs != arraysize(iput_field_indexes) &&
1657 iput_field_indexes[number_of_iputs] != DexFile::kDexNoIndex16) {
1658 // Check that there are no duplicate valid field indexes.
1659 DCHECK_EQ(0, std::count(iput_field_indexes + number_of_iputs + 1,
1660 iput_field_indexes + arraysize(iput_field_indexes),
1661 iput_field_indexes[number_of_iputs]));
1662 ++number_of_iputs;
1663 }
1664 // Check that there are no valid field indexes in the rest of the array.
1665 DCHECK_EQ(0, std::count_if(iput_field_indexes + number_of_iputs,
1666 iput_field_indexes + arraysize(iput_field_indexes),
1667 [](uint16_t index) { return index != DexFile::kDexNoIndex16; }));
1668
1669 // Create HInstanceFieldSet for each IPUT that stores non-zero data.
Andreas Gampe3db70682018-12-26 15:12:03 -08001670 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction,
1671 /* arg_vreg_index= */ 0u);
Vladimir Marko354efa62016-02-04 19:46:56 +00001672 bool needs_constructor_barrier = false;
1673 for (size_t i = 0; i != number_of_iputs; ++i) {
1674 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, iput_args[i]);
Roland Levillain1a653882016-03-18 18:05:57 +00001675 if (!value->IsConstant() || !value->AsConstant()->IsZeroBitPattern()) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001676 uint16_t field_index = iput_field_indexes[i];
Vladimir Markof44d36c2017-03-14 14:18:46 +00001677 bool is_final;
1678 HInstanceFieldSet* iput =
1679 CreateInstanceFieldSet(field_index, resolved_method, obj, value, &is_final);
Vladimir Marko354efa62016-02-04 19:46:56 +00001680 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1681
1682 // Check whether the field is final. If it is, we need to add a barrier.
Vladimir Markof44d36c2017-03-14 14:18:46 +00001683 if (is_final) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001684 needs_constructor_barrier = true;
1685 }
1686 }
1687 }
1688 if (needs_constructor_barrier) {
Vladimir Marko1a2a5cd2018-11-07 15:39:48 +00001689 // See DexCompilationUnit::RequiresConstructorBarrier for more details.
Igor Murashkind01745e2017-04-05 16:40:31 -07001690 DCHECK(obj != nullptr) << "only non-static methods can have a constructor fence";
1691
1692 HConstructorFence* constructor_fence =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001693 new (graph_->GetAllocator()) HConstructorFence(obj, kNoDexPc, graph_->GetAllocator());
Igor Murashkind01745e2017-04-05 16:40:31 -07001694 invoke_instruction->GetBlock()->InsertInstructionBefore(constructor_fence,
1695 invoke_instruction);
Vladimir Marko354efa62016-02-04 19:46:56 +00001696 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001697 *return_replacement = nullptr;
Vladimir Marko354efa62016-02-04 19:46:56 +00001698 break;
1699 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001700 default:
1701 LOG(FATAL) << "UNREACHABLE";
1702 UNREACHABLE();
1703 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001704 return true;
1705}
1706
Vladimir Markof44d36c2017-03-14 14:18:46 +00001707HInstanceFieldGet* HInliner::CreateInstanceFieldGet(uint32_t field_index,
1708 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001709 HInstruction* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001710 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001711 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1712 ArtField* resolved_field =
Andreas Gampe3db70682018-12-26 15:12:03 -08001713 class_linker->LookupResolvedField(field_index, referrer, /* is_static= */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001714 DCHECK(resolved_field != nullptr);
Vladimir Markoca6fff82017-10-03 14:49:14 +01001715 HInstanceFieldGet* iget = new (graph_->GetAllocator()) HInstanceFieldGet(
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001716 obj,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001717 resolved_field,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001718 DataType::FromShorty(resolved_field->GetTypeDescriptor()[0]),
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001719 resolved_field->GetOffset(),
1720 resolved_field->IsVolatile(),
1721 field_index,
1722 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001723 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001724 // Read barrier generates a runtime call in slow path and we need a valid
1725 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
Andreas Gampe3db70682018-12-26 15:12:03 -08001726 /* dex_pc= */ 0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001727 if (iget->GetType() == DataType::Type::kReference) {
Vladimir Marko456307a2016-04-19 14:12:13 +00001728 // Use the same dex_cache that we used for field lookup as the hint_dex_cache.
Vladimir Marko02ca05a2020-05-12 13:58:51 +01001729 Handle<mirror::DexCache> dex_cache =
1730 graph_->GetHandleCache()->NewHandle(referrer->GetDexCache());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001731 ReferenceTypePropagation rtp(graph_,
1732 outer_compilation_unit_.GetClassLoader(),
1733 dex_cache,
Andreas Gampe3db70682018-12-26 15:12:03 -08001734 /* is_first_run= */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001735 rtp.Visit(iget);
1736 }
1737 return iget;
1738}
1739
Vladimir Markof44d36c2017-03-14 14:18:46 +00001740HInstanceFieldSet* HInliner::CreateInstanceFieldSet(uint32_t field_index,
1741 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001742 HInstruction* obj,
Vladimir Markof44d36c2017-03-14 14:18:46 +00001743 HInstruction* value,
1744 bool* is_final)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001745 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001746 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1747 ArtField* resolved_field =
Andreas Gampe3db70682018-12-26 15:12:03 -08001748 class_linker->LookupResolvedField(field_index, referrer, /* is_static= */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001749 DCHECK(resolved_field != nullptr);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001750 if (is_final != nullptr) {
1751 // This information is needed only for constructors.
1752 DCHECK(referrer->IsConstructor());
1753 *is_final = resolved_field->IsFinal();
1754 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01001755 HInstanceFieldSet* iput = new (graph_->GetAllocator()) HInstanceFieldSet(
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001756 obj,
1757 value,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001758 resolved_field,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001759 DataType::FromShorty(resolved_field->GetTypeDescriptor()[0]),
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001760 resolved_field->GetOffset(),
1761 resolved_field->IsVolatile(),
1762 field_index,
1763 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001764 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001765 // Read barrier generates a runtime call in slow path and we need a valid
1766 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
Andreas Gampe3db70682018-12-26 15:12:03 -08001767 /* dex_pc= */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001768 return iput;
1769}
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001770
Vladimir Markob1d0ee12017-04-20 19:50:32 +01001771template <typename T>
Vladimir Marko02ca05a2020-05-12 13:58:51 +01001772static inline Handle<T> NewHandleIfDifferent(ObjPtr<T> object, Handle<T> hint, HGraph* graph)
Vladimir Markob1d0ee12017-04-20 19:50:32 +01001773 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko02ca05a2020-05-12 13:58:51 +01001774 return (object != hint.Get()) ? graph->GetHandleCache()->NewHandle(object) : hint;
Vladimir Markob1d0ee12017-04-20 19:50:32 +01001775}
1776
Vladimir Marko6be1dbd2018-11-13 13:09:51 +00001777static bool CanEncodeInlinedMethodInStackMap(const DexFile& caller_dex_file, ArtMethod* callee)
1778 REQUIRES_SHARED(Locks::mutator_lock_) {
1779 if (!Runtime::Current()->IsAotCompiler()) {
1780 // JIT can always encode methods in stack maps.
1781 return true;
1782 }
1783 if (IsSameDexFile(caller_dex_file, *callee->GetDexFile())) {
1784 return true;
1785 }
1786 // TODO(ngeoffray): Support more AOT cases for inlining:
1787 // - methods in multidex
1788 // - methods in boot image for on-device non-PIC compilation.
1789 return false;
1790}
1791
Eric Holk1868de92020-02-12 09:10:21 -08001792 // Substitutes parameters in the callee graph with their values from the caller.
1793void HInliner::SubstituteArguments(HGraph* callee_graph,
1794 HInvoke* invoke_instruction,
1795 ReferenceTypeInfo receiver_type,
1796 const DexCompilationUnit& dex_compilation_unit) {
1797 ArtMethod* const resolved_method = callee_graph->GetArtMethod();
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001798 size_t parameter_index = 0;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001799 bool run_rtp = false;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001800 for (HInstructionIterator instructions(callee_graph->GetEntryBlock()->GetInstructions());
1801 !instructions.Done();
1802 instructions.Advance()) {
1803 HInstruction* current = instructions.Current();
1804 if (current->IsParameterValue()) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001805 HInstruction* argument = invoke_instruction->InputAt(parameter_index);
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001806 if (argument->IsNullConstant()) {
1807 current->ReplaceWith(callee_graph->GetNullConstant());
1808 } else if (argument->IsIntConstant()) {
1809 current->ReplaceWith(callee_graph->GetIntConstant(argument->AsIntConstant()->GetValue()));
1810 } else if (argument->IsLongConstant()) {
1811 current->ReplaceWith(callee_graph->GetLongConstant(argument->AsLongConstant()->GetValue()));
1812 } else if (argument->IsFloatConstant()) {
1813 current->ReplaceWith(
1814 callee_graph->GetFloatConstant(argument->AsFloatConstant()->GetValue()));
1815 } else if (argument->IsDoubleConstant()) {
1816 current->ReplaceWith(
1817 callee_graph->GetDoubleConstant(argument->AsDoubleConstant()->GetValue()));
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001818 } else if (argument->GetType() == DataType::Type::kReference) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001819 if (!resolved_method->IsStatic() && parameter_index == 0 && receiver_type.IsValid()) {
1820 run_rtp = true;
1821 current->SetReferenceTypeInfo(receiver_type);
1822 } else {
1823 current->SetReferenceTypeInfo(argument->GetReferenceTypeInfo());
1824 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001825 current->AsParameterValue()->SetCanBeNull(argument->CanBeNull());
1826 }
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001827 ++parameter_index;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001828 }
1829 }
1830
David Brazdil94ab38f2016-06-21 17:48:19 +01001831 // We have replaced formal arguments with actual arguments. If actual types
1832 // are more specific than the declared ones, run RTP again on the inner graph.
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001833 if (run_rtp || ArgumentTypesMoreSpecific(invoke_instruction, resolved_method)) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001834 ReferenceTypePropagation(callee_graph,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001835 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +01001836 dex_compilation_unit.GetDexCache(),
Andreas Gampe3db70682018-12-26 15:12:03 -08001837 /* is_first_run= */ false).Run();
David Brazdil94ab38f2016-06-21 17:48:19 +01001838 }
Eric Holk1868de92020-02-12 09:10:21 -08001839}
David Brazdil94ab38f2016-06-21 17:48:19 +01001840
Eric Holk1868de92020-02-12 09:10:21 -08001841// Returns whether we can inline the callee_graph into the target_block.
1842//
1843// This performs a combination of semantics checks, compiler support checks, and
1844// resource limit checks.
1845//
1846// If this function returns true, it will also set out_number_of_instructions to
1847// the number of instructions in the inlined body.
1848bool HInliner::CanInlineBody(const HGraph* callee_graph,
1849 const HBasicBlock* target_block,
1850 size_t* out_number_of_instructions) const {
1851 const DexFile& callee_dex_file = callee_graph->GetDexFile();
1852 ArtMethod* const resolved_method = callee_graph->GetArtMethod();
1853 const uint32_t method_index = resolved_method->GetMethodIndex();
1854 const bool same_dex_file =
1855 IsSameDexFile(*outer_compilation_unit_.GetDexFile(), *resolved_method->GetDexFile());
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +00001856
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001857 HBasicBlock* exit_block = callee_graph->GetExitBlock();
1858 if (exit_block == nullptr) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001859 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedInfiniteLoop)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001860 << "Method " << callee_dex_file.PrettyMethod(method_index)
1861 << " could not be inlined because it has an infinite loop";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001862 return false;
1863 }
1864
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001865 bool has_one_return = false;
Vladimir Marko60584552015-09-03 13:35:12 +00001866 for (HBasicBlock* predecessor : exit_block->GetPredecessors()) {
1867 if (predecessor->GetLastInstruction()->IsThrow()) {
Eric Holk1868de92020-02-12 09:10:21 -08001868 if (target_block->IsTryBlock()) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001869 // TODO(ngeoffray): Support adding HTryBoundary in Hgraph::InlineInto.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001870 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedTryCatch)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001871 << "Method " << callee_dex_file.PrettyMethod(method_index)
1872 << " could not be inlined because one branch always throws and"
1873 << " caller is in a try/catch block";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001874 return false;
1875 } else if (graph_->GetExitBlock() == nullptr) {
1876 // TODO(ngeoffray): Support adding HExit in the caller graph.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001877 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedInfiniteLoop)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001878 << "Method " << callee_dex_file.PrettyMethod(method_index)
1879 << " could not be inlined because one branch always throws and"
1880 << " caller does not have an exit block";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001881 return false;
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00001882 } else if (graph_->HasIrreducibleLoops()) {
1883 // TODO(ngeoffray): Support re-computing loop information to graphs with
1884 // irreducible loops?
1885 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1886 << " could not be inlined because one branch always throws and"
1887 << " caller has irreducible loops";
1888 return false;
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001889 }
1890 } else {
1891 has_one_return = true;
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001892 }
1893 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001894
1895 if (!has_one_return) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001896 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedAlwaysThrows)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001897 << "Method " << callee_dex_file.PrettyMethod(method_index)
1898 << " could not be inlined because it always throws";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001899 return false;
1900 }
1901
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001902 size_t number_of_instructions = 0;
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001903 // Skip the entry block, it does not contain instructions that prevent inlining.
1904 for (HBasicBlock* block : callee_graph->GetReversePostOrderSkipEntryBlock()) {
David Sehrc757dec2016-11-04 15:48:34 -07001905 if (block->IsLoopHeader()) {
1906 if (block->GetLoopInformation()->IsIrreducible()) {
1907 // Don't inline methods with irreducible loops, they could prevent some
1908 // optimizations to run.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001909 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedIrreducibleLoop)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001910 << "Method " << callee_dex_file.PrettyMethod(method_index)
1911 << " could not be inlined because it contains an irreducible loop";
David Sehrc757dec2016-11-04 15:48:34 -07001912 return false;
1913 }
1914 if (!block->GetLoopInformation()->HasExitEdge()) {
1915 // Don't inline methods with loops without exit, since they cause the
1916 // loop information to be computed incorrectly when updating after
1917 // inlining.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001918 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedLoopWithoutExit)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001919 << "Method " << callee_dex_file.PrettyMethod(method_index)
1920 << " could not be inlined because it contains a loop with no exit";
David Sehrc757dec2016-11-04 15:48:34 -07001921 return false;
1922 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001923 }
1924
1925 for (HInstructionIterator instr_it(block->GetInstructions());
1926 !instr_it.Done();
1927 instr_it.Advance()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001928 if (++number_of_instructions >= inlining_budget_) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001929 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedInstructionBudget)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001930 << "Method " << callee_dex_file.PrettyMethod(method_index)
1931 << " is not inlined because the outer method has reached"
1932 << " its instruction budget limit.";
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001933 return false;
1934 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001935 HInstruction* current = instr_it.Current();
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001936 if (current->NeedsEnvironment() &&
1937 (total_number_of_dex_registers_ >= kMaximumNumberOfCumulatedDexRegisters)) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001938 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedEnvironmentBudget)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001939 << "Method " << callee_dex_file.PrettyMethod(method_index)
1940 << " is not inlined because its caller has reached"
1941 << " its environment budget limit.";
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001942 return false;
1943 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001944
Nicolas Geoffrayfbdfa6d2017-02-03 10:43:13 +00001945 if (current->NeedsEnvironment() &&
1946 !CanEncodeInlinedMethodInStackMap(*caller_compilation_unit_.GetDexFile(),
1947 resolved_method)) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001948 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedStackMaps)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001949 << "Method " << callee_dex_file.PrettyMethod(method_index)
1950 << " could not be inlined because " << current->DebugName()
1951 << " needs an environment, is in a different dex file"
1952 << ", and cannot be encoded in the stack maps.";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001953 return false;
1954 }
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001955
Vladimir Markodc151b22015-10-15 18:02:30 +01001956 if (!same_dex_file && current->NeedsDexCacheOfDeclaringClass()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001957 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedDexCache)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001958 << "Method " << callee_dex_file.PrettyMethod(method_index)
1959 << " could not be inlined because " << current->DebugName()
1960 << " it is in a different dex file and requires access to the dex cache";
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001961 return false;
1962 }
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001963
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001964 if (current->IsUnresolvedStaticFieldGet() ||
1965 current->IsUnresolvedInstanceFieldGet() ||
1966 current->IsUnresolvedStaticFieldSet() ||
1967 current->IsUnresolvedInstanceFieldSet()) {
1968 // Entrypoint for unresolved fields does not handle inlined frames.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001969 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedUnresolvedEntrypoint)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001970 << "Method " << callee_dex_file.PrettyMethod(method_index)
1971 << " could not be inlined because it is using an unresolved"
1972 << " entrypoint";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001973 return false;
1974 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001975 }
1976 }
Eric Holk1868de92020-02-12 09:10:21 -08001977
1978 *out_number_of_instructions = number_of_instructions;
1979 return true;
1980}
1981
1982bool HInliner::TryBuildAndInlineHelper(HInvoke* invoke_instruction,
1983 ArtMethod* resolved_method,
1984 ReferenceTypeInfo receiver_type,
1985 HInstruction** return_replacement) {
1986 DCHECK(!(resolved_method->IsStatic() && receiver_type.IsValid()));
1987 const dex::CodeItem* code_item = resolved_method->GetCodeItem();
1988 const DexFile& callee_dex_file = *resolved_method->GetDexFile();
1989 uint32_t method_index = resolved_method->GetDexMethodIndex();
1990 CodeItemDebugInfoAccessor code_item_accessor(resolved_method->DexInstructionDebugInfo());
1991 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
1992 Handle<mirror::DexCache> dex_cache = NewHandleIfDifferent(resolved_method->GetDexCache(),
1993 caller_compilation_unit_.GetDexCache(),
Vladimir Marko02ca05a2020-05-12 13:58:51 +01001994 graph_);
Eric Holk1868de92020-02-12 09:10:21 -08001995 Handle<mirror::ClassLoader> class_loader =
1996 NewHandleIfDifferent(resolved_method->GetDeclaringClass()->GetClassLoader(),
1997 caller_compilation_unit_.GetClassLoader(),
Vladimir Marko02ca05a2020-05-12 13:58:51 +01001998 graph_);
Eric Holk1868de92020-02-12 09:10:21 -08001999
Vladimir Marko02ca05a2020-05-12 13:58:51 +01002000 Handle<mirror::Class> compiling_class =
2001 graph_->GetHandleCache()->NewHandle(resolved_method->GetDeclaringClass());
Eric Holk1868de92020-02-12 09:10:21 -08002002 DexCompilationUnit dex_compilation_unit(
2003 class_loader,
2004 class_linker,
2005 callee_dex_file,
2006 code_item,
2007 resolved_method->GetDeclaringClass()->GetDexClassDefIndex(),
2008 method_index,
2009 resolved_method->GetAccessFlags(),
2010 /* verified_method= */ nullptr,
2011 dex_cache,
2012 compiling_class);
2013
2014 InvokeType invoke_type = invoke_instruction->GetInvokeType();
2015 if (invoke_type == kInterface) {
2016 // We have statically resolved the dispatch. To please the class linker
2017 // at runtime, we change this call as if it was a virtual call.
2018 invoke_type = kVirtual;
2019 }
2020
2021 bool caller_dead_reference_safe = graph_->IsDeadReferenceSafe();
2022 const dex::ClassDef& callee_class = resolved_method->GetClassDef();
2023 // MethodContainsRSensitiveAccess is currently slow, but HasDeadReferenceSafeAnnotation()
2024 // is currently rarely true.
2025 bool callee_dead_reference_safe =
2026 annotations::HasDeadReferenceSafeAnnotation(callee_dex_file, callee_class)
2027 && !annotations::MethodContainsRSensitiveAccess(callee_dex_file, callee_class, method_index);
2028
2029 const int32_t caller_instruction_counter = graph_->GetCurrentInstructionId();
2030 HGraph* callee_graph = new (graph_->GetAllocator()) HGraph(
2031 graph_->GetAllocator(),
2032 graph_->GetArenaStack(),
Vladimir Marko02ca05a2020-05-12 13:58:51 +01002033 graph_->GetHandleCache()->GetHandles(),
Eric Holk1868de92020-02-12 09:10:21 -08002034 callee_dex_file,
2035 method_index,
2036 codegen_->GetCompilerOptions().GetInstructionSet(),
2037 invoke_type,
2038 callee_dead_reference_safe,
2039 graph_->IsDebuggable(),
2040 /* osr= */ false,
2041 /* is_shared_jit_code= */ graph_->IsCompilingForSharedJitCode(),
2042 /* baseline= */ graph_->IsCompilingBaseline(),
2043 /* start_instruction_id= */ caller_instruction_counter);
2044 callee_graph->SetArtMethod(resolved_method);
2045
2046 // When they are needed, allocate `inline_stats_` on the Arena instead
2047 // of on the stack, as Clang might produce a stack frame too large
2048 // for this function, that would not fit the requirements of the
2049 // `-Wframe-larger-than` option.
2050 if (stats_ != nullptr) {
2051 // Reuse one object for all inline attempts from this caller to keep Arena memory usage low.
2052 if (inline_stats_ == nullptr) {
2053 void* storage = graph_->GetAllocator()->Alloc<OptimizingCompilerStats>(kArenaAllocMisc);
2054 inline_stats_ = new (storage) OptimizingCompilerStats;
2055 } else {
2056 inline_stats_->Reset();
2057 }
2058 }
2059 HGraphBuilder builder(callee_graph,
2060 code_item_accessor,
2061 &dex_compilation_unit,
2062 &outer_compilation_unit_,
2063 codegen_,
2064 inline_stats_,
Vladimir Marko02ca05a2020-05-12 13:58:51 +01002065 resolved_method->GetQuickenedInfo());
Eric Holk1868de92020-02-12 09:10:21 -08002066
2067 if (builder.BuildGraph() != kAnalysisSuccess) {
2068 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedCannotBuild)
2069 << "Method " << callee_dex_file.PrettyMethod(method_index)
2070 << " could not be built, so cannot be inlined";
2071 return false;
2072 }
2073
2074 SubstituteArguments(callee_graph, invoke_instruction, receiver_type, dex_compilation_unit);
2075
2076 RunOptimizations(callee_graph, code_item, dex_compilation_unit);
2077
2078 size_t number_of_instructions = 0;
2079 if (!CanInlineBody(callee_graph, invoke_instruction->GetBlock(), &number_of_instructions)) {
2080 return false;
2081 }
2082
David Brazdil3f523062016-02-29 16:53:33 +00002083 DCHECK_EQ(caller_instruction_counter, graph_->GetCurrentInstructionId())
2084 << "No instructions can be added to the outer graph while inner graph is being built";
2085
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002086 // Inline the callee graph inside the caller graph.
David Brazdil3f523062016-02-29 16:53:33 +00002087 const int32_t callee_instruction_counter = callee_graph->GetCurrentInstructionId();
2088 graph_->SetCurrentInstructionId(callee_instruction_counter);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00002089 *return_replacement = callee_graph->InlineInto(graph_, invoke_instruction);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002090 // Update our budget for other inlining attempts in `caller_graph`.
2091 total_number_of_instructions_ += number_of_instructions;
2092 UpdateInliningBudget();
David Brazdil3f523062016-02-29 16:53:33 +00002093
2094 DCHECK_EQ(callee_instruction_counter, callee_graph->GetCurrentInstructionId())
2095 << "No instructions can be added to the inner graph during inlining into the outer graph";
2096
Vladimir Marko438709f2017-02-23 18:56:13 +00002097 if (stats_ != nullptr) {
2098 DCHECK(inline_stats_ != nullptr);
2099 inline_stats_->AddTo(stats_);
2100 }
2101
Hans Boehm206348c2018-12-05 11:11:33 -08002102 if (caller_dead_reference_safe && !callee_dead_reference_safe) {
2103 // Caller was dead reference safe, but is not anymore, since we inlined dead
2104 // reference unsafe code. Prior transformations remain valid, since they did not
2105 // affect the inlined code.
2106 graph_->MarkDeadReferenceUnsafe();
2107 }
2108
Vladimir Markobe10e8e2016-01-22 12:09:44 +00002109 return true;
2110}
Calin Juravle2e768302015-07-28 14:41:11 +00002111
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002112void HInliner::RunOptimizations(HGraph* callee_graph,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002113 const dex::CodeItem* code_item,
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002114 const DexCompilationUnit& dex_compilation_unit) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01002115 // Note: if the outermost_graph_ is being compiled OSR, we should not run any
2116 // optimization that could lead to a HDeoptimize. The following optimizations do not.
Vladimir Marko438709f2017-02-23 18:56:13 +00002117 HDeadCodeElimination dce(callee_graph, inline_stats_, "dead_code_elimination$inliner");
Andreas Gampeca620d72016-11-08 08:09:33 -08002118 HConstantFolding fold(callee_graph, "constant_folding$inliner");
Vladimir Markobb089b62018-06-28 17:30:16 +01002119 InstructionSimplifier simplify(callee_graph, codegen_, inline_stats_);
Roland Levillaina3aef2e2016-04-06 17:45:58 +01002120
2121 HOptimization* optimizations[] = {
Roland Levillaina3aef2e2016-04-06 17:45:58 +01002122 &simplify,
2123 &fold,
2124 &dce,
2125 };
2126
2127 for (size_t i = 0; i < arraysize(optimizations); ++i) {
2128 HOptimization* optimization = optimizations[i];
2129 optimization->Run();
2130 }
2131
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002132 // Bail early for pathological cases on the environment (for example recursive calls,
2133 // or too large environment).
2134 if (total_number_of_dex_registers_ >= kMaximumNumberOfCumulatedDexRegisters) {
2135 LOG_NOTE() << "Calls in " << callee_graph->GetArtMethod()->PrettyMethod()
2136 << " will not be inlined because the outer method has reached"
2137 << " its environment budget limit.";
2138 return;
Roland Levillaina3aef2e2016-04-06 17:45:58 +01002139 }
2140
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002141 // Bail early if we know we already are over the limit.
2142 size_t number_of_instructions = CountNumberOfInstructions(callee_graph);
2143 if (number_of_instructions > inlining_budget_) {
2144 LOG_NOTE() << "Calls in " << callee_graph->GetArtMethod()->PrettyMethod()
2145 << " will not be inlined because the outer method has reached"
2146 << " its instruction budget limit. " << number_of_instructions;
2147 return;
2148 }
2149
Mathieu Chartier698ebbc2018-01-05 11:00:42 -08002150 CodeItemDataAccessor accessor(callee_graph->GetDexFile(), code_item);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002151 HInliner inliner(callee_graph,
2152 outermost_graph_,
2153 codegen_,
2154 outer_compilation_unit_,
2155 dex_compilation_unit,
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002156 inline_stats_,
Mathieu Chartier808c7a52017-12-15 11:19:33 -08002157 total_number_of_dex_registers_ + accessor.RegistersSize(),
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002158 total_number_of_instructions_ + number_of_instructions,
2159 this,
2160 depth_ + 1);
2161 inliner.Run();
Roland Levillaina3aef2e2016-04-06 17:45:58 +01002162}
2163
Vladimir Marko5a62af52020-05-11 15:16:24 +01002164static bool IsReferenceTypeRefinement(ObjPtr<mirror::Class> declared_class,
2165 bool declared_is_exact,
David Brazdil94ab38f2016-06-21 17:48:19 +01002166 bool declared_can_be_null,
2167 HInstruction* actual_obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002168 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdil94ab38f2016-06-21 17:48:19 +01002169 if (declared_can_be_null && !actual_obj->CanBeNull()) {
2170 return true;
2171 }
2172
2173 ReferenceTypeInfo actual_rti = actual_obj->GetReferenceTypeInfo();
Vladimir Marko5a62af52020-05-11 15:16:24 +01002174 ObjPtr<mirror::Class> actual_class = actual_rti.GetTypeHandle().Get();
2175 return (actual_rti.IsExact() && !declared_is_exact) ||
2176 (declared_class != actual_class && declared_class->IsAssignableFrom(actual_class));
David Brazdil94ab38f2016-06-21 17:48:19 +01002177}
2178
Vladimir Marko5a62af52020-05-11 15:16:24 +01002179static bool IsReferenceTypeRefinement(ObjPtr<mirror::Class> declared_class,
2180 bool declared_can_be_null,
2181 HInstruction* actual_obj)
2182 REQUIRES_SHARED(Locks::mutator_lock_) {
2183 bool admissible = ReferenceTypePropagation::IsAdmissible(declared_class);
2184 return IsReferenceTypeRefinement(
2185 admissible ? declared_class : GetClassRoot<mirror::Class>(),
2186 /*declared_is_exact=*/ admissible && declared_class->CannotBeAssignedFromOtherTypes(),
2187 declared_can_be_null,
2188 actual_obj);
David Brazdil94ab38f2016-06-21 17:48:19 +01002189}
2190
2191bool HInliner::ArgumentTypesMoreSpecific(HInvoke* invoke_instruction, ArtMethod* resolved_method) {
2192 // If this is an instance call, test whether the type of the `this` argument
2193 // is more specific than the class which declares the method.
2194 if (!resolved_method->IsStatic()) {
Vladimir Marko5a62af52020-05-11 15:16:24 +01002195 if (IsReferenceTypeRefinement(resolved_method->GetDeclaringClass(),
2196 /*declared_can_be_null=*/ false,
David Brazdil94ab38f2016-06-21 17:48:19 +01002197 invoke_instruction->InputAt(0u))) {
2198 return true;
2199 }
2200 }
2201
David Brazdil94ab38f2016-06-21 17:48:19 +01002202 // Iterate over the list of parameter types and test whether any of the
2203 // actual inputs has a more specific reference type than the type declared in
2204 // the signature.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002205 const dex::TypeList* param_list = resolved_method->GetParameterTypeList();
David Brazdil94ab38f2016-06-21 17:48:19 +01002206 for (size_t param_idx = 0,
2207 input_idx = resolved_method->IsStatic() ? 0 : 1,
2208 e = (param_list == nullptr ? 0 : param_list->Size());
2209 param_idx < e;
2210 ++param_idx, ++input_idx) {
2211 HInstruction* input = invoke_instruction->InputAt(input_idx);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002212 if (input->GetType() == DataType::Type::kReference) {
Vladimir Markob45528c2017-07-27 14:14:28 +01002213 ObjPtr<mirror::Class> param_cls = resolved_method->LookupResolvedClassFromTypeIndex(
2214 param_list->GetTypeItem(param_idx).type_idx_);
Vladimir Marko5a62af52020-05-11 15:16:24 +01002215 if (IsReferenceTypeRefinement(param_cls, /*declared_can_be_null=*/ true, input)) {
David Brazdil94ab38f2016-06-21 17:48:19 +01002216 return true;
2217 }
2218 }
2219 }
2220
2221 return false;
2222}
2223
2224bool HInliner::ReturnTypeMoreSpecific(HInvoke* invoke_instruction,
2225 HInstruction* return_replacement) {
Alex Light68289a52015-12-15 17:30:30 -08002226 // Check the integrity of reference types and run another type propagation if needed.
David Brazdil4833f5a2015-12-16 10:37:39 +00002227 if (return_replacement != nullptr) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002228 if (return_replacement->GetType() == DataType::Type::kReference) {
David Brazdil94ab38f2016-06-21 17:48:19 +01002229 // Test if the return type is a refinement of the declared return type.
Vladimir Marko5a62af52020-05-11 15:16:24 +01002230 ReferenceTypeInfo invoke_rti = invoke_instruction->GetReferenceTypeInfo();
2231 if (IsReferenceTypeRefinement(invoke_rti.GetTypeHandle().Get(),
2232 invoke_rti.IsExact(),
2233 /*declared_can_be_null=*/ true,
David Brazdil94ab38f2016-06-21 17:48:19 +01002234 return_replacement)) {
2235 return true;
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00002236 } else if (return_replacement->IsInstanceFieldGet()) {
2237 HInstanceFieldGet* field_get = return_replacement->AsInstanceFieldGet();
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00002238 if (field_get->GetFieldInfo().GetField() ==
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002239 GetClassRoot<mirror::Object>()->GetInstanceField(0)) {
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00002240 return true;
2241 }
David Brazdil94ab38f2016-06-21 17:48:19 +01002242 }
2243 } else if (return_replacement->IsInstanceOf()) {
2244 // Inlining InstanceOf into an If may put a tighter bound on reference types.
2245 return true;
2246 }
2247 }
2248
2249 return false;
2250}
2251
2252void HInliner::FixUpReturnReferenceType(ArtMethod* resolved_method,
2253 HInstruction* return_replacement) {
2254 if (return_replacement != nullptr) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002255 if (return_replacement->GetType() == DataType::Type::kReference) {
David Brazdil4833f5a2015-12-16 10:37:39 +00002256 if (!return_replacement->GetReferenceTypeInfo().IsValid()) {
2257 // Make sure that we have a valid type for the return. We may get an invalid one when
2258 // we inline invokes with multiple branches and create a Phi for the result.
2259 // TODO: we could be more precise by merging the phi inputs but that requires
2260 // some functionality from the reference type propagation.
2261 DCHECK(return_replacement->IsPhi());
Vladimir Markob45528c2017-07-27 14:14:28 +01002262 ObjPtr<mirror::Class> cls = resolved_method->LookupResolvedReturnType();
Vladimir Marko5a62af52020-05-11 15:16:24 +01002263 ReferenceTypeInfo rti = ReferenceTypePropagation::IsAdmissible(cls)
Vladimir Marko02ca05a2020-05-12 13:58:51 +01002264 ? ReferenceTypeInfo::Create(graph_->GetHandleCache()->NewHandle(cls))
Vladimir Marko5a62af52020-05-11 15:16:24 +01002265 : graph_->GetInexactObjectRti();
2266 return_replacement->SetReferenceTypeInfo(rti);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01002267 }
Calin Juravlecdfed3d2015-10-26 14:05:01 +00002268 }
Calin Juravle2e768302015-07-28 14:41:11 +00002269 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002270}
2271
2272} // namespace art