blob: 18390cc4d495810d0ac3ab027ada99a69d12f1c7 [file] [log] [blame]
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "inliner.h"
18
Mathieu Chartiere401d142015-04-22 13:56:20 -070019#include "art_method-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070020#include "base/enums.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000021#include "builder.h"
22#include "class_linker.h"
23#include "constant_folding.h"
24#include "dead_code_elimination.h"
Andreas Gampeb95c74b2017-04-20 19:43:21 -070025#include "dex/inline_method_analyser.h"
Vladimir Markobe10e8e2016-01-22 12:09:44 +000026#include "dex/verified_method.h"
27#include "dex/verification_results.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000028#include "driver/compiler_driver-inl.h"
Calin Juravleec748352015-07-29 13:52:12 +010029#include "driver/compiler_options.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000030#include "driver/dex_compilation_unit.h"
31#include "instruction_simplifier.h"
Scott Wakelingd60a1af2015-07-22 14:32:44 +010032#include "intrinsics.h"
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +000033#include "jit/jit.h"
34#include "jit/jit_code_cache.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000035#include "mirror/class_loader.h"
36#include "mirror/dex_cache.h"
37#include "nodes.h"
Nicolas Geoffray335005e2015-06-25 10:01:47 +010038#include "optimizing_compiler.h"
Nicolas Geoffray454a4812015-06-09 10:37:32 +010039#include "reference_type_propagation.h"
Matthew Gharritye9288852016-07-14 14:08:16 -070040#include "register_allocator_linear_scan.h"
Vladimir Markodc151b22015-10-15 18:02:30 +010041#include "sharpening.h"
David Brazdil4833f5a2015-12-16 10:37:39 +000042#include "ssa_builder.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000043#include "ssa_phi_elimination.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070044#include "scoped_thread_state_change-inl.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000045#include "thread.h"
46
47namespace art {
48
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000049// Instruction limit to control memory.
50static constexpr size_t kMaximumNumberOfTotalInstructions = 1024;
51
52// Maximum number of instructions for considering a method small,
53// which we will always try to inline if the other non-instruction limits
54// are not reached.
55static constexpr size_t kMaximumNumberOfInstructionsForSmallMethod = 3;
Nicolas Geoffray5949fa02015-12-18 10:57:10 +000056
57// Limit the number of dex registers that we accumulate while inlining
58// to avoid creating large amount of nested environments.
Nicolas Geoffrayf81621e2017-06-07 13:18:03 +010059static constexpr size_t kMaximumNumberOfCumulatedDexRegisters = 32;
Nicolas Geoffray5949fa02015-12-18 10:57:10 +000060
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000061// Limit recursive call inlining, which do not benefit from too
62// much inlining compared to code locality.
63static constexpr size_t kMaximumNumberOfRecursiveCalls = 4;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -070064
Calin Juravlee2492d42017-03-20 11:42:13 -070065// Controls the use of inline caches in AOT mode.
Calin Juravle8af70892017-03-28 15:31:44 -070066static constexpr bool kUseAOTInlineCaches = true;
Calin Juravlee2492d42017-03-20 11:42:13 -070067
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000068// We check for line numbers to make sure the DepthString implementation
69// aligns the output nicely.
70#define LOG_INTERNAL(msg) \
71 static_assert(__LINE__ > 10, "Unhandled line number"); \
72 static_assert(__LINE__ < 10000, "Unhandled line number"); \
73 VLOG(compiler) << DepthString(__LINE__) << msg
74
75#define LOG_TRY() LOG_INTERNAL("Try inlinining call: ")
76#define LOG_NOTE() LOG_INTERNAL("Note: ")
77#define LOG_SUCCESS() LOG_INTERNAL("Success: ")
78#define LOG_FAIL(stat) MaybeRecordStat(stat); LOG_INTERNAL("Fail: ")
79#define LOG_FAIL_NO_STAT() LOG_INTERNAL("Fail: ")
80
81std::string HInliner::DepthString(int line) const {
82 std::string value;
83 // Indent according to the inlining depth.
84 size_t count = depth_;
85 // Line numbers get printed in the log, so add a space if the log's line is less
86 // than 1000, and two if less than 100. 10 cannot be reached as it's the copyright.
87 if (!kIsTargetBuild) {
88 if (line < 100) {
89 value += " ";
90 }
91 if (line < 1000) {
92 value += " ";
93 }
94 // Safeguard if this file reaches more than 10000 lines.
95 DCHECK_LT(line, 10000);
96 }
97 for (size_t i = 0; i < count; ++i) {
98 value += " ";
99 }
100 return value;
101}
102
103static size_t CountNumberOfInstructions(HGraph* graph) {
104 size_t number_of_instructions = 0;
105 for (HBasicBlock* block : graph->GetReversePostOrderSkipEntryBlock()) {
106 for (HInstructionIterator instr_it(block->GetInstructions());
107 !instr_it.Done();
108 instr_it.Advance()) {
109 ++number_of_instructions;
110 }
111 }
112 return number_of_instructions;
113}
114
115void HInliner::UpdateInliningBudget() {
116 if (total_number_of_instructions_ >= kMaximumNumberOfTotalInstructions) {
117 // Always try to inline small methods.
118 inlining_budget_ = kMaximumNumberOfInstructionsForSmallMethod;
119 } else {
120 inlining_budget_ = std::max(
121 kMaximumNumberOfInstructionsForSmallMethod,
122 kMaximumNumberOfTotalInstructions - total_number_of_instructions_);
123 }
124}
125
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000126void HInliner::Run() {
Nicolas Geoffraye50b8d22015-03-13 08:57:42 +0000127 if (graph_->IsDebuggable()) {
128 // For simplicity, we currently never inline when the graph is debuggable. This avoids
129 // doing some logic in the runtime to discover if a method could have been inlined.
130 return;
131 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000132
133 // Initialize the number of instructions for the method being compiled. Recursive calls
134 // to HInliner::Run have already updated the instruction count.
135 if (outermost_graph_ == graph_) {
136 total_number_of_instructions_ = CountNumberOfInstructions(graph_);
137 }
138
139 UpdateInliningBudget();
140 DCHECK_NE(total_number_of_instructions_, 0u);
141 DCHECK_NE(inlining_budget_, 0u);
142
Roland Levillain6c3af162017-04-27 11:18:56 +0100143 // If we're compiling with a core image (which is only used for
144 // test purposes), honor inlining directives in method names:
145 // - if a method's name contains the substring "$inline$", ensure
146 // that this method is actually inlined;
147 // - if a method's name contains the substring "$noinline$", do not
148 // inline that method.
Nicolas Geoffray08490b82017-07-18 12:58:10 +0100149 // We limit this to AOT compilation, as the JIT may or may not inline
150 // depending on the state of classes at runtime.
151 const bool honor_inlining_directives =
152 IsCompilingWithCoreImage() && Runtime::Current()->IsAotCompiler();
Roland Levillain6c3af162017-04-27 11:18:56 +0100153
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +0000154 // Keep a copy of all blocks when starting the visit.
155 ArenaVector<HBasicBlock*> blocks = graph_->GetReversePostOrder();
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100156 DCHECK(!blocks.empty());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +0000157 // Because we are changing the graph when inlining,
158 // we just iterate over the blocks of the outer method.
159 // This avoids doing the inlining work again on the inlined blocks.
160 for (HBasicBlock* block : blocks) {
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000161 for (HInstruction* instruction = block->GetFirstInstruction(); instruction != nullptr;) {
162 HInstruction* next = instruction->GetNext();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100163 HInvoke* call = instruction->AsInvoke();
Razvan A Lupusoru3e90a962015-03-27 13:44:44 -0700164 // As long as the call is not intrinsified, it is worth trying to inline.
165 if (call != nullptr && call->GetIntrinsic() == Intrinsics::kNone) {
Roland Levillain6c3af162017-04-27 11:18:56 +0100166 if (honor_inlining_directives) {
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000167 // Debugging case: directives in method names control or assert on inlining.
168 std::string callee_name = outer_compilation_unit_.GetDexFile()->PrettyMethod(
169 call->GetDexMethodIndex(), /* with_signature */ false);
170 // Tests prevent inlining by having $noinline$ in their method names.
171 if (callee_name.find("$noinline$") == std::string::npos) {
172 if (!TryInline(call)) {
173 bool should_have_inlined = (callee_name.find("$inline$") != std::string::npos);
174 CHECK(!should_have_inlined) << "Could not inline " << callee_name;
175 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000176 }
Guillaume "Vermeille" Sancheze918d382015-06-03 15:32:41 +0100177 } else {
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000178 // Normal case: try to inline.
179 TryInline(call);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000180 }
181 }
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000182 instruction = next;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000183 }
184 }
185}
186
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100187static bool IsMethodOrDeclaringClassFinal(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700188 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100189 return method->IsFinal() || method->GetDeclaringClass()->IsFinal();
190}
191
192/**
193 * Given the `resolved_method` looked up in the dex cache, try to find
194 * the actual runtime target of an interface or virtual call.
195 * Return nullptr if the runtime target cannot be proven.
196 */
197static ArtMethod* FindVirtualOrInterfaceTarget(HInvoke* invoke, ArtMethod* resolved_method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700198 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100199 if (IsMethodOrDeclaringClassFinal(resolved_method)) {
200 // No need to lookup further, the resolved method will be the target.
201 return resolved_method;
202 }
203
204 HInstruction* receiver = invoke->InputAt(0);
205 if (receiver->IsNullCheck()) {
206 // Due to multiple levels of inlining within the same pass, it might be that
207 // null check does not have the reference type of the actual receiver.
208 receiver = receiver->InputAt(0);
209 }
210 ReferenceTypeInfo info = receiver->GetReferenceTypeInfo();
Calin Juravle2e768302015-07-28 14:41:11 +0000211 DCHECK(info.IsValid()) << "Invalid RTI for " << receiver->DebugName();
212 if (!info.IsExact()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100213 // We currently only support inlining with known receivers.
214 // TODO: Remove this check, we should be able to inline final methods
215 // on unknown receivers.
216 return nullptr;
217 } else if (info.GetTypeHandle()->IsInterface()) {
218 // Statically knowing that the receiver has an interface type cannot
219 // help us find what is the target method.
220 return nullptr;
221 } else if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(info.GetTypeHandle().Get())) {
222 // The method that we're trying to call is not in the receiver's class or super classes.
223 return nullptr;
Nicolas Geoffrayab5327d2016-03-18 11:36:20 +0000224 } else if (info.GetTypeHandle()->IsErroneous()) {
225 // If the type is erroneous, do not go further, as we are going to query the vtable or
226 // imt table, that we can only safely do on non-erroneous classes.
227 return nullptr;
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100228 }
229
230 ClassLinker* cl = Runtime::Current()->GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700231 PointerSize pointer_size = cl->GetImagePointerSize();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100232 if (invoke->IsInvokeInterface()) {
233 resolved_method = info.GetTypeHandle()->FindVirtualMethodForInterface(
234 resolved_method, pointer_size);
235 } else {
236 DCHECK(invoke->IsInvokeVirtual());
237 resolved_method = info.GetTypeHandle()->FindVirtualMethodForVirtual(
238 resolved_method, pointer_size);
239 }
240
241 if (resolved_method == nullptr) {
242 // The information we had on the receiver was not enough to find
243 // the target method. Since we check above the exact type of the receiver,
244 // the only reason this can happen is an IncompatibleClassChangeError.
245 return nullptr;
Alex Light9139e002015-10-09 15:59:48 -0700246 } else if (!resolved_method->IsInvokable()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100247 // The information we had on the receiver was not enough to find
248 // the target method. Since we check above the exact type of the receiver,
249 // the only reason this can happen is an IncompatibleClassChangeError.
250 return nullptr;
251 } else if (IsMethodOrDeclaringClassFinal(resolved_method)) {
252 // A final method has to be the target method.
253 return resolved_method;
254 } else if (info.IsExact()) {
255 // If we found a method and the receiver's concrete type is statically
256 // known, we know for sure the target.
257 return resolved_method;
258 } else {
259 // Even if we did find a method, the receiver type was not enough to
260 // statically find the runtime target.
261 return nullptr;
262 }
263}
264
265static uint32_t FindMethodIndexIn(ArtMethod* method,
266 const DexFile& dex_file,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000267 uint32_t name_and_signature_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700268 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100269 if (IsSameDexFile(*method->GetDexFile(), dex_file)) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100270 return method->GetDexMethodIndex();
271 } else {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000272 return method->FindDexMethodIndexInOtherDexFile(dex_file, name_and_signature_index);
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100273 }
274}
275
Andreas Gampea5b09a62016-11-17 15:21:22 -0800276static dex::TypeIndex FindClassIndexIn(mirror::Class* cls,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000277 const DexCompilationUnit& compilation_unit)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700278 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000279 const DexFile& dex_file = *compilation_unit.GetDexFile();
Andreas Gampea5b09a62016-11-17 15:21:22 -0800280 dex::TypeIndex index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100281 if (cls->GetDexCache() == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700282 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000283 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800284 } else if (!cls->GetDexTypeIndex().IsValid()) {
David Sehr709b0702016-10-13 09:12:37 -0700285 DCHECK(cls->IsProxyClass()) << cls->PrettyClass();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100286 // TODO: deal with proxy classes.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100287 } else if (IsSameDexFile(cls->GetDexFile(), dex_file)) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000288 DCHECK_EQ(cls->GetDexCache(), compilation_unit.GetDexCache().Get());
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000289 index = cls->GetDexTypeIndex();
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100290 } else {
291 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000292 // We cannot guarantee the entry will resolve to the same class,
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100293 // as there may be different class loaders. So only return the index if it's
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000294 // the right class already resolved with the class loader.
295 if (index.IsValid()) {
296 ObjPtr<mirror::Class> resolved = ClassLinker::LookupResolvedType(
297 index, compilation_unit.GetDexCache().Get(), compilation_unit.GetClassLoader().Get());
298 if (resolved != cls) {
299 index = dex::TypeIndex::Invalid();
300 }
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100301 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100302 }
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000303
304 return index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100305}
306
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000307class ScopedProfilingInfoInlineUse {
308 public:
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000309 explicit ScopedProfilingInfoInlineUse(ArtMethod* method, Thread* self)
310 : method_(method),
311 self_(self),
312 // Fetch the profiling info ahead of using it. If it's null when fetching,
313 // we should not call JitCodeCache::DoneInlining.
314 profiling_info_(
315 Runtime::Current()->GetJit()->GetCodeCache()->NotifyCompilerUse(method, self)) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000316 }
317
318 ~ScopedProfilingInfoInlineUse() {
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000319 if (profiling_info_ != nullptr) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700320 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000321 DCHECK_EQ(profiling_info_, method_->GetProfilingInfo(pointer_size));
322 Runtime::Current()->GetJit()->GetCodeCache()->DoneCompilerUse(method_, self_);
323 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000324 }
325
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000326 ProfilingInfo* GetProfilingInfo() const { return profiling_info_; }
327
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000328 private:
329 ArtMethod* const method_;
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000330 Thread* const self_;
331 ProfilingInfo* const profiling_info_;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000332};
333
Calin Juravle13439f02017-02-21 01:17:21 -0800334HInliner::InlineCacheType HInliner::GetInlineCacheType(
335 const Handle<mirror::ObjectArray<mirror::Class>>& classes)
336 REQUIRES_SHARED(Locks::mutator_lock_) {
337 uint8_t number_of_types = 0;
338 for (; number_of_types < InlineCache::kIndividualCacheSize; ++number_of_types) {
339 if (classes->Get(number_of_types) == nullptr) {
340 break;
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000341 }
342 }
Calin Juravle13439f02017-02-21 01:17:21 -0800343
344 if (number_of_types == 0) {
345 return kInlineCacheUninitialized;
346 } else if (number_of_types == 1) {
347 return kInlineCacheMonomorphic;
348 } else if (number_of_types == InlineCache::kIndividualCacheSize) {
349 return kInlineCacheMegamorphic;
350 } else {
351 return kInlineCachePolymorphic;
352 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000353}
354
355static mirror::Class* GetMonomorphicType(Handle<mirror::ObjectArray<mirror::Class>> classes)
356 REQUIRES_SHARED(Locks::mutator_lock_) {
357 DCHECK(classes->Get(0) != nullptr);
358 return classes->Get(0);
359}
360
Mingyao Yang063fc772016-08-02 11:02:54 -0700361ArtMethod* HInliner::TryCHADevirtualization(ArtMethod* resolved_method) {
362 if (!resolved_method->HasSingleImplementation()) {
363 return nullptr;
364 }
365 if (Runtime::Current()->IsAotCompiler()) {
366 // No CHA-based devirtulization for AOT compiler (yet).
367 return nullptr;
368 }
369 if (outermost_graph_->IsCompilingOsr()) {
370 // We do not support HDeoptimize in OSR methods.
371 return nullptr;
372 }
Mingyao Yange8fcd012017-01-20 10:43:30 -0800373 PointerSize pointer_size = caller_compilation_unit_.GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +0000374 ArtMethod* single_impl = resolved_method->GetSingleImplementation(pointer_size);
375 if (single_impl == nullptr) {
376 return nullptr;
377 }
378 if (single_impl->IsProxyMethod()) {
379 // Proxy method is a generic invoker that's not worth
380 // devirtualizing/inlining. It also causes issues when the proxy
381 // method is in another dex file if we try to rewrite invoke-interface to
382 // invoke-virtual because a proxy method doesn't have a real dex file.
383 return nullptr;
384 }
Nicolas Geoffray8e33e842017-04-03 16:55:16 +0100385 if (!single_impl->GetDeclaringClass()->IsResolved()) {
386 // There's a race with the class loading, which updates the CHA info
387 // before setting the class to resolved. So we just bail for this
388 // rare occurence.
389 return nullptr;
390 }
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +0000391 return single_impl;
Mingyao Yang063fc772016-08-02 11:02:54 -0700392}
393
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700394bool HInliner::TryInline(HInvoke* invoke_instruction) {
Orion Hodsonac141392017-01-13 11:53:47 +0000395 if (invoke_instruction->IsInvokeUnresolved() ||
396 invoke_instruction->IsInvokePolymorphic()) {
397 return false; // Don't bother to move further if we know the method is unresolved or an
398 // invoke-polymorphic.
Calin Juravle175dc732015-08-25 15:42:32 +0100399 }
400
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000401 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100402 uint32_t method_index = invoke_instruction->GetDexMethodIndex();
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000403 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000404 LOG_TRY() << caller_dex_file.PrettyMethod(method_index);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000405
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100406 ArtMethod* resolved_method = invoke_instruction->GetResolvedMethod();
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100407 if (resolved_method == nullptr) {
408 DCHECK(invoke_instruction->IsInvokeStaticOrDirect());
409 DCHECK(invoke_instruction->AsInvokeStaticOrDirect()->IsStringInit());
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000410 LOG_FAIL_NO_STAT() << "Not inlining a String.<init> method";
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100411 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000412 }
413 ArtMethod* actual_method = nullptr;
414
415 if (invoke_instruction->IsInvokeStaticOrDirect()) {
Andreas Gampefd2140f2015-12-23 16:30:44 -0800416 actual_method = resolved_method;
Vladimir Marko58155012015-08-19 12:49:41 +0000417 } else {
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100418 // Check if we can statically find the method.
419 actual_method = FindVirtualOrInterfaceTarget(invoke_instruction, resolved_method);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000420 }
421
Mingyao Yang063fc772016-08-02 11:02:54 -0700422 bool cha_devirtualize = false;
423 if (actual_method == nullptr) {
424 ArtMethod* method = TryCHADevirtualization(resolved_method);
425 if (method != nullptr) {
426 cha_devirtualize = true;
427 actual_method = method;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000428 LOG_NOTE() << "Try CHA-based inlining of " << actual_method->PrettyMethod();
Mingyao Yang063fc772016-08-02 11:02:54 -0700429 }
430 }
431
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100432 if (actual_method != nullptr) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700433 bool result = TryInlineAndReplace(invoke_instruction,
434 actual_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000435 ReferenceTypeInfo::CreateInvalid(),
Mingyao Yang063fc772016-08-02 11:02:54 -0700436 /* do_rtp */ true,
437 cha_devirtualize);
Calin Juravle69158982016-03-16 11:53:41 +0000438 if (result && !invoke_instruction->IsInvokeStaticOrDirect()) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700439 if (cha_devirtualize) {
440 // Add dependency due to devirtulization. We've assumed resolved_method
441 // has single implementation.
442 outermost_graph_->AddCHASingleImplementationDependency(resolved_method);
443 MaybeRecordStat(kCHAInline);
444 } else {
445 MaybeRecordStat(kInlinedInvokeVirtualOrInterface);
446 }
Calin Juravle69158982016-03-16 11:53:41 +0000447 }
448 return result;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100449 }
Andreas Gampefd2140f2015-12-23 16:30:44 -0800450 DCHECK(!invoke_instruction->IsInvokeStaticOrDirect());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100451
Calin Juravle13439f02017-02-21 01:17:21 -0800452 // Try using inline caches.
453 return TryInlineFromInlineCache(caller_dex_file, invoke_instruction, resolved_method);
454}
455
456static Handle<mirror::ObjectArray<mirror::Class>> AllocateInlineCacheHolder(
457 const DexCompilationUnit& compilation_unit,
458 StackHandleScope<1>* hs)
459 REQUIRES_SHARED(Locks::mutator_lock_) {
460 Thread* self = Thread::Current();
461 ClassLinker* class_linker = compilation_unit.GetClassLinker();
462 Handle<mirror::ObjectArray<mirror::Class>> inline_cache = hs->NewHandle(
463 mirror::ObjectArray<mirror::Class>::Alloc(
464 self,
465 class_linker->GetClassRoot(ClassLinker::kClassArrayClass),
466 InlineCache::kIndividualCacheSize));
467 if (inline_cache == nullptr) {
468 // We got an OOME. Just clear the exception, and don't inline.
469 DCHECK(self->IsExceptionPending());
470 self->ClearException();
471 VLOG(compiler) << "Out of memory in the compiler when trying to inline";
472 }
473 return inline_cache;
474}
475
Calin Juravleaf44e6c2017-05-23 14:24:55 -0700476bool HInliner::UseOnlyPolymorphicInliningWithNoDeopt() {
477 // If we are compiling AOT or OSR, pretend the call using inline caches is polymorphic and
478 // do not generate a deopt.
479 //
480 // For AOT:
481 // Generating a deopt does not ensure that we will actually capture the new types;
482 // and the danger is that we could be stuck in a loop with "forever" deoptimizations.
483 // Take for example the following scenario:
484 // - we capture the inline cache in one run
485 // - the next run, we deoptimize because we miss a type check, but the method
486 // never becomes hot again
487 // In this case, the inline cache will not be updated in the profile and the AOT code
488 // will keep deoptimizing.
489 // Another scenario is if we use profile compilation for a process which is not allowed
490 // to JIT (e.g. system server). If we deoptimize we will run interpreted code for the
491 // rest of the lifetime.
492 // TODO(calin):
493 // This is a compromise because we will most likely never update the inline cache
494 // in the profile (unless there's another reason to deopt). So we might be stuck with
495 // a sub-optimal inline cache.
496 // We could be smarter when capturing inline caches to mitigate this.
497 // (e.g. by having different thresholds for new and old methods).
498 //
499 // For OSR:
500 // We may come from the interpreter and it may have seen different receiver types.
501 return Runtime::Current()->IsAotCompiler() || outermost_graph_->IsCompilingOsr();
502}
Calin Juravle13439f02017-02-21 01:17:21 -0800503bool HInliner::TryInlineFromInlineCache(const DexFile& caller_dex_file,
504 HInvoke* invoke_instruction,
505 ArtMethod* resolved_method)
506 REQUIRES_SHARED(Locks::mutator_lock_) {
Calin Juravlee2492d42017-03-20 11:42:13 -0700507 if (Runtime::Current()->IsAotCompiler() && !kUseAOTInlineCaches) {
508 return false;
509 }
510
Calin Juravle13439f02017-02-21 01:17:21 -0800511 StackHandleScope<1> hs(Thread::Current());
512 Handle<mirror::ObjectArray<mirror::Class>> inline_cache;
513 InlineCacheType inline_cache_type = Runtime::Current()->IsAotCompiler()
514 ? GetInlineCacheAOT(caller_dex_file, invoke_instruction, &hs, &inline_cache)
515 : GetInlineCacheJIT(invoke_instruction, &hs, &inline_cache);
516
517 switch (inline_cache_type) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000518 case kInlineCacheNoData: {
519 LOG_FAIL_NO_STAT()
520 << "Interface or virtual call to "
521 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
522 << " could not be statically determined";
Calin Juravle13439f02017-02-21 01:17:21 -0800523 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000524 }
Calin Juravle13439f02017-02-21 01:17:21 -0800525
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000526 case kInlineCacheUninitialized: {
527 LOG_FAIL_NO_STAT()
528 << "Interface or virtual call to "
529 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
530 << " is not hit and not inlined";
531 return false;
532 }
533
534 case kInlineCacheMonomorphic: {
Calin Juravle13439f02017-02-21 01:17:21 -0800535 MaybeRecordStat(kMonomorphicCall);
Calin Juravleaf44e6c2017-05-23 14:24:55 -0700536 if (UseOnlyPolymorphicInliningWithNoDeopt()) {
Calin Juravle13439f02017-02-21 01:17:21 -0800537 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000538 } else {
Calin Juravle13439f02017-02-21 01:17:21 -0800539 return TryInlineMonomorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000540 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000541 }
Calin Juravle13439f02017-02-21 01:17:21 -0800542
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000543 case kInlineCachePolymorphic: {
Calin Juravle13439f02017-02-21 01:17:21 -0800544 MaybeRecordStat(kPolymorphicCall);
545 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000546 }
Calin Juravle13439f02017-02-21 01:17:21 -0800547
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000548 case kInlineCacheMegamorphic: {
549 LOG_FAIL_NO_STAT()
550 << "Interface or virtual call to "
551 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
552 << " is megamorphic and not inlined";
Calin Juravle13439f02017-02-21 01:17:21 -0800553 MaybeRecordStat(kMegamorphicCall);
554 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000555 }
Calin Juravle13439f02017-02-21 01:17:21 -0800556
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000557 case kInlineCacheMissingTypes: {
558 LOG_FAIL_NO_STAT()
559 << "Interface or virtual call to "
560 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
561 << " is missing types and not inlined";
Calin Juravle13439f02017-02-21 01:17:21 -0800562 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000563 }
Calin Juravle13439f02017-02-21 01:17:21 -0800564 }
565 UNREACHABLE();
566}
567
568HInliner::InlineCacheType HInliner::GetInlineCacheJIT(
569 HInvoke* invoke_instruction,
570 StackHandleScope<1>* hs,
571 /*out*/Handle<mirror::ObjectArray<mirror::Class>>* inline_cache)
572 REQUIRES_SHARED(Locks::mutator_lock_) {
573 DCHECK(Runtime::Current()->UseJitCompilation());
574
575 ArtMethod* caller = graph_->GetArtMethod();
576 // Under JIT, we should always know the caller.
577 DCHECK(caller != nullptr);
578 ScopedProfilingInfoInlineUse spiis(caller, Thread::Current());
579 ProfilingInfo* profiling_info = spiis.GetProfilingInfo();
580
581 if (profiling_info == nullptr) {
582 return kInlineCacheNoData;
583 }
584
585 *inline_cache = AllocateInlineCacheHolder(caller_compilation_unit_, hs);
586 if (inline_cache->Get() == nullptr) {
587 // We can't extract any data if we failed to allocate;
588 return kInlineCacheNoData;
589 } else {
590 Runtime::Current()->GetJit()->GetCodeCache()->CopyInlineCacheInto(
591 *profiling_info->GetInlineCache(invoke_instruction->GetDexPc()),
592 *inline_cache);
593 return GetInlineCacheType(*inline_cache);
594 }
595}
596
597HInliner::InlineCacheType HInliner::GetInlineCacheAOT(
598 const DexFile& caller_dex_file,
599 HInvoke* invoke_instruction,
600 StackHandleScope<1>* hs,
601 /*out*/Handle<mirror::ObjectArray<mirror::Class>>* inline_cache)
602 REQUIRES_SHARED(Locks::mutator_lock_) {
603 DCHECK(Runtime::Current()->IsAotCompiler());
604 const ProfileCompilationInfo* pci = compiler_driver_->GetProfileCompilationInfo();
605 if (pci == nullptr) {
606 return kInlineCacheNoData;
607 }
608
Calin Juravlecc3171a2017-05-19 16:47:53 -0700609 std::unique_ptr<ProfileCompilationInfo::OfflineProfileMethodInfo> offline_profile =
610 pci->GetMethod(caller_dex_file.GetLocation(),
611 caller_dex_file.GetLocationChecksum(),
612 caller_compilation_unit_.GetDexMethodIndex());
613 if (offline_profile == nullptr) {
Calin Juravle13439f02017-02-21 01:17:21 -0800614 return kInlineCacheNoData; // no profile information for this invocation.
615 }
616
617 *inline_cache = AllocateInlineCacheHolder(caller_compilation_unit_, hs);
618 if (inline_cache == nullptr) {
619 // We can't extract any data if we failed to allocate;
620 return kInlineCacheNoData;
621 } else {
622 return ExtractClassesFromOfflineProfile(invoke_instruction,
Calin Juravlecc3171a2017-05-19 16:47:53 -0700623 *(offline_profile.get()),
Calin Juravle13439f02017-02-21 01:17:21 -0800624 *inline_cache);
625 }
626}
627
628HInliner::InlineCacheType HInliner::ExtractClassesFromOfflineProfile(
629 const HInvoke* invoke_instruction,
630 const ProfileCompilationInfo::OfflineProfileMethodInfo& offline_profile,
631 /*out*/Handle<mirror::ObjectArray<mirror::Class>> inline_cache)
632 REQUIRES_SHARED(Locks::mutator_lock_) {
Calin Juravlee6f87cc2017-05-24 17:41:05 -0700633 const auto it = offline_profile.inline_caches->find(invoke_instruction->GetDexPc());
634 if (it == offline_profile.inline_caches->end()) {
Calin Juravle13439f02017-02-21 01:17:21 -0800635 return kInlineCacheUninitialized;
636 }
637
638 const ProfileCompilationInfo::DexPcData& dex_pc_data = it->second;
639
640 if (dex_pc_data.is_missing_types) {
641 return kInlineCacheMissingTypes;
642 }
643 if (dex_pc_data.is_megamorphic) {
644 return kInlineCacheMegamorphic;
645 }
646
647 DCHECK_LE(dex_pc_data.classes.size(), InlineCache::kIndividualCacheSize);
648 Thread* self = Thread::Current();
649 // We need to resolve the class relative to the containing dex file.
650 // So first, build a mapping from the index of dex file in the profile to
651 // its dex cache. This will avoid repeating the lookup when walking over
652 // the inline cache types.
653 std::vector<ObjPtr<mirror::DexCache>> dex_profile_index_to_dex_cache(
654 offline_profile.dex_references.size());
655 for (size_t i = 0; i < offline_profile.dex_references.size(); i++) {
656 bool found = false;
657 for (const DexFile* dex_file : compiler_driver_->GetDexFilesForOatFile()) {
658 if (offline_profile.dex_references[i].MatchesDex(dex_file)) {
659 dex_profile_index_to_dex_cache[i] =
660 caller_compilation_unit_.GetClassLinker()->FindDexCache(self, *dex_file);
661 found = true;
662 }
663 }
664 if (!found) {
665 VLOG(compiler) << "Could not find profiled dex file: "
666 << offline_profile.dex_references[i].dex_location;
667 return kInlineCacheMissingTypes;
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100668 }
669 }
670
Calin Juravle13439f02017-02-21 01:17:21 -0800671 // Walk over the classes and resolve them. If we cannot find a type we return
672 // kInlineCacheMissingTypes.
673 int ic_index = 0;
674 for (const ProfileCompilationInfo::ClassReference& class_ref : dex_pc_data.classes) {
675 ObjPtr<mirror::DexCache> dex_cache =
676 dex_profile_index_to_dex_cache[class_ref.dex_profile_index];
677 DCHECK(dex_cache != nullptr);
Calin Juravle08556882017-05-26 16:40:45 -0700678
679 if (!dex_cache->GetDexFile()->IsTypeIndexValid(class_ref.type_index)) {
680 VLOG(compiler) << "Profile data corrupt: type index " << class_ref.type_index
681 << "is invalid in location" << dex_cache->GetDexFile()->GetLocation();
682 return kInlineCacheNoData;
683 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000684 ObjPtr<mirror::Class> clazz = ClassLinker::LookupResolvedType(
685 class_ref.type_index,
686 dex_cache,
687 caller_compilation_unit_.GetClassLoader().Get());
Calin Juravle13439f02017-02-21 01:17:21 -0800688 if (clazz != nullptr) {
689 inline_cache->Set(ic_index++, clazz);
690 } else {
691 VLOG(compiler) << "Could not resolve class from inline cache in AOT mode "
692 << caller_compilation_unit_.GetDexFile()->PrettyMethod(
693 invoke_instruction->GetDexMethodIndex()) << " : "
694 << caller_compilation_unit_
695 .GetDexFile()->StringByTypeIdx(class_ref.type_index);
696 return kInlineCacheMissingTypes;
697 }
698 }
699 return GetInlineCacheType(inline_cache);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100700}
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000701
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000702HInstanceFieldGet* HInliner::BuildGetReceiverClass(ClassLinker* class_linker,
703 HInstruction* receiver,
704 uint32_t dex_pc) const {
705 ArtField* field = class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0);
706 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000707 HInstanceFieldGet* result = new (graph_->GetArena()) HInstanceFieldGet(
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000708 receiver,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000709 field,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000710 Primitive::kPrimNot,
711 field->GetOffset(),
712 field->IsVolatile(),
713 field->GetDexFieldIndex(),
714 field->GetDeclaringClass()->GetDexClassDefIndex(),
715 *field->GetDexFile(),
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000716 dex_pc);
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000717 // The class of a field is effectively final, and does not have any memory dependencies.
718 result->SetSideEffects(SideEffects::None());
719 return result;
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000720}
721
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000722static ArtMethod* ResolveMethodFromInlineCache(Handle<mirror::Class> klass,
723 ArtMethod* resolved_method,
724 HInstruction* invoke_instruction,
725 PointerSize pointer_size)
726 REQUIRES_SHARED(Locks::mutator_lock_) {
727 if (Runtime::Current()->IsAotCompiler()) {
728 // We can get unrelated types when working with profiles (corruption,
729 // systme updates, or anyone can write to it). So first check if the class
730 // actually implements the declaring class of the method that is being
731 // called in bytecode.
732 // Note: the lookup methods used below require to have assignable types.
733 if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(klass.Get())) {
734 return nullptr;
735 }
736 }
737
738 if (invoke_instruction->IsInvokeInterface()) {
739 resolved_method = klass->FindVirtualMethodForInterface(resolved_method, pointer_size);
740 } else {
741 DCHECK(invoke_instruction->IsInvokeVirtual());
742 resolved_method = klass->FindVirtualMethodForVirtual(resolved_method, pointer_size);
743 }
744 DCHECK(resolved_method != nullptr);
745 return resolved_method;
746}
747
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100748bool HInliner::TryInlineMonomorphicCall(HInvoke* invoke_instruction,
749 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000750 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000751 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
752 << invoke_instruction->DebugName();
753
Andreas Gampea5b09a62016-11-17 15:21:22 -0800754 dex::TypeIndex class_index = FindClassIndexIn(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000755 GetMonomorphicType(classes), caller_compilation_unit_);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800756 if (!class_index.IsValid()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000757 LOG_FAIL(kNotInlinedDexCache)
758 << "Call to " << ArtMethod::PrettyMethod(resolved_method)
759 << " from inline cache is not inlined because its class is not"
760 << " accessible to the caller";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100761 return false;
762 }
763
764 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700765 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000766 Handle<mirror::Class> monomorphic_type = handles_->NewHandle(GetMonomorphicType(classes));
767 resolved_method = ResolveMethodFromInlineCache(
768 monomorphic_type, resolved_method, invoke_instruction, pointer_size);
769
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000770 LOG_NOTE() << "Try inline monomorphic call to " << resolved_method->PrettyMethod();
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000771 if (resolved_method == nullptr) {
772 // Bogus AOT profile, bail.
773 DCHECK(Runtime::Current()->IsAotCompiler());
774 return false;
775 }
776
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100777 HInstruction* receiver = invoke_instruction->InputAt(0);
778 HInstruction* cursor = invoke_instruction->GetPrevious();
779 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Mingyao Yang063fc772016-08-02 11:02:54 -0700780 if (!TryInlineAndReplace(invoke_instruction,
781 resolved_method,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000782 ReferenceTypeInfo::Create(monomorphic_type, /* is_exact */ true),
Mingyao Yang063fc772016-08-02 11:02:54 -0700783 /* do_rtp */ false,
784 /* cha_devirtualize */ false)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100785 return false;
786 }
787
788 // We successfully inlined, now add a guard.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000789 AddTypeGuard(receiver,
790 cursor,
791 bb_cursor,
792 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000793 monomorphic_type,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000794 invoke_instruction,
795 /* with_deoptimization */ true);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100796
797 // Run type propagation to get the guard typed, and eventually propagate the
798 // type of the receiver.
Vladimir Marko456307a2016-04-19 14:12:13 +0000799 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000800 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +0000801 outer_compilation_unit_.GetDexCache(),
802 handles_,
803 /* is_first_run */ false);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100804 rtp_fixup.Run();
805
806 MaybeRecordStat(kInlinedMonomorphicCall);
807 return true;
808}
809
Mingyao Yang063fc772016-08-02 11:02:54 -0700810void HInliner::AddCHAGuard(HInstruction* invoke_instruction,
811 uint32_t dex_pc,
812 HInstruction* cursor,
813 HBasicBlock* bb_cursor) {
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800814 HShouldDeoptimizeFlag* deopt_flag = new (graph_->GetArena())
815 HShouldDeoptimizeFlag(graph_->GetArena(), dex_pc);
816 HInstruction* compare = new (graph_->GetArena()) HNotEqual(
Mingyao Yang063fc772016-08-02 11:02:54 -0700817 deopt_flag, graph_->GetIntConstant(0, dex_pc));
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000818 HInstruction* deopt = new (graph_->GetArena()) HDeoptimize(
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +0100819 graph_->GetArena(), compare, DeoptimizationKind::kCHA, dex_pc);
Mingyao Yang063fc772016-08-02 11:02:54 -0700820
821 if (cursor != nullptr) {
822 bb_cursor->InsertInstructionAfter(deopt_flag, cursor);
823 } else {
824 bb_cursor->InsertInstructionBefore(deopt_flag, bb_cursor->GetFirstInstruction());
825 }
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800826 bb_cursor->InsertInstructionAfter(compare, deopt_flag);
827 bb_cursor->InsertInstructionAfter(deopt, compare);
828
829 // Add receiver as input to aid CHA guard optimization later.
830 deopt_flag->AddInput(invoke_instruction->InputAt(0));
831 DCHECK_EQ(deopt_flag->InputCount(), 1u);
Mingyao Yang063fc772016-08-02 11:02:54 -0700832 deopt->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800833 outermost_graph_->IncrementNumberOfCHAGuards();
Mingyao Yang063fc772016-08-02 11:02:54 -0700834}
835
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000836HInstruction* HInliner::AddTypeGuard(HInstruction* receiver,
837 HInstruction* cursor,
838 HBasicBlock* bb_cursor,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800839 dex::TypeIndex class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000840 Handle<mirror::Class> klass,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000841 HInstruction* invoke_instruction,
842 bool with_deoptimization) {
843 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
844 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
845 class_linker, receiver, invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000846 if (cursor != nullptr) {
847 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
848 } else {
849 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
850 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000851
852 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Calin Juravle07f01df2017-04-28 19:58:01 -0700853 bool is_referrer;
854 ArtMethod* outermost_art_method = outermost_graph_->GetArtMethod();
855 if (outermost_art_method == nullptr) {
856 DCHECK(Runtime::Current()->IsAotCompiler());
857 // We are in AOT mode and we don't have an ART method to determine
858 // if the inlined method belongs to the referrer. Assume it doesn't.
859 is_referrer = false;
860 } else {
861 is_referrer = klass.Get() == outermost_art_method->GetDeclaringClass();
862 }
863
Nicolas Geoffray56876342016-12-16 16:09:08 +0000864 // Note that we will just compare the classes, so we don't need Java semantics access checks.
865 // Note that the type index and the dex file are relative to the method this type guard is
866 // inlined into.
867 HLoadClass* load_class = new (graph_->GetArena()) HLoadClass(graph_->GetCurrentMethod(),
868 class_index,
869 caller_dex_file,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000870 klass,
Nicolas Geoffray56876342016-12-16 16:09:08 +0000871 is_referrer,
872 invoke_instruction->GetDexPc(),
873 /* needs_access_check */ false);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000874 HLoadClass::LoadKind kind = HSharpening::ComputeLoadClassKind(
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000875 load_class, codegen_, compiler_driver_, caller_compilation_unit_);
876 DCHECK(kind != HLoadClass::LoadKind::kInvalid)
877 << "We should always be able to reference a class for inline caches";
878 // Insert before setting the kind, as setting the kind affects the inputs.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000879 bb_cursor->InsertInstructionAfter(load_class, receiver_class);
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000880 load_class->SetLoadKind(kind);
Calin Juravle13439f02017-02-21 01:17:21 -0800881 // In AOT mode, we will most likely load the class from BSS, which will involve a call
882 // to the runtime. In this case, the load instruction will need an environment so copy
883 // it from the invoke instruction.
884 if (load_class->NeedsEnvironment()) {
885 DCHECK(Runtime::Current()->IsAotCompiler());
886 load_class->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
887 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000888
Nicolas Geoffray56876342016-12-16 16:09:08 +0000889 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(load_class, receiver_class);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000890 bb_cursor->InsertInstructionAfter(compare, load_class);
891 if (with_deoptimization) {
892 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000893 graph_->GetArena(),
894 compare,
895 receiver,
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +0100896 Runtime::Current()->IsAotCompiler()
897 ? DeoptimizationKind::kAotInlineCache
898 : DeoptimizationKind::kJitInlineCache,
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000899 invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000900 bb_cursor->InsertInstructionAfter(deoptimize, compare);
901 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000902 DCHECK_EQ(invoke_instruction->InputAt(0), receiver);
903 receiver->ReplaceUsesDominatedBy(deoptimize, deoptimize);
904 deoptimize->SetReferenceTypeInfo(receiver->GetReferenceTypeInfo());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000905 }
906 return compare;
907}
908
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000909bool HInliner::TryInlinePolymorphicCall(HInvoke* invoke_instruction,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100910 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000911 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000912 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
913 << invoke_instruction->DebugName();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000914
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000915 if (TryInlinePolymorphicCallToSameTarget(invoke_instruction, resolved_method, classes)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000916 return true;
917 }
918
919 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700920 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000921
922 bool all_targets_inlined = true;
923 bool one_target_inlined = false;
924 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000925 if (classes->Get(i) == nullptr) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000926 break;
927 }
928 ArtMethod* method = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000929
930 Handle<mirror::Class> handle = handles_->NewHandle(classes->Get(i));
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000931 method = ResolveMethodFromInlineCache(
932 handle, resolved_method, invoke_instruction, pointer_size);
933 if (method == nullptr) {
934 DCHECK(Runtime::Current()->IsAotCompiler());
935 // AOT profile is bogus. This loop expects to iterate over all entries,
936 // so just just continue.
937 all_targets_inlined = false;
938 continue;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000939 }
940
941 HInstruction* receiver = invoke_instruction->InputAt(0);
942 HInstruction* cursor = invoke_instruction->GetPrevious();
943 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
944
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000945 dex::TypeIndex class_index = FindClassIndexIn(handle.Get(), caller_compilation_unit_);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000946 HInstruction* return_replacement = nullptr;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000947 LOG_NOTE() << "Try inline polymorphic call to " << method->PrettyMethod();
Andreas Gampea5b09a62016-11-17 15:21:22 -0800948 if (!class_index.IsValid() ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000949 !TryBuildAndInline(invoke_instruction,
950 method,
951 ReferenceTypeInfo::Create(handle, /* is_exact */ true),
952 &return_replacement)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000953 all_targets_inlined = false;
954 } else {
955 one_target_inlined = true;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000956
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000957 LOG_SUCCESS() << "Polymorphic call to " << ArtMethod::PrettyMethod(resolved_method)
958 << " has inlined " << ArtMethod::PrettyMethod(method);
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000959
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000960 // If we have inlined all targets before, and this receiver is the last seen,
961 // we deoptimize instead of keeping the original invoke instruction.
Calin Juravleaf44e6c2017-05-23 14:24:55 -0700962 bool deoptimize = !UseOnlyPolymorphicInliningWithNoDeopt() &&
963 all_targets_inlined &&
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000964 (i != InlineCache::kIndividualCacheSize - 1) &&
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000965 (classes->Get(i + 1) == nullptr);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100966
Nicolas Geoffray56876342016-12-16 16:09:08 +0000967 HInstruction* compare = AddTypeGuard(receiver,
968 cursor,
969 bb_cursor,
970 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000971 handle,
Nicolas Geoffray56876342016-12-16 16:09:08 +0000972 invoke_instruction,
973 deoptimize);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000974 if (deoptimize) {
975 if (return_replacement != nullptr) {
976 invoke_instruction->ReplaceWith(return_replacement);
977 }
978 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
979 // Because the inline cache data can be populated concurrently, we force the end of the
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000980 // iteration. Otherwise, we could see a new receiver type.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000981 break;
982 } else {
983 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
984 }
985 }
986 }
987
988 if (!one_target_inlined) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000989 LOG_FAIL_NO_STAT()
990 << "Call to " << ArtMethod::PrettyMethod(resolved_method)
991 << " from inline cache is not inlined because none"
992 << " of its targets could be inlined";
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000993 return false;
994 }
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000995
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000996 MaybeRecordStat(kInlinedPolymorphicCall);
997
998 // Run type propagation to get the guards typed.
Vladimir Marko456307a2016-04-19 14:12:13 +0000999 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001000 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +00001001 outer_compilation_unit_.GetDexCache(),
1002 handles_,
1003 /* is_first_run */ false);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001004 rtp_fixup.Run();
1005 return true;
1006}
1007
1008void HInliner::CreateDiamondPatternForPolymorphicInline(HInstruction* compare,
1009 HInstruction* return_replacement,
1010 HInstruction* invoke_instruction) {
1011 uint32_t dex_pc = invoke_instruction->GetDexPc();
1012 HBasicBlock* cursor_block = compare->GetBlock();
1013 HBasicBlock* original_invoke_block = invoke_instruction->GetBlock();
1014 ArenaAllocator* allocator = graph_->GetArena();
1015
1016 // Spit the block after the compare: `cursor_block` will now be the start of the diamond,
1017 // and the returned block is the start of the then branch (that could contain multiple blocks).
1018 HBasicBlock* then = cursor_block->SplitAfterForInlining(compare);
1019
1020 // Split the block containing the invoke before and after the invoke. The returned block
1021 // of the split before will contain the invoke and will be the otherwise branch of
1022 // the diamond. The returned block of the split after will be the merge block
1023 // of the diamond.
1024 HBasicBlock* end_then = invoke_instruction->GetBlock();
1025 HBasicBlock* otherwise = end_then->SplitBeforeForInlining(invoke_instruction);
1026 HBasicBlock* merge = otherwise->SplitAfterForInlining(invoke_instruction);
1027
1028 // If the methods we are inlining return a value, we create a phi in the merge block
1029 // that will have the `invoke_instruction and the `return_replacement` as inputs.
1030 if (return_replacement != nullptr) {
1031 HPhi* phi = new (allocator) HPhi(
1032 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke_instruction->GetType()), dex_pc);
1033 merge->AddPhi(phi);
1034 invoke_instruction->ReplaceWith(phi);
1035 phi->AddInput(return_replacement);
1036 phi->AddInput(invoke_instruction);
1037 }
1038
1039 // Add the control flow instructions.
1040 otherwise->AddInstruction(new (allocator) HGoto(dex_pc));
1041 end_then->AddInstruction(new (allocator) HGoto(dex_pc));
1042 cursor_block->AddInstruction(new (allocator) HIf(compare, dex_pc));
1043
1044 // Add the newly created blocks to the graph.
1045 graph_->AddBlock(then);
1046 graph_->AddBlock(otherwise);
1047 graph_->AddBlock(merge);
1048
1049 // Set up successor (and implictly predecessor) relations.
1050 cursor_block->AddSuccessor(otherwise);
1051 cursor_block->AddSuccessor(then);
1052 end_then->AddSuccessor(merge);
1053 otherwise->AddSuccessor(merge);
1054
1055 // Set up dominance information.
1056 then->SetDominator(cursor_block);
1057 cursor_block->AddDominatedBlock(then);
1058 otherwise->SetDominator(cursor_block);
1059 cursor_block->AddDominatedBlock(otherwise);
1060 merge->SetDominator(cursor_block);
1061 cursor_block->AddDominatedBlock(merge);
1062
1063 // Update the revert post order.
1064 size_t index = IndexOfElement(graph_->reverse_post_order_, cursor_block);
1065 MakeRoomFor(&graph_->reverse_post_order_, 1, index);
1066 graph_->reverse_post_order_[++index] = then;
1067 index = IndexOfElement(graph_->reverse_post_order_, end_then);
1068 MakeRoomFor(&graph_->reverse_post_order_, 2, index);
1069 graph_->reverse_post_order_[++index] = otherwise;
1070 graph_->reverse_post_order_[++index] = merge;
1071
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001072
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001073 graph_->UpdateLoopAndTryInformationOfNewBlock(
1074 then, original_invoke_block, /* replace_if_back_edge */ false);
1075 graph_->UpdateLoopAndTryInformationOfNewBlock(
1076 otherwise, original_invoke_block, /* replace_if_back_edge */ false);
1077
1078 // In case the original invoke location was a back edge, we need to update
1079 // the loop to now have the merge block as a back edge.
1080 graph_->UpdateLoopAndTryInformationOfNewBlock(
1081 merge, original_invoke_block, /* replace_if_back_edge */ true);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001082}
1083
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001084bool HInliner::TryInlinePolymorphicCallToSameTarget(
1085 HInvoke* invoke_instruction,
1086 ArtMethod* resolved_method,
1087 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001088 // This optimization only works under JIT for now.
Calin Juravle13439f02017-02-21 01:17:21 -08001089 if (!Runtime::Current()->UseJitCompilation()) {
1090 return false;
1091 }
1092
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001093 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -07001094 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001095
1096 DCHECK(resolved_method != nullptr);
1097 ArtMethod* actual_method = nullptr;
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001098 size_t method_index = invoke_instruction->IsInvokeVirtual()
1099 ? invoke_instruction->AsInvokeVirtual()->GetVTableIndex()
1100 : invoke_instruction->AsInvokeInterface()->GetImtIndex();
1101
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001102 // Check whether we are actually calling the same method among
1103 // the different types seen.
1104 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001105 if (classes->Get(i) == nullptr) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001106 break;
1107 }
1108 ArtMethod* new_method = nullptr;
1109 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001110 new_method = classes->Get(i)->GetImt(pointer_size)->Get(
Matthew Gharrity465ecc82016-07-19 21:32:52 +00001111 method_index, pointer_size);
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001112 if (new_method->IsRuntimeMethod()) {
1113 // Bail out as soon as we see a conflict trampoline in one of the target's
1114 // interface table.
1115 return false;
1116 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001117 } else {
1118 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001119 new_method = classes->Get(i)->GetEmbeddedVTableEntry(method_index, pointer_size);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001120 }
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001121 DCHECK(new_method != nullptr);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001122 if (actual_method == nullptr) {
1123 actual_method = new_method;
1124 } else if (actual_method != new_method) {
1125 // Different methods, bailout.
1126 return false;
1127 }
1128 }
1129
1130 HInstruction* receiver = invoke_instruction->InputAt(0);
1131 HInstruction* cursor = invoke_instruction->GetPrevious();
1132 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
1133
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001134 HInstruction* return_replacement = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001135 if (!TryBuildAndInline(invoke_instruction,
1136 actual_method,
1137 ReferenceTypeInfo::CreateInvalid(),
1138 &return_replacement)) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001139 return false;
1140 }
1141
1142 // We successfully inlined, now add a guard.
1143 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
1144 class_linker, receiver, invoke_instruction->GetDexPc());
1145
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001146 Primitive::Type type = Is64BitInstructionSet(graph_->GetInstructionSet())
1147 ? Primitive::kPrimLong
1148 : Primitive::kPrimInt;
1149 HClassTableGet* class_table_get = new (graph_->GetArena()) HClassTableGet(
1150 receiver_class,
1151 type,
Vladimir Markoa1de9182016-02-25 11:37:38 +00001152 invoke_instruction->IsInvokeVirtual() ? HClassTableGet::TableKind::kVTable
1153 : HClassTableGet::TableKind::kIMTable,
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001154 method_index,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001155 invoke_instruction->GetDexPc());
1156
1157 HConstant* constant;
1158 if (type == Primitive::kPrimLong) {
1159 constant = graph_->GetLongConstant(
1160 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
1161 } else {
1162 constant = graph_->GetIntConstant(
1163 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
1164 }
1165
1166 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(class_table_get, constant);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001167 if (cursor != nullptr) {
1168 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
1169 } else {
1170 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
1171 }
1172 bb_cursor->InsertInstructionAfter(class_table_get, receiver_class);
1173 bb_cursor->InsertInstructionAfter(compare, class_table_get);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001174
1175 if (outermost_graph_->IsCompilingOsr()) {
1176 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
1177 } else {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001178 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001179 graph_->GetArena(),
1180 compare,
1181 receiver,
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +01001182 DeoptimizationKind::kJitSameTarget,
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001183 invoke_instruction->GetDexPc());
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001184 bb_cursor->InsertInstructionAfter(deoptimize, compare);
1185 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
1186 if (return_replacement != nullptr) {
1187 invoke_instruction->ReplaceWith(return_replacement);
1188 }
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001189 receiver->ReplaceUsesDominatedBy(deoptimize, deoptimize);
Nicolas Geoffray1be7cbd2016-04-29 13:56:01 +01001190 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001191 deoptimize->SetReferenceTypeInfo(receiver->GetReferenceTypeInfo());
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001192 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001193
1194 // Run type propagation to get the guard typed.
Vladimir Marko456307a2016-04-19 14:12:13 +00001195 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001196 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +00001197 outer_compilation_unit_.GetDexCache(),
1198 handles_,
1199 /* is_first_run */ false);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001200 rtp_fixup.Run();
1201
1202 MaybeRecordStat(kInlinedPolymorphicCall);
1203
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001204 LOG_SUCCESS() << "Inlined same polymorphic target " << actual_method->PrettyMethod();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001205 return true;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001206}
1207
Mingyao Yang063fc772016-08-02 11:02:54 -07001208bool HInliner::TryInlineAndReplace(HInvoke* invoke_instruction,
1209 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001210 ReferenceTypeInfo receiver_type,
Mingyao Yang063fc772016-08-02 11:02:54 -07001211 bool do_rtp,
1212 bool cha_devirtualize) {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001213 HInstruction* return_replacement = nullptr;
Mingyao Yang063fc772016-08-02 11:02:54 -07001214 uint32_t dex_pc = invoke_instruction->GetDexPc();
1215 HInstruction* cursor = invoke_instruction->GetPrevious();
1216 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001217 if (!TryBuildAndInline(invoke_instruction, method, receiver_type, &return_replacement)) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001218 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +00001219 DCHECK(!method->IsProxyMethod());
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001220 // Turn an invoke-interface into an invoke-virtual. An invoke-virtual is always
1221 // better than an invoke-interface because:
1222 // 1) In the best case, the interface call has one more indirection (to fetch the IMT).
1223 // 2) We will not go to the conflict trampoline with an invoke-virtual.
1224 // TODO: Consider sharpening once it is not dependent on the compiler driver.
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +00001225
1226 if (method->IsDefault() && !method->IsCopied()) {
1227 // Changing to invoke-virtual cannot be done on an original default method
1228 // since it's not in any vtable. Devirtualization by exact type/inline-cache
1229 // always uses a method in the iftable which is never an original default
1230 // method.
1231 // On the other hand, inlining an original default method by CHA is fine.
1232 DCHECK(cha_devirtualize);
1233 return false;
1234 }
1235
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001236 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001237 uint32_t dex_method_index = FindMethodIndexIn(
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001238 method, caller_dex_file, invoke_instruction->GetDexMethodIndex());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001239 if (dex_method_index == DexFile::kDexNoIndex) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001240 return false;
1241 }
1242 HInvokeVirtual* new_invoke = new (graph_->GetArena()) HInvokeVirtual(
1243 graph_->GetArena(),
1244 invoke_instruction->GetNumberOfArguments(),
1245 invoke_instruction->GetType(),
1246 invoke_instruction->GetDexPc(),
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001247 dex_method_index,
1248 method,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001249 method->GetMethodIndex());
1250 HInputsRef inputs = invoke_instruction->GetInputs();
1251 for (size_t index = 0; index != inputs.size(); ++index) {
1252 new_invoke->SetArgumentAt(index, inputs[index]);
1253 }
1254 invoke_instruction->GetBlock()->InsertInstructionBefore(new_invoke, invoke_instruction);
1255 new_invoke->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
1256 if (invoke_instruction->GetType() == Primitive::kPrimNot) {
1257 new_invoke->SetReferenceTypeInfo(invoke_instruction->GetReferenceTypeInfo());
1258 }
1259 return_replacement = new_invoke;
1260 } else {
1261 // TODO: Consider sharpening an invoke virtual once it is not dependent on the
1262 // compiler driver.
1263 return false;
1264 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001265 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001266 if (cha_devirtualize) {
1267 AddCHAGuard(invoke_instruction, dex_pc, cursor, bb_cursor);
1268 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001269 if (return_replacement != nullptr) {
1270 invoke_instruction->ReplaceWith(return_replacement);
1271 }
1272 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
David Brazdil94ab38f2016-06-21 17:48:19 +01001273 FixUpReturnReferenceType(method, return_replacement);
1274 if (do_rtp && ReturnTypeMoreSpecific(invoke_instruction, return_replacement)) {
1275 // Actual return value has a more specific type than the method's declared
1276 // return type. Run RTP again on the outer graph to propagate it.
1277 ReferenceTypePropagation(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001278 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +01001279 outer_compilation_unit_.GetDexCache(),
1280 handles_,
1281 /* is_first_run */ false).Run();
1282 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001283 return true;
1284}
1285
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001286size_t HInliner::CountRecursiveCallsOf(ArtMethod* method) const {
1287 const HInliner* current = this;
1288 size_t count = 0;
1289 do {
1290 if (current->graph_->GetArtMethod() == method) {
1291 ++count;
1292 }
1293 current = current->parent_;
1294 } while (current != nullptr);
1295 return count;
1296}
1297
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001298bool HInliner::TryBuildAndInline(HInvoke* invoke_instruction,
1299 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001300 ReferenceTypeInfo receiver_type,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001301 HInstruction** return_replacement) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001302 if (method->IsProxyMethod()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001303 LOG_FAIL(kNotInlinedProxy)
1304 << "Method " << method->PrettyMethod()
1305 << " is not inlined because of unimplemented inline support for proxy methods.";
1306 return false;
1307 }
1308
1309 if (CountRecursiveCallsOf(method) > kMaximumNumberOfRecursiveCalls) {
1310 LOG_FAIL(kNotInlinedRecursiveBudget)
1311 << "Method "
1312 << method->PrettyMethod()
1313 << " is not inlined because it has reached its recursive call budget.";
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001314 return false;
1315 }
1316
Jeff Haodcdc85b2015-12-04 14:06:18 -08001317 // Check whether we're allowed to inline. The outermost compilation unit is the relevant
1318 // dex file here (though the transitivity of an inline chain would allow checking the calller).
1319 if (!compiler_driver_->MayInline(method->GetDexFile(),
1320 outer_compilation_unit_.GetDexFile())) {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001321 if (TryPatternSubstitution(invoke_instruction, method, return_replacement)) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001322 LOG_SUCCESS() << "Successfully replaced pattern of invoke "
1323 << method->PrettyMethod();
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001324 MaybeRecordStat(kReplacedInvokeWithSimplePattern);
1325 return true;
1326 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001327 LOG_FAIL(kNotInlinedWont)
1328 << "Won't inline " << method->PrettyMethod() << " in "
1329 << outer_compilation_unit_.GetDexFile()->GetLocation() << " ("
1330 << caller_compilation_unit_.GetDexFile()->GetLocation() << ") from "
1331 << method->GetDexFile()->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001332 return false;
1333 }
1334
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001335 bool same_dex_file = IsSameDexFile(*outer_compilation_unit_.GetDexFile(), *method->GetDexFile());
1336
1337 const DexFile::CodeItem* code_item = method->GetCodeItem();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001338
1339 if (code_item == nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001340 LOG_FAIL_NO_STAT()
1341 << "Method " << method->PrettyMethod() << " is not inlined because it is native";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001342 return false;
1343 }
1344
Calin Juravleec748352015-07-29 13:52:12 +01001345 size_t inline_max_code_units = compiler_driver_->GetCompilerOptions().GetInlineMaxCodeUnits();
1346 if (code_item->insns_size_in_code_units_ > inline_max_code_units) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001347 LOG_FAIL(kNotInlinedCodeItem)
1348 << "Method " << method->PrettyMethod()
1349 << " is not inlined because its code item is too big: "
1350 << code_item->insns_size_in_code_units_
1351 << " > "
1352 << inline_max_code_units;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001353 return false;
1354 }
1355
1356 if (code_item->tries_size_ != 0) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001357 LOG_FAIL(kNotInlinedTryCatch)
1358 << "Method " << method->PrettyMethod() << " is not inlined because of try block";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001359 return false;
1360 }
1361
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001362 if (!method->IsCompilable()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001363 LOG_FAIL(kNotInlinedNotVerified)
1364 << "Method " << method->PrettyMethod()
1365 << " has soft failures un-handled by the compiler, so it cannot be inlined";
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001366 }
1367
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001368 if (!method->GetDeclaringClass()->IsVerified()) {
1369 uint16_t class_def_idx = method->GetDeclaringClass()->GetDexClassDefIndex();
Calin Juravleffc87072016-04-20 14:22:09 +01001370 if (Runtime::Current()->UseJitCompilation() ||
Nicolas Geoffray5b82d332016-02-18 14:22:32 +00001371 !compiler_driver_->IsMethodVerifiedWithoutFailures(
1372 method->GetDexMethodIndex(), class_def_idx, *method->GetDexFile())) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001373 LOG_FAIL(kNotInlinedNotVerified)
1374 << "Method " << method->PrettyMethod()
1375 << " couldn't be verified, so it cannot be inlined";
Nicolas Geoffrayccc61972015-10-01 14:34:20 +01001376 return false;
1377 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001378 }
1379
Roland Levillain4c0eb422015-04-24 16:43:49 +01001380 if (invoke_instruction->IsInvokeStaticOrDirect() &&
1381 invoke_instruction->AsInvokeStaticOrDirect()->IsStaticWithImplicitClinitCheck()) {
1382 // Case of a static method that cannot be inlined because it implicitly
1383 // requires an initialization check of its declaring class.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001384 LOG_FAIL(kNotInlinedDexCache) << "Method " << method->PrettyMethod()
1385 << " is not inlined because it is static and requires a clinit"
1386 << " check that cannot be emitted due to Dex cache limitations";
Roland Levillain4c0eb422015-04-24 16:43:49 +01001387 return false;
1388 }
1389
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001390 if (!TryBuildAndInlineHelper(
1391 invoke_instruction, method, receiver_type, same_dex_file, return_replacement)) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001392 return false;
1393 }
1394
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001395 LOG_SUCCESS() << method->PrettyMethod();
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001396 MaybeRecordStat(kInlinedInvoke);
1397 return true;
1398}
1399
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001400static HInstruction* GetInvokeInputForArgVRegIndex(HInvoke* invoke_instruction,
1401 size_t arg_vreg_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001402 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001403 size_t input_index = 0;
1404 for (size_t i = 0; i < arg_vreg_index; ++i, ++input_index) {
1405 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
1406 if (Primitive::Is64BitType(invoke_instruction->InputAt(input_index)->GetType())) {
1407 ++i;
1408 DCHECK_NE(i, arg_vreg_index);
1409 }
1410 }
1411 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
1412 return invoke_instruction->InputAt(input_index);
1413}
1414
1415// Try to recognize known simple patterns and replace invoke call with appropriate instructions.
1416bool HInliner::TryPatternSubstitution(HInvoke* invoke_instruction,
1417 ArtMethod* resolved_method,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001418 HInstruction** return_replacement) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001419 InlineMethod inline_method;
1420 if (!InlineMethodAnalyser::AnalyseMethodCode(resolved_method, &inline_method)) {
1421 return false;
1422 }
1423
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001424 switch (inline_method.opcode) {
1425 case kInlineOpNop:
1426 DCHECK_EQ(invoke_instruction->GetType(), Primitive::kPrimVoid);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001427 *return_replacement = nullptr;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001428 break;
1429 case kInlineOpReturnArg:
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001430 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction,
1431 inline_method.d.return_data.arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001432 break;
1433 case kInlineOpNonWideConst:
1434 if (resolved_method->GetShorty()[0] == 'L') {
1435 DCHECK_EQ(inline_method.d.data, 0u);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001436 *return_replacement = graph_->GetNullConstant();
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001437 } else {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001438 *return_replacement = graph_->GetIntConstant(static_cast<int32_t>(inline_method.d.data));
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001439 }
1440 break;
1441 case kInlineOpIGet: {
1442 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1443 if (data.method_is_static || data.object_arg != 0u) {
1444 // TODO: Needs null check.
1445 return false;
1446 }
1447 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001448 HInstanceFieldGet* iget = CreateInstanceFieldGet(data.field_idx, resolved_method, obj);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001449 DCHECK_EQ(iget->GetFieldOffset().Uint32Value(), data.field_offset);
1450 DCHECK_EQ(iget->IsVolatile() ? 1u : 0u, data.is_volatile);
1451 invoke_instruction->GetBlock()->InsertInstructionBefore(iget, invoke_instruction);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001452 *return_replacement = iget;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001453 break;
1454 }
1455 case kInlineOpIPut: {
1456 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1457 if (data.method_is_static || data.object_arg != 0u) {
1458 // TODO: Needs null check.
1459 return false;
1460 }
1461 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
1462 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, data.src_arg);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001463 HInstanceFieldSet* iput = CreateInstanceFieldSet(data.field_idx, resolved_method, obj, value);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001464 DCHECK_EQ(iput->GetFieldOffset().Uint32Value(), data.field_offset);
1465 DCHECK_EQ(iput->IsVolatile() ? 1u : 0u, data.is_volatile);
1466 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1467 if (data.return_arg_plus1 != 0u) {
1468 size_t return_arg = data.return_arg_plus1 - 1u;
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001469 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction, return_arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001470 }
1471 break;
1472 }
Vladimir Marko354efa62016-02-04 19:46:56 +00001473 case kInlineOpConstructor: {
1474 const InlineConstructorData& data = inline_method.d.constructor_data;
1475 // Get the indexes to arrays for easier processing.
1476 uint16_t iput_field_indexes[] = {
1477 data.iput0_field_index, data.iput1_field_index, data.iput2_field_index
1478 };
1479 uint16_t iput_args[] = { data.iput0_arg, data.iput1_arg, data.iput2_arg };
1480 static_assert(arraysize(iput_args) == arraysize(iput_field_indexes), "Size mismatch");
1481 // Count valid field indexes.
1482 size_t number_of_iputs = 0u;
1483 while (number_of_iputs != arraysize(iput_field_indexes) &&
1484 iput_field_indexes[number_of_iputs] != DexFile::kDexNoIndex16) {
1485 // Check that there are no duplicate valid field indexes.
1486 DCHECK_EQ(0, std::count(iput_field_indexes + number_of_iputs + 1,
1487 iput_field_indexes + arraysize(iput_field_indexes),
1488 iput_field_indexes[number_of_iputs]));
1489 ++number_of_iputs;
1490 }
1491 // Check that there are no valid field indexes in the rest of the array.
1492 DCHECK_EQ(0, std::count_if(iput_field_indexes + number_of_iputs,
1493 iput_field_indexes + arraysize(iput_field_indexes),
1494 [](uint16_t index) { return index != DexFile::kDexNoIndex16; }));
1495
1496 // Create HInstanceFieldSet for each IPUT that stores non-zero data.
Vladimir Marko354efa62016-02-04 19:46:56 +00001497 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, /* this */ 0u);
1498 bool needs_constructor_barrier = false;
1499 for (size_t i = 0; i != number_of_iputs; ++i) {
1500 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, iput_args[i]);
Roland Levillain1a653882016-03-18 18:05:57 +00001501 if (!value->IsConstant() || !value->AsConstant()->IsZeroBitPattern()) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001502 uint16_t field_index = iput_field_indexes[i];
Vladimir Markof44d36c2017-03-14 14:18:46 +00001503 bool is_final;
1504 HInstanceFieldSet* iput =
1505 CreateInstanceFieldSet(field_index, resolved_method, obj, value, &is_final);
Vladimir Marko354efa62016-02-04 19:46:56 +00001506 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1507
1508 // Check whether the field is final. If it is, we need to add a barrier.
Vladimir Markof44d36c2017-03-14 14:18:46 +00001509 if (is_final) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001510 needs_constructor_barrier = true;
1511 }
1512 }
1513 }
1514 if (needs_constructor_barrier) {
Igor Murashkind01745e2017-04-05 16:40:31 -07001515 // See CompilerDriver::RequiresConstructorBarrier for more details.
1516 DCHECK(obj != nullptr) << "only non-static methods can have a constructor fence";
1517
1518 HConstructorFence* constructor_fence =
1519 new (graph_->GetArena()) HConstructorFence(obj, kNoDexPc, graph_->GetArena());
1520 invoke_instruction->GetBlock()->InsertInstructionBefore(constructor_fence,
1521 invoke_instruction);
Vladimir Marko354efa62016-02-04 19:46:56 +00001522 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001523 *return_replacement = nullptr;
Vladimir Marko354efa62016-02-04 19:46:56 +00001524 break;
1525 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001526 default:
1527 LOG(FATAL) << "UNREACHABLE";
1528 UNREACHABLE();
1529 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001530 return true;
1531}
1532
Vladimir Markof44d36c2017-03-14 14:18:46 +00001533HInstanceFieldGet* HInliner::CreateInstanceFieldGet(uint32_t field_index,
1534 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001535 HInstruction* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001536 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001537 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1538 ArtField* resolved_field =
1539 class_linker->LookupResolvedField(field_index, referrer, /* is_static */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001540 DCHECK(resolved_field != nullptr);
1541 HInstanceFieldGet* iget = new (graph_->GetArena()) HInstanceFieldGet(
1542 obj,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001543 resolved_field,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001544 resolved_field->GetTypeAsPrimitiveType(),
1545 resolved_field->GetOffset(),
1546 resolved_field->IsVolatile(),
1547 field_index,
1548 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001549 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001550 // Read barrier generates a runtime call in slow path and we need a valid
1551 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1552 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001553 if (iget->GetType() == Primitive::kPrimNot) {
Vladimir Marko456307a2016-04-19 14:12:13 +00001554 // Use the same dex_cache that we used for field lookup as the hint_dex_cache.
Vladimir Markof44d36c2017-03-14 14:18:46 +00001555 Handle<mirror::DexCache> dex_cache = handles_->NewHandle(referrer->GetDexCache());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001556 ReferenceTypePropagation rtp(graph_,
1557 outer_compilation_unit_.GetClassLoader(),
1558 dex_cache,
1559 handles_,
1560 /* is_first_run */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001561 rtp.Visit(iget);
1562 }
1563 return iget;
1564}
1565
Vladimir Markof44d36c2017-03-14 14:18:46 +00001566HInstanceFieldSet* HInliner::CreateInstanceFieldSet(uint32_t field_index,
1567 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001568 HInstruction* obj,
Vladimir Markof44d36c2017-03-14 14:18:46 +00001569 HInstruction* value,
1570 bool* is_final)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001571 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001572 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1573 ArtField* resolved_field =
1574 class_linker->LookupResolvedField(field_index, referrer, /* is_static */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001575 DCHECK(resolved_field != nullptr);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001576 if (is_final != nullptr) {
1577 // This information is needed only for constructors.
1578 DCHECK(referrer->IsConstructor());
1579 *is_final = resolved_field->IsFinal();
1580 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001581 HInstanceFieldSet* iput = new (graph_->GetArena()) HInstanceFieldSet(
1582 obj,
1583 value,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001584 resolved_field,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001585 resolved_field->GetTypeAsPrimitiveType(),
1586 resolved_field->GetOffset(),
1587 resolved_field->IsVolatile(),
1588 field_index,
1589 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001590 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001591 // Read barrier generates a runtime call in slow path and we need a valid
1592 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1593 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001594 return iput;
1595}
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001596
Vladimir Markob1d0ee12017-04-20 19:50:32 +01001597template <typename T>
1598static inline Handle<T> NewHandleIfDifferent(T* object,
1599 Handle<T> hint,
1600 VariableSizedHandleScope* handles)
1601 REQUIRES_SHARED(Locks::mutator_lock_) {
1602 return (object != hint.Get()) ? handles->NewHandle(object) : hint;
1603}
1604
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001605bool HInliner::TryBuildAndInlineHelper(HInvoke* invoke_instruction,
1606 ArtMethod* resolved_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001607 ReferenceTypeInfo receiver_type,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001608 bool same_dex_file,
1609 HInstruction** return_replacement) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001610 DCHECK(!(resolved_method->IsStatic() && receiver_type.IsValid()));
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001611 ScopedObjectAccess soa(Thread::Current());
1612 const DexFile::CodeItem* code_item = resolved_method->GetCodeItem();
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001613 const DexFile& callee_dex_file = *resolved_method->GetDexFile();
1614 uint32_t method_index = resolved_method->GetDexMethodIndex();
Calin Juravle2e768302015-07-28 14:41:11 +00001615 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Vladimir Markob1d0ee12017-04-20 19:50:32 +01001616 Handle<mirror::DexCache> dex_cache = NewHandleIfDifferent(resolved_method->GetDexCache(),
1617 caller_compilation_unit_.GetDexCache(),
1618 handles_);
1619 Handle<mirror::ClassLoader> class_loader =
1620 NewHandleIfDifferent(resolved_method->GetDeclaringClass()->GetClassLoader(),
1621 caller_compilation_unit_.GetClassLoader(),
1622 handles_);
Nicolas Geoffrayf1aedb12016-07-28 03:49:14 +01001623
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001624 DexCompilationUnit dex_compilation_unit(
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001625 class_loader,
Nicolas Geoffray5b82d332016-02-18 14:22:32 +00001626 class_linker,
1627 callee_dex_file,
1628 code_item,
1629 resolved_method->GetDeclaringClass()->GetDexClassDefIndex(),
1630 method_index,
1631 resolved_method->GetAccessFlags(),
1632 /* verified_method */ nullptr,
1633 dex_cache);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001634
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001635 InvokeType invoke_type = invoke_instruction->GetInvokeType();
Nicolas Geoffray35071052015-06-09 15:43:38 +01001636 if (invoke_type == kInterface) {
1637 // We have statically resolved the dispatch. To please the class linker
1638 // at runtime, we change this call as if it was a virtual call.
1639 invoke_type = kVirtual;
1640 }
David Brazdil3f523062016-02-29 16:53:33 +00001641
1642 const int32_t caller_instruction_counter = graph_->GetCurrentInstructionId();
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +00001643 HGraph* callee_graph = new (graph_->GetArena()) HGraph(
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001644 graph_->GetArena(),
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001645 callee_dex_file,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001646 method_index,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001647 compiler_driver_->GetInstructionSet(),
Nicolas Geoffray35071052015-06-09 15:43:38 +01001648 invoke_type,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001649 graph_->IsDebuggable(),
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001650 /* osr */ false,
David Brazdil3f523062016-02-29 16:53:33 +00001651 caller_instruction_counter);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001652 callee_graph->SetArtMethod(resolved_method);
David Brazdil5e8b1372015-01-23 14:39:08 +00001653
Vladimir Marko438709f2017-02-23 18:56:13 +00001654 // When they are needed, allocate `inline_stats_` on the Arena instead
Roland Levillaina8013fd2016-04-04 15:34:31 +01001655 // of on the stack, as Clang might produce a stack frame too large
1656 // for this function, that would not fit the requirements of the
1657 // `-Wframe-larger-than` option.
Vladimir Marko438709f2017-02-23 18:56:13 +00001658 if (stats_ != nullptr) {
1659 // Reuse one object for all inline attempts from this caller to keep Arena memory usage low.
1660 if (inline_stats_ == nullptr) {
1661 void* storage = graph_->GetArena()->Alloc<OptimizingCompilerStats>(kArenaAllocMisc);
1662 inline_stats_ = new (storage) OptimizingCompilerStats;
1663 } else {
1664 inline_stats_->Reset();
1665 }
1666 }
David Brazdil5e8b1372015-01-23 14:39:08 +00001667 HGraphBuilder builder(callee_graph,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001668 &dex_compilation_unit,
1669 &outer_compilation_unit_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001670 resolved_method->GetDexFile(),
David Brazdil86ea7ee2016-02-16 09:26:07 +00001671 *code_item,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001672 compiler_driver_,
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00001673 codegen_,
Vladimir Marko438709f2017-02-23 18:56:13 +00001674 inline_stats_,
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001675 resolved_method->GetQuickenedInfo(class_linker->GetImagePointerSize()),
David Brazdildee58d62016-04-07 09:54:26 +00001676 dex_cache,
1677 handles_);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001678
David Brazdildee58d62016-04-07 09:54:26 +00001679 if (builder.BuildGraph() != kAnalysisSuccess) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001680 LOG_FAIL(kNotInlinedCannotBuild)
1681 << "Method " << callee_dex_file.PrettyMethod(method_index)
1682 << " could not be built, so cannot be inlined";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001683 return false;
1684 }
1685
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001686 if (!RegisterAllocator::CanAllocateRegistersFor(*callee_graph,
1687 compiler_driver_->GetInstructionSet())) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001688 LOG_FAIL(kNotInlinedRegisterAllocator)
1689 << "Method " << callee_dex_file.PrettyMethod(method_index)
1690 << " cannot be inlined because of the register allocator";
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001691 return false;
1692 }
1693
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001694 size_t parameter_index = 0;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001695 bool run_rtp = false;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001696 for (HInstructionIterator instructions(callee_graph->GetEntryBlock()->GetInstructions());
1697 !instructions.Done();
1698 instructions.Advance()) {
1699 HInstruction* current = instructions.Current();
1700 if (current->IsParameterValue()) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001701 HInstruction* argument = invoke_instruction->InputAt(parameter_index);
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001702 if (argument->IsNullConstant()) {
1703 current->ReplaceWith(callee_graph->GetNullConstant());
1704 } else if (argument->IsIntConstant()) {
1705 current->ReplaceWith(callee_graph->GetIntConstant(argument->AsIntConstant()->GetValue()));
1706 } else if (argument->IsLongConstant()) {
1707 current->ReplaceWith(callee_graph->GetLongConstant(argument->AsLongConstant()->GetValue()));
1708 } else if (argument->IsFloatConstant()) {
1709 current->ReplaceWith(
1710 callee_graph->GetFloatConstant(argument->AsFloatConstant()->GetValue()));
1711 } else if (argument->IsDoubleConstant()) {
1712 current->ReplaceWith(
1713 callee_graph->GetDoubleConstant(argument->AsDoubleConstant()->GetValue()));
1714 } else if (argument->GetType() == Primitive::kPrimNot) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001715 if (!resolved_method->IsStatic() && parameter_index == 0 && receiver_type.IsValid()) {
1716 run_rtp = true;
1717 current->SetReferenceTypeInfo(receiver_type);
1718 } else {
1719 current->SetReferenceTypeInfo(argument->GetReferenceTypeInfo());
1720 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001721 current->AsParameterValue()->SetCanBeNull(argument->CanBeNull());
1722 }
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001723 ++parameter_index;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001724 }
1725 }
1726
David Brazdil94ab38f2016-06-21 17:48:19 +01001727 // We have replaced formal arguments with actual arguments. If actual types
1728 // are more specific than the declared ones, run RTP again on the inner graph.
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001729 if (run_rtp || ArgumentTypesMoreSpecific(invoke_instruction, resolved_method)) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001730 ReferenceTypePropagation(callee_graph,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001731 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +01001732 dex_compilation_unit.GetDexCache(),
1733 handles_,
1734 /* is_first_run */ false).Run();
1735 }
1736
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001737 RunOptimizations(callee_graph, code_item, dex_compilation_unit);
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +00001738
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001739 HBasicBlock* exit_block = callee_graph->GetExitBlock();
1740 if (exit_block == nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001741 LOG_FAIL(kNotInlinedInfiniteLoop)
1742 << "Method " << callee_dex_file.PrettyMethod(method_index)
1743 << " could not be inlined because it has an infinite loop";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001744 return false;
1745 }
1746
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001747 bool has_one_return = false;
Vladimir Marko60584552015-09-03 13:35:12 +00001748 for (HBasicBlock* predecessor : exit_block->GetPredecessors()) {
1749 if (predecessor->GetLastInstruction()->IsThrow()) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001750 if (invoke_instruction->GetBlock()->IsTryBlock()) {
1751 // TODO(ngeoffray): Support adding HTryBoundary in Hgraph::InlineInto.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001752 LOG_FAIL(kNotInlinedTryCatch)
1753 << "Method " << callee_dex_file.PrettyMethod(method_index)
1754 << " could not be inlined because one branch always throws and"
1755 << " caller is in a try/catch block";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001756 return false;
1757 } else if (graph_->GetExitBlock() == nullptr) {
1758 // TODO(ngeoffray): Support adding HExit in the caller graph.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001759 LOG_FAIL(kNotInlinedInfiniteLoop)
1760 << "Method " << callee_dex_file.PrettyMethod(method_index)
1761 << " could not be inlined because one branch always throws and"
1762 << " caller does not have an exit block";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001763 return false;
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00001764 } else if (graph_->HasIrreducibleLoops()) {
1765 // TODO(ngeoffray): Support re-computing loop information to graphs with
1766 // irreducible loops?
1767 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1768 << " could not be inlined because one branch always throws and"
1769 << " caller has irreducible loops";
1770 return false;
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001771 }
1772 } else {
1773 has_one_return = true;
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001774 }
1775 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001776
1777 if (!has_one_return) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001778 LOG_FAIL(kNotInlinedAlwaysThrows)
1779 << "Method " << callee_dex_file.PrettyMethod(method_index)
1780 << " could not be inlined because it always throws";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001781 return false;
1782 }
1783
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001784 size_t number_of_instructions = 0;
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001785 // Skip the entry block, it does not contain instructions that prevent inlining.
1786 for (HBasicBlock* block : callee_graph->GetReversePostOrderSkipEntryBlock()) {
David Sehrc757dec2016-11-04 15:48:34 -07001787 if (block->IsLoopHeader()) {
1788 if (block->GetLoopInformation()->IsIrreducible()) {
1789 // Don't inline methods with irreducible loops, they could prevent some
1790 // optimizations to run.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001791 LOG_FAIL(kNotInlinedIrreducibleLoop)
1792 << "Method " << callee_dex_file.PrettyMethod(method_index)
1793 << " could not be inlined because it contains an irreducible loop";
David Sehrc757dec2016-11-04 15:48:34 -07001794 return false;
1795 }
1796 if (!block->GetLoopInformation()->HasExitEdge()) {
1797 // Don't inline methods with loops without exit, since they cause the
1798 // loop information to be computed incorrectly when updating after
1799 // inlining.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001800 LOG_FAIL(kNotInlinedLoopWithoutExit)
1801 << "Method " << callee_dex_file.PrettyMethod(method_index)
1802 << " could not be inlined because it contains a loop with no exit";
David Sehrc757dec2016-11-04 15:48:34 -07001803 return false;
1804 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001805 }
1806
1807 for (HInstructionIterator instr_it(block->GetInstructions());
1808 !instr_it.Done();
1809 instr_it.Advance()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001810 if (++number_of_instructions >= inlining_budget_) {
1811 LOG_FAIL(kNotInlinedInstructionBudget)
1812 << "Method " << callee_dex_file.PrettyMethod(method_index)
1813 << " is not inlined because the outer method has reached"
1814 << " its instruction budget limit.";
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001815 return false;
1816 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001817 HInstruction* current = instr_it.Current();
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001818 if (current->NeedsEnvironment() &&
1819 (total_number_of_dex_registers_ >= kMaximumNumberOfCumulatedDexRegisters)) {
1820 LOG_FAIL(kNotInlinedEnvironmentBudget)
1821 << "Method " << callee_dex_file.PrettyMethod(method_index)
1822 << " is not inlined because its caller has reached"
1823 << " its environment budget limit.";
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001824 return false;
1825 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001826
Nicolas Geoffrayfbdfa6d2017-02-03 10:43:13 +00001827 if (current->NeedsEnvironment() &&
1828 !CanEncodeInlinedMethodInStackMap(*caller_compilation_unit_.GetDexFile(),
1829 resolved_method)) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001830 LOG_FAIL(kNotInlinedStackMaps)
1831 << "Method " << callee_dex_file.PrettyMethod(method_index)
1832 << " could not be inlined because " << current->DebugName()
1833 << " needs an environment, is in a different dex file"
1834 << ", and cannot be encoded in the stack maps.";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001835 return false;
1836 }
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001837
Vladimir Markodc151b22015-10-15 18:02:30 +01001838 if (!same_dex_file && current->NeedsDexCacheOfDeclaringClass()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001839 LOG_FAIL(kNotInlinedDexCache)
1840 << "Method " << callee_dex_file.PrettyMethod(method_index)
1841 << " could not be inlined because " << current->DebugName()
1842 << " it is in a different dex file and requires access to the dex cache";
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001843 return false;
1844 }
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001845
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001846 if (current->IsUnresolvedStaticFieldGet() ||
1847 current->IsUnresolvedInstanceFieldGet() ||
1848 current->IsUnresolvedStaticFieldSet() ||
1849 current->IsUnresolvedInstanceFieldSet()) {
1850 // Entrypoint for unresolved fields does not handle inlined frames.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001851 LOG_FAIL(kNotInlinedUnresolvedEntrypoint)
1852 << "Method " << callee_dex_file.PrettyMethod(method_index)
1853 << " could not be inlined because it is using an unresolved"
1854 << " entrypoint";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001855 return false;
1856 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001857 }
1858 }
David Brazdil3f523062016-02-29 16:53:33 +00001859 DCHECK_EQ(caller_instruction_counter, graph_->GetCurrentInstructionId())
1860 << "No instructions can be added to the outer graph while inner graph is being built";
1861
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001862 // Inline the callee graph inside the caller graph.
David Brazdil3f523062016-02-29 16:53:33 +00001863 const int32_t callee_instruction_counter = callee_graph->GetCurrentInstructionId();
1864 graph_->SetCurrentInstructionId(callee_instruction_counter);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001865 *return_replacement = callee_graph->InlineInto(graph_, invoke_instruction);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001866 // Update our budget for other inlining attempts in `caller_graph`.
1867 total_number_of_instructions_ += number_of_instructions;
1868 UpdateInliningBudget();
David Brazdil3f523062016-02-29 16:53:33 +00001869
1870 DCHECK_EQ(callee_instruction_counter, callee_graph->GetCurrentInstructionId())
1871 << "No instructions can be added to the inner graph during inlining into the outer graph";
1872
Vladimir Marko438709f2017-02-23 18:56:13 +00001873 if (stats_ != nullptr) {
1874 DCHECK(inline_stats_ != nullptr);
1875 inline_stats_->AddTo(stats_);
1876 }
1877
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001878 return true;
1879}
Calin Juravle2e768302015-07-28 14:41:11 +00001880
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001881void HInliner::RunOptimizations(HGraph* callee_graph,
1882 const DexFile::CodeItem* code_item,
1883 const DexCompilationUnit& dex_compilation_unit) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001884 // Note: if the outermost_graph_ is being compiled OSR, we should not run any
1885 // optimization that could lead to a HDeoptimize. The following optimizations do not.
Vladimir Marko438709f2017-02-23 18:56:13 +00001886 HDeadCodeElimination dce(callee_graph, inline_stats_, "dead_code_elimination$inliner");
Andreas Gampeca620d72016-11-08 08:09:33 -08001887 HConstantFolding fold(callee_graph, "constant_folding$inliner");
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001888 HSharpening sharpening(callee_graph, codegen_, dex_compilation_unit, compiler_driver_, handles_);
Vladimir Marko65979462017-05-19 17:25:12 +01001889 InstructionSimplifier simplify(callee_graph, codegen_, compiler_driver_, inline_stats_);
Vladimir Marko438709f2017-02-23 18:56:13 +00001890 IntrinsicsRecognizer intrinsics(callee_graph, inline_stats_);
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001891
1892 HOptimization* optimizations[] = {
1893 &intrinsics,
1894 &sharpening,
1895 &simplify,
1896 &fold,
1897 &dce,
1898 };
1899
1900 for (size_t i = 0; i < arraysize(optimizations); ++i) {
1901 HOptimization* optimization = optimizations[i];
1902 optimization->Run();
1903 }
1904
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001905 // Bail early for pathological cases on the environment (for example recursive calls,
1906 // or too large environment).
1907 if (total_number_of_dex_registers_ >= kMaximumNumberOfCumulatedDexRegisters) {
1908 LOG_NOTE() << "Calls in " << callee_graph->GetArtMethod()->PrettyMethod()
1909 << " will not be inlined because the outer method has reached"
1910 << " its environment budget limit.";
1911 return;
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001912 }
1913
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001914 // Bail early if we know we already are over the limit.
1915 size_t number_of_instructions = CountNumberOfInstructions(callee_graph);
1916 if (number_of_instructions > inlining_budget_) {
1917 LOG_NOTE() << "Calls in " << callee_graph->GetArtMethod()->PrettyMethod()
1918 << " will not be inlined because the outer method has reached"
1919 << " its instruction budget limit. " << number_of_instructions;
1920 return;
1921 }
1922
1923 HInliner inliner(callee_graph,
1924 outermost_graph_,
1925 codegen_,
1926 outer_compilation_unit_,
1927 dex_compilation_unit,
1928 compiler_driver_,
1929 handles_,
1930 inline_stats_,
1931 total_number_of_dex_registers_ + code_item->registers_size_,
1932 total_number_of_instructions_ + number_of_instructions,
1933 this,
1934 depth_ + 1);
1935 inliner.Run();
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001936}
1937
David Brazdil94ab38f2016-06-21 17:48:19 +01001938static bool IsReferenceTypeRefinement(ReferenceTypeInfo declared_rti,
1939 bool declared_can_be_null,
1940 HInstruction* actual_obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001941 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001942 if (declared_can_be_null && !actual_obj->CanBeNull()) {
1943 return true;
1944 }
1945
1946 ReferenceTypeInfo actual_rti = actual_obj->GetReferenceTypeInfo();
1947 return (actual_rti.IsExact() && !declared_rti.IsExact()) ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001948 declared_rti.IsStrictSupertypeOf(actual_rti);
David Brazdil94ab38f2016-06-21 17:48:19 +01001949}
1950
1951ReferenceTypeInfo HInliner::GetClassRTI(mirror::Class* klass) {
1952 return ReferenceTypePropagation::IsAdmissible(klass)
1953 ? ReferenceTypeInfo::Create(handles_->NewHandle(klass))
1954 : graph_->GetInexactObjectRti();
1955}
1956
1957bool HInliner::ArgumentTypesMoreSpecific(HInvoke* invoke_instruction, ArtMethod* resolved_method) {
1958 // If this is an instance call, test whether the type of the `this` argument
1959 // is more specific than the class which declares the method.
1960 if (!resolved_method->IsStatic()) {
1961 if (IsReferenceTypeRefinement(GetClassRTI(resolved_method->GetDeclaringClass()),
1962 /* declared_can_be_null */ false,
1963 invoke_instruction->InputAt(0u))) {
1964 return true;
1965 }
1966 }
1967
David Brazdil94ab38f2016-06-21 17:48:19 +01001968 // Iterate over the list of parameter types and test whether any of the
1969 // actual inputs has a more specific reference type than the type declared in
1970 // the signature.
1971 const DexFile::TypeList* param_list = resolved_method->GetParameterTypeList();
1972 for (size_t param_idx = 0,
1973 input_idx = resolved_method->IsStatic() ? 0 : 1,
1974 e = (param_list == nullptr ? 0 : param_list->Size());
1975 param_idx < e;
1976 ++param_idx, ++input_idx) {
1977 HInstruction* input = invoke_instruction->InputAt(input_idx);
1978 if (input->GetType() == Primitive::kPrimNot) {
Vladimir Marko942fd312017-01-16 20:52:19 +00001979 mirror::Class* param_cls = resolved_method->GetClassFromTypeIndex(
David Brazdil94ab38f2016-06-21 17:48:19 +01001980 param_list->GetTypeItem(param_idx).type_idx_,
Vladimir Marko942fd312017-01-16 20:52:19 +00001981 /* resolve */ false);
David Brazdil94ab38f2016-06-21 17:48:19 +01001982 if (IsReferenceTypeRefinement(GetClassRTI(param_cls),
1983 /* declared_can_be_null */ true,
1984 input)) {
1985 return true;
1986 }
1987 }
1988 }
1989
1990 return false;
1991}
1992
1993bool HInliner::ReturnTypeMoreSpecific(HInvoke* invoke_instruction,
1994 HInstruction* return_replacement) {
Alex Light68289a52015-12-15 17:30:30 -08001995 // Check the integrity of reference types and run another type propagation if needed.
David Brazdil4833f5a2015-12-16 10:37:39 +00001996 if (return_replacement != nullptr) {
1997 if (return_replacement->GetType() == Primitive::kPrimNot) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001998 // Test if the return type is a refinement of the declared return type.
1999 if (IsReferenceTypeRefinement(invoke_instruction->GetReferenceTypeInfo(),
2000 /* declared_can_be_null */ true,
2001 return_replacement)) {
2002 return true;
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00002003 } else if (return_replacement->IsInstanceFieldGet()) {
2004 HInstanceFieldGet* field_get = return_replacement->AsInstanceFieldGet();
2005 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2006 if (field_get->GetFieldInfo().GetField() ==
2007 class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0)) {
2008 return true;
2009 }
David Brazdil94ab38f2016-06-21 17:48:19 +01002010 }
2011 } else if (return_replacement->IsInstanceOf()) {
2012 // Inlining InstanceOf into an If may put a tighter bound on reference types.
2013 return true;
2014 }
2015 }
2016
2017 return false;
2018}
2019
2020void HInliner::FixUpReturnReferenceType(ArtMethod* resolved_method,
2021 HInstruction* return_replacement) {
2022 if (return_replacement != nullptr) {
2023 if (return_replacement->GetType() == Primitive::kPrimNot) {
David Brazdil4833f5a2015-12-16 10:37:39 +00002024 if (!return_replacement->GetReferenceTypeInfo().IsValid()) {
2025 // Make sure that we have a valid type for the return. We may get an invalid one when
2026 // we inline invokes with multiple branches and create a Phi for the result.
2027 // TODO: we could be more precise by merging the phi inputs but that requires
2028 // some functionality from the reference type propagation.
2029 DCHECK(return_replacement->IsPhi());
Vladimir Marko942fd312017-01-16 20:52:19 +00002030 mirror::Class* cls = resolved_method->GetReturnType(false /* resolve */);
David Brazdil94ab38f2016-06-21 17:48:19 +01002031 return_replacement->SetReferenceTypeInfo(GetClassRTI(cls));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01002032 }
Calin Juravlecdfed3d2015-10-26 14:05:01 +00002033 }
Calin Juravle2e768302015-07-28 14:41:11 +00002034 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002035}
2036
2037} // namespace art