blob: 452be6feaef758ef51743b0febe18d23505d3544 [file] [log] [blame]
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "inliner.h"
18
Mathieu Chartiere401d142015-04-22 13:56:20 -070019#include "art_method-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070020#include "base/enums.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000021#include "builder.h"
22#include "class_linker.h"
23#include "constant_folding.h"
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010024#include "data_type-inl.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000025#include "dead_code_elimination.h"
Andreas Gampeb95c74b2017-04-20 19:43:21 -070026#include "dex/inline_method_analyser.h"
Vladimir Markobe10e8e2016-01-22 12:09:44 +000027#include "dex/verification_results.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070028#include "dex/verified_method.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000029#include "driver/compiler_driver-inl.h"
Calin Juravleec748352015-07-29 13:52:12 +010030#include "driver/compiler_options.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000031#include "driver/dex_compilation_unit.h"
32#include "instruction_simplifier.h"
Scott Wakelingd60a1af2015-07-22 14:32:44 +010033#include "intrinsics.h"
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +000034#include "jit/jit.h"
35#include "jit/jit_code_cache.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000036#include "mirror/class_loader.h"
37#include "mirror/dex_cache.h"
38#include "nodes.h"
Nicolas Geoffray335005e2015-06-25 10:01:47 +010039#include "optimizing_compiler.h"
Nicolas Geoffray454a4812015-06-09 10:37:32 +010040#include "reference_type_propagation.h"
Matthew Gharritye9288852016-07-14 14:08:16 -070041#include "register_allocator_linear_scan.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070042#include "scoped_thread_state_change-inl.h"
Vladimir Markodc151b22015-10-15 18:02:30 +010043#include "sharpening.h"
David Brazdil4833f5a2015-12-16 10:37:39 +000044#include "ssa_builder.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000045#include "ssa_phi_elimination.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000046#include "thread.h"
47
48namespace art {
49
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000050// Instruction limit to control memory.
51static constexpr size_t kMaximumNumberOfTotalInstructions = 1024;
52
53// Maximum number of instructions for considering a method small,
54// which we will always try to inline if the other non-instruction limits
55// are not reached.
56static constexpr size_t kMaximumNumberOfInstructionsForSmallMethod = 3;
Nicolas Geoffray5949fa02015-12-18 10:57:10 +000057
58// Limit the number of dex registers that we accumulate while inlining
59// to avoid creating large amount of nested environments.
Nicolas Geoffrayf81621e2017-06-07 13:18:03 +010060static constexpr size_t kMaximumNumberOfCumulatedDexRegisters = 32;
Nicolas Geoffray5949fa02015-12-18 10:57:10 +000061
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000062// Limit recursive call inlining, which do not benefit from too
63// much inlining compared to code locality.
64static constexpr size_t kMaximumNumberOfRecursiveCalls = 4;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -070065
Calin Juravlee2492d42017-03-20 11:42:13 -070066// Controls the use of inline caches in AOT mode.
Calin Juravle8af70892017-03-28 15:31:44 -070067static constexpr bool kUseAOTInlineCaches = true;
Calin Juravlee2492d42017-03-20 11:42:13 -070068
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000069// We check for line numbers to make sure the DepthString implementation
70// aligns the output nicely.
71#define LOG_INTERNAL(msg) \
72 static_assert(__LINE__ > 10, "Unhandled line number"); \
73 static_assert(__LINE__ < 10000, "Unhandled line number"); \
74 VLOG(compiler) << DepthString(__LINE__) << msg
75
76#define LOG_TRY() LOG_INTERNAL("Try inlinining call: ")
77#define LOG_NOTE() LOG_INTERNAL("Note: ")
78#define LOG_SUCCESS() LOG_INTERNAL("Success: ")
Igor Murashkin1e065a52017-08-09 13:20:34 -070079#define LOG_FAIL(stats_ptr, stat) MaybeRecordStat(stats_ptr, stat); LOG_INTERNAL("Fail: ")
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000080#define LOG_FAIL_NO_STAT() LOG_INTERNAL("Fail: ")
81
82std::string HInliner::DepthString(int line) const {
83 std::string value;
84 // Indent according to the inlining depth.
85 size_t count = depth_;
86 // Line numbers get printed in the log, so add a space if the log's line is less
87 // than 1000, and two if less than 100. 10 cannot be reached as it's the copyright.
88 if (!kIsTargetBuild) {
89 if (line < 100) {
90 value += " ";
91 }
92 if (line < 1000) {
93 value += " ";
94 }
95 // Safeguard if this file reaches more than 10000 lines.
96 DCHECK_LT(line, 10000);
97 }
98 for (size_t i = 0; i < count; ++i) {
99 value += " ";
100 }
101 return value;
102}
103
104static size_t CountNumberOfInstructions(HGraph* graph) {
105 size_t number_of_instructions = 0;
106 for (HBasicBlock* block : graph->GetReversePostOrderSkipEntryBlock()) {
107 for (HInstructionIterator instr_it(block->GetInstructions());
108 !instr_it.Done();
109 instr_it.Advance()) {
110 ++number_of_instructions;
111 }
112 }
113 return number_of_instructions;
114}
115
116void HInliner::UpdateInliningBudget() {
117 if (total_number_of_instructions_ >= kMaximumNumberOfTotalInstructions) {
118 // Always try to inline small methods.
119 inlining_budget_ = kMaximumNumberOfInstructionsForSmallMethod;
120 } else {
121 inlining_budget_ = std::max(
122 kMaximumNumberOfInstructionsForSmallMethod,
123 kMaximumNumberOfTotalInstructions - total_number_of_instructions_);
124 }
125}
126
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000127void HInliner::Run() {
Nicolas Geoffraye50b8d22015-03-13 08:57:42 +0000128 if (graph_->IsDebuggable()) {
129 // For simplicity, we currently never inline when the graph is debuggable. This avoids
130 // doing some logic in the runtime to discover if a method could have been inlined.
131 return;
132 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000133
134 // Initialize the number of instructions for the method being compiled. Recursive calls
135 // to HInliner::Run have already updated the instruction count.
136 if (outermost_graph_ == graph_) {
137 total_number_of_instructions_ = CountNumberOfInstructions(graph_);
138 }
139
140 UpdateInliningBudget();
141 DCHECK_NE(total_number_of_instructions_, 0u);
142 DCHECK_NE(inlining_budget_, 0u);
143
Roland Levillain6c3af162017-04-27 11:18:56 +0100144 // If we're compiling with a core image (which is only used for
145 // test purposes), honor inlining directives in method names:
146 // - if a method's name contains the substring "$inline$", ensure
147 // that this method is actually inlined;
148 // - if a method's name contains the substring "$noinline$", do not
149 // inline that method.
Nicolas Geoffray08490b82017-07-18 12:58:10 +0100150 // We limit this to AOT compilation, as the JIT may or may not inline
151 // depending on the state of classes at runtime.
152 const bool honor_inlining_directives =
153 IsCompilingWithCoreImage() && Runtime::Current()->IsAotCompiler();
Roland Levillain6c3af162017-04-27 11:18:56 +0100154
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +0000155 // Keep a copy of all blocks when starting the visit.
156 ArenaVector<HBasicBlock*> blocks = graph_->GetReversePostOrder();
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100157 DCHECK(!blocks.empty());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +0000158 // Because we are changing the graph when inlining,
159 // we just iterate over the blocks of the outer method.
160 // This avoids doing the inlining work again on the inlined blocks.
161 for (HBasicBlock* block : blocks) {
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000162 for (HInstruction* instruction = block->GetFirstInstruction(); instruction != nullptr;) {
163 HInstruction* next = instruction->GetNext();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100164 HInvoke* call = instruction->AsInvoke();
Razvan A Lupusoru3e90a962015-03-27 13:44:44 -0700165 // As long as the call is not intrinsified, it is worth trying to inline.
166 if (call != nullptr && call->GetIntrinsic() == Intrinsics::kNone) {
Roland Levillain6c3af162017-04-27 11:18:56 +0100167 if (honor_inlining_directives) {
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000168 // Debugging case: directives in method names control or assert on inlining.
169 std::string callee_name = outer_compilation_unit_.GetDexFile()->PrettyMethod(
170 call->GetDexMethodIndex(), /* with_signature */ false);
171 // Tests prevent inlining by having $noinline$ in their method names.
172 if (callee_name.find("$noinline$") == std::string::npos) {
173 if (!TryInline(call)) {
Nicolas Geoffray1949baf2017-10-17 12:14:53 +0000174 bool should_have_inlined = (callee_name.find("$inline$") != std::string::npos);
175 CHECK(!should_have_inlined) << "Could not inline " << callee_name;
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000176 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000177 }
Guillaume "Vermeille" Sancheze918d382015-06-03 15:32:41 +0100178 } else {
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000179 // Normal case: try to inline.
180 TryInline(call);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000181 }
182 }
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000183 instruction = next;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000184 }
185 }
186}
187
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100188static bool IsMethodOrDeclaringClassFinal(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700189 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100190 return method->IsFinal() || method->GetDeclaringClass()->IsFinal();
191}
192
193/**
194 * Given the `resolved_method` looked up in the dex cache, try to find
195 * the actual runtime target of an interface or virtual call.
196 * Return nullptr if the runtime target cannot be proven.
197 */
198static ArtMethod* FindVirtualOrInterfaceTarget(HInvoke* invoke, ArtMethod* resolved_method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700199 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100200 if (IsMethodOrDeclaringClassFinal(resolved_method)) {
201 // No need to lookup further, the resolved method will be the target.
202 return resolved_method;
203 }
204
205 HInstruction* receiver = invoke->InputAt(0);
206 if (receiver->IsNullCheck()) {
207 // Due to multiple levels of inlining within the same pass, it might be that
208 // null check does not have the reference type of the actual receiver.
209 receiver = receiver->InputAt(0);
210 }
211 ReferenceTypeInfo info = receiver->GetReferenceTypeInfo();
Calin Juravle2e768302015-07-28 14:41:11 +0000212 DCHECK(info.IsValid()) << "Invalid RTI for " << receiver->DebugName();
213 if (!info.IsExact()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100214 // We currently only support inlining with known receivers.
215 // TODO: Remove this check, we should be able to inline final methods
216 // on unknown receivers.
217 return nullptr;
218 } else if (info.GetTypeHandle()->IsInterface()) {
219 // Statically knowing that the receiver has an interface type cannot
220 // help us find what is the target method.
221 return nullptr;
222 } else if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(info.GetTypeHandle().Get())) {
223 // The method that we're trying to call is not in the receiver's class or super classes.
224 return nullptr;
Nicolas Geoffrayab5327d2016-03-18 11:36:20 +0000225 } else if (info.GetTypeHandle()->IsErroneous()) {
226 // If the type is erroneous, do not go further, as we are going to query the vtable or
227 // imt table, that we can only safely do on non-erroneous classes.
228 return nullptr;
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100229 }
230
231 ClassLinker* cl = Runtime::Current()->GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700232 PointerSize pointer_size = cl->GetImagePointerSize();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100233 if (invoke->IsInvokeInterface()) {
234 resolved_method = info.GetTypeHandle()->FindVirtualMethodForInterface(
235 resolved_method, pointer_size);
236 } else {
237 DCHECK(invoke->IsInvokeVirtual());
238 resolved_method = info.GetTypeHandle()->FindVirtualMethodForVirtual(
239 resolved_method, pointer_size);
240 }
241
242 if (resolved_method == nullptr) {
243 // The information we had on the receiver was not enough to find
244 // the target method. Since we check above the exact type of the receiver,
245 // the only reason this can happen is an IncompatibleClassChangeError.
246 return nullptr;
Alex Light9139e002015-10-09 15:59:48 -0700247 } else if (!resolved_method->IsInvokable()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100248 // The information we had on the receiver was not enough to find
249 // the target method. Since we check above the exact type of the receiver,
250 // the only reason this can happen is an IncompatibleClassChangeError.
251 return nullptr;
252 } else if (IsMethodOrDeclaringClassFinal(resolved_method)) {
253 // A final method has to be the target method.
254 return resolved_method;
255 } else if (info.IsExact()) {
256 // If we found a method and the receiver's concrete type is statically
257 // known, we know for sure the target.
258 return resolved_method;
259 } else {
260 // Even if we did find a method, the receiver type was not enough to
261 // statically find the runtime target.
262 return nullptr;
263 }
264}
265
266static uint32_t FindMethodIndexIn(ArtMethod* method,
267 const DexFile& dex_file,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000268 uint32_t name_and_signature_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700269 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100270 if (IsSameDexFile(*method->GetDexFile(), dex_file)) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100271 return method->GetDexMethodIndex();
272 } else {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000273 return method->FindDexMethodIndexInOtherDexFile(dex_file, name_and_signature_index);
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100274 }
275}
276
Andreas Gampea5b09a62016-11-17 15:21:22 -0800277static dex::TypeIndex FindClassIndexIn(mirror::Class* cls,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000278 const DexCompilationUnit& compilation_unit)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700279 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000280 const DexFile& dex_file = *compilation_unit.GetDexFile();
Andreas Gampea5b09a62016-11-17 15:21:22 -0800281 dex::TypeIndex index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100282 if (cls->GetDexCache() == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700283 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000284 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800285 } else if (!cls->GetDexTypeIndex().IsValid()) {
David Sehr709b0702016-10-13 09:12:37 -0700286 DCHECK(cls->IsProxyClass()) << cls->PrettyClass();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100287 // TODO: deal with proxy classes.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100288 } else if (IsSameDexFile(cls->GetDexFile(), dex_file)) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000289 DCHECK_EQ(cls->GetDexCache(), compilation_unit.GetDexCache().Get());
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000290 index = cls->GetDexTypeIndex();
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100291 } else {
292 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000293 // We cannot guarantee the entry will resolve to the same class,
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100294 // as there may be different class loaders. So only return the index if it's
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000295 // the right class already resolved with the class loader.
296 if (index.IsValid()) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +0000297 ObjPtr<mirror::Class> resolved = compilation_unit.GetClassLinker()->LookupResolvedType(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000298 index, compilation_unit.GetDexCache().Get(), compilation_unit.GetClassLoader().Get());
299 if (resolved != cls) {
300 index = dex::TypeIndex::Invalid();
301 }
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100302 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100303 }
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000304
305 return index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100306}
307
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000308class ScopedProfilingInfoInlineUse {
309 public:
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000310 explicit ScopedProfilingInfoInlineUse(ArtMethod* method, Thread* self)
311 : method_(method),
312 self_(self),
313 // Fetch the profiling info ahead of using it. If it's null when fetching,
314 // we should not call JitCodeCache::DoneInlining.
315 profiling_info_(
316 Runtime::Current()->GetJit()->GetCodeCache()->NotifyCompilerUse(method, self)) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000317 }
318
319 ~ScopedProfilingInfoInlineUse() {
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000320 if (profiling_info_ != nullptr) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700321 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000322 DCHECK_EQ(profiling_info_, method_->GetProfilingInfo(pointer_size));
323 Runtime::Current()->GetJit()->GetCodeCache()->DoneCompilerUse(method_, self_);
324 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000325 }
326
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000327 ProfilingInfo* GetProfilingInfo() const { return profiling_info_; }
328
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000329 private:
330 ArtMethod* const method_;
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000331 Thread* const self_;
332 ProfilingInfo* const profiling_info_;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000333};
334
Calin Juravle13439f02017-02-21 01:17:21 -0800335HInliner::InlineCacheType HInliner::GetInlineCacheType(
336 const Handle<mirror::ObjectArray<mirror::Class>>& classes)
337 REQUIRES_SHARED(Locks::mutator_lock_) {
338 uint8_t number_of_types = 0;
339 for (; number_of_types < InlineCache::kIndividualCacheSize; ++number_of_types) {
340 if (classes->Get(number_of_types) == nullptr) {
341 break;
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000342 }
343 }
Calin Juravle13439f02017-02-21 01:17:21 -0800344
345 if (number_of_types == 0) {
346 return kInlineCacheUninitialized;
347 } else if (number_of_types == 1) {
348 return kInlineCacheMonomorphic;
349 } else if (number_of_types == InlineCache::kIndividualCacheSize) {
350 return kInlineCacheMegamorphic;
351 } else {
352 return kInlineCachePolymorphic;
353 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000354}
355
356static mirror::Class* GetMonomorphicType(Handle<mirror::ObjectArray<mirror::Class>> classes)
357 REQUIRES_SHARED(Locks::mutator_lock_) {
358 DCHECK(classes->Get(0) != nullptr);
359 return classes->Get(0);
360}
361
Mingyao Yang063fc772016-08-02 11:02:54 -0700362ArtMethod* HInliner::TryCHADevirtualization(ArtMethod* resolved_method) {
363 if (!resolved_method->HasSingleImplementation()) {
364 return nullptr;
365 }
366 if (Runtime::Current()->IsAotCompiler()) {
367 // No CHA-based devirtulization for AOT compiler (yet).
368 return nullptr;
369 }
370 if (outermost_graph_->IsCompilingOsr()) {
371 // We do not support HDeoptimize in OSR methods.
372 return nullptr;
373 }
Mingyao Yange8fcd012017-01-20 10:43:30 -0800374 PointerSize pointer_size = caller_compilation_unit_.GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +0000375 ArtMethod* single_impl = resolved_method->GetSingleImplementation(pointer_size);
376 if (single_impl == nullptr) {
377 return nullptr;
378 }
379 if (single_impl->IsProxyMethod()) {
380 // Proxy method is a generic invoker that's not worth
381 // devirtualizing/inlining. It also causes issues when the proxy
382 // method is in another dex file if we try to rewrite invoke-interface to
383 // invoke-virtual because a proxy method doesn't have a real dex file.
384 return nullptr;
385 }
Nicolas Geoffray8e33e842017-04-03 16:55:16 +0100386 if (!single_impl->GetDeclaringClass()->IsResolved()) {
387 // There's a race with the class loading, which updates the CHA info
388 // before setting the class to resolved. So we just bail for this
389 // rare occurence.
390 return nullptr;
391 }
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +0000392 return single_impl;
Mingyao Yang063fc772016-08-02 11:02:54 -0700393}
394
Aart Bika8b8e9b2018-01-09 11:01:02 -0800395static bool AlwaysThrows(ArtMethod* method) {
396 CodeItemDataAccessor accessor(method);
397 // Skip native methods, methods with try blocks, and methods that are too large.
398 if (!accessor.HasCodeItem() ||
399 accessor.TriesSize() != 0 ||
400 accessor.InsnsSizeInCodeUnits() > kMaximumNumberOfTotalInstructions) {
401 return false;
402 }
403 // Scan for exits.
404 bool throw_seen = false;
405 for (const DexInstructionPcPair& pair : accessor) {
406 switch (pair.Inst().Opcode()) {
407 case Instruction::RETURN:
408 case Instruction::RETURN_VOID:
409 case Instruction::RETURN_WIDE:
410 case Instruction::RETURN_OBJECT:
411 case Instruction::RETURN_VOID_NO_BARRIER:
412 return false; // found regular control flow back
413 case Instruction::THROW:
414 throw_seen = true;
415 break;
416 default:
417 break;
418 }
419 }
420 return throw_seen;
421}
422
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700423bool HInliner::TryInline(HInvoke* invoke_instruction) {
Orion Hodsonac141392017-01-13 11:53:47 +0000424 if (invoke_instruction->IsInvokeUnresolved() ||
425 invoke_instruction->IsInvokePolymorphic()) {
426 return false; // Don't bother to move further if we know the method is unresolved or an
427 // invoke-polymorphic.
Calin Juravle175dc732015-08-25 15:42:32 +0100428 }
429
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000430 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100431 uint32_t method_index = invoke_instruction->GetDexMethodIndex();
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000432 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000433 LOG_TRY() << caller_dex_file.PrettyMethod(method_index);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000434
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100435 ArtMethod* resolved_method = invoke_instruction->GetResolvedMethod();
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100436 if (resolved_method == nullptr) {
437 DCHECK(invoke_instruction->IsInvokeStaticOrDirect());
438 DCHECK(invoke_instruction->AsInvokeStaticOrDirect()->IsStringInit());
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000439 LOG_FAIL_NO_STAT() << "Not inlining a String.<init> method";
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100440 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000441 }
442 ArtMethod* actual_method = nullptr;
443
444 if (invoke_instruction->IsInvokeStaticOrDirect()) {
Andreas Gampefd2140f2015-12-23 16:30:44 -0800445 actual_method = resolved_method;
Vladimir Marko58155012015-08-19 12:49:41 +0000446 } else {
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100447 // Check if we can statically find the method.
448 actual_method = FindVirtualOrInterfaceTarget(invoke_instruction, resolved_method);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000449 }
450
Mingyao Yang063fc772016-08-02 11:02:54 -0700451 bool cha_devirtualize = false;
452 if (actual_method == nullptr) {
453 ArtMethod* method = TryCHADevirtualization(resolved_method);
454 if (method != nullptr) {
455 cha_devirtualize = true;
456 actual_method = method;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000457 LOG_NOTE() << "Try CHA-based inlining of " << actual_method->PrettyMethod();
Mingyao Yang063fc772016-08-02 11:02:54 -0700458 }
459 }
460
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100461 if (actual_method != nullptr) {
Aart Bikd4e328f2018-01-16 14:14:34 -0800462 // Single target.
Mingyao Yang063fc772016-08-02 11:02:54 -0700463 bool result = TryInlineAndReplace(invoke_instruction,
464 actual_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000465 ReferenceTypeInfo::CreateInvalid(),
Mingyao Yang063fc772016-08-02 11:02:54 -0700466 /* do_rtp */ true,
467 cha_devirtualize);
Aart Bikd4e328f2018-01-16 14:14:34 -0800468 if (result) {
469 // Successfully inlined.
470 if (!invoke_instruction->IsInvokeStaticOrDirect()) {
471 if (cha_devirtualize) {
472 // Add dependency due to devirtualization. We've assumed resolved_method
473 // has single implementation.
474 outermost_graph_->AddCHASingleImplementationDependency(resolved_method);
475 MaybeRecordStat(stats_, MethodCompilationStat::kCHAInline);
476 } else {
477 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedInvokeVirtualOrInterface);
478 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700479 }
Aart Bikd4e328f2018-01-16 14:14:34 -0800480 } else if (!cha_devirtualize && AlwaysThrows(actual_method)) {
481 // Set always throws property for non-inlined method call with single target
482 // (unless it was obtained through CHA, because that would imply we have
483 // to add the CHA dependency, which seems not worth it).
484 invoke_instruction->SetAlwaysThrows(true);
Calin Juravle69158982016-03-16 11:53:41 +0000485 }
486 return result;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100487 }
Andreas Gampefd2140f2015-12-23 16:30:44 -0800488 DCHECK(!invoke_instruction->IsInvokeStaticOrDirect());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100489
Calin Juravle13439f02017-02-21 01:17:21 -0800490 // Try using inline caches.
491 return TryInlineFromInlineCache(caller_dex_file, invoke_instruction, resolved_method);
492}
493
494static Handle<mirror::ObjectArray<mirror::Class>> AllocateInlineCacheHolder(
495 const DexCompilationUnit& compilation_unit,
496 StackHandleScope<1>* hs)
497 REQUIRES_SHARED(Locks::mutator_lock_) {
498 Thread* self = Thread::Current();
499 ClassLinker* class_linker = compilation_unit.GetClassLinker();
500 Handle<mirror::ObjectArray<mirror::Class>> inline_cache = hs->NewHandle(
501 mirror::ObjectArray<mirror::Class>::Alloc(
502 self,
503 class_linker->GetClassRoot(ClassLinker::kClassArrayClass),
504 InlineCache::kIndividualCacheSize));
505 if (inline_cache == nullptr) {
506 // We got an OOME. Just clear the exception, and don't inline.
507 DCHECK(self->IsExceptionPending());
508 self->ClearException();
509 VLOG(compiler) << "Out of memory in the compiler when trying to inline";
510 }
511 return inline_cache;
512}
513
Calin Juravleaf44e6c2017-05-23 14:24:55 -0700514bool HInliner::UseOnlyPolymorphicInliningWithNoDeopt() {
515 // If we are compiling AOT or OSR, pretend the call using inline caches is polymorphic and
516 // do not generate a deopt.
517 //
518 // For AOT:
519 // Generating a deopt does not ensure that we will actually capture the new types;
520 // and the danger is that we could be stuck in a loop with "forever" deoptimizations.
521 // Take for example the following scenario:
522 // - we capture the inline cache in one run
523 // - the next run, we deoptimize because we miss a type check, but the method
524 // never becomes hot again
525 // In this case, the inline cache will not be updated in the profile and the AOT code
526 // will keep deoptimizing.
527 // Another scenario is if we use profile compilation for a process which is not allowed
528 // to JIT (e.g. system server). If we deoptimize we will run interpreted code for the
529 // rest of the lifetime.
530 // TODO(calin):
531 // This is a compromise because we will most likely never update the inline cache
532 // in the profile (unless there's another reason to deopt). So we might be stuck with
533 // a sub-optimal inline cache.
534 // We could be smarter when capturing inline caches to mitigate this.
535 // (e.g. by having different thresholds for new and old methods).
536 //
537 // For OSR:
538 // We may come from the interpreter and it may have seen different receiver types.
539 return Runtime::Current()->IsAotCompiler() || outermost_graph_->IsCompilingOsr();
540}
Calin Juravle13439f02017-02-21 01:17:21 -0800541bool HInliner::TryInlineFromInlineCache(const DexFile& caller_dex_file,
542 HInvoke* invoke_instruction,
543 ArtMethod* resolved_method)
544 REQUIRES_SHARED(Locks::mutator_lock_) {
Calin Juravlee2492d42017-03-20 11:42:13 -0700545 if (Runtime::Current()->IsAotCompiler() && !kUseAOTInlineCaches) {
546 return false;
547 }
548
Calin Juravle13439f02017-02-21 01:17:21 -0800549 StackHandleScope<1> hs(Thread::Current());
550 Handle<mirror::ObjectArray<mirror::Class>> inline_cache;
551 InlineCacheType inline_cache_type = Runtime::Current()->IsAotCompiler()
552 ? GetInlineCacheAOT(caller_dex_file, invoke_instruction, &hs, &inline_cache)
553 : GetInlineCacheJIT(invoke_instruction, &hs, &inline_cache);
554
555 switch (inline_cache_type) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000556 case kInlineCacheNoData: {
557 LOG_FAIL_NO_STAT()
558 << "Interface or virtual call to "
559 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
560 << " could not be statically determined";
Calin Juravle13439f02017-02-21 01:17:21 -0800561 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000562 }
Calin Juravle13439f02017-02-21 01:17:21 -0800563
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000564 case kInlineCacheUninitialized: {
565 LOG_FAIL_NO_STAT()
566 << "Interface or virtual call to "
567 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
568 << " is not hit and not inlined";
569 return false;
570 }
571
572 case kInlineCacheMonomorphic: {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000573 MaybeRecordStat(stats_, MethodCompilationStat::kMonomorphicCall);
Calin Juravleaf44e6c2017-05-23 14:24:55 -0700574 if (UseOnlyPolymorphicInliningWithNoDeopt()) {
Calin Juravle13439f02017-02-21 01:17:21 -0800575 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000576 } else {
Calin Juravle13439f02017-02-21 01:17:21 -0800577 return TryInlineMonomorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000578 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000579 }
Calin Juravle13439f02017-02-21 01:17:21 -0800580
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000581 case kInlineCachePolymorphic: {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000582 MaybeRecordStat(stats_, MethodCompilationStat::kPolymorphicCall);
Calin Juravle13439f02017-02-21 01:17:21 -0800583 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000584 }
Calin Juravle13439f02017-02-21 01:17:21 -0800585
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000586 case kInlineCacheMegamorphic: {
587 LOG_FAIL_NO_STAT()
588 << "Interface or virtual call to "
589 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
590 << " is megamorphic and not inlined";
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000591 MaybeRecordStat(stats_, MethodCompilationStat::kMegamorphicCall);
Calin Juravle13439f02017-02-21 01:17:21 -0800592 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000593 }
Calin Juravle13439f02017-02-21 01:17:21 -0800594
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000595 case kInlineCacheMissingTypes: {
596 LOG_FAIL_NO_STAT()
597 << "Interface or virtual call to "
598 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
599 << " is missing types and not inlined";
Calin Juravle13439f02017-02-21 01:17:21 -0800600 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000601 }
Calin Juravle13439f02017-02-21 01:17:21 -0800602 }
603 UNREACHABLE();
604}
605
606HInliner::InlineCacheType HInliner::GetInlineCacheJIT(
607 HInvoke* invoke_instruction,
608 StackHandleScope<1>* hs,
609 /*out*/Handle<mirror::ObjectArray<mirror::Class>>* inline_cache)
610 REQUIRES_SHARED(Locks::mutator_lock_) {
611 DCHECK(Runtime::Current()->UseJitCompilation());
612
613 ArtMethod* caller = graph_->GetArtMethod();
614 // Under JIT, we should always know the caller.
615 DCHECK(caller != nullptr);
616 ScopedProfilingInfoInlineUse spiis(caller, Thread::Current());
617 ProfilingInfo* profiling_info = spiis.GetProfilingInfo();
618
619 if (profiling_info == nullptr) {
620 return kInlineCacheNoData;
621 }
622
623 *inline_cache = AllocateInlineCacheHolder(caller_compilation_unit_, hs);
624 if (inline_cache->Get() == nullptr) {
625 // We can't extract any data if we failed to allocate;
626 return kInlineCacheNoData;
627 } else {
628 Runtime::Current()->GetJit()->GetCodeCache()->CopyInlineCacheInto(
629 *profiling_info->GetInlineCache(invoke_instruction->GetDexPc()),
630 *inline_cache);
631 return GetInlineCacheType(*inline_cache);
632 }
633}
634
635HInliner::InlineCacheType HInliner::GetInlineCacheAOT(
636 const DexFile& caller_dex_file,
637 HInvoke* invoke_instruction,
638 StackHandleScope<1>* hs,
639 /*out*/Handle<mirror::ObjectArray<mirror::Class>>* inline_cache)
640 REQUIRES_SHARED(Locks::mutator_lock_) {
641 DCHECK(Runtime::Current()->IsAotCompiler());
642 const ProfileCompilationInfo* pci = compiler_driver_->GetProfileCompilationInfo();
643 if (pci == nullptr) {
644 return kInlineCacheNoData;
645 }
646
Calin Juravlecc3171a2017-05-19 16:47:53 -0700647 std::unique_ptr<ProfileCompilationInfo::OfflineProfileMethodInfo> offline_profile =
648 pci->GetMethod(caller_dex_file.GetLocation(),
649 caller_dex_file.GetLocationChecksum(),
650 caller_compilation_unit_.GetDexMethodIndex());
651 if (offline_profile == nullptr) {
Calin Juravle13439f02017-02-21 01:17:21 -0800652 return kInlineCacheNoData; // no profile information for this invocation.
653 }
654
655 *inline_cache = AllocateInlineCacheHolder(caller_compilation_unit_, hs);
656 if (inline_cache == nullptr) {
657 // We can't extract any data if we failed to allocate;
658 return kInlineCacheNoData;
659 } else {
660 return ExtractClassesFromOfflineProfile(invoke_instruction,
Calin Juravlecc3171a2017-05-19 16:47:53 -0700661 *(offline_profile.get()),
Calin Juravle13439f02017-02-21 01:17:21 -0800662 *inline_cache);
663 }
664}
665
666HInliner::InlineCacheType HInliner::ExtractClassesFromOfflineProfile(
667 const HInvoke* invoke_instruction,
668 const ProfileCompilationInfo::OfflineProfileMethodInfo& offline_profile,
669 /*out*/Handle<mirror::ObjectArray<mirror::Class>> inline_cache)
670 REQUIRES_SHARED(Locks::mutator_lock_) {
Calin Juravlee6f87cc2017-05-24 17:41:05 -0700671 const auto it = offline_profile.inline_caches->find(invoke_instruction->GetDexPc());
672 if (it == offline_profile.inline_caches->end()) {
Calin Juravle13439f02017-02-21 01:17:21 -0800673 return kInlineCacheUninitialized;
674 }
675
676 const ProfileCompilationInfo::DexPcData& dex_pc_data = it->second;
677
678 if (dex_pc_data.is_missing_types) {
679 return kInlineCacheMissingTypes;
680 }
681 if (dex_pc_data.is_megamorphic) {
682 return kInlineCacheMegamorphic;
683 }
684
685 DCHECK_LE(dex_pc_data.classes.size(), InlineCache::kIndividualCacheSize);
686 Thread* self = Thread::Current();
687 // We need to resolve the class relative to the containing dex file.
688 // So first, build a mapping from the index of dex file in the profile to
689 // its dex cache. This will avoid repeating the lookup when walking over
690 // the inline cache types.
691 std::vector<ObjPtr<mirror::DexCache>> dex_profile_index_to_dex_cache(
692 offline_profile.dex_references.size());
693 for (size_t i = 0; i < offline_profile.dex_references.size(); i++) {
694 bool found = false;
695 for (const DexFile* dex_file : compiler_driver_->GetDexFilesForOatFile()) {
696 if (offline_profile.dex_references[i].MatchesDex(dex_file)) {
697 dex_profile_index_to_dex_cache[i] =
698 caller_compilation_unit_.GetClassLinker()->FindDexCache(self, *dex_file);
699 found = true;
700 }
701 }
702 if (!found) {
703 VLOG(compiler) << "Could not find profiled dex file: "
704 << offline_profile.dex_references[i].dex_location;
705 return kInlineCacheMissingTypes;
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100706 }
707 }
708
Calin Juravle13439f02017-02-21 01:17:21 -0800709 // Walk over the classes and resolve them. If we cannot find a type we return
710 // kInlineCacheMissingTypes.
711 int ic_index = 0;
712 for (const ProfileCompilationInfo::ClassReference& class_ref : dex_pc_data.classes) {
713 ObjPtr<mirror::DexCache> dex_cache =
714 dex_profile_index_to_dex_cache[class_ref.dex_profile_index];
715 DCHECK(dex_cache != nullptr);
Calin Juravle08556882017-05-26 16:40:45 -0700716
717 if (!dex_cache->GetDexFile()->IsTypeIndexValid(class_ref.type_index)) {
718 VLOG(compiler) << "Profile data corrupt: type index " << class_ref.type_index
719 << "is invalid in location" << dex_cache->GetDexFile()->GetLocation();
720 return kInlineCacheNoData;
721 }
Vladimir Marko666ee3d2017-12-11 18:37:36 +0000722 ObjPtr<mirror::Class> clazz = caller_compilation_unit_.GetClassLinker()->LookupResolvedType(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000723 class_ref.type_index,
724 dex_cache,
725 caller_compilation_unit_.GetClassLoader().Get());
Calin Juravle13439f02017-02-21 01:17:21 -0800726 if (clazz != nullptr) {
727 inline_cache->Set(ic_index++, clazz);
728 } else {
729 VLOG(compiler) << "Could not resolve class from inline cache in AOT mode "
730 << caller_compilation_unit_.GetDexFile()->PrettyMethod(
731 invoke_instruction->GetDexMethodIndex()) << " : "
732 << caller_compilation_unit_
733 .GetDexFile()->StringByTypeIdx(class_ref.type_index);
734 return kInlineCacheMissingTypes;
735 }
736 }
737 return GetInlineCacheType(inline_cache);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100738}
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000739
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000740HInstanceFieldGet* HInliner::BuildGetReceiverClass(ClassLinker* class_linker,
741 HInstruction* receiver,
742 uint32_t dex_pc) const {
743 ArtField* field = class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0);
744 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
Vladimir Markoca6fff82017-10-03 14:49:14 +0100745 HInstanceFieldGet* result = new (graph_->GetAllocator()) HInstanceFieldGet(
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000746 receiver,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000747 field,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100748 DataType::Type::kReference,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000749 field->GetOffset(),
750 field->IsVolatile(),
751 field->GetDexFieldIndex(),
752 field->GetDeclaringClass()->GetDexClassDefIndex(),
753 *field->GetDexFile(),
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000754 dex_pc);
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000755 // The class of a field is effectively final, and does not have any memory dependencies.
756 result->SetSideEffects(SideEffects::None());
757 return result;
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000758}
759
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000760static ArtMethod* ResolveMethodFromInlineCache(Handle<mirror::Class> klass,
761 ArtMethod* resolved_method,
762 HInstruction* invoke_instruction,
763 PointerSize pointer_size)
764 REQUIRES_SHARED(Locks::mutator_lock_) {
765 if (Runtime::Current()->IsAotCompiler()) {
766 // We can get unrelated types when working with profiles (corruption,
767 // systme updates, or anyone can write to it). So first check if the class
768 // actually implements the declaring class of the method that is being
769 // called in bytecode.
770 // Note: the lookup methods used below require to have assignable types.
771 if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(klass.Get())) {
772 return nullptr;
773 }
774 }
775
776 if (invoke_instruction->IsInvokeInterface()) {
777 resolved_method = klass->FindVirtualMethodForInterface(resolved_method, pointer_size);
778 } else {
779 DCHECK(invoke_instruction->IsInvokeVirtual());
780 resolved_method = klass->FindVirtualMethodForVirtual(resolved_method, pointer_size);
781 }
782 DCHECK(resolved_method != nullptr);
783 return resolved_method;
784}
785
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100786bool HInliner::TryInlineMonomorphicCall(HInvoke* invoke_instruction,
787 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000788 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000789 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
790 << invoke_instruction->DebugName();
791
Andreas Gampea5b09a62016-11-17 15:21:22 -0800792 dex::TypeIndex class_index = FindClassIndexIn(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000793 GetMonomorphicType(classes), caller_compilation_unit_);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800794 if (!class_index.IsValid()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000795 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedDexCache)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000796 << "Call to " << ArtMethod::PrettyMethod(resolved_method)
797 << " from inline cache is not inlined because its class is not"
798 << " accessible to the caller";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100799 return false;
800 }
801
802 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700803 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000804 Handle<mirror::Class> monomorphic_type = handles_->NewHandle(GetMonomorphicType(classes));
805 resolved_method = ResolveMethodFromInlineCache(
806 monomorphic_type, resolved_method, invoke_instruction, pointer_size);
807
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000808 LOG_NOTE() << "Try inline monomorphic call to " << resolved_method->PrettyMethod();
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000809 if (resolved_method == nullptr) {
810 // Bogus AOT profile, bail.
811 DCHECK(Runtime::Current()->IsAotCompiler());
812 return false;
813 }
814
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100815 HInstruction* receiver = invoke_instruction->InputAt(0);
816 HInstruction* cursor = invoke_instruction->GetPrevious();
817 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Mingyao Yang063fc772016-08-02 11:02:54 -0700818 if (!TryInlineAndReplace(invoke_instruction,
819 resolved_method,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000820 ReferenceTypeInfo::Create(monomorphic_type, /* is_exact */ true),
Mingyao Yang063fc772016-08-02 11:02:54 -0700821 /* do_rtp */ false,
822 /* cha_devirtualize */ false)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100823 return false;
824 }
825
826 // We successfully inlined, now add a guard.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000827 AddTypeGuard(receiver,
828 cursor,
829 bb_cursor,
830 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000831 monomorphic_type,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000832 invoke_instruction,
833 /* with_deoptimization */ true);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100834
835 // Run type propagation to get the guard typed, and eventually propagate the
836 // type of the receiver.
Vladimir Marko456307a2016-04-19 14:12:13 +0000837 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000838 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +0000839 outer_compilation_unit_.GetDexCache(),
840 handles_,
841 /* is_first_run */ false);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100842 rtp_fixup.Run();
843
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000844 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedMonomorphicCall);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100845 return true;
846}
847
Mingyao Yang063fc772016-08-02 11:02:54 -0700848void HInliner::AddCHAGuard(HInstruction* invoke_instruction,
849 uint32_t dex_pc,
850 HInstruction* cursor,
851 HBasicBlock* bb_cursor) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100852 HShouldDeoptimizeFlag* deopt_flag = new (graph_->GetAllocator())
853 HShouldDeoptimizeFlag(graph_->GetAllocator(), dex_pc);
854 HInstruction* compare = new (graph_->GetAllocator()) HNotEqual(
Mingyao Yang063fc772016-08-02 11:02:54 -0700855 deopt_flag, graph_->GetIntConstant(0, dex_pc));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100856 HInstruction* deopt = new (graph_->GetAllocator()) HDeoptimize(
857 graph_->GetAllocator(), compare, DeoptimizationKind::kCHA, dex_pc);
Mingyao Yang063fc772016-08-02 11:02:54 -0700858
859 if (cursor != nullptr) {
860 bb_cursor->InsertInstructionAfter(deopt_flag, cursor);
861 } else {
862 bb_cursor->InsertInstructionBefore(deopt_flag, bb_cursor->GetFirstInstruction());
863 }
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800864 bb_cursor->InsertInstructionAfter(compare, deopt_flag);
865 bb_cursor->InsertInstructionAfter(deopt, compare);
866
867 // Add receiver as input to aid CHA guard optimization later.
868 deopt_flag->AddInput(invoke_instruction->InputAt(0));
869 DCHECK_EQ(deopt_flag->InputCount(), 1u);
Mingyao Yang063fc772016-08-02 11:02:54 -0700870 deopt->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800871 outermost_graph_->IncrementNumberOfCHAGuards();
Mingyao Yang063fc772016-08-02 11:02:54 -0700872}
873
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000874HInstruction* HInliner::AddTypeGuard(HInstruction* receiver,
875 HInstruction* cursor,
876 HBasicBlock* bb_cursor,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800877 dex::TypeIndex class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000878 Handle<mirror::Class> klass,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000879 HInstruction* invoke_instruction,
880 bool with_deoptimization) {
881 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
882 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
883 class_linker, receiver, invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000884 if (cursor != nullptr) {
885 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
886 } else {
887 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
888 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000889
890 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Calin Juravle07f01df2017-04-28 19:58:01 -0700891 bool is_referrer;
892 ArtMethod* outermost_art_method = outermost_graph_->GetArtMethod();
893 if (outermost_art_method == nullptr) {
894 DCHECK(Runtime::Current()->IsAotCompiler());
895 // We are in AOT mode and we don't have an ART method to determine
896 // if the inlined method belongs to the referrer. Assume it doesn't.
897 is_referrer = false;
898 } else {
899 is_referrer = klass.Get() == outermost_art_method->GetDeclaringClass();
900 }
901
Nicolas Geoffray56876342016-12-16 16:09:08 +0000902 // Note that we will just compare the classes, so we don't need Java semantics access checks.
903 // Note that the type index and the dex file are relative to the method this type guard is
904 // inlined into.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100905 HLoadClass* load_class = new (graph_->GetAllocator()) HLoadClass(graph_->GetCurrentMethod(),
906 class_index,
907 caller_dex_file,
908 klass,
909 is_referrer,
910 invoke_instruction->GetDexPc(),
911 /* needs_access_check */ false);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000912 HLoadClass::LoadKind kind = HSharpening::ComputeLoadClassKind(
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000913 load_class, codegen_, compiler_driver_, caller_compilation_unit_);
914 DCHECK(kind != HLoadClass::LoadKind::kInvalid)
915 << "We should always be able to reference a class for inline caches";
Vladimir Marko28e012a2017-12-07 11:22:59 +0000916 // Load kind must be set before inserting the instruction into the graph.
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000917 load_class->SetLoadKind(kind);
Vladimir Marko28e012a2017-12-07 11:22:59 +0000918 bb_cursor->InsertInstructionAfter(load_class, receiver_class);
Calin Juravle13439f02017-02-21 01:17:21 -0800919 // In AOT mode, we will most likely load the class from BSS, which will involve a call
920 // to the runtime. In this case, the load instruction will need an environment so copy
921 // it from the invoke instruction.
922 if (load_class->NeedsEnvironment()) {
923 DCHECK(Runtime::Current()->IsAotCompiler());
924 load_class->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
925 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000926
Vladimir Markoca6fff82017-10-03 14:49:14 +0100927 HNotEqual* compare = new (graph_->GetAllocator()) HNotEqual(load_class, receiver_class);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000928 bb_cursor->InsertInstructionAfter(compare, load_class);
929 if (with_deoptimization) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100930 HDeoptimize* deoptimize = new (graph_->GetAllocator()) HDeoptimize(
931 graph_->GetAllocator(),
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000932 compare,
933 receiver,
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +0100934 Runtime::Current()->IsAotCompiler()
935 ? DeoptimizationKind::kAotInlineCache
936 : DeoptimizationKind::kJitInlineCache,
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000937 invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000938 bb_cursor->InsertInstructionAfter(deoptimize, compare);
939 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000940 DCHECK_EQ(invoke_instruction->InputAt(0), receiver);
941 receiver->ReplaceUsesDominatedBy(deoptimize, deoptimize);
942 deoptimize->SetReferenceTypeInfo(receiver->GetReferenceTypeInfo());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000943 }
944 return compare;
945}
946
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000947bool HInliner::TryInlinePolymorphicCall(HInvoke* invoke_instruction,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100948 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000949 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000950 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
951 << invoke_instruction->DebugName();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000952
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000953 if (TryInlinePolymorphicCallToSameTarget(invoke_instruction, resolved_method, classes)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000954 return true;
955 }
956
957 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700958 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000959
960 bool all_targets_inlined = true;
961 bool one_target_inlined = false;
962 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000963 if (classes->Get(i) == nullptr) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000964 break;
965 }
966 ArtMethod* method = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000967
968 Handle<mirror::Class> handle = handles_->NewHandle(classes->Get(i));
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000969 method = ResolveMethodFromInlineCache(
970 handle, resolved_method, invoke_instruction, pointer_size);
971 if (method == nullptr) {
972 DCHECK(Runtime::Current()->IsAotCompiler());
973 // AOT profile is bogus. This loop expects to iterate over all entries,
974 // so just just continue.
975 all_targets_inlined = false;
976 continue;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000977 }
978
979 HInstruction* receiver = invoke_instruction->InputAt(0);
980 HInstruction* cursor = invoke_instruction->GetPrevious();
981 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
982
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000983 dex::TypeIndex class_index = FindClassIndexIn(handle.Get(), caller_compilation_unit_);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000984 HInstruction* return_replacement = nullptr;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000985 LOG_NOTE() << "Try inline polymorphic call to " << method->PrettyMethod();
Andreas Gampea5b09a62016-11-17 15:21:22 -0800986 if (!class_index.IsValid() ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000987 !TryBuildAndInline(invoke_instruction,
988 method,
989 ReferenceTypeInfo::Create(handle, /* is_exact */ true),
990 &return_replacement)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000991 all_targets_inlined = false;
992 } else {
993 one_target_inlined = true;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000994
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000995 LOG_SUCCESS() << "Polymorphic call to " << ArtMethod::PrettyMethod(resolved_method)
996 << " has inlined " << ArtMethod::PrettyMethod(method);
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000997
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000998 // If we have inlined all targets before, and this receiver is the last seen,
999 // we deoptimize instead of keeping the original invoke instruction.
Calin Juravleaf44e6c2017-05-23 14:24:55 -07001000 bool deoptimize = !UseOnlyPolymorphicInliningWithNoDeopt() &&
1001 all_targets_inlined &&
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001002 (i != InlineCache::kIndividualCacheSize - 1) &&
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001003 (classes->Get(i + 1) == nullptr);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001004
Nicolas Geoffray56876342016-12-16 16:09:08 +00001005 HInstruction* compare = AddTypeGuard(receiver,
1006 cursor,
1007 bb_cursor,
1008 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +00001009 handle,
Nicolas Geoffray56876342016-12-16 16:09:08 +00001010 invoke_instruction,
1011 deoptimize);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001012 if (deoptimize) {
1013 if (return_replacement != nullptr) {
1014 invoke_instruction->ReplaceWith(return_replacement);
1015 }
1016 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
1017 // Because the inline cache data can be populated concurrently, we force the end of the
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +00001018 // iteration. Otherwise, we could see a new receiver type.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001019 break;
1020 } else {
1021 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
1022 }
1023 }
1024 }
1025
1026 if (!one_target_inlined) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001027 LOG_FAIL_NO_STAT()
1028 << "Call to " << ArtMethod::PrettyMethod(resolved_method)
1029 << " from inline cache is not inlined because none"
1030 << " of its targets could be inlined";
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001031 return false;
1032 }
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001033
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001034 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedPolymorphicCall);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001035
1036 // Run type propagation to get the guards typed.
Vladimir Marko456307a2016-04-19 14:12:13 +00001037 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001038 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +00001039 outer_compilation_unit_.GetDexCache(),
1040 handles_,
1041 /* is_first_run */ false);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001042 rtp_fixup.Run();
1043 return true;
1044}
1045
1046void HInliner::CreateDiamondPatternForPolymorphicInline(HInstruction* compare,
1047 HInstruction* return_replacement,
1048 HInstruction* invoke_instruction) {
1049 uint32_t dex_pc = invoke_instruction->GetDexPc();
1050 HBasicBlock* cursor_block = compare->GetBlock();
1051 HBasicBlock* original_invoke_block = invoke_instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001052 ArenaAllocator* allocator = graph_->GetAllocator();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001053
1054 // Spit the block after the compare: `cursor_block` will now be the start of the diamond,
1055 // and the returned block is the start of the then branch (that could contain multiple blocks).
1056 HBasicBlock* then = cursor_block->SplitAfterForInlining(compare);
1057
1058 // Split the block containing the invoke before and after the invoke. The returned block
1059 // of the split before will contain the invoke and will be the otherwise branch of
1060 // the diamond. The returned block of the split after will be the merge block
1061 // of the diamond.
1062 HBasicBlock* end_then = invoke_instruction->GetBlock();
1063 HBasicBlock* otherwise = end_then->SplitBeforeForInlining(invoke_instruction);
1064 HBasicBlock* merge = otherwise->SplitAfterForInlining(invoke_instruction);
1065
1066 // If the methods we are inlining return a value, we create a phi in the merge block
1067 // that will have the `invoke_instruction and the `return_replacement` as inputs.
1068 if (return_replacement != nullptr) {
1069 HPhi* phi = new (allocator) HPhi(
1070 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke_instruction->GetType()), dex_pc);
1071 merge->AddPhi(phi);
1072 invoke_instruction->ReplaceWith(phi);
1073 phi->AddInput(return_replacement);
1074 phi->AddInput(invoke_instruction);
1075 }
1076
1077 // Add the control flow instructions.
1078 otherwise->AddInstruction(new (allocator) HGoto(dex_pc));
1079 end_then->AddInstruction(new (allocator) HGoto(dex_pc));
1080 cursor_block->AddInstruction(new (allocator) HIf(compare, dex_pc));
1081
1082 // Add the newly created blocks to the graph.
1083 graph_->AddBlock(then);
1084 graph_->AddBlock(otherwise);
1085 graph_->AddBlock(merge);
1086
1087 // Set up successor (and implictly predecessor) relations.
1088 cursor_block->AddSuccessor(otherwise);
1089 cursor_block->AddSuccessor(then);
1090 end_then->AddSuccessor(merge);
1091 otherwise->AddSuccessor(merge);
1092
1093 // Set up dominance information.
1094 then->SetDominator(cursor_block);
1095 cursor_block->AddDominatedBlock(then);
1096 otherwise->SetDominator(cursor_block);
1097 cursor_block->AddDominatedBlock(otherwise);
1098 merge->SetDominator(cursor_block);
1099 cursor_block->AddDominatedBlock(merge);
1100
1101 // Update the revert post order.
1102 size_t index = IndexOfElement(graph_->reverse_post_order_, cursor_block);
1103 MakeRoomFor(&graph_->reverse_post_order_, 1, index);
1104 graph_->reverse_post_order_[++index] = then;
1105 index = IndexOfElement(graph_->reverse_post_order_, end_then);
1106 MakeRoomFor(&graph_->reverse_post_order_, 2, index);
1107 graph_->reverse_post_order_[++index] = otherwise;
1108 graph_->reverse_post_order_[++index] = merge;
1109
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001110
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001111 graph_->UpdateLoopAndTryInformationOfNewBlock(
1112 then, original_invoke_block, /* replace_if_back_edge */ false);
1113 graph_->UpdateLoopAndTryInformationOfNewBlock(
1114 otherwise, original_invoke_block, /* replace_if_back_edge */ false);
1115
1116 // In case the original invoke location was a back edge, we need to update
1117 // the loop to now have the merge block as a back edge.
1118 graph_->UpdateLoopAndTryInformationOfNewBlock(
1119 merge, original_invoke_block, /* replace_if_back_edge */ true);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001120}
1121
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001122bool HInliner::TryInlinePolymorphicCallToSameTarget(
1123 HInvoke* invoke_instruction,
1124 ArtMethod* resolved_method,
1125 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001126 // This optimization only works under JIT for now.
Calin Juravle13439f02017-02-21 01:17:21 -08001127 if (!Runtime::Current()->UseJitCompilation()) {
1128 return false;
1129 }
1130
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001131 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -07001132 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001133
1134 DCHECK(resolved_method != nullptr);
1135 ArtMethod* actual_method = nullptr;
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001136 size_t method_index = invoke_instruction->IsInvokeVirtual()
1137 ? invoke_instruction->AsInvokeVirtual()->GetVTableIndex()
1138 : invoke_instruction->AsInvokeInterface()->GetImtIndex();
1139
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001140 // Check whether we are actually calling the same method among
1141 // the different types seen.
1142 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001143 if (classes->Get(i) == nullptr) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001144 break;
1145 }
1146 ArtMethod* new_method = nullptr;
1147 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001148 new_method = classes->Get(i)->GetImt(pointer_size)->Get(
Matthew Gharrity465ecc82016-07-19 21:32:52 +00001149 method_index, pointer_size);
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001150 if (new_method->IsRuntimeMethod()) {
1151 // Bail out as soon as we see a conflict trampoline in one of the target's
1152 // interface table.
1153 return false;
1154 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001155 } else {
1156 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001157 new_method = classes->Get(i)->GetEmbeddedVTableEntry(method_index, pointer_size);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001158 }
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001159 DCHECK(new_method != nullptr);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001160 if (actual_method == nullptr) {
1161 actual_method = new_method;
1162 } else if (actual_method != new_method) {
1163 // Different methods, bailout.
1164 return false;
1165 }
1166 }
1167
1168 HInstruction* receiver = invoke_instruction->InputAt(0);
1169 HInstruction* cursor = invoke_instruction->GetPrevious();
1170 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
1171
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001172 HInstruction* return_replacement = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001173 if (!TryBuildAndInline(invoke_instruction,
1174 actual_method,
1175 ReferenceTypeInfo::CreateInvalid(),
1176 &return_replacement)) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001177 return false;
1178 }
1179
1180 // We successfully inlined, now add a guard.
1181 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
1182 class_linker, receiver, invoke_instruction->GetDexPc());
1183
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001184 DataType::Type type = Is64BitInstructionSet(graph_->GetInstructionSet())
1185 ? DataType::Type::kInt64
1186 : DataType::Type::kInt32;
Vladimir Markoca6fff82017-10-03 14:49:14 +01001187 HClassTableGet* class_table_get = new (graph_->GetAllocator()) HClassTableGet(
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001188 receiver_class,
1189 type,
Vladimir Markoa1de9182016-02-25 11:37:38 +00001190 invoke_instruction->IsInvokeVirtual() ? HClassTableGet::TableKind::kVTable
1191 : HClassTableGet::TableKind::kIMTable,
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001192 method_index,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001193 invoke_instruction->GetDexPc());
1194
1195 HConstant* constant;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001196 if (type == DataType::Type::kInt64) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001197 constant = graph_->GetLongConstant(
1198 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
1199 } else {
1200 constant = graph_->GetIntConstant(
1201 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
1202 }
1203
Vladimir Markoca6fff82017-10-03 14:49:14 +01001204 HNotEqual* compare = new (graph_->GetAllocator()) HNotEqual(class_table_get, constant);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001205 if (cursor != nullptr) {
1206 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
1207 } else {
1208 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
1209 }
1210 bb_cursor->InsertInstructionAfter(class_table_get, receiver_class);
1211 bb_cursor->InsertInstructionAfter(compare, class_table_get);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001212
1213 if (outermost_graph_->IsCompilingOsr()) {
1214 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
1215 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +01001216 HDeoptimize* deoptimize = new (graph_->GetAllocator()) HDeoptimize(
1217 graph_->GetAllocator(),
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001218 compare,
1219 receiver,
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +01001220 DeoptimizationKind::kJitSameTarget,
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001221 invoke_instruction->GetDexPc());
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001222 bb_cursor->InsertInstructionAfter(deoptimize, compare);
1223 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
1224 if (return_replacement != nullptr) {
1225 invoke_instruction->ReplaceWith(return_replacement);
1226 }
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001227 receiver->ReplaceUsesDominatedBy(deoptimize, deoptimize);
Nicolas Geoffray1be7cbd2016-04-29 13:56:01 +01001228 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001229 deoptimize->SetReferenceTypeInfo(receiver->GetReferenceTypeInfo());
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001230 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001231
1232 // Run type propagation to get the guard typed.
Vladimir Marko456307a2016-04-19 14:12:13 +00001233 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001234 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +00001235 outer_compilation_unit_.GetDexCache(),
1236 handles_,
1237 /* is_first_run */ false);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001238 rtp_fixup.Run();
1239
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001240 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedPolymorphicCall);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001241
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001242 LOG_SUCCESS() << "Inlined same polymorphic target " << actual_method->PrettyMethod();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001243 return true;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001244}
1245
Mingyao Yang063fc772016-08-02 11:02:54 -07001246bool HInliner::TryInlineAndReplace(HInvoke* invoke_instruction,
1247 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001248 ReferenceTypeInfo receiver_type,
Mingyao Yang063fc772016-08-02 11:02:54 -07001249 bool do_rtp,
1250 bool cha_devirtualize) {
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001251 DCHECK(!invoke_instruction->IsIntrinsic());
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001252 HInstruction* return_replacement = nullptr;
Mingyao Yang063fc772016-08-02 11:02:54 -07001253 uint32_t dex_pc = invoke_instruction->GetDexPc();
1254 HInstruction* cursor = invoke_instruction->GetPrevious();
1255 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001256 bool should_remove_invoke_instruction = false;
1257
1258 // If invoke_instruction is devirtualized to a different method, give intrinsics
1259 // another chance before we try to inline it.
1260 bool wrong_invoke_type = false;
1261 if (invoke_instruction->GetResolvedMethod() != method &&
1262 IntrinsicsRecognizer::Recognize(invoke_instruction, method, &wrong_invoke_type)) {
1263 MaybeRecordStat(stats_, MethodCompilationStat::kIntrinsicRecognized);
1264 if (invoke_instruction->IsInvokeInterface()) {
1265 // We don't intrinsify an invoke-interface directly.
1266 // Replace the invoke-interface with an invoke-virtual.
1267 HInvokeVirtual* new_invoke = new (graph_->GetAllocator()) HInvokeVirtual(
1268 graph_->GetAllocator(),
1269 invoke_instruction->GetNumberOfArguments(),
1270 invoke_instruction->GetType(),
1271 invoke_instruction->GetDexPc(),
1272 invoke_instruction->GetDexMethodIndex(), // Use interface method's dex method index.
1273 method,
1274 method->GetMethodIndex());
1275 HInputsRef inputs = invoke_instruction->GetInputs();
1276 for (size_t index = 0; index != inputs.size(); ++index) {
1277 new_invoke->SetArgumentAt(index, inputs[index]);
1278 }
1279 invoke_instruction->GetBlock()->InsertInstructionBefore(new_invoke, invoke_instruction);
1280 new_invoke->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
1281 if (invoke_instruction->GetType() == DataType::Type::kReference) {
1282 new_invoke->SetReferenceTypeInfo(invoke_instruction->GetReferenceTypeInfo());
1283 }
1284 // Run intrinsic recognizer again to set new_invoke's intrinsic.
1285 IntrinsicsRecognizer::Recognize(new_invoke, method, &wrong_invoke_type);
1286 DCHECK_NE(new_invoke->GetIntrinsic(), Intrinsics::kNone);
1287 return_replacement = new_invoke;
1288 // invoke_instruction is replaced with new_invoke.
1289 should_remove_invoke_instruction = true;
1290 } else {
1291 // invoke_instruction is intrinsified and stays.
1292 }
1293 } else if (!TryBuildAndInline(invoke_instruction, method, receiver_type, &return_replacement)) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001294 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +00001295 DCHECK(!method->IsProxyMethod());
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001296 // Turn an invoke-interface into an invoke-virtual. An invoke-virtual is always
1297 // better than an invoke-interface because:
1298 // 1) In the best case, the interface call has one more indirection (to fetch the IMT).
1299 // 2) We will not go to the conflict trampoline with an invoke-virtual.
1300 // TODO: Consider sharpening once it is not dependent on the compiler driver.
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +00001301
1302 if (method->IsDefault() && !method->IsCopied()) {
1303 // Changing to invoke-virtual cannot be done on an original default method
1304 // since it's not in any vtable. Devirtualization by exact type/inline-cache
1305 // always uses a method in the iftable which is never an original default
1306 // method.
1307 // On the other hand, inlining an original default method by CHA is fine.
1308 DCHECK(cha_devirtualize);
1309 return false;
1310 }
1311
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001312 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001313 uint32_t dex_method_index = FindMethodIndexIn(
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001314 method, caller_dex_file, invoke_instruction->GetDexMethodIndex());
Andreas Gampee2abbc62017-09-15 11:59:26 -07001315 if (dex_method_index == dex::kDexNoIndex) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001316 return false;
1317 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01001318 HInvokeVirtual* new_invoke = new (graph_->GetAllocator()) HInvokeVirtual(
1319 graph_->GetAllocator(),
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001320 invoke_instruction->GetNumberOfArguments(),
1321 invoke_instruction->GetType(),
1322 invoke_instruction->GetDexPc(),
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001323 dex_method_index,
1324 method,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001325 method->GetMethodIndex());
1326 HInputsRef inputs = invoke_instruction->GetInputs();
1327 for (size_t index = 0; index != inputs.size(); ++index) {
1328 new_invoke->SetArgumentAt(index, inputs[index]);
1329 }
1330 invoke_instruction->GetBlock()->InsertInstructionBefore(new_invoke, invoke_instruction);
1331 new_invoke->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001332 if (invoke_instruction->GetType() == DataType::Type::kReference) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001333 new_invoke->SetReferenceTypeInfo(invoke_instruction->GetReferenceTypeInfo());
1334 }
1335 return_replacement = new_invoke;
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001336 // invoke_instruction is replaced with new_invoke.
1337 should_remove_invoke_instruction = true;
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001338 } else {
1339 // TODO: Consider sharpening an invoke virtual once it is not dependent on the
1340 // compiler driver.
1341 return false;
1342 }
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001343 } else {
1344 // invoke_instruction is inlined.
1345 should_remove_invoke_instruction = true;
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001346 }
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001347
Mingyao Yang063fc772016-08-02 11:02:54 -07001348 if (cha_devirtualize) {
1349 AddCHAGuard(invoke_instruction, dex_pc, cursor, bb_cursor);
1350 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001351 if (return_replacement != nullptr) {
1352 invoke_instruction->ReplaceWith(return_replacement);
1353 }
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001354 if (should_remove_invoke_instruction) {
1355 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
1356 }
David Brazdil94ab38f2016-06-21 17:48:19 +01001357 FixUpReturnReferenceType(method, return_replacement);
1358 if (do_rtp && ReturnTypeMoreSpecific(invoke_instruction, return_replacement)) {
1359 // Actual return value has a more specific type than the method's declared
1360 // return type. Run RTP again on the outer graph to propagate it.
1361 ReferenceTypePropagation(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001362 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +01001363 outer_compilation_unit_.GetDexCache(),
1364 handles_,
1365 /* is_first_run */ false).Run();
1366 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001367 return true;
1368}
1369
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001370size_t HInliner::CountRecursiveCallsOf(ArtMethod* method) const {
1371 const HInliner* current = this;
1372 size_t count = 0;
1373 do {
1374 if (current->graph_->GetArtMethod() == method) {
1375 ++count;
1376 }
1377 current = current->parent_;
1378 } while (current != nullptr);
1379 return count;
1380}
1381
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001382bool HInliner::TryBuildAndInline(HInvoke* invoke_instruction,
1383 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001384 ReferenceTypeInfo receiver_type,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001385 HInstruction** return_replacement) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001386 if (method->IsProxyMethod()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001387 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedProxy)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001388 << "Method " << method->PrettyMethod()
1389 << " is not inlined because of unimplemented inline support for proxy methods.";
1390 return false;
1391 }
1392
1393 if (CountRecursiveCallsOf(method) > kMaximumNumberOfRecursiveCalls) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001394 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedRecursiveBudget)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001395 << "Method "
1396 << method->PrettyMethod()
1397 << " is not inlined because it has reached its recursive call budget.";
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001398 return false;
1399 }
1400
Jeff Haodcdc85b2015-12-04 14:06:18 -08001401 // Check whether we're allowed to inline. The outermost compilation unit is the relevant
1402 // dex file here (though the transitivity of an inline chain would allow checking the calller).
1403 if (!compiler_driver_->MayInline(method->GetDexFile(),
1404 outer_compilation_unit_.GetDexFile())) {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001405 if (TryPatternSubstitution(invoke_instruction, method, return_replacement)) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001406 LOG_SUCCESS() << "Successfully replaced pattern of invoke "
1407 << method->PrettyMethod();
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001408 MaybeRecordStat(stats_, MethodCompilationStat::kReplacedInvokeWithSimplePattern);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001409 return true;
1410 }
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001411 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedWont)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001412 << "Won't inline " << method->PrettyMethod() << " in "
1413 << outer_compilation_unit_.GetDexFile()->GetLocation() << " ("
1414 << caller_compilation_unit_.GetDexFile()->GetLocation() << ") from "
1415 << method->GetDexFile()->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001416 return false;
1417 }
1418
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001419 bool same_dex_file = IsSameDexFile(*outer_compilation_unit_.GetDexFile(), *method->GetDexFile());
1420
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001421 CodeItemDataAccessor accessor(method);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001422
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001423 if (!accessor.HasCodeItem()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001424 LOG_FAIL_NO_STAT()
1425 << "Method " << method->PrettyMethod() << " is not inlined because it is native";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001426 return false;
1427 }
1428
Calin Juravleec748352015-07-29 13:52:12 +01001429 size_t inline_max_code_units = compiler_driver_->GetCompilerOptions().GetInlineMaxCodeUnits();
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001430 if (accessor.InsnsSizeInCodeUnits() > inline_max_code_units) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001431 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedCodeItem)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001432 << "Method " << method->PrettyMethod()
1433 << " is not inlined because its code item is too big: "
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001434 << accessor.InsnsSizeInCodeUnits()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001435 << " > "
1436 << inline_max_code_units;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001437 return false;
1438 }
1439
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001440 if (accessor.TriesSize() != 0) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001441 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedTryCatch)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001442 << "Method " << method->PrettyMethod() << " is not inlined because of try block";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001443 return false;
1444 }
1445
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001446 if (!method->IsCompilable()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001447 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedNotVerified)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001448 << "Method " << method->PrettyMethod()
1449 << " has soft failures un-handled by the compiler, so it cannot be inlined";
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001450 }
1451
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001452 if (!method->GetDeclaringClass()->IsVerified()) {
1453 uint16_t class_def_idx = method->GetDeclaringClass()->GetDexClassDefIndex();
Calin Juravleffc87072016-04-20 14:22:09 +01001454 if (Runtime::Current()->UseJitCompilation() ||
Nicolas Geoffray5b82d332016-02-18 14:22:32 +00001455 !compiler_driver_->IsMethodVerifiedWithoutFailures(
1456 method->GetDexMethodIndex(), class_def_idx, *method->GetDexFile())) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001457 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedNotVerified)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001458 << "Method " << method->PrettyMethod()
1459 << " couldn't be verified, so it cannot be inlined";
Nicolas Geoffrayccc61972015-10-01 14:34:20 +01001460 return false;
1461 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001462 }
1463
Roland Levillain4c0eb422015-04-24 16:43:49 +01001464 if (invoke_instruction->IsInvokeStaticOrDirect() &&
1465 invoke_instruction->AsInvokeStaticOrDirect()->IsStaticWithImplicitClinitCheck()) {
1466 // Case of a static method that cannot be inlined because it implicitly
1467 // requires an initialization check of its declaring class.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001468 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedDexCache)
1469 << "Method " << method->PrettyMethod()
1470 << " is not inlined because it is static and requires a clinit"
1471 << " check that cannot be emitted due to Dex cache limitations";
Roland Levillain4c0eb422015-04-24 16:43:49 +01001472 return false;
1473 }
1474
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001475 if (!TryBuildAndInlineHelper(
1476 invoke_instruction, method, receiver_type, same_dex_file, return_replacement)) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001477 return false;
1478 }
1479
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001480 LOG_SUCCESS() << method->PrettyMethod();
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001481 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedInvoke);
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001482 return true;
1483}
1484
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001485static HInstruction* GetInvokeInputForArgVRegIndex(HInvoke* invoke_instruction,
1486 size_t arg_vreg_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001487 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001488 size_t input_index = 0;
1489 for (size_t i = 0; i < arg_vreg_index; ++i, ++input_index) {
1490 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001491 if (DataType::Is64BitType(invoke_instruction->InputAt(input_index)->GetType())) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001492 ++i;
1493 DCHECK_NE(i, arg_vreg_index);
1494 }
1495 }
1496 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
1497 return invoke_instruction->InputAt(input_index);
1498}
1499
1500// Try to recognize known simple patterns and replace invoke call with appropriate instructions.
1501bool HInliner::TryPatternSubstitution(HInvoke* invoke_instruction,
1502 ArtMethod* resolved_method,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001503 HInstruction** return_replacement) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001504 InlineMethod inline_method;
1505 if (!InlineMethodAnalyser::AnalyseMethodCode(resolved_method, &inline_method)) {
1506 return false;
1507 }
1508
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001509 switch (inline_method.opcode) {
1510 case kInlineOpNop:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001511 DCHECK_EQ(invoke_instruction->GetType(), DataType::Type::kVoid);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001512 *return_replacement = nullptr;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001513 break;
1514 case kInlineOpReturnArg:
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001515 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction,
1516 inline_method.d.return_data.arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001517 break;
1518 case kInlineOpNonWideConst:
1519 if (resolved_method->GetShorty()[0] == 'L') {
1520 DCHECK_EQ(inline_method.d.data, 0u);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001521 *return_replacement = graph_->GetNullConstant();
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001522 } else {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001523 *return_replacement = graph_->GetIntConstant(static_cast<int32_t>(inline_method.d.data));
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001524 }
1525 break;
1526 case kInlineOpIGet: {
1527 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1528 if (data.method_is_static || data.object_arg != 0u) {
1529 // TODO: Needs null check.
1530 return false;
1531 }
1532 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001533 HInstanceFieldGet* iget = CreateInstanceFieldGet(data.field_idx, resolved_method, obj);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001534 DCHECK_EQ(iget->GetFieldOffset().Uint32Value(), data.field_offset);
1535 DCHECK_EQ(iget->IsVolatile() ? 1u : 0u, data.is_volatile);
1536 invoke_instruction->GetBlock()->InsertInstructionBefore(iget, invoke_instruction);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001537 *return_replacement = iget;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001538 break;
1539 }
1540 case kInlineOpIPut: {
1541 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1542 if (data.method_is_static || data.object_arg != 0u) {
1543 // TODO: Needs null check.
1544 return false;
1545 }
1546 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
1547 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, data.src_arg);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001548 HInstanceFieldSet* iput = CreateInstanceFieldSet(data.field_idx, resolved_method, obj, value);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001549 DCHECK_EQ(iput->GetFieldOffset().Uint32Value(), data.field_offset);
1550 DCHECK_EQ(iput->IsVolatile() ? 1u : 0u, data.is_volatile);
1551 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1552 if (data.return_arg_plus1 != 0u) {
1553 size_t return_arg = data.return_arg_plus1 - 1u;
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001554 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction, return_arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001555 }
1556 break;
1557 }
Vladimir Marko354efa62016-02-04 19:46:56 +00001558 case kInlineOpConstructor: {
1559 const InlineConstructorData& data = inline_method.d.constructor_data;
1560 // Get the indexes to arrays for easier processing.
1561 uint16_t iput_field_indexes[] = {
1562 data.iput0_field_index, data.iput1_field_index, data.iput2_field_index
1563 };
1564 uint16_t iput_args[] = { data.iput0_arg, data.iput1_arg, data.iput2_arg };
1565 static_assert(arraysize(iput_args) == arraysize(iput_field_indexes), "Size mismatch");
1566 // Count valid field indexes.
1567 size_t number_of_iputs = 0u;
1568 while (number_of_iputs != arraysize(iput_field_indexes) &&
1569 iput_field_indexes[number_of_iputs] != DexFile::kDexNoIndex16) {
1570 // Check that there are no duplicate valid field indexes.
1571 DCHECK_EQ(0, std::count(iput_field_indexes + number_of_iputs + 1,
1572 iput_field_indexes + arraysize(iput_field_indexes),
1573 iput_field_indexes[number_of_iputs]));
1574 ++number_of_iputs;
1575 }
1576 // Check that there are no valid field indexes in the rest of the array.
1577 DCHECK_EQ(0, std::count_if(iput_field_indexes + number_of_iputs,
1578 iput_field_indexes + arraysize(iput_field_indexes),
1579 [](uint16_t index) { return index != DexFile::kDexNoIndex16; }));
1580
1581 // Create HInstanceFieldSet for each IPUT that stores non-zero data.
Vladimir Marko354efa62016-02-04 19:46:56 +00001582 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, /* this */ 0u);
1583 bool needs_constructor_barrier = false;
1584 for (size_t i = 0; i != number_of_iputs; ++i) {
1585 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, iput_args[i]);
Roland Levillain1a653882016-03-18 18:05:57 +00001586 if (!value->IsConstant() || !value->AsConstant()->IsZeroBitPattern()) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001587 uint16_t field_index = iput_field_indexes[i];
Vladimir Markof44d36c2017-03-14 14:18:46 +00001588 bool is_final;
1589 HInstanceFieldSet* iput =
1590 CreateInstanceFieldSet(field_index, resolved_method, obj, value, &is_final);
Vladimir Marko354efa62016-02-04 19:46:56 +00001591 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1592
1593 // Check whether the field is final. If it is, we need to add a barrier.
Vladimir Markof44d36c2017-03-14 14:18:46 +00001594 if (is_final) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001595 needs_constructor_barrier = true;
1596 }
1597 }
1598 }
1599 if (needs_constructor_barrier) {
Igor Murashkind01745e2017-04-05 16:40:31 -07001600 // See CompilerDriver::RequiresConstructorBarrier for more details.
1601 DCHECK(obj != nullptr) << "only non-static methods can have a constructor fence";
1602
1603 HConstructorFence* constructor_fence =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001604 new (graph_->GetAllocator()) HConstructorFence(obj, kNoDexPc, graph_->GetAllocator());
Igor Murashkind01745e2017-04-05 16:40:31 -07001605 invoke_instruction->GetBlock()->InsertInstructionBefore(constructor_fence,
1606 invoke_instruction);
Vladimir Marko354efa62016-02-04 19:46:56 +00001607 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001608 *return_replacement = nullptr;
Vladimir Marko354efa62016-02-04 19:46:56 +00001609 break;
1610 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001611 default:
1612 LOG(FATAL) << "UNREACHABLE";
1613 UNREACHABLE();
1614 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001615 return true;
1616}
1617
Vladimir Markof44d36c2017-03-14 14:18:46 +00001618HInstanceFieldGet* HInliner::CreateInstanceFieldGet(uint32_t field_index,
1619 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001620 HInstruction* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001621 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001622 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1623 ArtField* resolved_field =
1624 class_linker->LookupResolvedField(field_index, referrer, /* is_static */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001625 DCHECK(resolved_field != nullptr);
Vladimir Markoca6fff82017-10-03 14:49:14 +01001626 HInstanceFieldGet* iget = new (graph_->GetAllocator()) HInstanceFieldGet(
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001627 obj,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001628 resolved_field,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001629 DataType::FromShorty(resolved_field->GetTypeDescriptor()[0]),
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001630 resolved_field->GetOffset(),
1631 resolved_field->IsVolatile(),
1632 field_index,
1633 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001634 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001635 // Read barrier generates a runtime call in slow path and we need a valid
1636 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1637 /* dex_pc */ 0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001638 if (iget->GetType() == DataType::Type::kReference) {
Vladimir Marko456307a2016-04-19 14:12:13 +00001639 // Use the same dex_cache that we used for field lookup as the hint_dex_cache.
Vladimir Markof44d36c2017-03-14 14:18:46 +00001640 Handle<mirror::DexCache> dex_cache = handles_->NewHandle(referrer->GetDexCache());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001641 ReferenceTypePropagation rtp(graph_,
1642 outer_compilation_unit_.GetClassLoader(),
1643 dex_cache,
1644 handles_,
1645 /* is_first_run */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001646 rtp.Visit(iget);
1647 }
1648 return iget;
1649}
1650
Vladimir Markof44d36c2017-03-14 14:18:46 +00001651HInstanceFieldSet* HInliner::CreateInstanceFieldSet(uint32_t field_index,
1652 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001653 HInstruction* obj,
Vladimir Markof44d36c2017-03-14 14:18:46 +00001654 HInstruction* value,
1655 bool* is_final)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001656 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001657 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1658 ArtField* resolved_field =
1659 class_linker->LookupResolvedField(field_index, referrer, /* is_static */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001660 DCHECK(resolved_field != nullptr);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001661 if (is_final != nullptr) {
1662 // This information is needed only for constructors.
1663 DCHECK(referrer->IsConstructor());
1664 *is_final = resolved_field->IsFinal();
1665 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01001666 HInstanceFieldSet* iput = new (graph_->GetAllocator()) HInstanceFieldSet(
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001667 obj,
1668 value,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001669 resolved_field,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001670 DataType::FromShorty(resolved_field->GetTypeDescriptor()[0]),
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001671 resolved_field->GetOffset(),
1672 resolved_field->IsVolatile(),
1673 field_index,
1674 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001675 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001676 // Read barrier generates a runtime call in slow path and we need a valid
1677 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1678 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001679 return iput;
1680}
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001681
Vladimir Markob1d0ee12017-04-20 19:50:32 +01001682template <typename T>
1683static inline Handle<T> NewHandleIfDifferent(T* object,
1684 Handle<T> hint,
1685 VariableSizedHandleScope* handles)
1686 REQUIRES_SHARED(Locks::mutator_lock_) {
1687 return (object != hint.Get()) ? handles->NewHandle(object) : hint;
1688}
1689
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001690bool HInliner::TryBuildAndInlineHelper(HInvoke* invoke_instruction,
1691 ArtMethod* resolved_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001692 ReferenceTypeInfo receiver_type,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001693 bool same_dex_file,
1694 HInstruction** return_replacement) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001695 DCHECK(!(resolved_method->IsStatic() && receiver_type.IsValid()));
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001696 ScopedObjectAccess soa(Thread::Current());
1697 const DexFile::CodeItem* code_item = resolved_method->GetCodeItem();
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001698 const DexFile& callee_dex_file = *resolved_method->GetDexFile();
1699 uint32_t method_index = resolved_method->GetDexMethodIndex();
Mathieu Chartier8892c6b2018-01-09 15:10:17 -08001700 CodeItemDebugInfoAccessor code_item_accessor(resolved_method);
Calin Juravle2e768302015-07-28 14:41:11 +00001701 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Vladimir Markob1d0ee12017-04-20 19:50:32 +01001702 Handle<mirror::DexCache> dex_cache = NewHandleIfDifferent(resolved_method->GetDexCache(),
1703 caller_compilation_unit_.GetDexCache(),
1704 handles_);
1705 Handle<mirror::ClassLoader> class_loader =
1706 NewHandleIfDifferent(resolved_method->GetDeclaringClass()->GetClassLoader(),
1707 caller_compilation_unit_.GetClassLoader(),
1708 handles_);
Nicolas Geoffrayf1aedb12016-07-28 03:49:14 +01001709
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001710 DexCompilationUnit dex_compilation_unit(
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001711 class_loader,
Nicolas Geoffray5b82d332016-02-18 14:22:32 +00001712 class_linker,
1713 callee_dex_file,
1714 code_item,
1715 resolved_method->GetDeclaringClass()->GetDexClassDefIndex(),
1716 method_index,
1717 resolved_method->GetAccessFlags(),
1718 /* verified_method */ nullptr,
1719 dex_cache);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001720
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001721 InvokeType invoke_type = invoke_instruction->GetInvokeType();
Nicolas Geoffray35071052015-06-09 15:43:38 +01001722 if (invoke_type == kInterface) {
1723 // We have statically resolved the dispatch. To please the class linker
1724 // at runtime, we change this call as if it was a virtual call.
1725 invoke_type = kVirtual;
1726 }
David Brazdil3f523062016-02-29 16:53:33 +00001727
1728 const int32_t caller_instruction_counter = graph_->GetCurrentInstructionId();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001729 HGraph* callee_graph = new (graph_->GetAllocator()) HGraph(
1730 graph_->GetAllocator(),
1731 graph_->GetArenaStack(),
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001732 callee_dex_file,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001733 method_index,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001734 compiler_driver_->GetInstructionSet(),
Nicolas Geoffray35071052015-06-09 15:43:38 +01001735 invoke_type,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001736 graph_->IsDebuggable(),
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001737 /* osr */ false,
David Brazdil3f523062016-02-29 16:53:33 +00001738 caller_instruction_counter);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001739 callee_graph->SetArtMethod(resolved_method);
David Brazdil5e8b1372015-01-23 14:39:08 +00001740
Vladimir Marko438709f2017-02-23 18:56:13 +00001741 // When they are needed, allocate `inline_stats_` on the Arena instead
Roland Levillaina8013fd2016-04-04 15:34:31 +01001742 // of on the stack, as Clang might produce a stack frame too large
1743 // for this function, that would not fit the requirements of the
1744 // `-Wframe-larger-than` option.
Vladimir Marko438709f2017-02-23 18:56:13 +00001745 if (stats_ != nullptr) {
1746 // Reuse one object for all inline attempts from this caller to keep Arena memory usage low.
1747 if (inline_stats_ == nullptr) {
Vladimir Markoca6fff82017-10-03 14:49:14 +01001748 void* storage = graph_->GetAllocator()->Alloc<OptimizingCompilerStats>(kArenaAllocMisc);
Vladimir Marko438709f2017-02-23 18:56:13 +00001749 inline_stats_ = new (storage) OptimizingCompilerStats;
1750 } else {
1751 inline_stats_->Reset();
1752 }
1753 }
David Brazdil5e8b1372015-01-23 14:39:08 +00001754 HGraphBuilder builder(callee_graph,
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001755 code_item_accessor,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001756 &dex_compilation_unit,
1757 &outer_compilation_unit_,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001758 compiler_driver_,
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00001759 codegen_,
Vladimir Marko438709f2017-02-23 18:56:13 +00001760 inline_stats_,
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001761 resolved_method->GetQuickenedInfo(),
David Brazdildee58d62016-04-07 09:54:26 +00001762 handles_);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001763
David Brazdildee58d62016-04-07 09:54:26 +00001764 if (builder.BuildGraph() != kAnalysisSuccess) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001765 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedCannotBuild)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001766 << "Method " << callee_dex_file.PrettyMethod(method_index)
1767 << " could not be built, so cannot be inlined";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001768 return false;
1769 }
1770
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001771 if (!RegisterAllocator::CanAllocateRegistersFor(*callee_graph,
1772 compiler_driver_->GetInstructionSet())) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001773 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedRegisterAllocator)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001774 << "Method " << callee_dex_file.PrettyMethod(method_index)
1775 << " cannot be inlined because of the register allocator";
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001776 return false;
1777 }
1778
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001779 size_t parameter_index = 0;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001780 bool run_rtp = false;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001781 for (HInstructionIterator instructions(callee_graph->GetEntryBlock()->GetInstructions());
1782 !instructions.Done();
1783 instructions.Advance()) {
1784 HInstruction* current = instructions.Current();
1785 if (current->IsParameterValue()) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001786 HInstruction* argument = invoke_instruction->InputAt(parameter_index);
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001787 if (argument->IsNullConstant()) {
1788 current->ReplaceWith(callee_graph->GetNullConstant());
1789 } else if (argument->IsIntConstant()) {
1790 current->ReplaceWith(callee_graph->GetIntConstant(argument->AsIntConstant()->GetValue()));
1791 } else if (argument->IsLongConstant()) {
1792 current->ReplaceWith(callee_graph->GetLongConstant(argument->AsLongConstant()->GetValue()));
1793 } else if (argument->IsFloatConstant()) {
1794 current->ReplaceWith(
1795 callee_graph->GetFloatConstant(argument->AsFloatConstant()->GetValue()));
1796 } else if (argument->IsDoubleConstant()) {
1797 current->ReplaceWith(
1798 callee_graph->GetDoubleConstant(argument->AsDoubleConstant()->GetValue()));
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001799 } else if (argument->GetType() == DataType::Type::kReference) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001800 if (!resolved_method->IsStatic() && parameter_index == 0 && receiver_type.IsValid()) {
1801 run_rtp = true;
1802 current->SetReferenceTypeInfo(receiver_type);
1803 } else {
1804 current->SetReferenceTypeInfo(argument->GetReferenceTypeInfo());
1805 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001806 current->AsParameterValue()->SetCanBeNull(argument->CanBeNull());
1807 }
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001808 ++parameter_index;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001809 }
1810 }
1811
David Brazdil94ab38f2016-06-21 17:48:19 +01001812 // We have replaced formal arguments with actual arguments. If actual types
1813 // are more specific than the declared ones, run RTP again on the inner graph.
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001814 if (run_rtp || ArgumentTypesMoreSpecific(invoke_instruction, resolved_method)) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001815 ReferenceTypePropagation(callee_graph,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001816 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +01001817 dex_compilation_unit.GetDexCache(),
1818 handles_,
1819 /* is_first_run */ false).Run();
1820 }
1821
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001822 RunOptimizations(callee_graph, code_item, dex_compilation_unit);
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +00001823
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001824 HBasicBlock* exit_block = callee_graph->GetExitBlock();
1825 if (exit_block == nullptr) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001826 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedInfiniteLoop)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001827 << "Method " << callee_dex_file.PrettyMethod(method_index)
1828 << " could not be inlined because it has an infinite loop";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001829 return false;
1830 }
1831
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001832 bool has_one_return = false;
Vladimir Marko60584552015-09-03 13:35:12 +00001833 for (HBasicBlock* predecessor : exit_block->GetPredecessors()) {
1834 if (predecessor->GetLastInstruction()->IsThrow()) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001835 if (invoke_instruction->GetBlock()->IsTryBlock()) {
1836 // TODO(ngeoffray): Support adding HTryBoundary in Hgraph::InlineInto.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001837 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedTryCatch)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001838 << "Method " << callee_dex_file.PrettyMethod(method_index)
1839 << " could not be inlined because one branch always throws and"
1840 << " caller is in a try/catch block";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001841 return false;
1842 } else if (graph_->GetExitBlock() == nullptr) {
1843 // TODO(ngeoffray): Support adding HExit in the caller graph.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001844 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedInfiniteLoop)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001845 << "Method " << callee_dex_file.PrettyMethod(method_index)
1846 << " could not be inlined because one branch always throws and"
1847 << " caller does not have an exit block";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001848 return false;
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00001849 } else if (graph_->HasIrreducibleLoops()) {
1850 // TODO(ngeoffray): Support re-computing loop information to graphs with
1851 // irreducible loops?
1852 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1853 << " could not be inlined because one branch always throws and"
1854 << " caller has irreducible loops";
1855 return false;
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001856 }
1857 } else {
1858 has_one_return = true;
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001859 }
1860 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001861
1862 if (!has_one_return) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001863 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedAlwaysThrows)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001864 << "Method " << callee_dex_file.PrettyMethod(method_index)
1865 << " could not be inlined because it always throws";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001866 return false;
1867 }
1868
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001869 size_t number_of_instructions = 0;
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001870 // Skip the entry block, it does not contain instructions that prevent inlining.
1871 for (HBasicBlock* block : callee_graph->GetReversePostOrderSkipEntryBlock()) {
David Sehrc757dec2016-11-04 15:48:34 -07001872 if (block->IsLoopHeader()) {
1873 if (block->GetLoopInformation()->IsIrreducible()) {
1874 // Don't inline methods with irreducible loops, they could prevent some
1875 // optimizations to run.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001876 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedIrreducibleLoop)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001877 << "Method " << callee_dex_file.PrettyMethod(method_index)
1878 << " could not be inlined because it contains an irreducible loop";
David Sehrc757dec2016-11-04 15:48:34 -07001879 return false;
1880 }
1881 if (!block->GetLoopInformation()->HasExitEdge()) {
1882 // Don't inline methods with loops without exit, since they cause the
1883 // loop information to be computed incorrectly when updating after
1884 // inlining.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001885 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedLoopWithoutExit)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001886 << "Method " << callee_dex_file.PrettyMethod(method_index)
1887 << " could not be inlined because it contains a loop with no exit";
David Sehrc757dec2016-11-04 15:48:34 -07001888 return false;
1889 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001890 }
1891
1892 for (HInstructionIterator instr_it(block->GetInstructions());
1893 !instr_it.Done();
1894 instr_it.Advance()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001895 if (++number_of_instructions >= inlining_budget_) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001896 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedInstructionBudget)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001897 << "Method " << callee_dex_file.PrettyMethod(method_index)
1898 << " is not inlined because the outer method has reached"
1899 << " its instruction budget limit.";
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001900 return false;
1901 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001902 HInstruction* current = instr_it.Current();
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001903 if (current->NeedsEnvironment() &&
1904 (total_number_of_dex_registers_ >= kMaximumNumberOfCumulatedDexRegisters)) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001905 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedEnvironmentBudget)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001906 << "Method " << callee_dex_file.PrettyMethod(method_index)
1907 << " is not inlined because its caller has reached"
1908 << " its environment budget limit.";
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001909 return false;
1910 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001911
Nicolas Geoffrayfbdfa6d2017-02-03 10:43:13 +00001912 if (current->NeedsEnvironment() &&
1913 !CanEncodeInlinedMethodInStackMap(*caller_compilation_unit_.GetDexFile(),
1914 resolved_method)) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001915 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedStackMaps)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001916 << "Method " << callee_dex_file.PrettyMethod(method_index)
1917 << " could not be inlined because " << current->DebugName()
1918 << " needs an environment, is in a different dex file"
1919 << ", and cannot be encoded in the stack maps.";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001920 return false;
1921 }
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001922
Vladimir Markodc151b22015-10-15 18:02:30 +01001923 if (!same_dex_file && current->NeedsDexCacheOfDeclaringClass()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001924 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedDexCache)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001925 << "Method " << callee_dex_file.PrettyMethod(method_index)
1926 << " could not be inlined because " << current->DebugName()
1927 << " it is in a different dex file and requires access to the dex cache";
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001928 return false;
1929 }
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001930
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001931 if (current->IsUnresolvedStaticFieldGet() ||
1932 current->IsUnresolvedInstanceFieldGet() ||
1933 current->IsUnresolvedStaticFieldSet() ||
1934 current->IsUnresolvedInstanceFieldSet()) {
1935 // Entrypoint for unresolved fields does not handle inlined frames.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001936 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedUnresolvedEntrypoint)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001937 << "Method " << callee_dex_file.PrettyMethod(method_index)
1938 << " could not be inlined because it is using an unresolved"
1939 << " entrypoint";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001940 return false;
1941 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001942 }
1943 }
David Brazdil3f523062016-02-29 16:53:33 +00001944 DCHECK_EQ(caller_instruction_counter, graph_->GetCurrentInstructionId())
1945 << "No instructions can be added to the outer graph while inner graph is being built";
1946
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001947 // Inline the callee graph inside the caller graph.
David Brazdil3f523062016-02-29 16:53:33 +00001948 const int32_t callee_instruction_counter = callee_graph->GetCurrentInstructionId();
1949 graph_->SetCurrentInstructionId(callee_instruction_counter);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001950 *return_replacement = callee_graph->InlineInto(graph_, invoke_instruction);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001951 // Update our budget for other inlining attempts in `caller_graph`.
1952 total_number_of_instructions_ += number_of_instructions;
1953 UpdateInliningBudget();
David Brazdil3f523062016-02-29 16:53:33 +00001954
1955 DCHECK_EQ(callee_instruction_counter, callee_graph->GetCurrentInstructionId())
1956 << "No instructions can be added to the inner graph during inlining into the outer graph";
1957
Vladimir Marko438709f2017-02-23 18:56:13 +00001958 if (stats_ != nullptr) {
1959 DCHECK(inline_stats_ != nullptr);
1960 inline_stats_->AddTo(stats_);
1961 }
1962
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001963 return true;
1964}
Calin Juravle2e768302015-07-28 14:41:11 +00001965
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001966void HInliner::RunOptimizations(HGraph* callee_graph,
1967 const DexFile::CodeItem* code_item,
1968 const DexCompilationUnit& dex_compilation_unit) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001969 // Note: if the outermost_graph_ is being compiled OSR, we should not run any
1970 // optimization that could lead to a HDeoptimize. The following optimizations do not.
Vladimir Marko438709f2017-02-23 18:56:13 +00001971 HDeadCodeElimination dce(callee_graph, inline_stats_, "dead_code_elimination$inliner");
Andreas Gampeca620d72016-11-08 08:09:33 -08001972 HConstantFolding fold(callee_graph, "constant_folding$inliner");
Vladimir Marko28e012a2017-12-07 11:22:59 +00001973 HSharpening sharpening(callee_graph, codegen_, compiler_driver_);
Vladimir Marko65979462017-05-19 17:25:12 +01001974 InstructionSimplifier simplify(callee_graph, codegen_, compiler_driver_, inline_stats_);
Vladimir Marko438709f2017-02-23 18:56:13 +00001975 IntrinsicsRecognizer intrinsics(callee_graph, inline_stats_);
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001976
1977 HOptimization* optimizations[] = {
1978 &intrinsics,
1979 &sharpening,
1980 &simplify,
1981 &fold,
1982 &dce,
1983 };
1984
1985 for (size_t i = 0; i < arraysize(optimizations); ++i) {
1986 HOptimization* optimization = optimizations[i];
1987 optimization->Run();
1988 }
1989
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001990 // Bail early for pathological cases on the environment (for example recursive calls,
1991 // or too large environment).
1992 if (total_number_of_dex_registers_ >= kMaximumNumberOfCumulatedDexRegisters) {
1993 LOG_NOTE() << "Calls in " << callee_graph->GetArtMethod()->PrettyMethod()
1994 << " will not be inlined because the outer method has reached"
1995 << " its environment budget limit.";
1996 return;
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001997 }
1998
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001999 // Bail early if we know we already are over the limit.
2000 size_t number_of_instructions = CountNumberOfInstructions(callee_graph);
2001 if (number_of_instructions > inlining_budget_) {
2002 LOG_NOTE() << "Calls in " << callee_graph->GetArtMethod()->PrettyMethod()
2003 << " will not be inlined because the outer method has reached"
2004 << " its instruction budget limit. " << number_of_instructions;
2005 return;
2006 }
2007
Mathieu Chartier698ebbc2018-01-05 11:00:42 -08002008 CodeItemDataAccessor accessor(callee_graph->GetDexFile(), code_item);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002009 HInliner inliner(callee_graph,
2010 outermost_graph_,
2011 codegen_,
2012 outer_compilation_unit_,
2013 dex_compilation_unit,
2014 compiler_driver_,
2015 handles_,
2016 inline_stats_,
Mathieu Chartier808c7a52017-12-15 11:19:33 -08002017 total_number_of_dex_registers_ + accessor.RegistersSize(),
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002018 total_number_of_instructions_ + number_of_instructions,
2019 this,
2020 depth_ + 1);
2021 inliner.Run();
Roland Levillaina3aef2e2016-04-06 17:45:58 +01002022}
2023
David Brazdil94ab38f2016-06-21 17:48:19 +01002024static bool IsReferenceTypeRefinement(ReferenceTypeInfo declared_rti,
2025 bool declared_can_be_null,
2026 HInstruction* actual_obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002027 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdil94ab38f2016-06-21 17:48:19 +01002028 if (declared_can_be_null && !actual_obj->CanBeNull()) {
2029 return true;
2030 }
2031
2032 ReferenceTypeInfo actual_rti = actual_obj->GetReferenceTypeInfo();
2033 return (actual_rti.IsExact() && !declared_rti.IsExact()) ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00002034 declared_rti.IsStrictSupertypeOf(actual_rti);
David Brazdil94ab38f2016-06-21 17:48:19 +01002035}
2036
Vladimir Markob45528c2017-07-27 14:14:28 +01002037ReferenceTypeInfo HInliner::GetClassRTI(ObjPtr<mirror::Class> klass) {
David Brazdil94ab38f2016-06-21 17:48:19 +01002038 return ReferenceTypePropagation::IsAdmissible(klass)
2039 ? ReferenceTypeInfo::Create(handles_->NewHandle(klass))
2040 : graph_->GetInexactObjectRti();
2041}
2042
2043bool HInliner::ArgumentTypesMoreSpecific(HInvoke* invoke_instruction, ArtMethod* resolved_method) {
2044 // If this is an instance call, test whether the type of the `this` argument
2045 // is more specific than the class which declares the method.
2046 if (!resolved_method->IsStatic()) {
2047 if (IsReferenceTypeRefinement(GetClassRTI(resolved_method->GetDeclaringClass()),
2048 /* declared_can_be_null */ false,
2049 invoke_instruction->InputAt(0u))) {
2050 return true;
2051 }
2052 }
2053
David Brazdil94ab38f2016-06-21 17:48:19 +01002054 // Iterate over the list of parameter types and test whether any of the
2055 // actual inputs has a more specific reference type than the type declared in
2056 // the signature.
2057 const DexFile::TypeList* param_list = resolved_method->GetParameterTypeList();
2058 for (size_t param_idx = 0,
2059 input_idx = resolved_method->IsStatic() ? 0 : 1,
2060 e = (param_list == nullptr ? 0 : param_list->Size());
2061 param_idx < e;
2062 ++param_idx, ++input_idx) {
2063 HInstruction* input = invoke_instruction->InputAt(input_idx);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002064 if (input->GetType() == DataType::Type::kReference) {
Vladimir Markob45528c2017-07-27 14:14:28 +01002065 ObjPtr<mirror::Class> param_cls = resolved_method->LookupResolvedClassFromTypeIndex(
2066 param_list->GetTypeItem(param_idx).type_idx_);
David Brazdil94ab38f2016-06-21 17:48:19 +01002067 if (IsReferenceTypeRefinement(GetClassRTI(param_cls),
2068 /* declared_can_be_null */ true,
2069 input)) {
2070 return true;
2071 }
2072 }
2073 }
2074
2075 return false;
2076}
2077
2078bool HInliner::ReturnTypeMoreSpecific(HInvoke* invoke_instruction,
2079 HInstruction* return_replacement) {
Alex Light68289a52015-12-15 17:30:30 -08002080 // Check the integrity of reference types and run another type propagation if needed.
David Brazdil4833f5a2015-12-16 10:37:39 +00002081 if (return_replacement != nullptr) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002082 if (return_replacement->GetType() == DataType::Type::kReference) {
David Brazdil94ab38f2016-06-21 17:48:19 +01002083 // Test if the return type is a refinement of the declared return type.
2084 if (IsReferenceTypeRefinement(invoke_instruction->GetReferenceTypeInfo(),
2085 /* declared_can_be_null */ true,
2086 return_replacement)) {
2087 return true;
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00002088 } else if (return_replacement->IsInstanceFieldGet()) {
2089 HInstanceFieldGet* field_get = return_replacement->AsInstanceFieldGet();
2090 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2091 if (field_get->GetFieldInfo().GetField() ==
2092 class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0)) {
2093 return true;
2094 }
David Brazdil94ab38f2016-06-21 17:48:19 +01002095 }
2096 } else if (return_replacement->IsInstanceOf()) {
2097 // Inlining InstanceOf into an If may put a tighter bound on reference types.
2098 return true;
2099 }
2100 }
2101
2102 return false;
2103}
2104
2105void HInliner::FixUpReturnReferenceType(ArtMethod* resolved_method,
2106 HInstruction* return_replacement) {
2107 if (return_replacement != nullptr) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002108 if (return_replacement->GetType() == DataType::Type::kReference) {
David Brazdil4833f5a2015-12-16 10:37:39 +00002109 if (!return_replacement->GetReferenceTypeInfo().IsValid()) {
2110 // Make sure that we have a valid type for the return. We may get an invalid one when
2111 // we inline invokes with multiple branches and create a Phi for the result.
2112 // TODO: we could be more precise by merging the phi inputs but that requires
2113 // some functionality from the reference type propagation.
2114 DCHECK(return_replacement->IsPhi());
Vladimir Markob45528c2017-07-27 14:14:28 +01002115 ObjPtr<mirror::Class> cls = resolved_method->LookupResolvedReturnType();
David Brazdil94ab38f2016-06-21 17:48:19 +01002116 return_replacement->SetReferenceTypeInfo(GetClassRTI(cls));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01002117 }
Calin Juravlecdfed3d2015-10-26 14:05:01 +00002118 }
Calin Juravle2e768302015-07-28 14:41:11 +00002119 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002120}
2121
2122} // namespace art