blob: e012a4287fece0d45749d86f5828b48aa1258f27 [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 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +000072 // Keep a copy of all blocks when starting the visit.
73 ArenaVector<HBasicBlock*> blocks = graph_->GetReversePostOrder();
Vladimir Markofa6b93c2015-09-15 10:15:55 +010074 DCHECK(!blocks.empty());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +000075 // Because we are changing the graph when inlining,
76 // we just iterate over the blocks of the outer method.
77 // This avoids doing the inlining work again on the inlined blocks.
78 for (HBasicBlock* block : blocks) {
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +000079 for (HInstruction* instruction = block->GetFirstInstruction(); instruction != nullptr;) {
80 HInstruction* next = instruction->GetNext();
Nicolas Geoffray454a4812015-06-09 10:37:32 +010081 HInvoke* call = instruction->AsInvoke();
Razvan A Lupusoru3e90a962015-03-27 13:44:44 -070082 // As long as the call is not intrinsified, it is worth trying to inline.
83 if (call != nullptr && call->GetIntrinsic() == Intrinsics::kNone) {
Nicolas Geoffrayb703d182017-02-14 18:05:28 +000084 if (kIsDebugBuild && IsCompilingWithCoreImage()) {
85 // Debugging case: directives in method names control or assert on inlining.
86 std::string callee_name = outer_compilation_unit_.GetDexFile()->PrettyMethod(
87 call->GetDexMethodIndex(), /* with_signature */ false);
88 // Tests prevent inlining by having $noinline$ in their method names.
89 if (callee_name.find("$noinline$") == std::string::npos) {
90 if (!TryInline(call)) {
91 bool should_have_inlined = (callee_name.find("$inline$") != std::string::npos);
92 CHECK(!should_have_inlined) << "Could not inline " << callee_name;
93 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000094 }
Guillaume "Vermeille" Sancheze918d382015-06-03 15:32:41 +010095 } else {
Nicolas Geoffrayb703d182017-02-14 18:05:28 +000096 // Normal case: try to inline.
97 TryInline(call);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000098 }
99 }
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000100 instruction = next;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000101 }
102 }
103}
104
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100105static bool IsMethodOrDeclaringClassFinal(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700106 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100107 return method->IsFinal() || method->GetDeclaringClass()->IsFinal();
108}
109
110/**
111 * Given the `resolved_method` looked up in the dex cache, try to find
112 * the actual runtime target of an interface or virtual call.
113 * Return nullptr if the runtime target cannot be proven.
114 */
115static ArtMethod* FindVirtualOrInterfaceTarget(HInvoke* invoke, ArtMethod* resolved_method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700116 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100117 if (IsMethodOrDeclaringClassFinal(resolved_method)) {
118 // No need to lookup further, the resolved method will be the target.
119 return resolved_method;
120 }
121
122 HInstruction* receiver = invoke->InputAt(0);
123 if (receiver->IsNullCheck()) {
124 // Due to multiple levels of inlining within the same pass, it might be that
125 // null check does not have the reference type of the actual receiver.
126 receiver = receiver->InputAt(0);
127 }
128 ReferenceTypeInfo info = receiver->GetReferenceTypeInfo();
Calin Juravle2e768302015-07-28 14:41:11 +0000129 DCHECK(info.IsValid()) << "Invalid RTI for " << receiver->DebugName();
130 if (!info.IsExact()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100131 // We currently only support inlining with known receivers.
132 // TODO: Remove this check, we should be able to inline final methods
133 // on unknown receivers.
134 return nullptr;
135 } else if (info.GetTypeHandle()->IsInterface()) {
136 // Statically knowing that the receiver has an interface type cannot
137 // help us find what is the target method.
138 return nullptr;
139 } else if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(info.GetTypeHandle().Get())) {
140 // The method that we're trying to call is not in the receiver's class or super classes.
141 return nullptr;
Nicolas Geoffrayab5327d2016-03-18 11:36:20 +0000142 } else if (info.GetTypeHandle()->IsErroneous()) {
143 // If the type is erroneous, do not go further, as we are going to query the vtable or
144 // imt table, that we can only safely do on non-erroneous classes.
145 return nullptr;
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100146 }
147
148 ClassLinker* cl = Runtime::Current()->GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700149 PointerSize pointer_size = cl->GetImagePointerSize();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100150 if (invoke->IsInvokeInterface()) {
151 resolved_method = info.GetTypeHandle()->FindVirtualMethodForInterface(
152 resolved_method, pointer_size);
153 } else {
154 DCHECK(invoke->IsInvokeVirtual());
155 resolved_method = info.GetTypeHandle()->FindVirtualMethodForVirtual(
156 resolved_method, pointer_size);
157 }
158
159 if (resolved_method == nullptr) {
160 // The information we had on the receiver was not enough to find
161 // the target method. Since we check above the exact type of the receiver,
162 // the only reason this can happen is an IncompatibleClassChangeError.
163 return nullptr;
Alex Light9139e002015-10-09 15:59:48 -0700164 } else if (!resolved_method->IsInvokable()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100165 // The information we had on the receiver was not enough to find
166 // the target method. Since we check above the exact type of the receiver,
167 // the only reason this can happen is an IncompatibleClassChangeError.
168 return nullptr;
169 } else if (IsMethodOrDeclaringClassFinal(resolved_method)) {
170 // A final method has to be the target method.
171 return resolved_method;
172 } else if (info.IsExact()) {
173 // If we found a method and the receiver's concrete type is statically
174 // known, we know for sure the target.
175 return resolved_method;
176 } else {
177 // Even if we did find a method, the receiver type was not enough to
178 // statically find the runtime target.
179 return nullptr;
180 }
181}
182
183static uint32_t FindMethodIndexIn(ArtMethod* method,
184 const DexFile& dex_file,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000185 uint32_t name_and_signature_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700186 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100187 if (IsSameDexFile(*method->GetDexFile(), dex_file)) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100188 return method->GetDexMethodIndex();
189 } else {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000190 return method->FindDexMethodIndexInOtherDexFile(dex_file, name_and_signature_index);
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100191 }
192}
193
Andreas Gampea5b09a62016-11-17 15:21:22 -0800194static dex::TypeIndex FindClassIndexIn(mirror::Class* cls,
Mathieu Chartier5812e202017-02-13 18:32:04 -0800195 const DexFile& dex_file,
196 Handle<mirror::DexCache> dex_cache)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700197 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampea5b09a62016-11-17 15:21:22 -0800198 dex::TypeIndex index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100199 if (cls->GetDexCache() == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700200 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000201 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800202 } else if (!cls->GetDexTypeIndex().IsValid()) {
David Sehr709b0702016-10-13 09:12:37 -0700203 DCHECK(cls->IsProxyClass()) << cls->PrettyClass();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100204 // TODO: deal with proxy classes.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100205 } else if (IsSameDexFile(cls->GetDexFile(), dex_file)) {
Mathieu Chartier5812e202017-02-13 18:32:04 -0800206 DCHECK_EQ(cls->GetDexCache(), dex_cache.Get());
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000207 index = cls->GetDexTypeIndex();
Mathieu Chartier5812e202017-02-13 18:32:04 -0800208 // Update the dex cache to ensure the class is in. The generated code will
209 // consider it is. We make it safe by updating the dex cache, as other
210 // dex files might also load the class, and there is no guarantee the dex
211 // cache of the dex file of the class will be updated.
212 if (dex_cache->GetResolvedType(index) == nullptr) {
213 dex_cache->SetResolvedType(index, cls);
214 }
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100215 } else {
216 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Mathieu Chartier5812e202017-02-13 18:32:04 -0800217 // We cannot guarantee the entry in the dex cache will resolve to the same class,
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100218 // as there may be different class loaders. So only return the index if it's
Mathieu Chartier5812e202017-02-13 18:32:04 -0800219 // the right class in the dex cache already.
220 if (index.IsValid() && dex_cache->GetResolvedType(index) != cls) {
221 index = dex::TypeIndex::Invalid();
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100222 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100223 }
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000224
225 return index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100226}
227
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000228class ScopedProfilingInfoInlineUse {
229 public:
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000230 explicit ScopedProfilingInfoInlineUse(ArtMethod* method, Thread* self)
231 : method_(method),
232 self_(self),
233 // Fetch the profiling info ahead of using it. If it's null when fetching,
234 // we should not call JitCodeCache::DoneInlining.
235 profiling_info_(
236 Runtime::Current()->GetJit()->GetCodeCache()->NotifyCompilerUse(method, self)) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000237 }
238
239 ~ScopedProfilingInfoInlineUse() {
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000240 if (profiling_info_ != nullptr) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700241 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000242 DCHECK_EQ(profiling_info_, method_->GetProfilingInfo(pointer_size));
243 Runtime::Current()->GetJit()->GetCodeCache()->DoneCompilerUse(method_, self_);
244 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000245 }
246
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000247 ProfilingInfo* GetProfilingInfo() const { return profiling_info_; }
248
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000249 private:
250 ArtMethod* const method_;
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000251 Thread* const self_;
252 ProfilingInfo* const profiling_info_;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000253};
254
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000255static bool IsMonomorphic(Handle<mirror::ObjectArray<mirror::Class>> classes)
256 REQUIRES_SHARED(Locks::mutator_lock_) {
257 DCHECK_GE(InlineCache::kIndividualCacheSize, 2);
258 return classes->Get(0) != nullptr && classes->Get(1) == nullptr;
259}
260
261static bool IsMegamorphic(Handle<mirror::ObjectArray<mirror::Class>> classes)
262 REQUIRES_SHARED(Locks::mutator_lock_) {
263 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
264 if (classes->Get(i) == nullptr) {
265 return false;
266 }
267 }
268 return true;
269}
270
271static mirror::Class* GetMonomorphicType(Handle<mirror::ObjectArray<mirror::Class>> classes)
272 REQUIRES_SHARED(Locks::mutator_lock_) {
273 DCHECK(classes->Get(0) != nullptr);
274 return classes->Get(0);
275}
276
277static bool IsUninitialized(Handle<mirror::ObjectArray<mirror::Class>> classes)
278 REQUIRES_SHARED(Locks::mutator_lock_) {
279 return classes->Get(0) == nullptr;
280}
281
282static bool IsPolymorphic(Handle<mirror::ObjectArray<mirror::Class>> classes)
283 REQUIRES_SHARED(Locks::mutator_lock_) {
284 DCHECK_GE(InlineCache::kIndividualCacheSize, 3);
285 return classes->Get(1) != nullptr &&
286 classes->Get(InlineCache::kIndividualCacheSize - 1) == nullptr;
287}
288
Mingyao Yang063fc772016-08-02 11:02:54 -0700289ArtMethod* HInliner::TryCHADevirtualization(ArtMethod* resolved_method) {
290 if (!resolved_method->HasSingleImplementation()) {
291 return nullptr;
292 }
293 if (Runtime::Current()->IsAotCompiler()) {
294 // No CHA-based devirtulization for AOT compiler (yet).
295 return nullptr;
296 }
297 if (outermost_graph_->IsCompilingOsr()) {
298 // We do not support HDeoptimize in OSR methods.
299 return nullptr;
300 }
Mingyao Yange8fcd012017-01-20 10:43:30 -0800301 PointerSize pointer_size = caller_compilation_unit_.GetClassLinker()->GetImagePointerSize();
302 return resolved_method->GetSingleImplementation(pointer_size);
Mingyao Yang063fc772016-08-02 11:02:54 -0700303}
304
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700305bool HInliner::TryInline(HInvoke* invoke_instruction) {
Orion Hodsonac141392017-01-13 11:53:47 +0000306 if (invoke_instruction->IsInvokeUnresolved() ||
307 invoke_instruction->IsInvokePolymorphic()) {
308 return false; // Don't bother to move further if we know the method is unresolved or an
309 // invoke-polymorphic.
Calin Juravle175dc732015-08-25 15:42:32 +0100310 }
311
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000312 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100313 uint32_t method_index = invoke_instruction->GetDexMethodIndex();
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000314 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -0700315 VLOG(compiler) << "Try inlining " << caller_dex_file.PrettyMethod(method_index);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000316
Nicolas Geoffray35071052015-06-09 15:43:38 +0100317 // We can query the dex cache directly. The verifier has populated it already.
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100318 ArtMethod* resolved_method = invoke_instruction->GetResolvedMethod();
Andreas Gampefd2140f2015-12-23 16:30:44 -0800319 ArtMethod* actual_method = nullptr;
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100320 if (resolved_method == nullptr) {
321 DCHECK(invoke_instruction->IsInvokeStaticOrDirect());
322 DCHECK(invoke_instruction->AsInvokeStaticOrDirect()->IsStringInit());
323 VLOG(compiler) << "Not inlining a String.<init> method";
324 return false;
325 } else if (invoke_instruction->IsInvokeStaticOrDirect()) {
Andreas Gampefd2140f2015-12-23 16:30:44 -0800326 actual_method = resolved_method;
Vladimir Marko58155012015-08-19 12:49:41 +0000327 } else {
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100328 // Check if we can statically find the method.
329 actual_method = FindVirtualOrInterfaceTarget(invoke_instruction, resolved_method);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000330 }
331
Mingyao Yang063fc772016-08-02 11:02:54 -0700332 bool cha_devirtualize = false;
333 if (actual_method == nullptr) {
334 ArtMethod* method = TryCHADevirtualization(resolved_method);
335 if (method != nullptr) {
336 cha_devirtualize = true;
337 actual_method = method;
338 }
339 }
340
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100341 if (actual_method != nullptr) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700342 bool result = TryInlineAndReplace(invoke_instruction,
343 actual_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000344 ReferenceTypeInfo::CreateInvalid(),
Mingyao Yang063fc772016-08-02 11:02:54 -0700345 /* do_rtp */ true,
346 cha_devirtualize);
Calin Juravle69158982016-03-16 11:53:41 +0000347 if (result && !invoke_instruction->IsInvokeStaticOrDirect()) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700348 if (cha_devirtualize) {
349 // Add dependency due to devirtulization. We've assumed resolved_method
350 // has single implementation.
351 outermost_graph_->AddCHASingleImplementationDependency(resolved_method);
352 MaybeRecordStat(kCHAInline);
353 } else {
354 MaybeRecordStat(kInlinedInvokeVirtualOrInterface);
355 }
Calin Juravle69158982016-03-16 11:53:41 +0000356 }
357 return result;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100358 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000359
Andreas Gampefd2140f2015-12-23 16:30:44 -0800360 DCHECK(!invoke_instruction->IsInvokeStaticOrDirect());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100361
362 // Check if we can use an inline cache.
363 ArtMethod* caller = graph_->GetArtMethod();
Calin Juravleffc87072016-04-20 14:22:09 +0100364 if (Runtime::Current()->UseJitCompilation()) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000365 // Under JIT, we should always know the caller.
366 DCHECK(caller != nullptr);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000367 ScopedProfilingInfoInlineUse spiis(caller, soa.Self());
368 ProfilingInfo* profiling_info = spiis.GetProfilingInfo();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000369 if (profiling_info != nullptr) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000370 StackHandleScope<1> hs(soa.Self());
371 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
372 Handle<mirror::ObjectArray<mirror::Class>> inline_cache = hs.NewHandle(
373 mirror::ObjectArray<mirror::Class>::Alloc(
374 soa.Self(),
375 class_linker->GetClassRoot(ClassLinker::kClassArrayClass),
376 InlineCache::kIndividualCacheSize));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800377 if (inline_cache == nullptr) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000378 // We got an OOME. Just clear the exception, and don't inline.
379 DCHECK(soa.Self()->IsExceptionPending());
380 soa.Self()->ClearException();
381 VLOG(compiler) << "Out of memory in the compiler when trying to inline";
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000382 return false;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000383 } else {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000384 Runtime::Current()->GetJit()->GetCodeCache()->CopyInlineCacheInto(
385 *profiling_info->GetInlineCache(invoke_instruction->GetDexPc()),
386 inline_cache);
387 if (IsUninitialized(inline_cache)) {
388 VLOG(compiler) << "Interface or virtual call to "
389 << caller_dex_file.PrettyMethod(method_index)
390 << " is not hit and not inlined";
391 return false;
392 } else if (IsMonomorphic(inline_cache)) {
393 MaybeRecordStat(kMonomorphicCall);
394 if (outermost_graph_->IsCompilingOsr()) {
395 // If we are compiling OSR, we pretend this call is polymorphic, as we may come from the
396 // interpreter and it may have seen different receiver types.
397 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
398 } else {
399 return TryInlineMonomorphicCall(invoke_instruction, resolved_method, inline_cache);
400 }
401 } else if (IsPolymorphic(inline_cache)) {
402 MaybeRecordStat(kPolymorphicCall);
403 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
404 } else {
405 DCHECK(IsMegamorphic(inline_cache));
406 VLOG(compiler) << "Interface or virtual call to "
407 << caller_dex_file.PrettyMethod(method_index)
408 << " is megamorphic and not inlined";
409 MaybeRecordStat(kMegamorphicCall);
410 return false;
411 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000412 }
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100413 }
414 }
415
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100416 VLOG(compiler) << "Interface or virtual call to "
David Sehr709b0702016-10-13 09:12:37 -0700417 << caller_dex_file.PrettyMethod(method_index)
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100418 << " could not be statically determined";
419 return false;
420}
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000421
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000422HInstanceFieldGet* HInliner::BuildGetReceiverClass(ClassLinker* class_linker,
423 HInstruction* receiver,
424 uint32_t dex_pc) const {
425 ArtField* field = class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0);
426 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000427 HInstanceFieldGet* result = new (graph_->GetArena()) HInstanceFieldGet(
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000428 receiver,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000429 field,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000430 Primitive::kPrimNot,
431 field->GetOffset(),
432 field->IsVolatile(),
433 field->GetDexFieldIndex(),
434 field->GetDeclaringClass()->GetDexClassDefIndex(),
435 *field->GetDexFile(),
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000436 dex_pc);
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000437 // The class of a field is effectively final, and does not have any memory dependencies.
438 result->SetSideEffects(SideEffects::None());
439 return result;
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000440}
441
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100442bool HInliner::TryInlineMonomorphicCall(HInvoke* invoke_instruction,
443 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000444 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000445 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
446 << invoke_instruction->DebugName();
447
Mathieu Chartier5812e202017-02-13 18:32:04 -0800448 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Andreas Gampea5b09a62016-11-17 15:21:22 -0800449 dex::TypeIndex class_index = FindClassIndexIn(
Mathieu Chartier5812e202017-02-13 18:32:04 -0800450 GetMonomorphicType(classes), caller_dex_file, caller_compilation_unit_.GetDexCache());
Andreas Gampea5b09a62016-11-17 15:21:22 -0800451 if (!class_index.IsValid()) {
David Sehr709b0702016-10-13 09:12:37 -0700452 VLOG(compiler) << "Call to " << ArtMethod::PrettyMethod(resolved_method)
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100453 << " from inline cache is not inlined because its class is not"
454 << " accessible to the caller";
455 return false;
456 }
457
458 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700459 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100460 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000461 resolved_method = GetMonomorphicType(classes)->FindVirtualMethodForInterface(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100462 resolved_method, pointer_size);
463 } else {
464 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000465 resolved_method = GetMonomorphicType(classes)->FindVirtualMethodForVirtual(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100466 resolved_method, pointer_size);
467 }
468 DCHECK(resolved_method != nullptr);
469 HInstruction* receiver = invoke_instruction->InputAt(0);
470 HInstruction* cursor = invoke_instruction->GetPrevious();
471 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000472 Handle<mirror::Class> monomorphic_type = handles_->NewHandle(GetMonomorphicType(classes));
Mingyao Yang063fc772016-08-02 11:02:54 -0700473 if (!TryInlineAndReplace(invoke_instruction,
474 resolved_method,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000475 ReferenceTypeInfo::Create(monomorphic_type, /* is_exact */ true),
Mingyao Yang063fc772016-08-02 11:02:54 -0700476 /* do_rtp */ false,
477 /* cha_devirtualize */ false)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100478 return false;
479 }
480
481 // We successfully inlined, now add a guard.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000482 AddTypeGuard(receiver,
483 cursor,
484 bb_cursor,
485 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000486 monomorphic_type,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000487 invoke_instruction,
488 /* with_deoptimization */ true);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100489
490 // Run type propagation to get the guard typed, and eventually propagate the
491 // type of the receiver.
Vladimir Marko456307a2016-04-19 14:12:13 +0000492 ReferenceTypePropagation rtp_fixup(graph_,
493 outer_compilation_unit_.GetDexCache(),
494 handles_,
495 /* is_first_run */ false);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100496 rtp_fixup.Run();
497
498 MaybeRecordStat(kInlinedMonomorphicCall);
499 return true;
500}
501
Mingyao Yang063fc772016-08-02 11:02:54 -0700502void HInliner::AddCHAGuard(HInstruction* invoke_instruction,
503 uint32_t dex_pc,
504 HInstruction* cursor,
505 HBasicBlock* bb_cursor) {
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800506 HShouldDeoptimizeFlag* deopt_flag = new (graph_->GetArena())
507 HShouldDeoptimizeFlag(graph_->GetArena(), dex_pc);
508 HInstruction* compare = new (graph_->GetArena()) HNotEqual(
Mingyao Yang063fc772016-08-02 11:02:54 -0700509 deopt_flag, graph_->GetIntConstant(0, dex_pc));
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800510 HInstruction* deopt = new (graph_->GetArena()) HDeoptimize(compare, dex_pc);
Mingyao Yang063fc772016-08-02 11:02:54 -0700511
512 if (cursor != nullptr) {
513 bb_cursor->InsertInstructionAfter(deopt_flag, cursor);
514 } else {
515 bb_cursor->InsertInstructionBefore(deopt_flag, bb_cursor->GetFirstInstruction());
516 }
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800517 bb_cursor->InsertInstructionAfter(compare, deopt_flag);
518 bb_cursor->InsertInstructionAfter(deopt, compare);
519
520 // Add receiver as input to aid CHA guard optimization later.
521 deopt_flag->AddInput(invoke_instruction->InputAt(0));
522 DCHECK_EQ(deopt_flag->InputCount(), 1u);
Mingyao Yang063fc772016-08-02 11:02:54 -0700523 deopt->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800524 outermost_graph_->IncrementNumberOfCHAGuards();
Mingyao Yang063fc772016-08-02 11:02:54 -0700525}
526
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000527HInstruction* HInliner::AddTypeGuard(HInstruction* receiver,
528 HInstruction* cursor,
529 HBasicBlock* bb_cursor,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800530 dex::TypeIndex class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000531 Handle<mirror::Class> klass,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000532 HInstruction* invoke_instruction,
533 bool with_deoptimization) {
534 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
535 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
536 class_linker, receiver, invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000537 if (cursor != nullptr) {
538 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
539 } else {
540 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
541 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000542
543 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000544 bool is_referrer = (klass.Get() == outermost_graph_->GetArtMethod()->GetDeclaringClass());
Nicolas Geoffray56876342016-12-16 16:09:08 +0000545 // Note that we will just compare the classes, so we don't need Java semantics access checks.
546 // Note that the type index and the dex file are relative to the method this type guard is
547 // inlined into.
548 HLoadClass* load_class = new (graph_->GetArena()) HLoadClass(graph_->GetCurrentMethod(),
549 class_index,
550 caller_dex_file,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000551 klass,
Nicolas Geoffray56876342016-12-16 16:09:08 +0000552 is_referrer,
553 invoke_instruction->GetDexPc(),
554 /* needs_access_check */ false);
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000555 HLoadClass::LoadKind kind = HSharpening::SharpenClass(
556 load_class, codegen_, compiler_driver_, caller_compilation_unit_);
557 DCHECK(kind != HLoadClass::LoadKind::kInvalid)
558 << "We should always be able to reference a class for inline caches";
559 // Insert before setting the kind, as setting the kind affects the inputs.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000560 bb_cursor->InsertInstructionAfter(load_class, receiver_class);
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000561 load_class->SetLoadKind(kind);
Nicolas Geoffray56876342016-12-16 16:09:08 +0000562
Nicolas Geoffray56876342016-12-16 16:09:08 +0000563 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(load_class, receiver_class);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000564 bb_cursor->InsertInstructionAfter(compare, load_class);
565 if (with_deoptimization) {
566 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
567 compare, invoke_instruction->GetDexPc());
568 bb_cursor->InsertInstructionAfter(deoptimize, compare);
569 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
570 }
571 return compare;
572}
573
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000574bool HInliner::TryInlinePolymorphicCall(HInvoke* invoke_instruction,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100575 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000576 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000577 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
578 << invoke_instruction->DebugName();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000579
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000580 if (TryInlinePolymorphicCallToSameTarget(invoke_instruction, resolved_method, classes)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000581 return true;
582 }
583
584 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700585 PointerSize pointer_size = class_linker->GetImagePointerSize();
Mathieu Chartier5812e202017-02-13 18:32:04 -0800586 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000587
588 bool all_targets_inlined = true;
589 bool one_target_inlined = false;
590 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000591 if (classes->Get(i) == nullptr) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000592 break;
593 }
594 ArtMethod* method = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000595
596 Handle<mirror::Class> handle = handles_->NewHandle(classes->Get(i));
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000597 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000598 method = handle->FindVirtualMethodForInterface(resolved_method, pointer_size);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000599 } else {
600 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000601 method = handle->FindVirtualMethodForVirtual(resolved_method, pointer_size);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000602 }
603
604 HInstruction* receiver = invoke_instruction->InputAt(0);
605 HInstruction* cursor = invoke_instruction->GetPrevious();
606 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
607
Mathieu Chartier5812e202017-02-13 18:32:04 -0800608 dex::TypeIndex class_index = FindClassIndexIn(
609 handle.Get(), caller_dex_file, caller_compilation_unit_.GetDexCache());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000610 HInstruction* return_replacement = nullptr;
Andreas Gampea5b09a62016-11-17 15:21:22 -0800611 if (!class_index.IsValid() ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000612 !TryBuildAndInline(invoke_instruction,
613 method,
614 ReferenceTypeInfo::Create(handle, /* is_exact */ true),
615 &return_replacement)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000616 all_targets_inlined = false;
617 } else {
618 one_target_inlined = true;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000619
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000620 VLOG(compiler) << "Polymorphic call to " << ArtMethod::PrettyMethod(resolved_method)
621 << " has inlined " << ArtMethod::PrettyMethod(method);
622
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000623 // If we have inlined all targets before, and this receiver is the last seen,
624 // we deoptimize instead of keeping the original invoke instruction.
625 bool deoptimize = all_targets_inlined &&
626 (i != InlineCache::kIndividualCacheSize - 1) &&
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000627 (classes->Get(i + 1) == nullptr);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100628
629 if (outermost_graph_->IsCompilingOsr()) {
630 // We do not support HDeoptimize in OSR methods.
631 deoptimize = false;
632 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000633 HInstruction* compare = AddTypeGuard(receiver,
634 cursor,
635 bb_cursor,
636 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000637 handle,
Nicolas Geoffray56876342016-12-16 16:09:08 +0000638 invoke_instruction,
639 deoptimize);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000640 if (deoptimize) {
641 if (return_replacement != nullptr) {
642 invoke_instruction->ReplaceWith(return_replacement);
643 }
644 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
645 // Because the inline cache data can be populated concurrently, we force the end of the
646 // iteration. Otherhwise, we could see a new receiver type.
647 break;
648 } else {
649 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
650 }
651 }
652 }
653
654 if (!one_target_inlined) {
David Sehr709b0702016-10-13 09:12:37 -0700655 VLOG(compiler) << "Call to " << ArtMethod::PrettyMethod(resolved_method)
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000656 << " from inline cache is not inlined because none"
657 << " of its targets could be inlined";
658 return false;
659 }
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000660
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000661 MaybeRecordStat(kInlinedPolymorphicCall);
662
663 // Run type propagation to get the guards typed.
Vladimir Marko456307a2016-04-19 14:12:13 +0000664 ReferenceTypePropagation rtp_fixup(graph_,
665 outer_compilation_unit_.GetDexCache(),
666 handles_,
667 /* is_first_run */ false);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000668 rtp_fixup.Run();
669 return true;
670}
671
672void HInliner::CreateDiamondPatternForPolymorphicInline(HInstruction* compare,
673 HInstruction* return_replacement,
674 HInstruction* invoke_instruction) {
675 uint32_t dex_pc = invoke_instruction->GetDexPc();
676 HBasicBlock* cursor_block = compare->GetBlock();
677 HBasicBlock* original_invoke_block = invoke_instruction->GetBlock();
678 ArenaAllocator* allocator = graph_->GetArena();
679
680 // Spit the block after the compare: `cursor_block` will now be the start of the diamond,
681 // and the returned block is the start of the then branch (that could contain multiple blocks).
682 HBasicBlock* then = cursor_block->SplitAfterForInlining(compare);
683
684 // Split the block containing the invoke before and after the invoke. The returned block
685 // of the split before will contain the invoke and will be the otherwise branch of
686 // the diamond. The returned block of the split after will be the merge block
687 // of the diamond.
688 HBasicBlock* end_then = invoke_instruction->GetBlock();
689 HBasicBlock* otherwise = end_then->SplitBeforeForInlining(invoke_instruction);
690 HBasicBlock* merge = otherwise->SplitAfterForInlining(invoke_instruction);
691
692 // If the methods we are inlining return a value, we create a phi in the merge block
693 // that will have the `invoke_instruction and the `return_replacement` as inputs.
694 if (return_replacement != nullptr) {
695 HPhi* phi = new (allocator) HPhi(
696 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke_instruction->GetType()), dex_pc);
697 merge->AddPhi(phi);
698 invoke_instruction->ReplaceWith(phi);
699 phi->AddInput(return_replacement);
700 phi->AddInput(invoke_instruction);
701 }
702
703 // Add the control flow instructions.
704 otherwise->AddInstruction(new (allocator) HGoto(dex_pc));
705 end_then->AddInstruction(new (allocator) HGoto(dex_pc));
706 cursor_block->AddInstruction(new (allocator) HIf(compare, dex_pc));
707
708 // Add the newly created blocks to the graph.
709 graph_->AddBlock(then);
710 graph_->AddBlock(otherwise);
711 graph_->AddBlock(merge);
712
713 // Set up successor (and implictly predecessor) relations.
714 cursor_block->AddSuccessor(otherwise);
715 cursor_block->AddSuccessor(then);
716 end_then->AddSuccessor(merge);
717 otherwise->AddSuccessor(merge);
718
719 // Set up dominance information.
720 then->SetDominator(cursor_block);
721 cursor_block->AddDominatedBlock(then);
722 otherwise->SetDominator(cursor_block);
723 cursor_block->AddDominatedBlock(otherwise);
724 merge->SetDominator(cursor_block);
725 cursor_block->AddDominatedBlock(merge);
726
727 // Update the revert post order.
728 size_t index = IndexOfElement(graph_->reverse_post_order_, cursor_block);
729 MakeRoomFor(&graph_->reverse_post_order_, 1, index);
730 graph_->reverse_post_order_[++index] = then;
731 index = IndexOfElement(graph_->reverse_post_order_, end_then);
732 MakeRoomFor(&graph_->reverse_post_order_, 2, index);
733 graph_->reverse_post_order_[++index] = otherwise;
734 graph_->reverse_post_order_[++index] = merge;
735
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000736
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +0000737 graph_->UpdateLoopAndTryInformationOfNewBlock(
738 then, original_invoke_block, /* replace_if_back_edge */ false);
739 graph_->UpdateLoopAndTryInformationOfNewBlock(
740 otherwise, original_invoke_block, /* replace_if_back_edge */ false);
741
742 // In case the original invoke location was a back edge, we need to update
743 // the loop to now have the merge block as a back edge.
744 graph_->UpdateLoopAndTryInformationOfNewBlock(
745 merge, original_invoke_block, /* replace_if_back_edge */ true);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000746}
747
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000748bool HInliner::TryInlinePolymorphicCallToSameTarget(
749 HInvoke* invoke_instruction,
750 ArtMethod* resolved_method,
751 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000752 // This optimization only works under JIT for now.
Calin Juravleffc87072016-04-20 14:22:09 +0100753 DCHECK(Runtime::Current()->UseJitCompilation());
Roland Levillain2aba7cd2016-02-03 12:27:20 +0000754 if (graph_->GetInstructionSet() == kMips64) {
755 // TODO: Support HClassTableGet for mips64.
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000756 return false;
757 }
758 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700759 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000760
761 DCHECK(resolved_method != nullptr);
762 ArtMethod* actual_method = nullptr;
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000763 size_t method_index = invoke_instruction->IsInvokeVirtual()
764 ? invoke_instruction->AsInvokeVirtual()->GetVTableIndex()
765 : invoke_instruction->AsInvokeInterface()->GetImtIndex();
766
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000767 // Check whether we are actually calling the same method among
768 // the different types seen.
769 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000770 if (classes->Get(i) == nullptr) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000771 break;
772 }
773 ArtMethod* new_method = nullptr;
774 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000775 new_method = classes->Get(i)->GetImt(pointer_size)->Get(
Matthew Gharrity465ecc82016-07-19 21:32:52 +0000776 method_index, pointer_size);
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000777 if (new_method->IsRuntimeMethod()) {
778 // Bail out as soon as we see a conflict trampoline in one of the target's
779 // interface table.
780 return false;
781 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000782 } else {
783 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000784 new_method = classes->Get(i)->GetEmbeddedVTableEntry(method_index, pointer_size);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000785 }
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000786 DCHECK(new_method != nullptr);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000787 if (actual_method == nullptr) {
788 actual_method = new_method;
789 } else if (actual_method != new_method) {
790 // Different methods, bailout.
David Sehr709b0702016-10-13 09:12:37 -0700791 VLOG(compiler) << "Call to " << ArtMethod::PrettyMethod(resolved_method)
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000792 << " from inline cache is not inlined because it resolves"
793 << " to different methods";
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000794 return false;
795 }
796 }
797
798 HInstruction* receiver = invoke_instruction->InputAt(0);
799 HInstruction* cursor = invoke_instruction->GetPrevious();
800 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
801
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100802 HInstruction* return_replacement = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000803 if (!TryBuildAndInline(invoke_instruction,
804 actual_method,
805 ReferenceTypeInfo::CreateInvalid(),
806 &return_replacement)) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000807 return false;
808 }
809
810 // We successfully inlined, now add a guard.
811 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
812 class_linker, receiver, invoke_instruction->GetDexPc());
813
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000814 Primitive::Type type = Is64BitInstructionSet(graph_->GetInstructionSet())
815 ? Primitive::kPrimLong
816 : Primitive::kPrimInt;
817 HClassTableGet* class_table_get = new (graph_->GetArena()) HClassTableGet(
818 receiver_class,
819 type,
Vladimir Markoa1de9182016-02-25 11:37:38 +0000820 invoke_instruction->IsInvokeVirtual() ? HClassTableGet::TableKind::kVTable
821 : HClassTableGet::TableKind::kIMTable,
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000822 method_index,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000823 invoke_instruction->GetDexPc());
824
825 HConstant* constant;
826 if (type == Primitive::kPrimLong) {
827 constant = graph_->GetLongConstant(
828 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
829 } else {
830 constant = graph_->GetIntConstant(
831 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
832 }
833
834 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(class_table_get, constant);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000835 if (cursor != nullptr) {
836 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
837 } else {
838 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
839 }
840 bb_cursor->InsertInstructionAfter(class_table_get, receiver_class);
841 bb_cursor->InsertInstructionAfter(compare, class_table_get);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100842
843 if (outermost_graph_->IsCompilingOsr()) {
844 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
845 } else {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100846 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
847 compare, invoke_instruction->GetDexPc());
848 bb_cursor->InsertInstructionAfter(deoptimize, compare);
849 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
850 if (return_replacement != nullptr) {
851 invoke_instruction->ReplaceWith(return_replacement);
852 }
Nicolas Geoffray1be7cbd2016-04-29 13:56:01 +0100853 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100854 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000855
856 // Run type propagation to get the guard typed.
Vladimir Marko456307a2016-04-19 14:12:13 +0000857 ReferenceTypePropagation rtp_fixup(graph_,
858 outer_compilation_unit_.GetDexCache(),
859 handles_,
860 /* is_first_run */ false);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000861 rtp_fixup.Run();
862
863 MaybeRecordStat(kInlinedPolymorphicCall);
864
865 return true;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100866}
867
Mingyao Yang063fc772016-08-02 11:02:54 -0700868bool HInliner::TryInlineAndReplace(HInvoke* invoke_instruction,
869 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000870 ReferenceTypeInfo receiver_type,
Mingyao Yang063fc772016-08-02 11:02:54 -0700871 bool do_rtp,
872 bool cha_devirtualize) {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000873 HInstruction* return_replacement = nullptr;
Mingyao Yang063fc772016-08-02 11:02:54 -0700874 uint32_t dex_pc = invoke_instruction->GetDexPc();
875 HInstruction* cursor = invoke_instruction->GetPrevious();
876 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000877 if (!TryBuildAndInline(invoke_instruction, method, receiver_type, &return_replacement)) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000878 if (invoke_instruction->IsInvokeInterface()) {
879 // Turn an invoke-interface into an invoke-virtual. An invoke-virtual is always
880 // better than an invoke-interface because:
881 // 1) In the best case, the interface call has one more indirection (to fetch the IMT).
882 // 2) We will not go to the conflict trampoline with an invoke-virtual.
883 // TODO: Consider sharpening once it is not dependent on the compiler driver.
884 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100885 uint32_t dex_method_index = FindMethodIndexIn(
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000886 method, caller_dex_file, invoke_instruction->GetDexMethodIndex());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100887 if (dex_method_index == DexFile::kDexNoIndex) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000888 return false;
889 }
890 HInvokeVirtual* new_invoke = new (graph_->GetArena()) HInvokeVirtual(
891 graph_->GetArena(),
892 invoke_instruction->GetNumberOfArguments(),
893 invoke_instruction->GetType(),
894 invoke_instruction->GetDexPc(),
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100895 dex_method_index,
896 method,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000897 method->GetMethodIndex());
898 HInputsRef inputs = invoke_instruction->GetInputs();
899 for (size_t index = 0; index != inputs.size(); ++index) {
900 new_invoke->SetArgumentAt(index, inputs[index]);
901 }
902 invoke_instruction->GetBlock()->InsertInstructionBefore(new_invoke, invoke_instruction);
903 new_invoke->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
904 if (invoke_instruction->GetType() == Primitive::kPrimNot) {
905 new_invoke->SetReferenceTypeInfo(invoke_instruction->GetReferenceTypeInfo());
906 }
907 return_replacement = new_invoke;
908 } else {
909 // TODO: Consider sharpening an invoke virtual once it is not dependent on the
910 // compiler driver.
911 return false;
912 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000913 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700914 if (cha_devirtualize) {
915 AddCHAGuard(invoke_instruction, dex_pc, cursor, bb_cursor);
916 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000917 if (return_replacement != nullptr) {
918 invoke_instruction->ReplaceWith(return_replacement);
919 }
920 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
David Brazdil94ab38f2016-06-21 17:48:19 +0100921 FixUpReturnReferenceType(method, return_replacement);
922 if (do_rtp && ReturnTypeMoreSpecific(invoke_instruction, return_replacement)) {
923 // Actual return value has a more specific type than the method's declared
924 // return type. Run RTP again on the outer graph to propagate it.
925 ReferenceTypePropagation(graph_,
926 outer_compilation_unit_.GetDexCache(),
927 handles_,
928 /* is_first_run */ false).Run();
929 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000930 return true;
931}
932
933bool HInliner::TryBuildAndInline(HInvoke* invoke_instruction,
934 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000935 ReferenceTypeInfo receiver_type,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000936 HInstruction** return_replacement) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100937 if (method->IsProxyMethod()) {
David Sehr709b0702016-10-13 09:12:37 -0700938 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100939 << " is not inlined because of unimplemented inline support for proxy methods.";
940 return false;
941 }
942
Jeff Haodcdc85b2015-12-04 14:06:18 -0800943 // Check whether we're allowed to inline. The outermost compilation unit is the relevant
944 // dex file here (though the transitivity of an inline chain would allow checking the calller).
945 if (!compiler_driver_->MayInline(method->GetDexFile(),
946 outer_compilation_unit_.GetDexFile())) {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000947 if (TryPatternSubstitution(invoke_instruction, method, return_replacement)) {
David Sehr709b0702016-10-13 09:12:37 -0700948 VLOG(compiler) << "Successfully replaced pattern of invoke "
949 << method->PrettyMethod();
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000950 MaybeRecordStat(kReplacedInvokeWithSimplePattern);
951 return true;
952 }
David Sehr709b0702016-10-13 09:12:37 -0700953 VLOG(compiler) << "Won't inline " << method->PrettyMethod() << " in "
Jeff Haodcdc85b2015-12-04 14:06:18 -0800954 << outer_compilation_unit_.GetDexFile()->GetLocation() << " ("
955 << caller_compilation_unit_.GetDexFile()->GetLocation() << ") from "
956 << method->GetDexFile()->GetLocation();
957 return false;
958 }
959
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100960 bool same_dex_file = IsSameDexFile(*outer_compilation_unit_.GetDexFile(), *method->GetDexFile());
961
962 const DexFile::CodeItem* code_item = method->GetCodeItem();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000963
964 if (code_item == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700965 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000966 << " is not inlined because it is native";
967 return false;
968 }
969
Calin Juravleec748352015-07-29 13:52:12 +0100970 size_t inline_max_code_units = compiler_driver_->GetCompilerOptions().GetInlineMaxCodeUnits();
971 if (code_item->insns_size_in_code_units_ > inline_max_code_units) {
David Sehr709b0702016-10-13 09:12:37 -0700972 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000973 << " is too big to inline: "
974 << code_item->insns_size_in_code_units_
975 << " > "
976 << inline_max_code_units;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000977 return false;
978 }
979
980 if (code_item->tries_size_ != 0) {
David Sehr709b0702016-10-13 09:12:37 -0700981 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000982 << " is not inlined because of try block";
983 return false;
984 }
985
Nicolas Geoffray250a3782016-04-20 16:27:53 +0100986 if (!method->IsCompilable()) {
David Sehr709b0702016-10-13 09:12:37 -0700987 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffray250a3782016-04-20 16:27:53 +0100988 << " has soft failures un-handled by the compiler, so it cannot be inlined";
989 }
990
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100991 if (!method->GetDeclaringClass()->IsVerified()) {
992 uint16_t class_def_idx = method->GetDeclaringClass()->GetDexClassDefIndex();
Calin Juravleffc87072016-04-20 14:22:09 +0100993 if (Runtime::Current()->UseJitCompilation() ||
Nicolas Geoffray5b82d332016-02-18 14:22:32 +0000994 !compiler_driver_->IsMethodVerifiedWithoutFailures(
995 method->GetDexMethodIndex(), class_def_idx, *method->GetDexFile())) {
David Sehr709b0702016-10-13 09:12:37 -0700996 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffrayccc61972015-10-01 14:34:20 +0100997 << " couldn't be verified, so it cannot be inlined";
998 return false;
999 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001000 }
1001
Roland Levillain4c0eb422015-04-24 16:43:49 +01001002 if (invoke_instruction->IsInvokeStaticOrDirect() &&
1003 invoke_instruction->AsInvokeStaticOrDirect()->IsStaticWithImplicitClinitCheck()) {
1004 // Case of a static method that cannot be inlined because it implicitly
1005 // requires an initialization check of its declaring class.
David Sehr709b0702016-10-13 09:12:37 -07001006 VLOG(compiler) << "Method " << method->PrettyMethod()
Roland Levillain4c0eb422015-04-24 16:43:49 +01001007 << " is not inlined because it is static and requires a clinit"
1008 << " check that cannot be emitted due to Dex cache limitations";
1009 return false;
1010 }
1011
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001012 if (!TryBuildAndInlineHelper(
1013 invoke_instruction, method, receiver_type, same_dex_file, return_replacement)) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001014 return false;
1015 }
1016
David Sehr709b0702016-10-13 09:12:37 -07001017 VLOG(compiler) << "Successfully inlined " << method->PrettyMethod();
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001018 MaybeRecordStat(kInlinedInvoke);
1019 return true;
1020}
1021
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001022static HInstruction* GetInvokeInputForArgVRegIndex(HInvoke* invoke_instruction,
1023 size_t arg_vreg_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001024 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001025 size_t input_index = 0;
1026 for (size_t i = 0; i < arg_vreg_index; ++i, ++input_index) {
1027 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
1028 if (Primitive::Is64BitType(invoke_instruction->InputAt(input_index)->GetType())) {
1029 ++i;
1030 DCHECK_NE(i, arg_vreg_index);
1031 }
1032 }
1033 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
1034 return invoke_instruction->InputAt(input_index);
1035}
1036
1037// Try to recognize known simple patterns and replace invoke call with appropriate instructions.
1038bool HInliner::TryPatternSubstitution(HInvoke* invoke_instruction,
1039 ArtMethod* resolved_method,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001040 HInstruction** return_replacement) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001041 InlineMethod inline_method;
1042 if (!InlineMethodAnalyser::AnalyseMethodCode(resolved_method, &inline_method)) {
1043 return false;
1044 }
1045
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001046 switch (inline_method.opcode) {
1047 case kInlineOpNop:
1048 DCHECK_EQ(invoke_instruction->GetType(), Primitive::kPrimVoid);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001049 *return_replacement = nullptr;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001050 break;
1051 case kInlineOpReturnArg:
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001052 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction,
1053 inline_method.d.return_data.arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001054 break;
1055 case kInlineOpNonWideConst:
1056 if (resolved_method->GetShorty()[0] == 'L') {
1057 DCHECK_EQ(inline_method.d.data, 0u);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001058 *return_replacement = graph_->GetNullConstant();
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001059 } else {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001060 *return_replacement = graph_->GetIntConstant(static_cast<int32_t>(inline_method.d.data));
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001061 }
1062 break;
1063 case kInlineOpIGet: {
1064 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1065 if (data.method_is_static || data.object_arg != 0u) {
1066 // TODO: Needs null check.
1067 return false;
1068 }
Vladimir Marko354efa62016-02-04 19:46:56 +00001069 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001070 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
Vladimir Marko354efa62016-02-04 19:46:56 +00001071 HInstanceFieldGet* iget = CreateInstanceFieldGet(dex_cache, data.field_idx, obj);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001072 DCHECK_EQ(iget->GetFieldOffset().Uint32Value(), data.field_offset);
1073 DCHECK_EQ(iget->IsVolatile() ? 1u : 0u, data.is_volatile);
1074 invoke_instruction->GetBlock()->InsertInstructionBefore(iget, invoke_instruction);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001075 *return_replacement = iget;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001076 break;
1077 }
1078 case kInlineOpIPut: {
1079 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1080 if (data.method_is_static || data.object_arg != 0u) {
1081 // TODO: Needs null check.
1082 return false;
1083 }
Vladimir Marko354efa62016-02-04 19:46:56 +00001084 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001085 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
1086 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, data.src_arg);
Vladimir Marko354efa62016-02-04 19:46:56 +00001087 HInstanceFieldSet* iput = CreateInstanceFieldSet(dex_cache, data.field_idx, obj, value);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001088 DCHECK_EQ(iput->GetFieldOffset().Uint32Value(), data.field_offset);
1089 DCHECK_EQ(iput->IsVolatile() ? 1u : 0u, data.is_volatile);
1090 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1091 if (data.return_arg_plus1 != 0u) {
1092 size_t return_arg = data.return_arg_plus1 - 1u;
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001093 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction, return_arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001094 }
1095 break;
1096 }
Vladimir Marko354efa62016-02-04 19:46:56 +00001097 case kInlineOpConstructor: {
1098 const InlineConstructorData& data = inline_method.d.constructor_data;
1099 // Get the indexes to arrays for easier processing.
1100 uint16_t iput_field_indexes[] = {
1101 data.iput0_field_index, data.iput1_field_index, data.iput2_field_index
1102 };
1103 uint16_t iput_args[] = { data.iput0_arg, data.iput1_arg, data.iput2_arg };
1104 static_assert(arraysize(iput_args) == arraysize(iput_field_indexes), "Size mismatch");
1105 // Count valid field indexes.
1106 size_t number_of_iputs = 0u;
1107 while (number_of_iputs != arraysize(iput_field_indexes) &&
1108 iput_field_indexes[number_of_iputs] != DexFile::kDexNoIndex16) {
1109 // Check that there are no duplicate valid field indexes.
1110 DCHECK_EQ(0, std::count(iput_field_indexes + number_of_iputs + 1,
1111 iput_field_indexes + arraysize(iput_field_indexes),
1112 iput_field_indexes[number_of_iputs]));
1113 ++number_of_iputs;
1114 }
1115 // Check that there are no valid field indexes in the rest of the array.
1116 DCHECK_EQ(0, std::count_if(iput_field_indexes + number_of_iputs,
1117 iput_field_indexes + arraysize(iput_field_indexes),
1118 [](uint16_t index) { return index != DexFile::kDexNoIndex16; }));
1119
1120 // Create HInstanceFieldSet for each IPUT that stores non-zero data.
1121 Handle<mirror::DexCache> dex_cache;
1122 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, /* this */ 0u);
1123 bool needs_constructor_barrier = false;
1124 for (size_t i = 0; i != number_of_iputs; ++i) {
1125 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, iput_args[i]);
Roland Levillain1a653882016-03-18 18:05:57 +00001126 if (!value->IsConstant() || !value->AsConstant()->IsZeroBitPattern()) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001127 if (dex_cache.GetReference() == nullptr) {
1128 dex_cache = handles_->NewHandle(resolved_method->GetDexCache());
1129 }
1130 uint16_t field_index = iput_field_indexes[i];
1131 HInstanceFieldSet* iput = CreateInstanceFieldSet(dex_cache, field_index, obj, value);
1132 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1133
1134 // Check whether the field is final. If it is, we need to add a barrier.
Andreas Gampe542451c2016-07-26 09:02:02 -07001135 PointerSize pointer_size = InstructionSetPointerSize(codegen_->GetInstructionSet());
Vladimir Marko354efa62016-02-04 19:46:56 +00001136 ArtField* resolved_field = dex_cache->GetResolvedField(field_index, pointer_size);
1137 DCHECK(resolved_field != nullptr);
1138 if (resolved_field->IsFinal()) {
1139 needs_constructor_barrier = true;
1140 }
1141 }
1142 }
1143 if (needs_constructor_barrier) {
1144 HMemoryBarrier* barrier = new (graph_->GetArena()) HMemoryBarrier(kStoreStore, kNoDexPc);
1145 invoke_instruction->GetBlock()->InsertInstructionBefore(barrier, invoke_instruction);
1146 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001147 *return_replacement = nullptr;
Vladimir Marko354efa62016-02-04 19:46:56 +00001148 break;
1149 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001150 default:
1151 LOG(FATAL) << "UNREACHABLE";
1152 UNREACHABLE();
1153 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001154 return true;
1155}
1156
Vladimir Marko354efa62016-02-04 19:46:56 +00001157HInstanceFieldGet* HInliner::CreateInstanceFieldGet(Handle<mirror::DexCache> dex_cache,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001158 uint32_t field_index,
1159 HInstruction* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001160 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001161 PointerSize pointer_size = InstructionSetPointerSize(codegen_->GetInstructionSet());
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001162 ArtField* resolved_field = dex_cache->GetResolvedField(field_index, pointer_size);
1163 DCHECK(resolved_field != nullptr);
1164 HInstanceFieldGet* iget = new (graph_->GetArena()) HInstanceFieldGet(
1165 obj,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001166 resolved_field,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001167 resolved_field->GetTypeAsPrimitiveType(),
1168 resolved_field->GetOffset(),
1169 resolved_field->IsVolatile(),
1170 field_index,
1171 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Marko354efa62016-02-04 19:46:56 +00001172 *dex_cache->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001173 // Read barrier generates a runtime call in slow path and we need a valid
1174 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1175 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001176 if (iget->GetType() == Primitive::kPrimNot) {
Vladimir Marko456307a2016-04-19 14:12:13 +00001177 // Use the same dex_cache that we used for field lookup as the hint_dex_cache.
Mathieu Chartier5812e202017-02-13 18:32:04 -08001178 ReferenceTypePropagation rtp(graph_, dex_cache, handles_, /* is_first_run */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001179 rtp.Visit(iget);
1180 }
1181 return iget;
1182}
1183
Vladimir Marko354efa62016-02-04 19:46:56 +00001184HInstanceFieldSet* HInliner::CreateInstanceFieldSet(Handle<mirror::DexCache> dex_cache,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001185 uint32_t field_index,
1186 HInstruction* obj,
1187 HInstruction* value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001188 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001189 PointerSize pointer_size = InstructionSetPointerSize(codegen_->GetInstructionSet());
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001190 ArtField* resolved_field = dex_cache->GetResolvedField(field_index, pointer_size);
1191 DCHECK(resolved_field != nullptr);
1192 HInstanceFieldSet* iput = new (graph_->GetArena()) HInstanceFieldSet(
1193 obj,
1194 value,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001195 resolved_field,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001196 resolved_field->GetTypeAsPrimitiveType(),
1197 resolved_field->GetOffset(),
1198 resolved_field->IsVolatile(),
1199 field_index,
1200 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Marko354efa62016-02-04 19:46:56 +00001201 *dex_cache->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001202 // Read barrier generates a runtime call in slow path and we need a valid
1203 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1204 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001205 return iput;
1206}
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001207
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001208bool HInliner::TryBuildAndInlineHelper(HInvoke* invoke_instruction,
1209 ArtMethod* resolved_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001210 ReferenceTypeInfo receiver_type,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001211 bool same_dex_file,
1212 HInstruction** return_replacement) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001213 DCHECK(!(resolved_method->IsStatic() && receiver_type.IsValid()));
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001214 ScopedObjectAccess soa(Thread::Current());
1215 const DexFile::CodeItem* code_item = resolved_method->GetCodeItem();
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001216 const DexFile& callee_dex_file = *resolved_method->GetDexFile();
1217 uint32_t method_index = resolved_method->GetDexMethodIndex();
Calin Juravle2e768302015-07-28 14:41:11 +00001218 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Mathieu Chartier736b5602015-09-02 14:54:11 -07001219 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Nicolas Geoffrayf1aedb12016-07-28 03:49:14 +01001220 Handle<mirror::ClassLoader> class_loader(handles_->NewHandle(
1221 resolved_method->GetDeclaringClass()->GetClassLoader()));
1222
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001223 DexCompilationUnit dex_compilation_unit(
Mathieu Chartier5812e202017-02-13 18:32:04 -08001224 class_loader.ToJObject(),
Nicolas Geoffray5b82d332016-02-18 14:22:32 +00001225 class_linker,
1226 callee_dex_file,
1227 code_item,
1228 resolved_method->GetDeclaringClass()->GetDexClassDefIndex(),
1229 method_index,
1230 resolved_method->GetAccessFlags(),
1231 /* verified_method */ nullptr,
1232 dex_cache);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001233
Calin Juravle3cd4fc82015-05-14 15:15:42 +01001234 bool requires_ctor_barrier = false;
1235
1236 if (dex_compilation_unit.IsConstructor()) {
1237 // If it's a super invocation and we already generate a barrier there's no need
1238 // to generate another one.
1239 // We identify super calls by looking at the "this" pointer. If its value is the
1240 // same as the local "this" pointer then we must have a super invocation.
1241 bool is_super_invocation = invoke_instruction->InputAt(0)->IsParameterValue()
1242 && invoke_instruction->InputAt(0)->AsParameterValue()->IsThis();
1243 if (is_super_invocation && graph_->ShouldGenerateConstructorBarrier()) {
1244 requires_ctor_barrier = false;
1245 } else {
1246 Thread* self = Thread::Current();
1247 requires_ctor_barrier = compiler_driver_->RequiresConstructorBarrier(self,
1248 dex_compilation_unit.GetDexFile(),
1249 dex_compilation_unit.GetClassDefIndex());
1250 }
1251 }
1252
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001253 InvokeType invoke_type = invoke_instruction->GetInvokeType();
Nicolas Geoffray35071052015-06-09 15:43:38 +01001254 if (invoke_type == kInterface) {
1255 // We have statically resolved the dispatch. To please the class linker
1256 // at runtime, we change this call as if it was a virtual call.
1257 invoke_type = kVirtual;
1258 }
David Brazdil3f523062016-02-29 16:53:33 +00001259
1260 const int32_t caller_instruction_counter = graph_->GetCurrentInstructionId();
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +00001261 HGraph* callee_graph = new (graph_->GetArena()) HGraph(
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001262 graph_->GetArena(),
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001263 callee_dex_file,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001264 method_index,
Calin Juravle3cd4fc82015-05-14 15:15:42 +01001265 requires_ctor_barrier,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001266 compiler_driver_->GetInstructionSet(),
Nicolas Geoffray35071052015-06-09 15:43:38 +01001267 invoke_type,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001268 graph_->IsDebuggable(),
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001269 /* osr */ false,
David Brazdil3f523062016-02-29 16:53:33 +00001270 caller_instruction_counter);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001271 callee_graph->SetArtMethod(resolved_method);
David Brazdil5e8b1372015-01-23 14:39:08 +00001272
Roland Levillaina8013fd2016-04-04 15:34:31 +01001273 // When they are needed, allocate `inline_stats` on the heap instead
1274 // of on the stack, as Clang might produce a stack frame too large
1275 // for this function, that would not fit the requirements of the
1276 // `-Wframe-larger-than` option.
1277 std::unique_ptr<OptimizingCompilerStats> inline_stats =
1278 (stats_ == nullptr) ? nullptr : MakeUnique<OptimizingCompilerStats>();
David Brazdil5e8b1372015-01-23 14:39:08 +00001279 HGraphBuilder builder(callee_graph,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001280 &dex_compilation_unit,
1281 &outer_compilation_unit_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001282 resolved_method->GetDexFile(),
David Brazdil86ea7ee2016-02-16 09:26:07 +00001283 *code_item,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001284 compiler_driver_,
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00001285 codegen_,
Roland Levillaina8013fd2016-04-04 15:34:31 +01001286 inline_stats.get(),
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001287 resolved_method->GetQuickenedInfo(class_linker->GetImagePointerSize()),
David Brazdildee58d62016-04-07 09:54:26 +00001288 dex_cache,
1289 handles_);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001290
David Brazdildee58d62016-04-07 09:54:26 +00001291 if (builder.BuildGraph() != kAnalysisSuccess) {
David Sehr709b0702016-10-13 09:12:37 -07001292 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001293 << " could not be built, so cannot be inlined";
1294 return false;
1295 }
1296
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001297 if (!RegisterAllocator::CanAllocateRegistersFor(*callee_graph,
1298 compiler_driver_->GetInstructionSet())) {
David Sehr709b0702016-10-13 09:12:37 -07001299 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001300 << " cannot be inlined because of the register allocator";
1301 return false;
1302 }
1303
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001304 size_t parameter_index = 0;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001305 bool run_rtp = false;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001306 for (HInstructionIterator instructions(callee_graph->GetEntryBlock()->GetInstructions());
1307 !instructions.Done();
1308 instructions.Advance()) {
1309 HInstruction* current = instructions.Current();
1310 if (current->IsParameterValue()) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001311 HInstruction* argument = invoke_instruction->InputAt(parameter_index);
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001312 if (argument->IsNullConstant()) {
1313 current->ReplaceWith(callee_graph->GetNullConstant());
1314 } else if (argument->IsIntConstant()) {
1315 current->ReplaceWith(callee_graph->GetIntConstant(argument->AsIntConstant()->GetValue()));
1316 } else if (argument->IsLongConstant()) {
1317 current->ReplaceWith(callee_graph->GetLongConstant(argument->AsLongConstant()->GetValue()));
1318 } else if (argument->IsFloatConstant()) {
1319 current->ReplaceWith(
1320 callee_graph->GetFloatConstant(argument->AsFloatConstant()->GetValue()));
1321 } else if (argument->IsDoubleConstant()) {
1322 current->ReplaceWith(
1323 callee_graph->GetDoubleConstant(argument->AsDoubleConstant()->GetValue()));
1324 } else if (argument->GetType() == Primitive::kPrimNot) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001325 if (!resolved_method->IsStatic() && parameter_index == 0 && receiver_type.IsValid()) {
1326 run_rtp = true;
1327 current->SetReferenceTypeInfo(receiver_type);
1328 } else {
1329 current->SetReferenceTypeInfo(argument->GetReferenceTypeInfo());
1330 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001331 current->AsParameterValue()->SetCanBeNull(argument->CanBeNull());
1332 }
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001333 ++parameter_index;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001334 }
1335 }
1336
David Brazdil94ab38f2016-06-21 17:48:19 +01001337 // We have replaced formal arguments with actual arguments. If actual types
1338 // are more specific than the declared ones, run RTP again on the inner graph.
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001339 if (run_rtp || ArgumentTypesMoreSpecific(invoke_instruction, resolved_method)) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001340 ReferenceTypePropagation(callee_graph,
1341 dex_compilation_unit.GetDexCache(),
1342 handles_,
1343 /* is_first_run */ false).Run();
1344 }
1345
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001346 size_t number_of_instructions_budget = kMaximumNumberOfHInstructions;
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001347 size_t number_of_inlined_instructions =
1348 RunOptimizations(callee_graph, code_item, dex_compilation_unit);
1349 number_of_instructions_budget += number_of_inlined_instructions;
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +00001350
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001351 HBasicBlock* exit_block = callee_graph->GetExitBlock();
1352 if (exit_block == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07001353 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001354 << " could not be inlined because it has an infinite loop";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001355 return false;
1356 }
1357
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001358 bool has_one_return = false;
Vladimir Marko60584552015-09-03 13:35:12 +00001359 for (HBasicBlock* predecessor : exit_block->GetPredecessors()) {
1360 if (predecessor->GetLastInstruction()->IsThrow()) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001361 if (invoke_instruction->GetBlock()->IsTryBlock()) {
1362 // TODO(ngeoffray): Support adding HTryBoundary in Hgraph::InlineInto.
1363 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1364 << " could not be inlined because one branch always throws and"
1365 << " caller is in a try/catch block";
1366 return false;
1367 } else if (graph_->GetExitBlock() == nullptr) {
1368 // TODO(ngeoffray): Support adding HExit in the caller graph.
1369 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1370 << " could not be inlined because one branch always throws and"
1371 << " caller does not have an exit block";
1372 return false;
1373 }
1374 } else {
1375 has_one_return = true;
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001376 }
1377 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001378
1379 if (!has_one_return) {
David Sehr709b0702016-10-13 09:12:37 -07001380 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001381 << " could not be inlined because it always throws";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001382 return false;
1383 }
1384
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001385 size_t number_of_instructions = 0;
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001386
1387 bool can_inline_environment =
1388 total_number_of_dex_registers_ < kMaximumNumberOfCumulatedDexRegisters;
1389
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001390 // Skip the entry block, it does not contain instructions that prevent inlining.
1391 for (HBasicBlock* block : callee_graph->GetReversePostOrderSkipEntryBlock()) {
David Sehrc757dec2016-11-04 15:48:34 -07001392 if (block->IsLoopHeader()) {
1393 if (block->GetLoopInformation()->IsIrreducible()) {
1394 // Don't inline methods with irreducible loops, they could prevent some
1395 // optimizations to run.
1396 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1397 << " could not be inlined because it contains an irreducible loop";
1398 return false;
1399 }
1400 if (!block->GetLoopInformation()->HasExitEdge()) {
1401 // Don't inline methods with loops without exit, since they cause the
1402 // loop information to be computed incorrectly when updating after
1403 // inlining.
1404 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1405 << " could not be inlined because it contains a loop with no exit";
1406 return false;
1407 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001408 }
1409
1410 for (HInstructionIterator instr_it(block->GetInstructions());
1411 !instr_it.Done();
1412 instr_it.Advance()) {
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001413 if (number_of_instructions++ == number_of_instructions_budget) {
David Sehr709b0702016-10-13 09:12:37 -07001414 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001415 << " is not inlined because its caller has reached"
1416 << " its instruction budget limit.";
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001417 return false;
1418 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001419 HInstruction* current = instr_it.Current();
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001420 if (!can_inline_environment && current->NeedsEnvironment()) {
David Sehr709b0702016-10-13 09:12:37 -07001421 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001422 << " is not inlined because its caller has reached"
1423 << " its environment budget limit.";
1424 return false;
1425 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001426
Nicolas Geoffrayfbdfa6d2017-02-03 10:43:13 +00001427 if (current->NeedsEnvironment() &&
1428 !CanEncodeInlinedMethodInStackMap(*caller_compilation_unit_.GetDexFile(),
1429 resolved_method)) {
David Sehr709b0702016-10-13 09:12:37 -07001430 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001431 << " could not be inlined because " << current->DebugName()
Nicolas Geoffrayfbdfa6d2017-02-03 10:43:13 +00001432 << " needs an environment, is in a different dex file"
1433 << ", and cannot be encoded in the stack maps.";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001434 return false;
1435 }
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001436
Vladimir Markodc151b22015-10-15 18:02:30 +01001437 if (!same_dex_file && current->NeedsDexCacheOfDeclaringClass()) {
David Sehr709b0702016-10-13 09:12:37 -07001438 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001439 << " could not be inlined because " << current->DebugName()
1440 << " it is in a different dex file and requires access to the dex cache";
1441 return false;
1442 }
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001443
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001444 if (current->IsUnresolvedStaticFieldGet() ||
1445 current->IsUnresolvedInstanceFieldGet() ||
1446 current->IsUnresolvedStaticFieldSet() ||
1447 current->IsUnresolvedInstanceFieldSet()) {
1448 // Entrypoint for unresolved fields does not handle inlined frames.
David Sehr709b0702016-10-13 09:12:37 -07001449 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001450 << " could not be inlined because it is using an unresolved"
1451 << " entrypoint";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001452 return false;
1453 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001454 }
1455 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001456 number_of_inlined_instructions_ += number_of_instructions;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001457
David Brazdil3f523062016-02-29 16:53:33 +00001458 DCHECK_EQ(caller_instruction_counter, graph_->GetCurrentInstructionId())
1459 << "No instructions can be added to the outer graph while inner graph is being built";
1460
1461 const int32_t callee_instruction_counter = callee_graph->GetCurrentInstructionId();
1462 graph_->SetCurrentInstructionId(callee_instruction_counter);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001463 *return_replacement = callee_graph->InlineInto(graph_, invoke_instruction);
David Brazdil3f523062016-02-29 16:53:33 +00001464
1465 DCHECK_EQ(callee_instruction_counter, callee_graph->GetCurrentInstructionId())
1466 << "No instructions can be added to the inner graph during inlining into the outer graph";
1467
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001468 return true;
1469}
Calin Juravle2e768302015-07-28 14:41:11 +00001470
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001471size_t HInliner::RunOptimizations(HGraph* callee_graph,
1472 const DexFile::CodeItem* code_item,
1473 const DexCompilationUnit& dex_compilation_unit) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001474 // Note: if the outermost_graph_ is being compiled OSR, we should not run any
1475 // optimization that could lead to a HDeoptimize. The following optimizations do not.
Andreas Gampeca620d72016-11-08 08:09:33 -08001476 HDeadCodeElimination dce(callee_graph, stats_, "dead_code_elimination$inliner");
1477 HConstantFolding fold(callee_graph, "constant_folding$inliner");
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001478 HSharpening sharpening(callee_graph, codegen_, dex_compilation_unit, compiler_driver_, handles_);
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001479 InstructionSimplifier simplify(callee_graph, stats_);
Nicolas Geoffray762869d2016-07-15 15:28:35 +01001480 IntrinsicsRecognizer intrinsics(callee_graph, stats_);
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001481
1482 HOptimization* optimizations[] = {
1483 &intrinsics,
1484 &sharpening,
1485 &simplify,
1486 &fold,
1487 &dce,
1488 };
1489
1490 for (size_t i = 0; i < arraysize(optimizations); ++i) {
1491 HOptimization* optimization = optimizations[i];
1492 optimization->Run();
1493 }
1494
1495 size_t number_of_inlined_instructions = 0u;
1496 if (depth_ + 1 < compiler_driver_->GetCompilerOptions().GetInlineDepthLimit()) {
1497 HInliner inliner(callee_graph,
1498 outermost_graph_,
1499 codegen_,
1500 outer_compilation_unit_,
1501 dex_compilation_unit,
1502 compiler_driver_,
1503 handles_,
1504 stats_,
1505 total_number_of_dex_registers_ + code_item->registers_size_,
1506 depth_ + 1);
1507 inliner.Run();
1508 number_of_inlined_instructions += inliner.number_of_inlined_instructions_;
1509 }
1510
1511 return number_of_inlined_instructions;
1512}
1513
David Brazdil94ab38f2016-06-21 17:48:19 +01001514static bool IsReferenceTypeRefinement(ReferenceTypeInfo declared_rti,
1515 bool declared_can_be_null,
1516 HInstruction* actual_obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001517 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001518 if (declared_can_be_null && !actual_obj->CanBeNull()) {
1519 return true;
1520 }
1521
1522 ReferenceTypeInfo actual_rti = actual_obj->GetReferenceTypeInfo();
1523 return (actual_rti.IsExact() && !declared_rti.IsExact()) ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001524 declared_rti.IsStrictSupertypeOf(actual_rti);
David Brazdil94ab38f2016-06-21 17:48:19 +01001525}
1526
1527ReferenceTypeInfo HInliner::GetClassRTI(mirror::Class* klass) {
1528 return ReferenceTypePropagation::IsAdmissible(klass)
1529 ? ReferenceTypeInfo::Create(handles_->NewHandle(klass))
1530 : graph_->GetInexactObjectRti();
1531}
1532
1533bool HInliner::ArgumentTypesMoreSpecific(HInvoke* invoke_instruction, ArtMethod* resolved_method) {
1534 // If this is an instance call, test whether the type of the `this` argument
1535 // is more specific than the class which declares the method.
1536 if (!resolved_method->IsStatic()) {
1537 if (IsReferenceTypeRefinement(GetClassRTI(resolved_method->GetDeclaringClass()),
1538 /* declared_can_be_null */ false,
1539 invoke_instruction->InputAt(0u))) {
1540 return true;
1541 }
1542 }
1543
David Brazdil94ab38f2016-06-21 17:48:19 +01001544 // Iterate over the list of parameter types and test whether any of the
1545 // actual inputs has a more specific reference type than the type declared in
1546 // the signature.
1547 const DexFile::TypeList* param_list = resolved_method->GetParameterTypeList();
1548 for (size_t param_idx = 0,
1549 input_idx = resolved_method->IsStatic() ? 0 : 1,
1550 e = (param_list == nullptr ? 0 : param_list->Size());
1551 param_idx < e;
1552 ++param_idx, ++input_idx) {
1553 HInstruction* input = invoke_instruction->InputAt(input_idx);
1554 if (input->GetType() == Primitive::kPrimNot) {
Vladimir Marko942fd312017-01-16 20:52:19 +00001555 mirror::Class* param_cls = resolved_method->GetClassFromTypeIndex(
David Brazdil94ab38f2016-06-21 17:48:19 +01001556 param_list->GetTypeItem(param_idx).type_idx_,
Vladimir Marko942fd312017-01-16 20:52:19 +00001557 /* resolve */ false);
David Brazdil94ab38f2016-06-21 17:48:19 +01001558 if (IsReferenceTypeRefinement(GetClassRTI(param_cls),
1559 /* declared_can_be_null */ true,
1560 input)) {
1561 return true;
1562 }
1563 }
1564 }
1565
1566 return false;
1567}
1568
1569bool HInliner::ReturnTypeMoreSpecific(HInvoke* invoke_instruction,
1570 HInstruction* return_replacement) {
Alex Light68289a52015-12-15 17:30:30 -08001571 // Check the integrity of reference types and run another type propagation if needed.
David Brazdil4833f5a2015-12-16 10:37:39 +00001572 if (return_replacement != nullptr) {
1573 if (return_replacement->GetType() == Primitive::kPrimNot) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001574 // Test if the return type is a refinement of the declared return type.
1575 if (IsReferenceTypeRefinement(invoke_instruction->GetReferenceTypeInfo(),
1576 /* declared_can_be_null */ true,
1577 return_replacement)) {
1578 return true;
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001579 } else if (return_replacement->IsInstanceFieldGet()) {
1580 HInstanceFieldGet* field_get = return_replacement->AsInstanceFieldGet();
1581 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1582 if (field_get->GetFieldInfo().GetField() ==
1583 class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0)) {
1584 return true;
1585 }
David Brazdil94ab38f2016-06-21 17:48:19 +01001586 }
1587 } else if (return_replacement->IsInstanceOf()) {
1588 // Inlining InstanceOf into an If may put a tighter bound on reference types.
1589 return true;
1590 }
1591 }
1592
1593 return false;
1594}
1595
1596void HInliner::FixUpReturnReferenceType(ArtMethod* resolved_method,
1597 HInstruction* return_replacement) {
1598 if (return_replacement != nullptr) {
1599 if (return_replacement->GetType() == Primitive::kPrimNot) {
David Brazdil4833f5a2015-12-16 10:37:39 +00001600 if (!return_replacement->GetReferenceTypeInfo().IsValid()) {
1601 // Make sure that we have a valid type for the return. We may get an invalid one when
1602 // we inline invokes with multiple branches and create a Phi for the result.
1603 // TODO: we could be more precise by merging the phi inputs but that requires
1604 // some functionality from the reference type propagation.
1605 DCHECK(return_replacement->IsPhi());
Vladimir Marko942fd312017-01-16 20:52:19 +00001606 mirror::Class* cls = resolved_method->GetReturnType(false /* resolve */);
David Brazdil94ab38f2016-06-21 17:48:19 +01001607 return_replacement->SetReferenceTypeInfo(GetClassRTI(cls));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001608 }
Calin Juravlecdfed3d2015-10-26 14:05:01 +00001609 }
Calin Juravle2e768302015-07-28 14:41:11 +00001610 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001611}
1612
1613} // namespace art