blob: 51fef7c9cb70da18596fecdf58883ad38144a5ee [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.
381 ReferenceTypePropagation rtp_fixup(graph_, handles_);
382 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());
395 if (graph_->GetInstructionSet() == kMips || graph_->GetInstructionSet() == kMips64) {
396 // TODO: Support HClassTableGet for mips and mips64.
397 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.
423 return false;
424 }
425 }
426
427 HInstruction* receiver = invoke_instruction->InputAt(0);
428 HInstruction* cursor = invoke_instruction->GetPrevious();
429 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
430
431 if (!TryInline(invoke_instruction, actual_method, /* do_rtp */ false)) {
432 return false;
433 }
434
435 // We successfully inlined, now add a guard.
436 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
437 class_linker, receiver, invoke_instruction->GetDexPc());
438
439 size_t method_offset = invoke_instruction->IsInvokeVirtual()
440 ? actual_method->GetVtableIndex()
441 : invoke_instruction->AsInvokeInterface()->GetImtIndex();
442
443 Primitive::Type type = Is64BitInstructionSet(graph_->GetInstructionSet())
444 ? Primitive::kPrimLong
445 : Primitive::kPrimInt;
446 HClassTableGet* class_table_get = new (graph_->GetArena()) HClassTableGet(
447 receiver_class,
448 type,
449 invoke_instruction->IsInvokeVirtual() ? HClassTableGet::kVTable : HClassTableGet::kIMTable,
450 method_offset,
451 invoke_instruction->GetDexPc());
452
453 HConstant* constant;
454 if (type == Primitive::kPrimLong) {
455 constant = graph_->GetLongConstant(
456 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
457 } else {
458 constant = graph_->GetIntConstant(
459 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
460 }
461
462 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(class_table_get, constant);
463 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
464 compare, invoke_instruction->GetDexPc());
465 // TODO: Extend reference type propagation to understand the guard.
466 if (cursor != nullptr) {
467 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
468 } else {
469 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
470 }
471 bb_cursor->InsertInstructionAfter(class_table_get, receiver_class);
472 bb_cursor->InsertInstructionAfter(compare, class_table_get);
473 bb_cursor->InsertInstructionAfter(deoptimize, compare);
474 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
475
476 // Run type propagation to get the guard typed.
477 ReferenceTypePropagation rtp_fixup(graph_, handles_);
478 rtp_fixup.Run();
479
480 MaybeRecordStat(kInlinedPolymorphicCall);
481
482 return true;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100483}
484
485bool HInliner::TryInline(HInvoke* invoke_instruction, ArtMethod* method, bool do_rtp) {
486 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800487
488 // Check whether we're allowed to inline. The outermost compilation unit is the relevant
489 // dex file here (though the transitivity of an inline chain would allow checking the calller).
490 if (!compiler_driver_->MayInline(method->GetDexFile(),
491 outer_compilation_unit_.GetDexFile())) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000492 if (TryPatternSubstitution(invoke_instruction, method, do_rtp)) {
493 VLOG(compiler) << "Successfully replaced pattern of invoke " << PrettyMethod(method);
494 MaybeRecordStat(kReplacedInvokeWithSimplePattern);
495 return true;
496 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800497 VLOG(compiler) << "Won't inline " << PrettyMethod(method) << " in "
498 << outer_compilation_unit_.GetDexFile()->GetLocation() << " ("
499 << caller_compilation_unit_.GetDexFile()->GetLocation() << ") from "
500 << method->GetDexFile()->GetLocation();
501 return false;
502 }
503
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100504 uint32_t method_index = FindMethodIndexIn(
505 method, caller_dex_file, invoke_instruction->GetDexMethodIndex());
506 if (method_index == DexFile::kDexNoIndex) {
507 VLOG(compiler) << "Call to "
508 << PrettyMethod(method)
509 << " cannot be inlined because unaccessible to caller";
510 return false;
511 }
512
513 bool same_dex_file = IsSameDexFile(*outer_compilation_unit_.GetDexFile(), *method->GetDexFile());
514
515 const DexFile::CodeItem* code_item = method->GetCodeItem();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000516
517 if (code_item == nullptr) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100518 VLOG(compiler) << "Method " << PrettyMethod(method)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000519 << " is not inlined because it is native";
520 return false;
521 }
522
Calin Juravleec748352015-07-29 13:52:12 +0100523 size_t inline_max_code_units = compiler_driver_->GetCompilerOptions().GetInlineMaxCodeUnits();
524 if (code_item->insns_size_in_code_units_ > inline_max_code_units) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100525 VLOG(compiler) << "Method " << PrettyMethod(method)
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000526 << " is too big to inline: "
527 << code_item->insns_size_in_code_units_
528 << " > "
529 << inline_max_code_units;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000530 return false;
531 }
532
533 if (code_item->tries_size_ != 0) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100534 VLOG(compiler) << "Method " << PrettyMethod(method)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000535 << " is not inlined because of try block";
536 return false;
537 }
538
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100539 if (!method->GetDeclaringClass()->IsVerified()) {
540 uint16_t class_def_idx = method->GetDeclaringClass()->GetDexClassDefIndex();
Nicolas Geoffrayccc61972015-10-01 14:34:20 +0100541 if (!compiler_driver_->IsMethodVerifiedWithoutFailures(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100542 method->GetDexMethodIndex(), class_def_idx, *method->GetDexFile())) {
Nicolas Geoffrayccc61972015-10-01 14:34:20 +0100543 VLOG(compiler) << "Method " << PrettyMethod(method_index, caller_dex_file)
544 << " couldn't be verified, so it cannot be inlined";
545 return false;
546 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000547 }
548
Roland Levillain4c0eb422015-04-24 16:43:49 +0100549 if (invoke_instruction->IsInvokeStaticOrDirect() &&
550 invoke_instruction->AsInvokeStaticOrDirect()->IsStaticWithImplicitClinitCheck()) {
551 // Case of a static method that cannot be inlined because it implicitly
552 // requires an initialization check of its declaring class.
553 VLOG(compiler) << "Method " << PrettyMethod(method_index, caller_dex_file)
554 << " is not inlined because it is static and requires a clinit"
555 << " check that cannot be emitted due to Dex cache limitations";
556 return false;
557 }
558
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100559 if (!TryBuildAndInline(method, invoke_instruction, same_dex_file, do_rtp)) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +0000560 return false;
561 }
562
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000563 VLOG(compiler) << "Successfully inlined " << PrettyMethod(method_index, caller_dex_file);
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +0000564 MaybeRecordStat(kInlinedInvoke);
565 return true;
566}
567
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000568static HInstruction* GetInvokeInputForArgVRegIndex(HInvoke* invoke_instruction,
569 size_t arg_vreg_index)
570 SHARED_REQUIRES(Locks::mutator_lock_) {
571 size_t input_index = 0;
572 for (size_t i = 0; i < arg_vreg_index; ++i, ++input_index) {
573 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
574 if (Primitive::Is64BitType(invoke_instruction->InputAt(input_index)->GetType())) {
575 ++i;
576 DCHECK_NE(i, arg_vreg_index);
577 }
578 }
579 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
580 return invoke_instruction->InputAt(input_index);
581}
582
583// Try to recognize known simple patterns and replace invoke call with appropriate instructions.
584bool HInliner::TryPatternSubstitution(HInvoke* invoke_instruction,
585 ArtMethod* resolved_method,
586 bool do_rtp) {
587 InlineMethod inline_method;
588 if (!InlineMethodAnalyser::AnalyseMethodCode(resolved_method, &inline_method)) {
589 return false;
590 }
591
592 HInstruction* return_replacement = nullptr;
593 switch (inline_method.opcode) {
594 case kInlineOpNop:
595 DCHECK_EQ(invoke_instruction->GetType(), Primitive::kPrimVoid);
596 break;
597 case kInlineOpReturnArg:
598 return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction,
599 inline_method.d.return_data.arg);
600 break;
601 case kInlineOpNonWideConst:
602 if (resolved_method->GetShorty()[0] == 'L') {
603 DCHECK_EQ(inline_method.d.data, 0u);
604 return_replacement = graph_->GetNullConstant();
605 } else {
606 return_replacement = graph_->GetIntConstant(static_cast<int32_t>(inline_method.d.data));
607 }
608 break;
609 case kInlineOpIGet: {
610 const InlineIGetIPutData& data = inline_method.d.ifield_data;
611 if (data.method_is_static || data.object_arg != 0u) {
612 // TODO: Needs null check.
613 return false;
614 }
615 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
616 HInstanceFieldGet* iget = CreateInstanceFieldGet(resolved_method, data.field_idx, obj);
617 DCHECK_EQ(iget->GetFieldOffset().Uint32Value(), data.field_offset);
618 DCHECK_EQ(iget->IsVolatile() ? 1u : 0u, data.is_volatile);
619 invoke_instruction->GetBlock()->InsertInstructionBefore(iget, invoke_instruction);
620 return_replacement = iget;
621 break;
622 }
623 case kInlineOpIPut: {
624 const InlineIGetIPutData& data = inline_method.d.ifield_data;
625 if (data.method_is_static || data.object_arg != 0u) {
626 // TODO: Needs null check.
627 return false;
628 }
629 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
630 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, data.src_arg);
631 HInstanceFieldSet* iput = CreateInstanceFieldSet(resolved_method, data.field_idx, obj, value);
632 DCHECK_EQ(iput->GetFieldOffset().Uint32Value(), data.field_offset);
633 DCHECK_EQ(iput->IsVolatile() ? 1u : 0u, data.is_volatile);
634 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
635 if (data.return_arg_plus1 != 0u) {
636 size_t return_arg = data.return_arg_plus1 - 1u;
637 return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction, return_arg);
638 }
639 break;
640 }
641 default:
642 LOG(FATAL) << "UNREACHABLE";
643 UNREACHABLE();
644 }
645
646 if (return_replacement != nullptr) {
647 invoke_instruction->ReplaceWith(return_replacement);
648 }
649 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
650
651 FixUpReturnReferenceType(resolved_method, invoke_instruction, return_replacement, do_rtp);
652 return true;
653}
654
655HInstanceFieldGet* HInliner::CreateInstanceFieldGet(ArtMethod* resolved_method,
656 uint32_t field_index,
657 HInstruction* obj)
658 SHARED_REQUIRES(Locks::mutator_lock_) {
659 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
660 size_t pointer_size = InstructionSetPointerSize(codegen_->GetInstructionSet());
661 ArtField* resolved_field = dex_cache->GetResolvedField(field_index, pointer_size);
662 DCHECK(resolved_field != nullptr);
663 HInstanceFieldGet* iget = new (graph_->GetArena()) HInstanceFieldGet(
664 obj,
665 resolved_field->GetTypeAsPrimitiveType(),
666 resolved_field->GetOffset(),
667 resolved_field->IsVolatile(),
668 field_index,
669 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
670 *resolved_method->GetDexFile(),
671 dex_cache,
672 kNoDexPc);
673 if (iget->GetType() == Primitive::kPrimNot) {
674 ReferenceTypePropagation rtp(graph_, handles_);
675 rtp.Visit(iget);
676 }
677 return iget;
678}
679
680HInstanceFieldSet* HInliner::CreateInstanceFieldSet(ArtMethod* resolved_method,
681 uint32_t field_index,
682 HInstruction* obj,
683 HInstruction* value)
684 SHARED_REQUIRES(Locks::mutator_lock_) {
685 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
686 size_t pointer_size = InstructionSetPointerSize(codegen_->GetInstructionSet());
687 ArtField* resolved_field = dex_cache->GetResolvedField(field_index, pointer_size);
688 DCHECK(resolved_field != nullptr);
689 HInstanceFieldSet* iput = new (graph_->GetArena()) HInstanceFieldSet(
690 obj,
691 value,
692 resolved_field->GetTypeAsPrimitiveType(),
693 resolved_field->GetOffset(),
694 resolved_field->IsVolatile(),
695 field_index,
696 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
697 *resolved_method->GetDexFile(),
698 dex_cache,
699 kNoDexPc);
700 return iput;
701}
Mathieu Chartiere401d142015-04-22 13:56:20 -0700702bool HInliner::TryBuildAndInline(ArtMethod* resolved_method,
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +0000703 HInvoke* invoke_instruction,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100704 bool same_dex_file,
705 bool do_rtp) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +0000706 ScopedObjectAccess soa(Thread::Current());
707 const DexFile::CodeItem* code_item = resolved_method->GetCodeItem();
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100708 const DexFile& callee_dex_file = *resolved_method->GetDexFile();
709 uint32_t method_index = resolved_method->GetDexMethodIndex();
Calin Juravle2e768302015-07-28 14:41:11 +0000710 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Mathieu Chartier736b5602015-09-02 14:54:11 -0700711 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000712 DexCompilationUnit dex_compilation_unit(
713 nullptr,
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000714 caller_compilation_unit_.GetClassLoader(),
Calin Juravle2e768302015-07-28 14:41:11 +0000715 class_linker,
Nicolas Geoffray8dbf0cf2015-08-11 02:14:38 +0000716 callee_dex_file,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000717 code_item,
718 resolved_method->GetDeclaringClass()->GetDexClassDefIndex(),
Nicolas Geoffray8dbf0cf2015-08-11 02:14:38 +0000719 method_index,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000720 resolved_method->GetAccessFlags(),
Mathieu Chartier736b5602015-09-02 14:54:11 -0700721 compiler_driver_->GetVerifiedMethod(&callee_dex_file, method_index),
722 dex_cache);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000723
Calin Juravle3cd4fc82015-05-14 15:15:42 +0100724 bool requires_ctor_barrier = false;
725
726 if (dex_compilation_unit.IsConstructor()) {
727 // If it's a super invocation and we already generate a barrier there's no need
728 // to generate another one.
729 // We identify super calls by looking at the "this" pointer. If its value is the
730 // same as the local "this" pointer then we must have a super invocation.
731 bool is_super_invocation = invoke_instruction->InputAt(0)->IsParameterValue()
732 && invoke_instruction->InputAt(0)->AsParameterValue()->IsThis();
733 if (is_super_invocation && graph_->ShouldGenerateConstructorBarrier()) {
734 requires_ctor_barrier = false;
735 } else {
736 Thread* self = Thread::Current();
737 requires_ctor_barrier = compiler_driver_->RequiresConstructorBarrier(self,
738 dex_compilation_unit.GetDexFile(),
739 dex_compilation_unit.GetClassDefIndex());
740 }
741 }
742
Nicolas Geoffray35071052015-06-09 15:43:38 +0100743 InvokeType invoke_type = invoke_instruction->GetOriginalInvokeType();
744 if (invoke_type == kInterface) {
745 // We have statically resolved the dispatch. To please the class linker
746 // at runtime, we change this call as if it was a virtual call.
747 invoke_type = kVirtual;
748 }
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +0000749 HGraph* callee_graph = new (graph_->GetArena()) HGraph(
Nicolas Geoffray0a23d742015-05-07 11:57:35 +0100750 graph_->GetArena(),
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100751 callee_dex_file,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +0100752 method_index,
Calin Juravle3cd4fc82015-05-14 15:15:42 +0100753 requires_ctor_barrier,
Mathieu Chartiere401d142015-04-22 13:56:20 -0700754 compiler_driver_->GetInstructionSet(),
Nicolas Geoffray35071052015-06-09 15:43:38 +0100755 invoke_type,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +0100756 graph_->IsDebuggable(),
757 graph_->GetCurrentInstructionId());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100758 callee_graph->SetArtMethod(resolved_method);
David Brazdil5e8b1372015-01-23 14:39:08 +0000759
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000760 OptimizingCompilerStats inline_stats;
David Brazdil5e8b1372015-01-23 14:39:08 +0000761 HGraphBuilder builder(callee_graph,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000762 &dex_compilation_unit,
763 &outer_compilation_unit_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000764 resolved_method->GetDexFile(),
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000765 compiler_driver_,
Nicolas Geoffray9523a3e2015-07-17 11:51:28 +0000766 &inline_stats,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700767 resolved_method->GetQuickenedInfo(),
768 dex_cache);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000769
David Brazdil5e8b1372015-01-23 14:39:08 +0000770 if (!builder.BuildGraph(*code_item)) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100771 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000772 << " could not be built, so cannot be inlined";
773 return false;
774 }
775
Nicolas Geoffray259136f2014-12-17 23:21:58 +0000776 if (!RegisterAllocator::CanAllocateRegistersFor(*callee_graph,
777 compiler_driver_->GetInstructionSet())) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100778 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffray259136f2014-12-17 23:21:58 +0000779 << " cannot be inlined because of the register allocator";
780 return false;
781 }
782
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000783 if (callee_graph->TryBuildingSsa(handles_) != kAnalysisSuccess) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100784 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000785 << " could not be transformed to SSA";
786 return false;
787 }
788
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700789 size_t parameter_index = 0;
790 for (HInstructionIterator instructions(callee_graph->GetEntryBlock()->GetInstructions());
791 !instructions.Done();
792 instructions.Advance()) {
793 HInstruction* current = instructions.Current();
794 if (current->IsParameterValue()) {
795 HInstruction* argument = invoke_instruction->InputAt(parameter_index++);
796 if (argument->IsNullConstant()) {
797 current->ReplaceWith(callee_graph->GetNullConstant());
798 } else if (argument->IsIntConstant()) {
799 current->ReplaceWith(callee_graph->GetIntConstant(argument->AsIntConstant()->GetValue()));
800 } else if (argument->IsLongConstant()) {
801 current->ReplaceWith(callee_graph->GetLongConstant(argument->AsLongConstant()->GetValue()));
802 } else if (argument->IsFloatConstant()) {
803 current->ReplaceWith(
804 callee_graph->GetFloatConstant(argument->AsFloatConstant()->GetValue()));
805 } else if (argument->IsDoubleConstant()) {
806 current->ReplaceWith(
807 callee_graph->GetDoubleConstant(argument->AsDoubleConstant()->GetValue()));
808 } else if (argument->GetType() == Primitive::kPrimNot) {
809 current->SetReferenceTypeInfo(argument->GetReferenceTypeInfo());
810 current->AsParameterValue()->SetCanBeNull(argument->CanBeNull());
811 }
812 }
813 }
814
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000815 // Run simple optimizations on the graph.
Calin Juravle7a9c8852015-04-21 14:07:50 +0100816 HDeadCodeElimination dce(callee_graph, stats_);
Nicolas Geoffraye34648d2015-11-23 08:59:07 +0000817 HConstantFolding fold(callee_graph);
Vladimir Markodc151b22015-10-15 18:02:30 +0100818 HSharpening sharpening(callee_graph, codegen_, dex_compilation_unit, compiler_driver_);
Calin Juravleacf735c2015-02-12 15:25:22 +0000819 InstructionSimplifier simplify(callee_graph, stats_);
Nicolas Geoffraye34648d2015-11-23 08:59:07 +0000820 IntrinsicsRecognizer intrinsics(callee_graph, compiler_driver_);
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000821
822 HOptimization* optimizations[] = {
Scott Wakelingd60a1af2015-07-22 14:32:44 +0100823 &intrinsics,
Vladimir Markodc151b22015-10-15 18:02:30 +0100824 &sharpening,
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000825 &simplify,
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700826 &fold,
Vladimir Marko9e23df52015-11-10 17:14:35 +0000827 &dce,
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000828 };
829
830 for (size_t i = 0; i < arraysize(optimizations); ++i) {
831 HOptimization* optimization = optimizations[i];
832 optimization->Run();
833 }
834
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700835 size_t number_of_instructions_budget = kMaximumNumberOfHInstructions;
Calin Juravleec748352015-07-29 13:52:12 +0100836 if (depth_ + 1 < compiler_driver_->GetCompilerOptions().GetInlineDepthLimit()) {
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000837 HInliner inliner(callee_graph,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100838 outermost_graph_,
Vladimir Markodc151b22015-10-15 18:02:30 +0100839 codegen_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000840 outer_compilation_unit_,
841 dex_compilation_unit,
842 compiler_driver_,
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100843 handles_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000844 stats_,
Nicolas Geoffray5949fa02015-12-18 10:57:10 +0000845 total_number_of_dex_registers_ + code_item->registers_size_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000846 depth_ + 1);
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000847 inliner.Run();
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700848 number_of_instructions_budget += inliner.number_of_inlined_instructions_;
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000849 }
850
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100851 // TODO: We should abort only if all predecessors throw. However,
852 // HGraph::InlineInto currently does not handle an exit block with
853 // a throw predecessor.
854 HBasicBlock* exit_block = callee_graph->GetExitBlock();
855 if (exit_block == nullptr) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100856 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100857 << " could not be inlined because it has an infinite loop";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100858 return false;
859 }
860
861 bool has_throw_predecessor = false;
Vladimir Marko60584552015-09-03 13:35:12 +0000862 for (HBasicBlock* predecessor : exit_block->GetPredecessors()) {
863 if (predecessor->GetLastInstruction()->IsThrow()) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100864 has_throw_predecessor = true;
865 break;
866 }
867 }
868 if (has_throw_predecessor) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100869 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100870 << " could not be inlined because one branch always throws";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100871 return false;
872 }
873
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000874 HReversePostOrderIterator it(*callee_graph);
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000875 it.Advance(); // Past the entry block, it does not contain instructions that prevent inlining.
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700876 size_t number_of_instructions = 0;
Nicolas Geoffray5949fa02015-12-18 10:57:10 +0000877
878 bool can_inline_environment =
879 total_number_of_dex_registers_ < kMaximumNumberOfCumulatedDexRegisters;
880
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000881 for (; !it.Done(); it.Advance()) {
882 HBasicBlock* block = it.Current();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000883
884 if (block->IsLoopHeader() && block->GetLoopInformation()->IsIrreducible()) {
885 // Don't inline methods with irreducible loops, they could prevent some
886 // optimizations to run.
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100887 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000888 << " could not be inlined because it contains an irreducible loop";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000889 return false;
890 }
891
892 for (HInstructionIterator instr_it(block->GetInstructions());
893 !instr_it.Done();
894 instr_it.Advance()) {
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700895 if (number_of_instructions++ == number_of_instructions_budget) {
896 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffray5949fa02015-12-18 10:57:10 +0000897 << " is not inlined because its caller has reached"
898 << " its instruction budget limit.";
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700899 return false;
900 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000901 HInstruction* current = instr_it.Current();
Nicolas Geoffray5949fa02015-12-18 10:57:10 +0000902 if (!can_inline_environment && current->NeedsEnvironment()) {
903 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
904 << " is not inlined because its caller has reached"
905 << " its environment budget limit.";
906 return false;
907 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000908
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100909 if (current->IsInvokeInterface()) {
910 // Disable inlining of interface calls. The cost in case of entering the
911 // resolution conflict is currently too high.
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 interface call.";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000914 return false;
915 }
916
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100917 if (!same_dex_file && current->NeedsEnvironment()) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100918 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000919 << " could not be inlined because " << current->DebugName()
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100920 << " needs an environment and is in a different dex file";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000921 return false;
922 }
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000923
Vladimir Markodc151b22015-10-15 18:02:30 +0100924 if (!same_dex_file && current->NeedsDexCacheOfDeclaringClass()) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100925 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000926 << " could not be inlined because " << current->DebugName()
927 << " it is in a different dex file and requires access to the dex cache";
928 return false;
929 }
Nicolas Geoffrayd9309292015-10-31 22:21:31 +0000930
931 if (current->IsNewInstance() &&
932 (current->AsNewInstance()->GetEntrypoint() == kQuickAllocObjectWithAccessCheck)) {
933 // Allocation entrypoint does not handle inlined frames.
934 return false;
935 }
936
937 if (current->IsNewArray() &&
938 (current->AsNewArray()->GetEntrypoint() == kQuickAllocArrayWithAccessCheck)) {
939 // Allocation entrypoint does not handle inlined frames.
940 return false;
941 }
942
943 if (current->IsUnresolvedStaticFieldGet() ||
944 current->IsUnresolvedInstanceFieldGet() ||
945 current->IsUnresolvedStaticFieldSet() ||
946 current->IsUnresolvedInstanceFieldSet()) {
947 // Entrypoint for unresolved fields does not handle inlined frames.
948 return false;
949 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000950 }
951 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700952 number_of_inlined_instructions_ += number_of_instructions;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000953
Calin Juravle2e768302015-07-28 14:41:11 +0000954 HInstruction* return_replacement = callee_graph->InlineInto(graph_, invoke_instruction);
Calin Juravle214bbcd2015-10-20 14:54:07 +0100955 if (return_replacement != nullptr) {
956 DCHECK_EQ(graph_, return_replacement->GetBlock()->GetGraph());
957 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000958 FixUpReturnReferenceType(resolved_method, invoke_instruction, return_replacement, do_rtp);
959 return true;
960}
Calin Juravle2e768302015-07-28 14:41:11 +0000961
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000962void HInliner::FixUpReturnReferenceType(ArtMethod* resolved_method,
963 HInvoke* invoke_instruction,
964 HInstruction* return_replacement,
965 bool do_rtp) {
Alex Light68289a52015-12-15 17:30:30 -0800966 // Check the integrity of reference types and run another type propagation if needed.
David Brazdil4833f5a2015-12-16 10:37:39 +0000967 if (return_replacement != nullptr) {
968 if (return_replacement->GetType() == Primitive::kPrimNot) {
969 if (!return_replacement->GetReferenceTypeInfo().IsValid()) {
970 // Make sure that we have a valid type for the return. We may get an invalid one when
971 // we inline invokes with multiple branches and create a Phi for the result.
972 // TODO: we could be more precise by merging the phi inputs but that requires
973 // some functionality from the reference type propagation.
974 DCHECK(return_replacement->IsPhi());
975 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
976 ReferenceTypeInfo::TypeHandle return_handle =
977 handles_->NewHandle(resolved_method->GetReturnType(true /* resolve */, pointer_size));
978 return_replacement->SetReferenceTypeInfo(ReferenceTypeInfo::Create(
979 return_handle, return_handle->CannotBeAssignedFromOtherTypes() /* is_exact */));
980 }
Alex Light68289a52015-12-15 17:30:30 -0800981
David Brazdil4833f5a2015-12-16 10:37:39 +0000982 if (do_rtp) {
983 // If the return type is a refinement of the declared type run the type propagation again.
984 ReferenceTypeInfo return_rti = return_replacement->GetReferenceTypeInfo();
985 ReferenceTypeInfo invoke_rti = invoke_instruction->GetReferenceTypeInfo();
986 if (invoke_rti.IsStrictSupertypeOf(return_rti)
987 || (return_rti.IsExact() && !invoke_rti.IsExact())
988 || !return_replacement->CanBeNull()) {
989 ReferenceTypePropagation(graph_, handles_).Run();
990 }
991 }
992 } else if (return_replacement->IsInstanceOf()) {
993 if (do_rtp) {
994 // Inlining InstanceOf into an If may put a tighter bound on reference types.
995 ReferenceTypePropagation(graph_, handles_).Run();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100996 }
Calin Juravlecdfed3d2015-10-26 14:05:01 +0000997 }
Calin Juravle2e768302015-07-28 14:41:11 +0000998 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000999}
1000
1001} // namespace art