blob: 6d5f6eb55e1d32b2254601910b3756b4a9138d79 [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"
24#include "driver/compiler_driver-inl.h"
Calin Juravleec748352015-07-29 13:52:12 +010025#include "driver/compiler_options.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000026#include "driver/dex_compilation_unit.h"
27#include "instruction_simplifier.h"
Scott Wakelingd60a1af2015-07-22 14:32:44 +010028#include "intrinsics.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000029#include "mirror/class_loader.h"
30#include "mirror/dex_cache.h"
31#include "nodes.h"
Nicolas Geoffray335005e2015-06-25 10:01:47 +010032#include "optimizing_compiler.h"
Nicolas Geoffray454a4812015-06-09 10:37:32 +010033#include "reference_type_propagation.h"
Nicolas Geoffray259136f2014-12-17 23:21:58 +000034#include "register_allocator.h"
Vladimir Markodc151b22015-10-15 18:02:30 +010035#include "sharpening.h"
David Brazdild9510df2015-11-04 23:30:22 +000036#include "ssa_builder.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000037#include "ssa_phi_elimination.h"
38#include "scoped_thread_state_change.h"
39#include "thread.h"
Calin Juravlef1c6d9e2015-04-13 18:42:21 +010040#include "dex/verified_method.h"
41#include "dex/verification_results.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000042
43namespace art {
44
Nicolas Geoffrayfcb76132015-12-17 12:43:00 +000045static constexpr size_t kMaximumNumberOfHInstructions = 32;
46
47// Limit the number of dex registers that we accumulate while inlining
48// to avoid creating large amount of nested environments.
49static constexpr size_t kMaximumNumberOfCumulatedDexRegisters = 64;
50
51// Avoid inlining within a huge method due to memory pressure.
52static constexpr size_t kMaximumCodeUnitSize = 4096;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -070053
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000054void HInliner::Run() {
Calin Juravle8f96df82015-07-29 15:58:48 +010055 const CompilerOptions& compiler_options = compiler_driver_->GetCompilerOptions();
56 if ((compiler_options.GetInlineDepthLimit() == 0)
57 || (compiler_options.GetInlineMaxCodeUnits() == 0)) {
58 return;
59 }
Nicolas Geoffrayfcb76132015-12-17 12:43:00 +000060 if (caller_compilation_unit_.GetCodeItem()->insns_size_in_code_units_ > kMaximumCodeUnitSize) {
61 return;
62 }
Nicolas Geoffraye50b8d22015-03-13 08:57:42 +000063 if (graph_->IsDebuggable()) {
64 // For simplicity, we currently never inline when the graph is debuggable. This avoids
65 // doing some logic in the runtime to discover if a method could have been inlined.
66 return;
67 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +010068 const ArenaVector<HBasicBlock*>& blocks = graph_->GetReversePostOrder();
69 DCHECK(!blocks.empty());
70 HBasicBlock* next_block = blocks[0];
71 for (size_t i = 0; i < blocks.size(); ++i) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +010072 // Because we are changing the graph when inlining, we need to remember the next block.
73 // This avoids doing the inlining work again on the inlined blocks.
Vladimir Markofa6b93c2015-09-15 10:15:55 +010074 if (blocks[i] != next_block) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +010075 continue;
76 }
77 HBasicBlock* block = next_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +010078 next_block = (i == blocks.size() - 1) ? nullptr : blocks[i + 1];
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 Geoffray79041292015-03-26 10:05:54 +000084 // We use the original invoke type to ensure the resolution of the called method
85 // works properly.
Vladimir Marko58155012015-08-19 12:49:41 +000086 if (!TryInline(call)) {
Nicolas Geoffray335005e2015-06-25 10:01:47 +010087 if (kIsDebugBuild && IsCompilingWithCoreImage()) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000088 std::string callee_name =
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +000089 PrettyMethod(call->GetDexMethodIndex(), *outer_compilation_unit_.GetDexFile());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000090 bool should_inline = callee_name.find("$inline$") != std::string::npos;
91 CHECK(!should_inline) << "Could not inline " << callee_name;
92 }
Guillaume "Vermeille" Sancheze918d382015-06-03 15:32:41 +010093 } else {
Nicolas Geoffray335005e2015-06-25 10:01:47 +010094 if (kIsDebugBuild && IsCompilingWithCoreImage()) {
Guillaume "Vermeille" Sancheze918d382015-06-03 15:32:41 +010095 std::string callee_name =
96 PrettyMethod(call->GetDexMethodIndex(), *outer_compilation_unit_.GetDexFile());
97 bool must_not_inline = callee_name.find("$noinline$") != std::string::npos;
98 CHECK(!must_not_inline) << "Should not have inlined " << callee_name;
99 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000100 }
101 }
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000102 instruction = next;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000103 }
104 }
105}
106
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100107static bool IsMethodOrDeclaringClassFinal(ArtMethod* method)
Mathieu Chartier90443472015-07-16 20:32:27 -0700108 SHARED_REQUIRES(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100109 return method->IsFinal() || method->GetDeclaringClass()->IsFinal();
110}
111
112/**
113 * Given the `resolved_method` looked up in the dex cache, try to find
114 * the actual runtime target of an interface or virtual call.
115 * Return nullptr if the runtime target cannot be proven.
116 */
117static ArtMethod* FindVirtualOrInterfaceTarget(HInvoke* invoke, ArtMethod* resolved_method)
Mathieu Chartier90443472015-07-16 20:32:27 -0700118 SHARED_REQUIRES(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100119 if (IsMethodOrDeclaringClassFinal(resolved_method)) {
120 // No need to lookup further, the resolved method will be the target.
121 return resolved_method;
122 }
123
124 HInstruction* receiver = invoke->InputAt(0);
125 if (receiver->IsNullCheck()) {
126 // Due to multiple levels of inlining within the same pass, it might be that
127 // null check does not have the reference type of the actual receiver.
128 receiver = receiver->InputAt(0);
129 }
130 ReferenceTypeInfo info = receiver->GetReferenceTypeInfo();
Calin Juravle2e768302015-07-28 14:41:11 +0000131 DCHECK(info.IsValid()) << "Invalid RTI for " << receiver->DebugName();
132 if (!info.IsExact()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100133 // We currently only support inlining with known receivers.
134 // TODO: Remove this check, we should be able to inline final methods
135 // on unknown receivers.
136 return nullptr;
137 } else if (info.GetTypeHandle()->IsInterface()) {
138 // Statically knowing that the receiver has an interface type cannot
139 // help us find what is the target method.
140 return nullptr;
141 } else if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(info.GetTypeHandle().Get())) {
142 // The method that we're trying to call is not in the receiver's class or super classes.
143 return nullptr;
144 }
145
146 ClassLinker* cl = Runtime::Current()->GetClassLinker();
147 size_t pointer_size = cl->GetImagePointerSize();
148 if (invoke->IsInvokeInterface()) {
149 resolved_method = info.GetTypeHandle()->FindVirtualMethodForInterface(
150 resolved_method, pointer_size);
151 } else {
152 DCHECK(invoke->IsInvokeVirtual());
153 resolved_method = info.GetTypeHandle()->FindVirtualMethodForVirtual(
154 resolved_method, pointer_size);
155 }
156
157 if (resolved_method == nullptr) {
158 // The information we had on the receiver was not enough to find
159 // the target method. Since we check above the exact type of the receiver,
160 // the only reason this can happen is an IncompatibleClassChangeError.
161 return nullptr;
Alex Light9139e002015-10-09 15:59:48 -0700162 } else if (!resolved_method->IsInvokable()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100163 // The information we had on the receiver was not enough to find
164 // the target method. Since we check above the exact type of the receiver,
165 // the only reason this can happen is an IncompatibleClassChangeError.
166 return nullptr;
167 } else if (IsMethodOrDeclaringClassFinal(resolved_method)) {
168 // A final method has to be the target method.
169 return resolved_method;
170 } else if (info.IsExact()) {
171 // If we found a method and the receiver's concrete type is statically
172 // known, we know for sure the target.
173 return resolved_method;
174 } else {
175 // Even if we did find a method, the receiver type was not enough to
176 // statically find the runtime target.
177 return nullptr;
178 }
179}
180
181static uint32_t FindMethodIndexIn(ArtMethod* method,
182 const DexFile& dex_file,
183 uint32_t referrer_index)
Mathieu Chartier90443472015-07-16 20:32:27 -0700184 SHARED_REQUIRES(Locks::mutator_lock_) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100185 if (IsSameDexFile(*method->GetDexFile(), dex_file)) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100186 return method->GetDexMethodIndex();
187 } else {
188 return method->FindDexMethodIndexInOtherDexFile(dex_file, referrer_index);
189 }
190}
191
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100192static uint32_t FindClassIndexIn(mirror::Class* cls, const DexFile& dex_file)
193 SHARED_REQUIRES(Locks::mutator_lock_) {
194 if (cls->GetDexCache() == nullptr) {
195 DCHECK(cls->IsArrayClass());
196 // TODO: find the class in `dex_file`.
197 return DexFile::kDexNoIndex;
198 } else if (cls->GetDexTypeIndex() == DexFile::kDexNoIndex16) {
199 // TODO: deal with proxy classes.
200 return DexFile::kDexNoIndex;
201 } else if (IsSameDexFile(cls->GetDexFile(), dex_file)) {
202 // Update the dex cache to ensure the class is in. The generated code will
203 // consider it is. We make it safe by updating the dex cache, as other
204 // dex files might also load the class, and there is no guarantee the dex
205 // cache of the dex file of the class will be updated.
206 if (cls->GetDexCache()->GetResolvedType(cls->GetDexTypeIndex()) == nullptr) {
207 cls->GetDexCache()->SetResolvedType(cls->GetDexTypeIndex(), cls);
208 }
209 return cls->GetDexTypeIndex();
210 } else {
211 // TODO: find the class in `dex_file`.
212 return DexFile::kDexNoIndex;
213 }
214}
215
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700216bool HInliner::TryInline(HInvoke* invoke_instruction) {
Calin Juravle175dc732015-08-25 15:42:32 +0100217 if (invoke_instruction->IsInvokeUnresolved()) {
218 return false; // Don't bother to move further if we know the method is unresolved.
219 }
220
Vladimir Marko58155012015-08-19 12:49:41 +0000221 uint32_t method_index = invoke_instruction->GetDexMethodIndex();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000222 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000223 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
224 VLOG(compiler) << "Try inlining " << PrettyMethod(method_index, caller_dex_file);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000225
Nicolas Geoffray35071052015-06-09 15:43:38 +0100226 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
227 // We can query the dex cache directly. The verifier has populated it already.
Vladimir Marko58155012015-08-19 12:49:41 +0000228 ArtMethod* resolved_method;
229 if (invoke_instruction->IsInvokeStaticOrDirect()) {
Nicolas Geoffraye5234232015-12-02 09:06:11 +0000230 if (invoke_instruction->AsInvokeStaticOrDirect()->IsStringInit()) {
231 VLOG(compiler) << "Not inlining a String.<init> method";
232 return false;
233 }
Vladimir Marko58155012015-08-19 12:49:41 +0000234 MethodReference ref = invoke_instruction->AsInvokeStaticOrDirect()->GetTargetMethod();
Mathieu Chartier736b5602015-09-02 14:54:11 -0700235 mirror::DexCache* const dex_cache = (&caller_dex_file == ref.dex_file)
236 ? caller_compilation_unit_.GetDexCache().Get()
237 : class_linker->FindDexCache(soa.Self(), *ref.dex_file);
238 resolved_method = dex_cache->GetResolvedMethod(
Vladimir Marko58155012015-08-19 12:49:41 +0000239 ref.dex_method_index, class_linker->GetImagePointerSize());
240 } else {
Mathieu Chartier736b5602015-09-02 14:54:11 -0700241 resolved_method = caller_compilation_unit_.GetDexCache().Get()->GetResolvedMethod(
Vladimir Marko58155012015-08-19 12:49:41 +0000242 method_index, class_linker->GetImagePointerSize());
243 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000244
Mathieu Chartiere401d142015-04-22 13:56:20 -0700245 if (resolved_method == nullptr) {
Calin Juravle175dc732015-08-25 15:42:32 +0100246 // TODO: Can this still happen?
Nicolas Geoffray35071052015-06-09 15:43:38 +0100247 // Method cannot be resolved if it is in another dex file we do not have access to.
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000248 VLOG(compiler) << "Method cannot be resolved " << PrettyMethod(method_index, caller_dex_file);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000249 return false;
250 }
251
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100252 if (invoke_instruction->IsInvokeStaticOrDirect()) {
253 return TryInline(invoke_instruction, resolved_method);
254 }
255
256 // Check if we can statically find the method.
257 ArtMethod* actual_method = FindVirtualOrInterfaceTarget(invoke_instruction, resolved_method);
258 if (actual_method != nullptr) {
259 return TryInline(invoke_instruction, actual_method);
260 }
261
262 // Check if we can use an inline cache.
263 ArtMethod* caller = graph_->GetArtMethod();
264 size_t pointer_size = class_linker->GetImagePointerSize();
265 // Under JIT, we should always know the caller.
266 DCHECK(!Runtime::Current()->UseJit() || (caller != nullptr));
267 if (caller != nullptr && caller->GetProfilingInfo(pointer_size) != nullptr) {
268 ProfilingInfo* profiling_info = caller->GetProfilingInfo(pointer_size);
269 const InlineCache& ic = *profiling_info->GetInlineCache(invoke_instruction->GetDexPc());
270 if (ic.IsUnitialized()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100271 VLOG(compiler) << "Interface or virtual call to "
272 << PrettyMethod(method_index, caller_dex_file)
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100273 << " is not hit and not inlined";
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100274 return false;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100275 } else if (ic.IsMonomorphic()) {
276 MaybeRecordStat(kMonomorphicCall);
277 return TryInlineMonomorphicCall(invoke_instruction, resolved_method, ic);
278 } else if (ic.IsPolymorphic()) {
279 MaybeRecordStat(kPolymorphicCall);
280 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, ic);
281 } else {
282 DCHECK(ic.IsMegamorphic());
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100283 VLOG(compiler) << "Interface or virtual call to "
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100284 << PrettyMethod(method_index, caller_dex_file)
285 << " is megamorphic and not inlined";
286 MaybeRecordStat(kMegamorphicCall);
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100287 return false;
288 }
289 }
290
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100291 VLOG(compiler) << "Interface or virtual call to "
292 << PrettyMethod(method_index, caller_dex_file)
293 << " could not be statically determined";
294 return false;
295}
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000296
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100297bool HInliner::TryInlineMonomorphicCall(HInvoke* invoke_instruction,
298 ArtMethod* resolved_method,
299 const InlineCache& ic) {
300 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
301 uint32_t class_index = FindClassIndexIn(ic.GetMonomorphicType(), caller_dex_file);
302 if (class_index == DexFile::kDexNoIndex) {
303 VLOG(compiler) << "Call to " << PrettyMethod(resolved_method)
304 << " from inline cache is not inlined because its class is not"
305 << " accessible to the caller";
306 return false;
307 }
308
309 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
310 size_t pointer_size = class_linker->GetImagePointerSize();
311 if (invoke_instruction->IsInvokeInterface()) {
312 resolved_method = ic.GetMonomorphicType()->FindVirtualMethodForInterface(
313 resolved_method, pointer_size);
314 } else {
315 DCHECK(invoke_instruction->IsInvokeVirtual());
316 resolved_method = ic.GetMonomorphicType()->FindVirtualMethodForVirtual(
317 resolved_method, pointer_size);
318 }
319 DCHECK(resolved_method != nullptr);
320 HInstruction* receiver = invoke_instruction->InputAt(0);
321 HInstruction* cursor = invoke_instruction->GetPrevious();
322 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
323
324 if (!TryInline(invoke_instruction, resolved_method, /* do_rtp */ false)) {
325 return false;
326 }
327
328 // We successfully inlined, now add a guard.
329 ArtField* field = class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0);
330 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
331 HInstanceFieldGet* field_get = new (graph_->GetArena()) HInstanceFieldGet(
332 receiver,
333 Primitive::kPrimNot,
334 field->GetOffset(),
335 field->IsVolatile(),
336 field->GetDexFieldIndex(),
337 field->GetDeclaringClass()->GetDexClassDefIndex(),
338 *field->GetDexFile(),
339 handles_->NewHandle(field->GetDexCache()),
340 invoke_instruction->GetDexPc());
341
342 bool is_referrer =
343 (ic.GetMonomorphicType() == outermost_graph_->GetArtMethod()->GetDeclaringClass());
344 HLoadClass* load_class = new (graph_->GetArena()) HLoadClass(graph_->GetCurrentMethod(),
345 class_index,
346 caller_dex_file,
347 is_referrer,
348 invoke_instruction->GetDexPc(),
349 /* needs_access_check */ false,
350 /* is_in_dex_cache */ true);
351
352 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(load_class, field_get);
353 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
354 compare, invoke_instruction->GetDexPc());
355 // TODO: Extend reference type propagation to understand the guard.
356 if (cursor != nullptr) {
357 bb_cursor->InsertInstructionAfter(load_class, cursor);
358 } else {
359 bb_cursor->InsertInstructionBefore(load_class, bb_cursor->GetFirstInstruction());
360 }
361 bb_cursor->InsertInstructionAfter(field_get, load_class);
362 bb_cursor->InsertInstructionAfter(compare, field_get);
363 bb_cursor->InsertInstructionAfter(deoptimize, compare);
364 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
365
366 // Run type propagation to get the guard typed, and eventually propagate the
367 // type of the receiver.
368 ReferenceTypePropagation rtp_fixup(graph_, handles_);
369 rtp_fixup.Run();
370
371 MaybeRecordStat(kInlinedMonomorphicCall);
372 return true;
373}
374
375bool HInliner::TryInlinePolymorphicCall(HInvoke* invoke_instruction ATTRIBUTE_UNUSED,
376 ArtMethod* resolved_method,
377 const InlineCache& ic ATTRIBUTE_UNUSED) {
378 // TODO
379 VLOG(compiler) << "Unimplemented polymorphic inlining for "
380 << PrettyMethod(resolved_method);
381 return false;
382}
383
384bool HInliner::TryInline(HInvoke* invoke_instruction, ArtMethod* method, bool do_rtp) {
385 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
386 uint32_t method_index = FindMethodIndexIn(
387 method, caller_dex_file, invoke_instruction->GetDexMethodIndex());
388 if (method_index == DexFile::kDexNoIndex) {
389 VLOG(compiler) << "Call to "
390 << PrettyMethod(method)
391 << " cannot be inlined because unaccessible to caller";
392 return false;
393 }
394
395 bool same_dex_file = IsSameDexFile(*outer_compilation_unit_.GetDexFile(), *method->GetDexFile());
396
397 const DexFile::CodeItem* code_item = method->GetCodeItem();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000398
399 if (code_item == nullptr) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100400 VLOG(compiler) << "Method " << PrettyMethod(method)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000401 << " is not inlined because it is native";
402 return false;
403 }
404
Calin Juravleec748352015-07-29 13:52:12 +0100405 size_t inline_max_code_units = compiler_driver_->GetCompilerOptions().GetInlineMaxCodeUnits();
406 if (code_item->insns_size_in_code_units_ > inline_max_code_units) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100407 VLOG(compiler) << "Method " << PrettyMethod(method)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000408 << " is too big to inline";
409 return false;
410 }
411
412 if (code_item->tries_size_ != 0) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100413 VLOG(compiler) << "Method " << PrettyMethod(method)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000414 << " is not inlined because of try block";
415 return false;
416 }
417
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100418 if (!method->GetDeclaringClass()->IsVerified()) {
419 uint16_t class_def_idx = method->GetDeclaringClass()->GetDexClassDefIndex();
Nicolas Geoffrayccc61972015-10-01 14:34:20 +0100420 if (!compiler_driver_->IsMethodVerifiedWithoutFailures(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100421 method->GetDexMethodIndex(), class_def_idx, *method->GetDexFile())) {
Nicolas Geoffrayccc61972015-10-01 14:34:20 +0100422 VLOG(compiler) << "Method " << PrettyMethod(method_index, caller_dex_file)
423 << " couldn't be verified, so it cannot be inlined";
424 return false;
425 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000426 }
427
Roland Levillain4c0eb422015-04-24 16:43:49 +0100428 if (invoke_instruction->IsInvokeStaticOrDirect() &&
429 invoke_instruction->AsInvokeStaticOrDirect()->IsStaticWithImplicitClinitCheck()) {
430 // Case of a static method that cannot be inlined because it implicitly
431 // requires an initialization check of its declaring class.
432 VLOG(compiler) << "Method " << PrettyMethod(method_index, caller_dex_file)
433 << " is not inlined because it is static and requires a clinit"
434 << " check that cannot be emitted due to Dex cache limitations";
435 return false;
436 }
437
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100438 if (!TryBuildAndInline(method, invoke_instruction, same_dex_file, do_rtp)) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +0000439 return false;
440 }
441
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000442 VLOG(compiler) << "Successfully inlined " << PrettyMethod(method_index, caller_dex_file);
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +0000443 MaybeRecordStat(kInlinedInvoke);
444 return true;
445}
446
Mathieu Chartiere401d142015-04-22 13:56:20 -0700447bool HInliner::TryBuildAndInline(ArtMethod* resolved_method,
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +0000448 HInvoke* invoke_instruction,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100449 bool same_dex_file,
450 bool do_rtp) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +0000451 ScopedObjectAccess soa(Thread::Current());
452 const DexFile::CodeItem* code_item = resolved_method->GetCodeItem();
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100453 const DexFile& callee_dex_file = *resolved_method->GetDexFile();
454 uint32_t method_index = resolved_method->GetDexMethodIndex();
Calin Juravle2e768302015-07-28 14:41:11 +0000455 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Mathieu Chartier736b5602015-09-02 14:54:11 -0700456 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000457 DexCompilationUnit dex_compilation_unit(
458 nullptr,
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000459 caller_compilation_unit_.GetClassLoader(),
Calin Juravle2e768302015-07-28 14:41:11 +0000460 class_linker,
Nicolas Geoffray8dbf0cf2015-08-11 02:14:38 +0000461 callee_dex_file,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000462 code_item,
463 resolved_method->GetDeclaringClass()->GetDexClassDefIndex(),
Nicolas Geoffray8dbf0cf2015-08-11 02:14:38 +0000464 method_index,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000465 resolved_method->GetAccessFlags(),
Mathieu Chartier736b5602015-09-02 14:54:11 -0700466 compiler_driver_->GetVerifiedMethod(&callee_dex_file, method_index),
467 dex_cache);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000468
Calin Juravle3cd4fc82015-05-14 15:15:42 +0100469 bool requires_ctor_barrier = false;
470
471 if (dex_compilation_unit.IsConstructor()) {
472 // If it's a super invocation and we already generate a barrier there's no need
473 // to generate another one.
474 // We identify super calls by looking at the "this" pointer. If its value is the
475 // same as the local "this" pointer then we must have a super invocation.
476 bool is_super_invocation = invoke_instruction->InputAt(0)->IsParameterValue()
477 && invoke_instruction->InputAt(0)->AsParameterValue()->IsThis();
478 if (is_super_invocation && graph_->ShouldGenerateConstructorBarrier()) {
479 requires_ctor_barrier = false;
480 } else {
481 Thread* self = Thread::Current();
482 requires_ctor_barrier = compiler_driver_->RequiresConstructorBarrier(self,
483 dex_compilation_unit.GetDexFile(),
484 dex_compilation_unit.GetClassDefIndex());
485 }
486 }
487
Nicolas Geoffray35071052015-06-09 15:43:38 +0100488 InvokeType invoke_type = invoke_instruction->GetOriginalInvokeType();
489 if (invoke_type == kInterface) {
490 // We have statically resolved the dispatch. To please the class linker
491 // at runtime, we change this call as if it was a virtual call.
492 invoke_type = kVirtual;
493 }
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +0000494 HGraph* callee_graph = new (graph_->GetArena()) HGraph(
Nicolas Geoffray0a23d742015-05-07 11:57:35 +0100495 graph_->GetArena(),
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100496 callee_dex_file,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +0100497 method_index,
Calin Juravle3cd4fc82015-05-14 15:15:42 +0100498 requires_ctor_barrier,
Mathieu Chartiere401d142015-04-22 13:56:20 -0700499 compiler_driver_->GetInstructionSet(),
Nicolas Geoffray35071052015-06-09 15:43:38 +0100500 invoke_type,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +0100501 graph_->IsDebuggable(),
502 graph_->GetCurrentInstructionId());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100503 callee_graph->SetArtMethod(resolved_method);
David Brazdil5e8b1372015-01-23 14:39:08 +0000504
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000505 OptimizingCompilerStats inline_stats;
David Brazdil5e8b1372015-01-23 14:39:08 +0000506 HGraphBuilder builder(callee_graph,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000507 &dex_compilation_unit,
508 &outer_compilation_unit_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000509 resolved_method->GetDexFile(),
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000510 compiler_driver_,
Nicolas Geoffray9523a3e2015-07-17 11:51:28 +0000511 &inline_stats,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700512 resolved_method->GetQuickenedInfo(),
513 dex_cache);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000514
David Brazdil5e8b1372015-01-23 14:39:08 +0000515 if (!builder.BuildGraph(*code_item)) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100516 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000517 << " could not be built, so cannot be inlined";
518 return false;
519 }
520
Nicolas Geoffray259136f2014-12-17 23:21:58 +0000521 if (!RegisterAllocator::CanAllocateRegistersFor(*callee_graph,
522 compiler_driver_->GetInstructionSet())) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100523 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffray259136f2014-12-17 23:21:58 +0000524 << " cannot be inlined because of the register allocator";
525 return false;
526 }
527
David Brazdild9510df2015-11-04 23:30:22 +0000528 if (callee_graph->TryBuildingSsa(handles_) != kBuildSsaSuccess) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100529 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000530 << " could not be transformed to SSA";
531 return false;
532 }
533
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700534 size_t parameter_index = 0;
535 for (HInstructionIterator instructions(callee_graph->GetEntryBlock()->GetInstructions());
536 !instructions.Done();
537 instructions.Advance()) {
538 HInstruction* current = instructions.Current();
539 if (current->IsParameterValue()) {
540 HInstruction* argument = invoke_instruction->InputAt(parameter_index++);
541 if (argument->IsNullConstant()) {
542 current->ReplaceWith(callee_graph->GetNullConstant());
543 } else if (argument->IsIntConstant()) {
544 current->ReplaceWith(callee_graph->GetIntConstant(argument->AsIntConstant()->GetValue()));
545 } else if (argument->IsLongConstant()) {
546 current->ReplaceWith(callee_graph->GetLongConstant(argument->AsLongConstant()->GetValue()));
547 } else if (argument->IsFloatConstant()) {
548 current->ReplaceWith(
549 callee_graph->GetFloatConstant(argument->AsFloatConstant()->GetValue()));
550 } else if (argument->IsDoubleConstant()) {
551 current->ReplaceWith(
552 callee_graph->GetDoubleConstant(argument->AsDoubleConstant()->GetValue()));
553 } else if (argument->GetType() == Primitive::kPrimNot) {
554 current->SetReferenceTypeInfo(argument->GetReferenceTypeInfo());
555 current->AsParameterValue()->SetCanBeNull(argument->CanBeNull());
556 }
557 }
558 }
559
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000560 // Run simple optimizations on the graph.
Calin Juravle7a9c8852015-04-21 14:07:50 +0100561 HDeadCodeElimination dce(callee_graph, stats_);
Nicolas Geoffraye34648d2015-11-23 08:59:07 +0000562 HConstantFolding fold(callee_graph);
Vladimir Markodc151b22015-10-15 18:02:30 +0100563 HSharpening sharpening(callee_graph, codegen_, dex_compilation_unit, compiler_driver_);
Calin Juravleacf735c2015-02-12 15:25:22 +0000564 InstructionSimplifier simplify(callee_graph, stats_);
Nicolas Geoffraye34648d2015-11-23 08:59:07 +0000565 IntrinsicsRecognizer intrinsics(callee_graph, compiler_driver_);
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000566
567 HOptimization* optimizations[] = {
Scott Wakelingd60a1af2015-07-22 14:32:44 +0100568 &intrinsics,
Vladimir Markodc151b22015-10-15 18:02:30 +0100569 &sharpening,
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000570 &simplify,
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700571 &fold,
Vladimir Marko9e23df52015-11-10 17:14:35 +0000572 &dce,
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000573 };
574
575 for (size_t i = 0; i < arraysize(optimizations); ++i) {
576 HOptimization* optimization = optimizations[i];
577 optimization->Run();
578 }
579
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700580 size_t number_of_instructions_budget = kMaximumNumberOfHInstructions;
Calin Juravleec748352015-07-29 13:52:12 +0100581 if (depth_ + 1 < compiler_driver_->GetCompilerOptions().GetInlineDepthLimit()) {
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000582 HInliner inliner(callee_graph,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100583 outermost_graph_,
Vladimir Markodc151b22015-10-15 18:02:30 +0100584 codegen_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000585 outer_compilation_unit_,
586 dex_compilation_unit,
587 compiler_driver_,
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100588 handles_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000589 stats_,
Nicolas Geoffrayfcb76132015-12-17 12:43:00 +0000590 total_number_of_dex_registers_ + code_item->registers_size_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000591 depth_ + 1);
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000592 inliner.Run();
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700593 number_of_instructions_budget += inliner.number_of_inlined_instructions_;
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000594 }
595
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100596 // TODO: We should abort only if all predecessors throw. However,
597 // HGraph::InlineInto currently does not handle an exit block with
598 // a throw predecessor.
599 HBasicBlock* exit_block = callee_graph->GetExitBlock();
600 if (exit_block == nullptr) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100601 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100602 << " could not be inlined because it has an infinite loop";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100603 return false;
604 }
605
606 bool has_throw_predecessor = false;
Vladimir Marko60584552015-09-03 13:35:12 +0000607 for (HBasicBlock* predecessor : exit_block->GetPredecessors()) {
608 if (predecessor->GetLastInstruction()->IsThrow()) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100609 has_throw_predecessor = true;
610 break;
611 }
612 }
613 if (has_throw_predecessor) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100614 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100615 << " could not be inlined because one branch always throws";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100616 return false;
617 }
618
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000619 HReversePostOrderIterator it(*callee_graph);
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000620 it.Advance(); // Past the entry block, it does not contain instructions that prevent inlining.
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700621 size_t number_of_instructions = 0;
Nicolas Geoffrayfcb76132015-12-17 12:43:00 +0000622
623 bool can_inline_environment =
624 total_number_of_dex_registers_ < kMaximumNumberOfCumulatedDexRegisters;
625
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000626 for (; !it.Done(); it.Advance()) {
627 HBasicBlock* block = it.Current();
628 if (block->IsLoopHeader()) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100629 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000630 << " could not be inlined because it contains a loop";
631 return false;
632 }
633
634 for (HInstructionIterator instr_it(block->GetInstructions());
635 !instr_it.Done();
636 instr_it.Advance()) {
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700637 if (number_of_instructions++ == number_of_instructions_budget) {
638 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffrayfcb76132015-12-17 12:43:00 +0000639 << " is not inlined because its caller has reached"
640 << " its instruction budget limit.";
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700641 return false;
642 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000643 HInstruction* current = instr_it.Current();
Nicolas Geoffrayfcb76132015-12-17 12:43:00 +0000644 if (!can_inline_environment && current->NeedsEnvironment()) {
645 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
646 << " is not inlined because its caller has reached"
647 << " its environment budget limit.";
648 return false;
649 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000650
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100651 if (current->IsInvokeInterface()) {
652 // Disable inlining of interface calls. The cost in case of entering the
653 // resolution conflict is currently too high.
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100654 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100655 << " could not be inlined because it has an interface call.";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000656 return false;
657 }
658
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100659 if (!same_dex_file && current->NeedsEnvironment()) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100660 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000661 << " could not be inlined because " << current->DebugName()
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100662 << " needs an environment and is in a different dex file";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000663 return false;
664 }
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000665
Vladimir Markodc151b22015-10-15 18:02:30 +0100666 if (!same_dex_file && current->NeedsDexCacheOfDeclaringClass()) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100667 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000668 << " could not be inlined because " << current->DebugName()
669 << " it is in a different dex file and requires access to the dex cache";
670 return false;
671 }
Nicolas Geoffrayd9309292015-10-31 22:21:31 +0000672
673 if (current->IsNewInstance() &&
674 (current->AsNewInstance()->GetEntrypoint() == kQuickAllocObjectWithAccessCheck)) {
675 // Allocation entrypoint does not handle inlined frames.
676 return false;
677 }
678
679 if (current->IsNewArray() &&
680 (current->AsNewArray()->GetEntrypoint() == kQuickAllocArrayWithAccessCheck)) {
681 // Allocation entrypoint does not handle inlined frames.
682 return false;
683 }
684
685 if (current->IsUnresolvedStaticFieldGet() ||
686 current->IsUnresolvedInstanceFieldGet() ||
687 current->IsUnresolvedStaticFieldSet() ||
688 current->IsUnresolvedInstanceFieldSet()) {
689 // Entrypoint for unresolved fields does not handle inlined frames.
690 return false;
691 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000692 }
693 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700694 number_of_inlined_instructions_ += number_of_instructions;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000695
Calin Juravle2e768302015-07-28 14:41:11 +0000696 HInstruction* return_replacement = callee_graph->InlineInto(graph_, invoke_instruction);
Calin Juravle214bbcd2015-10-20 14:54:07 +0100697 if (return_replacement != nullptr) {
698 DCHECK_EQ(graph_, return_replacement->GetBlock()->GetGraph());
699 }
Calin Juravle2e768302015-07-28 14:41:11 +0000700
Calin Juravlecdfed3d2015-10-26 14:05:01 +0000701 // Check the integrity of reference types and run another type propagation if needed.
David Brazdild9510df2015-11-04 23:30:22 +0000702 if (return_replacement != nullptr) {
703 if (return_replacement->GetType() == Primitive::kPrimNot) {
704 if (!return_replacement->GetReferenceTypeInfo().IsValid()) {
705 // Make sure that we have a valid type for the return. We may get an invalid one when
706 // we inline invokes with multiple branches and create a Phi for the result.
707 // TODO: we could be more precise by merging the phi inputs but that requires
708 // some functionality from the reference type propagation.
709 DCHECK(return_replacement->IsPhi());
710 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
711 ReferenceTypeInfo::TypeHandle return_handle =
712 handles_->NewHandle(resolved_method->GetReturnType(true /* resolve */, pointer_size));
713 return_replacement->SetReferenceTypeInfo(ReferenceTypeInfo::Create(
714 return_handle, return_handle->CannotBeAssignedFromOtherTypes() /* is_exact */));
715 }
Calin Juravlecdfed3d2015-10-26 14:05:01 +0000716
David Brazdild9510df2015-11-04 23:30:22 +0000717 if (do_rtp) {
718 // If the return type is a refinement of the declared type run the type propagation again.
719 ReferenceTypeInfo return_rti = return_replacement->GetReferenceTypeInfo();
720 ReferenceTypeInfo invoke_rti = invoke_instruction->GetReferenceTypeInfo();
721 if (invoke_rti.IsStrictSupertypeOf(return_rti)
722 || (return_rti.IsExact() && !invoke_rti.IsExact())
723 || !return_replacement->CanBeNull()) {
724 ReferenceTypePropagation(graph_, handles_).Run();
725 }
726 }
727 } else if (return_replacement->IsInstanceOf()) {
728 if (do_rtp) {
729 // Inlining InstanceOf into an If may put a tighter bound on reference types.
730 ReferenceTypePropagation(graph_, handles_).Run();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100731 }
Calin Juravlecdfed3d2015-10-26 14:05:01 +0000732 }
Calin Juravle2e768302015-07-28 14:41:11 +0000733 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +0000734
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000735 return true;
736}
737
738} // namespace art