blob: f9e9abbdfd272686255783615039732def174ebc [file] [log] [blame]
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "inliner.h"
18
Mathieu Chartiere401d142015-04-22 13:56:20 -070019#include "art_method-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070020#include "base/enums.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000021#include "builder.h"
22#include "class_linker.h"
Vladimir Markob4eb1b12018-05-24 11:09:38 +010023#include "class_root.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000024#include "constant_folding.h"
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010025#include "data_type-inl.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000026#include "dead_code_elimination.h"
Andreas Gampeb95c74b2017-04-20 19:43:21 -070027#include "dex/inline_method_analyser.h"
Vladimir Markobe10e8e2016-01-22 12:09:44 +000028#include "dex/verification_results.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070029#include "dex/verified_method.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000030#include "driver/compiler_driver-inl.h"
Calin Juravleec748352015-07-29 13:52:12 +010031#include "driver/compiler_options.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000032#include "driver/dex_compilation_unit.h"
33#include "instruction_simplifier.h"
Scott Wakelingd60a1af2015-07-22 14:32:44 +010034#include "intrinsics.h"
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +000035#include "jit/jit.h"
36#include "jit/jit_code_cache.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000037#include "mirror/class_loader.h"
38#include "mirror/dex_cache.h"
Andreas Gampe52ecb652018-10-24 15:18:21 -070039#include "mirror/object_array-alloc-inl.h"
40#include "mirror/object_array-inl.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000041#include "nodes.h"
Nicolas Geoffray335005e2015-06-25 10:01:47 +010042#include "optimizing_compiler.h"
Nicolas Geoffray454a4812015-06-09 10:37:32 +010043#include "reference_type_propagation.h"
Matthew Gharritye9288852016-07-14 14:08:16 -070044#include "register_allocator_linear_scan.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070045#include "scoped_thread_state_change-inl.h"
Vladimir Markodc151b22015-10-15 18:02:30 +010046#include "sharpening.h"
David Brazdil4833f5a2015-12-16 10:37:39 +000047#include "ssa_builder.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000048#include "ssa_phi_elimination.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000049#include "thread.h"
50
51namespace art {
52
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000053// Instruction limit to control memory.
54static constexpr size_t kMaximumNumberOfTotalInstructions = 1024;
55
56// Maximum number of instructions for considering a method small,
57// which we will always try to inline if the other non-instruction limits
58// are not reached.
59static constexpr size_t kMaximumNumberOfInstructionsForSmallMethod = 3;
Nicolas Geoffray5949fa02015-12-18 10:57:10 +000060
61// Limit the number of dex registers that we accumulate while inlining
62// to avoid creating large amount of nested environments.
Nicolas Geoffrayf81621e2017-06-07 13:18:03 +010063static constexpr size_t kMaximumNumberOfCumulatedDexRegisters = 32;
Nicolas Geoffray5949fa02015-12-18 10:57:10 +000064
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000065// Limit recursive call inlining, which do not benefit from too
66// much inlining compared to code locality.
67static constexpr size_t kMaximumNumberOfRecursiveCalls = 4;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -070068
Calin Juravlee2492d42017-03-20 11:42:13 -070069// Controls the use of inline caches in AOT mode.
Calin Juravle8af70892017-03-28 15:31:44 -070070static constexpr bool kUseAOTInlineCaches = true;
Calin Juravlee2492d42017-03-20 11:42:13 -070071
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000072// We check for line numbers to make sure the DepthString implementation
73// aligns the output nicely.
74#define LOG_INTERNAL(msg) \
75 static_assert(__LINE__ > 10, "Unhandled line number"); \
76 static_assert(__LINE__ < 10000, "Unhandled line number"); \
77 VLOG(compiler) << DepthString(__LINE__) << msg
78
79#define LOG_TRY() LOG_INTERNAL("Try inlinining call: ")
80#define LOG_NOTE() LOG_INTERNAL("Note: ")
81#define LOG_SUCCESS() LOG_INTERNAL("Success: ")
Igor Murashkin1e065a52017-08-09 13:20:34 -070082#define LOG_FAIL(stats_ptr, stat) MaybeRecordStat(stats_ptr, stat); LOG_INTERNAL("Fail: ")
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000083#define LOG_FAIL_NO_STAT() LOG_INTERNAL("Fail: ")
84
85std::string HInliner::DepthString(int line) const {
86 std::string value;
87 // Indent according to the inlining depth.
88 size_t count = depth_;
89 // Line numbers get printed in the log, so add a space if the log's line is less
90 // than 1000, and two if less than 100. 10 cannot be reached as it's the copyright.
91 if (!kIsTargetBuild) {
92 if (line < 100) {
93 value += " ";
94 }
95 if (line < 1000) {
96 value += " ";
97 }
98 // Safeguard if this file reaches more than 10000 lines.
99 DCHECK_LT(line, 10000);
100 }
101 for (size_t i = 0; i < count; ++i) {
102 value += " ";
103 }
104 return value;
105}
106
107static size_t CountNumberOfInstructions(HGraph* graph) {
108 size_t number_of_instructions = 0;
109 for (HBasicBlock* block : graph->GetReversePostOrderSkipEntryBlock()) {
110 for (HInstructionIterator instr_it(block->GetInstructions());
111 !instr_it.Done();
112 instr_it.Advance()) {
113 ++number_of_instructions;
114 }
115 }
116 return number_of_instructions;
117}
118
119void HInliner::UpdateInliningBudget() {
120 if (total_number_of_instructions_ >= kMaximumNumberOfTotalInstructions) {
121 // Always try to inline small methods.
122 inlining_budget_ = kMaximumNumberOfInstructionsForSmallMethod;
123 } else {
124 inlining_budget_ = std::max(
125 kMaximumNumberOfInstructionsForSmallMethod,
126 kMaximumNumberOfTotalInstructions - total_number_of_instructions_);
127 }
128}
129
Aart Bik24773202018-04-26 10:28:51 -0700130bool HInliner::Run() {
Vladimir Marko213ee2d2018-06-22 11:56:34 +0100131 if (codegen_->GetCompilerOptions().GetInlineMaxCodeUnits() == 0) {
Aart Bik24773202018-04-26 10:28:51 -0700132 // Inlining effectively disabled.
133 return false;
134 } else if (graph_->IsDebuggable()) {
Nicolas Geoffraye50b8d22015-03-13 08:57:42 +0000135 // For simplicity, we currently never inline when the graph is debuggable. This avoids
136 // doing some logic in the runtime to discover if a method could have been inlined.
Aart Bik24773202018-04-26 10:28:51 -0700137 return false;
Nicolas Geoffraye50b8d22015-03-13 08:57:42 +0000138 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000139
Aart Bik24773202018-04-26 10:28:51 -0700140 bool didInline = false;
141
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000142 // Initialize the number of instructions for the method being compiled. Recursive calls
143 // to HInliner::Run have already updated the instruction count.
144 if (outermost_graph_ == graph_) {
145 total_number_of_instructions_ = CountNumberOfInstructions(graph_);
146 }
147
148 UpdateInliningBudget();
149 DCHECK_NE(total_number_of_instructions_, 0u);
150 DCHECK_NE(inlining_budget_, 0u);
151
Roland Levillain6c3af162017-04-27 11:18:56 +0100152 // If we're compiling with a core image (which is only used for
153 // test purposes), honor inlining directives in method names:
154 // - if a method's name contains the substring "$inline$", ensure
155 // that this method is actually inlined;
156 // - if a method's name contains the substring "$noinline$", do not
157 // inline that method.
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000158 // We limit the latter to AOT compilation, as the JIT may or may not inline
Nicolas Geoffray08490b82017-07-18 12:58:10 +0100159 // depending on the state of classes at runtime.
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000160 const bool honor_noinline_directives = IsCompilingWithCoreImage();
161 const bool honor_inline_directives =
162 honor_noinline_directives && Runtime::Current()->IsAotCompiler();
Roland Levillain6c3af162017-04-27 11:18:56 +0100163
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +0000164 // Keep a copy of all blocks when starting the visit.
165 ArenaVector<HBasicBlock*> blocks = graph_->GetReversePostOrder();
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100166 DCHECK(!blocks.empty());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +0000167 // Because we are changing the graph when inlining,
168 // we just iterate over the blocks of the outer method.
169 // This avoids doing the inlining work again on the inlined blocks.
170 for (HBasicBlock* block : blocks) {
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000171 for (HInstruction* instruction = block->GetFirstInstruction(); instruction != nullptr;) {
172 HInstruction* next = instruction->GetNext();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100173 HInvoke* call = instruction->AsInvoke();
Razvan A Lupusoru3e90a962015-03-27 13:44:44 -0700174 // As long as the call is not intrinsified, it is worth trying to inline.
175 if (call != nullptr && call->GetIntrinsic() == Intrinsics::kNone) {
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000176 if (honor_noinline_directives) {
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000177 // Debugging case: directives in method names control or assert on inlining.
178 std::string callee_name = outer_compilation_unit_.GetDexFile()->PrettyMethod(
179 call->GetDexMethodIndex(), /* with_signature */ false);
180 // Tests prevent inlining by having $noinline$ in their method names.
181 if (callee_name.find("$noinline$") == std::string::npos) {
Aart Bik24773202018-04-26 10:28:51 -0700182 if (TryInline(call)) {
183 didInline = true;
Aart Bik54e45c52018-04-27 13:57:21 -0700184 } else if (honor_inline_directives) {
Nicolas Geoffray1949baf2017-10-17 12:14:53 +0000185 bool should_have_inlined = (callee_name.find("$inline$") != std::string::npos);
186 CHECK(!should_have_inlined) << "Could not inline " << callee_name;
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000187 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000188 }
Guillaume "Vermeille" Sancheze918d382015-06-03 15:32:41 +0100189 } else {
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000190 DCHECK(!honor_inline_directives);
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000191 // Normal case: try to inline.
Aart Bik24773202018-04-26 10:28:51 -0700192 if (TryInline(call)) {
193 didInline = true;
194 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000195 }
196 }
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000197 instruction = next;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000198 }
199 }
Aart Bik24773202018-04-26 10:28:51 -0700200
201 return didInline;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000202}
203
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100204static bool IsMethodOrDeclaringClassFinal(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700205 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100206 return method->IsFinal() || method->GetDeclaringClass()->IsFinal();
207}
208
209/**
210 * Given the `resolved_method` looked up in the dex cache, try to find
211 * the actual runtime target of an interface or virtual call.
212 * Return nullptr if the runtime target cannot be proven.
213 */
214static ArtMethod* FindVirtualOrInterfaceTarget(HInvoke* invoke, ArtMethod* resolved_method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700215 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100216 if (IsMethodOrDeclaringClassFinal(resolved_method)) {
217 // No need to lookup further, the resolved method will be the target.
218 return resolved_method;
219 }
220
221 HInstruction* receiver = invoke->InputAt(0);
222 if (receiver->IsNullCheck()) {
223 // Due to multiple levels of inlining within the same pass, it might be that
224 // null check does not have the reference type of the actual receiver.
225 receiver = receiver->InputAt(0);
226 }
227 ReferenceTypeInfo info = receiver->GetReferenceTypeInfo();
Calin Juravle2e768302015-07-28 14:41:11 +0000228 DCHECK(info.IsValid()) << "Invalid RTI for " << receiver->DebugName();
229 if (!info.IsExact()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100230 // We currently only support inlining with known receivers.
231 // TODO: Remove this check, we should be able to inline final methods
232 // on unknown receivers.
233 return nullptr;
234 } else if (info.GetTypeHandle()->IsInterface()) {
235 // Statically knowing that the receiver has an interface type cannot
236 // help us find what is the target method.
237 return nullptr;
238 } else if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(info.GetTypeHandle().Get())) {
239 // The method that we're trying to call is not in the receiver's class or super classes.
240 return nullptr;
Nicolas Geoffrayab5327d2016-03-18 11:36:20 +0000241 } else if (info.GetTypeHandle()->IsErroneous()) {
242 // If the type is erroneous, do not go further, as we are going to query the vtable or
243 // imt table, that we can only safely do on non-erroneous classes.
244 return nullptr;
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100245 }
246
247 ClassLinker* cl = Runtime::Current()->GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700248 PointerSize pointer_size = cl->GetImagePointerSize();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100249 if (invoke->IsInvokeInterface()) {
250 resolved_method = info.GetTypeHandle()->FindVirtualMethodForInterface(
251 resolved_method, pointer_size);
252 } else {
253 DCHECK(invoke->IsInvokeVirtual());
254 resolved_method = info.GetTypeHandle()->FindVirtualMethodForVirtual(
255 resolved_method, pointer_size);
256 }
257
258 if (resolved_method == nullptr) {
259 // The information we had on the receiver was not enough to find
260 // the target method. Since we check above the exact type of the receiver,
261 // the only reason this can happen is an IncompatibleClassChangeError.
262 return nullptr;
Alex Light9139e002015-10-09 15:59:48 -0700263 } else if (!resolved_method->IsInvokable()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100264 // The information we had on the receiver was not enough to find
265 // the target method. Since we check above the exact type of the receiver,
266 // the only reason this can happen is an IncompatibleClassChangeError.
267 return nullptr;
268 } else if (IsMethodOrDeclaringClassFinal(resolved_method)) {
269 // A final method has to be the target method.
270 return resolved_method;
271 } else if (info.IsExact()) {
272 // If we found a method and the receiver's concrete type is statically
273 // known, we know for sure the target.
274 return resolved_method;
275 } else {
276 // Even if we did find a method, the receiver type was not enough to
277 // statically find the runtime target.
278 return nullptr;
279 }
280}
281
282static uint32_t FindMethodIndexIn(ArtMethod* method,
283 const DexFile& dex_file,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000284 uint32_t name_and_signature_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700285 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100286 if (IsSameDexFile(*method->GetDexFile(), dex_file)) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100287 return method->GetDexMethodIndex();
288 } else {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000289 return method->FindDexMethodIndexInOtherDexFile(dex_file, name_and_signature_index);
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100290 }
291}
292
Andreas Gampea5b09a62016-11-17 15:21:22 -0800293static dex::TypeIndex FindClassIndexIn(mirror::Class* cls,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000294 const DexCompilationUnit& compilation_unit)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700295 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000296 const DexFile& dex_file = *compilation_unit.GetDexFile();
Andreas Gampea5b09a62016-11-17 15:21:22 -0800297 dex::TypeIndex index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100298 if (cls->GetDexCache() == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700299 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000300 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800301 } else if (!cls->GetDexTypeIndex().IsValid()) {
David Sehr709b0702016-10-13 09:12:37 -0700302 DCHECK(cls->IsProxyClass()) << cls->PrettyClass();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100303 // TODO: deal with proxy classes.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100304 } else if (IsSameDexFile(cls->GetDexFile(), dex_file)) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000305 DCHECK_EQ(cls->GetDexCache(), compilation_unit.GetDexCache().Get());
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000306 index = cls->GetDexTypeIndex();
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100307 } else {
308 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000309 // We cannot guarantee the entry will resolve to the same class,
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100310 // as there may be different class loaders. So only return the index if it's
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000311 // the right class already resolved with the class loader.
312 if (index.IsValid()) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +0000313 ObjPtr<mirror::Class> resolved = compilation_unit.GetClassLinker()->LookupResolvedType(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000314 index, compilation_unit.GetDexCache().Get(), compilation_unit.GetClassLoader().Get());
315 if (resolved != cls) {
316 index = dex::TypeIndex::Invalid();
317 }
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100318 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100319 }
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000320
321 return index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100322}
323
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000324class ScopedProfilingInfoInlineUse {
325 public:
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000326 explicit ScopedProfilingInfoInlineUse(ArtMethod* method, Thread* self)
327 : method_(method),
328 self_(self),
329 // Fetch the profiling info ahead of using it. If it's null when fetching,
330 // we should not call JitCodeCache::DoneInlining.
331 profiling_info_(
332 Runtime::Current()->GetJit()->GetCodeCache()->NotifyCompilerUse(method, self)) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000333 }
334
335 ~ScopedProfilingInfoInlineUse() {
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000336 if (profiling_info_ != nullptr) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700337 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000338 DCHECK_EQ(profiling_info_, method_->GetProfilingInfo(pointer_size));
339 Runtime::Current()->GetJit()->GetCodeCache()->DoneCompilerUse(method_, self_);
340 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000341 }
342
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000343 ProfilingInfo* GetProfilingInfo() const { return profiling_info_; }
344
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000345 private:
346 ArtMethod* const method_;
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000347 Thread* const self_;
348 ProfilingInfo* const profiling_info_;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000349};
350
Calin Juravle13439f02017-02-21 01:17:21 -0800351HInliner::InlineCacheType HInliner::GetInlineCacheType(
352 const Handle<mirror::ObjectArray<mirror::Class>>& classes)
353 REQUIRES_SHARED(Locks::mutator_lock_) {
354 uint8_t number_of_types = 0;
355 for (; number_of_types < InlineCache::kIndividualCacheSize; ++number_of_types) {
356 if (classes->Get(number_of_types) == nullptr) {
357 break;
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000358 }
359 }
Calin Juravle13439f02017-02-21 01:17:21 -0800360
361 if (number_of_types == 0) {
362 return kInlineCacheUninitialized;
363 } else if (number_of_types == 1) {
364 return kInlineCacheMonomorphic;
365 } else if (number_of_types == InlineCache::kIndividualCacheSize) {
366 return kInlineCacheMegamorphic;
367 } else {
368 return kInlineCachePolymorphic;
369 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000370}
371
372static mirror::Class* GetMonomorphicType(Handle<mirror::ObjectArray<mirror::Class>> classes)
373 REQUIRES_SHARED(Locks::mutator_lock_) {
374 DCHECK(classes->Get(0) != nullptr);
375 return classes->Get(0);
376}
377
Mingyao Yang063fc772016-08-02 11:02:54 -0700378ArtMethod* HInliner::TryCHADevirtualization(ArtMethod* resolved_method) {
379 if (!resolved_method->HasSingleImplementation()) {
380 return nullptr;
381 }
382 if (Runtime::Current()->IsAotCompiler()) {
383 // No CHA-based devirtulization for AOT compiler (yet).
384 return nullptr;
385 }
386 if (outermost_graph_->IsCompilingOsr()) {
387 // We do not support HDeoptimize in OSR methods.
388 return nullptr;
389 }
Mingyao Yange8fcd012017-01-20 10:43:30 -0800390 PointerSize pointer_size = caller_compilation_unit_.GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +0000391 ArtMethod* single_impl = resolved_method->GetSingleImplementation(pointer_size);
392 if (single_impl == nullptr) {
393 return nullptr;
394 }
395 if (single_impl->IsProxyMethod()) {
396 // Proxy method is a generic invoker that's not worth
397 // devirtualizing/inlining. It also causes issues when the proxy
398 // method is in another dex file if we try to rewrite invoke-interface to
399 // invoke-virtual because a proxy method doesn't have a real dex file.
400 return nullptr;
401 }
Nicolas Geoffray8e33e842017-04-03 16:55:16 +0100402 if (!single_impl->GetDeclaringClass()->IsResolved()) {
403 // There's a race with the class loading, which updates the CHA info
404 // before setting the class to resolved. So we just bail for this
405 // rare occurence.
406 return nullptr;
407 }
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +0000408 return single_impl;
Mingyao Yang063fc772016-08-02 11:02:54 -0700409}
410
Aart Bik2c148f02018-02-02 14:30:35 -0800411static bool IsMethodUnverified(CompilerDriver* const compiler_driver, ArtMethod* method)
David Sehr0225f8e2018-01-31 08:52:24 +0000412 REQUIRES_SHARED(Locks::mutator_lock_) {
Aart Bik2c148f02018-02-02 14:30:35 -0800413 if (!method->GetDeclaringClass()->IsVerified()) {
414 if (Runtime::Current()->UseJitCompilation()) {
415 // We're at runtime, we know this is cold code if the class
416 // is not verified, so don't bother analyzing.
417 return true;
418 }
419 uint16_t class_def_idx = method->GetDeclaringClass()->GetDexClassDefIndex();
420 if (!compiler_driver->IsMethodVerifiedWithoutFailures(
421 method->GetDexMethodIndex(), class_def_idx, *method->GetDexFile())) {
422 // Method has soft or hard failures, don't analyze.
423 return true;
424 }
425 }
426 return false;
427}
428
429static bool AlwaysThrows(CompilerDriver* const compiler_driver, ArtMethod* method)
430 REQUIRES_SHARED(Locks::mutator_lock_) {
431 DCHECK(method != nullptr);
432 // Skip non-compilable and unverified methods.
433 if (!method->IsCompilable() || IsMethodUnverified(compiler_driver, method)) {
434 return false;
435 }
Aart Bika8b8e9b2018-01-09 11:01:02 -0800436 // Skip native methods, methods with try blocks, and methods that are too large.
Aart Bik2c148f02018-02-02 14:30:35 -0800437 CodeItemDataAccessor accessor(method->DexInstructionData());
Aart Bika8b8e9b2018-01-09 11:01:02 -0800438 if (!accessor.HasCodeItem() ||
439 accessor.TriesSize() != 0 ||
440 accessor.InsnsSizeInCodeUnits() > kMaximumNumberOfTotalInstructions) {
441 return false;
442 }
443 // Scan for exits.
444 bool throw_seen = false;
445 for (const DexInstructionPcPair& pair : accessor) {
446 switch (pair.Inst().Opcode()) {
447 case Instruction::RETURN:
448 case Instruction::RETURN_VOID:
449 case Instruction::RETURN_WIDE:
450 case Instruction::RETURN_OBJECT:
451 case Instruction::RETURN_VOID_NO_BARRIER:
452 return false; // found regular control flow back
453 case Instruction::THROW:
454 throw_seen = true;
455 break;
456 default:
457 break;
458 }
459 }
460 return throw_seen;
461}
462
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700463bool HInliner::TryInline(HInvoke* invoke_instruction) {
Orion Hodsonac141392017-01-13 11:53:47 +0000464 if (invoke_instruction->IsInvokeUnresolved() ||
Orion Hodson4c8e12e2018-05-18 08:33:20 +0100465 invoke_instruction->IsInvokePolymorphic() ||
466 invoke_instruction->IsInvokeCustom()) {
467 return false; // Don't bother to move further if we know the method is unresolved or the
468 // invocation is polymorphic (invoke-{polymorphic,custom}).
Calin Juravle175dc732015-08-25 15:42:32 +0100469 }
470
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000471 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100472 uint32_t method_index = invoke_instruction->GetDexMethodIndex();
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000473 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000474 LOG_TRY() << caller_dex_file.PrettyMethod(method_index);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000475
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100476 ArtMethod* resolved_method = invoke_instruction->GetResolvedMethod();
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100477 if (resolved_method == nullptr) {
478 DCHECK(invoke_instruction->IsInvokeStaticOrDirect());
479 DCHECK(invoke_instruction->AsInvokeStaticOrDirect()->IsStringInit());
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000480 LOG_FAIL_NO_STAT() << "Not inlining a String.<init> method";
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100481 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000482 }
483 ArtMethod* actual_method = nullptr;
484
485 if (invoke_instruction->IsInvokeStaticOrDirect()) {
Andreas Gampefd2140f2015-12-23 16:30:44 -0800486 actual_method = resolved_method;
Vladimir Marko58155012015-08-19 12:49:41 +0000487 } else {
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100488 // Check if we can statically find the method.
489 actual_method = FindVirtualOrInterfaceTarget(invoke_instruction, resolved_method);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000490 }
491
Mingyao Yang063fc772016-08-02 11:02:54 -0700492 bool cha_devirtualize = false;
493 if (actual_method == nullptr) {
494 ArtMethod* method = TryCHADevirtualization(resolved_method);
495 if (method != nullptr) {
496 cha_devirtualize = true;
497 actual_method = method;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000498 LOG_NOTE() << "Try CHA-based inlining of " << actual_method->PrettyMethod();
Mingyao Yang063fc772016-08-02 11:02:54 -0700499 }
500 }
501
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100502 if (actual_method != nullptr) {
Aart Bikd4e328f2018-01-16 14:14:34 -0800503 // Single target.
Mingyao Yang063fc772016-08-02 11:02:54 -0700504 bool result = TryInlineAndReplace(invoke_instruction,
505 actual_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000506 ReferenceTypeInfo::CreateInvalid(),
Mingyao Yang063fc772016-08-02 11:02:54 -0700507 /* do_rtp */ true,
508 cha_devirtualize);
Aart Bikd4e328f2018-01-16 14:14:34 -0800509 if (result) {
510 // Successfully inlined.
511 if (!invoke_instruction->IsInvokeStaticOrDirect()) {
512 if (cha_devirtualize) {
513 // Add dependency due to devirtualization. We've assumed resolved_method
514 // has single implementation.
515 outermost_graph_->AddCHASingleImplementationDependency(resolved_method);
516 MaybeRecordStat(stats_, MethodCompilationStat::kCHAInline);
517 } else {
518 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedInvokeVirtualOrInterface);
519 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700520 }
Aart Bik2c148f02018-02-02 14:30:35 -0800521 } else if (!cha_devirtualize && AlwaysThrows(compiler_driver_, actual_method)) {
Aart Bikd4e328f2018-01-16 14:14:34 -0800522 // Set always throws property for non-inlined method call with single target
523 // (unless it was obtained through CHA, because that would imply we have
524 // to add the CHA dependency, which seems not worth it).
525 invoke_instruction->SetAlwaysThrows(true);
Calin Juravle69158982016-03-16 11:53:41 +0000526 }
527 return result;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100528 }
Andreas Gampefd2140f2015-12-23 16:30:44 -0800529 DCHECK(!invoke_instruction->IsInvokeStaticOrDirect());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100530
Calin Juravle13439f02017-02-21 01:17:21 -0800531 // Try using inline caches.
532 return TryInlineFromInlineCache(caller_dex_file, invoke_instruction, resolved_method);
533}
534
535static Handle<mirror::ObjectArray<mirror::Class>> AllocateInlineCacheHolder(
536 const DexCompilationUnit& compilation_unit,
537 StackHandleScope<1>* hs)
538 REQUIRES_SHARED(Locks::mutator_lock_) {
539 Thread* self = Thread::Current();
540 ClassLinker* class_linker = compilation_unit.GetClassLinker();
541 Handle<mirror::ObjectArray<mirror::Class>> inline_cache = hs->NewHandle(
542 mirror::ObjectArray<mirror::Class>::Alloc(
543 self,
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100544 GetClassRoot<mirror::ObjectArray<mirror::Class>>(class_linker),
Calin Juravle13439f02017-02-21 01:17:21 -0800545 InlineCache::kIndividualCacheSize));
546 if (inline_cache == nullptr) {
547 // We got an OOME. Just clear the exception, and don't inline.
548 DCHECK(self->IsExceptionPending());
549 self->ClearException();
550 VLOG(compiler) << "Out of memory in the compiler when trying to inline";
551 }
552 return inline_cache;
553}
554
Calin Juravleaf44e6c2017-05-23 14:24:55 -0700555bool HInliner::UseOnlyPolymorphicInliningWithNoDeopt() {
556 // If we are compiling AOT or OSR, pretend the call using inline caches is polymorphic and
557 // do not generate a deopt.
558 //
559 // For AOT:
560 // Generating a deopt does not ensure that we will actually capture the new types;
561 // and the danger is that we could be stuck in a loop with "forever" deoptimizations.
562 // Take for example the following scenario:
563 // - we capture the inline cache in one run
564 // - the next run, we deoptimize because we miss a type check, but the method
565 // never becomes hot again
566 // In this case, the inline cache will not be updated in the profile and the AOT code
567 // will keep deoptimizing.
568 // Another scenario is if we use profile compilation for a process which is not allowed
569 // to JIT (e.g. system server). If we deoptimize we will run interpreted code for the
570 // rest of the lifetime.
571 // TODO(calin):
572 // This is a compromise because we will most likely never update the inline cache
573 // in the profile (unless there's another reason to deopt). So we might be stuck with
574 // a sub-optimal inline cache.
575 // We could be smarter when capturing inline caches to mitigate this.
576 // (e.g. by having different thresholds for new and old methods).
577 //
578 // For OSR:
579 // We may come from the interpreter and it may have seen different receiver types.
580 return Runtime::Current()->IsAotCompiler() || outermost_graph_->IsCompilingOsr();
581}
Calin Juravle13439f02017-02-21 01:17:21 -0800582bool HInliner::TryInlineFromInlineCache(const DexFile& caller_dex_file,
583 HInvoke* invoke_instruction,
584 ArtMethod* resolved_method)
585 REQUIRES_SHARED(Locks::mutator_lock_) {
Calin Juravlee2492d42017-03-20 11:42:13 -0700586 if (Runtime::Current()->IsAotCompiler() && !kUseAOTInlineCaches) {
587 return false;
588 }
589
Calin Juravle13439f02017-02-21 01:17:21 -0800590 StackHandleScope<1> hs(Thread::Current());
591 Handle<mirror::ObjectArray<mirror::Class>> inline_cache;
592 InlineCacheType inline_cache_type = Runtime::Current()->IsAotCompiler()
593 ? GetInlineCacheAOT(caller_dex_file, invoke_instruction, &hs, &inline_cache)
594 : GetInlineCacheJIT(invoke_instruction, &hs, &inline_cache);
595
596 switch (inline_cache_type) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000597 case kInlineCacheNoData: {
598 LOG_FAIL_NO_STAT()
599 << "Interface or virtual call to "
600 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
601 << " could not be statically determined";
Calin Juravle13439f02017-02-21 01:17:21 -0800602 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000603 }
Calin Juravle13439f02017-02-21 01:17:21 -0800604
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000605 case kInlineCacheUninitialized: {
606 LOG_FAIL_NO_STAT()
607 << "Interface or virtual call to "
608 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
609 << " is not hit and not inlined";
610 return false;
611 }
612
613 case kInlineCacheMonomorphic: {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000614 MaybeRecordStat(stats_, MethodCompilationStat::kMonomorphicCall);
Calin Juravleaf44e6c2017-05-23 14:24:55 -0700615 if (UseOnlyPolymorphicInliningWithNoDeopt()) {
Calin Juravle13439f02017-02-21 01:17:21 -0800616 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000617 } else {
Calin Juravle13439f02017-02-21 01:17:21 -0800618 return TryInlineMonomorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000619 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000620 }
Calin Juravle13439f02017-02-21 01:17:21 -0800621
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000622 case kInlineCachePolymorphic: {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000623 MaybeRecordStat(stats_, MethodCompilationStat::kPolymorphicCall);
Calin Juravle13439f02017-02-21 01:17:21 -0800624 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000625 }
Calin Juravle13439f02017-02-21 01:17:21 -0800626
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000627 case kInlineCacheMegamorphic: {
628 LOG_FAIL_NO_STAT()
629 << "Interface or virtual call to "
630 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
631 << " is megamorphic and not inlined";
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000632 MaybeRecordStat(stats_, MethodCompilationStat::kMegamorphicCall);
Calin Juravle13439f02017-02-21 01:17:21 -0800633 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000634 }
Calin Juravle13439f02017-02-21 01:17:21 -0800635
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000636 case kInlineCacheMissingTypes: {
637 LOG_FAIL_NO_STAT()
638 << "Interface or virtual call to "
639 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
640 << " is missing types and not inlined";
Calin Juravle13439f02017-02-21 01:17:21 -0800641 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000642 }
Calin Juravle13439f02017-02-21 01:17:21 -0800643 }
644 UNREACHABLE();
645}
646
647HInliner::InlineCacheType HInliner::GetInlineCacheJIT(
648 HInvoke* invoke_instruction,
649 StackHandleScope<1>* hs,
650 /*out*/Handle<mirror::ObjectArray<mirror::Class>>* inline_cache)
651 REQUIRES_SHARED(Locks::mutator_lock_) {
652 DCHECK(Runtime::Current()->UseJitCompilation());
653
654 ArtMethod* caller = graph_->GetArtMethod();
655 // Under JIT, we should always know the caller.
656 DCHECK(caller != nullptr);
657 ScopedProfilingInfoInlineUse spiis(caller, Thread::Current());
658 ProfilingInfo* profiling_info = spiis.GetProfilingInfo();
659
660 if (profiling_info == nullptr) {
661 return kInlineCacheNoData;
662 }
663
664 *inline_cache = AllocateInlineCacheHolder(caller_compilation_unit_, hs);
665 if (inline_cache->Get() == nullptr) {
666 // We can't extract any data if we failed to allocate;
667 return kInlineCacheNoData;
668 } else {
669 Runtime::Current()->GetJit()->GetCodeCache()->CopyInlineCacheInto(
670 *profiling_info->GetInlineCache(invoke_instruction->GetDexPc()),
671 *inline_cache);
672 return GetInlineCacheType(*inline_cache);
673 }
674}
675
676HInliner::InlineCacheType HInliner::GetInlineCacheAOT(
677 const DexFile& caller_dex_file,
678 HInvoke* invoke_instruction,
679 StackHandleScope<1>* hs,
680 /*out*/Handle<mirror::ObjectArray<mirror::Class>>* inline_cache)
681 REQUIRES_SHARED(Locks::mutator_lock_) {
682 DCHECK(Runtime::Current()->IsAotCompiler());
683 const ProfileCompilationInfo* pci = compiler_driver_->GetProfileCompilationInfo();
684 if (pci == nullptr) {
685 return kInlineCacheNoData;
686 }
687
Calin Juravlecc3171a2017-05-19 16:47:53 -0700688 std::unique_ptr<ProfileCompilationInfo::OfflineProfileMethodInfo> offline_profile =
689 pci->GetMethod(caller_dex_file.GetLocation(),
690 caller_dex_file.GetLocationChecksum(),
691 caller_compilation_unit_.GetDexMethodIndex());
692 if (offline_profile == nullptr) {
Calin Juravle13439f02017-02-21 01:17:21 -0800693 return kInlineCacheNoData; // no profile information for this invocation.
694 }
695
696 *inline_cache = AllocateInlineCacheHolder(caller_compilation_unit_, hs);
697 if (inline_cache == nullptr) {
698 // We can't extract any data if we failed to allocate;
699 return kInlineCacheNoData;
700 } else {
701 return ExtractClassesFromOfflineProfile(invoke_instruction,
Calin Juravlecc3171a2017-05-19 16:47:53 -0700702 *(offline_profile.get()),
Calin Juravle13439f02017-02-21 01:17:21 -0800703 *inline_cache);
704 }
705}
706
707HInliner::InlineCacheType HInliner::ExtractClassesFromOfflineProfile(
708 const HInvoke* invoke_instruction,
709 const ProfileCompilationInfo::OfflineProfileMethodInfo& offline_profile,
710 /*out*/Handle<mirror::ObjectArray<mirror::Class>> inline_cache)
711 REQUIRES_SHARED(Locks::mutator_lock_) {
Calin Juravlee6f87cc2017-05-24 17:41:05 -0700712 const auto it = offline_profile.inline_caches->find(invoke_instruction->GetDexPc());
713 if (it == offline_profile.inline_caches->end()) {
Calin Juravle13439f02017-02-21 01:17:21 -0800714 return kInlineCacheUninitialized;
715 }
716
717 const ProfileCompilationInfo::DexPcData& dex_pc_data = it->second;
718
719 if (dex_pc_data.is_missing_types) {
720 return kInlineCacheMissingTypes;
721 }
722 if (dex_pc_data.is_megamorphic) {
723 return kInlineCacheMegamorphic;
724 }
725
726 DCHECK_LE(dex_pc_data.classes.size(), InlineCache::kIndividualCacheSize);
727 Thread* self = Thread::Current();
728 // We need to resolve the class relative to the containing dex file.
729 // So first, build a mapping from the index of dex file in the profile to
730 // its dex cache. This will avoid repeating the lookup when walking over
731 // the inline cache types.
732 std::vector<ObjPtr<mirror::DexCache>> dex_profile_index_to_dex_cache(
733 offline_profile.dex_references.size());
734 for (size_t i = 0; i < offline_profile.dex_references.size(); i++) {
735 bool found = false;
Vladimir Marko213ee2d2018-06-22 11:56:34 +0100736 for (const DexFile* dex_file : codegen_->GetCompilerOptions().GetDexFilesForOatFile()) {
Calin Juravle13439f02017-02-21 01:17:21 -0800737 if (offline_profile.dex_references[i].MatchesDex(dex_file)) {
738 dex_profile_index_to_dex_cache[i] =
739 caller_compilation_unit_.GetClassLinker()->FindDexCache(self, *dex_file);
740 found = true;
741 }
742 }
743 if (!found) {
744 VLOG(compiler) << "Could not find profiled dex file: "
745 << offline_profile.dex_references[i].dex_location;
746 return kInlineCacheMissingTypes;
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100747 }
748 }
749
Calin Juravle13439f02017-02-21 01:17:21 -0800750 // Walk over the classes and resolve them. If we cannot find a type we return
751 // kInlineCacheMissingTypes.
752 int ic_index = 0;
753 for (const ProfileCompilationInfo::ClassReference& class_ref : dex_pc_data.classes) {
754 ObjPtr<mirror::DexCache> dex_cache =
755 dex_profile_index_to_dex_cache[class_ref.dex_profile_index];
756 DCHECK(dex_cache != nullptr);
Calin Juravle08556882017-05-26 16:40:45 -0700757
758 if (!dex_cache->GetDexFile()->IsTypeIndexValid(class_ref.type_index)) {
759 VLOG(compiler) << "Profile data corrupt: type index " << class_ref.type_index
760 << "is invalid in location" << dex_cache->GetDexFile()->GetLocation();
761 return kInlineCacheNoData;
762 }
Vladimir Marko666ee3d2017-12-11 18:37:36 +0000763 ObjPtr<mirror::Class> clazz = caller_compilation_unit_.GetClassLinker()->LookupResolvedType(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000764 class_ref.type_index,
765 dex_cache,
766 caller_compilation_unit_.GetClassLoader().Get());
Calin Juravle13439f02017-02-21 01:17:21 -0800767 if (clazz != nullptr) {
768 inline_cache->Set(ic_index++, clazz);
769 } else {
770 VLOG(compiler) << "Could not resolve class from inline cache in AOT mode "
771 << caller_compilation_unit_.GetDexFile()->PrettyMethod(
772 invoke_instruction->GetDexMethodIndex()) << " : "
773 << caller_compilation_unit_
774 .GetDexFile()->StringByTypeIdx(class_ref.type_index);
775 return kInlineCacheMissingTypes;
776 }
777 }
778 return GetInlineCacheType(inline_cache);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100779}
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000780
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000781HInstanceFieldGet* HInliner::BuildGetReceiverClass(ClassLinker* class_linker,
782 HInstruction* receiver,
783 uint32_t dex_pc) const {
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100784 ArtField* field = GetClassRoot<mirror::Object>(class_linker)->GetInstanceField(0);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000785 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
Vladimir Markoca6fff82017-10-03 14:49:14 +0100786 HInstanceFieldGet* result = new (graph_->GetAllocator()) HInstanceFieldGet(
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000787 receiver,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000788 field,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100789 DataType::Type::kReference,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000790 field->GetOffset(),
791 field->IsVolatile(),
792 field->GetDexFieldIndex(),
793 field->GetDeclaringClass()->GetDexClassDefIndex(),
794 *field->GetDexFile(),
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000795 dex_pc);
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000796 // The class of a field is effectively final, and does not have any memory dependencies.
797 result->SetSideEffects(SideEffects::None());
798 return result;
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000799}
800
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000801static ArtMethod* ResolveMethodFromInlineCache(Handle<mirror::Class> klass,
802 ArtMethod* resolved_method,
803 HInstruction* invoke_instruction,
804 PointerSize pointer_size)
805 REQUIRES_SHARED(Locks::mutator_lock_) {
806 if (Runtime::Current()->IsAotCompiler()) {
807 // We can get unrelated types when working with profiles (corruption,
808 // systme updates, or anyone can write to it). So first check if the class
809 // actually implements the declaring class of the method that is being
810 // called in bytecode.
811 // Note: the lookup methods used below require to have assignable types.
812 if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(klass.Get())) {
813 return nullptr;
814 }
815 }
816
817 if (invoke_instruction->IsInvokeInterface()) {
818 resolved_method = klass->FindVirtualMethodForInterface(resolved_method, pointer_size);
819 } else {
820 DCHECK(invoke_instruction->IsInvokeVirtual());
821 resolved_method = klass->FindVirtualMethodForVirtual(resolved_method, pointer_size);
822 }
823 DCHECK(resolved_method != nullptr);
824 return resolved_method;
825}
826
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100827bool HInliner::TryInlineMonomorphicCall(HInvoke* invoke_instruction,
828 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000829 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000830 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
831 << invoke_instruction->DebugName();
832
Andreas Gampea5b09a62016-11-17 15:21:22 -0800833 dex::TypeIndex class_index = FindClassIndexIn(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000834 GetMonomorphicType(classes), caller_compilation_unit_);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800835 if (!class_index.IsValid()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000836 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedDexCache)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000837 << "Call to " << ArtMethod::PrettyMethod(resolved_method)
838 << " from inline cache is not inlined because its class is not"
839 << " accessible to the caller";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100840 return false;
841 }
842
843 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700844 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000845 Handle<mirror::Class> monomorphic_type = handles_->NewHandle(GetMonomorphicType(classes));
846 resolved_method = ResolveMethodFromInlineCache(
847 monomorphic_type, resolved_method, invoke_instruction, pointer_size);
848
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000849 LOG_NOTE() << "Try inline monomorphic call to " << resolved_method->PrettyMethod();
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000850 if (resolved_method == nullptr) {
851 // Bogus AOT profile, bail.
852 DCHECK(Runtime::Current()->IsAotCompiler());
853 return false;
854 }
855
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100856 HInstruction* receiver = invoke_instruction->InputAt(0);
857 HInstruction* cursor = invoke_instruction->GetPrevious();
858 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Mingyao Yang063fc772016-08-02 11:02:54 -0700859 if (!TryInlineAndReplace(invoke_instruction,
860 resolved_method,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000861 ReferenceTypeInfo::Create(monomorphic_type, /* is_exact */ true),
Mingyao Yang063fc772016-08-02 11:02:54 -0700862 /* do_rtp */ false,
863 /* cha_devirtualize */ false)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100864 return false;
865 }
866
867 // We successfully inlined, now add a guard.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000868 AddTypeGuard(receiver,
869 cursor,
870 bb_cursor,
871 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000872 monomorphic_type,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000873 invoke_instruction,
874 /* with_deoptimization */ true);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100875
876 // Run type propagation to get the guard typed, and eventually propagate the
877 // type of the receiver.
Vladimir Marko456307a2016-04-19 14:12:13 +0000878 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000879 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +0000880 outer_compilation_unit_.GetDexCache(),
881 handles_,
882 /* is_first_run */ false);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100883 rtp_fixup.Run();
884
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000885 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedMonomorphicCall);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100886 return true;
887}
888
Mingyao Yang063fc772016-08-02 11:02:54 -0700889void HInliner::AddCHAGuard(HInstruction* invoke_instruction,
890 uint32_t dex_pc,
891 HInstruction* cursor,
892 HBasicBlock* bb_cursor) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100893 HShouldDeoptimizeFlag* deopt_flag = new (graph_->GetAllocator())
894 HShouldDeoptimizeFlag(graph_->GetAllocator(), dex_pc);
895 HInstruction* compare = new (graph_->GetAllocator()) HNotEqual(
Mingyao Yang063fc772016-08-02 11:02:54 -0700896 deopt_flag, graph_->GetIntConstant(0, dex_pc));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100897 HInstruction* deopt = new (graph_->GetAllocator()) HDeoptimize(
898 graph_->GetAllocator(), compare, DeoptimizationKind::kCHA, dex_pc);
Mingyao Yang063fc772016-08-02 11:02:54 -0700899
900 if (cursor != nullptr) {
901 bb_cursor->InsertInstructionAfter(deopt_flag, cursor);
902 } else {
903 bb_cursor->InsertInstructionBefore(deopt_flag, bb_cursor->GetFirstInstruction());
904 }
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800905 bb_cursor->InsertInstructionAfter(compare, deopt_flag);
906 bb_cursor->InsertInstructionAfter(deopt, compare);
907
908 // Add receiver as input to aid CHA guard optimization later.
909 deopt_flag->AddInput(invoke_instruction->InputAt(0));
910 DCHECK_EQ(deopt_flag->InputCount(), 1u);
Mingyao Yang063fc772016-08-02 11:02:54 -0700911 deopt->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800912 outermost_graph_->IncrementNumberOfCHAGuards();
Mingyao Yang063fc772016-08-02 11:02:54 -0700913}
914
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000915HInstruction* HInliner::AddTypeGuard(HInstruction* receiver,
916 HInstruction* cursor,
917 HBasicBlock* bb_cursor,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800918 dex::TypeIndex class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000919 Handle<mirror::Class> klass,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000920 HInstruction* invoke_instruction,
921 bool with_deoptimization) {
922 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
923 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
924 class_linker, receiver, invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000925 if (cursor != nullptr) {
926 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
927 } else {
928 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
929 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000930
931 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Calin Juravle07f01df2017-04-28 19:58:01 -0700932 bool is_referrer;
933 ArtMethod* outermost_art_method = outermost_graph_->GetArtMethod();
934 if (outermost_art_method == nullptr) {
935 DCHECK(Runtime::Current()->IsAotCompiler());
936 // We are in AOT mode and we don't have an ART method to determine
937 // if the inlined method belongs to the referrer. Assume it doesn't.
938 is_referrer = false;
939 } else {
940 is_referrer = klass.Get() == outermost_art_method->GetDeclaringClass();
941 }
942
Nicolas Geoffray56876342016-12-16 16:09:08 +0000943 // Note that we will just compare the classes, so we don't need Java semantics access checks.
944 // Note that the type index and the dex file are relative to the method this type guard is
945 // inlined into.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100946 HLoadClass* load_class = new (graph_->GetAllocator()) HLoadClass(graph_->GetCurrentMethod(),
947 class_index,
948 caller_dex_file,
949 klass,
950 is_referrer,
951 invoke_instruction->GetDexPc(),
952 /* needs_access_check */ false);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000953 HLoadClass::LoadKind kind = HSharpening::ComputeLoadClassKind(
Vladimir Markobb089b62018-06-28 17:30:16 +0100954 load_class, codegen_, caller_compilation_unit_);
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000955 DCHECK(kind != HLoadClass::LoadKind::kInvalid)
956 << "We should always be able to reference a class for inline caches";
Vladimir Marko28e012a2017-12-07 11:22:59 +0000957 // Load kind must be set before inserting the instruction into the graph.
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000958 load_class->SetLoadKind(kind);
Vladimir Marko28e012a2017-12-07 11:22:59 +0000959 bb_cursor->InsertInstructionAfter(load_class, receiver_class);
Calin Juravle13439f02017-02-21 01:17:21 -0800960 // In AOT mode, we will most likely load the class from BSS, which will involve a call
961 // to the runtime. In this case, the load instruction will need an environment so copy
962 // it from the invoke instruction.
963 if (load_class->NeedsEnvironment()) {
964 DCHECK(Runtime::Current()->IsAotCompiler());
965 load_class->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
966 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000967
Vladimir Markoca6fff82017-10-03 14:49:14 +0100968 HNotEqual* compare = new (graph_->GetAllocator()) HNotEqual(load_class, receiver_class);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000969 bb_cursor->InsertInstructionAfter(compare, load_class);
970 if (with_deoptimization) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100971 HDeoptimize* deoptimize = new (graph_->GetAllocator()) HDeoptimize(
972 graph_->GetAllocator(),
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000973 compare,
974 receiver,
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +0100975 Runtime::Current()->IsAotCompiler()
976 ? DeoptimizationKind::kAotInlineCache
977 : DeoptimizationKind::kJitInlineCache,
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000978 invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000979 bb_cursor->InsertInstructionAfter(deoptimize, compare);
980 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000981 DCHECK_EQ(invoke_instruction->InputAt(0), receiver);
982 receiver->ReplaceUsesDominatedBy(deoptimize, deoptimize);
983 deoptimize->SetReferenceTypeInfo(receiver->GetReferenceTypeInfo());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000984 }
985 return compare;
986}
987
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000988bool HInliner::TryInlinePolymorphicCall(HInvoke* invoke_instruction,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100989 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000990 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000991 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
992 << invoke_instruction->DebugName();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000993
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000994 if (TryInlinePolymorphicCallToSameTarget(invoke_instruction, resolved_method, classes)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000995 return true;
996 }
997
998 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700999 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001000
1001 bool all_targets_inlined = true;
1002 bool one_target_inlined = false;
1003 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001004 if (classes->Get(i) == nullptr) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001005 break;
1006 }
1007 ArtMethod* method = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001008
1009 Handle<mirror::Class> handle = handles_->NewHandle(classes->Get(i));
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +00001010 method = ResolveMethodFromInlineCache(
1011 handle, resolved_method, invoke_instruction, pointer_size);
1012 if (method == nullptr) {
1013 DCHECK(Runtime::Current()->IsAotCompiler());
1014 // AOT profile is bogus. This loop expects to iterate over all entries,
1015 // so just just continue.
1016 all_targets_inlined = false;
1017 continue;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001018 }
1019
1020 HInstruction* receiver = invoke_instruction->InputAt(0);
1021 HInstruction* cursor = invoke_instruction->GetPrevious();
1022 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
1023
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001024 dex::TypeIndex class_index = FindClassIndexIn(handle.Get(), caller_compilation_unit_);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001025 HInstruction* return_replacement = nullptr;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001026 LOG_NOTE() << "Try inline polymorphic call to " << method->PrettyMethod();
Andreas Gampea5b09a62016-11-17 15:21:22 -08001027 if (!class_index.IsValid() ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001028 !TryBuildAndInline(invoke_instruction,
1029 method,
1030 ReferenceTypeInfo::Create(handle, /* is_exact */ true),
1031 &return_replacement)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001032 all_targets_inlined = false;
1033 } else {
1034 one_target_inlined = true;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001035
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001036 LOG_SUCCESS() << "Polymorphic call to " << ArtMethod::PrettyMethod(resolved_method)
1037 << " has inlined " << ArtMethod::PrettyMethod(method);
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001038
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001039 // If we have inlined all targets before, and this receiver is the last seen,
1040 // we deoptimize instead of keeping the original invoke instruction.
Calin Juravleaf44e6c2017-05-23 14:24:55 -07001041 bool deoptimize = !UseOnlyPolymorphicInliningWithNoDeopt() &&
1042 all_targets_inlined &&
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001043 (i != InlineCache::kIndividualCacheSize - 1) &&
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001044 (classes->Get(i + 1) == nullptr);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001045
Nicolas Geoffray56876342016-12-16 16:09:08 +00001046 HInstruction* compare = AddTypeGuard(receiver,
1047 cursor,
1048 bb_cursor,
1049 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +00001050 handle,
Nicolas Geoffray56876342016-12-16 16:09:08 +00001051 invoke_instruction,
1052 deoptimize);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001053 if (deoptimize) {
1054 if (return_replacement != nullptr) {
1055 invoke_instruction->ReplaceWith(return_replacement);
1056 }
1057 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
1058 // Because the inline cache data can be populated concurrently, we force the end of the
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +00001059 // iteration. Otherwise, we could see a new receiver type.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001060 break;
1061 } else {
1062 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
1063 }
1064 }
1065 }
1066
1067 if (!one_target_inlined) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001068 LOG_FAIL_NO_STAT()
1069 << "Call to " << ArtMethod::PrettyMethod(resolved_method)
1070 << " from inline cache is not inlined because none"
1071 << " of its targets could be inlined";
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001072 return false;
1073 }
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001074
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001075 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedPolymorphicCall);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001076
1077 // Run type propagation to get the guards typed.
Vladimir Marko456307a2016-04-19 14:12:13 +00001078 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001079 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +00001080 outer_compilation_unit_.GetDexCache(),
1081 handles_,
1082 /* is_first_run */ false);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001083 rtp_fixup.Run();
1084 return true;
1085}
1086
1087void HInliner::CreateDiamondPatternForPolymorphicInline(HInstruction* compare,
1088 HInstruction* return_replacement,
1089 HInstruction* invoke_instruction) {
1090 uint32_t dex_pc = invoke_instruction->GetDexPc();
1091 HBasicBlock* cursor_block = compare->GetBlock();
1092 HBasicBlock* original_invoke_block = invoke_instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001093 ArenaAllocator* allocator = graph_->GetAllocator();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001094
1095 // Spit the block after the compare: `cursor_block` will now be the start of the diamond,
1096 // and the returned block is the start of the then branch (that could contain multiple blocks).
1097 HBasicBlock* then = cursor_block->SplitAfterForInlining(compare);
1098
1099 // Split the block containing the invoke before and after the invoke. The returned block
1100 // of the split before will contain the invoke and will be the otherwise branch of
1101 // the diamond. The returned block of the split after will be the merge block
1102 // of the diamond.
1103 HBasicBlock* end_then = invoke_instruction->GetBlock();
1104 HBasicBlock* otherwise = end_then->SplitBeforeForInlining(invoke_instruction);
1105 HBasicBlock* merge = otherwise->SplitAfterForInlining(invoke_instruction);
1106
1107 // If the methods we are inlining return a value, we create a phi in the merge block
1108 // that will have the `invoke_instruction and the `return_replacement` as inputs.
1109 if (return_replacement != nullptr) {
1110 HPhi* phi = new (allocator) HPhi(
1111 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke_instruction->GetType()), dex_pc);
1112 merge->AddPhi(phi);
1113 invoke_instruction->ReplaceWith(phi);
1114 phi->AddInput(return_replacement);
1115 phi->AddInput(invoke_instruction);
1116 }
1117
1118 // Add the control flow instructions.
1119 otherwise->AddInstruction(new (allocator) HGoto(dex_pc));
1120 end_then->AddInstruction(new (allocator) HGoto(dex_pc));
1121 cursor_block->AddInstruction(new (allocator) HIf(compare, dex_pc));
1122
1123 // Add the newly created blocks to the graph.
1124 graph_->AddBlock(then);
1125 graph_->AddBlock(otherwise);
1126 graph_->AddBlock(merge);
1127
1128 // Set up successor (and implictly predecessor) relations.
1129 cursor_block->AddSuccessor(otherwise);
1130 cursor_block->AddSuccessor(then);
1131 end_then->AddSuccessor(merge);
1132 otherwise->AddSuccessor(merge);
1133
1134 // Set up dominance information.
1135 then->SetDominator(cursor_block);
1136 cursor_block->AddDominatedBlock(then);
1137 otherwise->SetDominator(cursor_block);
1138 cursor_block->AddDominatedBlock(otherwise);
1139 merge->SetDominator(cursor_block);
1140 cursor_block->AddDominatedBlock(merge);
1141
1142 // Update the revert post order.
1143 size_t index = IndexOfElement(graph_->reverse_post_order_, cursor_block);
1144 MakeRoomFor(&graph_->reverse_post_order_, 1, index);
1145 graph_->reverse_post_order_[++index] = then;
1146 index = IndexOfElement(graph_->reverse_post_order_, end_then);
1147 MakeRoomFor(&graph_->reverse_post_order_, 2, index);
1148 graph_->reverse_post_order_[++index] = otherwise;
1149 graph_->reverse_post_order_[++index] = merge;
1150
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001151
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001152 graph_->UpdateLoopAndTryInformationOfNewBlock(
1153 then, original_invoke_block, /* replace_if_back_edge */ false);
1154 graph_->UpdateLoopAndTryInformationOfNewBlock(
1155 otherwise, original_invoke_block, /* replace_if_back_edge */ false);
1156
1157 // In case the original invoke location was a back edge, we need to update
1158 // the loop to now have the merge block as a back edge.
1159 graph_->UpdateLoopAndTryInformationOfNewBlock(
1160 merge, original_invoke_block, /* replace_if_back_edge */ true);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001161}
1162
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001163bool HInliner::TryInlinePolymorphicCallToSameTarget(
1164 HInvoke* invoke_instruction,
1165 ArtMethod* resolved_method,
1166 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001167 // This optimization only works under JIT for now.
Calin Juravle13439f02017-02-21 01:17:21 -08001168 if (!Runtime::Current()->UseJitCompilation()) {
1169 return false;
1170 }
1171
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001172 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -07001173 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001174
1175 DCHECK(resolved_method != nullptr);
1176 ArtMethod* actual_method = nullptr;
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001177 size_t method_index = invoke_instruction->IsInvokeVirtual()
1178 ? invoke_instruction->AsInvokeVirtual()->GetVTableIndex()
1179 : invoke_instruction->AsInvokeInterface()->GetImtIndex();
1180
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001181 // Check whether we are actually calling the same method among
1182 // the different types seen.
1183 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001184 if (classes->Get(i) == nullptr) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001185 break;
1186 }
1187 ArtMethod* new_method = nullptr;
1188 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001189 new_method = classes->Get(i)->GetImt(pointer_size)->Get(
Matthew Gharrity465ecc82016-07-19 21:32:52 +00001190 method_index, pointer_size);
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001191 if (new_method->IsRuntimeMethod()) {
1192 // Bail out as soon as we see a conflict trampoline in one of the target's
1193 // interface table.
1194 return false;
1195 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001196 } else {
1197 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001198 new_method = classes->Get(i)->GetEmbeddedVTableEntry(method_index, pointer_size);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001199 }
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001200 DCHECK(new_method != nullptr);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001201 if (actual_method == nullptr) {
1202 actual_method = new_method;
1203 } else if (actual_method != new_method) {
1204 // Different methods, bailout.
1205 return false;
1206 }
1207 }
1208
1209 HInstruction* receiver = invoke_instruction->InputAt(0);
1210 HInstruction* cursor = invoke_instruction->GetPrevious();
1211 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
1212
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001213 HInstruction* return_replacement = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001214 if (!TryBuildAndInline(invoke_instruction,
1215 actual_method,
1216 ReferenceTypeInfo::CreateInvalid(),
1217 &return_replacement)) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001218 return false;
1219 }
1220
1221 // We successfully inlined, now add a guard.
1222 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
1223 class_linker, receiver, invoke_instruction->GetDexPc());
1224
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001225 DataType::Type type = Is64BitInstructionSet(graph_->GetInstructionSet())
1226 ? DataType::Type::kInt64
1227 : DataType::Type::kInt32;
Vladimir Markoca6fff82017-10-03 14:49:14 +01001228 HClassTableGet* class_table_get = new (graph_->GetAllocator()) HClassTableGet(
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001229 receiver_class,
1230 type,
Vladimir Markoa1de9182016-02-25 11:37:38 +00001231 invoke_instruction->IsInvokeVirtual() ? HClassTableGet::TableKind::kVTable
1232 : HClassTableGet::TableKind::kIMTable,
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001233 method_index,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001234 invoke_instruction->GetDexPc());
1235
1236 HConstant* constant;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001237 if (type == DataType::Type::kInt64) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001238 constant = graph_->GetLongConstant(
1239 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
1240 } else {
1241 constant = graph_->GetIntConstant(
1242 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
1243 }
1244
Vladimir Markoca6fff82017-10-03 14:49:14 +01001245 HNotEqual* compare = new (graph_->GetAllocator()) HNotEqual(class_table_get, constant);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001246 if (cursor != nullptr) {
1247 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
1248 } else {
1249 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
1250 }
1251 bb_cursor->InsertInstructionAfter(class_table_get, receiver_class);
1252 bb_cursor->InsertInstructionAfter(compare, class_table_get);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001253
1254 if (outermost_graph_->IsCompilingOsr()) {
1255 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
1256 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +01001257 HDeoptimize* deoptimize = new (graph_->GetAllocator()) HDeoptimize(
1258 graph_->GetAllocator(),
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001259 compare,
1260 receiver,
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +01001261 DeoptimizationKind::kJitSameTarget,
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001262 invoke_instruction->GetDexPc());
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001263 bb_cursor->InsertInstructionAfter(deoptimize, compare);
1264 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
1265 if (return_replacement != nullptr) {
1266 invoke_instruction->ReplaceWith(return_replacement);
1267 }
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001268 receiver->ReplaceUsesDominatedBy(deoptimize, deoptimize);
Nicolas Geoffray1be7cbd2016-04-29 13:56:01 +01001269 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001270 deoptimize->SetReferenceTypeInfo(receiver->GetReferenceTypeInfo());
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001271 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001272
1273 // Run type propagation to get the guard typed.
Vladimir Marko456307a2016-04-19 14:12:13 +00001274 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001275 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +00001276 outer_compilation_unit_.GetDexCache(),
1277 handles_,
1278 /* is_first_run */ false);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001279 rtp_fixup.Run();
1280
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001281 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedPolymorphicCall);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001282
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001283 LOG_SUCCESS() << "Inlined same polymorphic target " << actual_method->PrettyMethod();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001284 return true;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001285}
1286
Mingyao Yang063fc772016-08-02 11:02:54 -07001287bool HInliner::TryInlineAndReplace(HInvoke* invoke_instruction,
1288 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001289 ReferenceTypeInfo receiver_type,
Mingyao Yang063fc772016-08-02 11:02:54 -07001290 bool do_rtp,
1291 bool cha_devirtualize) {
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001292 DCHECK(!invoke_instruction->IsIntrinsic());
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001293 HInstruction* return_replacement = nullptr;
Mingyao Yang063fc772016-08-02 11:02:54 -07001294 uint32_t dex_pc = invoke_instruction->GetDexPc();
1295 HInstruction* cursor = invoke_instruction->GetPrevious();
1296 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001297 bool should_remove_invoke_instruction = false;
1298
1299 // If invoke_instruction is devirtualized to a different method, give intrinsics
1300 // another chance before we try to inline it.
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01001301 if (invoke_instruction->GetResolvedMethod() != method && method->IsIntrinsic()) {
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001302 MaybeRecordStat(stats_, MethodCompilationStat::kIntrinsicRecognized);
1303 if (invoke_instruction->IsInvokeInterface()) {
1304 // We don't intrinsify an invoke-interface directly.
1305 // Replace the invoke-interface with an invoke-virtual.
1306 HInvokeVirtual* new_invoke = new (graph_->GetAllocator()) HInvokeVirtual(
1307 graph_->GetAllocator(),
1308 invoke_instruction->GetNumberOfArguments(),
1309 invoke_instruction->GetType(),
1310 invoke_instruction->GetDexPc(),
1311 invoke_instruction->GetDexMethodIndex(), // Use interface method's dex method index.
1312 method,
1313 method->GetMethodIndex());
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01001314 DCHECK_NE(new_invoke->GetIntrinsic(), Intrinsics::kNone);
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001315 HInputsRef inputs = invoke_instruction->GetInputs();
1316 for (size_t index = 0; index != inputs.size(); ++index) {
1317 new_invoke->SetArgumentAt(index, inputs[index]);
1318 }
1319 invoke_instruction->GetBlock()->InsertInstructionBefore(new_invoke, invoke_instruction);
1320 new_invoke->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
1321 if (invoke_instruction->GetType() == DataType::Type::kReference) {
1322 new_invoke->SetReferenceTypeInfo(invoke_instruction->GetReferenceTypeInfo());
1323 }
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001324 return_replacement = new_invoke;
1325 // invoke_instruction is replaced with new_invoke.
1326 should_remove_invoke_instruction = true;
1327 } else {
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01001328 invoke_instruction->SetResolvedMethod(method);
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001329 }
1330 } else if (!TryBuildAndInline(invoke_instruction, method, receiver_type, &return_replacement)) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001331 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +00001332 DCHECK(!method->IsProxyMethod());
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001333 // Turn an invoke-interface into an invoke-virtual. An invoke-virtual is always
1334 // better than an invoke-interface because:
1335 // 1) In the best case, the interface call has one more indirection (to fetch the IMT).
1336 // 2) We will not go to the conflict trampoline with an invoke-virtual.
1337 // TODO: Consider sharpening once it is not dependent on the compiler driver.
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +00001338
1339 if (method->IsDefault() && !method->IsCopied()) {
1340 // Changing to invoke-virtual cannot be done on an original default method
1341 // since it's not in any vtable. Devirtualization by exact type/inline-cache
1342 // always uses a method in the iftable which is never an original default
1343 // method.
1344 // On the other hand, inlining an original default method by CHA is fine.
1345 DCHECK(cha_devirtualize);
1346 return false;
1347 }
1348
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001349 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001350 uint32_t dex_method_index = FindMethodIndexIn(
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001351 method, caller_dex_file, invoke_instruction->GetDexMethodIndex());
Andreas Gampee2abbc62017-09-15 11:59:26 -07001352 if (dex_method_index == dex::kDexNoIndex) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001353 return false;
1354 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01001355 HInvokeVirtual* new_invoke = new (graph_->GetAllocator()) HInvokeVirtual(
1356 graph_->GetAllocator(),
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001357 invoke_instruction->GetNumberOfArguments(),
1358 invoke_instruction->GetType(),
1359 invoke_instruction->GetDexPc(),
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001360 dex_method_index,
1361 method,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001362 method->GetMethodIndex());
1363 HInputsRef inputs = invoke_instruction->GetInputs();
1364 for (size_t index = 0; index != inputs.size(); ++index) {
1365 new_invoke->SetArgumentAt(index, inputs[index]);
1366 }
1367 invoke_instruction->GetBlock()->InsertInstructionBefore(new_invoke, invoke_instruction);
1368 new_invoke->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001369 if (invoke_instruction->GetType() == DataType::Type::kReference) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001370 new_invoke->SetReferenceTypeInfo(invoke_instruction->GetReferenceTypeInfo());
1371 }
1372 return_replacement = new_invoke;
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001373 // invoke_instruction is replaced with new_invoke.
1374 should_remove_invoke_instruction = true;
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001375 } else {
1376 // TODO: Consider sharpening an invoke virtual once it is not dependent on the
1377 // compiler driver.
1378 return false;
1379 }
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001380 } else {
1381 // invoke_instruction is inlined.
1382 should_remove_invoke_instruction = true;
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001383 }
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001384
Mingyao Yang063fc772016-08-02 11:02:54 -07001385 if (cha_devirtualize) {
1386 AddCHAGuard(invoke_instruction, dex_pc, cursor, bb_cursor);
1387 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001388 if (return_replacement != nullptr) {
1389 invoke_instruction->ReplaceWith(return_replacement);
1390 }
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001391 if (should_remove_invoke_instruction) {
1392 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
1393 }
David Brazdil94ab38f2016-06-21 17:48:19 +01001394 FixUpReturnReferenceType(method, return_replacement);
1395 if (do_rtp && ReturnTypeMoreSpecific(invoke_instruction, return_replacement)) {
1396 // Actual return value has a more specific type than the method's declared
1397 // return type. Run RTP again on the outer graph to propagate it.
1398 ReferenceTypePropagation(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001399 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +01001400 outer_compilation_unit_.GetDexCache(),
1401 handles_,
1402 /* is_first_run */ false).Run();
1403 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001404 return true;
1405}
1406
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001407size_t HInliner::CountRecursiveCallsOf(ArtMethod* method) const {
1408 const HInliner* current = this;
1409 size_t count = 0;
1410 do {
1411 if (current->graph_->GetArtMethod() == method) {
1412 ++count;
1413 }
1414 current = current->parent_;
1415 } while (current != nullptr);
1416 return count;
1417}
1418
Vladimir Marko213ee2d2018-06-22 11:56:34 +01001419static inline bool MayInline(const CompilerOptions& compiler_options,
1420 const DexFile& inlined_from,
1421 const DexFile& inlined_into) {
1422 if (kIsTargetBuild) {
1423 return true;
1424 }
1425
1426 // We're not allowed to inline across dex files if we're the no-inline-from dex file.
1427 if (!IsSameDexFile(inlined_from, inlined_into) &&
1428 ContainsElement(compiler_options.GetNoInlineFromDexFile(), &inlined_from)) {
1429 return false;
1430 }
1431
1432 return true;
1433}
1434
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001435bool HInliner::TryBuildAndInline(HInvoke* invoke_instruction,
1436 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001437 ReferenceTypeInfo receiver_type,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001438 HInstruction** return_replacement) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001439 if (method->IsProxyMethod()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001440 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedProxy)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001441 << "Method " << method->PrettyMethod()
1442 << " is not inlined because of unimplemented inline support for proxy methods.";
1443 return false;
1444 }
1445
1446 if (CountRecursiveCallsOf(method) > kMaximumNumberOfRecursiveCalls) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001447 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedRecursiveBudget)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001448 << "Method "
1449 << method->PrettyMethod()
1450 << " is not inlined because it has reached its recursive call budget.";
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001451 return false;
1452 }
1453
Jeff Haodcdc85b2015-12-04 14:06:18 -08001454 // Check whether we're allowed to inline. The outermost compilation unit is the relevant
1455 // dex file here (though the transitivity of an inline chain would allow checking the calller).
Vladimir Marko213ee2d2018-06-22 11:56:34 +01001456 if (!MayInline(codegen_->GetCompilerOptions(),
1457 *method->GetDexFile(),
1458 *outer_compilation_unit_.GetDexFile())) {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001459 if (TryPatternSubstitution(invoke_instruction, method, return_replacement)) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001460 LOG_SUCCESS() << "Successfully replaced pattern of invoke "
1461 << method->PrettyMethod();
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001462 MaybeRecordStat(stats_, MethodCompilationStat::kReplacedInvokeWithSimplePattern);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001463 return true;
1464 }
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001465 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedWont)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001466 << "Won't inline " << method->PrettyMethod() << " in "
1467 << outer_compilation_unit_.GetDexFile()->GetLocation() << " ("
1468 << caller_compilation_unit_.GetDexFile()->GetLocation() << ") from "
1469 << method->GetDexFile()->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001470 return false;
1471 }
1472
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001473 bool same_dex_file = IsSameDexFile(*outer_compilation_unit_.GetDexFile(), *method->GetDexFile());
1474
David Sehr0225f8e2018-01-31 08:52:24 +00001475 CodeItemDataAccessor accessor(method->DexInstructionData());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001476
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001477 if (!accessor.HasCodeItem()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001478 LOG_FAIL_NO_STAT()
1479 << "Method " << method->PrettyMethod() << " is not inlined because it is native";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001480 return false;
1481 }
1482
Vladimir Marko213ee2d2018-06-22 11:56:34 +01001483 size_t inline_max_code_units = codegen_->GetCompilerOptions().GetInlineMaxCodeUnits();
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001484 if (accessor.InsnsSizeInCodeUnits() > inline_max_code_units) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001485 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedCodeItem)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001486 << "Method " << method->PrettyMethod()
1487 << " is not inlined because its code item is too big: "
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001488 << accessor.InsnsSizeInCodeUnits()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001489 << " > "
1490 << inline_max_code_units;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001491 return false;
1492 }
1493
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001494 if (accessor.TriesSize() != 0) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001495 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedTryCatch)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001496 << "Method " << method->PrettyMethod() << " is not inlined because of try block";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001497 return false;
1498 }
1499
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001500 if (!method->IsCompilable()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001501 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedNotVerified)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001502 << "Method " << method->PrettyMethod()
1503 << " has soft failures un-handled by the compiler, so it cannot be inlined";
Aart Bik897df032018-02-07 13:29:11 -08001504 return false;
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001505 }
1506
Aart Bik2c148f02018-02-02 14:30:35 -08001507 if (IsMethodUnverified(compiler_driver_, method)) {
1508 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedNotVerified)
1509 << "Method " << method->PrettyMethod()
1510 << " couldn't be verified, so it cannot be inlined";
1511 return false;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001512 }
1513
Roland Levillain4c0eb422015-04-24 16:43:49 +01001514 if (invoke_instruction->IsInvokeStaticOrDirect() &&
1515 invoke_instruction->AsInvokeStaticOrDirect()->IsStaticWithImplicitClinitCheck()) {
1516 // Case of a static method that cannot be inlined because it implicitly
1517 // requires an initialization check of its declaring class.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001518 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedDexCache)
1519 << "Method " << method->PrettyMethod()
1520 << " is not inlined because it is static and requires a clinit"
1521 << " check that cannot be emitted due to Dex cache limitations";
Roland Levillain4c0eb422015-04-24 16:43:49 +01001522 return false;
1523 }
1524
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001525 if (!TryBuildAndInlineHelper(
1526 invoke_instruction, method, receiver_type, same_dex_file, return_replacement)) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001527 return false;
1528 }
1529
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001530 LOG_SUCCESS() << method->PrettyMethod();
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001531 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedInvoke);
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001532 return true;
1533}
1534
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001535static HInstruction* GetInvokeInputForArgVRegIndex(HInvoke* invoke_instruction,
1536 size_t arg_vreg_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001537 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001538 size_t input_index = 0;
1539 for (size_t i = 0; i < arg_vreg_index; ++i, ++input_index) {
1540 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001541 if (DataType::Is64BitType(invoke_instruction->InputAt(input_index)->GetType())) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001542 ++i;
1543 DCHECK_NE(i, arg_vreg_index);
1544 }
1545 }
1546 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
1547 return invoke_instruction->InputAt(input_index);
1548}
1549
1550// Try to recognize known simple patterns and replace invoke call with appropriate instructions.
1551bool HInliner::TryPatternSubstitution(HInvoke* invoke_instruction,
1552 ArtMethod* resolved_method,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001553 HInstruction** return_replacement) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001554 InlineMethod inline_method;
1555 if (!InlineMethodAnalyser::AnalyseMethodCode(resolved_method, &inline_method)) {
1556 return false;
1557 }
1558
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001559 switch (inline_method.opcode) {
1560 case kInlineOpNop:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001561 DCHECK_EQ(invoke_instruction->GetType(), DataType::Type::kVoid);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001562 *return_replacement = nullptr;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001563 break;
1564 case kInlineOpReturnArg:
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001565 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction,
1566 inline_method.d.return_data.arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001567 break;
1568 case kInlineOpNonWideConst:
1569 if (resolved_method->GetShorty()[0] == 'L') {
1570 DCHECK_EQ(inline_method.d.data, 0u);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001571 *return_replacement = graph_->GetNullConstant();
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001572 } else {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001573 *return_replacement = graph_->GetIntConstant(static_cast<int32_t>(inline_method.d.data));
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001574 }
1575 break;
1576 case kInlineOpIGet: {
1577 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1578 if (data.method_is_static || data.object_arg != 0u) {
1579 // TODO: Needs null check.
1580 return false;
1581 }
1582 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001583 HInstanceFieldGet* iget = CreateInstanceFieldGet(data.field_idx, resolved_method, obj);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001584 DCHECK_EQ(iget->GetFieldOffset().Uint32Value(), data.field_offset);
1585 DCHECK_EQ(iget->IsVolatile() ? 1u : 0u, data.is_volatile);
1586 invoke_instruction->GetBlock()->InsertInstructionBefore(iget, invoke_instruction);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001587 *return_replacement = iget;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001588 break;
1589 }
1590 case kInlineOpIPut: {
1591 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1592 if (data.method_is_static || data.object_arg != 0u) {
1593 // TODO: Needs null check.
1594 return false;
1595 }
1596 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
1597 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, data.src_arg);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001598 HInstanceFieldSet* iput = CreateInstanceFieldSet(data.field_idx, resolved_method, obj, value);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001599 DCHECK_EQ(iput->GetFieldOffset().Uint32Value(), data.field_offset);
1600 DCHECK_EQ(iput->IsVolatile() ? 1u : 0u, data.is_volatile);
1601 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1602 if (data.return_arg_plus1 != 0u) {
1603 size_t return_arg = data.return_arg_plus1 - 1u;
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001604 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction, return_arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001605 }
1606 break;
1607 }
Vladimir Marko354efa62016-02-04 19:46:56 +00001608 case kInlineOpConstructor: {
1609 const InlineConstructorData& data = inline_method.d.constructor_data;
1610 // Get the indexes to arrays for easier processing.
1611 uint16_t iput_field_indexes[] = {
1612 data.iput0_field_index, data.iput1_field_index, data.iput2_field_index
1613 };
1614 uint16_t iput_args[] = { data.iput0_arg, data.iput1_arg, data.iput2_arg };
1615 static_assert(arraysize(iput_args) == arraysize(iput_field_indexes), "Size mismatch");
1616 // Count valid field indexes.
1617 size_t number_of_iputs = 0u;
1618 while (number_of_iputs != arraysize(iput_field_indexes) &&
1619 iput_field_indexes[number_of_iputs] != DexFile::kDexNoIndex16) {
1620 // Check that there are no duplicate valid field indexes.
1621 DCHECK_EQ(0, std::count(iput_field_indexes + number_of_iputs + 1,
1622 iput_field_indexes + arraysize(iput_field_indexes),
1623 iput_field_indexes[number_of_iputs]));
1624 ++number_of_iputs;
1625 }
1626 // Check that there are no valid field indexes in the rest of the array.
1627 DCHECK_EQ(0, std::count_if(iput_field_indexes + number_of_iputs,
1628 iput_field_indexes + arraysize(iput_field_indexes),
1629 [](uint16_t index) { return index != DexFile::kDexNoIndex16; }));
1630
1631 // Create HInstanceFieldSet for each IPUT that stores non-zero data.
Vladimir Marko354efa62016-02-04 19:46:56 +00001632 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, /* this */ 0u);
1633 bool needs_constructor_barrier = false;
1634 for (size_t i = 0; i != number_of_iputs; ++i) {
1635 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, iput_args[i]);
Roland Levillain1a653882016-03-18 18:05:57 +00001636 if (!value->IsConstant() || !value->AsConstant()->IsZeroBitPattern()) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001637 uint16_t field_index = iput_field_indexes[i];
Vladimir Markof44d36c2017-03-14 14:18:46 +00001638 bool is_final;
1639 HInstanceFieldSet* iput =
1640 CreateInstanceFieldSet(field_index, resolved_method, obj, value, &is_final);
Vladimir Marko354efa62016-02-04 19:46:56 +00001641 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1642
1643 // Check whether the field is final. If it is, we need to add a barrier.
Vladimir Markof44d36c2017-03-14 14:18:46 +00001644 if (is_final) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001645 needs_constructor_barrier = true;
1646 }
1647 }
1648 }
1649 if (needs_constructor_barrier) {
Igor Murashkind01745e2017-04-05 16:40:31 -07001650 // See CompilerDriver::RequiresConstructorBarrier for more details.
1651 DCHECK(obj != nullptr) << "only non-static methods can have a constructor fence";
1652
1653 HConstructorFence* constructor_fence =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001654 new (graph_->GetAllocator()) HConstructorFence(obj, kNoDexPc, graph_->GetAllocator());
Igor Murashkind01745e2017-04-05 16:40:31 -07001655 invoke_instruction->GetBlock()->InsertInstructionBefore(constructor_fence,
1656 invoke_instruction);
Vladimir Marko354efa62016-02-04 19:46:56 +00001657 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001658 *return_replacement = nullptr;
Vladimir Marko354efa62016-02-04 19:46:56 +00001659 break;
1660 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001661 default:
1662 LOG(FATAL) << "UNREACHABLE";
1663 UNREACHABLE();
1664 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001665 return true;
1666}
1667
Vladimir Markof44d36c2017-03-14 14:18:46 +00001668HInstanceFieldGet* HInliner::CreateInstanceFieldGet(uint32_t field_index,
1669 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001670 HInstruction* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001671 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001672 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1673 ArtField* resolved_field =
1674 class_linker->LookupResolvedField(field_index, referrer, /* is_static */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001675 DCHECK(resolved_field != nullptr);
Vladimir Markoca6fff82017-10-03 14:49:14 +01001676 HInstanceFieldGet* iget = new (graph_->GetAllocator()) HInstanceFieldGet(
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001677 obj,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001678 resolved_field,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001679 DataType::FromShorty(resolved_field->GetTypeDescriptor()[0]),
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001680 resolved_field->GetOffset(),
1681 resolved_field->IsVolatile(),
1682 field_index,
1683 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001684 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001685 // Read barrier generates a runtime call in slow path and we need a valid
1686 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1687 /* dex_pc */ 0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001688 if (iget->GetType() == DataType::Type::kReference) {
Vladimir Marko456307a2016-04-19 14:12:13 +00001689 // Use the same dex_cache that we used for field lookup as the hint_dex_cache.
Vladimir Markof44d36c2017-03-14 14:18:46 +00001690 Handle<mirror::DexCache> dex_cache = handles_->NewHandle(referrer->GetDexCache());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001691 ReferenceTypePropagation rtp(graph_,
1692 outer_compilation_unit_.GetClassLoader(),
1693 dex_cache,
1694 handles_,
1695 /* is_first_run */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001696 rtp.Visit(iget);
1697 }
1698 return iget;
1699}
1700
Vladimir Markof44d36c2017-03-14 14:18:46 +00001701HInstanceFieldSet* HInliner::CreateInstanceFieldSet(uint32_t field_index,
1702 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001703 HInstruction* obj,
Vladimir Markof44d36c2017-03-14 14:18:46 +00001704 HInstruction* value,
1705 bool* is_final)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001706 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001707 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1708 ArtField* resolved_field =
1709 class_linker->LookupResolvedField(field_index, referrer, /* is_static */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001710 DCHECK(resolved_field != nullptr);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001711 if (is_final != nullptr) {
1712 // This information is needed only for constructors.
1713 DCHECK(referrer->IsConstructor());
1714 *is_final = resolved_field->IsFinal();
1715 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01001716 HInstanceFieldSet* iput = new (graph_->GetAllocator()) HInstanceFieldSet(
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001717 obj,
1718 value,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001719 resolved_field,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001720 DataType::FromShorty(resolved_field->GetTypeDescriptor()[0]),
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001721 resolved_field->GetOffset(),
1722 resolved_field->IsVolatile(),
1723 field_index,
1724 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001725 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001726 // Read barrier generates a runtime call in slow path and we need a valid
1727 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1728 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001729 return iput;
1730}
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001731
Vladimir Markob1d0ee12017-04-20 19:50:32 +01001732template <typename T>
1733static inline Handle<T> NewHandleIfDifferent(T* object,
1734 Handle<T> hint,
1735 VariableSizedHandleScope* handles)
1736 REQUIRES_SHARED(Locks::mutator_lock_) {
1737 return (object != hint.Get()) ? handles->NewHandle(object) : hint;
1738}
1739
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001740bool HInliner::TryBuildAndInlineHelper(HInvoke* invoke_instruction,
1741 ArtMethod* resolved_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001742 ReferenceTypeInfo receiver_type,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001743 bool same_dex_file,
1744 HInstruction** return_replacement) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001745 DCHECK(!(resolved_method->IsStatic() && receiver_type.IsValid()));
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001746 ScopedObjectAccess soa(Thread::Current());
1747 const DexFile::CodeItem* code_item = resolved_method->GetCodeItem();
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001748 const DexFile& callee_dex_file = *resolved_method->GetDexFile();
1749 uint32_t method_index = resolved_method->GetDexMethodIndex();
David Sehr0225f8e2018-01-31 08:52:24 +00001750 CodeItemDebugInfoAccessor code_item_accessor(resolved_method->DexInstructionDebugInfo());
Calin Juravle2e768302015-07-28 14:41:11 +00001751 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Vladimir Markob1d0ee12017-04-20 19:50:32 +01001752 Handle<mirror::DexCache> dex_cache = NewHandleIfDifferent(resolved_method->GetDexCache(),
1753 caller_compilation_unit_.GetDexCache(),
1754 handles_);
1755 Handle<mirror::ClassLoader> class_loader =
1756 NewHandleIfDifferent(resolved_method->GetDeclaringClass()->GetClassLoader(),
1757 caller_compilation_unit_.GetClassLoader(),
1758 handles_);
Nicolas Geoffrayf1aedb12016-07-28 03:49:14 +01001759
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001760 Handle<mirror::Class> compiling_class = handles_->NewHandle(resolved_method->GetDeclaringClass());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001761 DexCompilationUnit dex_compilation_unit(
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001762 class_loader,
Nicolas Geoffray5b82d332016-02-18 14:22:32 +00001763 class_linker,
1764 callee_dex_file,
1765 code_item,
1766 resolved_method->GetDeclaringClass()->GetDexClassDefIndex(),
1767 method_index,
1768 resolved_method->GetAccessFlags(),
1769 /* verified_method */ nullptr,
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001770 dex_cache,
1771 compiling_class);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001772
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001773 InvokeType invoke_type = invoke_instruction->GetInvokeType();
Nicolas Geoffray35071052015-06-09 15:43:38 +01001774 if (invoke_type == kInterface) {
1775 // We have statically resolved the dispatch. To please the class linker
1776 // at runtime, we change this call as if it was a virtual call.
1777 invoke_type = kVirtual;
1778 }
David Brazdil3f523062016-02-29 16:53:33 +00001779
1780 const int32_t caller_instruction_counter = graph_->GetCurrentInstructionId();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001781 HGraph* callee_graph = new (graph_->GetAllocator()) HGraph(
1782 graph_->GetAllocator(),
1783 graph_->GetArenaStack(),
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001784 callee_dex_file,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001785 method_index,
Vladimir Markoa0431112018-06-25 09:32:54 +01001786 codegen_->GetCompilerOptions().GetInstructionSet(),
Nicolas Geoffray35071052015-06-09 15:43:38 +01001787 invoke_type,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001788 graph_->IsDebuggable(),
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001789 /* osr */ false,
David Brazdil3f523062016-02-29 16:53:33 +00001790 caller_instruction_counter);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001791 callee_graph->SetArtMethod(resolved_method);
David Brazdil5e8b1372015-01-23 14:39:08 +00001792
Vladimir Marko438709f2017-02-23 18:56:13 +00001793 // When they are needed, allocate `inline_stats_` on the Arena instead
Roland Levillaina8013fd2016-04-04 15:34:31 +01001794 // of on the stack, as Clang might produce a stack frame too large
1795 // for this function, that would not fit the requirements of the
1796 // `-Wframe-larger-than` option.
Vladimir Marko438709f2017-02-23 18:56:13 +00001797 if (stats_ != nullptr) {
1798 // Reuse one object for all inline attempts from this caller to keep Arena memory usage low.
1799 if (inline_stats_ == nullptr) {
Vladimir Markoca6fff82017-10-03 14:49:14 +01001800 void* storage = graph_->GetAllocator()->Alloc<OptimizingCompilerStats>(kArenaAllocMisc);
Vladimir Marko438709f2017-02-23 18:56:13 +00001801 inline_stats_ = new (storage) OptimizingCompilerStats;
1802 } else {
1803 inline_stats_->Reset();
1804 }
1805 }
David Brazdil5e8b1372015-01-23 14:39:08 +00001806 HGraphBuilder builder(callee_graph,
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001807 code_item_accessor,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001808 &dex_compilation_unit,
1809 &outer_compilation_unit_,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001810 compiler_driver_,
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00001811 codegen_,
Vladimir Marko438709f2017-02-23 18:56:13 +00001812 inline_stats_,
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001813 resolved_method->GetQuickenedInfo(),
David Brazdildee58d62016-04-07 09:54:26 +00001814 handles_);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001815
David Brazdildee58d62016-04-07 09:54:26 +00001816 if (builder.BuildGraph() != kAnalysisSuccess) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001817 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedCannotBuild)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001818 << "Method " << callee_dex_file.PrettyMethod(method_index)
1819 << " could not be built, so cannot be inlined";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001820 return false;
1821 }
1822
Vladimir Markoa0431112018-06-25 09:32:54 +01001823 if (!RegisterAllocator::CanAllocateRegistersFor(
1824 *callee_graph, codegen_->GetCompilerOptions().GetInstructionSet())) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001825 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedRegisterAllocator)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001826 << "Method " << callee_dex_file.PrettyMethod(method_index)
1827 << " cannot be inlined because of the register allocator";
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001828 return false;
1829 }
1830
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001831 size_t parameter_index = 0;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001832 bool run_rtp = false;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001833 for (HInstructionIterator instructions(callee_graph->GetEntryBlock()->GetInstructions());
1834 !instructions.Done();
1835 instructions.Advance()) {
1836 HInstruction* current = instructions.Current();
1837 if (current->IsParameterValue()) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001838 HInstruction* argument = invoke_instruction->InputAt(parameter_index);
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001839 if (argument->IsNullConstant()) {
1840 current->ReplaceWith(callee_graph->GetNullConstant());
1841 } else if (argument->IsIntConstant()) {
1842 current->ReplaceWith(callee_graph->GetIntConstant(argument->AsIntConstant()->GetValue()));
1843 } else if (argument->IsLongConstant()) {
1844 current->ReplaceWith(callee_graph->GetLongConstant(argument->AsLongConstant()->GetValue()));
1845 } else if (argument->IsFloatConstant()) {
1846 current->ReplaceWith(
1847 callee_graph->GetFloatConstant(argument->AsFloatConstant()->GetValue()));
1848 } else if (argument->IsDoubleConstant()) {
1849 current->ReplaceWith(
1850 callee_graph->GetDoubleConstant(argument->AsDoubleConstant()->GetValue()));
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001851 } else if (argument->GetType() == DataType::Type::kReference) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001852 if (!resolved_method->IsStatic() && parameter_index == 0 && receiver_type.IsValid()) {
1853 run_rtp = true;
1854 current->SetReferenceTypeInfo(receiver_type);
1855 } else {
1856 current->SetReferenceTypeInfo(argument->GetReferenceTypeInfo());
1857 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001858 current->AsParameterValue()->SetCanBeNull(argument->CanBeNull());
1859 }
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001860 ++parameter_index;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001861 }
1862 }
1863
David Brazdil94ab38f2016-06-21 17:48:19 +01001864 // We have replaced formal arguments with actual arguments. If actual types
1865 // are more specific than the declared ones, run RTP again on the inner graph.
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001866 if (run_rtp || ArgumentTypesMoreSpecific(invoke_instruction, resolved_method)) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001867 ReferenceTypePropagation(callee_graph,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001868 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +01001869 dex_compilation_unit.GetDexCache(),
1870 handles_,
1871 /* is_first_run */ false).Run();
1872 }
1873
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001874 RunOptimizations(callee_graph, code_item, dex_compilation_unit);
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +00001875
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001876 HBasicBlock* exit_block = callee_graph->GetExitBlock();
1877 if (exit_block == nullptr) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001878 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedInfiniteLoop)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001879 << "Method " << callee_dex_file.PrettyMethod(method_index)
1880 << " could not be inlined because it has an infinite loop";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001881 return false;
1882 }
1883
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001884 bool has_one_return = false;
Vladimir Marko60584552015-09-03 13:35:12 +00001885 for (HBasicBlock* predecessor : exit_block->GetPredecessors()) {
1886 if (predecessor->GetLastInstruction()->IsThrow()) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001887 if (invoke_instruction->GetBlock()->IsTryBlock()) {
1888 // TODO(ngeoffray): Support adding HTryBoundary in Hgraph::InlineInto.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001889 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedTryCatch)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001890 << "Method " << callee_dex_file.PrettyMethod(method_index)
1891 << " could not be inlined because one branch always throws and"
1892 << " caller is in a try/catch block";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001893 return false;
1894 } else if (graph_->GetExitBlock() == nullptr) {
1895 // TODO(ngeoffray): Support adding HExit in the caller graph.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001896 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedInfiniteLoop)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001897 << "Method " << callee_dex_file.PrettyMethod(method_index)
1898 << " could not be inlined because one branch always throws and"
1899 << " caller does not have an exit block";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001900 return false;
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00001901 } else if (graph_->HasIrreducibleLoops()) {
1902 // TODO(ngeoffray): Support re-computing loop information to graphs with
1903 // irreducible loops?
1904 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1905 << " could not be inlined because one branch always throws and"
1906 << " caller has irreducible loops";
1907 return false;
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001908 }
1909 } else {
1910 has_one_return = true;
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001911 }
1912 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001913
1914 if (!has_one_return) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001915 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedAlwaysThrows)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001916 << "Method " << callee_dex_file.PrettyMethod(method_index)
1917 << " could not be inlined because it always throws";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001918 return false;
1919 }
1920
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001921 size_t number_of_instructions = 0;
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001922 // Skip the entry block, it does not contain instructions that prevent inlining.
1923 for (HBasicBlock* block : callee_graph->GetReversePostOrderSkipEntryBlock()) {
David Sehrc757dec2016-11-04 15:48:34 -07001924 if (block->IsLoopHeader()) {
1925 if (block->GetLoopInformation()->IsIrreducible()) {
1926 // Don't inline methods with irreducible loops, they could prevent some
1927 // optimizations to run.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001928 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedIrreducibleLoop)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001929 << "Method " << callee_dex_file.PrettyMethod(method_index)
1930 << " could not be inlined because it contains an irreducible loop";
David Sehrc757dec2016-11-04 15:48:34 -07001931 return false;
1932 }
1933 if (!block->GetLoopInformation()->HasExitEdge()) {
1934 // Don't inline methods with loops without exit, since they cause the
1935 // loop information to be computed incorrectly when updating after
1936 // inlining.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001937 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedLoopWithoutExit)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001938 << "Method " << callee_dex_file.PrettyMethod(method_index)
1939 << " could not be inlined because it contains a loop with no exit";
David Sehrc757dec2016-11-04 15:48:34 -07001940 return false;
1941 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001942 }
1943
1944 for (HInstructionIterator instr_it(block->GetInstructions());
1945 !instr_it.Done();
1946 instr_it.Advance()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001947 if (++number_of_instructions >= inlining_budget_) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001948 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedInstructionBudget)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001949 << "Method " << callee_dex_file.PrettyMethod(method_index)
1950 << " is not inlined because the outer method has reached"
1951 << " its instruction budget limit.";
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001952 return false;
1953 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001954 HInstruction* current = instr_it.Current();
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001955 if (current->NeedsEnvironment() &&
1956 (total_number_of_dex_registers_ >= kMaximumNumberOfCumulatedDexRegisters)) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001957 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedEnvironmentBudget)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001958 << "Method " << callee_dex_file.PrettyMethod(method_index)
1959 << " is not inlined because its caller has reached"
1960 << " its environment budget limit.";
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001961 return false;
1962 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001963
Nicolas Geoffrayfbdfa6d2017-02-03 10:43:13 +00001964 if (current->NeedsEnvironment() &&
1965 !CanEncodeInlinedMethodInStackMap(*caller_compilation_unit_.GetDexFile(),
1966 resolved_method)) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001967 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedStackMaps)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001968 << "Method " << callee_dex_file.PrettyMethod(method_index)
1969 << " could not be inlined because " << current->DebugName()
1970 << " needs an environment, is in a different dex file"
1971 << ", and cannot be encoded in the stack maps.";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001972 return false;
1973 }
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001974
Vladimir Markodc151b22015-10-15 18:02:30 +01001975 if (!same_dex_file && current->NeedsDexCacheOfDeclaringClass()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001976 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedDexCache)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001977 << "Method " << callee_dex_file.PrettyMethod(method_index)
1978 << " could not be inlined because " << current->DebugName()
1979 << " it is in a different dex file and requires access to the dex cache";
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001980 return false;
1981 }
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001982
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001983 if (current->IsUnresolvedStaticFieldGet() ||
1984 current->IsUnresolvedInstanceFieldGet() ||
1985 current->IsUnresolvedStaticFieldSet() ||
1986 current->IsUnresolvedInstanceFieldSet()) {
1987 // Entrypoint for unresolved fields does not handle inlined frames.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001988 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedUnresolvedEntrypoint)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001989 << "Method " << callee_dex_file.PrettyMethod(method_index)
1990 << " could not be inlined because it is using an unresolved"
1991 << " entrypoint";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001992 return false;
1993 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001994 }
1995 }
David Brazdil3f523062016-02-29 16:53:33 +00001996 DCHECK_EQ(caller_instruction_counter, graph_->GetCurrentInstructionId())
1997 << "No instructions can be added to the outer graph while inner graph is being built";
1998
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001999 // Inline the callee graph inside the caller graph.
David Brazdil3f523062016-02-29 16:53:33 +00002000 const int32_t callee_instruction_counter = callee_graph->GetCurrentInstructionId();
2001 graph_->SetCurrentInstructionId(callee_instruction_counter);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00002002 *return_replacement = callee_graph->InlineInto(graph_, invoke_instruction);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002003 // Update our budget for other inlining attempts in `caller_graph`.
2004 total_number_of_instructions_ += number_of_instructions;
2005 UpdateInliningBudget();
David Brazdil3f523062016-02-29 16:53:33 +00002006
2007 DCHECK_EQ(callee_instruction_counter, callee_graph->GetCurrentInstructionId())
2008 << "No instructions can be added to the inner graph during inlining into the outer graph";
2009
Vladimir Marko438709f2017-02-23 18:56:13 +00002010 if (stats_ != nullptr) {
2011 DCHECK(inline_stats_ != nullptr);
2012 inline_stats_->AddTo(stats_);
2013 }
2014
Vladimir Markobe10e8e2016-01-22 12:09:44 +00002015 return true;
2016}
Calin Juravle2e768302015-07-28 14:41:11 +00002017
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002018void HInliner::RunOptimizations(HGraph* callee_graph,
2019 const DexFile::CodeItem* code_item,
2020 const DexCompilationUnit& dex_compilation_unit) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01002021 // Note: if the outermost_graph_ is being compiled OSR, we should not run any
2022 // optimization that could lead to a HDeoptimize. The following optimizations do not.
Vladimir Marko438709f2017-02-23 18:56:13 +00002023 HDeadCodeElimination dce(callee_graph, inline_stats_, "dead_code_elimination$inliner");
Andreas Gampeca620d72016-11-08 08:09:33 -08002024 HConstantFolding fold(callee_graph, "constant_folding$inliner");
Vladimir Markobb089b62018-06-28 17:30:16 +01002025 InstructionSimplifier simplify(callee_graph, codegen_, inline_stats_);
Roland Levillaina3aef2e2016-04-06 17:45:58 +01002026
2027 HOptimization* optimizations[] = {
Roland Levillaina3aef2e2016-04-06 17:45:58 +01002028 &simplify,
2029 &fold,
2030 &dce,
2031 };
2032
2033 for (size_t i = 0; i < arraysize(optimizations); ++i) {
2034 HOptimization* optimization = optimizations[i];
2035 optimization->Run();
2036 }
2037
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002038 // Bail early for pathological cases on the environment (for example recursive calls,
2039 // or too large environment).
2040 if (total_number_of_dex_registers_ >= kMaximumNumberOfCumulatedDexRegisters) {
2041 LOG_NOTE() << "Calls in " << callee_graph->GetArtMethod()->PrettyMethod()
2042 << " will not be inlined because the outer method has reached"
2043 << " its environment budget limit.";
2044 return;
Roland Levillaina3aef2e2016-04-06 17:45:58 +01002045 }
2046
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002047 // Bail early if we know we already are over the limit.
2048 size_t number_of_instructions = CountNumberOfInstructions(callee_graph);
2049 if (number_of_instructions > inlining_budget_) {
2050 LOG_NOTE() << "Calls in " << callee_graph->GetArtMethod()->PrettyMethod()
2051 << " will not be inlined because the outer method has reached"
2052 << " its instruction budget limit. " << number_of_instructions;
2053 return;
2054 }
2055
Mathieu Chartier698ebbc2018-01-05 11:00:42 -08002056 CodeItemDataAccessor accessor(callee_graph->GetDexFile(), code_item);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002057 HInliner inliner(callee_graph,
2058 outermost_graph_,
2059 codegen_,
2060 outer_compilation_unit_,
2061 dex_compilation_unit,
2062 compiler_driver_,
2063 handles_,
2064 inline_stats_,
Mathieu Chartier808c7a52017-12-15 11:19:33 -08002065 total_number_of_dex_registers_ + accessor.RegistersSize(),
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002066 total_number_of_instructions_ + number_of_instructions,
2067 this,
2068 depth_ + 1);
2069 inliner.Run();
Roland Levillaina3aef2e2016-04-06 17:45:58 +01002070}
2071
David Brazdil94ab38f2016-06-21 17:48:19 +01002072static bool IsReferenceTypeRefinement(ReferenceTypeInfo declared_rti,
2073 bool declared_can_be_null,
2074 HInstruction* actual_obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002075 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdil94ab38f2016-06-21 17:48:19 +01002076 if (declared_can_be_null && !actual_obj->CanBeNull()) {
2077 return true;
2078 }
2079
2080 ReferenceTypeInfo actual_rti = actual_obj->GetReferenceTypeInfo();
2081 return (actual_rti.IsExact() && !declared_rti.IsExact()) ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00002082 declared_rti.IsStrictSupertypeOf(actual_rti);
David Brazdil94ab38f2016-06-21 17:48:19 +01002083}
2084
Vladimir Markob45528c2017-07-27 14:14:28 +01002085ReferenceTypeInfo HInliner::GetClassRTI(ObjPtr<mirror::Class> klass) {
David Brazdil94ab38f2016-06-21 17:48:19 +01002086 return ReferenceTypePropagation::IsAdmissible(klass)
2087 ? ReferenceTypeInfo::Create(handles_->NewHandle(klass))
2088 : graph_->GetInexactObjectRti();
2089}
2090
2091bool HInliner::ArgumentTypesMoreSpecific(HInvoke* invoke_instruction, ArtMethod* resolved_method) {
2092 // If this is an instance call, test whether the type of the `this` argument
2093 // is more specific than the class which declares the method.
2094 if (!resolved_method->IsStatic()) {
2095 if (IsReferenceTypeRefinement(GetClassRTI(resolved_method->GetDeclaringClass()),
2096 /* declared_can_be_null */ false,
2097 invoke_instruction->InputAt(0u))) {
2098 return true;
2099 }
2100 }
2101
David Brazdil94ab38f2016-06-21 17:48:19 +01002102 // Iterate over the list of parameter types and test whether any of the
2103 // actual inputs has a more specific reference type than the type declared in
2104 // the signature.
2105 const DexFile::TypeList* param_list = resolved_method->GetParameterTypeList();
2106 for (size_t param_idx = 0,
2107 input_idx = resolved_method->IsStatic() ? 0 : 1,
2108 e = (param_list == nullptr ? 0 : param_list->Size());
2109 param_idx < e;
2110 ++param_idx, ++input_idx) {
2111 HInstruction* input = invoke_instruction->InputAt(input_idx);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002112 if (input->GetType() == DataType::Type::kReference) {
Vladimir Markob45528c2017-07-27 14:14:28 +01002113 ObjPtr<mirror::Class> param_cls = resolved_method->LookupResolvedClassFromTypeIndex(
2114 param_list->GetTypeItem(param_idx).type_idx_);
David Brazdil94ab38f2016-06-21 17:48:19 +01002115 if (IsReferenceTypeRefinement(GetClassRTI(param_cls),
2116 /* declared_can_be_null */ true,
2117 input)) {
2118 return true;
2119 }
2120 }
2121 }
2122
2123 return false;
2124}
2125
2126bool HInliner::ReturnTypeMoreSpecific(HInvoke* invoke_instruction,
2127 HInstruction* return_replacement) {
Alex Light68289a52015-12-15 17:30:30 -08002128 // Check the integrity of reference types and run another type propagation if needed.
David Brazdil4833f5a2015-12-16 10:37:39 +00002129 if (return_replacement != nullptr) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002130 if (return_replacement->GetType() == DataType::Type::kReference) {
David Brazdil94ab38f2016-06-21 17:48:19 +01002131 // Test if the return type is a refinement of the declared return type.
2132 if (IsReferenceTypeRefinement(invoke_instruction->GetReferenceTypeInfo(),
2133 /* declared_can_be_null */ true,
2134 return_replacement)) {
2135 return true;
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00002136 } else if (return_replacement->IsInstanceFieldGet()) {
2137 HInstanceFieldGet* field_get = return_replacement->AsInstanceFieldGet();
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00002138 if (field_get->GetFieldInfo().GetField() ==
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002139 GetClassRoot<mirror::Object>()->GetInstanceField(0)) {
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00002140 return true;
2141 }
David Brazdil94ab38f2016-06-21 17:48:19 +01002142 }
2143 } else if (return_replacement->IsInstanceOf()) {
2144 // Inlining InstanceOf into an If may put a tighter bound on reference types.
2145 return true;
2146 }
2147 }
2148
2149 return false;
2150}
2151
2152void HInliner::FixUpReturnReferenceType(ArtMethod* resolved_method,
2153 HInstruction* return_replacement) {
2154 if (return_replacement != nullptr) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002155 if (return_replacement->GetType() == DataType::Type::kReference) {
David Brazdil4833f5a2015-12-16 10:37:39 +00002156 if (!return_replacement->GetReferenceTypeInfo().IsValid()) {
2157 // Make sure that we have a valid type for the return. We may get an invalid one when
2158 // we inline invokes with multiple branches and create a Phi for the result.
2159 // TODO: we could be more precise by merging the phi inputs but that requires
2160 // some functionality from the reference type propagation.
2161 DCHECK(return_replacement->IsPhi());
Vladimir Markob45528c2017-07-27 14:14:28 +01002162 ObjPtr<mirror::Class> cls = resolved_method->LookupResolvedReturnType();
David Brazdil94ab38f2016-06-21 17:48:19 +01002163 return_replacement->SetReferenceTypeInfo(GetClassRTI(cls));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01002164 }
Calin Juravlecdfed3d2015-10-26 14:05:01 +00002165 }
Calin Juravle2e768302015-07-28 14:41:11 +00002166 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002167}
2168
2169} // namespace art