blob: 68e96fba743089b6cc213c766a903323b1b9e8fa [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 Geoffraye53798a2014-12-01 10:31:54 +000031#include "mirror/class_loader.h"
32#include "mirror/dex_cache.h"
33#include "nodes.h"
Nicolas Geoffray335005e2015-06-25 10:01:47 +010034#include "optimizing_compiler.h"
Nicolas Geoffray454a4812015-06-09 10:37:32 +010035#include "reference_type_propagation.h"
Nicolas Geoffray259136f2014-12-17 23:21:58 +000036#include "register_allocator.h"
Vladimir Markobe10e8e2016-01-22 12:09:44 +000037#include "quick/inline_method_analyser.h"
Vladimir Markodc151b22015-10-15 18:02:30 +010038#include "sharpening.h"
David Brazdil4833f5a2015-12-16 10:37:39 +000039#include "ssa_builder.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000040#include "ssa_phi_elimination.h"
41#include "scoped_thread_state_change.h"
42#include "thread.h"
43
44namespace art {
45
Nicolas Geoffray5949fa02015-12-18 10:57:10 +000046static constexpr size_t kMaximumNumberOfHInstructions = 32;
47
48// Limit the number of dex registers that we accumulate while inlining
49// to avoid creating large amount of nested environments.
50static constexpr size_t kMaximumNumberOfCumulatedDexRegisters = 64;
51
52// Avoid inlining within a huge method due to memory pressure.
53static constexpr size_t kMaximumCodeUnitSize = 4096;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -070054
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000055void HInliner::Run() {
Calin Juravle8f96df82015-07-29 15:58:48 +010056 const CompilerOptions& compiler_options = compiler_driver_->GetCompilerOptions();
57 if ((compiler_options.GetInlineDepthLimit() == 0)
58 || (compiler_options.GetInlineMaxCodeUnits() == 0)) {
59 return;
60 }
Nicolas Geoffray5949fa02015-12-18 10:57:10 +000061 if (caller_compilation_unit_.GetCodeItem()->insns_size_in_code_units_ > kMaximumCodeUnitSize) {
62 return;
63 }
Nicolas Geoffraye50b8d22015-03-13 08:57:42 +000064 if (graph_->IsDebuggable()) {
65 // For simplicity, we currently never inline when the graph is debuggable. This avoids
66 // doing some logic in the runtime to discover if a method could have been inlined.
67 return;
68 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +010069 const ArenaVector<HBasicBlock*>& blocks = graph_->GetReversePostOrder();
70 DCHECK(!blocks.empty());
71 HBasicBlock* next_block = blocks[0];
72 for (size_t i = 0; i < blocks.size(); ++i) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +010073 // Because we are changing the graph when inlining, we need to remember the next block.
74 // This avoids doing the inlining work again on the inlined blocks.
Vladimir Markofa6b93c2015-09-15 10:15:55 +010075 if (blocks[i] != next_block) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +010076 continue;
77 }
78 HBasicBlock* block = next_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +010079 next_block = (i == blocks.size() - 1) ? nullptr : blocks[i + 1];
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +000080 for (HInstruction* instruction = block->GetFirstInstruction(); instruction != nullptr;) {
81 HInstruction* next = instruction->GetNext();
Nicolas Geoffray454a4812015-06-09 10:37:32 +010082 HInvoke* call = instruction->AsInvoke();
Razvan A Lupusoru3e90a962015-03-27 13:44:44 -070083 // As long as the call is not intrinsified, it is worth trying to inline.
84 if (call != nullptr && call->GetIntrinsic() == Intrinsics::kNone) {
Nicolas Geoffray79041292015-03-26 10:05:54 +000085 // We use the original invoke type to ensure the resolution of the called method
86 // works properly.
Vladimir Marko58155012015-08-19 12:49:41 +000087 if (!TryInline(call)) {
Nicolas Geoffray335005e2015-06-25 10:01:47 +010088 if (kIsDebugBuild && IsCompilingWithCoreImage()) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000089 std::string callee_name =
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +000090 PrettyMethod(call->GetDexMethodIndex(), *outer_compilation_unit_.GetDexFile());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000091 bool should_inline = callee_name.find("$inline$") != std::string::npos;
92 CHECK(!should_inline) << "Could not inline " << callee_name;
93 }
Guillaume "Vermeille" Sancheze918d382015-06-03 15:32:41 +010094 } else {
Nicolas Geoffray335005e2015-06-25 10:01:47 +010095 if (kIsDebugBuild && IsCompilingWithCoreImage()) {
Guillaume "Vermeille" Sancheze918d382015-06-03 15:32:41 +010096 std::string callee_name =
97 PrettyMethod(call->GetDexMethodIndex(), *outer_compilation_unit_.GetDexFile());
98 bool must_not_inline = callee_name.find("$noinline$") != std::string::npos;
99 CHECK(!must_not_inline) << "Should not have inlined " << callee_name;
100 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000101 }
102 }
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000103 instruction = next;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000104 }
105 }
106}
107
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100108static bool IsMethodOrDeclaringClassFinal(ArtMethod* method)
Mathieu Chartier90443472015-07-16 20:32:27 -0700109 SHARED_REQUIRES(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100110 return method->IsFinal() || method->GetDeclaringClass()->IsFinal();
111}
112
113/**
114 * Given the `resolved_method` looked up in the dex cache, try to find
115 * the actual runtime target of an interface or virtual call.
116 * Return nullptr if the runtime target cannot be proven.
117 */
118static ArtMethod* FindVirtualOrInterfaceTarget(HInvoke* invoke, ArtMethod* resolved_method)
Mathieu Chartier90443472015-07-16 20:32:27 -0700119 SHARED_REQUIRES(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100120 if (IsMethodOrDeclaringClassFinal(resolved_method)) {
121 // No need to lookup further, the resolved method will be the target.
122 return resolved_method;
123 }
124
125 HInstruction* receiver = invoke->InputAt(0);
126 if (receiver->IsNullCheck()) {
127 // Due to multiple levels of inlining within the same pass, it might be that
128 // null check does not have the reference type of the actual receiver.
129 receiver = receiver->InputAt(0);
130 }
131 ReferenceTypeInfo info = receiver->GetReferenceTypeInfo();
Calin Juravle2e768302015-07-28 14:41:11 +0000132 DCHECK(info.IsValid()) << "Invalid RTI for " << receiver->DebugName();
133 if (!info.IsExact()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100134 // We currently only support inlining with known receivers.
135 // TODO: Remove this check, we should be able to inline final methods
136 // on unknown receivers.
137 return nullptr;
138 } else if (info.GetTypeHandle()->IsInterface()) {
139 // Statically knowing that the receiver has an interface type cannot
140 // help us find what is the target method.
141 return nullptr;
142 } else if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(info.GetTypeHandle().Get())) {
143 // The method that we're trying to call is not in the receiver's class or super classes.
144 return nullptr;
145 }
146
147 ClassLinker* cl = Runtime::Current()->GetClassLinker();
148 size_t pointer_size = cl->GetImagePointerSize();
149 if (invoke->IsInvokeInterface()) {
150 resolved_method = info.GetTypeHandle()->FindVirtualMethodForInterface(
151 resolved_method, pointer_size);
152 } else {
153 DCHECK(invoke->IsInvokeVirtual());
154 resolved_method = info.GetTypeHandle()->FindVirtualMethodForVirtual(
155 resolved_method, pointer_size);
156 }
157
158 if (resolved_method == nullptr) {
159 // The information we had on the receiver was not enough to find
160 // the target method. Since we check above the exact type of the receiver,
161 // the only reason this can happen is an IncompatibleClassChangeError.
162 return nullptr;
Alex Light9139e002015-10-09 15:59:48 -0700163 } else if (!resolved_method->IsInvokable()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100164 // The information we had on the receiver was not enough to find
165 // the target method. Since we check above the exact type of the receiver,
166 // the only reason this can happen is an IncompatibleClassChangeError.
167 return nullptr;
168 } else if (IsMethodOrDeclaringClassFinal(resolved_method)) {
169 // A final method has to be the target method.
170 return resolved_method;
171 } else if (info.IsExact()) {
172 // If we found a method and the receiver's concrete type is statically
173 // known, we know for sure the target.
174 return resolved_method;
175 } else {
176 // Even if we did find a method, the receiver type was not enough to
177 // statically find the runtime target.
178 return nullptr;
179 }
180}
181
182static uint32_t FindMethodIndexIn(ArtMethod* method,
183 const DexFile& dex_file,
184 uint32_t referrer_index)
Mathieu Chartier90443472015-07-16 20:32:27 -0700185 SHARED_REQUIRES(Locks::mutator_lock_) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100186 if (IsSameDexFile(*method->GetDexFile(), dex_file)) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100187 return method->GetDexMethodIndex();
188 } else {
189 return method->FindDexMethodIndexInOtherDexFile(dex_file, referrer_index);
190 }
191}
192
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100193static uint32_t FindClassIndexIn(mirror::Class* cls, const DexFile& dex_file)
194 SHARED_REQUIRES(Locks::mutator_lock_) {
195 if (cls->GetDexCache() == nullptr) {
196 DCHECK(cls->IsArrayClass());
197 // TODO: find the class in `dex_file`.
198 return DexFile::kDexNoIndex;
199 } else if (cls->GetDexTypeIndex() == DexFile::kDexNoIndex16) {
200 // TODO: deal with proxy classes.
201 return DexFile::kDexNoIndex;
202 } else if (IsSameDexFile(cls->GetDexFile(), dex_file)) {
203 // Update the dex cache to ensure the class is in. The generated code will
204 // consider it is. We make it safe by updating the dex cache, as other
205 // dex files might also load the class, and there is no guarantee the dex
206 // cache of the dex file of the class will be updated.
207 if (cls->GetDexCache()->GetResolvedType(cls->GetDexTypeIndex()) == nullptr) {
208 cls->GetDexCache()->SetResolvedType(cls->GetDexTypeIndex(), cls);
209 }
210 return cls->GetDexTypeIndex();
211 } else {
212 // TODO: find the class in `dex_file`.
213 return DexFile::kDexNoIndex;
214 }
215}
216
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700217bool HInliner::TryInline(HInvoke* invoke_instruction) {
Calin Juravle175dc732015-08-25 15:42:32 +0100218 if (invoke_instruction->IsInvokeUnresolved()) {
219 return false; // Don't bother to move further if we know the method is unresolved.
220 }
221
Vladimir Marko58155012015-08-19 12:49:41 +0000222 uint32_t method_index = invoke_instruction->GetDexMethodIndex();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000223 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000224 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
225 VLOG(compiler) << "Try inlining " << PrettyMethod(method_index, caller_dex_file);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000226
Nicolas Geoffray35071052015-06-09 15:43:38 +0100227 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
228 // We can query the dex cache directly. The verifier has populated it already.
Vladimir Marko58155012015-08-19 12:49:41 +0000229 ArtMethod* resolved_method;
Andreas Gampefd2140f2015-12-23 16:30:44 -0800230 ArtMethod* actual_method = nullptr;
Vladimir Marko58155012015-08-19 12:49:41 +0000231 if (invoke_instruction->IsInvokeStaticOrDirect()) {
Nicolas Geoffraye5234232015-12-02 09:06:11 +0000232 if (invoke_instruction->AsInvokeStaticOrDirect()->IsStringInit()) {
233 VLOG(compiler) << "Not inlining a String.<init> method";
234 return false;
235 }
Vladimir Marko58155012015-08-19 12:49:41 +0000236 MethodReference ref = invoke_instruction->AsInvokeStaticOrDirect()->GetTargetMethod();
Mathieu Chartier736b5602015-09-02 14:54:11 -0700237 mirror::DexCache* const dex_cache = (&caller_dex_file == ref.dex_file)
238 ? caller_compilation_unit_.GetDexCache().Get()
239 : class_linker->FindDexCache(soa.Self(), *ref.dex_file);
240 resolved_method = dex_cache->GetResolvedMethod(
Vladimir Marko58155012015-08-19 12:49:41 +0000241 ref.dex_method_index, class_linker->GetImagePointerSize());
Andreas Gampefd2140f2015-12-23 16:30:44 -0800242 // actual_method == resolved_method for direct or static calls.
243 actual_method = resolved_method;
Vladimir Marko58155012015-08-19 12:49:41 +0000244 } else {
Mathieu Chartier736b5602015-09-02 14:54:11 -0700245 resolved_method = caller_compilation_unit_.GetDexCache().Get()->GetResolvedMethod(
Vladimir Marko58155012015-08-19 12:49:41 +0000246 method_index, class_linker->GetImagePointerSize());
Andreas Gampefd2140f2015-12-23 16:30:44 -0800247 if (resolved_method != nullptr) {
248 // Check if we can statically find the method.
249 actual_method = FindVirtualOrInterfaceTarget(invoke_instruction, resolved_method);
250 }
Vladimir Marko58155012015-08-19 12:49:41 +0000251 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000252
Mathieu Chartiere401d142015-04-22 13:56:20 -0700253 if (resolved_method == nullptr) {
Calin Juravle175dc732015-08-25 15:42:32 +0100254 // TODO: Can this still happen?
Nicolas Geoffray35071052015-06-09 15:43:38 +0100255 // Method cannot be resolved if it is in another dex file we do not have access to.
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000256 VLOG(compiler) << "Method cannot be resolved " << PrettyMethod(method_index, caller_dex_file);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000257 return false;
258 }
259
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100260 if (actual_method != nullptr) {
261 return TryInline(invoke_instruction, actual_method);
262 }
Andreas Gampefd2140f2015-12-23 16:30:44 -0800263 DCHECK(!invoke_instruction->IsInvokeStaticOrDirect());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100264
265 // Check if we can use an inline cache.
266 ArtMethod* caller = graph_->GetArtMethod();
267 size_t pointer_size = class_linker->GetImagePointerSize();
268 // Under JIT, we should always know the caller.
269 DCHECK(!Runtime::Current()->UseJit() || (caller != nullptr));
270 if (caller != nullptr && caller->GetProfilingInfo(pointer_size) != nullptr) {
271 ProfilingInfo* profiling_info = caller->GetProfilingInfo(pointer_size);
272 const InlineCache& ic = *profiling_info->GetInlineCache(invoke_instruction->GetDexPc());
273 if (ic.IsUnitialized()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100274 VLOG(compiler) << "Interface or virtual call to "
275 << PrettyMethod(method_index, caller_dex_file)
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100276 << " is not hit and not inlined";
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100277 return false;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100278 } else if (ic.IsMonomorphic()) {
279 MaybeRecordStat(kMonomorphicCall);
280 return TryInlineMonomorphicCall(invoke_instruction, resolved_method, ic);
281 } else if (ic.IsPolymorphic()) {
282 MaybeRecordStat(kPolymorphicCall);
283 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, ic);
284 } else {
285 DCHECK(ic.IsMegamorphic());
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100286 VLOG(compiler) << "Interface or virtual call to "
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100287 << PrettyMethod(method_index, caller_dex_file)
288 << " is megamorphic and not inlined";
289 MaybeRecordStat(kMegamorphicCall);
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100290 return false;
291 }
292 }
293
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100294 VLOG(compiler) << "Interface or virtual call to "
295 << PrettyMethod(method_index, caller_dex_file)
296 << " could not be statically determined";
297 return false;
298}
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000299
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000300HInstanceFieldGet* HInliner::BuildGetReceiverClass(ClassLinker* class_linker,
301 HInstruction* receiver,
302 uint32_t dex_pc) const {
303 ArtField* field = class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0);
304 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
305 return new (graph_->GetArena()) HInstanceFieldGet(
306 receiver,
307 Primitive::kPrimNot,
308 field->GetOffset(),
309 field->IsVolatile(),
310 field->GetDexFieldIndex(),
311 field->GetDeclaringClass()->GetDexClassDefIndex(),
312 *field->GetDexFile(),
313 handles_->NewHandle(field->GetDexCache()),
314 dex_pc);
315}
316
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100317bool HInliner::TryInlineMonomorphicCall(HInvoke* invoke_instruction,
318 ArtMethod* resolved_method,
319 const InlineCache& ic) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000320 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
321 << invoke_instruction->DebugName();
322
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100323 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
324 uint32_t class_index = FindClassIndexIn(ic.GetMonomorphicType(), caller_dex_file);
325 if (class_index == DexFile::kDexNoIndex) {
326 VLOG(compiler) << "Call to " << PrettyMethod(resolved_method)
327 << " from inline cache is not inlined because its class is not"
328 << " accessible to the caller";
329 return false;
330 }
331
332 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
333 size_t pointer_size = class_linker->GetImagePointerSize();
334 if (invoke_instruction->IsInvokeInterface()) {
335 resolved_method = ic.GetMonomorphicType()->FindVirtualMethodForInterface(
336 resolved_method, pointer_size);
337 } else {
338 DCHECK(invoke_instruction->IsInvokeVirtual());
339 resolved_method = ic.GetMonomorphicType()->FindVirtualMethodForVirtual(
340 resolved_method, pointer_size);
341 }
342 DCHECK(resolved_method != nullptr);
343 HInstruction* receiver = invoke_instruction->InputAt(0);
344 HInstruction* cursor = invoke_instruction->GetPrevious();
345 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
346
347 if (!TryInline(invoke_instruction, resolved_method, /* do_rtp */ false)) {
348 return false;
349 }
350
351 // We successfully inlined, now add a guard.
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000352 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
353 class_linker, receiver, invoke_instruction->GetDexPc());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100354
355 bool is_referrer =
356 (ic.GetMonomorphicType() == outermost_graph_->GetArtMethod()->GetDeclaringClass());
357 HLoadClass* load_class = new (graph_->GetArena()) HLoadClass(graph_->GetCurrentMethod(),
358 class_index,
359 caller_dex_file,
360 is_referrer,
361 invoke_instruction->GetDexPc(),
362 /* needs_access_check */ false,
363 /* is_in_dex_cache */ true);
364
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000365 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(load_class, receiver_class);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100366 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
367 compare, invoke_instruction->GetDexPc());
368 // TODO: Extend reference type propagation to understand the guard.
369 if (cursor != nullptr) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000370 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100371 } else {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000372 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100373 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000374 bb_cursor->InsertInstructionAfter(load_class, receiver_class);
Nicolas Geoffray7c0f2e52016-01-18 15:24:53 +0000375 bb_cursor->InsertInstructionAfter(compare, load_class);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100376 bb_cursor->InsertInstructionAfter(deoptimize, compare);
377 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
378
379 // Run type propagation to get the guard typed, and eventually propagate the
380 // type of the receiver.
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000381 ReferenceTypePropagation rtp_fixup(graph_, handles_, /* is_first_run */ false);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100382 rtp_fixup.Run();
383
384 MaybeRecordStat(kInlinedMonomorphicCall);
385 return true;
386}
387
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000388bool HInliner::TryInlinePolymorphicCall(HInvoke* invoke_instruction,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100389 ArtMethod* resolved_method,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000390 const InlineCache& ic) {
391 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
392 << invoke_instruction->DebugName();
393 // This optimization only works under JIT for now.
394 DCHECK(Runtime::Current()->UseJit());
Roland Levillain2aba7cd2016-02-03 12:27:20 +0000395 if (graph_->GetInstructionSet() == kMips64) {
396 // TODO: Support HClassTableGet for mips64.
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000397 return false;
398 }
399 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
400 size_t pointer_size = class_linker->GetImagePointerSize();
401
402 DCHECK(resolved_method != nullptr);
403 ArtMethod* actual_method = nullptr;
404 // Check whether we are actually calling the same method among
405 // the different types seen.
406 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
407 if (ic.GetTypeAt(i) == nullptr) {
408 break;
409 }
410 ArtMethod* new_method = nullptr;
411 if (invoke_instruction->IsInvokeInterface()) {
412 new_method = ic.GetTypeAt(i)->FindVirtualMethodForInterface(
413 resolved_method, pointer_size);
414 } else {
415 DCHECK(invoke_instruction->IsInvokeVirtual());
416 new_method = ic.GetTypeAt(i)->FindVirtualMethodForVirtual(
417 resolved_method, pointer_size);
418 }
419 if (actual_method == nullptr) {
420 actual_method = new_method;
421 } else if (actual_method != new_method) {
422 // Different methods, bailout.
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000423 VLOG(compiler) << "Call to " << PrettyMethod(resolved_method)
424 << " from inline cache is not inlined because it resolves"
425 << " to different methods";
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000426 return false;
427 }
428 }
429
430 HInstruction* receiver = invoke_instruction->InputAt(0);
431 HInstruction* cursor = invoke_instruction->GetPrevious();
432 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
433
434 if (!TryInline(invoke_instruction, actual_method, /* do_rtp */ false)) {
435 return false;
436 }
437
438 // We successfully inlined, now add a guard.
439 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
440 class_linker, receiver, invoke_instruction->GetDexPc());
441
442 size_t method_offset = invoke_instruction->IsInvokeVirtual()
443 ? actual_method->GetVtableIndex()
444 : invoke_instruction->AsInvokeInterface()->GetImtIndex();
445
446 Primitive::Type type = Is64BitInstructionSet(graph_->GetInstructionSet())
447 ? Primitive::kPrimLong
448 : Primitive::kPrimInt;
449 HClassTableGet* class_table_get = new (graph_->GetArena()) HClassTableGet(
450 receiver_class,
451 type,
452 invoke_instruction->IsInvokeVirtual() ? HClassTableGet::kVTable : HClassTableGet::kIMTable,
453 method_offset,
454 invoke_instruction->GetDexPc());
455
456 HConstant* constant;
457 if (type == Primitive::kPrimLong) {
458 constant = graph_->GetLongConstant(
459 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
460 } else {
461 constant = graph_->GetIntConstant(
462 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
463 }
464
465 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(class_table_get, constant);
466 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
467 compare, invoke_instruction->GetDexPc());
468 // TODO: Extend reference type propagation to understand the guard.
469 if (cursor != nullptr) {
470 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
471 } else {
472 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
473 }
474 bb_cursor->InsertInstructionAfter(class_table_get, receiver_class);
475 bb_cursor->InsertInstructionAfter(compare, class_table_get);
476 bb_cursor->InsertInstructionAfter(deoptimize, compare);
477 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
478
479 // Run type propagation to get the guard typed.
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000480 ReferenceTypePropagation rtp_fixup(graph_, handles_, /* is_first_run */ false);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000481 rtp_fixup.Run();
482
483 MaybeRecordStat(kInlinedPolymorphicCall);
484
485 return true;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100486}
487
488bool HInliner::TryInline(HInvoke* invoke_instruction, ArtMethod* method, bool do_rtp) {
489 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800490
491 // Check whether we're allowed to inline. The outermost compilation unit is the relevant
492 // dex file here (though the transitivity of an inline chain would allow checking the calller).
493 if (!compiler_driver_->MayInline(method->GetDexFile(),
494 outer_compilation_unit_.GetDexFile())) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000495 if (TryPatternSubstitution(invoke_instruction, method, do_rtp)) {
496 VLOG(compiler) << "Successfully replaced pattern of invoke " << PrettyMethod(method);
497 MaybeRecordStat(kReplacedInvokeWithSimplePattern);
498 return true;
499 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800500 VLOG(compiler) << "Won't inline " << PrettyMethod(method) << " in "
501 << outer_compilation_unit_.GetDexFile()->GetLocation() << " ("
502 << caller_compilation_unit_.GetDexFile()->GetLocation() << ") from "
503 << method->GetDexFile()->GetLocation();
504 return false;
505 }
506
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100507 uint32_t method_index = FindMethodIndexIn(
508 method, caller_dex_file, invoke_instruction->GetDexMethodIndex());
509 if (method_index == DexFile::kDexNoIndex) {
510 VLOG(compiler) << "Call to "
511 << PrettyMethod(method)
512 << " cannot be inlined because unaccessible to caller";
513 return false;
514 }
515
516 bool same_dex_file = IsSameDexFile(*outer_compilation_unit_.GetDexFile(), *method->GetDexFile());
517
518 const DexFile::CodeItem* code_item = method->GetCodeItem();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000519
520 if (code_item == nullptr) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100521 VLOG(compiler) << "Method " << PrettyMethod(method)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000522 << " is not inlined because it is native";
523 return false;
524 }
525
Calin Juravleec748352015-07-29 13:52:12 +0100526 size_t inline_max_code_units = compiler_driver_->GetCompilerOptions().GetInlineMaxCodeUnits();
527 if (code_item->insns_size_in_code_units_ > inline_max_code_units) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100528 VLOG(compiler) << "Method " << PrettyMethod(method)
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000529 << " is too big to inline: "
530 << code_item->insns_size_in_code_units_
531 << " > "
532 << inline_max_code_units;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000533 return false;
534 }
535
536 if (code_item->tries_size_ != 0) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100537 VLOG(compiler) << "Method " << PrettyMethod(method)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000538 << " is not inlined because of try block";
539 return false;
540 }
541
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100542 if (!method->GetDeclaringClass()->IsVerified()) {
543 uint16_t class_def_idx = method->GetDeclaringClass()->GetDexClassDefIndex();
Nicolas Geoffrayccc61972015-10-01 14:34:20 +0100544 if (!compiler_driver_->IsMethodVerifiedWithoutFailures(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100545 method->GetDexMethodIndex(), class_def_idx, *method->GetDexFile())) {
Nicolas Geoffrayccc61972015-10-01 14:34:20 +0100546 VLOG(compiler) << "Method " << PrettyMethod(method_index, caller_dex_file)
547 << " couldn't be verified, so it cannot be inlined";
548 return false;
549 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000550 }
551
Roland Levillain4c0eb422015-04-24 16:43:49 +0100552 if (invoke_instruction->IsInvokeStaticOrDirect() &&
553 invoke_instruction->AsInvokeStaticOrDirect()->IsStaticWithImplicitClinitCheck()) {
554 // Case of a static method that cannot be inlined because it implicitly
555 // requires an initialization check of its declaring class.
556 VLOG(compiler) << "Method " << PrettyMethod(method_index, caller_dex_file)
557 << " is not inlined because it is static and requires a clinit"
558 << " check that cannot be emitted due to Dex cache limitations";
559 return false;
560 }
561
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100562 if (!TryBuildAndInline(method, invoke_instruction, same_dex_file, do_rtp)) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +0000563 return false;
564 }
565
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000566 VLOG(compiler) << "Successfully inlined " << PrettyMethod(method_index, caller_dex_file);
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +0000567 MaybeRecordStat(kInlinedInvoke);
568 return true;
569}
570
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000571static HInstruction* GetInvokeInputForArgVRegIndex(HInvoke* invoke_instruction,
572 size_t arg_vreg_index)
573 SHARED_REQUIRES(Locks::mutator_lock_) {
574 size_t input_index = 0;
575 for (size_t i = 0; i < arg_vreg_index; ++i, ++input_index) {
576 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
577 if (Primitive::Is64BitType(invoke_instruction->InputAt(input_index)->GetType())) {
578 ++i;
579 DCHECK_NE(i, arg_vreg_index);
580 }
581 }
582 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
583 return invoke_instruction->InputAt(input_index);
584}
585
586// Try to recognize known simple patterns and replace invoke call with appropriate instructions.
587bool HInliner::TryPatternSubstitution(HInvoke* invoke_instruction,
588 ArtMethod* resolved_method,
589 bool do_rtp) {
590 InlineMethod inline_method;
591 if (!InlineMethodAnalyser::AnalyseMethodCode(resolved_method, &inline_method)) {
592 return false;
593 }
594
595 HInstruction* return_replacement = nullptr;
596 switch (inline_method.opcode) {
597 case kInlineOpNop:
598 DCHECK_EQ(invoke_instruction->GetType(), Primitive::kPrimVoid);
599 break;
600 case kInlineOpReturnArg:
601 return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction,
602 inline_method.d.return_data.arg);
603 break;
604 case kInlineOpNonWideConst:
605 if (resolved_method->GetShorty()[0] == 'L') {
606 DCHECK_EQ(inline_method.d.data, 0u);
607 return_replacement = graph_->GetNullConstant();
608 } else {
609 return_replacement = graph_->GetIntConstant(static_cast<int32_t>(inline_method.d.data));
610 }
611 break;
612 case kInlineOpIGet: {
613 const InlineIGetIPutData& data = inline_method.d.ifield_data;
614 if (data.method_is_static || data.object_arg != 0u) {
615 // TODO: Needs null check.
616 return false;
617 }
Vladimir Marko354efa62016-02-04 19:46:56 +0000618 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000619 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
Vladimir Marko354efa62016-02-04 19:46:56 +0000620 HInstanceFieldGet* iget = CreateInstanceFieldGet(dex_cache, data.field_idx, obj);
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000621 DCHECK_EQ(iget->GetFieldOffset().Uint32Value(), data.field_offset);
622 DCHECK_EQ(iget->IsVolatile() ? 1u : 0u, data.is_volatile);
623 invoke_instruction->GetBlock()->InsertInstructionBefore(iget, invoke_instruction);
624 return_replacement = iget;
625 break;
626 }
627 case kInlineOpIPut: {
628 const InlineIGetIPutData& data = inline_method.d.ifield_data;
629 if (data.method_is_static || data.object_arg != 0u) {
630 // TODO: Needs null check.
631 return false;
632 }
Vladimir Marko354efa62016-02-04 19:46:56 +0000633 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000634 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
635 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, data.src_arg);
Vladimir Marko354efa62016-02-04 19:46:56 +0000636 HInstanceFieldSet* iput = CreateInstanceFieldSet(dex_cache, data.field_idx, obj, value);
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000637 DCHECK_EQ(iput->GetFieldOffset().Uint32Value(), data.field_offset);
638 DCHECK_EQ(iput->IsVolatile() ? 1u : 0u, data.is_volatile);
639 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
640 if (data.return_arg_plus1 != 0u) {
641 size_t return_arg = data.return_arg_plus1 - 1u;
642 return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction, return_arg);
643 }
644 break;
645 }
Vladimir Marko354efa62016-02-04 19:46:56 +0000646 case kInlineOpConstructor: {
647 const InlineConstructorData& data = inline_method.d.constructor_data;
648 // Get the indexes to arrays for easier processing.
649 uint16_t iput_field_indexes[] = {
650 data.iput0_field_index, data.iput1_field_index, data.iput2_field_index
651 };
652 uint16_t iput_args[] = { data.iput0_arg, data.iput1_arg, data.iput2_arg };
653 static_assert(arraysize(iput_args) == arraysize(iput_field_indexes), "Size mismatch");
654 // Count valid field indexes.
655 size_t number_of_iputs = 0u;
656 while (number_of_iputs != arraysize(iput_field_indexes) &&
657 iput_field_indexes[number_of_iputs] != DexFile::kDexNoIndex16) {
658 // Check that there are no duplicate valid field indexes.
659 DCHECK_EQ(0, std::count(iput_field_indexes + number_of_iputs + 1,
660 iput_field_indexes + arraysize(iput_field_indexes),
661 iput_field_indexes[number_of_iputs]));
662 ++number_of_iputs;
663 }
664 // Check that there are no valid field indexes in the rest of the array.
665 DCHECK_EQ(0, std::count_if(iput_field_indexes + number_of_iputs,
666 iput_field_indexes + arraysize(iput_field_indexes),
667 [](uint16_t index) { return index != DexFile::kDexNoIndex16; }));
668
669 // Create HInstanceFieldSet for each IPUT that stores non-zero data.
670 Handle<mirror::DexCache> dex_cache;
671 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, /* this */ 0u);
672 bool needs_constructor_barrier = false;
673 for (size_t i = 0; i != number_of_iputs; ++i) {
674 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, iput_args[i]);
675 if (!value->IsConstant() ||
676 (!value->AsConstant()->IsZero() && !value->IsNullConstant())) {
677 if (dex_cache.GetReference() == nullptr) {
678 dex_cache = handles_->NewHandle(resolved_method->GetDexCache());
679 }
680 uint16_t field_index = iput_field_indexes[i];
681 HInstanceFieldSet* iput = CreateInstanceFieldSet(dex_cache, field_index, obj, value);
682 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
683
684 // Check whether the field is final. If it is, we need to add a barrier.
685 size_t pointer_size = InstructionSetPointerSize(codegen_->GetInstructionSet());
686 ArtField* resolved_field = dex_cache->GetResolvedField(field_index, pointer_size);
687 DCHECK(resolved_field != nullptr);
688 if (resolved_field->IsFinal()) {
689 needs_constructor_barrier = true;
690 }
691 }
692 }
693 if (needs_constructor_barrier) {
694 HMemoryBarrier* barrier = new (graph_->GetArena()) HMemoryBarrier(kStoreStore, kNoDexPc);
695 invoke_instruction->GetBlock()->InsertInstructionBefore(barrier, invoke_instruction);
696 }
697 break;
698 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000699 default:
700 LOG(FATAL) << "UNREACHABLE";
701 UNREACHABLE();
702 }
703
704 if (return_replacement != nullptr) {
705 invoke_instruction->ReplaceWith(return_replacement);
706 }
707 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
708
709 FixUpReturnReferenceType(resolved_method, invoke_instruction, return_replacement, do_rtp);
710 return true;
711}
712
Vladimir Marko354efa62016-02-04 19:46:56 +0000713HInstanceFieldGet* HInliner::CreateInstanceFieldGet(Handle<mirror::DexCache> dex_cache,
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000714 uint32_t field_index,
715 HInstruction* obj)
716 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000717 size_t pointer_size = InstructionSetPointerSize(codegen_->GetInstructionSet());
718 ArtField* resolved_field = dex_cache->GetResolvedField(field_index, pointer_size);
719 DCHECK(resolved_field != nullptr);
720 HInstanceFieldGet* iget = new (graph_->GetArena()) HInstanceFieldGet(
721 obj,
722 resolved_field->GetTypeAsPrimitiveType(),
723 resolved_field->GetOffset(),
724 resolved_field->IsVolatile(),
725 field_index,
726 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Marko354efa62016-02-04 19:46:56 +0000727 *dex_cache->GetDexFile(),
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000728 dex_cache,
Vladimir Markoadda4352016-01-29 10:24:41 +0000729 // Read barrier generates a runtime call in slow path and we need a valid
730 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
731 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000732 if (iget->GetType() == Primitive::kPrimNot) {
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000733 ReferenceTypePropagation rtp(graph_, handles_, /* is_first_run */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000734 rtp.Visit(iget);
735 }
736 return iget;
737}
738
Vladimir Marko354efa62016-02-04 19:46:56 +0000739HInstanceFieldSet* HInliner::CreateInstanceFieldSet(Handle<mirror::DexCache> dex_cache,
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000740 uint32_t field_index,
741 HInstruction* obj,
742 HInstruction* value)
743 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000744 size_t pointer_size = InstructionSetPointerSize(codegen_->GetInstructionSet());
745 ArtField* resolved_field = dex_cache->GetResolvedField(field_index, pointer_size);
746 DCHECK(resolved_field != nullptr);
747 HInstanceFieldSet* iput = new (graph_->GetArena()) HInstanceFieldSet(
748 obj,
749 value,
750 resolved_field->GetTypeAsPrimitiveType(),
751 resolved_field->GetOffset(),
752 resolved_field->IsVolatile(),
753 field_index,
754 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Marko354efa62016-02-04 19:46:56 +0000755 *dex_cache->GetDexFile(),
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000756 dex_cache,
Vladimir Markoadda4352016-01-29 10:24:41 +0000757 // Read barrier generates a runtime call in slow path and we need a valid
758 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
759 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000760 return iput;
761}
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000762
Mathieu Chartiere401d142015-04-22 13:56:20 -0700763bool HInliner::TryBuildAndInline(ArtMethod* resolved_method,
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +0000764 HInvoke* invoke_instruction,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100765 bool same_dex_file,
766 bool do_rtp) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +0000767 ScopedObjectAccess soa(Thread::Current());
768 const DexFile::CodeItem* code_item = resolved_method->GetCodeItem();
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100769 const DexFile& callee_dex_file = *resolved_method->GetDexFile();
770 uint32_t method_index = resolved_method->GetDexMethodIndex();
Calin Juravle2e768302015-07-28 14:41:11 +0000771 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Mathieu Chartier736b5602015-09-02 14:54:11 -0700772 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000773 DexCompilationUnit dex_compilation_unit(
774 nullptr,
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000775 caller_compilation_unit_.GetClassLoader(),
Calin Juravle2e768302015-07-28 14:41:11 +0000776 class_linker,
Nicolas Geoffray8dbf0cf2015-08-11 02:14:38 +0000777 callee_dex_file,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000778 code_item,
779 resolved_method->GetDeclaringClass()->GetDexClassDefIndex(),
Nicolas Geoffray8dbf0cf2015-08-11 02:14:38 +0000780 method_index,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000781 resolved_method->GetAccessFlags(),
Mathieu Chartier736b5602015-09-02 14:54:11 -0700782 compiler_driver_->GetVerifiedMethod(&callee_dex_file, method_index),
783 dex_cache);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000784
Calin Juravle3cd4fc82015-05-14 15:15:42 +0100785 bool requires_ctor_barrier = false;
786
787 if (dex_compilation_unit.IsConstructor()) {
788 // If it's a super invocation and we already generate a barrier there's no need
789 // to generate another one.
790 // We identify super calls by looking at the "this" pointer. If its value is the
791 // same as the local "this" pointer then we must have a super invocation.
792 bool is_super_invocation = invoke_instruction->InputAt(0)->IsParameterValue()
793 && invoke_instruction->InputAt(0)->AsParameterValue()->IsThis();
794 if (is_super_invocation && graph_->ShouldGenerateConstructorBarrier()) {
795 requires_ctor_barrier = false;
796 } else {
797 Thread* self = Thread::Current();
798 requires_ctor_barrier = compiler_driver_->RequiresConstructorBarrier(self,
799 dex_compilation_unit.GetDexFile(),
800 dex_compilation_unit.GetClassDefIndex());
801 }
802 }
803
Nicolas Geoffray35071052015-06-09 15:43:38 +0100804 InvokeType invoke_type = invoke_instruction->GetOriginalInvokeType();
805 if (invoke_type == kInterface) {
806 // We have statically resolved the dispatch. To please the class linker
807 // at runtime, we change this call as if it was a virtual call.
808 invoke_type = kVirtual;
809 }
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +0000810 HGraph* callee_graph = new (graph_->GetArena()) HGraph(
Nicolas Geoffray0a23d742015-05-07 11:57:35 +0100811 graph_->GetArena(),
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100812 callee_dex_file,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +0100813 method_index,
Calin Juravle3cd4fc82015-05-14 15:15:42 +0100814 requires_ctor_barrier,
Mathieu Chartiere401d142015-04-22 13:56:20 -0700815 compiler_driver_->GetInstructionSet(),
Nicolas Geoffray35071052015-06-09 15:43:38 +0100816 invoke_type,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +0100817 graph_->IsDebuggable(),
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000818 /* osr */ false,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +0100819 graph_->GetCurrentInstructionId());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100820 callee_graph->SetArtMethod(resolved_method);
David Brazdil5e8b1372015-01-23 14:39:08 +0000821
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000822 OptimizingCompilerStats inline_stats;
David Brazdil5e8b1372015-01-23 14:39:08 +0000823 HGraphBuilder builder(callee_graph,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000824 &dex_compilation_unit,
825 &outer_compilation_unit_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000826 resolved_method->GetDexFile(),
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000827 compiler_driver_,
Nicolas Geoffray9523a3e2015-07-17 11:51:28 +0000828 &inline_stats,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700829 resolved_method->GetQuickenedInfo(),
830 dex_cache);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000831
David Brazdilbadd8262016-02-02 16:28:56 +0000832 if (builder.BuildGraph(*code_item, handles_) != kAnalysisSuccess) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100833 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000834 << " could not be built, so cannot be inlined";
835 return false;
836 }
837
Nicolas Geoffray259136f2014-12-17 23:21:58 +0000838 if (!RegisterAllocator::CanAllocateRegistersFor(*callee_graph,
839 compiler_driver_->GetInstructionSet())) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100840 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffray259136f2014-12-17 23:21:58 +0000841 << " cannot be inlined because of the register allocator";
842 return false;
843 }
844
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700845 size_t parameter_index = 0;
846 for (HInstructionIterator instructions(callee_graph->GetEntryBlock()->GetInstructions());
847 !instructions.Done();
848 instructions.Advance()) {
849 HInstruction* current = instructions.Current();
850 if (current->IsParameterValue()) {
851 HInstruction* argument = invoke_instruction->InputAt(parameter_index++);
852 if (argument->IsNullConstant()) {
853 current->ReplaceWith(callee_graph->GetNullConstant());
854 } else if (argument->IsIntConstant()) {
855 current->ReplaceWith(callee_graph->GetIntConstant(argument->AsIntConstant()->GetValue()));
856 } else if (argument->IsLongConstant()) {
857 current->ReplaceWith(callee_graph->GetLongConstant(argument->AsLongConstant()->GetValue()));
858 } else if (argument->IsFloatConstant()) {
859 current->ReplaceWith(
860 callee_graph->GetFloatConstant(argument->AsFloatConstant()->GetValue()));
861 } else if (argument->IsDoubleConstant()) {
862 current->ReplaceWith(
863 callee_graph->GetDoubleConstant(argument->AsDoubleConstant()->GetValue()));
864 } else if (argument->GetType() == Primitive::kPrimNot) {
865 current->SetReferenceTypeInfo(argument->GetReferenceTypeInfo());
866 current->AsParameterValue()->SetCanBeNull(argument->CanBeNull());
867 }
868 }
869 }
870
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000871 // Run simple optimizations on the graph.
Calin Juravle7a9c8852015-04-21 14:07:50 +0100872 HDeadCodeElimination dce(callee_graph, stats_);
Nicolas Geoffraye34648d2015-11-23 08:59:07 +0000873 HConstantFolding fold(callee_graph);
Vladimir Markodc151b22015-10-15 18:02:30 +0100874 HSharpening sharpening(callee_graph, codegen_, dex_compilation_unit, compiler_driver_);
Calin Juravleacf735c2015-02-12 15:25:22 +0000875 InstructionSimplifier simplify(callee_graph, stats_);
Nicolas Geoffraye34648d2015-11-23 08:59:07 +0000876 IntrinsicsRecognizer intrinsics(callee_graph, compiler_driver_);
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000877
878 HOptimization* optimizations[] = {
Scott Wakelingd60a1af2015-07-22 14:32:44 +0100879 &intrinsics,
Vladimir Markodc151b22015-10-15 18:02:30 +0100880 &sharpening,
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000881 &simplify,
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700882 &fold,
Vladimir Marko9e23df52015-11-10 17:14:35 +0000883 &dce,
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000884 };
885
886 for (size_t i = 0; i < arraysize(optimizations); ++i) {
887 HOptimization* optimization = optimizations[i];
888 optimization->Run();
889 }
890
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700891 size_t number_of_instructions_budget = kMaximumNumberOfHInstructions;
Calin Juravleec748352015-07-29 13:52:12 +0100892 if (depth_ + 1 < compiler_driver_->GetCompilerOptions().GetInlineDepthLimit()) {
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000893 HInliner inliner(callee_graph,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100894 outermost_graph_,
Vladimir Markodc151b22015-10-15 18:02:30 +0100895 codegen_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000896 outer_compilation_unit_,
897 dex_compilation_unit,
898 compiler_driver_,
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100899 handles_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000900 stats_,
Nicolas Geoffray5949fa02015-12-18 10:57:10 +0000901 total_number_of_dex_registers_ + code_item->registers_size_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000902 depth_ + 1);
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000903 inliner.Run();
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700904 number_of_instructions_budget += inliner.number_of_inlined_instructions_;
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000905 }
906
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100907 // TODO: We should abort only if all predecessors throw. However,
908 // HGraph::InlineInto currently does not handle an exit block with
909 // a throw predecessor.
910 HBasicBlock* exit_block = callee_graph->GetExitBlock();
911 if (exit_block == nullptr) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100912 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100913 << " could not be inlined because it has an infinite loop";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100914 return false;
915 }
916
917 bool has_throw_predecessor = false;
Vladimir Marko60584552015-09-03 13:35:12 +0000918 for (HBasicBlock* predecessor : exit_block->GetPredecessors()) {
919 if (predecessor->GetLastInstruction()->IsThrow()) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100920 has_throw_predecessor = true;
921 break;
922 }
923 }
924 if (has_throw_predecessor) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100925 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100926 << " could not be inlined because one branch always throws";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100927 return false;
928 }
929
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000930 HReversePostOrderIterator it(*callee_graph);
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000931 it.Advance(); // Past the entry block, it does not contain instructions that prevent inlining.
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700932 size_t number_of_instructions = 0;
Nicolas Geoffray5949fa02015-12-18 10:57:10 +0000933
934 bool can_inline_environment =
935 total_number_of_dex_registers_ < kMaximumNumberOfCumulatedDexRegisters;
936
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000937 for (; !it.Done(); it.Advance()) {
938 HBasicBlock* block = it.Current();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000939
940 if (block->IsLoopHeader() && block->GetLoopInformation()->IsIrreducible()) {
941 // Don't inline methods with irreducible loops, they could prevent some
942 // optimizations to run.
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100943 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000944 << " could not be inlined because it contains an irreducible loop";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000945 return false;
946 }
947
948 for (HInstructionIterator instr_it(block->GetInstructions());
949 !instr_it.Done();
950 instr_it.Advance()) {
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700951 if (number_of_instructions++ == number_of_instructions_budget) {
952 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffray5949fa02015-12-18 10:57:10 +0000953 << " is not inlined because its caller has reached"
954 << " its instruction budget limit.";
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700955 return false;
956 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000957 HInstruction* current = instr_it.Current();
Nicolas Geoffray5949fa02015-12-18 10:57:10 +0000958 if (!can_inline_environment && current->NeedsEnvironment()) {
959 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
960 << " is not inlined because its caller has reached"
961 << " its environment budget limit.";
962 return false;
963 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000964
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100965 if (current->IsInvokeInterface()) {
966 // Disable inlining of interface calls. The cost in case of entering the
967 // resolution conflict is currently too high.
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100968 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100969 << " could not be inlined because it has an interface call.";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000970 return false;
971 }
972
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100973 if (!same_dex_file && current->NeedsEnvironment()) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100974 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000975 << " could not be inlined because " << current->DebugName()
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100976 << " needs an environment and is in a different dex file";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000977 return false;
978 }
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000979
Vladimir Markodc151b22015-10-15 18:02:30 +0100980 if (!same_dex_file && current->NeedsDexCacheOfDeclaringClass()) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100981 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000982 << " could not be inlined because " << current->DebugName()
983 << " it is in a different dex file and requires access to the dex cache";
984 return false;
985 }
Nicolas Geoffrayd9309292015-10-31 22:21:31 +0000986
987 if (current->IsNewInstance() &&
988 (current->AsNewInstance()->GetEntrypoint() == kQuickAllocObjectWithAccessCheck)) {
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000989 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
990 << " could not be inlined because it is using an entrypoint"
991 << " with access checks";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +0000992 // Allocation entrypoint does not handle inlined frames.
993 return false;
994 }
995
996 if (current->IsNewArray() &&
997 (current->AsNewArray()->GetEntrypoint() == kQuickAllocArrayWithAccessCheck)) {
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000998 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
999 << " could not be inlined because it is using an entrypoint"
1000 << " with access checks";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001001 // Allocation entrypoint does not handle inlined frames.
1002 return false;
1003 }
1004
1005 if (current->IsUnresolvedStaticFieldGet() ||
1006 current->IsUnresolvedInstanceFieldGet() ||
1007 current->IsUnresolvedStaticFieldSet() ||
1008 current->IsUnresolvedInstanceFieldSet()) {
1009 // Entrypoint for unresolved fields does not handle inlined frames.
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001010 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
1011 << " could not be inlined because it is using an unresolved"
1012 << " entrypoint";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001013 return false;
1014 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001015 }
1016 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001017 number_of_inlined_instructions_ += number_of_instructions;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001018
Calin Juravle2e768302015-07-28 14:41:11 +00001019 HInstruction* return_replacement = callee_graph->InlineInto(graph_, invoke_instruction);
Calin Juravle214bbcd2015-10-20 14:54:07 +01001020 if (return_replacement != nullptr) {
1021 DCHECK_EQ(graph_, return_replacement->GetBlock()->GetGraph());
1022 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001023 FixUpReturnReferenceType(resolved_method, invoke_instruction, return_replacement, do_rtp);
1024 return true;
1025}
Calin Juravle2e768302015-07-28 14:41:11 +00001026
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001027void HInliner::FixUpReturnReferenceType(ArtMethod* resolved_method,
1028 HInvoke* invoke_instruction,
1029 HInstruction* return_replacement,
1030 bool do_rtp) {
Alex Light68289a52015-12-15 17:30:30 -08001031 // Check the integrity of reference types and run another type propagation if needed.
David Brazdil4833f5a2015-12-16 10:37:39 +00001032 if (return_replacement != nullptr) {
1033 if (return_replacement->GetType() == Primitive::kPrimNot) {
1034 if (!return_replacement->GetReferenceTypeInfo().IsValid()) {
1035 // Make sure that we have a valid type for the return. We may get an invalid one when
1036 // we inline invokes with multiple branches and create a Phi for the result.
1037 // TODO: we could be more precise by merging the phi inputs but that requires
1038 // some functionality from the reference type propagation.
1039 DCHECK(return_replacement->IsPhi());
1040 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1041 ReferenceTypeInfo::TypeHandle return_handle =
1042 handles_->NewHandle(resolved_method->GetReturnType(true /* resolve */, pointer_size));
1043 return_replacement->SetReferenceTypeInfo(ReferenceTypeInfo::Create(
1044 return_handle, return_handle->CannotBeAssignedFromOtherTypes() /* is_exact */));
1045 }
Alex Light68289a52015-12-15 17:30:30 -08001046
David Brazdil4833f5a2015-12-16 10:37:39 +00001047 if (do_rtp) {
1048 // If the return type is a refinement of the declared type run the type propagation again.
1049 ReferenceTypeInfo return_rti = return_replacement->GetReferenceTypeInfo();
1050 ReferenceTypeInfo invoke_rti = invoke_instruction->GetReferenceTypeInfo();
1051 if (invoke_rti.IsStrictSupertypeOf(return_rti)
1052 || (return_rti.IsExact() && !invoke_rti.IsExact())
1053 || !return_replacement->CanBeNull()) {
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001054 ReferenceTypePropagation(graph_, handles_, /* is_first_run */ false).Run();
David Brazdil4833f5a2015-12-16 10:37:39 +00001055 }
1056 }
1057 } else if (return_replacement->IsInstanceOf()) {
1058 if (do_rtp) {
1059 // Inlining InstanceOf into an If may put a tighter bound on reference types.
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001060 ReferenceTypePropagation(graph_, handles_, /* is_first_run */ false).Run();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001061 }
Calin Juravlecdfed3d2015-10-26 14:05:01 +00001062 }
Calin Juravle2e768302015-07-28 14:41:11 +00001063 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001064}
1065
1066} // namespace art