blob: 790751fd74bd3e5bb31fcfa50229f5be44e1f2f1 [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"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000020#include "builder.h"
21#include "class_linker.h"
22#include "constant_folding.h"
23#include "dead_code_elimination.h"
Vladimir Markobe10e8e2016-01-22 12:09:44 +000024#include "dex/verified_method.h"
25#include "dex/verification_results.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000026#include "driver/compiler_driver-inl.h"
Calin Juravleec748352015-07-29 13:52:12 +010027#include "driver/compiler_options.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000028#include "driver/dex_compilation_unit.h"
29#include "instruction_simplifier.h"
Scott Wakelingd60a1af2015-07-22 14:32:44 +010030#include "intrinsics.h"
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +000031#include "jit/jit.h"
32#include "jit/jit_code_cache.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000033#include "mirror/class_loader.h"
34#include "mirror/dex_cache.h"
35#include "nodes.h"
Nicolas Geoffray335005e2015-06-25 10:01:47 +010036#include "optimizing_compiler.h"
Nicolas Geoffray454a4812015-06-09 10:37:32 +010037#include "reference_type_propagation.h"
Matthew Gharritye9288852016-07-14 14:08:16 -070038#include "register_allocator_linear_scan.h"
Vladimir Markobe10e8e2016-01-22 12:09:44 +000039#include "quick/inline_method_analyser.h"
Vladimir Markodc151b22015-10-15 18:02:30 +010040#include "sharpening.h"
David Brazdil4833f5a2015-12-16 10:37:39 +000041#include "ssa_builder.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000042#include "ssa_phi_elimination.h"
43#include "scoped_thread_state_change.h"
44#include "thread.h"
45
46namespace art {
47
Nicolas Geoffray5949fa02015-12-18 10:57:10 +000048static constexpr size_t kMaximumNumberOfHInstructions = 32;
49
50// Limit the number of dex registers that we accumulate while inlining
51// to avoid creating large amount of nested environments.
52static constexpr size_t kMaximumNumberOfCumulatedDexRegisters = 64;
53
54// Avoid inlining within a huge method due to memory pressure.
55static constexpr size_t kMaximumCodeUnitSize = 4096;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -070056
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000057void HInliner::Run() {
Calin Juravle8f96df82015-07-29 15:58:48 +010058 const CompilerOptions& compiler_options = compiler_driver_->GetCompilerOptions();
59 if ((compiler_options.GetInlineDepthLimit() == 0)
60 || (compiler_options.GetInlineMaxCodeUnits() == 0)) {
61 return;
62 }
Nicolas Geoffray5949fa02015-12-18 10:57:10 +000063 if (caller_compilation_unit_.GetCodeItem()->insns_size_in_code_units_ > kMaximumCodeUnitSize) {
64 return;
65 }
Nicolas Geoffraye50b8d22015-03-13 08:57:42 +000066 if (graph_->IsDebuggable()) {
67 // For simplicity, we currently never inline when the graph is debuggable. This avoids
68 // doing some logic in the runtime to discover if a method could have been inlined.
69 return;
70 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +010071 const ArenaVector<HBasicBlock*>& blocks = graph_->GetReversePostOrder();
72 DCHECK(!blocks.empty());
73 HBasicBlock* next_block = blocks[0];
74 for (size_t i = 0; i < blocks.size(); ++i) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +010075 // Because we are changing the graph when inlining, we need to remember the next block.
76 // This avoids doing the inlining work again on the inlined blocks.
Vladimir Markofa6b93c2015-09-15 10:15:55 +010077 if (blocks[i] != next_block) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +010078 continue;
79 }
80 HBasicBlock* block = next_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +010081 next_block = (i == blocks.size() - 1) ? nullptr : blocks[i + 1];
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +000082 for (HInstruction* instruction = block->GetFirstInstruction(); instruction != nullptr;) {
83 HInstruction* next = instruction->GetNext();
Nicolas Geoffray454a4812015-06-09 10:37:32 +010084 HInvoke* call = instruction->AsInvoke();
Razvan A Lupusoru3e90a962015-03-27 13:44:44 -070085 // As long as the call is not intrinsified, it is worth trying to inline.
86 if (call != nullptr && call->GetIntrinsic() == Intrinsics::kNone) {
Nicolas Geoffray79041292015-03-26 10:05:54 +000087 // We use the original invoke type to ensure the resolution of the called method
88 // works properly.
Vladimir Marko58155012015-08-19 12:49:41 +000089 if (!TryInline(call)) {
Nicolas Geoffray335005e2015-06-25 10:01:47 +010090 if (kIsDebugBuild && IsCompilingWithCoreImage()) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000091 std::string callee_name =
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +000092 PrettyMethod(call->GetDexMethodIndex(), *outer_compilation_unit_.GetDexFile());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000093 bool should_inline = callee_name.find("$inline$") != std::string::npos;
94 CHECK(!should_inline) << "Could not inline " << callee_name;
95 }
Guillaume "Vermeille" Sancheze918d382015-06-03 15:32:41 +010096 } else {
Nicolas Geoffray335005e2015-06-25 10:01:47 +010097 if (kIsDebugBuild && IsCompilingWithCoreImage()) {
Guillaume "Vermeille" Sancheze918d382015-06-03 15:32:41 +010098 std::string callee_name =
99 PrettyMethod(call->GetDexMethodIndex(), *outer_compilation_unit_.GetDexFile());
100 bool must_not_inline = callee_name.find("$noinline$") != std::string::npos;
101 CHECK(!must_not_inline) << "Should not have inlined " << callee_name;
102 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000103 }
104 }
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000105 instruction = next;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000106 }
107 }
108}
109
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100110static bool IsMethodOrDeclaringClassFinal(ArtMethod* method)
Mathieu Chartier90443472015-07-16 20:32:27 -0700111 SHARED_REQUIRES(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100112 return method->IsFinal() || method->GetDeclaringClass()->IsFinal();
113}
114
115/**
116 * Given the `resolved_method` looked up in the dex cache, try to find
117 * the actual runtime target of an interface or virtual call.
118 * Return nullptr if the runtime target cannot be proven.
119 */
120static ArtMethod* FindVirtualOrInterfaceTarget(HInvoke* invoke, ArtMethod* resolved_method)
Mathieu Chartier90443472015-07-16 20:32:27 -0700121 SHARED_REQUIRES(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100122 if (IsMethodOrDeclaringClassFinal(resolved_method)) {
123 // No need to lookup further, the resolved method will be the target.
124 return resolved_method;
125 }
126
127 HInstruction* receiver = invoke->InputAt(0);
128 if (receiver->IsNullCheck()) {
129 // Due to multiple levels of inlining within the same pass, it might be that
130 // null check does not have the reference type of the actual receiver.
131 receiver = receiver->InputAt(0);
132 }
133 ReferenceTypeInfo info = receiver->GetReferenceTypeInfo();
Calin Juravle2e768302015-07-28 14:41:11 +0000134 DCHECK(info.IsValid()) << "Invalid RTI for " << receiver->DebugName();
135 if (!info.IsExact()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100136 // We currently only support inlining with known receivers.
137 // TODO: Remove this check, we should be able to inline final methods
138 // on unknown receivers.
139 return nullptr;
140 } else if (info.GetTypeHandle()->IsInterface()) {
141 // Statically knowing that the receiver has an interface type cannot
142 // help us find what is the target method.
143 return nullptr;
144 } else if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(info.GetTypeHandle().Get())) {
145 // The method that we're trying to call is not in the receiver's class or super classes.
146 return nullptr;
Nicolas Geoffrayab5327d2016-03-18 11:36:20 +0000147 } else if (info.GetTypeHandle()->IsErroneous()) {
148 // If the type is erroneous, do not go further, as we are going to query the vtable or
149 // imt table, that we can only safely do on non-erroneous classes.
150 return nullptr;
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100151 }
152
153 ClassLinker* cl = Runtime::Current()->GetClassLinker();
154 size_t pointer_size = cl->GetImagePointerSize();
155 if (invoke->IsInvokeInterface()) {
156 resolved_method = info.GetTypeHandle()->FindVirtualMethodForInterface(
157 resolved_method, pointer_size);
158 } else {
159 DCHECK(invoke->IsInvokeVirtual());
160 resolved_method = info.GetTypeHandle()->FindVirtualMethodForVirtual(
161 resolved_method, pointer_size);
162 }
163
164 if (resolved_method == nullptr) {
165 // 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;
Alex Light9139e002015-10-09 15:59:48 -0700169 } else if (!resolved_method->IsInvokable()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100170 // The information we had on the receiver was not enough to find
171 // the target method. Since we check above the exact type of the receiver,
172 // the only reason this can happen is an IncompatibleClassChangeError.
173 return nullptr;
174 } else if (IsMethodOrDeclaringClassFinal(resolved_method)) {
175 // A final method has to be the target method.
176 return resolved_method;
177 } else if (info.IsExact()) {
178 // If we found a method and the receiver's concrete type is statically
179 // known, we know for sure the target.
180 return resolved_method;
181 } else {
182 // Even if we did find a method, the receiver type was not enough to
183 // statically find the runtime target.
184 return nullptr;
185 }
186}
187
188static uint32_t FindMethodIndexIn(ArtMethod* method,
189 const DexFile& dex_file,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000190 uint32_t name_and_signature_index)
Mathieu Chartier90443472015-07-16 20:32:27 -0700191 SHARED_REQUIRES(Locks::mutator_lock_) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100192 if (IsSameDexFile(*method->GetDexFile(), dex_file)) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100193 return method->GetDexMethodIndex();
194 } else {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000195 return method->FindDexMethodIndexInOtherDexFile(dex_file, name_and_signature_index);
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100196 }
197}
198
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000199static uint32_t FindClassIndexIn(mirror::Class* cls,
200 const DexFile& dex_file,
201 Handle<mirror::DexCache> dex_cache)
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100202 SHARED_REQUIRES(Locks::mutator_lock_) {
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000203 uint32_t index = DexFile::kDexNoIndex;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100204 if (cls->GetDexCache() == nullptr) {
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000205 DCHECK(cls->IsArrayClass()) << PrettyClass(cls);
206 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100207 } else if (cls->GetDexTypeIndex() == DexFile::kDexNoIndex16) {
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000208 DCHECK(cls->IsProxyClass()) << PrettyClass(cls);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100209 // TODO: deal with proxy classes.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100210 } else if (IsSameDexFile(cls->GetDexFile(), dex_file)) {
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100211 DCHECK_EQ(cls->GetDexCache(), dex_cache.Get());
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000212 index = cls->GetDexTypeIndex();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100213 // Update the dex cache to ensure the class is in. The generated code will
214 // consider it is. We make it safe by updating the dex cache, as other
215 // dex files might also load the class, and there is no guarantee the dex
216 // cache of the dex file of the class will be updated.
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000217 if (dex_cache->GetResolvedType(index) == nullptr) {
218 dex_cache->SetResolvedType(index, cls);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100219 }
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100220 } else {
221 index = cls->FindTypeIndexInOtherDexFile(dex_file);
222 // We cannot guarantee the entry in the dex cache will resolve to the same class,
223 // as there may be different class loaders. So only return the index if it's
224 // the right class in the dex cache already.
225 if (index != DexFile::kDexNoIndex && dex_cache->GetResolvedType(index) != cls) {
226 index = DexFile::kDexNoIndex;
227 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100228 }
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000229
230 return index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100231}
232
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000233class ScopedProfilingInfoInlineUse {
234 public:
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000235 explicit ScopedProfilingInfoInlineUse(ArtMethod* method, Thread* self)
236 : method_(method),
237 self_(self),
238 // Fetch the profiling info ahead of using it. If it's null when fetching,
239 // we should not call JitCodeCache::DoneInlining.
240 profiling_info_(
241 Runtime::Current()->GetJit()->GetCodeCache()->NotifyCompilerUse(method, self)) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000242 }
243
244 ~ScopedProfilingInfoInlineUse() {
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000245 if (profiling_info_ != nullptr) {
246 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
247 DCHECK_EQ(profiling_info_, method_->GetProfilingInfo(pointer_size));
248 Runtime::Current()->GetJit()->GetCodeCache()->DoneCompilerUse(method_, self_);
249 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000250 }
251
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000252 ProfilingInfo* GetProfilingInfo() const { return profiling_info_; }
253
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000254 private:
255 ArtMethod* const method_;
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000256 Thread* const self_;
257 ProfilingInfo* const profiling_info_;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000258};
259
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700260bool HInliner::TryInline(HInvoke* invoke_instruction) {
Calin Juravle175dc732015-08-25 15:42:32 +0100261 if (invoke_instruction->IsInvokeUnresolved()) {
262 return false; // Don't bother to move further if we know the method is unresolved.
263 }
264
Vladimir Marko58155012015-08-19 12:49:41 +0000265 uint32_t method_index = invoke_instruction->GetDexMethodIndex();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000266 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000267 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
268 VLOG(compiler) << "Try inlining " << PrettyMethod(method_index, caller_dex_file);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000269
Nicolas Geoffray35071052015-06-09 15:43:38 +0100270 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
271 // We can query the dex cache directly. The verifier has populated it already.
Vladimir Marko58155012015-08-19 12:49:41 +0000272 ArtMethod* resolved_method;
Andreas Gampefd2140f2015-12-23 16:30:44 -0800273 ArtMethod* actual_method = nullptr;
Vladimir Marko58155012015-08-19 12:49:41 +0000274 if (invoke_instruction->IsInvokeStaticOrDirect()) {
Nicolas Geoffraye5234232015-12-02 09:06:11 +0000275 if (invoke_instruction->AsInvokeStaticOrDirect()->IsStringInit()) {
276 VLOG(compiler) << "Not inlining a String.<init> method";
277 return false;
278 }
Vladimir Marko58155012015-08-19 12:49:41 +0000279 MethodReference ref = invoke_instruction->AsInvokeStaticOrDirect()->GetTargetMethod();
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100280 mirror::DexCache* const dex_cache = IsSameDexFile(caller_dex_file, *ref.dex_file)
Mathieu Chartier736b5602015-09-02 14:54:11 -0700281 ? caller_compilation_unit_.GetDexCache().Get()
282 : class_linker->FindDexCache(soa.Self(), *ref.dex_file);
283 resolved_method = dex_cache->GetResolvedMethod(
Vladimir Marko58155012015-08-19 12:49:41 +0000284 ref.dex_method_index, class_linker->GetImagePointerSize());
Andreas Gampefd2140f2015-12-23 16:30:44 -0800285 // actual_method == resolved_method for direct or static calls.
286 actual_method = resolved_method;
Vladimir Marko58155012015-08-19 12:49:41 +0000287 } else {
Mathieu Chartier736b5602015-09-02 14:54:11 -0700288 resolved_method = caller_compilation_unit_.GetDexCache().Get()->GetResolvedMethod(
Vladimir Marko58155012015-08-19 12:49:41 +0000289 method_index, class_linker->GetImagePointerSize());
Andreas Gampefd2140f2015-12-23 16:30:44 -0800290 if (resolved_method != nullptr) {
291 // Check if we can statically find the method.
292 actual_method = FindVirtualOrInterfaceTarget(invoke_instruction, resolved_method);
293 }
Vladimir Marko58155012015-08-19 12:49:41 +0000294 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000295
Mathieu Chartiere401d142015-04-22 13:56:20 -0700296 if (resolved_method == nullptr) {
Calin Juravle175dc732015-08-25 15:42:32 +0100297 // TODO: Can this still happen?
Nicolas Geoffray35071052015-06-09 15:43:38 +0100298 // Method cannot be resolved if it is in another dex file we do not have access to.
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000299 VLOG(compiler) << "Method cannot be resolved " << PrettyMethod(method_index, caller_dex_file);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000300 return false;
301 }
302
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100303 if (actual_method != nullptr) {
Calin Juravle69158982016-03-16 11:53:41 +0000304 bool result = TryInlineAndReplace(invoke_instruction, actual_method, /* do_rtp */ true);
305 if (result && !invoke_instruction->IsInvokeStaticOrDirect()) {
306 MaybeRecordStat(kInlinedInvokeVirtualOrInterface);
307 }
308 return result;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100309 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000310
Andreas Gampefd2140f2015-12-23 16:30:44 -0800311 DCHECK(!invoke_instruction->IsInvokeStaticOrDirect());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100312
313 // Check if we can use an inline cache.
314 ArtMethod* caller = graph_->GetArtMethod();
Calin Juravleffc87072016-04-20 14:22:09 +0100315 if (Runtime::Current()->UseJitCompilation()) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000316 // Under JIT, we should always know the caller.
317 DCHECK(caller != nullptr);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000318 ScopedProfilingInfoInlineUse spiis(caller, soa.Self());
319 ProfilingInfo* profiling_info = spiis.GetProfilingInfo();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000320 if (profiling_info != nullptr) {
321 const InlineCache& ic = *profiling_info->GetInlineCache(invoke_instruction->GetDexPc());
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000322 if (ic.IsUninitialized()) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000323 VLOG(compiler) << "Interface or virtual call to "
324 << PrettyMethod(method_index, caller_dex_file)
325 << " is not hit and not inlined";
326 return false;
327 } else if (ic.IsMonomorphic()) {
328 MaybeRecordStat(kMonomorphicCall);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100329 if (outermost_graph_->IsCompilingOsr()) {
330 // If we are compiling OSR, we pretend this call is polymorphic, as we may come from the
331 // interpreter and it may have seen different receiver types.
332 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, ic);
333 } else {
334 return TryInlineMonomorphicCall(invoke_instruction, resolved_method, ic);
335 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000336 } else if (ic.IsPolymorphic()) {
337 MaybeRecordStat(kPolymorphicCall);
338 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, ic);
339 } else {
340 DCHECK(ic.IsMegamorphic());
341 VLOG(compiler) << "Interface or virtual call to "
342 << PrettyMethod(method_index, caller_dex_file)
343 << " is megamorphic and not inlined";
344 MaybeRecordStat(kMegamorphicCall);
345 return false;
346 }
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100347 }
348 }
349
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100350 VLOG(compiler) << "Interface or virtual call to "
351 << PrettyMethod(method_index, caller_dex_file)
352 << " could not be statically determined";
353 return false;
354}
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000355
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000356HInstanceFieldGet* HInliner::BuildGetReceiverClass(ClassLinker* class_linker,
357 HInstruction* receiver,
358 uint32_t dex_pc) const {
359 ArtField* field = class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0);
360 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000361 HInstanceFieldGet* result = new (graph_->GetArena()) HInstanceFieldGet(
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000362 receiver,
363 Primitive::kPrimNot,
364 field->GetOffset(),
365 field->IsVolatile(),
366 field->GetDexFieldIndex(),
367 field->GetDeclaringClass()->GetDexClassDefIndex(),
368 *field->GetDexFile(),
369 handles_->NewHandle(field->GetDexCache()),
370 dex_pc);
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000371 // The class of a field is effectively final, and does not have any memory dependencies.
372 result->SetSideEffects(SideEffects::None());
373 return result;
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000374}
375
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100376bool HInliner::TryInlineMonomorphicCall(HInvoke* invoke_instruction,
377 ArtMethod* resolved_method,
378 const InlineCache& ic) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000379 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
380 << invoke_instruction->DebugName();
381
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100382 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000383 uint32_t class_index = FindClassIndexIn(
384 ic.GetMonomorphicType(), caller_dex_file, caller_compilation_unit_.GetDexCache());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100385 if (class_index == DexFile::kDexNoIndex) {
386 VLOG(compiler) << "Call to " << PrettyMethod(resolved_method)
387 << " from inline cache is not inlined because its class is not"
388 << " accessible to the caller";
389 return false;
390 }
391
392 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
393 size_t pointer_size = class_linker->GetImagePointerSize();
394 if (invoke_instruction->IsInvokeInterface()) {
395 resolved_method = ic.GetMonomorphicType()->FindVirtualMethodForInterface(
396 resolved_method, pointer_size);
397 } else {
398 DCHECK(invoke_instruction->IsInvokeVirtual());
399 resolved_method = ic.GetMonomorphicType()->FindVirtualMethodForVirtual(
400 resolved_method, pointer_size);
401 }
402 DCHECK(resolved_method != nullptr);
403 HInstruction* receiver = invoke_instruction->InputAt(0);
404 HInstruction* cursor = invoke_instruction->GetPrevious();
405 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
406
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000407 if (!TryInlineAndReplace(invoke_instruction, resolved_method, /* do_rtp */ false)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100408 return false;
409 }
410
411 // We successfully inlined, now add a guard.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100412 bool is_referrer =
413 (ic.GetMonomorphicType() == outermost_graph_->GetArtMethod()->GetDeclaringClass());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000414 AddTypeGuard(receiver,
415 cursor,
416 bb_cursor,
417 class_index,
418 is_referrer,
419 invoke_instruction,
420 /* with_deoptimization */ true);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100421
422 // Run type propagation to get the guard typed, and eventually propagate the
423 // type of the receiver.
Vladimir Marko456307a2016-04-19 14:12:13 +0000424 ReferenceTypePropagation rtp_fixup(graph_,
425 outer_compilation_unit_.GetDexCache(),
426 handles_,
427 /* is_first_run */ false);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100428 rtp_fixup.Run();
429
430 MaybeRecordStat(kInlinedMonomorphicCall);
431 return true;
432}
433
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000434HInstruction* HInliner::AddTypeGuard(HInstruction* receiver,
435 HInstruction* cursor,
436 HBasicBlock* bb_cursor,
437 uint32_t class_index,
438 bool is_referrer,
439 HInstruction* invoke_instruction,
440 bool with_deoptimization) {
441 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
442 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
443 class_linker, receiver, invoke_instruction->GetDexPc());
444
445 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
446 // Note that we will just compare the classes, so we don't need Java semantics access checks.
447 // Also, the caller of `AddTypeGuard` must have guaranteed that the class is in the dex cache.
448 HLoadClass* load_class = new (graph_->GetArena()) HLoadClass(graph_->GetCurrentMethod(),
449 class_index,
450 caller_dex_file,
451 is_referrer,
452 invoke_instruction->GetDexPc(),
453 /* needs_access_check */ false,
454 /* is_in_dex_cache */ true);
455
456 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(load_class, receiver_class);
457 // TODO: Extend reference type propagation to understand the guard.
458 if (cursor != nullptr) {
459 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
460 } else {
461 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
462 }
463 bb_cursor->InsertInstructionAfter(load_class, receiver_class);
464 bb_cursor->InsertInstructionAfter(compare, load_class);
465 if (with_deoptimization) {
466 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
467 compare, invoke_instruction->GetDexPc());
468 bb_cursor->InsertInstructionAfter(deoptimize, compare);
469 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
470 }
471 return compare;
472}
473
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000474bool HInliner::TryInlinePolymorphicCall(HInvoke* invoke_instruction,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100475 ArtMethod* resolved_method,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000476 const InlineCache& ic) {
477 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
478 << invoke_instruction->DebugName();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000479
480 if (TryInlinePolymorphicCallToSameTarget(invoke_instruction, resolved_method, ic)) {
481 return true;
482 }
483
484 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
485 size_t pointer_size = class_linker->GetImagePointerSize();
486 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
487
488 bool all_targets_inlined = true;
489 bool one_target_inlined = false;
490 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
491 if (ic.GetTypeAt(i) == nullptr) {
492 break;
493 }
494 ArtMethod* method = nullptr;
495 if (invoke_instruction->IsInvokeInterface()) {
496 method = ic.GetTypeAt(i)->FindVirtualMethodForInterface(
497 resolved_method, pointer_size);
498 } else {
499 DCHECK(invoke_instruction->IsInvokeVirtual());
500 method = ic.GetTypeAt(i)->FindVirtualMethodForVirtual(
501 resolved_method, pointer_size);
502 }
503
504 HInstruction* receiver = invoke_instruction->InputAt(0);
505 HInstruction* cursor = invoke_instruction->GetPrevious();
506 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
507
Nicolas Geoffray1fe26e12016-02-18 16:55:42 +0000508 uint32_t class_index = FindClassIndexIn(
509 ic.GetTypeAt(i), caller_dex_file, caller_compilation_unit_.GetDexCache());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000510 HInstruction* return_replacement = nullptr;
511 if (class_index == DexFile::kDexNoIndex ||
512 !TryBuildAndInline(invoke_instruction, method, &return_replacement)) {
513 all_targets_inlined = false;
514 } else {
515 one_target_inlined = true;
516 bool is_referrer = (ic.GetTypeAt(i) == outermost_graph_->GetArtMethod()->GetDeclaringClass());
517
518 // If we have inlined all targets before, and this receiver is the last seen,
519 // we deoptimize instead of keeping the original invoke instruction.
520 bool deoptimize = all_targets_inlined &&
521 (i != InlineCache::kIndividualCacheSize - 1) &&
522 (ic.GetTypeAt(i + 1) == nullptr);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100523
524 if (outermost_graph_->IsCompilingOsr()) {
525 // We do not support HDeoptimize in OSR methods.
526 deoptimize = false;
527 }
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000528 HInstruction* compare = AddTypeGuard(
529 receiver, cursor, bb_cursor, class_index, is_referrer, invoke_instruction, deoptimize);
530 if (deoptimize) {
531 if (return_replacement != nullptr) {
532 invoke_instruction->ReplaceWith(return_replacement);
533 }
534 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
535 // Because the inline cache data can be populated concurrently, we force the end of the
536 // iteration. Otherhwise, we could see a new receiver type.
537 break;
538 } else {
539 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
540 }
541 }
542 }
543
544 if (!one_target_inlined) {
545 VLOG(compiler) << "Call to " << PrettyMethod(resolved_method)
546 << " from inline cache is not inlined because none"
547 << " of its targets could be inlined";
548 return false;
549 }
550 MaybeRecordStat(kInlinedPolymorphicCall);
551
552 // Run type propagation to get the guards typed.
Vladimir Marko456307a2016-04-19 14:12:13 +0000553 ReferenceTypePropagation rtp_fixup(graph_,
554 outer_compilation_unit_.GetDexCache(),
555 handles_,
556 /* is_first_run */ false);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000557 rtp_fixup.Run();
558 return true;
559}
560
561void HInliner::CreateDiamondPatternForPolymorphicInline(HInstruction* compare,
562 HInstruction* return_replacement,
563 HInstruction* invoke_instruction) {
564 uint32_t dex_pc = invoke_instruction->GetDexPc();
565 HBasicBlock* cursor_block = compare->GetBlock();
566 HBasicBlock* original_invoke_block = invoke_instruction->GetBlock();
567 ArenaAllocator* allocator = graph_->GetArena();
568
569 // Spit the block after the compare: `cursor_block` will now be the start of the diamond,
570 // and the returned block is the start of the then branch (that could contain multiple blocks).
571 HBasicBlock* then = cursor_block->SplitAfterForInlining(compare);
572
573 // Split the block containing the invoke before and after the invoke. The returned block
574 // of the split before will contain the invoke and will be the otherwise branch of
575 // the diamond. The returned block of the split after will be the merge block
576 // of the diamond.
577 HBasicBlock* end_then = invoke_instruction->GetBlock();
578 HBasicBlock* otherwise = end_then->SplitBeforeForInlining(invoke_instruction);
579 HBasicBlock* merge = otherwise->SplitAfterForInlining(invoke_instruction);
580
581 // If the methods we are inlining return a value, we create a phi in the merge block
582 // that will have the `invoke_instruction and the `return_replacement` as inputs.
583 if (return_replacement != nullptr) {
584 HPhi* phi = new (allocator) HPhi(
585 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke_instruction->GetType()), dex_pc);
586 merge->AddPhi(phi);
587 invoke_instruction->ReplaceWith(phi);
588 phi->AddInput(return_replacement);
589 phi->AddInput(invoke_instruction);
590 }
591
592 // Add the control flow instructions.
593 otherwise->AddInstruction(new (allocator) HGoto(dex_pc));
594 end_then->AddInstruction(new (allocator) HGoto(dex_pc));
595 cursor_block->AddInstruction(new (allocator) HIf(compare, dex_pc));
596
597 // Add the newly created blocks to the graph.
598 graph_->AddBlock(then);
599 graph_->AddBlock(otherwise);
600 graph_->AddBlock(merge);
601
602 // Set up successor (and implictly predecessor) relations.
603 cursor_block->AddSuccessor(otherwise);
604 cursor_block->AddSuccessor(then);
605 end_then->AddSuccessor(merge);
606 otherwise->AddSuccessor(merge);
607
608 // Set up dominance information.
609 then->SetDominator(cursor_block);
610 cursor_block->AddDominatedBlock(then);
611 otherwise->SetDominator(cursor_block);
612 cursor_block->AddDominatedBlock(otherwise);
613 merge->SetDominator(cursor_block);
614 cursor_block->AddDominatedBlock(merge);
615
616 // Update the revert post order.
617 size_t index = IndexOfElement(graph_->reverse_post_order_, cursor_block);
618 MakeRoomFor(&graph_->reverse_post_order_, 1, index);
619 graph_->reverse_post_order_[++index] = then;
620 index = IndexOfElement(graph_->reverse_post_order_, end_then);
621 MakeRoomFor(&graph_->reverse_post_order_, 2, index);
622 graph_->reverse_post_order_[++index] = otherwise;
623 graph_->reverse_post_order_[++index] = merge;
624
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000625
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +0000626 graph_->UpdateLoopAndTryInformationOfNewBlock(
627 then, original_invoke_block, /* replace_if_back_edge */ false);
628 graph_->UpdateLoopAndTryInformationOfNewBlock(
629 otherwise, original_invoke_block, /* replace_if_back_edge */ false);
630
631 // In case the original invoke location was a back edge, we need to update
632 // the loop to now have the merge block as a back edge.
633 graph_->UpdateLoopAndTryInformationOfNewBlock(
634 merge, original_invoke_block, /* replace_if_back_edge */ true);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000635}
636
637bool HInliner::TryInlinePolymorphicCallToSameTarget(HInvoke* invoke_instruction,
638 ArtMethod* resolved_method,
639 const InlineCache& ic) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000640 // This optimization only works under JIT for now.
Calin Juravleffc87072016-04-20 14:22:09 +0100641 DCHECK(Runtime::Current()->UseJitCompilation());
Roland Levillain2aba7cd2016-02-03 12:27:20 +0000642 if (graph_->GetInstructionSet() == kMips64) {
643 // TODO: Support HClassTableGet for mips64.
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000644 return false;
645 }
646 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
647 size_t pointer_size = class_linker->GetImagePointerSize();
648
649 DCHECK(resolved_method != nullptr);
650 ArtMethod* actual_method = nullptr;
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000651 size_t method_index = invoke_instruction->IsInvokeVirtual()
652 ? invoke_instruction->AsInvokeVirtual()->GetVTableIndex()
653 : invoke_instruction->AsInvokeInterface()->GetImtIndex();
654
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000655 // Check whether we are actually calling the same method among
656 // the different types seen.
657 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
658 if (ic.GetTypeAt(i) == nullptr) {
659 break;
660 }
661 ArtMethod* new_method = nullptr;
662 if (invoke_instruction->IsInvokeInterface()) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +0000663 new_method = ic.GetTypeAt(i)->GetImt(pointer_size)->Get(
664 method_index % ImTable::kSize, pointer_size);
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000665 if (new_method->IsRuntimeMethod()) {
666 // Bail out as soon as we see a conflict trampoline in one of the target's
667 // interface table.
668 return false;
669 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000670 } else {
671 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000672 new_method = ic.GetTypeAt(i)->GetEmbeddedVTableEntry(method_index, pointer_size);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000673 }
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000674 DCHECK(new_method != nullptr);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000675 if (actual_method == nullptr) {
676 actual_method = new_method;
677 } else if (actual_method != new_method) {
678 // Different methods, bailout.
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000679 VLOG(compiler) << "Call to " << PrettyMethod(resolved_method)
680 << " from inline cache is not inlined because it resolves"
681 << " to different methods";
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000682 return false;
683 }
684 }
685
686 HInstruction* receiver = invoke_instruction->InputAt(0);
687 HInstruction* cursor = invoke_instruction->GetPrevious();
688 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
689
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100690 HInstruction* return_replacement = nullptr;
691 if (!TryBuildAndInline(invoke_instruction, actual_method, &return_replacement)) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000692 return false;
693 }
694
695 // We successfully inlined, now add a guard.
696 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
697 class_linker, receiver, invoke_instruction->GetDexPc());
698
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000699 Primitive::Type type = Is64BitInstructionSet(graph_->GetInstructionSet())
700 ? Primitive::kPrimLong
701 : Primitive::kPrimInt;
702 HClassTableGet* class_table_get = new (graph_->GetArena()) HClassTableGet(
703 receiver_class,
704 type,
Vladimir Markoa1de9182016-02-25 11:37:38 +0000705 invoke_instruction->IsInvokeVirtual() ? HClassTableGet::TableKind::kVTable
706 : HClassTableGet::TableKind::kIMTable,
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000707 method_index,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000708 invoke_instruction->GetDexPc());
709
710 HConstant* constant;
711 if (type == Primitive::kPrimLong) {
712 constant = graph_->GetLongConstant(
713 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
714 } else {
715 constant = graph_->GetIntConstant(
716 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
717 }
718
719 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(class_table_get, constant);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000720 if (cursor != nullptr) {
721 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
722 } else {
723 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
724 }
725 bb_cursor->InsertInstructionAfter(class_table_get, receiver_class);
726 bb_cursor->InsertInstructionAfter(compare, class_table_get);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100727
728 if (outermost_graph_->IsCompilingOsr()) {
729 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
730 } else {
731 // TODO: Extend reference type propagation to understand the guard.
732 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
733 compare, invoke_instruction->GetDexPc());
734 bb_cursor->InsertInstructionAfter(deoptimize, compare);
735 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
736 if (return_replacement != nullptr) {
737 invoke_instruction->ReplaceWith(return_replacement);
738 }
Nicolas Geoffray1be7cbd2016-04-29 13:56:01 +0100739 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100740 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000741
742 // Run type propagation to get the guard typed.
Vladimir Marko456307a2016-04-19 14:12:13 +0000743 ReferenceTypePropagation rtp_fixup(graph_,
744 outer_compilation_unit_.GetDexCache(),
745 handles_,
746 /* is_first_run */ false);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000747 rtp_fixup.Run();
748
749 MaybeRecordStat(kInlinedPolymorphicCall);
750
751 return true;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100752}
753
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000754bool HInliner::TryInlineAndReplace(HInvoke* invoke_instruction, ArtMethod* method, bool do_rtp) {
755 HInstruction* return_replacement = nullptr;
756 if (!TryBuildAndInline(invoke_instruction, method, &return_replacement)) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000757 if (invoke_instruction->IsInvokeInterface()) {
758 // Turn an invoke-interface into an invoke-virtual. An invoke-virtual is always
759 // better than an invoke-interface because:
760 // 1) In the best case, the interface call has one more indirection (to fetch the IMT).
761 // 2) We will not go to the conflict trampoline with an invoke-virtual.
762 // TODO: Consider sharpening once it is not dependent on the compiler driver.
763 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
764 uint32_t method_index = FindMethodIndexIn(
765 method, caller_dex_file, invoke_instruction->GetDexMethodIndex());
766 if (method_index == DexFile::kDexNoIndex) {
767 return false;
768 }
769 HInvokeVirtual* new_invoke = new (graph_->GetArena()) HInvokeVirtual(
770 graph_->GetArena(),
771 invoke_instruction->GetNumberOfArguments(),
772 invoke_instruction->GetType(),
773 invoke_instruction->GetDexPc(),
774 method_index,
775 method->GetMethodIndex());
776 HInputsRef inputs = invoke_instruction->GetInputs();
777 for (size_t index = 0; index != inputs.size(); ++index) {
778 new_invoke->SetArgumentAt(index, inputs[index]);
779 }
780 invoke_instruction->GetBlock()->InsertInstructionBefore(new_invoke, invoke_instruction);
781 new_invoke->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
782 if (invoke_instruction->GetType() == Primitive::kPrimNot) {
783 new_invoke->SetReferenceTypeInfo(invoke_instruction->GetReferenceTypeInfo());
784 }
785 return_replacement = new_invoke;
786 } else {
787 // TODO: Consider sharpening an invoke virtual once it is not dependent on the
788 // compiler driver.
789 return false;
790 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000791 }
792 if (return_replacement != nullptr) {
793 invoke_instruction->ReplaceWith(return_replacement);
794 }
795 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
David Brazdil94ab38f2016-06-21 17:48:19 +0100796 FixUpReturnReferenceType(method, return_replacement);
797 if (do_rtp && ReturnTypeMoreSpecific(invoke_instruction, return_replacement)) {
798 // Actual return value has a more specific type than the method's declared
799 // return type. Run RTP again on the outer graph to propagate it.
800 ReferenceTypePropagation(graph_,
801 outer_compilation_unit_.GetDexCache(),
802 handles_,
803 /* is_first_run */ false).Run();
804 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000805 return true;
806}
807
808bool HInliner::TryBuildAndInline(HInvoke* invoke_instruction,
809 ArtMethod* method,
810 HInstruction** return_replacement) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100811 if (method->IsProxyMethod()) {
812 VLOG(compiler) << "Method " << PrettyMethod(method)
813 << " is not inlined because of unimplemented inline support for proxy methods.";
814 return false;
815 }
816
Jeff Haodcdc85b2015-12-04 14:06:18 -0800817 // Check whether we're allowed to inline. The outermost compilation unit is the relevant
818 // dex file here (though the transitivity of an inline chain would allow checking the calller).
819 if (!compiler_driver_->MayInline(method->GetDexFile(),
820 outer_compilation_unit_.GetDexFile())) {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000821 if (TryPatternSubstitution(invoke_instruction, method, return_replacement)) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000822 VLOG(compiler) << "Successfully replaced pattern of invoke " << PrettyMethod(method);
823 MaybeRecordStat(kReplacedInvokeWithSimplePattern);
824 return true;
825 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800826 VLOG(compiler) << "Won't inline " << PrettyMethod(method) << " in "
827 << outer_compilation_unit_.GetDexFile()->GetLocation() << " ("
828 << caller_compilation_unit_.GetDexFile()->GetLocation() << ") from "
829 << method->GetDexFile()->GetLocation();
830 return false;
831 }
832
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100833 bool same_dex_file = IsSameDexFile(*outer_compilation_unit_.GetDexFile(), *method->GetDexFile());
834
835 const DexFile::CodeItem* code_item = method->GetCodeItem();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000836
837 if (code_item == nullptr) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100838 VLOG(compiler) << "Method " << PrettyMethod(method)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000839 << " is not inlined because it is native";
840 return false;
841 }
842
Calin Juravleec748352015-07-29 13:52:12 +0100843 size_t inline_max_code_units = compiler_driver_->GetCompilerOptions().GetInlineMaxCodeUnits();
844 if (code_item->insns_size_in_code_units_ > inline_max_code_units) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100845 VLOG(compiler) << "Method " << PrettyMethod(method)
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000846 << " is too big to inline: "
847 << code_item->insns_size_in_code_units_
848 << " > "
849 << inline_max_code_units;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000850 return false;
851 }
852
853 if (code_item->tries_size_ != 0) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100854 VLOG(compiler) << "Method " << PrettyMethod(method)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000855 << " is not inlined because of try block";
856 return false;
857 }
858
Nicolas Geoffray250a3782016-04-20 16:27:53 +0100859 if (!method->IsCompilable()) {
860 VLOG(compiler) << "Method " << PrettyMethod(method)
861 << " has soft failures un-handled by the compiler, so it cannot be inlined";
862 }
863
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100864 if (!method->GetDeclaringClass()->IsVerified()) {
865 uint16_t class_def_idx = method->GetDeclaringClass()->GetDexClassDefIndex();
Calin Juravleffc87072016-04-20 14:22:09 +0100866 if (Runtime::Current()->UseJitCompilation() ||
Nicolas Geoffray5b82d332016-02-18 14:22:32 +0000867 !compiler_driver_->IsMethodVerifiedWithoutFailures(
868 method->GetDexMethodIndex(), class_def_idx, *method->GetDexFile())) {
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100869 VLOG(compiler) << "Method " << PrettyMethod(method)
Nicolas Geoffrayccc61972015-10-01 14:34:20 +0100870 << " couldn't be verified, so it cannot be inlined";
871 return false;
872 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000873 }
874
Roland Levillain4c0eb422015-04-24 16:43:49 +0100875 if (invoke_instruction->IsInvokeStaticOrDirect() &&
876 invoke_instruction->AsInvokeStaticOrDirect()->IsStaticWithImplicitClinitCheck()) {
877 // Case of a static method that cannot be inlined because it implicitly
878 // requires an initialization check of its declaring class.
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100879 VLOG(compiler) << "Method " << PrettyMethod(method)
Roland Levillain4c0eb422015-04-24 16:43:49 +0100880 << " is not inlined because it is static and requires a clinit"
881 << " check that cannot be emitted due to Dex cache limitations";
882 return false;
883 }
884
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000885 if (!TryBuildAndInlineHelper(invoke_instruction, method, same_dex_file, return_replacement)) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +0000886 return false;
887 }
888
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100889 VLOG(compiler) << "Successfully inlined " << PrettyMethod(method);
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +0000890 MaybeRecordStat(kInlinedInvoke);
891 return true;
892}
893
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000894static HInstruction* GetInvokeInputForArgVRegIndex(HInvoke* invoke_instruction,
895 size_t arg_vreg_index)
896 SHARED_REQUIRES(Locks::mutator_lock_) {
897 size_t input_index = 0;
898 for (size_t i = 0; i < arg_vreg_index; ++i, ++input_index) {
899 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
900 if (Primitive::Is64BitType(invoke_instruction->InputAt(input_index)->GetType())) {
901 ++i;
902 DCHECK_NE(i, arg_vreg_index);
903 }
904 }
905 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
906 return invoke_instruction->InputAt(input_index);
907}
908
909// Try to recognize known simple patterns and replace invoke call with appropriate instructions.
910bool HInliner::TryPatternSubstitution(HInvoke* invoke_instruction,
911 ArtMethod* resolved_method,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000912 HInstruction** return_replacement) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000913 InlineMethod inline_method;
914 if (!InlineMethodAnalyser::AnalyseMethodCode(resolved_method, &inline_method)) {
915 return false;
916 }
917
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000918 switch (inline_method.opcode) {
919 case kInlineOpNop:
920 DCHECK_EQ(invoke_instruction->GetType(), Primitive::kPrimVoid);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000921 *return_replacement = nullptr;
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000922 break;
923 case kInlineOpReturnArg:
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000924 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction,
925 inline_method.d.return_data.arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000926 break;
927 case kInlineOpNonWideConst:
928 if (resolved_method->GetShorty()[0] == 'L') {
929 DCHECK_EQ(inline_method.d.data, 0u);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000930 *return_replacement = graph_->GetNullConstant();
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000931 } else {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000932 *return_replacement = graph_->GetIntConstant(static_cast<int32_t>(inline_method.d.data));
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000933 }
934 break;
935 case kInlineOpIGet: {
936 const InlineIGetIPutData& data = inline_method.d.ifield_data;
937 if (data.method_is_static || data.object_arg != 0u) {
938 // TODO: Needs null check.
939 return false;
940 }
Vladimir Marko354efa62016-02-04 19:46:56 +0000941 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000942 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
Vladimir Marko354efa62016-02-04 19:46:56 +0000943 HInstanceFieldGet* iget = CreateInstanceFieldGet(dex_cache, data.field_idx, obj);
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000944 DCHECK_EQ(iget->GetFieldOffset().Uint32Value(), data.field_offset);
945 DCHECK_EQ(iget->IsVolatile() ? 1u : 0u, data.is_volatile);
946 invoke_instruction->GetBlock()->InsertInstructionBefore(iget, invoke_instruction);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000947 *return_replacement = iget;
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000948 break;
949 }
950 case kInlineOpIPut: {
951 const InlineIGetIPutData& data = inline_method.d.ifield_data;
952 if (data.method_is_static || data.object_arg != 0u) {
953 // TODO: Needs null check.
954 return false;
955 }
Vladimir Marko354efa62016-02-04 19:46:56 +0000956 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000957 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
958 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, data.src_arg);
Vladimir Marko354efa62016-02-04 19:46:56 +0000959 HInstanceFieldSet* iput = CreateInstanceFieldSet(dex_cache, data.field_idx, obj, value);
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000960 DCHECK_EQ(iput->GetFieldOffset().Uint32Value(), data.field_offset);
961 DCHECK_EQ(iput->IsVolatile() ? 1u : 0u, data.is_volatile);
962 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
963 if (data.return_arg_plus1 != 0u) {
964 size_t return_arg = data.return_arg_plus1 - 1u;
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000965 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction, return_arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000966 }
967 break;
968 }
Vladimir Marko354efa62016-02-04 19:46:56 +0000969 case kInlineOpConstructor: {
970 const InlineConstructorData& data = inline_method.d.constructor_data;
971 // Get the indexes to arrays for easier processing.
972 uint16_t iput_field_indexes[] = {
973 data.iput0_field_index, data.iput1_field_index, data.iput2_field_index
974 };
975 uint16_t iput_args[] = { data.iput0_arg, data.iput1_arg, data.iput2_arg };
976 static_assert(arraysize(iput_args) == arraysize(iput_field_indexes), "Size mismatch");
977 // Count valid field indexes.
978 size_t number_of_iputs = 0u;
979 while (number_of_iputs != arraysize(iput_field_indexes) &&
980 iput_field_indexes[number_of_iputs] != DexFile::kDexNoIndex16) {
981 // Check that there are no duplicate valid field indexes.
982 DCHECK_EQ(0, std::count(iput_field_indexes + number_of_iputs + 1,
983 iput_field_indexes + arraysize(iput_field_indexes),
984 iput_field_indexes[number_of_iputs]));
985 ++number_of_iputs;
986 }
987 // Check that there are no valid field indexes in the rest of the array.
988 DCHECK_EQ(0, std::count_if(iput_field_indexes + number_of_iputs,
989 iput_field_indexes + arraysize(iput_field_indexes),
990 [](uint16_t index) { return index != DexFile::kDexNoIndex16; }));
991
992 // Create HInstanceFieldSet for each IPUT that stores non-zero data.
993 Handle<mirror::DexCache> dex_cache;
994 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, /* this */ 0u);
995 bool needs_constructor_barrier = false;
996 for (size_t i = 0; i != number_of_iputs; ++i) {
997 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, iput_args[i]);
Roland Levillain1a653882016-03-18 18:05:57 +0000998 if (!value->IsConstant() || !value->AsConstant()->IsZeroBitPattern()) {
Vladimir Marko354efa62016-02-04 19:46:56 +0000999 if (dex_cache.GetReference() == nullptr) {
1000 dex_cache = handles_->NewHandle(resolved_method->GetDexCache());
1001 }
1002 uint16_t field_index = iput_field_indexes[i];
1003 HInstanceFieldSet* iput = CreateInstanceFieldSet(dex_cache, field_index, obj, value);
1004 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1005
1006 // Check whether the field is final. If it is, we need to add a barrier.
1007 size_t pointer_size = InstructionSetPointerSize(codegen_->GetInstructionSet());
1008 ArtField* resolved_field = dex_cache->GetResolvedField(field_index, pointer_size);
1009 DCHECK(resolved_field != nullptr);
1010 if (resolved_field->IsFinal()) {
1011 needs_constructor_barrier = true;
1012 }
1013 }
1014 }
1015 if (needs_constructor_barrier) {
1016 HMemoryBarrier* barrier = new (graph_->GetArena()) HMemoryBarrier(kStoreStore, kNoDexPc);
1017 invoke_instruction->GetBlock()->InsertInstructionBefore(barrier, invoke_instruction);
1018 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001019 *return_replacement = nullptr;
Vladimir Marko354efa62016-02-04 19:46:56 +00001020 break;
1021 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001022 default:
1023 LOG(FATAL) << "UNREACHABLE";
1024 UNREACHABLE();
1025 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001026 return true;
1027}
1028
Vladimir Marko354efa62016-02-04 19:46:56 +00001029HInstanceFieldGet* HInliner::CreateInstanceFieldGet(Handle<mirror::DexCache> dex_cache,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001030 uint32_t field_index,
1031 HInstruction* obj)
1032 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001033 size_t pointer_size = InstructionSetPointerSize(codegen_->GetInstructionSet());
1034 ArtField* resolved_field = dex_cache->GetResolvedField(field_index, pointer_size);
1035 DCHECK(resolved_field != nullptr);
1036 HInstanceFieldGet* iget = new (graph_->GetArena()) HInstanceFieldGet(
1037 obj,
1038 resolved_field->GetTypeAsPrimitiveType(),
1039 resolved_field->GetOffset(),
1040 resolved_field->IsVolatile(),
1041 field_index,
1042 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Marko354efa62016-02-04 19:46:56 +00001043 *dex_cache->GetDexFile(),
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001044 dex_cache,
Vladimir Markoadda4352016-01-29 10:24:41 +00001045 // Read barrier generates a runtime call in slow path and we need a valid
1046 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1047 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001048 if (iget->GetType() == Primitive::kPrimNot) {
Vladimir Marko456307a2016-04-19 14:12:13 +00001049 // Use the same dex_cache that we used for field lookup as the hint_dex_cache.
1050 ReferenceTypePropagation rtp(graph_, dex_cache, handles_, /* is_first_run */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001051 rtp.Visit(iget);
1052 }
1053 return iget;
1054}
1055
Vladimir Marko354efa62016-02-04 19:46:56 +00001056HInstanceFieldSet* HInliner::CreateInstanceFieldSet(Handle<mirror::DexCache> dex_cache,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001057 uint32_t field_index,
1058 HInstruction* obj,
1059 HInstruction* value)
1060 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001061 size_t pointer_size = InstructionSetPointerSize(codegen_->GetInstructionSet());
1062 ArtField* resolved_field = dex_cache->GetResolvedField(field_index, pointer_size);
1063 DCHECK(resolved_field != nullptr);
1064 HInstanceFieldSet* iput = new (graph_->GetArena()) HInstanceFieldSet(
1065 obj,
1066 value,
1067 resolved_field->GetTypeAsPrimitiveType(),
1068 resolved_field->GetOffset(),
1069 resolved_field->IsVolatile(),
1070 field_index,
1071 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Marko354efa62016-02-04 19:46:56 +00001072 *dex_cache->GetDexFile(),
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001073 dex_cache,
Vladimir Markoadda4352016-01-29 10:24:41 +00001074 // Read barrier generates a runtime call in slow path and we need a valid
1075 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1076 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001077 return iput;
1078}
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001079
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001080bool HInliner::TryBuildAndInlineHelper(HInvoke* invoke_instruction,
1081 ArtMethod* resolved_method,
1082 bool same_dex_file,
1083 HInstruction** return_replacement) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001084 ScopedObjectAccess soa(Thread::Current());
1085 const DexFile::CodeItem* code_item = resolved_method->GetCodeItem();
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001086 const DexFile& callee_dex_file = *resolved_method->GetDexFile();
1087 uint32_t method_index = resolved_method->GetDexMethodIndex();
Calin Juravle2e768302015-07-28 14:41:11 +00001088 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Mathieu Chartier736b5602015-09-02 14:54:11 -07001089 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001090 DexCompilationUnit dex_compilation_unit(
Nicolas Geoffray5b82d332016-02-18 14:22:32 +00001091 caller_compilation_unit_.GetClassLoader(),
1092 class_linker,
1093 callee_dex_file,
1094 code_item,
1095 resolved_method->GetDeclaringClass()->GetDexClassDefIndex(),
1096 method_index,
1097 resolved_method->GetAccessFlags(),
1098 /* verified_method */ nullptr,
1099 dex_cache);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001100
Calin Juravle3cd4fc82015-05-14 15:15:42 +01001101 bool requires_ctor_barrier = false;
1102
1103 if (dex_compilation_unit.IsConstructor()) {
1104 // If it's a super invocation and we already generate a barrier there's no need
1105 // to generate another one.
1106 // We identify super calls by looking at the "this" pointer. If its value is the
1107 // same as the local "this" pointer then we must have a super invocation.
1108 bool is_super_invocation = invoke_instruction->InputAt(0)->IsParameterValue()
1109 && invoke_instruction->InputAt(0)->AsParameterValue()->IsThis();
1110 if (is_super_invocation && graph_->ShouldGenerateConstructorBarrier()) {
1111 requires_ctor_barrier = false;
1112 } else {
1113 Thread* self = Thread::Current();
1114 requires_ctor_barrier = compiler_driver_->RequiresConstructorBarrier(self,
1115 dex_compilation_unit.GetDexFile(),
1116 dex_compilation_unit.GetClassDefIndex());
1117 }
1118 }
1119
Nicolas Geoffray35071052015-06-09 15:43:38 +01001120 InvokeType invoke_type = invoke_instruction->GetOriginalInvokeType();
1121 if (invoke_type == kInterface) {
1122 // We have statically resolved the dispatch. To please the class linker
1123 // at runtime, we change this call as if it was a virtual call.
1124 invoke_type = kVirtual;
1125 }
David Brazdil3f523062016-02-29 16:53:33 +00001126
1127 const int32_t caller_instruction_counter = graph_->GetCurrentInstructionId();
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +00001128 HGraph* callee_graph = new (graph_->GetArena()) HGraph(
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001129 graph_->GetArena(),
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001130 callee_dex_file,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001131 method_index,
Calin Juravle3cd4fc82015-05-14 15:15:42 +01001132 requires_ctor_barrier,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001133 compiler_driver_->GetInstructionSet(),
Nicolas Geoffray35071052015-06-09 15:43:38 +01001134 invoke_type,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001135 graph_->IsDebuggable(),
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001136 /* osr */ false,
David Brazdil3f523062016-02-29 16:53:33 +00001137 caller_instruction_counter);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001138 callee_graph->SetArtMethod(resolved_method);
David Brazdil5e8b1372015-01-23 14:39:08 +00001139
Roland Levillaina8013fd2016-04-04 15:34:31 +01001140 // When they are needed, allocate `inline_stats` on the heap instead
1141 // of on the stack, as Clang might produce a stack frame too large
1142 // for this function, that would not fit the requirements of the
1143 // `-Wframe-larger-than` option.
1144 std::unique_ptr<OptimizingCompilerStats> inline_stats =
1145 (stats_ == nullptr) ? nullptr : MakeUnique<OptimizingCompilerStats>();
David Brazdil5e8b1372015-01-23 14:39:08 +00001146 HGraphBuilder builder(callee_graph,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001147 &dex_compilation_unit,
1148 &outer_compilation_unit_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001149 resolved_method->GetDexFile(),
David Brazdil86ea7ee2016-02-16 09:26:07 +00001150 *code_item,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001151 compiler_driver_,
Roland Levillaina8013fd2016-04-04 15:34:31 +01001152 inline_stats.get(),
Mathieu Chartier736b5602015-09-02 14:54:11 -07001153 resolved_method->GetQuickenedInfo(),
David Brazdildee58d62016-04-07 09:54:26 +00001154 dex_cache,
1155 handles_);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001156
David Brazdildee58d62016-04-07 09:54:26 +00001157 if (builder.BuildGraph() != kAnalysisSuccess) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001158 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001159 << " could not be built, so cannot be inlined";
1160 return false;
1161 }
1162
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001163 if (!RegisterAllocator::CanAllocateRegistersFor(*callee_graph,
1164 compiler_driver_->GetInstructionSet())) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001165 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001166 << " cannot be inlined because of the register allocator";
1167 return false;
1168 }
1169
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001170 size_t parameter_index = 0;
1171 for (HInstructionIterator instructions(callee_graph->GetEntryBlock()->GetInstructions());
1172 !instructions.Done();
1173 instructions.Advance()) {
1174 HInstruction* current = instructions.Current();
1175 if (current->IsParameterValue()) {
1176 HInstruction* argument = invoke_instruction->InputAt(parameter_index++);
1177 if (argument->IsNullConstant()) {
1178 current->ReplaceWith(callee_graph->GetNullConstant());
1179 } else if (argument->IsIntConstant()) {
1180 current->ReplaceWith(callee_graph->GetIntConstant(argument->AsIntConstant()->GetValue()));
1181 } else if (argument->IsLongConstant()) {
1182 current->ReplaceWith(callee_graph->GetLongConstant(argument->AsLongConstant()->GetValue()));
1183 } else if (argument->IsFloatConstant()) {
1184 current->ReplaceWith(
1185 callee_graph->GetFloatConstant(argument->AsFloatConstant()->GetValue()));
1186 } else if (argument->IsDoubleConstant()) {
1187 current->ReplaceWith(
1188 callee_graph->GetDoubleConstant(argument->AsDoubleConstant()->GetValue()));
1189 } else if (argument->GetType() == Primitive::kPrimNot) {
1190 current->SetReferenceTypeInfo(argument->GetReferenceTypeInfo());
1191 current->AsParameterValue()->SetCanBeNull(argument->CanBeNull());
1192 }
1193 }
1194 }
1195
David Brazdil94ab38f2016-06-21 17:48:19 +01001196 // We have replaced formal arguments with actual arguments. If actual types
1197 // are more specific than the declared ones, run RTP again on the inner graph.
1198 if (ArgumentTypesMoreSpecific(invoke_instruction, resolved_method)) {
1199 ReferenceTypePropagation(callee_graph,
1200 dex_compilation_unit.GetDexCache(),
1201 handles_,
1202 /* is_first_run */ false).Run();
1203 }
1204
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001205 size_t number_of_instructions_budget = kMaximumNumberOfHInstructions;
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001206 size_t number_of_inlined_instructions =
1207 RunOptimizations(callee_graph, code_item, dex_compilation_unit);
1208 number_of_instructions_budget += number_of_inlined_instructions;
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +00001209
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001210 // TODO: We should abort only if all predecessors throw. However,
1211 // HGraph::InlineInto currently does not handle an exit block with
1212 // a throw predecessor.
1213 HBasicBlock* exit_block = callee_graph->GetExitBlock();
1214 if (exit_block == nullptr) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001215 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001216 << " could not be inlined because it has an infinite loop";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001217 return false;
1218 }
1219
1220 bool has_throw_predecessor = false;
Vladimir Marko60584552015-09-03 13:35:12 +00001221 for (HBasicBlock* predecessor : exit_block->GetPredecessors()) {
1222 if (predecessor->GetLastInstruction()->IsThrow()) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001223 has_throw_predecessor = true;
1224 break;
1225 }
1226 }
1227 if (has_throw_predecessor) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001228 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001229 << " could not be inlined because one branch always throws";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001230 return false;
1231 }
1232
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001233 HReversePostOrderIterator it(*callee_graph);
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +00001234 it.Advance(); // Past the entry block, it does not contain instructions that prevent inlining.
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001235 size_t number_of_instructions = 0;
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001236
1237 bool can_inline_environment =
1238 total_number_of_dex_registers_ < kMaximumNumberOfCumulatedDexRegisters;
1239
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001240 for (; !it.Done(); it.Advance()) {
1241 HBasicBlock* block = it.Current();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001242
1243 if (block->IsLoopHeader() && block->GetLoopInformation()->IsIrreducible()) {
1244 // Don't inline methods with irreducible loops, they could prevent some
1245 // optimizations to run.
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001246 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001247 << " could not be inlined because it contains an irreducible loop";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001248 return false;
1249 }
1250
1251 for (HInstructionIterator instr_it(block->GetInstructions());
1252 !instr_it.Done();
1253 instr_it.Advance()) {
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001254 if (number_of_instructions++ == number_of_instructions_budget) {
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001255 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001256 << " is not inlined because its caller has reached"
1257 << " its instruction budget limit.";
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001258 return false;
1259 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001260 HInstruction* current = instr_it.Current();
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001261 if (!can_inline_environment && current->NeedsEnvironment()) {
1262 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
1263 << " is not inlined because its caller has reached"
1264 << " its environment budget limit.";
1265 return false;
1266 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001267
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001268 if (!same_dex_file && current->NeedsEnvironment()) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001269 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001270 << " could not be inlined because " << current->DebugName()
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001271 << " needs an environment and is in a different dex file";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001272 return false;
1273 }
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001274
Vladimir Markodc151b22015-10-15 18:02:30 +01001275 if (!same_dex_file && current->NeedsDexCacheOfDeclaringClass()) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001276 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001277 << " could not be inlined because " << current->DebugName()
1278 << " it is in a different dex file and requires access to the dex cache";
1279 return false;
1280 }
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001281
1282 if (current->IsNewInstance() &&
1283 (current->AsNewInstance()->GetEntrypoint() == kQuickAllocObjectWithAccessCheck)) {
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001284 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
1285 << " could not be inlined because it is using an entrypoint"
1286 << " with access checks";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001287 // Allocation entrypoint does not handle inlined frames.
1288 return false;
1289 }
1290
1291 if (current->IsNewArray() &&
1292 (current->AsNewArray()->GetEntrypoint() == kQuickAllocArrayWithAccessCheck)) {
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001293 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
1294 << " could not be inlined because it is using an entrypoint"
1295 << " with access checks";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001296 // Allocation entrypoint does not handle inlined frames.
1297 return false;
1298 }
1299
1300 if (current->IsUnresolvedStaticFieldGet() ||
1301 current->IsUnresolvedInstanceFieldGet() ||
1302 current->IsUnresolvedStaticFieldSet() ||
1303 current->IsUnresolvedInstanceFieldSet()) {
1304 // Entrypoint for unresolved fields does not handle inlined frames.
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001305 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
1306 << " could not be inlined because it is using an unresolved"
1307 << " entrypoint";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001308 return false;
1309 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001310 }
1311 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001312 number_of_inlined_instructions_ += number_of_instructions;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001313
David Brazdil3f523062016-02-29 16:53:33 +00001314 DCHECK_EQ(caller_instruction_counter, graph_->GetCurrentInstructionId())
1315 << "No instructions can be added to the outer graph while inner graph is being built";
1316
1317 const int32_t callee_instruction_counter = callee_graph->GetCurrentInstructionId();
1318 graph_->SetCurrentInstructionId(callee_instruction_counter);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001319 *return_replacement = callee_graph->InlineInto(graph_, invoke_instruction);
David Brazdil3f523062016-02-29 16:53:33 +00001320
1321 DCHECK_EQ(callee_instruction_counter, callee_graph->GetCurrentInstructionId())
1322 << "No instructions can be added to the inner graph during inlining into the outer graph";
1323
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001324 return true;
1325}
Calin Juravle2e768302015-07-28 14:41:11 +00001326
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001327size_t HInliner::RunOptimizations(HGraph* callee_graph,
1328 const DexFile::CodeItem* code_item,
1329 const DexCompilationUnit& dex_compilation_unit) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001330 // Note: if the outermost_graph_ is being compiled OSR, we should not run any
1331 // optimization that could lead to a HDeoptimize. The following optimizations do not.
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001332 HDeadCodeElimination dce(callee_graph, stats_);
1333 HConstantFolding fold(callee_graph);
1334 HSharpening sharpening(callee_graph, codegen_, dex_compilation_unit, compiler_driver_);
1335 InstructionSimplifier simplify(callee_graph, stats_);
1336 IntrinsicsRecognizer intrinsics(callee_graph, compiler_driver_, stats_);
1337
1338 HOptimization* optimizations[] = {
1339 &intrinsics,
1340 &sharpening,
1341 &simplify,
1342 &fold,
1343 &dce,
1344 };
1345
1346 for (size_t i = 0; i < arraysize(optimizations); ++i) {
1347 HOptimization* optimization = optimizations[i];
1348 optimization->Run();
1349 }
1350
1351 size_t number_of_inlined_instructions = 0u;
1352 if (depth_ + 1 < compiler_driver_->GetCompilerOptions().GetInlineDepthLimit()) {
1353 HInliner inliner(callee_graph,
1354 outermost_graph_,
1355 codegen_,
1356 outer_compilation_unit_,
1357 dex_compilation_unit,
1358 compiler_driver_,
1359 handles_,
1360 stats_,
1361 total_number_of_dex_registers_ + code_item->registers_size_,
1362 depth_ + 1);
1363 inliner.Run();
1364 number_of_inlined_instructions += inliner.number_of_inlined_instructions_;
1365 }
1366
1367 return number_of_inlined_instructions;
1368}
1369
David Brazdil94ab38f2016-06-21 17:48:19 +01001370static bool IsReferenceTypeRefinement(ReferenceTypeInfo declared_rti,
1371 bool declared_can_be_null,
1372 HInstruction* actual_obj)
1373 SHARED_REQUIRES(Locks::mutator_lock_) {
1374 if (declared_can_be_null && !actual_obj->CanBeNull()) {
1375 return true;
1376 }
1377
1378 ReferenceTypeInfo actual_rti = actual_obj->GetReferenceTypeInfo();
1379 return (actual_rti.IsExact() && !declared_rti.IsExact()) ||
1380 declared_rti.IsStrictSupertypeOf(actual_rti);
1381}
1382
1383ReferenceTypeInfo HInliner::GetClassRTI(mirror::Class* klass) {
1384 return ReferenceTypePropagation::IsAdmissible(klass)
1385 ? ReferenceTypeInfo::Create(handles_->NewHandle(klass))
1386 : graph_->GetInexactObjectRti();
1387}
1388
1389bool HInliner::ArgumentTypesMoreSpecific(HInvoke* invoke_instruction, ArtMethod* resolved_method) {
1390 // If this is an instance call, test whether the type of the `this` argument
1391 // is more specific than the class which declares the method.
1392 if (!resolved_method->IsStatic()) {
1393 if (IsReferenceTypeRefinement(GetClassRTI(resolved_method->GetDeclaringClass()),
1394 /* declared_can_be_null */ false,
1395 invoke_instruction->InputAt(0u))) {
1396 return true;
1397 }
1398 }
1399
1400 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1401
1402 // Iterate over the list of parameter types and test whether any of the
1403 // actual inputs has a more specific reference type than the type declared in
1404 // the signature.
1405 const DexFile::TypeList* param_list = resolved_method->GetParameterTypeList();
1406 for (size_t param_idx = 0,
1407 input_idx = resolved_method->IsStatic() ? 0 : 1,
1408 e = (param_list == nullptr ? 0 : param_list->Size());
1409 param_idx < e;
1410 ++param_idx, ++input_idx) {
1411 HInstruction* input = invoke_instruction->InputAt(input_idx);
1412 if (input->GetType() == Primitive::kPrimNot) {
1413 mirror::Class* param_cls = resolved_method->GetDexCacheResolvedType(
1414 param_list->GetTypeItem(param_idx).type_idx_,
1415 pointer_size);
1416 if (IsReferenceTypeRefinement(GetClassRTI(param_cls),
1417 /* declared_can_be_null */ true,
1418 input)) {
1419 return true;
1420 }
1421 }
1422 }
1423
1424 return false;
1425}
1426
1427bool HInliner::ReturnTypeMoreSpecific(HInvoke* invoke_instruction,
1428 HInstruction* return_replacement) {
Alex Light68289a52015-12-15 17:30:30 -08001429 // Check the integrity of reference types and run another type propagation if needed.
David Brazdil4833f5a2015-12-16 10:37:39 +00001430 if (return_replacement != nullptr) {
1431 if (return_replacement->GetType() == Primitive::kPrimNot) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001432 // Test if the return type is a refinement of the declared return type.
1433 if (IsReferenceTypeRefinement(invoke_instruction->GetReferenceTypeInfo(),
1434 /* declared_can_be_null */ true,
1435 return_replacement)) {
1436 return true;
1437 }
1438 } else if (return_replacement->IsInstanceOf()) {
1439 // Inlining InstanceOf into an If may put a tighter bound on reference types.
1440 return true;
1441 }
1442 }
1443
1444 return false;
1445}
1446
1447void HInliner::FixUpReturnReferenceType(ArtMethod* resolved_method,
1448 HInstruction* return_replacement) {
1449 if (return_replacement != nullptr) {
1450 if (return_replacement->GetType() == Primitive::kPrimNot) {
David Brazdil4833f5a2015-12-16 10:37:39 +00001451 if (!return_replacement->GetReferenceTypeInfo().IsValid()) {
1452 // Make sure that we have a valid type for the return. We may get an invalid one when
1453 // we inline invokes with multiple branches and create a Phi for the result.
1454 // TODO: we could be more precise by merging the phi inputs but that requires
1455 // some functionality from the reference type propagation.
1456 DCHECK(return_replacement->IsPhi());
1457 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray44fd0e52016-03-16 15:16:06 +00001458 mirror::Class* cls = resolved_method->GetReturnType(false /* resolve */, pointer_size);
David Brazdil94ab38f2016-06-21 17:48:19 +01001459 return_replacement->SetReferenceTypeInfo(GetClassRTI(cls));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001460 }
Calin Juravlecdfed3d2015-10-26 14:05:01 +00001461 }
Calin Juravle2e768302015-07-28 14:41:11 +00001462 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001463}
1464
1465} // namespace art