blob: 14437dea39bbc4a0227f303916f2834a936e48b9 [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,
Vladimir Markobfb80d22017-02-14 14:08:12 +0000195 const DexCompilationUnit& compilation_unit)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700196 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markobfb80d22017-02-14 14:08:12 +0000197 const DexFile& dex_file = *compilation_unit.GetDexFile();
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)) {
Vladimir Markobfb80d22017-02-14 14:08:12 +0000206 DCHECK_EQ(cls->GetDexCache(), compilation_unit.GetDexCache().Get());
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000207 index = cls->GetDexTypeIndex();
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100208 } else {
209 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Vladimir Markobfb80d22017-02-14 14:08:12 +0000210 // We cannot guarantee the entry will resolve to the same class,
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100211 // as there may be different class loaders. So only return the index if it's
Vladimir Markobfb80d22017-02-14 14:08:12 +0000212 // the right class already resolved with the class loader.
213 if (index.IsValid()) {
214 ObjPtr<mirror::Class> resolved = ClassLinker::LookupResolvedType(
215 index, compilation_unit.GetDexCache().Get(), compilation_unit.GetClassLoader().Get());
216 if (resolved != cls) {
217 index = dex::TypeIndex::Invalid();
218 }
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100219 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100220 }
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000221
222 return index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100223}
224
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000225class ScopedProfilingInfoInlineUse {
226 public:
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000227 explicit ScopedProfilingInfoInlineUse(ArtMethod* method, Thread* self)
228 : method_(method),
229 self_(self),
230 // Fetch the profiling info ahead of using it. If it's null when fetching,
231 // we should not call JitCodeCache::DoneInlining.
232 profiling_info_(
233 Runtime::Current()->GetJit()->GetCodeCache()->NotifyCompilerUse(method, self)) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000234 }
235
236 ~ScopedProfilingInfoInlineUse() {
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000237 if (profiling_info_ != nullptr) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700238 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000239 DCHECK_EQ(profiling_info_, method_->GetProfilingInfo(pointer_size));
240 Runtime::Current()->GetJit()->GetCodeCache()->DoneCompilerUse(method_, self_);
241 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000242 }
243
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000244 ProfilingInfo* GetProfilingInfo() const { return profiling_info_; }
245
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000246 private:
247 ArtMethod* const method_;
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000248 Thread* const self_;
249 ProfilingInfo* const profiling_info_;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000250};
251
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000252static bool IsMonomorphic(Handle<mirror::ObjectArray<mirror::Class>> classes)
253 REQUIRES_SHARED(Locks::mutator_lock_) {
254 DCHECK_GE(InlineCache::kIndividualCacheSize, 2);
255 return classes->Get(0) != nullptr && classes->Get(1) == nullptr;
256}
257
258static bool IsMegamorphic(Handle<mirror::ObjectArray<mirror::Class>> classes)
259 REQUIRES_SHARED(Locks::mutator_lock_) {
260 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
261 if (classes->Get(i) == nullptr) {
262 return false;
263 }
264 }
265 return true;
266}
267
268static mirror::Class* GetMonomorphicType(Handle<mirror::ObjectArray<mirror::Class>> classes)
269 REQUIRES_SHARED(Locks::mutator_lock_) {
270 DCHECK(classes->Get(0) != nullptr);
271 return classes->Get(0);
272}
273
274static bool IsUninitialized(Handle<mirror::ObjectArray<mirror::Class>> classes)
275 REQUIRES_SHARED(Locks::mutator_lock_) {
276 return classes->Get(0) == nullptr;
277}
278
279static bool IsPolymorphic(Handle<mirror::ObjectArray<mirror::Class>> classes)
280 REQUIRES_SHARED(Locks::mutator_lock_) {
281 DCHECK_GE(InlineCache::kIndividualCacheSize, 3);
282 return classes->Get(1) != nullptr &&
283 classes->Get(InlineCache::kIndividualCacheSize - 1) == nullptr;
284}
285
Mingyao Yang063fc772016-08-02 11:02:54 -0700286ArtMethod* HInliner::TryCHADevirtualization(ArtMethod* resolved_method) {
287 if (!resolved_method->HasSingleImplementation()) {
288 return nullptr;
289 }
290 if (Runtime::Current()->IsAotCompiler()) {
291 // No CHA-based devirtulization for AOT compiler (yet).
292 return nullptr;
293 }
294 if (outermost_graph_->IsCompilingOsr()) {
295 // We do not support HDeoptimize in OSR methods.
296 return nullptr;
297 }
Mingyao Yange8fcd012017-01-20 10:43:30 -0800298 PointerSize pointer_size = caller_compilation_unit_.GetClassLinker()->GetImagePointerSize();
299 return resolved_method->GetSingleImplementation(pointer_size);
Mingyao Yang063fc772016-08-02 11:02:54 -0700300}
301
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700302bool HInliner::TryInline(HInvoke* invoke_instruction) {
Orion Hodsonac141392017-01-13 11:53:47 +0000303 if (invoke_instruction->IsInvokeUnresolved() ||
304 invoke_instruction->IsInvokePolymorphic()) {
305 return false; // Don't bother to move further if we know the method is unresolved or an
306 // invoke-polymorphic.
Calin Juravle175dc732015-08-25 15:42:32 +0100307 }
308
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000309 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100310 uint32_t method_index = invoke_instruction->GetDexMethodIndex();
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000311 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -0700312 VLOG(compiler) << "Try inlining " << caller_dex_file.PrettyMethod(method_index);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000313
Nicolas Geoffray35071052015-06-09 15:43:38 +0100314 // We can query the dex cache directly. The verifier has populated it already.
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100315 ArtMethod* resolved_method = invoke_instruction->GetResolvedMethod();
Andreas Gampefd2140f2015-12-23 16:30:44 -0800316 ArtMethod* actual_method = nullptr;
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100317 if (resolved_method == nullptr) {
318 DCHECK(invoke_instruction->IsInvokeStaticOrDirect());
319 DCHECK(invoke_instruction->AsInvokeStaticOrDirect()->IsStringInit());
320 VLOG(compiler) << "Not inlining a String.<init> method";
321 return false;
322 } else if (invoke_instruction->IsInvokeStaticOrDirect()) {
Andreas Gampefd2140f2015-12-23 16:30:44 -0800323 actual_method = resolved_method;
Vladimir Marko58155012015-08-19 12:49:41 +0000324 } else {
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100325 // Check if we can statically find the method.
326 actual_method = FindVirtualOrInterfaceTarget(invoke_instruction, resolved_method);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000327 }
328
Mingyao Yang063fc772016-08-02 11:02:54 -0700329 bool cha_devirtualize = false;
330 if (actual_method == nullptr) {
331 ArtMethod* method = TryCHADevirtualization(resolved_method);
332 if (method != nullptr) {
333 cha_devirtualize = true;
334 actual_method = method;
335 }
336 }
337
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100338 if (actual_method != nullptr) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700339 bool result = TryInlineAndReplace(invoke_instruction,
340 actual_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000341 ReferenceTypeInfo::CreateInvalid(),
Mingyao Yang063fc772016-08-02 11:02:54 -0700342 /* do_rtp */ true,
343 cha_devirtualize);
Calin Juravle69158982016-03-16 11:53:41 +0000344 if (result && !invoke_instruction->IsInvokeStaticOrDirect()) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700345 if (cha_devirtualize) {
346 // Add dependency due to devirtulization. We've assumed resolved_method
347 // has single implementation.
348 outermost_graph_->AddCHASingleImplementationDependency(resolved_method);
349 MaybeRecordStat(kCHAInline);
350 } else {
351 MaybeRecordStat(kInlinedInvokeVirtualOrInterface);
352 }
Calin Juravle69158982016-03-16 11:53:41 +0000353 }
354 return result;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100355 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000356
Andreas Gampefd2140f2015-12-23 16:30:44 -0800357 DCHECK(!invoke_instruction->IsInvokeStaticOrDirect());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100358
359 // Check if we can use an inline cache.
360 ArtMethod* caller = graph_->GetArtMethod();
Calin Juravleffc87072016-04-20 14:22:09 +0100361 if (Runtime::Current()->UseJitCompilation()) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000362 // Under JIT, we should always know the caller.
363 DCHECK(caller != nullptr);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000364 ScopedProfilingInfoInlineUse spiis(caller, soa.Self());
365 ProfilingInfo* profiling_info = spiis.GetProfilingInfo();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000366 if (profiling_info != nullptr) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000367 StackHandleScope<1> hs(soa.Self());
368 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
369 Handle<mirror::ObjectArray<mirror::Class>> inline_cache = hs.NewHandle(
370 mirror::ObjectArray<mirror::Class>::Alloc(
371 soa.Self(),
372 class_linker->GetClassRoot(ClassLinker::kClassArrayClass),
373 InlineCache::kIndividualCacheSize));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800374 if (inline_cache == nullptr) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000375 // We got an OOME. Just clear the exception, and don't inline.
376 DCHECK(soa.Self()->IsExceptionPending());
377 soa.Self()->ClearException();
378 VLOG(compiler) << "Out of memory in the compiler when trying to inline";
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000379 return false;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000380 } else {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000381 Runtime::Current()->GetJit()->GetCodeCache()->CopyInlineCacheInto(
382 *profiling_info->GetInlineCache(invoke_instruction->GetDexPc()),
383 inline_cache);
384 if (IsUninitialized(inline_cache)) {
385 VLOG(compiler) << "Interface or virtual call to "
386 << caller_dex_file.PrettyMethod(method_index)
387 << " is not hit and not inlined";
388 return false;
389 } else if (IsMonomorphic(inline_cache)) {
390 MaybeRecordStat(kMonomorphicCall);
391 if (outermost_graph_->IsCompilingOsr()) {
392 // If we are compiling OSR, we pretend this call is polymorphic, as we may come from the
393 // interpreter and it may have seen different receiver types.
394 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
395 } else {
396 return TryInlineMonomorphicCall(invoke_instruction, resolved_method, inline_cache);
397 }
398 } else if (IsPolymorphic(inline_cache)) {
399 MaybeRecordStat(kPolymorphicCall);
400 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
401 } else {
402 DCHECK(IsMegamorphic(inline_cache));
403 VLOG(compiler) << "Interface or virtual call to "
404 << caller_dex_file.PrettyMethod(method_index)
405 << " is megamorphic and not inlined";
406 MaybeRecordStat(kMegamorphicCall);
407 return false;
408 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000409 }
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100410 }
411 }
412
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100413 VLOG(compiler) << "Interface or virtual call to "
David Sehr709b0702016-10-13 09:12:37 -0700414 << caller_dex_file.PrettyMethod(method_index)
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100415 << " could not be statically determined";
416 return false;
417}
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000418
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000419HInstanceFieldGet* HInliner::BuildGetReceiverClass(ClassLinker* class_linker,
420 HInstruction* receiver,
421 uint32_t dex_pc) const {
422 ArtField* field = class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0);
423 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000424 HInstanceFieldGet* result = new (graph_->GetArena()) HInstanceFieldGet(
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000425 receiver,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000426 field,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000427 Primitive::kPrimNot,
428 field->GetOffset(),
429 field->IsVolatile(),
430 field->GetDexFieldIndex(),
431 field->GetDeclaringClass()->GetDexClassDefIndex(),
432 *field->GetDexFile(),
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000433 dex_pc);
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000434 // The class of a field is effectively final, and does not have any memory dependencies.
435 result->SetSideEffects(SideEffects::None());
436 return result;
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000437}
438
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100439bool HInliner::TryInlineMonomorphicCall(HInvoke* invoke_instruction,
440 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000441 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000442 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
443 << invoke_instruction->DebugName();
444
Andreas Gampea5b09a62016-11-17 15:21:22 -0800445 dex::TypeIndex class_index = FindClassIndexIn(
Vladimir Markobfb80d22017-02-14 14:08:12 +0000446 GetMonomorphicType(classes), caller_compilation_unit_);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800447 if (!class_index.IsValid()) {
David Sehr709b0702016-10-13 09:12:37 -0700448 VLOG(compiler) << "Call to " << ArtMethod::PrettyMethod(resolved_method)
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100449 << " from inline cache is not inlined because its class is not"
450 << " accessible to the caller";
451 return false;
452 }
453
454 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700455 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100456 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000457 resolved_method = GetMonomorphicType(classes)->FindVirtualMethodForInterface(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100458 resolved_method, pointer_size);
459 } else {
460 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000461 resolved_method = GetMonomorphicType(classes)->FindVirtualMethodForVirtual(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100462 resolved_method, pointer_size);
463 }
464 DCHECK(resolved_method != nullptr);
465 HInstruction* receiver = invoke_instruction->InputAt(0);
466 HInstruction* cursor = invoke_instruction->GetPrevious();
467 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000468 Handle<mirror::Class> monomorphic_type = handles_->NewHandle(GetMonomorphicType(classes));
Mingyao Yang063fc772016-08-02 11:02:54 -0700469 if (!TryInlineAndReplace(invoke_instruction,
470 resolved_method,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000471 ReferenceTypeInfo::Create(monomorphic_type, /* is_exact */ true),
Mingyao Yang063fc772016-08-02 11:02:54 -0700472 /* do_rtp */ false,
473 /* cha_devirtualize */ false)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100474 return false;
475 }
476
477 // We successfully inlined, now add a guard.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000478 AddTypeGuard(receiver,
479 cursor,
480 bb_cursor,
481 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000482 monomorphic_type,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000483 invoke_instruction,
484 /* with_deoptimization */ true);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100485
486 // Run type propagation to get the guard typed, and eventually propagate the
487 // type of the receiver.
Vladimir Marko456307a2016-04-19 14:12:13 +0000488 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Markobfb80d22017-02-14 14:08:12 +0000489 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +0000490 outer_compilation_unit_.GetDexCache(),
491 handles_,
492 /* is_first_run */ false);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100493 rtp_fixup.Run();
494
495 MaybeRecordStat(kInlinedMonomorphicCall);
496 return true;
497}
498
Mingyao Yang063fc772016-08-02 11:02:54 -0700499void HInliner::AddCHAGuard(HInstruction* invoke_instruction,
500 uint32_t dex_pc,
501 HInstruction* cursor,
502 HBasicBlock* bb_cursor) {
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800503 HShouldDeoptimizeFlag* deopt_flag = new (graph_->GetArena())
504 HShouldDeoptimizeFlag(graph_->GetArena(), dex_pc);
505 HInstruction* compare = new (graph_->GetArena()) HNotEqual(
Mingyao Yang063fc772016-08-02 11:02:54 -0700506 deopt_flag, graph_->GetIntConstant(0, dex_pc));
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800507 HInstruction* deopt = new (graph_->GetArena()) HDeoptimize(compare, dex_pc);
Mingyao Yang063fc772016-08-02 11:02:54 -0700508
509 if (cursor != nullptr) {
510 bb_cursor->InsertInstructionAfter(deopt_flag, cursor);
511 } else {
512 bb_cursor->InsertInstructionBefore(deopt_flag, bb_cursor->GetFirstInstruction());
513 }
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800514 bb_cursor->InsertInstructionAfter(compare, deopt_flag);
515 bb_cursor->InsertInstructionAfter(deopt, compare);
516
517 // Add receiver as input to aid CHA guard optimization later.
518 deopt_flag->AddInput(invoke_instruction->InputAt(0));
519 DCHECK_EQ(deopt_flag->InputCount(), 1u);
Mingyao Yang063fc772016-08-02 11:02:54 -0700520 deopt->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800521 outermost_graph_->IncrementNumberOfCHAGuards();
Mingyao Yang063fc772016-08-02 11:02:54 -0700522}
523
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000524HInstruction* HInliner::AddTypeGuard(HInstruction* receiver,
525 HInstruction* cursor,
526 HBasicBlock* bb_cursor,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800527 dex::TypeIndex class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000528 Handle<mirror::Class> klass,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000529 HInstruction* invoke_instruction,
530 bool with_deoptimization) {
531 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
532 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
533 class_linker, receiver, invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000534 if (cursor != nullptr) {
535 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
536 } else {
537 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
538 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000539
540 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000541 bool is_referrer = (klass.Get() == outermost_graph_->GetArtMethod()->GetDeclaringClass());
Nicolas Geoffray56876342016-12-16 16:09:08 +0000542 // Note that we will just compare the classes, so we don't need Java semantics access checks.
543 // Note that the type index and the dex file are relative to the method this type guard is
544 // inlined into.
545 HLoadClass* load_class = new (graph_->GetArena()) HLoadClass(graph_->GetCurrentMethod(),
546 class_index,
547 caller_dex_file,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000548 klass,
Nicolas Geoffray56876342016-12-16 16:09:08 +0000549 is_referrer,
550 invoke_instruction->GetDexPc(),
551 /* needs_access_check */ false);
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000552 HLoadClass::LoadKind kind = HSharpening::SharpenClass(
553 load_class, codegen_, compiler_driver_, caller_compilation_unit_);
554 DCHECK(kind != HLoadClass::LoadKind::kInvalid)
555 << "We should always be able to reference a class for inline caches";
556 // Insert before setting the kind, as setting the kind affects the inputs.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000557 bb_cursor->InsertInstructionAfter(load_class, receiver_class);
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000558 load_class->SetLoadKind(kind);
Nicolas Geoffray56876342016-12-16 16:09:08 +0000559
Nicolas Geoffray56876342016-12-16 16:09:08 +0000560 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(load_class, receiver_class);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000561 bb_cursor->InsertInstructionAfter(compare, load_class);
562 if (with_deoptimization) {
563 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
564 compare, invoke_instruction->GetDexPc());
565 bb_cursor->InsertInstructionAfter(deoptimize, compare);
566 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
567 }
568 return compare;
569}
570
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000571bool HInliner::TryInlinePolymorphicCall(HInvoke* invoke_instruction,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100572 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000573 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000574 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
575 << invoke_instruction->DebugName();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000576
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000577 if (TryInlinePolymorphicCallToSameTarget(invoke_instruction, resolved_method, classes)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000578 return true;
579 }
580
581 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700582 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000583
584 bool all_targets_inlined = true;
585 bool one_target_inlined = false;
586 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000587 if (classes->Get(i) == nullptr) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000588 break;
589 }
590 ArtMethod* method = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000591
592 Handle<mirror::Class> handle = handles_->NewHandle(classes->Get(i));
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000593 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000594 method = handle->FindVirtualMethodForInterface(resolved_method, pointer_size);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000595 } else {
596 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000597 method = handle->FindVirtualMethodForVirtual(resolved_method, pointer_size);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000598 }
599
600 HInstruction* receiver = invoke_instruction->InputAt(0);
601 HInstruction* cursor = invoke_instruction->GetPrevious();
602 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
603
Vladimir Markobfb80d22017-02-14 14:08:12 +0000604 dex::TypeIndex class_index = FindClassIndexIn(handle.Get(), caller_compilation_unit_);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000605 HInstruction* return_replacement = nullptr;
Andreas Gampea5b09a62016-11-17 15:21:22 -0800606 if (!class_index.IsValid() ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000607 !TryBuildAndInline(invoke_instruction,
608 method,
609 ReferenceTypeInfo::Create(handle, /* is_exact */ true),
610 &return_replacement)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000611 all_targets_inlined = false;
612 } else {
613 one_target_inlined = true;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000614
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000615 VLOG(compiler) << "Polymorphic call to " << ArtMethod::PrettyMethod(resolved_method)
616 << " has inlined " << ArtMethod::PrettyMethod(method);
617
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000618 // If we have inlined all targets before, and this receiver is the last seen,
619 // we deoptimize instead of keeping the original invoke instruction.
620 bool deoptimize = all_targets_inlined &&
621 (i != InlineCache::kIndividualCacheSize - 1) &&
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000622 (classes->Get(i + 1) == nullptr);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100623
624 if (outermost_graph_->IsCompilingOsr()) {
625 // We do not support HDeoptimize in OSR methods.
626 deoptimize = false;
627 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000628 HInstruction* compare = AddTypeGuard(receiver,
629 cursor,
630 bb_cursor,
631 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000632 handle,
Nicolas Geoffray56876342016-12-16 16:09:08 +0000633 invoke_instruction,
634 deoptimize);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000635 if (deoptimize) {
636 if (return_replacement != nullptr) {
637 invoke_instruction->ReplaceWith(return_replacement);
638 }
639 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
640 // Because the inline cache data can be populated concurrently, we force the end of the
641 // iteration. Otherhwise, we could see a new receiver type.
642 break;
643 } else {
644 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
645 }
646 }
647 }
648
649 if (!one_target_inlined) {
David Sehr709b0702016-10-13 09:12:37 -0700650 VLOG(compiler) << "Call to " << ArtMethod::PrettyMethod(resolved_method)
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000651 << " from inline cache is not inlined because none"
652 << " of its targets could be inlined";
653 return false;
654 }
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000655
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000656 MaybeRecordStat(kInlinedPolymorphicCall);
657
658 // Run type propagation to get the guards typed.
Vladimir Marko456307a2016-04-19 14:12:13 +0000659 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Markobfb80d22017-02-14 14:08:12 +0000660 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +0000661 outer_compilation_unit_.GetDexCache(),
662 handles_,
663 /* is_first_run */ false);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000664 rtp_fixup.Run();
665 return true;
666}
667
668void HInliner::CreateDiamondPatternForPolymorphicInline(HInstruction* compare,
669 HInstruction* return_replacement,
670 HInstruction* invoke_instruction) {
671 uint32_t dex_pc = invoke_instruction->GetDexPc();
672 HBasicBlock* cursor_block = compare->GetBlock();
673 HBasicBlock* original_invoke_block = invoke_instruction->GetBlock();
674 ArenaAllocator* allocator = graph_->GetArena();
675
676 // Spit the block after the compare: `cursor_block` will now be the start of the diamond,
677 // and the returned block is the start of the then branch (that could contain multiple blocks).
678 HBasicBlock* then = cursor_block->SplitAfterForInlining(compare);
679
680 // Split the block containing the invoke before and after the invoke. The returned block
681 // of the split before will contain the invoke and will be the otherwise branch of
682 // the diamond. The returned block of the split after will be the merge block
683 // of the diamond.
684 HBasicBlock* end_then = invoke_instruction->GetBlock();
685 HBasicBlock* otherwise = end_then->SplitBeforeForInlining(invoke_instruction);
686 HBasicBlock* merge = otherwise->SplitAfterForInlining(invoke_instruction);
687
688 // If the methods we are inlining return a value, we create a phi in the merge block
689 // that will have the `invoke_instruction and the `return_replacement` as inputs.
690 if (return_replacement != nullptr) {
691 HPhi* phi = new (allocator) HPhi(
692 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke_instruction->GetType()), dex_pc);
693 merge->AddPhi(phi);
694 invoke_instruction->ReplaceWith(phi);
695 phi->AddInput(return_replacement);
696 phi->AddInput(invoke_instruction);
697 }
698
699 // Add the control flow instructions.
700 otherwise->AddInstruction(new (allocator) HGoto(dex_pc));
701 end_then->AddInstruction(new (allocator) HGoto(dex_pc));
702 cursor_block->AddInstruction(new (allocator) HIf(compare, dex_pc));
703
704 // Add the newly created blocks to the graph.
705 graph_->AddBlock(then);
706 graph_->AddBlock(otherwise);
707 graph_->AddBlock(merge);
708
709 // Set up successor (and implictly predecessor) relations.
710 cursor_block->AddSuccessor(otherwise);
711 cursor_block->AddSuccessor(then);
712 end_then->AddSuccessor(merge);
713 otherwise->AddSuccessor(merge);
714
715 // Set up dominance information.
716 then->SetDominator(cursor_block);
717 cursor_block->AddDominatedBlock(then);
718 otherwise->SetDominator(cursor_block);
719 cursor_block->AddDominatedBlock(otherwise);
720 merge->SetDominator(cursor_block);
721 cursor_block->AddDominatedBlock(merge);
722
723 // Update the revert post order.
724 size_t index = IndexOfElement(graph_->reverse_post_order_, cursor_block);
725 MakeRoomFor(&graph_->reverse_post_order_, 1, index);
726 graph_->reverse_post_order_[++index] = then;
727 index = IndexOfElement(graph_->reverse_post_order_, end_then);
728 MakeRoomFor(&graph_->reverse_post_order_, 2, index);
729 graph_->reverse_post_order_[++index] = otherwise;
730 graph_->reverse_post_order_[++index] = merge;
731
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000732
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +0000733 graph_->UpdateLoopAndTryInformationOfNewBlock(
734 then, original_invoke_block, /* replace_if_back_edge */ false);
735 graph_->UpdateLoopAndTryInformationOfNewBlock(
736 otherwise, original_invoke_block, /* replace_if_back_edge */ false);
737
738 // In case the original invoke location was a back edge, we need to update
739 // the loop to now have the merge block as a back edge.
740 graph_->UpdateLoopAndTryInformationOfNewBlock(
741 merge, original_invoke_block, /* replace_if_back_edge */ true);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000742}
743
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000744bool HInliner::TryInlinePolymorphicCallToSameTarget(
745 HInvoke* invoke_instruction,
746 ArtMethod* resolved_method,
747 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000748 // This optimization only works under JIT for now.
Calin Juravleffc87072016-04-20 14:22:09 +0100749 DCHECK(Runtime::Current()->UseJitCompilation());
Roland Levillain2aba7cd2016-02-03 12:27:20 +0000750 if (graph_->GetInstructionSet() == kMips64) {
751 // TODO: Support HClassTableGet for mips64.
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000752 return false;
753 }
754 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700755 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000756
757 DCHECK(resolved_method != nullptr);
758 ArtMethod* actual_method = nullptr;
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000759 size_t method_index = invoke_instruction->IsInvokeVirtual()
760 ? invoke_instruction->AsInvokeVirtual()->GetVTableIndex()
761 : invoke_instruction->AsInvokeInterface()->GetImtIndex();
762
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000763 // Check whether we are actually calling the same method among
764 // the different types seen.
765 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000766 if (classes->Get(i) == nullptr) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000767 break;
768 }
769 ArtMethod* new_method = nullptr;
770 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000771 new_method = classes->Get(i)->GetImt(pointer_size)->Get(
Matthew Gharrity465ecc82016-07-19 21:32:52 +0000772 method_index, pointer_size);
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000773 if (new_method->IsRuntimeMethod()) {
774 // Bail out as soon as we see a conflict trampoline in one of the target's
775 // interface table.
776 return false;
777 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000778 } else {
779 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000780 new_method = classes->Get(i)->GetEmbeddedVTableEntry(method_index, pointer_size);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000781 }
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000782 DCHECK(new_method != nullptr);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000783 if (actual_method == nullptr) {
784 actual_method = new_method;
785 } else if (actual_method != new_method) {
786 // Different methods, bailout.
David Sehr709b0702016-10-13 09:12:37 -0700787 VLOG(compiler) << "Call to " << ArtMethod::PrettyMethod(resolved_method)
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000788 << " from inline cache is not inlined because it resolves"
789 << " to different methods";
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000790 return false;
791 }
792 }
793
794 HInstruction* receiver = invoke_instruction->InputAt(0);
795 HInstruction* cursor = invoke_instruction->GetPrevious();
796 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
797
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100798 HInstruction* return_replacement = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000799 if (!TryBuildAndInline(invoke_instruction,
800 actual_method,
801 ReferenceTypeInfo::CreateInvalid(),
802 &return_replacement)) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000803 return false;
804 }
805
806 // We successfully inlined, now add a guard.
807 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
808 class_linker, receiver, invoke_instruction->GetDexPc());
809
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000810 Primitive::Type type = Is64BitInstructionSet(graph_->GetInstructionSet())
811 ? Primitive::kPrimLong
812 : Primitive::kPrimInt;
813 HClassTableGet* class_table_get = new (graph_->GetArena()) HClassTableGet(
814 receiver_class,
815 type,
Vladimir Markoa1de9182016-02-25 11:37:38 +0000816 invoke_instruction->IsInvokeVirtual() ? HClassTableGet::TableKind::kVTable
817 : HClassTableGet::TableKind::kIMTable,
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000818 method_index,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000819 invoke_instruction->GetDexPc());
820
821 HConstant* constant;
822 if (type == Primitive::kPrimLong) {
823 constant = graph_->GetLongConstant(
824 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
825 } else {
826 constant = graph_->GetIntConstant(
827 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
828 }
829
830 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(class_table_get, constant);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000831 if (cursor != nullptr) {
832 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
833 } else {
834 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
835 }
836 bb_cursor->InsertInstructionAfter(class_table_get, receiver_class);
837 bb_cursor->InsertInstructionAfter(compare, class_table_get);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100838
839 if (outermost_graph_->IsCompilingOsr()) {
840 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
841 } else {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100842 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
843 compare, invoke_instruction->GetDexPc());
844 bb_cursor->InsertInstructionAfter(deoptimize, compare);
845 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
846 if (return_replacement != nullptr) {
847 invoke_instruction->ReplaceWith(return_replacement);
848 }
Nicolas Geoffray1be7cbd2016-04-29 13:56:01 +0100849 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100850 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000851
852 // Run type propagation to get the guard typed.
Vladimir Marko456307a2016-04-19 14:12:13 +0000853 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Markobfb80d22017-02-14 14:08:12 +0000854 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +0000855 outer_compilation_unit_.GetDexCache(),
856 handles_,
857 /* is_first_run */ false);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000858 rtp_fixup.Run();
859
860 MaybeRecordStat(kInlinedPolymorphicCall);
861
862 return true;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100863}
864
Mingyao Yang063fc772016-08-02 11:02:54 -0700865bool HInliner::TryInlineAndReplace(HInvoke* invoke_instruction,
866 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000867 ReferenceTypeInfo receiver_type,
Mingyao Yang063fc772016-08-02 11:02:54 -0700868 bool do_rtp,
869 bool cha_devirtualize) {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000870 HInstruction* return_replacement = nullptr;
Mingyao Yang063fc772016-08-02 11:02:54 -0700871 uint32_t dex_pc = invoke_instruction->GetDexPc();
872 HInstruction* cursor = invoke_instruction->GetPrevious();
873 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000874 if (!TryBuildAndInline(invoke_instruction, method, receiver_type, &return_replacement)) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000875 if (invoke_instruction->IsInvokeInterface()) {
876 // Turn an invoke-interface into an invoke-virtual. An invoke-virtual is always
877 // better than an invoke-interface because:
878 // 1) In the best case, the interface call has one more indirection (to fetch the IMT).
879 // 2) We will not go to the conflict trampoline with an invoke-virtual.
880 // TODO: Consider sharpening once it is not dependent on the compiler driver.
881 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100882 uint32_t dex_method_index = FindMethodIndexIn(
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000883 method, caller_dex_file, invoke_instruction->GetDexMethodIndex());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100884 if (dex_method_index == DexFile::kDexNoIndex) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000885 return false;
886 }
887 HInvokeVirtual* new_invoke = new (graph_->GetArena()) HInvokeVirtual(
888 graph_->GetArena(),
889 invoke_instruction->GetNumberOfArguments(),
890 invoke_instruction->GetType(),
891 invoke_instruction->GetDexPc(),
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100892 dex_method_index,
893 method,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000894 method->GetMethodIndex());
895 HInputsRef inputs = invoke_instruction->GetInputs();
896 for (size_t index = 0; index != inputs.size(); ++index) {
897 new_invoke->SetArgumentAt(index, inputs[index]);
898 }
899 invoke_instruction->GetBlock()->InsertInstructionBefore(new_invoke, invoke_instruction);
900 new_invoke->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
901 if (invoke_instruction->GetType() == Primitive::kPrimNot) {
902 new_invoke->SetReferenceTypeInfo(invoke_instruction->GetReferenceTypeInfo());
903 }
904 return_replacement = new_invoke;
905 } else {
906 // TODO: Consider sharpening an invoke virtual once it is not dependent on the
907 // compiler driver.
908 return false;
909 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000910 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700911 if (cha_devirtualize) {
912 AddCHAGuard(invoke_instruction, dex_pc, cursor, bb_cursor);
913 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000914 if (return_replacement != nullptr) {
915 invoke_instruction->ReplaceWith(return_replacement);
916 }
917 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
David Brazdil94ab38f2016-06-21 17:48:19 +0100918 FixUpReturnReferenceType(method, return_replacement);
919 if (do_rtp && ReturnTypeMoreSpecific(invoke_instruction, return_replacement)) {
920 // Actual return value has a more specific type than the method's declared
921 // return type. Run RTP again on the outer graph to propagate it.
922 ReferenceTypePropagation(graph_,
Vladimir Markobfb80d22017-02-14 14:08:12 +0000923 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +0100924 outer_compilation_unit_.GetDexCache(),
925 handles_,
926 /* is_first_run */ false).Run();
927 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000928 return true;
929}
930
931bool HInliner::TryBuildAndInline(HInvoke* invoke_instruction,
932 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000933 ReferenceTypeInfo receiver_type,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000934 HInstruction** return_replacement) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100935 if (method->IsProxyMethod()) {
David Sehr709b0702016-10-13 09:12:37 -0700936 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100937 << " is not inlined because of unimplemented inline support for proxy methods.";
938 return false;
939 }
940
Jeff Haodcdc85b2015-12-04 14:06:18 -0800941 // Check whether we're allowed to inline. The outermost compilation unit is the relevant
942 // dex file here (though the transitivity of an inline chain would allow checking the calller).
943 if (!compiler_driver_->MayInline(method->GetDexFile(),
944 outer_compilation_unit_.GetDexFile())) {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000945 if (TryPatternSubstitution(invoke_instruction, method, return_replacement)) {
David Sehr709b0702016-10-13 09:12:37 -0700946 VLOG(compiler) << "Successfully replaced pattern of invoke "
947 << method->PrettyMethod();
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000948 MaybeRecordStat(kReplacedInvokeWithSimplePattern);
949 return true;
950 }
David Sehr709b0702016-10-13 09:12:37 -0700951 VLOG(compiler) << "Won't inline " << method->PrettyMethod() << " in "
Jeff Haodcdc85b2015-12-04 14:06:18 -0800952 << outer_compilation_unit_.GetDexFile()->GetLocation() << " ("
953 << caller_compilation_unit_.GetDexFile()->GetLocation() << ") from "
954 << method->GetDexFile()->GetLocation();
955 return false;
956 }
957
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100958 bool same_dex_file = IsSameDexFile(*outer_compilation_unit_.GetDexFile(), *method->GetDexFile());
959
960 const DexFile::CodeItem* code_item = method->GetCodeItem();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000961
962 if (code_item == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700963 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000964 << " is not inlined because it is native";
965 return false;
966 }
967
Calin Juravleec748352015-07-29 13:52:12 +0100968 size_t inline_max_code_units = compiler_driver_->GetCompilerOptions().GetInlineMaxCodeUnits();
969 if (code_item->insns_size_in_code_units_ > inline_max_code_units) {
David Sehr709b0702016-10-13 09:12:37 -0700970 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000971 << " is too big to inline: "
972 << code_item->insns_size_in_code_units_
973 << " > "
974 << inline_max_code_units;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000975 return false;
976 }
977
978 if (code_item->tries_size_ != 0) {
David Sehr709b0702016-10-13 09:12:37 -0700979 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000980 << " is not inlined because of try block";
981 return false;
982 }
983
Nicolas Geoffray250a3782016-04-20 16:27:53 +0100984 if (!method->IsCompilable()) {
David Sehr709b0702016-10-13 09:12:37 -0700985 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffray250a3782016-04-20 16:27:53 +0100986 << " has soft failures un-handled by the compiler, so it cannot be inlined";
987 }
988
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100989 if (!method->GetDeclaringClass()->IsVerified()) {
990 uint16_t class_def_idx = method->GetDeclaringClass()->GetDexClassDefIndex();
Calin Juravleffc87072016-04-20 14:22:09 +0100991 if (Runtime::Current()->UseJitCompilation() ||
Nicolas Geoffray5b82d332016-02-18 14:22:32 +0000992 !compiler_driver_->IsMethodVerifiedWithoutFailures(
993 method->GetDexMethodIndex(), class_def_idx, *method->GetDexFile())) {
David Sehr709b0702016-10-13 09:12:37 -0700994 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffrayccc61972015-10-01 14:34:20 +0100995 << " couldn't be verified, so it cannot be inlined";
996 return false;
997 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000998 }
999
Roland Levillain4c0eb422015-04-24 16:43:49 +01001000 if (invoke_instruction->IsInvokeStaticOrDirect() &&
1001 invoke_instruction->AsInvokeStaticOrDirect()->IsStaticWithImplicitClinitCheck()) {
1002 // Case of a static method that cannot be inlined because it implicitly
1003 // requires an initialization check of its declaring class.
David Sehr709b0702016-10-13 09:12:37 -07001004 VLOG(compiler) << "Method " << method->PrettyMethod()
Roland Levillain4c0eb422015-04-24 16:43:49 +01001005 << " is not inlined because it is static and requires a clinit"
1006 << " check that cannot be emitted due to Dex cache limitations";
1007 return false;
1008 }
1009
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001010 if (!TryBuildAndInlineHelper(
1011 invoke_instruction, method, receiver_type, same_dex_file, return_replacement)) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001012 return false;
1013 }
1014
David Sehr709b0702016-10-13 09:12:37 -07001015 VLOG(compiler) << "Successfully inlined " << method->PrettyMethod();
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001016 MaybeRecordStat(kInlinedInvoke);
1017 return true;
1018}
1019
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001020static HInstruction* GetInvokeInputForArgVRegIndex(HInvoke* invoke_instruction,
1021 size_t arg_vreg_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001022 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001023 size_t input_index = 0;
1024 for (size_t i = 0; i < arg_vreg_index; ++i, ++input_index) {
1025 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
1026 if (Primitive::Is64BitType(invoke_instruction->InputAt(input_index)->GetType())) {
1027 ++i;
1028 DCHECK_NE(i, arg_vreg_index);
1029 }
1030 }
1031 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
1032 return invoke_instruction->InputAt(input_index);
1033}
1034
1035// Try to recognize known simple patterns and replace invoke call with appropriate instructions.
1036bool HInliner::TryPatternSubstitution(HInvoke* invoke_instruction,
1037 ArtMethod* resolved_method,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001038 HInstruction** return_replacement) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001039 InlineMethod inline_method;
1040 if (!InlineMethodAnalyser::AnalyseMethodCode(resolved_method, &inline_method)) {
1041 return false;
1042 }
1043
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001044 switch (inline_method.opcode) {
1045 case kInlineOpNop:
1046 DCHECK_EQ(invoke_instruction->GetType(), Primitive::kPrimVoid);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001047 *return_replacement = nullptr;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001048 break;
1049 case kInlineOpReturnArg:
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001050 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction,
1051 inline_method.d.return_data.arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001052 break;
1053 case kInlineOpNonWideConst:
1054 if (resolved_method->GetShorty()[0] == 'L') {
1055 DCHECK_EQ(inline_method.d.data, 0u);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001056 *return_replacement = graph_->GetNullConstant();
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001057 } else {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001058 *return_replacement = graph_->GetIntConstant(static_cast<int32_t>(inline_method.d.data));
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001059 }
1060 break;
1061 case kInlineOpIGet: {
1062 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1063 if (data.method_is_static || data.object_arg != 0u) {
1064 // TODO: Needs null check.
1065 return false;
1066 }
Vladimir Marko354efa62016-02-04 19:46:56 +00001067 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001068 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
Vladimir Marko354efa62016-02-04 19:46:56 +00001069 HInstanceFieldGet* iget = CreateInstanceFieldGet(dex_cache, data.field_idx, obj);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001070 DCHECK_EQ(iget->GetFieldOffset().Uint32Value(), data.field_offset);
1071 DCHECK_EQ(iget->IsVolatile() ? 1u : 0u, data.is_volatile);
1072 invoke_instruction->GetBlock()->InsertInstructionBefore(iget, invoke_instruction);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001073 *return_replacement = iget;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001074 break;
1075 }
1076 case kInlineOpIPut: {
1077 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1078 if (data.method_is_static || data.object_arg != 0u) {
1079 // TODO: Needs null check.
1080 return false;
1081 }
Vladimir Marko354efa62016-02-04 19:46:56 +00001082 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001083 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
1084 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, data.src_arg);
Vladimir Marko354efa62016-02-04 19:46:56 +00001085 HInstanceFieldSet* iput = CreateInstanceFieldSet(dex_cache, data.field_idx, obj, value);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001086 DCHECK_EQ(iput->GetFieldOffset().Uint32Value(), data.field_offset);
1087 DCHECK_EQ(iput->IsVolatile() ? 1u : 0u, data.is_volatile);
1088 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1089 if (data.return_arg_plus1 != 0u) {
1090 size_t return_arg = data.return_arg_plus1 - 1u;
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001091 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction, return_arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001092 }
1093 break;
1094 }
Vladimir Marko354efa62016-02-04 19:46:56 +00001095 case kInlineOpConstructor: {
1096 const InlineConstructorData& data = inline_method.d.constructor_data;
1097 // Get the indexes to arrays for easier processing.
1098 uint16_t iput_field_indexes[] = {
1099 data.iput0_field_index, data.iput1_field_index, data.iput2_field_index
1100 };
1101 uint16_t iput_args[] = { data.iput0_arg, data.iput1_arg, data.iput2_arg };
1102 static_assert(arraysize(iput_args) == arraysize(iput_field_indexes), "Size mismatch");
1103 // Count valid field indexes.
1104 size_t number_of_iputs = 0u;
1105 while (number_of_iputs != arraysize(iput_field_indexes) &&
1106 iput_field_indexes[number_of_iputs] != DexFile::kDexNoIndex16) {
1107 // Check that there are no duplicate valid field indexes.
1108 DCHECK_EQ(0, std::count(iput_field_indexes + number_of_iputs + 1,
1109 iput_field_indexes + arraysize(iput_field_indexes),
1110 iput_field_indexes[number_of_iputs]));
1111 ++number_of_iputs;
1112 }
1113 // Check that there are no valid field indexes in the rest of the array.
1114 DCHECK_EQ(0, std::count_if(iput_field_indexes + number_of_iputs,
1115 iput_field_indexes + arraysize(iput_field_indexes),
1116 [](uint16_t index) { return index != DexFile::kDexNoIndex16; }));
1117
1118 // Create HInstanceFieldSet for each IPUT that stores non-zero data.
1119 Handle<mirror::DexCache> dex_cache;
1120 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, /* this */ 0u);
1121 bool needs_constructor_barrier = false;
1122 for (size_t i = 0; i != number_of_iputs; ++i) {
1123 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, iput_args[i]);
Roland Levillain1a653882016-03-18 18:05:57 +00001124 if (!value->IsConstant() || !value->AsConstant()->IsZeroBitPattern()) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001125 if (dex_cache.GetReference() == nullptr) {
1126 dex_cache = handles_->NewHandle(resolved_method->GetDexCache());
1127 }
1128 uint16_t field_index = iput_field_indexes[i];
1129 HInstanceFieldSet* iput = CreateInstanceFieldSet(dex_cache, field_index, obj, value);
1130 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1131
1132 // Check whether the field is final. If it is, we need to add a barrier.
Andreas Gampe542451c2016-07-26 09:02:02 -07001133 PointerSize pointer_size = InstructionSetPointerSize(codegen_->GetInstructionSet());
Vladimir Marko354efa62016-02-04 19:46:56 +00001134 ArtField* resolved_field = dex_cache->GetResolvedField(field_index, pointer_size);
1135 DCHECK(resolved_field != nullptr);
1136 if (resolved_field->IsFinal()) {
1137 needs_constructor_barrier = true;
1138 }
1139 }
1140 }
1141 if (needs_constructor_barrier) {
1142 HMemoryBarrier* barrier = new (graph_->GetArena()) HMemoryBarrier(kStoreStore, kNoDexPc);
1143 invoke_instruction->GetBlock()->InsertInstructionBefore(barrier, invoke_instruction);
1144 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001145 *return_replacement = nullptr;
Vladimir Marko354efa62016-02-04 19:46:56 +00001146 break;
1147 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001148 default:
1149 LOG(FATAL) << "UNREACHABLE";
1150 UNREACHABLE();
1151 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001152 return true;
1153}
1154
Vladimir Marko354efa62016-02-04 19:46:56 +00001155HInstanceFieldGet* HInliner::CreateInstanceFieldGet(Handle<mirror::DexCache> dex_cache,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001156 uint32_t field_index,
1157 HInstruction* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001158 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001159 PointerSize pointer_size = InstructionSetPointerSize(codegen_->GetInstructionSet());
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001160 ArtField* resolved_field = dex_cache->GetResolvedField(field_index, pointer_size);
1161 DCHECK(resolved_field != nullptr);
1162 HInstanceFieldGet* iget = new (graph_->GetArena()) HInstanceFieldGet(
1163 obj,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001164 resolved_field,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001165 resolved_field->GetTypeAsPrimitiveType(),
1166 resolved_field->GetOffset(),
1167 resolved_field->IsVolatile(),
1168 field_index,
1169 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Marko354efa62016-02-04 19:46:56 +00001170 *dex_cache->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001171 // Read barrier generates a runtime call in slow path and we need a valid
1172 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1173 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001174 if (iget->GetType() == Primitive::kPrimNot) {
Vladimir Marko456307a2016-04-19 14:12:13 +00001175 // Use the same dex_cache that we used for field lookup as the hint_dex_cache.
Vladimir Markobfb80d22017-02-14 14:08:12 +00001176 ReferenceTypePropagation rtp(graph_,
1177 outer_compilation_unit_.GetClassLoader(),
1178 dex_cache,
1179 handles_,
1180 /* 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(
Vladimir Markobfb80d22017-02-14 14:08:12 +00001226 class_loader,
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
Vladimir Marko438709f2017-02-23 18:56:13 +00001275 // When they are needed, allocate `inline_stats_` on the Arena instead
Roland Levillaina8013fd2016-04-04 15:34:31 +01001276 // 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.
Vladimir Marko438709f2017-02-23 18:56:13 +00001279 if (stats_ != nullptr) {
1280 // Reuse one object for all inline attempts from this caller to keep Arena memory usage low.
1281 if (inline_stats_ == nullptr) {
1282 void* storage = graph_->GetArena()->Alloc<OptimizingCompilerStats>(kArenaAllocMisc);
1283 inline_stats_ = new (storage) OptimizingCompilerStats;
1284 } else {
1285 inline_stats_->Reset();
1286 }
1287 }
David Brazdil5e8b1372015-01-23 14:39:08 +00001288 HGraphBuilder builder(callee_graph,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001289 &dex_compilation_unit,
1290 &outer_compilation_unit_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001291 resolved_method->GetDexFile(),
David Brazdil86ea7ee2016-02-16 09:26:07 +00001292 *code_item,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001293 compiler_driver_,
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00001294 codegen_,
Vladimir Marko438709f2017-02-23 18:56:13 +00001295 inline_stats_,
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001296 resolved_method->GetQuickenedInfo(class_linker->GetImagePointerSize()),
David Brazdildee58d62016-04-07 09:54:26 +00001297 dex_cache,
1298 handles_);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001299
David Brazdildee58d62016-04-07 09:54:26 +00001300 if (builder.BuildGraph() != kAnalysisSuccess) {
David Sehr709b0702016-10-13 09:12:37 -07001301 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001302 << " could not be built, so cannot be inlined";
1303 return false;
1304 }
1305
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001306 if (!RegisterAllocator::CanAllocateRegistersFor(*callee_graph,
1307 compiler_driver_->GetInstructionSet())) {
David Sehr709b0702016-10-13 09:12:37 -07001308 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001309 << " cannot be inlined because of the register allocator";
1310 return false;
1311 }
1312
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001313 size_t parameter_index = 0;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001314 bool run_rtp = false;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001315 for (HInstructionIterator instructions(callee_graph->GetEntryBlock()->GetInstructions());
1316 !instructions.Done();
1317 instructions.Advance()) {
1318 HInstruction* current = instructions.Current();
1319 if (current->IsParameterValue()) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001320 HInstruction* argument = invoke_instruction->InputAt(parameter_index);
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001321 if (argument->IsNullConstant()) {
1322 current->ReplaceWith(callee_graph->GetNullConstant());
1323 } else if (argument->IsIntConstant()) {
1324 current->ReplaceWith(callee_graph->GetIntConstant(argument->AsIntConstant()->GetValue()));
1325 } else if (argument->IsLongConstant()) {
1326 current->ReplaceWith(callee_graph->GetLongConstant(argument->AsLongConstant()->GetValue()));
1327 } else if (argument->IsFloatConstant()) {
1328 current->ReplaceWith(
1329 callee_graph->GetFloatConstant(argument->AsFloatConstant()->GetValue()));
1330 } else if (argument->IsDoubleConstant()) {
1331 current->ReplaceWith(
1332 callee_graph->GetDoubleConstant(argument->AsDoubleConstant()->GetValue()));
1333 } else if (argument->GetType() == Primitive::kPrimNot) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001334 if (!resolved_method->IsStatic() && parameter_index == 0 && receiver_type.IsValid()) {
1335 run_rtp = true;
1336 current->SetReferenceTypeInfo(receiver_type);
1337 } else {
1338 current->SetReferenceTypeInfo(argument->GetReferenceTypeInfo());
1339 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001340 current->AsParameterValue()->SetCanBeNull(argument->CanBeNull());
1341 }
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001342 ++parameter_index;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001343 }
1344 }
1345
David Brazdil94ab38f2016-06-21 17:48:19 +01001346 // We have replaced formal arguments with actual arguments. If actual types
1347 // are more specific than the declared ones, run RTP again on the inner graph.
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001348 if (run_rtp || ArgumentTypesMoreSpecific(invoke_instruction, resolved_method)) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001349 ReferenceTypePropagation(callee_graph,
Vladimir Markobfb80d22017-02-14 14:08:12 +00001350 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +01001351 dex_compilation_unit.GetDexCache(),
1352 handles_,
1353 /* is_first_run */ false).Run();
1354 }
1355
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001356 size_t number_of_instructions_budget = kMaximumNumberOfHInstructions;
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001357 size_t number_of_inlined_instructions =
1358 RunOptimizations(callee_graph, code_item, dex_compilation_unit);
1359 number_of_instructions_budget += number_of_inlined_instructions;
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +00001360
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001361 HBasicBlock* exit_block = callee_graph->GetExitBlock();
1362 if (exit_block == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07001363 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001364 << " could not be inlined because it has an infinite loop";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001365 return false;
1366 }
1367
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001368 bool has_one_return = false;
Vladimir Marko60584552015-09-03 13:35:12 +00001369 for (HBasicBlock* predecessor : exit_block->GetPredecessors()) {
1370 if (predecessor->GetLastInstruction()->IsThrow()) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001371 if (invoke_instruction->GetBlock()->IsTryBlock()) {
1372 // TODO(ngeoffray): Support adding HTryBoundary in Hgraph::InlineInto.
1373 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1374 << " could not be inlined because one branch always throws and"
1375 << " caller is in a try/catch block";
1376 return false;
1377 } else if (graph_->GetExitBlock() == nullptr) {
1378 // TODO(ngeoffray): Support adding HExit in the caller graph.
1379 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1380 << " could not be inlined because one branch always throws and"
1381 << " caller does not have an exit block";
1382 return false;
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00001383 } else if (graph_->HasIrreducibleLoops()) {
1384 // TODO(ngeoffray): Support re-computing loop information to graphs with
1385 // irreducible loops?
1386 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1387 << " could not be inlined because one branch always throws and"
1388 << " caller has irreducible loops";
1389 return false;
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001390 }
1391 } else {
1392 has_one_return = true;
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001393 }
1394 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001395
1396 if (!has_one_return) {
David Sehr709b0702016-10-13 09:12:37 -07001397 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001398 << " could not be inlined because it always throws";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001399 return false;
1400 }
1401
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001402 size_t number_of_instructions = 0;
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001403
1404 bool can_inline_environment =
1405 total_number_of_dex_registers_ < kMaximumNumberOfCumulatedDexRegisters;
1406
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001407 // Skip the entry block, it does not contain instructions that prevent inlining.
1408 for (HBasicBlock* block : callee_graph->GetReversePostOrderSkipEntryBlock()) {
David Sehrc757dec2016-11-04 15:48:34 -07001409 if (block->IsLoopHeader()) {
1410 if (block->GetLoopInformation()->IsIrreducible()) {
1411 // Don't inline methods with irreducible loops, they could prevent some
1412 // optimizations to run.
1413 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1414 << " could not be inlined because it contains an irreducible loop";
1415 return false;
1416 }
1417 if (!block->GetLoopInformation()->HasExitEdge()) {
1418 // Don't inline methods with loops without exit, since they cause the
1419 // loop information to be computed incorrectly when updating after
1420 // inlining.
1421 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1422 << " could not be inlined because it contains a loop with no exit";
1423 return false;
1424 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001425 }
1426
1427 for (HInstructionIterator instr_it(block->GetInstructions());
1428 !instr_it.Done();
1429 instr_it.Advance()) {
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001430 if (number_of_instructions++ == number_of_instructions_budget) {
David Sehr709b0702016-10-13 09:12:37 -07001431 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001432 << " is not inlined because its caller has reached"
1433 << " its instruction budget limit.";
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001434 return false;
1435 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001436 HInstruction* current = instr_it.Current();
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001437 if (!can_inline_environment && current->NeedsEnvironment()) {
David Sehr709b0702016-10-13 09:12:37 -07001438 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001439 << " is not inlined because its caller has reached"
1440 << " its environment budget limit.";
1441 return false;
1442 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001443
Nicolas Geoffrayfbdfa6d2017-02-03 10:43:13 +00001444 if (current->NeedsEnvironment() &&
1445 !CanEncodeInlinedMethodInStackMap(*caller_compilation_unit_.GetDexFile(),
1446 resolved_method)) {
David Sehr709b0702016-10-13 09:12:37 -07001447 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001448 << " could not be inlined because " << current->DebugName()
Nicolas Geoffrayfbdfa6d2017-02-03 10:43:13 +00001449 << " needs an environment, is in a different dex file"
1450 << ", and cannot be encoded in the stack maps.";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001451 return false;
1452 }
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001453
Vladimir Markodc151b22015-10-15 18:02:30 +01001454 if (!same_dex_file && current->NeedsDexCacheOfDeclaringClass()) {
David Sehr709b0702016-10-13 09:12:37 -07001455 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001456 << " could not be inlined because " << current->DebugName()
1457 << " it is in a different dex file and requires access to the dex cache";
1458 return false;
1459 }
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001460
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001461 if (current->IsUnresolvedStaticFieldGet() ||
1462 current->IsUnresolvedInstanceFieldGet() ||
1463 current->IsUnresolvedStaticFieldSet() ||
1464 current->IsUnresolvedInstanceFieldSet()) {
1465 // Entrypoint for unresolved fields does not handle inlined frames.
David Sehr709b0702016-10-13 09:12:37 -07001466 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001467 << " could not be inlined because it is using an unresolved"
1468 << " entrypoint";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001469 return false;
1470 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001471 }
1472 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001473 number_of_inlined_instructions_ += number_of_instructions;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001474
David Brazdil3f523062016-02-29 16:53:33 +00001475 DCHECK_EQ(caller_instruction_counter, graph_->GetCurrentInstructionId())
1476 << "No instructions can be added to the outer graph while inner graph is being built";
1477
1478 const int32_t callee_instruction_counter = callee_graph->GetCurrentInstructionId();
1479 graph_->SetCurrentInstructionId(callee_instruction_counter);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001480 *return_replacement = callee_graph->InlineInto(graph_, invoke_instruction);
David Brazdil3f523062016-02-29 16:53:33 +00001481
1482 DCHECK_EQ(callee_instruction_counter, callee_graph->GetCurrentInstructionId())
1483 << "No instructions can be added to the inner graph during inlining into the outer graph";
1484
Vladimir Marko438709f2017-02-23 18:56:13 +00001485 if (stats_ != nullptr) {
1486 DCHECK(inline_stats_ != nullptr);
1487 inline_stats_->AddTo(stats_);
1488 }
1489
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001490 return true;
1491}
Calin Juravle2e768302015-07-28 14:41:11 +00001492
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001493size_t HInliner::RunOptimizations(HGraph* callee_graph,
1494 const DexFile::CodeItem* code_item,
1495 const DexCompilationUnit& dex_compilation_unit) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001496 // Note: if the outermost_graph_ is being compiled OSR, we should not run any
1497 // optimization that could lead to a HDeoptimize. The following optimizations do not.
Vladimir Marko438709f2017-02-23 18:56:13 +00001498 HDeadCodeElimination dce(callee_graph, inline_stats_, "dead_code_elimination$inliner");
Andreas Gampeca620d72016-11-08 08:09:33 -08001499 HConstantFolding fold(callee_graph, "constant_folding$inliner");
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001500 HSharpening sharpening(callee_graph, codegen_, dex_compilation_unit, compiler_driver_, handles_);
Vladimir Marko438709f2017-02-23 18:56:13 +00001501 InstructionSimplifier simplify(callee_graph, inline_stats_);
1502 IntrinsicsRecognizer intrinsics(callee_graph, inline_stats_);
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001503
1504 HOptimization* optimizations[] = {
1505 &intrinsics,
1506 &sharpening,
1507 &simplify,
1508 &fold,
1509 &dce,
1510 };
1511
1512 for (size_t i = 0; i < arraysize(optimizations); ++i) {
1513 HOptimization* optimization = optimizations[i];
1514 optimization->Run();
1515 }
1516
1517 size_t number_of_inlined_instructions = 0u;
1518 if (depth_ + 1 < compiler_driver_->GetCompilerOptions().GetInlineDepthLimit()) {
1519 HInliner inliner(callee_graph,
1520 outermost_graph_,
1521 codegen_,
1522 outer_compilation_unit_,
1523 dex_compilation_unit,
1524 compiler_driver_,
1525 handles_,
Vladimir Marko438709f2017-02-23 18:56:13 +00001526 inline_stats_,
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001527 total_number_of_dex_registers_ + code_item->registers_size_,
1528 depth_ + 1);
1529 inliner.Run();
1530 number_of_inlined_instructions += inliner.number_of_inlined_instructions_;
1531 }
1532
1533 return number_of_inlined_instructions;
1534}
1535
David Brazdil94ab38f2016-06-21 17:48:19 +01001536static bool IsReferenceTypeRefinement(ReferenceTypeInfo declared_rti,
1537 bool declared_can_be_null,
1538 HInstruction* actual_obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001539 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001540 if (declared_can_be_null && !actual_obj->CanBeNull()) {
1541 return true;
1542 }
1543
1544 ReferenceTypeInfo actual_rti = actual_obj->GetReferenceTypeInfo();
1545 return (actual_rti.IsExact() && !declared_rti.IsExact()) ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001546 declared_rti.IsStrictSupertypeOf(actual_rti);
David Brazdil94ab38f2016-06-21 17:48:19 +01001547}
1548
1549ReferenceTypeInfo HInliner::GetClassRTI(mirror::Class* klass) {
1550 return ReferenceTypePropagation::IsAdmissible(klass)
1551 ? ReferenceTypeInfo::Create(handles_->NewHandle(klass))
1552 : graph_->GetInexactObjectRti();
1553}
1554
1555bool HInliner::ArgumentTypesMoreSpecific(HInvoke* invoke_instruction, ArtMethod* resolved_method) {
1556 // If this is an instance call, test whether the type of the `this` argument
1557 // is more specific than the class which declares the method.
1558 if (!resolved_method->IsStatic()) {
1559 if (IsReferenceTypeRefinement(GetClassRTI(resolved_method->GetDeclaringClass()),
1560 /* declared_can_be_null */ false,
1561 invoke_instruction->InputAt(0u))) {
1562 return true;
1563 }
1564 }
1565
David Brazdil94ab38f2016-06-21 17:48:19 +01001566 // Iterate over the list of parameter types and test whether any of the
1567 // actual inputs has a more specific reference type than the type declared in
1568 // the signature.
1569 const DexFile::TypeList* param_list = resolved_method->GetParameterTypeList();
1570 for (size_t param_idx = 0,
1571 input_idx = resolved_method->IsStatic() ? 0 : 1,
1572 e = (param_list == nullptr ? 0 : param_list->Size());
1573 param_idx < e;
1574 ++param_idx, ++input_idx) {
1575 HInstruction* input = invoke_instruction->InputAt(input_idx);
1576 if (input->GetType() == Primitive::kPrimNot) {
Vladimir Marko942fd312017-01-16 20:52:19 +00001577 mirror::Class* param_cls = resolved_method->GetClassFromTypeIndex(
David Brazdil94ab38f2016-06-21 17:48:19 +01001578 param_list->GetTypeItem(param_idx).type_idx_,
Vladimir Marko942fd312017-01-16 20:52:19 +00001579 /* resolve */ false);
David Brazdil94ab38f2016-06-21 17:48:19 +01001580 if (IsReferenceTypeRefinement(GetClassRTI(param_cls),
1581 /* declared_can_be_null */ true,
1582 input)) {
1583 return true;
1584 }
1585 }
1586 }
1587
1588 return false;
1589}
1590
1591bool HInliner::ReturnTypeMoreSpecific(HInvoke* invoke_instruction,
1592 HInstruction* return_replacement) {
Alex Light68289a52015-12-15 17:30:30 -08001593 // Check the integrity of reference types and run another type propagation if needed.
David Brazdil4833f5a2015-12-16 10:37:39 +00001594 if (return_replacement != nullptr) {
1595 if (return_replacement->GetType() == Primitive::kPrimNot) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001596 // Test if the return type is a refinement of the declared return type.
1597 if (IsReferenceTypeRefinement(invoke_instruction->GetReferenceTypeInfo(),
1598 /* declared_can_be_null */ true,
1599 return_replacement)) {
1600 return true;
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001601 } else if (return_replacement->IsInstanceFieldGet()) {
1602 HInstanceFieldGet* field_get = return_replacement->AsInstanceFieldGet();
1603 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1604 if (field_get->GetFieldInfo().GetField() ==
1605 class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0)) {
1606 return true;
1607 }
David Brazdil94ab38f2016-06-21 17:48:19 +01001608 }
1609 } else if (return_replacement->IsInstanceOf()) {
1610 // Inlining InstanceOf into an If may put a tighter bound on reference types.
1611 return true;
1612 }
1613 }
1614
1615 return false;
1616}
1617
1618void HInliner::FixUpReturnReferenceType(ArtMethod* resolved_method,
1619 HInstruction* return_replacement) {
1620 if (return_replacement != nullptr) {
1621 if (return_replacement->GetType() == Primitive::kPrimNot) {
David Brazdil4833f5a2015-12-16 10:37:39 +00001622 if (!return_replacement->GetReferenceTypeInfo().IsValid()) {
1623 // Make sure that we have a valid type for the return. We may get an invalid one when
1624 // we inline invokes with multiple branches and create a Phi for the result.
1625 // TODO: we could be more precise by merging the phi inputs but that requires
1626 // some functionality from the reference type propagation.
1627 DCHECK(return_replacement->IsPhi());
Vladimir Marko942fd312017-01-16 20:52:19 +00001628 mirror::Class* cls = resolved_method->GetReturnType(false /* resolve */);
David Brazdil94ab38f2016-06-21 17:48:19 +01001629 return_replacement->SetReferenceTypeInfo(GetClassRTI(cls));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001630 }
Calin Juravlecdfed3d2015-10-26 14:05:01 +00001631 }
Calin Juravle2e768302015-07-28 14:41:11 +00001632 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001633}
1634
1635} // namespace art