blob: c970e5cbba31d9e724921b846b71a429990238c6 [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"
Vladimir Markobe10e8e2016-01-22 12:09:44 +000025#include "dex/verified_method.h"
26#include "dex/verification_results.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000027#include "driver/compiler_driver-inl.h"
Calin Juravleec748352015-07-29 13:52:12 +010028#include "driver/compiler_options.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000029#include "driver/dex_compilation_unit.h"
30#include "instruction_simplifier.h"
Scott Wakelingd60a1af2015-07-22 14:32:44 +010031#include "intrinsics.h"
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +000032#include "jit/jit.h"
33#include "jit/jit_code_cache.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000034#include "mirror/class_loader.h"
35#include "mirror/dex_cache.h"
36#include "nodes.h"
Nicolas Geoffray335005e2015-06-25 10:01:47 +010037#include "optimizing_compiler.h"
Nicolas Geoffray454a4812015-06-09 10:37:32 +010038#include "reference_type_propagation.h"
Matthew Gharritye9288852016-07-14 14:08:16 -070039#include "register_allocator_linear_scan.h"
Vladimir Markobe10e8e2016-01-22 12:09:44 +000040#include "quick/inline_method_analyser.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 Geoffray5949fa02015-12-18 10:57:10 +000049static constexpr size_t kMaximumNumberOfHInstructions = 32;
50
51// Limit the number of dex registers that we accumulate while inlining
52// to avoid creating large amount of nested environments.
53static constexpr size_t kMaximumNumberOfCumulatedDexRegisters = 64;
54
55// Avoid inlining within a huge method due to memory pressure.
56static constexpr size_t kMaximumCodeUnitSize = 4096;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -070057
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000058void HInliner::Run() {
Calin Juravle8f96df82015-07-29 15:58:48 +010059 const CompilerOptions& compiler_options = compiler_driver_->GetCompilerOptions();
60 if ((compiler_options.GetInlineDepthLimit() == 0)
61 || (compiler_options.GetInlineMaxCodeUnits() == 0)) {
62 return;
63 }
Nicolas Geoffray5949fa02015-12-18 10:57:10 +000064 if (caller_compilation_unit_.GetCodeItem()->insns_size_in_code_units_ > kMaximumCodeUnitSize) {
65 return;
66 }
Nicolas Geoffraye50b8d22015-03-13 08:57:42 +000067 if (graph_->IsDebuggable()) {
68 // For simplicity, we currently never inline when the graph is debuggable. This avoids
69 // doing some logic in the runtime to discover if a method could have been inlined.
70 return;
71 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +010072 const ArenaVector<HBasicBlock*>& blocks = graph_->GetReversePostOrder();
73 DCHECK(!blocks.empty());
74 HBasicBlock* next_block = blocks[0];
75 for (size_t i = 0; i < blocks.size(); ++i) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +010076 // Because we are changing the graph when inlining, we need to remember the next block.
77 // This avoids doing the inlining work again on the inlined blocks.
Vladimir Markofa6b93c2015-09-15 10:15:55 +010078 if (blocks[i] != next_block) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +010079 continue;
80 }
81 HBasicBlock* block = next_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +010082 next_block = (i == blocks.size() - 1) ? nullptr : blocks[i + 1];
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +000083 for (HInstruction* instruction = block->GetFirstInstruction(); instruction != nullptr;) {
84 HInstruction* next = instruction->GetNext();
Nicolas Geoffray454a4812015-06-09 10:37:32 +010085 HInvoke* call = instruction->AsInvoke();
Razvan A Lupusoru3e90a962015-03-27 13:44:44 -070086 // As long as the call is not intrinsified, it is worth trying to inline.
87 if (call != nullptr && call->GetIntrinsic() == Intrinsics::kNone) {
Nicolas Geoffray79041292015-03-26 10:05:54 +000088 // We use the original invoke type to ensure the resolution of the called method
89 // works properly.
Vladimir Marko58155012015-08-19 12:49:41 +000090 if (!TryInline(call)) {
Nicolas Geoffray335005e2015-06-25 10:01:47 +010091 if (kIsDebugBuild && IsCompilingWithCoreImage()) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000092 std::string callee_name =
David Sehr709b0702016-10-13 09:12:37 -070093 outer_compilation_unit_.GetDexFile()->PrettyMethod(call->GetDexMethodIndex());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000094 bool should_inline = callee_name.find("$inline$") != std::string::npos;
95 CHECK(!should_inline) << "Could not inline " << callee_name;
96 }
Guillaume "Vermeille" Sancheze918d382015-06-03 15:32:41 +010097 } else {
Nicolas Geoffray335005e2015-06-25 10:01:47 +010098 if (kIsDebugBuild && IsCompilingWithCoreImage()) {
Guillaume "Vermeille" Sancheze918d382015-06-03 15:32:41 +010099 std::string callee_name =
David Sehr709b0702016-10-13 09:12:37 -0700100 outer_compilation_unit_.GetDexFile()->PrettyMethod(call->GetDexMethodIndex());
Guillaume "Vermeille" Sancheze918d382015-06-03 15:32:41 +0100101 bool must_not_inline = callee_name.find("$noinline$") != std::string::npos;
102 CHECK(!must_not_inline) << "Should not have inlined " << callee_name;
103 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000104 }
105 }
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000106 instruction = next;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000107 }
108 }
109}
110
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100111static bool IsMethodOrDeclaringClassFinal(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700112 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100113 return method->IsFinal() || method->GetDeclaringClass()->IsFinal();
114}
115
116/**
117 * Given the `resolved_method` looked up in the dex cache, try to find
118 * the actual runtime target of an interface or virtual call.
119 * Return nullptr if the runtime target cannot be proven.
120 */
121static ArtMethod* FindVirtualOrInterfaceTarget(HInvoke* invoke, ArtMethod* resolved_method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700122 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100123 if (IsMethodOrDeclaringClassFinal(resolved_method)) {
124 // No need to lookup further, the resolved method will be the target.
125 return resolved_method;
126 }
127
128 HInstruction* receiver = invoke->InputAt(0);
129 if (receiver->IsNullCheck()) {
130 // Due to multiple levels of inlining within the same pass, it might be that
131 // null check does not have the reference type of the actual receiver.
132 receiver = receiver->InputAt(0);
133 }
134 ReferenceTypeInfo info = receiver->GetReferenceTypeInfo();
Calin Juravle2e768302015-07-28 14:41:11 +0000135 DCHECK(info.IsValid()) << "Invalid RTI for " << receiver->DebugName();
136 if (!info.IsExact()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100137 // We currently only support inlining with known receivers.
138 // TODO: Remove this check, we should be able to inline final methods
139 // on unknown receivers.
140 return nullptr;
141 } else if (info.GetTypeHandle()->IsInterface()) {
142 // Statically knowing that the receiver has an interface type cannot
143 // help us find what is the target method.
144 return nullptr;
145 } else if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(info.GetTypeHandle().Get())) {
146 // The method that we're trying to call is not in the receiver's class or super classes.
147 return nullptr;
Nicolas Geoffrayab5327d2016-03-18 11:36:20 +0000148 } else if (info.GetTypeHandle()->IsErroneous()) {
149 // If the type is erroneous, do not go further, as we are going to query the vtable or
150 // imt table, that we can only safely do on non-erroneous classes.
151 return nullptr;
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100152 }
153
154 ClassLinker* cl = Runtime::Current()->GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700155 PointerSize pointer_size = cl->GetImagePointerSize();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100156 if (invoke->IsInvokeInterface()) {
157 resolved_method = info.GetTypeHandle()->FindVirtualMethodForInterface(
158 resolved_method, pointer_size);
159 } else {
160 DCHECK(invoke->IsInvokeVirtual());
161 resolved_method = info.GetTypeHandle()->FindVirtualMethodForVirtual(
162 resolved_method, pointer_size);
163 }
164
165 if (resolved_method == nullptr) {
166 // The information we had on the receiver was not enough to find
167 // the target method. Since we check above the exact type of the receiver,
168 // the only reason this can happen is an IncompatibleClassChangeError.
169 return nullptr;
Alex Light9139e002015-10-09 15:59:48 -0700170 } else if (!resolved_method->IsInvokable()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100171 // The information we had on the receiver was not enough to find
172 // the target method. Since we check above the exact type of the receiver,
173 // the only reason this can happen is an IncompatibleClassChangeError.
174 return nullptr;
175 } else if (IsMethodOrDeclaringClassFinal(resolved_method)) {
176 // A final method has to be the target method.
177 return resolved_method;
178 } else if (info.IsExact()) {
179 // If we found a method and the receiver's concrete type is statically
180 // known, we know for sure the target.
181 return resolved_method;
182 } else {
183 // Even if we did find a method, the receiver type was not enough to
184 // statically find the runtime target.
185 return nullptr;
186 }
187}
188
189static uint32_t FindMethodIndexIn(ArtMethod* method,
190 const DexFile& dex_file,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000191 uint32_t name_and_signature_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700192 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100193 if (IsSameDexFile(*method->GetDexFile(), dex_file)) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100194 return method->GetDexMethodIndex();
195 } else {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000196 return method->FindDexMethodIndexInOtherDexFile(dex_file, name_and_signature_index);
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100197 }
198}
199
Andreas Gampea5b09a62016-11-17 15:21:22 -0800200static dex::TypeIndex FindClassIndexIn(mirror::Class* cls,
201 const DexFile& dex_file,
202 Handle<mirror::DexCache> dex_cache)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700203 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampea5b09a62016-11-17 15:21:22 -0800204 dex::TypeIndex index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100205 if (cls->GetDexCache() == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700206 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000207 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800208 } else if (!cls->GetDexTypeIndex().IsValid()) {
David Sehr709b0702016-10-13 09:12:37 -0700209 DCHECK(cls->IsProxyClass()) << cls->PrettyClass();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100210 // TODO: deal with proxy classes.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100211 } else if (IsSameDexFile(cls->GetDexFile(), dex_file)) {
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100212 DCHECK_EQ(cls->GetDexCache(), dex_cache.Get());
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000213 index = cls->GetDexTypeIndex();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100214 // Update the dex cache to ensure the class is in. The generated code will
215 // consider it is. We make it safe by updating the dex cache, as other
216 // dex files might also load the class, and there is no guarantee the dex
217 // cache of the dex file of the class will be updated.
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000218 if (dex_cache->GetResolvedType(index) == nullptr) {
219 dex_cache->SetResolvedType(index, cls);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100220 }
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100221 } else {
222 index = cls->FindTypeIndexInOtherDexFile(dex_file);
223 // We cannot guarantee the entry in the dex cache will resolve to the same class,
224 // as there may be different class loaders. So only return the index if it's
225 // the right class in the dex cache already.
Andreas Gampea5b09a62016-11-17 15:21:22 -0800226 if (index.IsValid() && dex_cache->GetResolvedType(index) != cls) {
227 index = dex::TypeIndex::Invalid();
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100228 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100229 }
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000230
231 return index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100232}
233
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000234class ScopedProfilingInfoInlineUse {
235 public:
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000236 explicit ScopedProfilingInfoInlineUse(ArtMethod* method, Thread* self)
237 : method_(method),
238 self_(self),
239 // Fetch the profiling info ahead of using it. If it's null when fetching,
240 // we should not call JitCodeCache::DoneInlining.
241 profiling_info_(
242 Runtime::Current()->GetJit()->GetCodeCache()->NotifyCompilerUse(method, self)) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000243 }
244
245 ~ScopedProfilingInfoInlineUse() {
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000246 if (profiling_info_ != nullptr) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700247 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000248 DCHECK_EQ(profiling_info_, method_->GetProfilingInfo(pointer_size));
249 Runtime::Current()->GetJit()->GetCodeCache()->DoneCompilerUse(method_, self_);
250 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000251 }
252
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000253 ProfilingInfo* GetProfilingInfo() const { return profiling_info_; }
254
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000255 private:
256 ArtMethod* const method_;
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000257 Thread* const self_;
258 ProfilingInfo* const profiling_info_;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000259};
260
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000261static bool IsMonomorphic(Handle<mirror::ObjectArray<mirror::Class>> classes)
262 REQUIRES_SHARED(Locks::mutator_lock_) {
263 DCHECK_GE(InlineCache::kIndividualCacheSize, 2);
264 return classes->Get(0) != nullptr && classes->Get(1) == nullptr;
265}
266
267static bool IsMegamorphic(Handle<mirror::ObjectArray<mirror::Class>> classes)
268 REQUIRES_SHARED(Locks::mutator_lock_) {
269 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
270 if (classes->Get(i) == nullptr) {
271 return false;
272 }
273 }
274 return true;
275}
276
277static mirror::Class* GetMonomorphicType(Handle<mirror::ObjectArray<mirror::Class>> classes)
278 REQUIRES_SHARED(Locks::mutator_lock_) {
279 DCHECK(classes->Get(0) != nullptr);
280 return classes->Get(0);
281}
282
283static bool IsUninitialized(Handle<mirror::ObjectArray<mirror::Class>> classes)
284 REQUIRES_SHARED(Locks::mutator_lock_) {
285 return classes->Get(0) == nullptr;
286}
287
288static bool IsPolymorphic(Handle<mirror::ObjectArray<mirror::Class>> classes)
289 REQUIRES_SHARED(Locks::mutator_lock_) {
290 DCHECK_GE(InlineCache::kIndividualCacheSize, 3);
291 return classes->Get(1) != nullptr &&
292 classes->Get(InlineCache::kIndividualCacheSize - 1) == nullptr;
293}
294
Mingyao Yang063fc772016-08-02 11:02:54 -0700295ArtMethod* HInliner::TryCHADevirtualization(ArtMethod* resolved_method) {
296 if (!resolved_method->HasSingleImplementation()) {
297 return nullptr;
298 }
299 if (Runtime::Current()->IsAotCompiler()) {
300 // No CHA-based devirtulization for AOT compiler (yet).
301 return nullptr;
302 }
303 if (outermost_graph_->IsCompilingOsr()) {
304 // We do not support HDeoptimize in OSR methods.
305 return nullptr;
306 }
307 return resolved_method->GetSingleImplementation();
308}
309
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700310bool HInliner::TryInline(HInvoke* invoke_instruction) {
Calin Juravle175dc732015-08-25 15:42:32 +0100311 if (invoke_instruction->IsInvokeUnresolved()) {
312 return false; // Don't bother to move further if we know the method is unresolved.
313 }
314
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000315 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100316 uint32_t method_index = invoke_instruction->GetDexMethodIndex();
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000317 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -0700318 VLOG(compiler) << "Try inlining " << caller_dex_file.PrettyMethod(method_index);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000319
Nicolas Geoffray35071052015-06-09 15:43:38 +0100320 // We can query the dex cache directly. The verifier has populated it already.
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100321 ArtMethod* resolved_method = invoke_instruction->GetResolvedMethod();
Andreas Gampefd2140f2015-12-23 16:30:44 -0800322 ArtMethod* actual_method = nullptr;
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100323 if (resolved_method == nullptr) {
324 DCHECK(invoke_instruction->IsInvokeStaticOrDirect());
325 DCHECK(invoke_instruction->AsInvokeStaticOrDirect()->IsStringInit());
326 VLOG(compiler) << "Not inlining a String.<init> method";
327 return false;
328 } else if (invoke_instruction->IsInvokeStaticOrDirect()) {
Andreas Gampefd2140f2015-12-23 16:30:44 -0800329 actual_method = resolved_method;
Vladimir Marko58155012015-08-19 12:49:41 +0000330 } else {
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100331 // Check if we can statically find the method.
332 actual_method = FindVirtualOrInterfaceTarget(invoke_instruction, resolved_method);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000333 }
334
Mingyao Yang063fc772016-08-02 11:02:54 -0700335 bool cha_devirtualize = false;
336 if (actual_method == nullptr) {
337 ArtMethod* method = TryCHADevirtualization(resolved_method);
338 if (method != nullptr) {
339 cha_devirtualize = true;
340 actual_method = method;
341 }
342 }
343
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100344 if (actual_method != nullptr) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700345 bool result = TryInlineAndReplace(invoke_instruction,
346 actual_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000347 ReferenceTypeInfo::CreateInvalid(),
Mingyao Yang063fc772016-08-02 11:02:54 -0700348 /* do_rtp */ true,
349 cha_devirtualize);
Calin Juravle69158982016-03-16 11:53:41 +0000350 if (result && !invoke_instruction->IsInvokeStaticOrDirect()) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700351 if (cha_devirtualize) {
352 // Add dependency due to devirtulization. We've assumed resolved_method
353 // has single implementation.
354 outermost_graph_->AddCHASingleImplementationDependency(resolved_method);
355 MaybeRecordStat(kCHAInline);
356 } else {
357 MaybeRecordStat(kInlinedInvokeVirtualOrInterface);
358 }
Calin Juravle69158982016-03-16 11:53:41 +0000359 }
360 return result;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100361 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000362
Andreas Gampefd2140f2015-12-23 16:30:44 -0800363 DCHECK(!invoke_instruction->IsInvokeStaticOrDirect());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100364
365 // Check if we can use an inline cache.
366 ArtMethod* caller = graph_->GetArtMethod();
Calin Juravleffc87072016-04-20 14:22:09 +0100367 if (Runtime::Current()->UseJitCompilation()) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000368 // Under JIT, we should always know the caller.
369 DCHECK(caller != nullptr);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000370 ScopedProfilingInfoInlineUse spiis(caller, soa.Self());
371 ProfilingInfo* profiling_info = spiis.GetProfilingInfo();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000372 if (profiling_info != nullptr) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000373 StackHandleScope<1> hs(soa.Self());
374 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
375 Handle<mirror::ObjectArray<mirror::Class>> inline_cache = hs.NewHandle(
376 mirror::ObjectArray<mirror::Class>::Alloc(
377 soa.Self(),
378 class_linker->GetClassRoot(ClassLinker::kClassArrayClass),
379 InlineCache::kIndividualCacheSize));
380 if (inline_cache.Get() == nullptr) {
381 // We got an OOME. Just clear the exception, and don't inline.
382 DCHECK(soa.Self()->IsExceptionPending());
383 soa.Self()->ClearException();
384 VLOG(compiler) << "Out of memory in the compiler when trying to inline";
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000385 return false;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000386 } else {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000387 Runtime::Current()->GetJit()->GetCodeCache()->CopyInlineCacheInto(
388 *profiling_info->GetInlineCache(invoke_instruction->GetDexPc()),
389 inline_cache);
390 if (IsUninitialized(inline_cache)) {
391 VLOG(compiler) << "Interface or virtual call to "
392 << caller_dex_file.PrettyMethod(method_index)
393 << " is not hit and not inlined";
394 return false;
395 } else if (IsMonomorphic(inline_cache)) {
396 MaybeRecordStat(kMonomorphicCall);
397 if (outermost_graph_->IsCompilingOsr()) {
398 // If we are compiling OSR, we pretend this call is polymorphic, as we may come from the
399 // interpreter and it may have seen different receiver types.
400 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
401 } else {
402 return TryInlineMonomorphicCall(invoke_instruction, resolved_method, inline_cache);
403 }
404 } else if (IsPolymorphic(inline_cache)) {
405 MaybeRecordStat(kPolymorphicCall);
406 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
407 } else {
408 DCHECK(IsMegamorphic(inline_cache));
409 VLOG(compiler) << "Interface or virtual call to "
410 << caller_dex_file.PrettyMethod(method_index)
411 << " is megamorphic and not inlined";
412 MaybeRecordStat(kMegamorphicCall);
413 return false;
414 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000415 }
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100416 }
417 }
418
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100419 VLOG(compiler) << "Interface or virtual call to "
David Sehr709b0702016-10-13 09:12:37 -0700420 << caller_dex_file.PrettyMethod(method_index)
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100421 << " could not be statically determined";
422 return false;
423}
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000424
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000425HInstanceFieldGet* HInliner::BuildGetReceiverClass(ClassLinker* class_linker,
426 HInstruction* receiver,
427 uint32_t dex_pc) const {
428 ArtField* field = class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0);
429 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000430 HInstanceFieldGet* result = new (graph_->GetArena()) HInstanceFieldGet(
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000431 receiver,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000432 field,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000433 Primitive::kPrimNot,
434 field->GetOffset(),
435 field->IsVolatile(),
436 field->GetDexFieldIndex(),
437 field->GetDeclaringClass()->GetDexClassDefIndex(),
438 *field->GetDexFile(),
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000439 dex_pc);
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000440 // The class of a field is effectively final, and does not have any memory dependencies.
441 result->SetSideEffects(SideEffects::None());
442 return result;
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000443}
444
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100445bool HInliner::TryInlineMonomorphicCall(HInvoke* invoke_instruction,
446 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000447 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000448 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
449 << invoke_instruction->DebugName();
450
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100451 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Andreas Gampea5b09a62016-11-17 15:21:22 -0800452 dex::TypeIndex class_index = FindClassIndexIn(
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000453 GetMonomorphicType(classes), caller_dex_file, caller_compilation_unit_.GetDexCache());
Andreas Gampea5b09a62016-11-17 15:21:22 -0800454 if (!class_index.IsValid()) {
David Sehr709b0702016-10-13 09:12:37 -0700455 VLOG(compiler) << "Call to " << ArtMethod::PrettyMethod(resolved_method)
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100456 << " from inline cache is not inlined because its class is not"
457 << " accessible to the caller";
458 return false;
459 }
460
461 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700462 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100463 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000464 resolved_method = GetMonomorphicType(classes)->FindVirtualMethodForInterface(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100465 resolved_method, pointer_size);
466 } else {
467 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000468 resolved_method = GetMonomorphicType(classes)->FindVirtualMethodForVirtual(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100469 resolved_method, pointer_size);
470 }
471 DCHECK(resolved_method != nullptr);
472 HInstruction* receiver = invoke_instruction->InputAt(0);
473 HInstruction* cursor = invoke_instruction->GetPrevious();
474 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000475 Handle<mirror::Class> handle = handles_->NewHandle(GetMonomorphicType(classes));
Mingyao Yang063fc772016-08-02 11:02:54 -0700476 if (!TryInlineAndReplace(invoke_instruction,
477 resolved_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000478 ReferenceTypeInfo::Create(handle, /* is_exact */ true),
Mingyao Yang063fc772016-08-02 11:02:54 -0700479 /* do_rtp */ false,
480 /* cha_devirtualize */ false)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100481 return false;
482 }
483
484 // We successfully inlined, now add a guard.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000485 AddTypeGuard(receiver,
486 cursor,
487 bb_cursor,
488 class_index,
Nicolas Geoffray56876342016-12-16 16:09:08 +0000489 GetMonomorphicType(classes),
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000490 invoke_instruction,
491 /* with_deoptimization */ true);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100492
493 // Run type propagation to get the guard typed, and eventually propagate the
494 // type of the receiver.
Vladimir Marko456307a2016-04-19 14:12:13 +0000495 ReferenceTypePropagation rtp_fixup(graph_,
496 outer_compilation_unit_.GetDexCache(),
497 handles_,
498 /* is_first_run */ false);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100499 rtp_fixup.Run();
500
501 MaybeRecordStat(kInlinedMonomorphicCall);
502 return true;
503}
504
Mingyao Yang063fc772016-08-02 11:02:54 -0700505void HInliner::AddCHAGuard(HInstruction* invoke_instruction,
506 uint32_t dex_pc,
507 HInstruction* cursor,
508 HBasicBlock* bb_cursor) {
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800509 HShouldDeoptimizeFlag* deopt_flag = new (graph_->GetArena())
510 HShouldDeoptimizeFlag(graph_->GetArena(), dex_pc);
511 HInstruction* compare = new (graph_->GetArena()) HNotEqual(
Mingyao Yang063fc772016-08-02 11:02:54 -0700512 deopt_flag, graph_->GetIntConstant(0, dex_pc));
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800513 HInstruction* deopt = new (graph_->GetArena()) HDeoptimize(compare, dex_pc);
Mingyao Yang063fc772016-08-02 11:02:54 -0700514
515 if (cursor != nullptr) {
516 bb_cursor->InsertInstructionAfter(deopt_flag, cursor);
517 } else {
518 bb_cursor->InsertInstructionBefore(deopt_flag, bb_cursor->GetFirstInstruction());
519 }
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800520 bb_cursor->InsertInstructionAfter(compare, deopt_flag);
521 bb_cursor->InsertInstructionAfter(deopt, compare);
522
523 // Add receiver as input to aid CHA guard optimization later.
524 deopt_flag->AddInput(invoke_instruction->InputAt(0));
525 DCHECK_EQ(deopt_flag->InputCount(), 1u);
Mingyao Yang063fc772016-08-02 11:02:54 -0700526 deopt->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800527 outermost_graph_->IncrementNumberOfCHAGuards();
Mingyao Yang063fc772016-08-02 11:02:54 -0700528}
529
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000530HInstruction* HInliner::AddTypeGuard(HInstruction* receiver,
531 HInstruction* cursor,
532 HBasicBlock* bb_cursor,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800533 dex::TypeIndex class_index,
Nicolas Geoffray56876342016-12-16 16:09:08 +0000534 mirror::Class* klass,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000535 HInstruction* invoke_instruction,
536 bool with_deoptimization) {
Nicolas Geoffray56876342016-12-16 16:09:08 +0000537 ScopedAssertNoThreadSuspension sants("Adding compiler type guard");
538
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000539 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
540 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
541 class_linker, receiver, invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000542 if (cursor != nullptr) {
543 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
544 } else {
545 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
546 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000547
548 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
549 bool is_referrer = (klass == outermost_graph_->GetArtMethod()->GetDeclaringClass());
550 // Note that we will just compare the classes, so we don't need Java semantics access checks.
551 // Note that the type index and the dex file are relative to the method this type guard is
552 // inlined into.
553 HLoadClass* load_class = new (graph_->GetArena()) HLoadClass(graph_->GetCurrentMethod(),
554 class_index,
555 caller_dex_file,
556 is_referrer,
557 invoke_instruction->GetDexPc(),
558 /* needs_access_check */ false);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000559 bb_cursor->InsertInstructionAfter(load_class, receiver_class);
Nicolas Geoffray56876342016-12-16 16:09:08 +0000560 // Sharpen after adding the instruction, as the sharpening may remove inputs.
561 HSharpening::SharpenClass(load_class, klass, handles_, codegen_, compiler_driver_);
562
563 // TODO: Extend reference type propagation to understand the guard.
564 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(load_class, receiver_class);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000565 bb_cursor->InsertInstructionAfter(compare, load_class);
566 if (with_deoptimization) {
567 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
568 compare, invoke_instruction->GetDexPc());
569 bb_cursor->InsertInstructionAfter(deoptimize, compare);
570 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
571 }
572 return compare;
573}
574
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000575bool HInliner::TryInlinePolymorphicCall(HInvoke* invoke_instruction,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100576 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000577 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000578 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
579 << invoke_instruction->DebugName();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000580
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000581 if (TryInlinePolymorphicCallToSameTarget(invoke_instruction, resolved_method, classes)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000582 return true;
583 }
584
585 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700586 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000587 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
588
589 bool all_targets_inlined = true;
590 bool one_target_inlined = false;
591 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000592 if (classes->Get(i) == nullptr) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000593 break;
594 }
595 ArtMethod* method = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000596
597 Handle<mirror::Class> handle = handles_->NewHandle(classes->Get(i));
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000598 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000599 method = handle->FindVirtualMethodForInterface(resolved_method, pointer_size);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000600 } else {
601 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000602 method = handle->FindVirtualMethodForVirtual(resolved_method, pointer_size);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000603 }
604
605 HInstruction* receiver = invoke_instruction->InputAt(0);
606 HInstruction* cursor = invoke_instruction->GetPrevious();
607 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
608
Andreas Gampea5b09a62016-11-17 15:21:22 -0800609 dex::TypeIndex class_index = FindClassIndexIn(
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000610 handle.Get(), caller_dex_file, caller_compilation_unit_.GetDexCache());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000611 HInstruction* return_replacement = nullptr;
Andreas Gampea5b09a62016-11-17 15:21:22 -0800612 if (!class_index.IsValid() ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000613 !TryBuildAndInline(invoke_instruction,
614 method,
615 ReferenceTypeInfo::Create(handle, /* is_exact */ true),
616 &return_replacement)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000617 all_targets_inlined = false;
618 } else {
619 one_target_inlined = true;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000620
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000621 VLOG(compiler) << "Polymorphic call to " << ArtMethod::PrettyMethod(resolved_method)
622 << " has inlined " << ArtMethod::PrettyMethod(method);
623
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000624 // If we have inlined all targets before, and this receiver is the last seen,
625 // we deoptimize instead of keeping the original invoke instruction.
626 bool deoptimize = all_targets_inlined &&
627 (i != InlineCache::kIndividualCacheSize - 1) &&
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000628 (classes->Get(i + 1) == nullptr);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100629
630 if (outermost_graph_->IsCompilingOsr()) {
631 // We do not support HDeoptimize in OSR methods.
632 deoptimize = false;
633 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000634 HInstruction* compare = AddTypeGuard(receiver,
635 cursor,
636 bb_cursor,
637 class_index,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000638 handle.Get(),
Nicolas Geoffray56876342016-12-16 16:09:08 +0000639 invoke_instruction,
640 deoptimize);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000641 if (deoptimize) {
642 if (return_replacement != nullptr) {
643 invoke_instruction->ReplaceWith(return_replacement);
644 }
645 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
646 // Because the inline cache data can be populated concurrently, we force the end of the
647 // iteration. Otherhwise, we could see a new receiver type.
648 break;
649 } else {
650 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
651 }
652 }
653 }
654
655 if (!one_target_inlined) {
David Sehr709b0702016-10-13 09:12:37 -0700656 VLOG(compiler) << "Call to " << ArtMethod::PrettyMethod(resolved_method)
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000657 << " from inline cache is not inlined because none"
658 << " of its targets could be inlined";
659 return false;
660 }
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000661
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000662 MaybeRecordStat(kInlinedPolymorphicCall);
663
664 // Run type propagation to get the guards typed.
Vladimir Marko456307a2016-04-19 14:12:13 +0000665 ReferenceTypePropagation rtp_fixup(graph_,
666 outer_compilation_unit_.GetDexCache(),
667 handles_,
668 /* is_first_run */ false);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000669 rtp_fixup.Run();
670 return true;
671}
672
673void HInliner::CreateDiamondPatternForPolymorphicInline(HInstruction* compare,
674 HInstruction* return_replacement,
675 HInstruction* invoke_instruction) {
676 uint32_t dex_pc = invoke_instruction->GetDexPc();
677 HBasicBlock* cursor_block = compare->GetBlock();
678 HBasicBlock* original_invoke_block = invoke_instruction->GetBlock();
679 ArenaAllocator* allocator = graph_->GetArena();
680
681 // Spit the block after the compare: `cursor_block` will now be the start of the diamond,
682 // and the returned block is the start of the then branch (that could contain multiple blocks).
683 HBasicBlock* then = cursor_block->SplitAfterForInlining(compare);
684
685 // Split the block containing the invoke before and after the invoke. The returned block
686 // of the split before will contain the invoke and will be the otherwise branch of
687 // the diamond. The returned block of the split after will be the merge block
688 // of the diamond.
689 HBasicBlock* end_then = invoke_instruction->GetBlock();
690 HBasicBlock* otherwise = end_then->SplitBeforeForInlining(invoke_instruction);
691 HBasicBlock* merge = otherwise->SplitAfterForInlining(invoke_instruction);
692
693 // If the methods we are inlining return a value, we create a phi in the merge block
694 // that will have the `invoke_instruction and the `return_replacement` as inputs.
695 if (return_replacement != nullptr) {
696 HPhi* phi = new (allocator) HPhi(
697 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke_instruction->GetType()), dex_pc);
698 merge->AddPhi(phi);
699 invoke_instruction->ReplaceWith(phi);
700 phi->AddInput(return_replacement);
701 phi->AddInput(invoke_instruction);
702 }
703
704 // Add the control flow instructions.
705 otherwise->AddInstruction(new (allocator) HGoto(dex_pc));
706 end_then->AddInstruction(new (allocator) HGoto(dex_pc));
707 cursor_block->AddInstruction(new (allocator) HIf(compare, dex_pc));
708
709 // Add the newly created blocks to the graph.
710 graph_->AddBlock(then);
711 graph_->AddBlock(otherwise);
712 graph_->AddBlock(merge);
713
714 // Set up successor (and implictly predecessor) relations.
715 cursor_block->AddSuccessor(otherwise);
716 cursor_block->AddSuccessor(then);
717 end_then->AddSuccessor(merge);
718 otherwise->AddSuccessor(merge);
719
720 // Set up dominance information.
721 then->SetDominator(cursor_block);
722 cursor_block->AddDominatedBlock(then);
723 otherwise->SetDominator(cursor_block);
724 cursor_block->AddDominatedBlock(otherwise);
725 merge->SetDominator(cursor_block);
726 cursor_block->AddDominatedBlock(merge);
727
728 // Update the revert post order.
729 size_t index = IndexOfElement(graph_->reverse_post_order_, cursor_block);
730 MakeRoomFor(&graph_->reverse_post_order_, 1, index);
731 graph_->reverse_post_order_[++index] = then;
732 index = IndexOfElement(graph_->reverse_post_order_, end_then);
733 MakeRoomFor(&graph_->reverse_post_order_, 2, index);
734 graph_->reverse_post_order_[++index] = otherwise;
735 graph_->reverse_post_order_[++index] = merge;
736
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000737
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +0000738 graph_->UpdateLoopAndTryInformationOfNewBlock(
739 then, original_invoke_block, /* replace_if_back_edge */ false);
740 graph_->UpdateLoopAndTryInformationOfNewBlock(
741 otherwise, original_invoke_block, /* replace_if_back_edge */ false);
742
743 // In case the original invoke location was a back edge, we need to update
744 // the loop to now have the merge block as a back edge.
745 graph_->UpdateLoopAndTryInformationOfNewBlock(
746 merge, original_invoke_block, /* replace_if_back_edge */ true);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000747}
748
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000749bool HInliner::TryInlinePolymorphicCallToSameTarget(
750 HInvoke* invoke_instruction,
751 ArtMethod* resolved_method,
752 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000753 // This optimization only works under JIT for now.
Calin Juravleffc87072016-04-20 14:22:09 +0100754 DCHECK(Runtime::Current()->UseJitCompilation());
Roland Levillain2aba7cd2016-02-03 12:27:20 +0000755 if (graph_->GetInstructionSet() == kMips64) {
756 // TODO: Support HClassTableGet for mips64.
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000757 return false;
758 }
759 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700760 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000761
762 DCHECK(resolved_method != nullptr);
763 ArtMethod* actual_method = nullptr;
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000764 size_t method_index = invoke_instruction->IsInvokeVirtual()
765 ? invoke_instruction->AsInvokeVirtual()->GetVTableIndex()
766 : invoke_instruction->AsInvokeInterface()->GetImtIndex();
767
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000768 // Check whether we are actually calling the same method among
769 // the different types seen.
770 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000771 if (classes->Get(i) == nullptr) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000772 break;
773 }
774 ArtMethod* new_method = nullptr;
775 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000776 new_method = classes->Get(i)->GetImt(pointer_size)->Get(
Matthew Gharrity465ecc82016-07-19 21:32:52 +0000777 method_index, pointer_size);
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000778 if (new_method->IsRuntimeMethod()) {
779 // Bail out as soon as we see a conflict trampoline in one of the target's
780 // interface table.
781 return false;
782 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000783 } else {
784 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000785 new_method = classes->Get(i)->GetEmbeddedVTableEntry(method_index, pointer_size);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000786 }
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000787 DCHECK(new_method != nullptr);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000788 if (actual_method == nullptr) {
789 actual_method = new_method;
790 } else if (actual_method != new_method) {
791 // Different methods, bailout.
David Sehr709b0702016-10-13 09:12:37 -0700792 VLOG(compiler) << "Call to " << ArtMethod::PrettyMethod(resolved_method)
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000793 << " from inline cache is not inlined because it resolves"
794 << " to different methods";
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000795 return false;
796 }
797 }
798
799 HInstruction* receiver = invoke_instruction->InputAt(0);
800 HInstruction* cursor = invoke_instruction->GetPrevious();
801 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
802
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100803 HInstruction* return_replacement = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000804 if (!TryBuildAndInline(invoke_instruction,
805 actual_method,
806 ReferenceTypeInfo::CreateInvalid(),
807 &return_replacement)) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000808 return false;
809 }
810
811 // We successfully inlined, now add a guard.
812 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
813 class_linker, receiver, invoke_instruction->GetDexPc());
814
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000815 Primitive::Type type = Is64BitInstructionSet(graph_->GetInstructionSet())
816 ? Primitive::kPrimLong
817 : Primitive::kPrimInt;
818 HClassTableGet* class_table_get = new (graph_->GetArena()) HClassTableGet(
819 receiver_class,
820 type,
Vladimir Markoa1de9182016-02-25 11:37:38 +0000821 invoke_instruction->IsInvokeVirtual() ? HClassTableGet::TableKind::kVTable
822 : HClassTableGet::TableKind::kIMTable,
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000823 method_index,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000824 invoke_instruction->GetDexPc());
825
826 HConstant* constant;
827 if (type == Primitive::kPrimLong) {
828 constant = graph_->GetLongConstant(
829 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
830 } else {
831 constant = graph_->GetIntConstant(
832 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
833 }
834
835 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(class_table_get, constant);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000836 if (cursor != nullptr) {
837 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
838 } else {
839 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
840 }
841 bb_cursor->InsertInstructionAfter(class_table_get, receiver_class);
842 bb_cursor->InsertInstructionAfter(compare, class_table_get);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100843
844 if (outermost_graph_->IsCompilingOsr()) {
845 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
846 } else {
847 // TODO: Extend reference type propagation to understand the guard.
848 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
849 compare, invoke_instruction->GetDexPc());
850 bb_cursor->InsertInstructionAfter(deoptimize, compare);
851 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
852 if (return_replacement != nullptr) {
853 invoke_instruction->ReplaceWith(return_replacement);
854 }
Nicolas Geoffray1be7cbd2016-04-29 13:56:01 +0100855 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100856 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000857
858 // Run type propagation to get the guard typed.
Vladimir Marko456307a2016-04-19 14:12:13 +0000859 ReferenceTypePropagation rtp_fixup(graph_,
860 outer_compilation_unit_.GetDexCache(),
861 handles_,
862 /* is_first_run */ false);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000863 rtp_fixup.Run();
864
865 MaybeRecordStat(kInlinedPolymorphicCall);
866
867 return true;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100868}
869
Mingyao Yang063fc772016-08-02 11:02:54 -0700870bool HInliner::TryInlineAndReplace(HInvoke* invoke_instruction,
871 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000872 ReferenceTypeInfo receiver_type,
Mingyao Yang063fc772016-08-02 11:02:54 -0700873 bool do_rtp,
874 bool cha_devirtualize) {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000875 HInstruction* return_replacement = nullptr;
Mingyao Yang063fc772016-08-02 11:02:54 -0700876 uint32_t dex_pc = invoke_instruction->GetDexPc();
877 HInstruction* cursor = invoke_instruction->GetPrevious();
878 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000879 if (!TryBuildAndInline(invoke_instruction, method, receiver_type, &return_replacement)) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000880 if (invoke_instruction->IsInvokeInterface()) {
881 // Turn an invoke-interface into an invoke-virtual. An invoke-virtual is always
882 // better than an invoke-interface because:
883 // 1) In the best case, the interface call has one more indirection (to fetch the IMT).
884 // 2) We will not go to the conflict trampoline with an invoke-virtual.
885 // TODO: Consider sharpening once it is not dependent on the compiler driver.
886 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100887 uint32_t dex_method_index = FindMethodIndexIn(
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000888 method, caller_dex_file, invoke_instruction->GetDexMethodIndex());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100889 if (dex_method_index == DexFile::kDexNoIndex) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000890 return false;
891 }
892 HInvokeVirtual* new_invoke = new (graph_->GetArena()) HInvokeVirtual(
893 graph_->GetArena(),
894 invoke_instruction->GetNumberOfArguments(),
895 invoke_instruction->GetType(),
896 invoke_instruction->GetDexPc(),
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100897 dex_method_index,
898 method,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000899 method->GetMethodIndex());
900 HInputsRef inputs = invoke_instruction->GetInputs();
901 for (size_t index = 0; index != inputs.size(); ++index) {
902 new_invoke->SetArgumentAt(index, inputs[index]);
903 }
904 invoke_instruction->GetBlock()->InsertInstructionBefore(new_invoke, invoke_instruction);
905 new_invoke->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
906 if (invoke_instruction->GetType() == Primitive::kPrimNot) {
907 new_invoke->SetReferenceTypeInfo(invoke_instruction->GetReferenceTypeInfo());
908 }
909 return_replacement = new_invoke;
910 } else {
911 // TODO: Consider sharpening an invoke virtual once it is not dependent on the
912 // compiler driver.
913 return false;
914 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000915 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700916 if (cha_devirtualize) {
917 AddCHAGuard(invoke_instruction, dex_pc, cursor, bb_cursor);
918 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000919 if (return_replacement != nullptr) {
920 invoke_instruction->ReplaceWith(return_replacement);
921 }
922 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
David Brazdil94ab38f2016-06-21 17:48:19 +0100923 FixUpReturnReferenceType(method, return_replacement);
924 if (do_rtp && ReturnTypeMoreSpecific(invoke_instruction, return_replacement)) {
925 // Actual return value has a more specific type than the method's declared
926 // return type. Run RTP again on the outer graph to propagate it.
927 ReferenceTypePropagation(graph_,
928 outer_compilation_unit_.GetDexCache(),
929 handles_,
930 /* is_first_run */ false).Run();
931 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000932 return true;
933}
934
935bool HInliner::TryBuildAndInline(HInvoke* invoke_instruction,
936 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000937 ReferenceTypeInfo receiver_type,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000938 HInstruction** return_replacement) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100939 if (method->IsProxyMethod()) {
David Sehr709b0702016-10-13 09:12:37 -0700940 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100941 << " is not inlined because of unimplemented inline support for proxy methods.";
942 return false;
943 }
944
Jeff Haodcdc85b2015-12-04 14:06:18 -0800945 // Check whether we're allowed to inline. The outermost compilation unit is the relevant
946 // dex file here (though the transitivity of an inline chain would allow checking the calller).
947 if (!compiler_driver_->MayInline(method->GetDexFile(),
948 outer_compilation_unit_.GetDexFile())) {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000949 if (TryPatternSubstitution(invoke_instruction, method, return_replacement)) {
David Sehr709b0702016-10-13 09:12:37 -0700950 VLOG(compiler) << "Successfully replaced pattern of invoke "
951 << method->PrettyMethod();
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000952 MaybeRecordStat(kReplacedInvokeWithSimplePattern);
953 return true;
954 }
David Sehr709b0702016-10-13 09:12:37 -0700955 VLOG(compiler) << "Won't inline " << method->PrettyMethod() << " in "
Jeff Haodcdc85b2015-12-04 14:06:18 -0800956 << outer_compilation_unit_.GetDexFile()->GetLocation() << " ("
957 << caller_compilation_unit_.GetDexFile()->GetLocation() << ") from "
958 << method->GetDexFile()->GetLocation();
959 return false;
960 }
961
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100962 bool same_dex_file = IsSameDexFile(*outer_compilation_unit_.GetDexFile(), *method->GetDexFile());
963
964 const DexFile::CodeItem* code_item = method->GetCodeItem();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000965
966 if (code_item == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700967 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000968 << " is not inlined because it is native";
969 return false;
970 }
971
Calin Juravleec748352015-07-29 13:52:12 +0100972 size_t inline_max_code_units = compiler_driver_->GetCompilerOptions().GetInlineMaxCodeUnits();
973 if (code_item->insns_size_in_code_units_ > inline_max_code_units) {
David Sehr709b0702016-10-13 09:12:37 -0700974 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000975 << " is too big to inline: "
976 << code_item->insns_size_in_code_units_
977 << " > "
978 << inline_max_code_units;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000979 return false;
980 }
981
982 if (code_item->tries_size_ != 0) {
David Sehr709b0702016-10-13 09:12:37 -0700983 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000984 << " is not inlined because of try block";
985 return false;
986 }
987
Nicolas Geoffray250a3782016-04-20 16:27:53 +0100988 if (!method->IsCompilable()) {
David Sehr709b0702016-10-13 09:12:37 -0700989 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffray250a3782016-04-20 16:27:53 +0100990 << " has soft failures un-handled by the compiler, so it cannot be inlined";
991 }
992
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100993 if (!method->GetDeclaringClass()->IsVerified()) {
994 uint16_t class_def_idx = method->GetDeclaringClass()->GetDexClassDefIndex();
Calin Juravleffc87072016-04-20 14:22:09 +0100995 if (Runtime::Current()->UseJitCompilation() ||
Nicolas Geoffray5b82d332016-02-18 14:22:32 +0000996 !compiler_driver_->IsMethodVerifiedWithoutFailures(
997 method->GetDexMethodIndex(), class_def_idx, *method->GetDexFile())) {
David Sehr709b0702016-10-13 09:12:37 -0700998 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffrayccc61972015-10-01 14:34:20 +0100999 << " couldn't be verified, so it cannot be inlined";
1000 return false;
1001 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001002 }
1003
Roland Levillain4c0eb422015-04-24 16:43:49 +01001004 if (invoke_instruction->IsInvokeStaticOrDirect() &&
1005 invoke_instruction->AsInvokeStaticOrDirect()->IsStaticWithImplicitClinitCheck()) {
1006 // Case of a static method that cannot be inlined because it implicitly
1007 // requires an initialization check of its declaring class.
David Sehr709b0702016-10-13 09:12:37 -07001008 VLOG(compiler) << "Method " << method->PrettyMethod()
Roland Levillain4c0eb422015-04-24 16:43:49 +01001009 << " is not inlined because it is static and requires a clinit"
1010 << " check that cannot be emitted due to Dex cache limitations";
1011 return false;
1012 }
1013
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001014 if (!TryBuildAndInlineHelper(
1015 invoke_instruction, method, receiver_type, same_dex_file, return_replacement)) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001016 return false;
1017 }
1018
David Sehr709b0702016-10-13 09:12:37 -07001019 VLOG(compiler) << "Successfully inlined " << method->PrettyMethod();
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001020 MaybeRecordStat(kInlinedInvoke);
1021 return true;
1022}
1023
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001024static HInstruction* GetInvokeInputForArgVRegIndex(HInvoke* invoke_instruction,
1025 size_t arg_vreg_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001026 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001027 size_t input_index = 0;
1028 for (size_t i = 0; i < arg_vreg_index; ++i, ++input_index) {
1029 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
1030 if (Primitive::Is64BitType(invoke_instruction->InputAt(input_index)->GetType())) {
1031 ++i;
1032 DCHECK_NE(i, arg_vreg_index);
1033 }
1034 }
1035 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
1036 return invoke_instruction->InputAt(input_index);
1037}
1038
1039// Try to recognize known simple patterns and replace invoke call with appropriate instructions.
1040bool HInliner::TryPatternSubstitution(HInvoke* invoke_instruction,
1041 ArtMethod* resolved_method,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001042 HInstruction** return_replacement) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001043 InlineMethod inline_method;
1044 if (!InlineMethodAnalyser::AnalyseMethodCode(resolved_method, &inline_method)) {
1045 return false;
1046 }
1047
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001048 switch (inline_method.opcode) {
1049 case kInlineOpNop:
1050 DCHECK_EQ(invoke_instruction->GetType(), Primitive::kPrimVoid);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001051 *return_replacement = nullptr;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001052 break;
1053 case kInlineOpReturnArg:
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001054 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction,
1055 inline_method.d.return_data.arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001056 break;
1057 case kInlineOpNonWideConst:
1058 if (resolved_method->GetShorty()[0] == 'L') {
1059 DCHECK_EQ(inline_method.d.data, 0u);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001060 *return_replacement = graph_->GetNullConstant();
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001061 } else {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001062 *return_replacement = graph_->GetIntConstant(static_cast<int32_t>(inline_method.d.data));
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001063 }
1064 break;
1065 case kInlineOpIGet: {
1066 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1067 if (data.method_is_static || data.object_arg != 0u) {
1068 // TODO: Needs null check.
1069 return false;
1070 }
Vladimir Marko354efa62016-02-04 19:46:56 +00001071 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001072 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
Vladimir Marko354efa62016-02-04 19:46:56 +00001073 HInstanceFieldGet* iget = CreateInstanceFieldGet(dex_cache, data.field_idx, obj);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001074 DCHECK_EQ(iget->GetFieldOffset().Uint32Value(), data.field_offset);
1075 DCHECK_EQ(iget->IsVolatile() ? 1u : 0u, data.is_volatile);
1076 invoke_instruction->GetBlock()->InsertInstructionBefore(iget, invoke_instruction);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001077 *return_replacement = iget;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001078 break;
1079 }
1080 case kInlineOpIPut: {
1081 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1082 if (data.method_is_static || data.object_arg != 0u) {
1083 // TODO: Needs null check.
1084 return false;
1085 }
Vladimir Marko354efa62016-02-04 19:46:56 +00001086 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001087 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
1088 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, data.src_arg);
Vladimir Marko354efa62016-02-04 19:46:56 +00001089 HInstanceFieldSet* iput = CreateInstanceFieldSet(dex_cache, data.field_idx, obj, value);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001090 DCHECK_EQ(iput->GetFieldOffset().Uint32Value(), data.field_offset);
1091 DCHECK_EQ(iput->IsVolatile() ? 1u : 0u, data.is_volatile);
1092 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1093 if (data.return_arg_plus1 != 0u) {
1094 size_t return_arg = data.return_arg_plus1 - 1u;
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001095 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction, return_arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001096 }
1097 break;
1098 }
Vladimir Marko354efa62016-02-04 19:46:56 +00001099 case kInlineOpConstructor: {
1100 const InlineConstructorData& data = inline_method.d.constructor_data;
1101 // Get the indexes to arrays for easier processing.
1102 uint16_t iput_field_indexes[] = {
1103 data.iput0_field_index, data.iput1_field_index, data.iput2_field_index
1104 };
1105 uint16_t iput_args[] = { data.iput0_arg, data.iput1_arg, data.iput2_arg };
1106 static_assert(arraysize(iput_args) == arraysize(iput_field_indexes), "Size mismatch");
1107 // Count valid field indexes.
1108 size_t number_of_iputs = 0u;
1109 while (number_of_iputs != arraysize(iput_field_indexes) &&
1110 iput_field_indexes[number_of_iputs] != DexFile::kDexNoIndex16) {
1111 // Check that there are no duplicate valid field indexes.
1112 DCHECK_EQ(0, std::count(iput_field_indexes + number_of_iputs + 1,
1113 iput_field_indexes + arraysize(iput_field_indexes),
1114 iput_field_indexes[number_of_iputs]));
1115 ++number_of_iputs;
1116 }
1117 // Check that there are no valid field indexes in the rest of the array.
1118 DCHECK_EQ(0, std::count_if(iput_field_indexes + number_of_iputs,
1119 iput_field_indexes + arraysize(iput_field_indexes),
1120 [](uint16_t index) { return index != DexFile::kDexNoIndex16; }));
1121
1122 // Create HInstanceFieldSet for each IPUT that stores non-zero data.
1123 Handle<mirror::DexCache> dex_cache;
1124 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, /* this */ 0u);
1125 bool needs_constructor_barrier = false;
1126 for (size_t i = 0; i != number_of_iputs; ++i) {
1127 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, iput_args[i]);
Roland Levillain1a653882016-03-18 18:05:57 +00001128 if (!value->IsConstant() || !value->AsConstant()->IsZeroBitPattern()) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001129 if (dex_cache.GetReference() == nullptr) {
1130 dex_cache = handles_->NewHandle(resolved_method->GetDexCache());
1131 }
1132 uint16_t field_index = iput_field_indexes[i];
1133 HInstanceFieldSet* iput = CreateInstanceFieldSet(dex_cache, field_index, obj, value);
1134 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1135
1136 // Check whether the field is final. If it is, we need to add a barrier.
Andreas Gampe542451c2016-07-26 09:02:02 -07001137 PointerSize pointer_size = InstructionSetPointerSize(codegen_->GetInstructionSet());
Vladimir Marko354efa62016-02-04 19:46:56 +00001138 ArtField* resolved_field = dex_cache->GetResolvedField(field_index, pointer_size);
1139 DCHECK(resolved_field != nullptr);
1140 if (resolved_field->IsFinal()) {
1141 needs_constructor_barrier = true;
1142 }
1143 }
1144 }
1145 if (needs_constructor_barrier) {
1146 HMemoryBarrier* barrier = new (graph_->GetArena()) HMemoryBarrier(kStoreStore, kNoDexPc);
1147 invoke_instruction->GetBlock()->InsertInstructionBefore(barrier, invoke_instruction);
1148 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001149 *return_replacement = nullptr;
Vladimir Marko354efa62016-02-04 19:46:56 +00001150 break;
1151 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001152 default:
1153 LOG(FATAL) << "UNREACHABLE";
1154 UNREACHABLE();
1155 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001156 return true;
1157}
1158
Vladimir Marko354efa62016-02-04 19:46:56 +00001159HInstanceFieldGet* HInliner::CreateInstanceFieldGet(Handle<mirror::DexCache> dex_cache,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001160 uint32_t field_index,
1161 HInstruction* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001162 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001163 PointerSize pointer_size = InstructionSetPointerSize(codegen_->GetInstructionSet());
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001164 ArtField* resolved_field = dex_cache->GetResolvedField(field_index, pointer_size);
1165 DCHECK(resolved_field != nullptr);
1166 HInstanceFieldGet* iget = new (graph_->GetArena()) HInstanceFieldGet(
1167 obj,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001168 resolved_field,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001169 resolved_field->GetTypeAsPrimitiveType(),
1170 resolved_field->GetOffset(),
1171 resolved_field->IsVolatile(),
1172 field_index,
1173 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Marko354efa62016-02-04 19:46:56 +00001174 *dex_cache->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001175 // Read barrier generates a runtime call in slow path and we need a valid
1176 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1177 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001178 if (iget->GetType() == Primitive::kPrimNot) {
Vladimir Marko456307a2016-04-19 14:12:13 +00001179 // Use the same dex_cache that we used for field lookup as the hint_dex_cache.
1180 ReferenceTypePropagation rtp(graph_, dex_cache, handles_, /* is_first_run */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001181 rtp.Visit(iget);
1182 }
1183 return iget;
1184}
1185
Vladimir Marko354efa62016-02-04 19:46:56 +00001186HInstanceFieldSet* HInliner::CreateInstanceFieldSet(Handle<mirror::DexCache> dex_cache,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001187 uint32_t field_index,
1188 HInstruction* obj,
1189 HInstruction* value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001190 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001191 PointerSize pointer_size = InstructionSetPointerSize(codegen_->GetInstructionSet());
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001192 ArtField* resolved_field = dex_cache->GetResolvedField(field_index, pointer_size);
1193 DCHECK(resolved_field != nullptr);
1194 HInstanceFieldSet* iput = new (graph_->GetArena()) HInstanceFieldSet(
1195 obj,
1196 value,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001197 resolved_field,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001198 resolved_field->GetTypeAsPrimitiveType(),
1199 resolved_field->GetOffset(),
1200 resolved_field->IsVolatile(),
1201 field_index,
1202 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Marko354efa62016-02-04 19:46:56 +00001203 *dex_cache->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001204 // Read barrier generates a runtime call in slow path and we need a valid
1205 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1206 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001207 return iput;
1208}
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001209
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001210bool HInliner::TryBuildAndInlineHelper(HInvoke* invoke_instruction,
1211 ArtMethod* resolved_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001212 ReferenceTypeInfo receiver_type,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001213 bool same_dex_file,
1214 HInstruction** return_replacement) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001215 DCHECK(!(resolved_method->IsStatic() && receiver_type.IsValid()));
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001216 ScopedObjectAccess soa(Thread::Current());
1217 const DexFile::CodeItem* code_item = resolved_method->GetCodeItem();
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001218 const DexFile& callee_dex_file = *resolved_method->GetDexFile();
1219 uint32_t method_index = resolved_method->GetDexMethodIndex();
Calin Juravle2e768302015-07-28 14:41:11 +00001220 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Mathieu Chartier736b5602015-09-02 14:54:11 -07001221 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Nicolas Geoffrayf1aedb12016-07-28 03:49:14 +01001222 Handle<mirror::ClassLoader> class_loader(handles_->NewHandle(
1223 resolved_method->GetDeclaringClass()->GetClassLoader()));
1224
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001225 DexCompilationUnit dex_compilation_unit(
Nicolas Geoffrayf1aedb12016-07-28 03:49:14 +01001226 class_loader.ToJObject(),
Nicolas Geoffray5b82d332016-02-18 14:22:32 +00001227 class_linker,
1228 callee_dex_file,
1229 code_item,
1230 resolved_method->GetDeclaringClass()->GetDexClassDefIndex(),
1231 method_index,
1232 resolved_method->GetAccessFlags(),
1233 /* verified_method */ nullptr,
1234 dex_cache);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001235
Calin Juravle3cd4fc82015-05-14 15:15:42 +01001236 bool requires_ctor_barrier = false;
1237
1238 if (dex_compilation_unit.IsConstructor()) {
1239 // If it's a super invocation and we already generate a barrier there's no need
1240 // to generate another one.
1241 // We identify super calls by looking at the "this" pointer. If its value is the
1242 // same as the local "this" pointer then we must have a super invocation.
1243 bool is_super_invocation = invoke_instruction->InputAt(0)->IsParameterValue()
1244 && invoke_instruction->InputAt(0)->AsParameterValue()->IsThis();
1245 if (is_super_invocation && graph_->ShouldGenerateConstructorBarrier()) {
1246 requires_ctor_barrier = false;
1247 } else {
1248 Thread* self = Thread::Current();
1249 requires_ctor_barrier = compiler_driver_->RequiresConstructorBarrier(self,
1250 dex_compilation_unit.GetDexFile(),
1251 dex_compilation_unit.GetClassDefIndex());
1252 }
1253 }
1254
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001255 InvokeType invoke_type = invoke_instruction->GetInvokeType();
Nicolas Geoffray35071052015-06-09 15:43:38 +01001256 if (invoke_type == kInterface) {
1257 // We have statically resolved the dispatch. To please the class linker
1258 // at runtime, we change this call as if it was a virtual call.
1259 invoke_type = kVirtual;
1260 }
David Brazdil3f523062016-02-29 16:53:33 +00001261
1262 const int32_t caller_instruction_counter = graph_->GetCurrentInstructionId();
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +00001263 HGraph* callee_graph = new (graph_->GetArena()) HGraph(
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001264 graph_->GetArena(),
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001265 callee_dex_file,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001266 method_index,
Calin Juravle3cd4fc82015-05-14 15:15:42 +01001267 requires_ctor_barrier,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001268 compiler_driver_->GetInstructionSet(),
Nicolas Geoffray35071052015-06-09 15:43:38 +01001269 invoke_type,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001270 graph_->IsDebuggable(),
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001271 /* osr */ false,
David Brazdil3f523062016-02-29 16:53:33 +00001272 caller_instruction_counter);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001273 callee_graph->SetArtMethod(resolved_method);
David Brazdil5e8b1372015-01-23 14:39:08 +00001274
Roland Levillaina8013fd2016-04-04 15:34:31 +01001275 // When they are needed, allocate `inline_stats` on the heap instead
1276 // of on the stack, as Clang might produce a stack frame too large
1277 // for this function, that would not fit the requirements of the
1278 // `-Wframe-larger-than` option.
1279 std::unique_ptr<OptimizingCompilerStats> inline_stats =
1280 (stats_ == nullptr) ? nullptr : MakeUnique<OptimizingCompilerStats>();
David Brazdil5e8b1372015-01-23 14:39:08 +00001281 HGraphBuilder builder(callee_graph,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001282 &dex_compilation_unit,
1283 &outer_compilation_unit_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001284 resolved_method->GetDexFile(),
David Brazdil86ea7ee2016-02-16 09:26:07 +00001285 *code_item,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001286 compiler_driver_,
Roland Levillaina8013fd2016-04-04 15:34:31 +01001287 inline_stats.get(),
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001288 resolved_method->GetQuickenedInfo(class_linker->GetImagePointerSize()),
David Brazdildee58d62016-04-07 09:54:26 +00001289 dex_cache,
1290 handles_);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001291
David Brazdildee58d62016-04-07 09:54:26 +00001292 if (builder.BuildGraph() != kAnalysisSuccess) {
David Sehr709b0702016-10-13 09:12:37 -07001293 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001294 << " could not be built, so cannot be inlined";
1295 return false;
1296 }
1297
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001298 if (!RegisterAllocator::CanAllocateRegistersFor(*callee_graph,
1299 compiler_driver_->GetInstructionSet())) {
David Sehr709b0702016-10-13 09:12:37 -07001300 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001301 << " cannot be inlined because of the register allocator";
1302 return false;
1303 }
1304
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001305 size_t parameter_index = 0;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001306 bool run_rtp = false;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001307 for (HInstructionIterator instructions(callee_graph->GetEntryBlock()->GetInstructions());
1308 !instructions.Done();
1309 instructions.Advance()) {
1310 HInstruction* current = instructions.Current();
1311 if (current->IsParameterValue()) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001312 HInstruction* argument = invoke_instruction->InputAt(parameter_index);
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001313 if (argument->IsNullConstant()) {
1314 current->ReplaceWith(callee_graph->GetNullConstant());
1315 } else if (argument->IsIntConstant()) {
1316 current->ReplaceWith(callee_graph->GetIntConstant(argument->AsIntConstant()->GetValue()));
1317 } else if (argument->IsLongConstant()) {
1318 current->ReplaceWith(callee_graph->GetLongConstant(argument->AsLongConstant()->GetValue()));
1319 } else if (argument->IsFloatConstant()) {
1320 current->ReplaceWith(
1321 callee_graph->GetFloatConstant(argument->AsFloatConstant()->GetValue()));
1322 } else if (argument->IsDoubleConstant()) {
1323 current->ReplaceWith(
1324 callee_graph->GetDoubleConstant(argument->AsDoubleConstant()->GetValue()));
1325 } else if (argument->GetType() == Primitive::kPrimNot) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001326 if (!resolved_method->IsStatic() && parameter_index == 0 && receiver_type.IsValid()) {
1327 run_rtp = true;
1328 current->SetReferenceTypeInfo(receiver_type);
1329 } else {
1330 current->SetReferenceTypeInfo(argument->GetReferenceTypeInfo());
1331 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001332 current->AsParameterValue()->SetCanBeNull(argument->CanBeNull());
1333 }
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001334 ++parameter_index;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001335 }
1336 }
1337
David Brazdil94ab38f2016-06-21 17:48:19 +01001338 // We have replaced formal arguments with actual arguments. If actual types
1339 // are more specific than the declared ones, run RTP again on the inner graph.
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001340 if (run_rtp || ArgumentTypesMoreSpecific(invoke_instruction, resolved_method)) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001341 ReferenceTypePropagation(callee_graph,
1342 dex_compilation_unit.GetDexCache(),
1343 handles_,
1344 /* is_first_run */ false).Run();
1345 }
1346
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001347 size_t number_of_instructions_budget = kMaximumNumberOfHInstructions;
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001348 size_t number_of_inlined_instructions =
1349 RunOptimizations(callee_graph, code_item, dex_compilation_unit);
1350 number_of_instructions_budget += number_of_inlined_instructions;
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +00001351
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001352 // TODO: We should abort only if all predecessors throw. However,
1353 // HGraph::InlineInto currently does not handle an exit block with
1354 // a throw predecessor.
1355 HBasicBlock* exit_block = callee_graph->GetExitBlock();
1356 if (exit_block == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07001357 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001358 << " could not be inlined because it has an infinite loop";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001359 return false;
1360 }
1361
1362 bool has_throw_predecessor = false;
Vladimir Marko60584552015-09-03 13:35:12 +00001363 for (HBasicBlock* predecessor : exit_block->GetPredecessors()) {
1364 if (predecessor->GetLastInstruction()->IsThrow()) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001365 has_throw_predecessor = true;
1366 break;
1367 }
1368 }
1369 if (has_throw_predecessor) {
David Sehr709b0702016-10-13 09:12:37 -07001370 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001371 << " could not be inlined because one branch always throws";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001372 return false;
1373 }
1374
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001375 size_t number_of_instructions = 0;
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001376
1377 bool can_inline_environment =
1378 total_number_of_dex_registers_ < kMaximumNumberOfCumulatedDexRegisters;
1379
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001380 // Skip the entry block, it does not contain instructions that prevent inlining.
1381 for (HBasicBlock* block : callee_graph->GetReversePostOrderSkipEntryBlock()) {
David Sehrc757dec2016-11-04 15:48:34 -07001382 if (block->IsLoopHeader()) {
1383 if (block->GetLoopInformation()->IsIrreducible()) {
1384 // Don't inline methods with irreducible loops, they could prevent some
1385 // optimizations to run.
1386 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1387 << " could not be inlined because it contains an irreducible loop";
1388 return false;
1389 }
1390 if (!block->GetLoopInformation()->HasExitEdge()) {
1391 // Don't inline methods with loops without exit, since they cause the
1392 // loop information to be computed incorrectly when updating after
1393 // inlining.
1394 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1395 << " could not be inlined because it contains a loop with no exit";
1396 return false;
1397 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001398 }
1399
1400 for (HInstructionIterator instr_it(block->GetInstructions());
1401 !instr_it.Done();
1402 instr_it.Advance()) {
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001403 if (number_of_instructions++ == number_of_instructions_budget) {
David Sehr709b0702016-10-13 09:12:37 -07001404 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001405 << " is not inlined because its caller has reached"
1406 << " its instruction budget limit.";
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001407 return false;
1408 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001409 HInstruction* current = instr_it.Current();
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001410 if (!can_inline_environment && current->NeedsEnvironment()) {
David Sehr709b0702016-10-13 09:12:37 -07001411 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001412 << " is not inlined because its caller has reached"
1413 << " its environment budget limit.";
1414 return false;
1415 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001416
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001417 if (!same_dex_file && current->NeedsEnvironment()) {
David Sehr709b0702016-10-13 09:12:37 -07001418 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001419 << " could not be inlined because " << current->DebugName()
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001420 << " needs an environment and is in a different dex file";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001421 return false;
1422 }
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001423
Vladimir Markodc151b22015-10-15 18:02:30 +01001424 if (!same_dex_file && current->NeedsDexCacheOfDeclaringClass()) {
David Sehr709b0702016-10-13 09:12:37 -07001425 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001426 << " could not be inlined because " << current->DebugName()
1427 << " it is in a different dex file and requires access to the dex cache";
1428 return false;
1429 }
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001430
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001431 if (current->IsNewArray() &&
1432 (current->AsNewArray()->GetEntrypoint() == kQuickAllocArrayWithAccessCheck)) {
David Sehr709b0702016-10-13 09:12:37 -07001433 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001434 << " could not be inlined because it is using an entrypoint"
1435 << " with access checks";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001436 // Allocation entrypoint does not handle inlined frames.
1437 return false;
1438 }
1439
1440 if (current->IsUnresolvedStaticFieldGet() ||
1441 current->IsUnresolvedInstanceFieldGet() ||
1442 current->IsUnresolvedStaticFieldSet() ||
1443 current->IsUnresolvedInstanceFieldSet()) {
1444 // Entrypoint for unresolved fields does not handle inlined frames.
David Sehr709b0702016-10-13 09:12:37 -07001445 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001446 << " could not be inlined because it is using an unresolved"
1447 << " entrypoint";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001448 return false;
1449 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001450 }
1451 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001452 number_of_inlined_instructions_ += number_of_instructions;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001453
David Brazdil3f523062016-02-29 16:53:33 +00001454 DCHECK_EQ(caller_instruction_counter, graph_->GetCurrentInstructionId())
1455 << "No instructions can be added to the outer graph while inner graph is being built";
1456
1457 const int32_t callee_instruction_counter = callee_graph->GetCurrentInstructionId();
1458 graph_->SetCurrentInstructionId(callee_instruction_counter);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001459 *return_replacement = callee_graph->InlineInto(graph_, invoke_instruction);
David Brazdil3f523062016-02-29 16:53:33 +00001460
1461 DCHECK_EQ(callee_instruction_counter, callee_graph->GetCurrentInstructionId())
1462 << "No instructions can be added to the inner graph during inlining into the outer graph";
1463
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001464 return true;
1465}
Calin Juravle2e768302015-07-28 14:41:11 +00001466
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001467size_t HInliner::RunOptimizations(HGraph* callee_graph,
1468 const DexFile::CodeItem* code_item,
1469 const DexCompilationUnit& dex_compilation_unit) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001470 // Note: if the outermost_graph_ is being compiled OSR, we should not run any
1471 // optimization that could lead to a HDeoptimize. The following optimizations do not.
Andreas Gampeca620d72016-11-08 08:09:33 -08001472 HDeadCodeElimination dce(callee_graph, stats_, "dead_code_elimination$inliner");
1473 HConstantFolding fold(callee_graph, "constant_folding$inliner");
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001474 HSharpening sharpening(callee_graph, codegen_, dex_compilation_unit, compiler_driver_, handles_);
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001475 InstructionSimplifier simplify(callee_graph, stats_);
Nicolas Geoffray762869d2016-07-15 15:28:35 +01001476 IntrinsicsRecognizer intrinsics(callee_graph, stats_);
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001477
1478 HOptimization* optimizations[] = {
1479 &intrinsics,
1480 &sharpening,
1481 &simplify,
1482 &fold,
1483 &dce,
1484 };
1485
1486 for (size_t i = 0; i < arraysize(optimizations); ++i) {
1487 HOptimization* optimization = optimizations[i];
1488 optimization->Run();
1489 }
1490
1491 size_t number_of_inlined_instructions = 0u;
1492 if (depth_ + 1 < compiler_driver_->GetCompilerOptions().GetInlineDepthLimit()) {
1493 HInliner inliner(callee_graph,
1494 outermost_graph_,
1495 codegen_,
1496 outer_compilation_unit_,
1497 dex_compilation_unit,
1498 compiler_driver_,
1499 handles_,
1500 stats_,
1501 total_number_of_dex_registers_ + code_item->registers_size_,
1502 depth_ + 1);
1503 inliner.Run();
1504 number_of_inlined_instructions += inliner.number_of_inlined_instructions_;
1505 }
1506
1507 return number_of_inlined_instructions;
1508}
1509
David Brazdil94ab38f2016-06-21 17:48:19 +01001510static bool IsReferenceTypeRefinement(ReferenceTypeInfo declared_rti,
1511 bool declared_can_be_null,
1512 HInstruction* actual_obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001513 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001514 if (declared_can_be_null && !actual_obj->CanBeNull()) {
1515 return true;
1516 }
1517
1518 ReferenceTypeInfo actual_rti = actual_obj->GetReferenceTypeInfo();
1519 return (actual_rti.IsExact() && !declared_rti.IsExact()) ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001520 declared_rti.IsStrictSupertypeOf(actual_rti);
David Brazdil94ab38f2016-06-21 17:48:19 +01001521}
1522
1523ReferenceTypeInfo HInliner::GetClassRTI(mirror::Class* klass) {
1524 return ReferenceTypePropagation::IsAdmissible(klass)
1525 ? ReferenceTypeInfo::Create(handles_->NewHandle(klass))
1526 : graph_->GetInexactObjectRti();
1527}
1528
1529bool HInliner::ArgumentTypesMoreSpecific(HInvoke* invoke_instruction, ArtMethod* resolved_method) {
1530 // If this is an instance call, test whether the type of the `this` argument
1531 // is more specific than the class which declares the method.
1532 if (!resolved_method->IsStatic()) {
1533 if (IsReferenceTypeRefinement(GetClassRTI(resolved_method->GetDeclaringClass()),
1534 /* declared_can_be_null */ false,
1535 invoke_instruction->InputAt(0u))) {
1536 return true;
1537 }
1538 }
1539
Andreas Gampe542451c2016-07-26 09:02:02 -07001540 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
David Brazdil94ab38f2016-06-21 17:48:19 +01001541
1542 // Iterate over the list of parameter types and test whether any of the
1543 // actual inputs has a more specific reference type than the type declared in
1544 // the signature.
1545 const DexFile::TypeList* param_list = resolved_method->GetParameterTypeList();
1546 for (size_t param_idx = 0,
1547 input_idx = resolved_method->IsStatic() ? 0 : 1,
1548 e = (param_list == nullptr ? 0 : param_list->Size());
1549 param_idx < e;
1550 ++param_idx, ++input_idx) {
1551 HInstruction* input = invoke_instruction->InputAt(input_idx);
1552 if (input->GetType() == Primitive::kPrimNot) {
1553 mirror::Class* param_cls = resolved_method->GetDexCacheResolvedType(
1554 param_list->GetTypeItem(param_idx).type_idx_,
1555 pointer_size);
1556 if (IsReferenceTypeRefinement(GetClassRTI(param_cls),
1557 /* declared_can_be_null */ true,
1558 input)) {
1559 return true;
1560 }
1561 }
1562 }
1563
1564 return false;
1565}
1566
1567bool HInliner::ReturnTypeMoreSpecific(HInvoke* invoke_instruction,
1568 HInstruction* return_replacement) {
Alex Light68289a52015-12-15 17:30:30 -08001569 // Check the integrity of reference types and run another type propagation if needed.
David Brazdil4833f5a2015-12-16 10:37:39 +00001570 if (return_replacement != nullptr) {
1571 if (return_replacement->GetType() == Primitive::kPrimNot) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001572 // Test if the return type is a refinement of the declared return type.
1573 if (IsReferenceTypeRefinement(invoke_instruction->GetReferenceTypeInfo(),
1574 /* declared_can_be_null */ true,
1575 return_replacement)) {
1576 return true;
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001577 } else if (return_replacement->IsInstanceFieldGet()) {
1578 HInstanceFieldGet* field_get = return_replacement->AsInstanceFieldGet();
1579 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1580 if (field_get->GetFieldInfo().GetField() ==
1581 class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0)) {
1582 return true;
1583 }
David Brazdil94ab38f2016-06-21 17:48:19 +01001584 }
1585 } else if (return_replacement->IsInstanceOf()) {
1586 // Inlining InstanceOf into an If may put a tighter bound on reference types.
1587 return true;
1588 }
1589 }
1590
1591 return false;
1592}
1593
1594void HInliner::FixUpReturnReferenceType(ArtMethod* resolved_method,
1595 HInstruction* return_replacement) {
1596 if (return_replacement != nullptr) {
1597 if (return_replacement->GetType() == Primitive::kPrimNot) {
David Brazdil4833f5a2015-12-16 10:37:39 +00001598 if (!return_replacement->GetReferenceTypeInfo().IsValid()) {
1599 // Make sure that we have a valid type for the return. We may get an invalid one when
1600 // we inline invokes with multiple branches and create a Phi for the result.
1601 // TODO: we could be more precise by merging the phi inputs but that requires
1602 // some functionality from the reference type propagation.
1603 DCHECK(return_replacement->IsPhi());
Andreas Gampe542451c2016-07-26 09:02:02 -07001604 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray44fd0e52016-03-16 15:16:06 +00001605 mirror::Class* cls = resolved_method->GetReturnType(false /* resolve */, pointer_size);
David Brazdil94ab38f2016-06-21 17:48:19 +01001606 return_replacement->SetReferenceTypeInfo(GetClassRTI(cls));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001607 }
Calin Juravlecdfed3d2015-10-26 14:05:01 +00001608 }
Calin Juravle2e768302015-07-28 14:41:11 +00001609 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001610}
1611
1612} // namespace art