blob: 1f8a58cdaa2584372dfe24fc4b9072cce716971f [file] [log] [blame]
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "inliner.h"
18
Mathieu Chartiere401d142015-04-22 13:56:20 -070019#include "art_method-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070020#include "base/enums.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000021#include "builder.h"
22#include "class_linker.h"
23#include "constant_folding.h"
24#include "dead_code_elimination.h"
Andreas Gampeb95c74b2017-04-20 19:43:21 -070025#include "dex/inline_method_analyser.h"
Vladimir Markobe10e8e2016-01-22 12:09:44 +000026#include "dex/verified_method.h"
27#include "dex/verification_results.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000028#include "driver/compiler_driver-inl.h"
Calin Juravleec748352015-07-29 13:52:12 +010029#include "driver/compiler_options.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000030#include "driver/dex_compilation_unit.h"
31#include "instruction_simplifier.h"
Scott Wakelingd60a1af2015-07-22 14:32:44 +010032#include "intrinsics.h"
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +000033#include "jit/jit.h"
34#include "jit/jit_code_cache.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000035#include "mirror/class_loader.h"
36#include "mirror/dex_cache.h"
37#include "nodes.h"
Nicolas Geoffray335005e2015-06-25 10:01:47 +010038#include "optimizing_compiler.h"
Nicolas Geoffray454a4812015-06-09 10:37:32 +010039#include "reference_type_propagation.h"
Matthew Gharritye9288852016-07-14 14:08:16 -070040#include "register_allocator_linear_scan.h"
Vladimir Markodc151b22015-10-15 18:02:30 +010041#include "sharpening.h"
David Brazdil4833f5a2015-12-16 10:37:39 +000042#include "ssa_builder.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000043#include "ssa_phi_elimination.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070044#include "scoped_thread_state_change-inl.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000045#include "thread.h"
46
47namespace art {
48
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000049// Instruction limit to control memory.
50static constexpr size_t kMaximumNumberOfTotalInstructions = 1024;
51
52// Maximum number of instructions for considering a method small,
53// which we will always try to inline if the other non-instruction limits
54// are not reached.
55static constexpr size_t kMaximumNumberOfInstructionsForSmallMethod = 3;
Nicolas Geoffray5949fa02015-12-18 10:57:10 +000056
57// Limit the number of dex registers that we accumulate while inlining
58// to avoid creating large amount of nested environments.
59static constexpr size_t kMaximumNumberOfCumulatedDexRegisters = 64;
60
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000061// Limit recursive call inlining, which do not benefit from too
62// much inlining compared to code locality.
63static constexpr size_t kMaximumNumberOfRecursiveCalls = 4;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -070064
Calin Juravlee2492d42017-03-20 11:42:13 -070065// Controls the use of inline caches in AOT mode.
Calin Juravle8af70892017-03-28 15:31:44 -070066static constexpr bool kUseAOTInlineCaches = true;
Calin Juravlee2492d42017-03-20 11:42:13 -070067
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000068// We check for line numbers to make sure the DepthString implementation
69// aligns the output nicely.
70#define LOG_INTERNAL(msg) \
71 static_assert(__LINE__ > 10, "Unhandled line number"); \
72 static_assert(__LINE__ < 10000, "Unhandled line number"); \
73 VLOG(compiler) << DepthString(__LINE__) << msg
74
75#define LOG_TRY() LOG_INTERNAL("Try inlinining call: ")
76#define LOG_NOTE() LOG_INTERNAL("Note: ")
77#define LOG_SUCCESS() LOG_INTERNAL("Success: ")
78#define LOG_FAIL(stat) MaybeRecordStat(stat); LOG_INTERNAL("Fail: ")
79#define LOG_FAIL_NO_STAT() LOG_INTERNAL("Fail: ")
80
81std::string HInliner::DepthString(int line) const {
82 std::string value;
83 // Indent according to the inlining depth.
84 size_t count = depth_;
85 // Line numbers get printed in the log, so add a space if the log's line is less
86 // than 1000, and two if less than 100. 10 cannot be reached as it's the copyright.
87 if (!kIsTargetBuild) {
88 if (line < 100) {
89 value += " ";
90 }
91 if (line < 1000) {
92 value += " ";
93 }
94 // Safeguard if this file reaches more than 10000 lines.
95 DCHECK_LT(line, 10000);
96 }
97 for (size_t i = 0; i < count; ++i) {
98 value += " ";
99 }
100 return value;
101}
102
103static size_t CountNumberOfInstructions(HGraph* graph) {
104 size_t number_of_instructions = 0;
105 for (HBasicBlock* block : graph->GetReversePostOrderSkipEntryBlock()) {
106 for (HInstructionIterator instr_it(block->GetInstructions());
107 !instr_it.Done();
108 instr_it.Advance()) {
109 ++number_of_instructions;
110 }
111 }
112 return number_of_instructions;
113}
114
115void HInliner::UpdateInliningBudget() {
116 if (total_number_of_instructions_ >= kMaximumNumberOfTotalInstructions) {
117 // Always try to inline small methods.
118 inlining_budget_ = kMaximumNumberOfInstructionsForSmallMethod;
119 } else {
120 inlining_budget_ = std::max(
121 kMaximumNumberOfInstructionsForSmallMethod,
122 kMaximumNumberOfTotalInstructions - total_number_of_instructions_);
123 }
124}
125
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000126void HInliner::Run() {
Nicolas Geoffraye50b8d22015-03-13 08:57:42 +0000127 if (graph_->IsDebuggable()) {
128 // For simplicity, we currently never inline when the graph is debuggable. This avoids
129 // doing some logic in the runtime to discover if a method could have been inlined.
130 return;
131 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000132
133 // Initialize the number of instructions for the method being compiled. Recursive calls
134 // to HInliner::Run have already updated the instruction count.
135 if (outermost_graph_ == graph_) {
136 total_number_of_instructions_ = CountNumberOfInstructions(graph_);
137 }
138
139 UpdateInliningBudget();
140 DCHECK_NE(total_number_of_instructions_, 0u);
141 DCHECK_NE(inlining_budget_, 0u);
142
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +0000143 // Keep a copy of all blocks when starting the visit.
144 ArenaVector<HBasicBlock*> blocks = graph_->GetReversePostOrder();
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100145 DCHECK(!blocks.empty());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +0000146 // Because we are changing the graph when inlining,
147 // we just iterate over the blocks of the outer method.
148 // This avoids doing the inlining work again on the inlined blocks.
149 for (HBasicBlock* block : blocks) {
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000150 for (HInstruction* instruction = block->GetFirstInstruction(); instruction != nullptr;) {
151 HInstruction* next = instruction->GetNext();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100152 HInvoke* call = instruction->AsInvoke();
Razvan A Lupusoru3e90a962015-03-27 13:44:44 -0700153 // As long as the call is not intrinsified, it is worth trying to inline.
154 if (call != nullptr && call->GetIntrinsic() == Intrinsics::kNone) {
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000155 if (kIsDebugBuild && IsCompilingWithCoreImage()) {
156 // Debugging case: directives in method names control or assert on inlining.
157 std::string callee_name = outer_compilation_unit_.GetDexFile()->PrettyMethod(
158 call->GetDexMethodIndex(), /* with_signature */ false);
159 // Tests prevent inlining by having $noinline$ in their method names.
160 if (callee_name.find("$noinline$") == std::string::npos) {
161 if (!TryInline(call)) {
162 bool should_have_inlined = (callee_name.find("$inline$") != std::string::npos);
163 CHECK(!should_have_inlined) << "Could not inline " << callee_name;
164 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000165 }
Guillaume "Vermeille" Sancheze918d382015-06-03 15:32:41 +0100166 } else {
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000167 // Normal case: try to inline.
168 TryInline(call);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000169 }
170 }
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000171 instruction = next;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000172 }
173 }
174}
175
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100176static bool IsMethodOrDeclaringClassFinal(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700177 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100178 return method->IsFinal() || method->GetDeclaringClass()->IsFinal();
179}
180
181/**
182 * Given the `resolved_method` looked up in the dex cache, try to find
183 * the actual runtime target of an interface or virtual call.
184 * Return nullptr if the runtime target cannot be proven.
185 */
186static ArtMethod* FindVirtualOrInterfaceTarget(HInvoke* invoke, ArtMethod* resolved_method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700187 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100188 if (IsMethodOrDeclaringClassFinal(resolved_method)) {
189 // No need to lookup further, the resolved method will be the target.
190 return resolved_method;
191 }
192
193 HInstruction* receiver = invoke->InputAt(0);
194 if (receiver->IsNullCheck()) {
195 // Due to multiple levels of inlining within the same pass, it might be that
196 // null check does not have the reference type of the actual receiver.
197 receiver = receiver->InputAt(0);
198 }
199 ReferenceTypeInfo info = receiver->GetReferenceTypeInfo();
Calin Juravle2e768302015-07-28 14:41:11 +0000200 DCHECK(info.IsValid()) << "Invalid RTI for " << receiver->DebugName();
201 if (!info.IsExact()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100202 // We currently only support inlining with known receivers.
203 // TODO: Remove this check, we should be able to inline final methods
204 // on unknown receivers.
205 return nullptr;
206 } else if (info.GetTypeHandle()->IsInterface()) {
207 // Statically knowing that the receiver has an interface type cannot
208 // help us find what is the target method.
209 return nullptr;
210 } else if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(info.GetTypeHandle().Get())) {
211 // The method that we're trying to call is not in the receiver's class or super classes.
212 return nullptr;
Nicolas Geoffrayab5327d2016-03-18 11:36:20 +0000213 } else if (info.GetTypeHandle()->IsErroneous()) {
214 // If the type is erroneous, do not go further, as we are going to query the vtable or
215 // imt table, that we can only safely do on non-erroneous classes.
216 return nullptr;
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100217 }
218
219 ClassLinker* cl = Runtime::Current()->GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700220 PointerSize pointer_size = cl->GetImagePointerSize();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100221 if (invoke->IsInvokeInterface()) {
222 resolved_method = info.GetTypeHandle()->FindVirtualMethodForInterface(
223 resolved_method, pointer_size);
224 } else {
225 DCHECK(invoke->IsInvokeVirtual());
226 resolved_method = info.GetTypeHandle()->FindVirtualMethodForVirtual(
227 resolved_method, pointer_size);
228 }
229
230 if (resolved_method == nullptr) {
231 // The information we had on the receiver was not enough to find
232 // the target method. Since we check above the exact type of the receiver,
233 // the only reason this can happen is an IncompatibleClassChangeError.
234 return nullptr;
Alex Light9139e002015-10-09 15:59:48 -0700235 } else if (!resolved_method->IsInvokable()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100236 // The information we had on the receiver was not enough to find
237 // the target method. Since we check above the exact type of the receiver,
238 // the only reason this can happen is an IncompatibleClassChangeError.
239 return nullptr;
240 } else if (IsMethodOrDeclaringClassFinal(resolved_method)) {
241 // A final method has to be the target method.
242 return resolved_method;
243 } else if (info.IsExact()) {
244 // If we found a method and the receiver's concrete type is statically
245 // known, we know for sure the target.
246 return resolved_method;
247 } else {
248 // Even if we did find a method, the receiver type was not enough to
249 // statically find the runtime target.
250 return nullptr;
251 }
252}
253
254static uint32_t FindMethodIndexIn(ArtMethod* method,
255 const DexFile& dex_file,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000256 uint32_t name_and_signature_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700257 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100258 if (IsSameDexFile(*method->GetDexFile(), dex_file)) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100259 return method->GetDexMethodIndex();
260 } else {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000261 return method->FindDexMethodIndexInOtherDexFile(dex_file, name_and_signature_index);
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100262 }
263}
264
Andreas Gampea5b09a62016-11-17 15:21:22 -0800265static dex::TypeIndex FindClassIndexIn(mirror::Class* cls,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000266 const DexCompilationUnit& compilation_unit)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700267 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000268 const DexFile& dex_file = *compilation_unit.GetDexFile();
Andreas Gampea5b09a62016-11-17 15:21:22 -0800269 dex::TypeIndex index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100270 if (cls->GetDexCache() == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700271 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000272 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800273 } else if (!cls->GetDexTypeIndex().IsValid()) {
David Sehr709b0702016-10-13 09:12:37 -0700274 DCHECK(cls->IsProxyClass()) << cls->PrettyClass();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100275 // TODO: deal with proxy classes.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100276 } else if (IsSameDexFile(cls->GetDexFile(), dex_file)) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000277 DCHECK_EQ(cls->GetDexCache(), compilation_unit.GetDexCache().Get());
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000278 index = cls->GetDexTypeIndex();
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100279 } else {
280 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000281 // We cannot guarantee the entry will resolve to the same class,
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100282 // as there may be different class loaders. So only return the index if it's
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000283 // the right class already resolved with the class loader.
284 if (index.IsValid()) {
285 ObjPtr<mirror::Class> resolved = ClassLinker::LookupResolvedType(
286 index, compilation_unit.GetDexCache().Get(), compilation_unit.GetClassLoader().Get());
287 if (resolved != cls) {
288 index = dex::TypeIndex::Invalid();
289 }
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100290 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100291 }
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000292
293 return index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100294}
295
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000296class ScopedProfilingInfoInlineUse {
297 public:
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000298 explicit ScopedProfilingInfoInlineUse(ArtMethod* method, Thread* self)
299 : method_(method),
300 self_(self),
301 // Fetch the profiling info ahead of using it. If it's null when fetching,
302 // we should not call JitCodeCache::DoneInlining.
303 profiling_info_(
304 Runtime::Current()->GetJit()->GetCodeCache()->NotifyCompilerUse(method, self)) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000305 }
306
307 ~ScopedProfilingInfoInlineUse() {
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000308 if (profiling_info_ != nullptr) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700309 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000310 DCHECK_EQ(profiling_info_, method_->GetProfilingInfo(pointer_size));
311 Runtime::Current()->GetJit()->GetCodeCache()->DoneCompilerUse(method_, self_);
312 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000313 }
314
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000315 ProfilingInfo* GetProfilingInfo() const { return profiling_info_; }
316
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000317 private:
318 ArtMethod* const method_;
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000319 Thread* const self_;
320 ProfilingInfo* const profiling_info_;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000321};
322
Calin Juravle13439f02017-02-21 01:17:21 -0800323HInliner::InlineCacheType HInliner::GetInlineCacheType(
324 const Handle<mirror::ObjectArray<mirror::Class>>& classes)
325 REQUIRES_SHARED(Locks::mutator_lock_) {
326 uint8_t number_of_types = 0;
327 for (; number_of_types < InlineCache::kIndividualCacheSize; ++number_of_types) {
328 if (classes->Get(number_of_types) == nullptr) {
329 break;
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000330 }
331 }
Calin Juravle13439f02017-02-21 01:17:21 -0800332
333 if (number_of_types == 0) {
334 return kInlineCacheUninitialized;
335 } else if (number_of_types == 1) {
336 return kInlineCacheMonomorphic;
337 } else if (number_of_types == InlineCache::kIndividualCacheSize) {
338 return kInlineCacheMegamorphic;
339 } else {
340 return kInlineCachePolymorphic;
341 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000342}
343
344static mirror::Class* GetMonomorphicType(Handle<mirror::ObjectArray<mirror::Class>> classes)
345 REQUIRES_SHARED(Locks::mutator_lock_) {
346 DCHECK(classes->Get(0) != nullptr);
347 return classes->Get(0);
348}
349
Mingyao Yang063fc772016-08-02 11:02:54 -0700350ArtMethod* HInliner::TryCHADevirtualization(ArtMethod* resolved_method) {
351 if (!resolved_method->HasSingleImplementation()) {
352 return nullptr;
353 }
354 if (Runtime::Current()->IsAotCompiler()) {
355 // No CHA-based devirtulization for AOT compiler (yet).
356 return nullptr;
357 }
358 if (outermost_graph_->IsCompilingOsr()) {
359 // We do not support HDeoptimize in OSR methods.
360 return nullptr;
361 }
Mingyao Yange8fcd012017-01-20 10:43:30 -0800362 PointerSize pointer_size = caller_compilation_unit_.GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +0000363 ArtMethod* single_impl = resolved_method->GetSingleImplementation(pointer_size);
364 if (single_impl == nullptr) {
365 return nullptr;
366 }
367 if (single_impl->IsProxyMethod()) {
368 // Proxy method is a generic invoker that's not worth
369 // devirtualizing/inlining. It also causes issues when the proxy
370 // method is in another dex file if we try to rewrite invoke-interface to
371 // invoke-virtual because a proxy method doesn't have a real dex file.
372 return nullptr;
373 }
Nicolas Geoffray8e33e842017-04-03 16:55:16 +0100374 if (!single_impl->GetDeclaringClass()->IsResolved()) {
375 // There's a race with the class loading, which updates the CHA info
376 // before setting the class to resolved. So we just bail for this
377 // rare occurence.
378 return nullptr;
379 }
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +0000380 return single_impl;
Mingyao Yang063fc772016-08-02 11:02:54 -0700381}
382
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700383bool HInliner::TryInline(HInvoke* invoke_instruction) {
Orion Hodsonac141392017-01-13 11:53:47 +0000384 if (invoke_instruction->IsInvokeUnresolved() ||
385 invoke_instruction->IsInvokePolymorphic()) {
386 return false; // Don't bother to move further if we know the method is unresolved or an
387 // invoke-polymorphic.
Calin Juravle175dc732015-08-25 15:42:32 +0100388 }
389
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000390 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100391 uint32_t method_index = invoke_instruction->GetDexMethodIndex();
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000392 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000393 LOG_TRY() << caller_dex_file.PrettyMethod(method_index);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000394
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100395 ArtMethod* resolved_method = invoke_instruction->GetResolvedMethod();
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100396 if (resolved_method == nullptr) {
397 DCHECK(invoke_instruction->IsInvokeStaticOrDirect());
398 DCHECK(invoke_instruction->AsInvokeStaticOrDirect()->IsStringInit());
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000399 LOG_FAIL_NO_STAT() << "Not inlining a String.<init> method";
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100400 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000401 }
402 ArtMethod* actual_method = nullptr;
403
404 if (invoke_instruction->IsInvokeStaticOrDirect()) {
Andreas Gampefd2140f2015-12-23 16:30:44 -0800405 actual_method = resolved_method;
Vladimir Marko58155012015-08-19 12:49:41 +0000406 } else {
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100407 // Check if we can statically find the method.
408 actual_method = FindVirtualOrInterfaceTarget(invoke_instruction, resolved_method);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000409 }
410
Mingyao Yang063fc772016-08-02 11:02:54 -0700411 bool cha_devirtualize = false;
412 if (actual_method == nullptr) {
413 ArtMethod* method = TryCHADevirtualization(resolved_method);
414 if (method != nullptr) {
415 cha_devirtualize = true;
416 actual_method = method;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000417 LOG_NOTE() << "Try CHA-based inlining of " << actual_method->PrettyMethod();
Mingyao Yang063fc772016-08-02 11:02:54 -0700418 }
419 }
420
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100421 if (actual_method != nullptr) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700422 bool result = TryInlineAndReplace(invoke_instruction,
423 actual_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000424 ReferenceTypeInfo::CreateInvalid(),
Mingyao Yang063fc772016-08-02 11:02:54 -0700425 /* do_rtp */ true,
426 cha_devirtualize);
Calin Juravle69158982016-03-16 11:53:41 +0000427 if (result && !invoke_instruction->IsInvokeStaticOrDirect()) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700428 if (cha_devirtualize) {
429 // Add dependency due to devirtulization. We've assumed resolved_method
430 // has single implementation.
431 outermost_graph_->AddCHASingleImplementationDependency(resolved_method);
432 MaybeRecordStat(kCHAInline);
433 } else {
434 MaybeRecordStat(kInlinedInvokeVirtualOrInterface);
435 }
Calin Juravle69158982016-03-16 11:53:41 +0000436 }
437 return result;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100438 }
Andreas Gampefd2140f2015-12-23 16:30:44 -0800439 DCHECK(!invoke_instruction->IsInvokeStaticOrDirect());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100440
Calin Juravle13439f02017-02-21 01:17:21 -0800441 // Try using inline caches.
442 return TryInlineFromInlineCache(caller_dex_file, invoke_instruction, resolved_method);
443}
444
445static Handle<mirror::ObjectArray<mirror::Class>> AllocateInlineCacheHolder(
446 const DexCompilationUnit& compilation_unit,
447 StackHandleScope<1>* hs)
448 REQUIRES_SHARED(Locks::mutator_lock_) {
449 Thread* self = Thread::Current();
450 ClassLinker* class_linker = compilation_unit.GetClassLinker();
451 Handle<mirror::ObjectArray<mirror::Class>> inline_cache = hs->NewHandle(
452 mirror::ObjectArray<mirror::Class>::Alloc(
453 self,
454 class_linker->GetClassRoot(ClassLinker::kClassArrayClass),
455 InlineCache::kIndividualCacheSize));
456 if (inline_cache == nullptr) {
457 // We got an OOME. Just clear the exception, and don't inline.
458 DCHECK(self->IsExceptionPending());
459 self->ClearException();
460 VLOG(compiler) << "Out of memory in the compiler when trying to inline";
461 }
462 return inline_cache;
463}
464
465bool HInliner::TryInlineFromInlineCache(const DexFile& caller_dex_file,
466 HInvoke* invoke_instruction,
467 ArtMethod* resolved_method)
468 REQUIRES_SHARED(Locks::mutator_lock_) {
Calin Juravlee2492d42017-03-20 11:42:13 -0700469 if (Runtime::Current()->IsAotCompiler() && !kUseAOTInlineCaches) {
470 return false;
471 }
472
Calin Juravle13439f02017-02-21 01:17:21 -0800473 StackHandleScope<1> hs(Thread::Current());
474 Handle<mirror::ObjectArray<mirror::Class>> inline_cache;
475 InlineCacheType inline_cache_type = Runtime::Current()->IsAotCompiler()
476 ? GetInlineCacheAOT(caller_dex_file, invoke_instruction, &hs, &inline_cache)
477 : GetInlineCacheJIT(invoke_instruction, &hs, &inline_cache);
478
479 switch (inline_cache_type) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000480 case kInlineCacheNoData: {
481 LOG_FAIL_NO_STAT()
482 << "Interface or virtual call to "
483 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
484 << " could not be statically determined";
Calin Juravle13439f02017-02-21 01:17:21 -0800485 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000486 }
Calin Juravle13439f02017-02-21 01:17:21 -0800487
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000488 case kInlineCacheUninitialized: {
489 LOG_FAIL_NO_STAT()
490 << "Interface or virtual call to "
491 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
492 << " is not hit and not inlined";
493 return false;
494 }
495
496 case kInlineCacheMonomorphic: {
Calin Juravle13439f02017-02-21 01:17:21 -0800497 MaybeRecordStat(kMonomorphicCall);
498 if (outermost_graph_->IsCompilingOsr()) {
499 // If we are compiling OSR, we pretend this call is polymorphic, as we may come from the
500 // interpreter and it may have seen different receiver types.
501 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000502 } else {
Calin Juravle13439f02017-02-21 01:17:21 -0800503 return TryInlineMonomorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000504 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000505 }
Calin Juravle13439f02017-02-21 01:17:21 -0800506
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000507 case kInlineCachePolymorphic: {
Calin Juravle13439f02017-02-21 01:17:21 -0800508 MaybeRecordStat(kPolymorphicCall);
509 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000510 }
Calin Juravle13439f02017-02-21 01:17:21 -0800511
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000512 case kInlineCacheMegamorphic: {
513 LOG_FAIL_NO_STAT()
514 << "Interface or virtual call to "
515 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
516 << " is megamorphic and not inlined";
Calin Juravle13439f02017-02-21 01:17:21 -0800517 MaybeRecordStat(kMegamorphicCall);
518 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000519 }
Calin Juravle13439f02017-02-21 01:17:21 -0800520
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000521 case kInlineCacheMissingTypes: {
522 LOG_FAIL_NO_STAT()
523 << "Interface or virtual call to "
524 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
525 << " is missing types and not inlined";
Calin Juravle13439f02017-02-21 01:17:21 -0800526 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000527 }
Calin Juravle13439f02017-02-21 01:17:21 -0800528 }
529 UNREACHABLE();
530}
531
532HInliner::InlineCacheType HInliner::GetInlineCacheJIT(
533 HInvoke* invoke_instruction,
534 StackHandleScope<1>* hs,
535 /*out*/Handle<mirror::ObjectArray<mirror::Class>>* inline_cache)
536 REQUIRES_SHARED(Locks::mutator_lock_) {
537 DCHECK(Runtime::Current()->UseJitCompilation());
538
539 ArtMethod* caller = graph_->GetArtMethod();
540 // Under JIT, we should always know the caller.
541 DCHECK(caller != nullptr);
542 ScopedProfilingInfoInlineUse spiis(caller, Thread::Current());
543 ProfilingInfo* profiling_info = spiis.GetProfilingInfo();
544
545 if (profiling_info == nullptr) {
546 return kInlineCacheNoData;
547 }
548
549 *inline_cache = AllocateInlineCacheHolder(caller_compilation_unit_, hs);
550 if (inline_cache->Get() == nullptr) {
551 // We can't extract any data if we failed to allocate;
552 return kInlineCacheNoData;
553 } else {
554 Runtime::Current()->GetJit()->GetCodeCache()->CopyInlineCacheInto(
555 *profiling_info->GetInlineCache(invoke_instruction->GetDexPc()),
556 *inline_cache);
557 return GetInlineCacheType(*inline_cache);
558 }
559}
560
561HInliner::InlineCacheType HInliner::GetInlineCacheAOT(
562 const DexFile& caller_dex_file,
563 HInvoke* invoke_instruction,
564 StackHandleScope<1>* hs,
565 /*out*/Handle<mirror::ObjectArray<mirror::Class>>* inline_cache)
566 REQUIRES_SHARED(Locks::mutator_lock_) {
567 DCHECK(Runtime::Current()->IsAotCompiler());
568 const ProfileCompilationInfo* pci = compiler_driver_->GetProfileCompilationInfo();
569 if (pci == nullptr) {
570 return kInlineCacheNoData;
571 }
572
573 ProfileCompilationInfo::OfflineProfileMethodInfo offline_profile;
574 bool found = pci->GetMethod(caller_dex_file.GetLocation(),
575 caller_dex_file.GetLocationChecksum(),
576 caller_compilation_unit_.GetDexMethodIndex(),
577 &offline_profile);
578 if (!found) {
579 return kInlineCacheNoData; // no profile information for this invocation.
580 }
581
582 *inline_cache = AllocateInlineCacheHolder(caller_compilation_unit_, hs);
583 if (inline_cache == nullptr) {
584 // We can't extract any data if we failed to allocate;
585 return kInlineCacheNoData;
586 } else {
587 return ExtractClassesFromOfflineProfile(invoke_instruction,
588 offline_profile,
589 *inline_cache);
590 }
591}
592
593HInliner::InlineCacheType HInliner::ExtractClassesFromOfflineProfile(
594 const HInvoke* invoke_instruction,
595 const ProfileCompilationInfo::OfflineProfileMethodInfo& offline_profile,
596 /*out*/Handle<mirror::ObjectArray<mirror::Class>> inline_cache)
597 REQUIRES_SHARED(Locks::mutator_lock_) {
598 const auto it = offline_profile.inline_caches.find(invoke_instruction->GetDexPc());
599 if (it == offline_profile.inline_caches.end()) {
600 return kInlineCacheUninitialized;
601 }
602
603 const ProfileCompilationInfo::DexPcData& dex_pc_data = it->second;
604
605 if (dex_pc_data.is_missing_types) {
606 return kInlineCacheMissingTypes;
607 }
608 if (dex_pc_data.is_megamorphic) {
609 return kInlineCacheMegamorphic;
610 }
611
612 DCHECK_LE(dex_pc_data.classes.size(), InlineCache::kIndividualCacheSize);
613 Thread* self = Thread::Current();
614 // We need to resolve the class relative to the containing dex file.
615 // So first, build a mapping from the index of dex file in the profile to
616 // its dex cache. This will avoid repeating the lookup when walking over
617 // the inline cache types.
618 std::vector<ObjPtr<mirror::DexCache>> dex_profile_index_to_dex_cache(
619 offline_profile.dex_references.size());
620 for (size_t i = 0; i < offline_profile.dex_references.size(); i++) {
621 bool found = false;
622 for (const DexFile* dex_file : compiler_driver_->GetDexFilesForOatFile()) {
623 if (offline_profile.dex_references[i].MatchesDex(dex_file)) {
624 dex_profile_index_to_dex_cache[i] =
625 caller_compilation_unit_.GetClassLinker()->FindDexCache(self, *dex_file);
626 found = true;
627 }
628 }
629 if (!found) {
630 VLOG(compiler) << "Could not find profiled dex file: "
631 << offline_profile.dex_references[i].dex_location;
632 return kInlineCacheMissingTypes;
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100633 }
634 }
635
Calin Juravle13439f02017-02-21 01:17:21 -0800636 // Walk over the classes and resolve them. If we cannot find a type we return
637 // kInlineCacheMissingTypes.
638 int ic_index = 0;
639 for (const ProfileCompilationInfo::ClassReference& class_ref : dex_pc_data.classes) {
640 ObjPtr<mirror::DexCache> dex_cache =
641 dex_profile_index_to_dex_cache[class_ref.dex_profile_index];
642 DCHECK(dex_cache != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000643 ObjPtr<mirror::Class> clazz = ClassLinker::LookupResolvedType(
644 class_ref.type_index,
645 dex_cache,
646 caller_compilation_unit_.GetClassLoader().Get());
Calin Juravle13439f02017-02-21 01:17:21 -0800647 if (clazz != nullptr) {
648 inline_cache->Set(ic_index++, clazz);
649 } else {
650 VLOG(compiler) << "Could not resolve class from inline cache in AOT mode "
651 << caller_compilation_unit_.GetDexFile()->PrettyMethod(
652 invoke_instruction->GetDexMethodIndex()) << " : "
653 << caller_compilation_unit_
654 .GetDexFile()->StringByTypeIdx(class_ref.type_index);
655 return kInlineCacheMissingTypes;
656 }
657 }
658 return GetInlineCacheType(inline_cache);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100659}
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000660
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000661HInstanceFieldGet* HInliner::BuildGetReceiverClass(ClassLinker* class_linker,
662 HInstruction* receiver,
663 uint32_t dex_pc) const {
664 ArtField* field = class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0);
665 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000666 HInstanceFieldGet* result = new (graph_->GetArena()) HInstanceFieldGet(
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000667 receiver,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000668 field,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000669 Primitive::kPrimNot,
670 field->GetOffset(),
671 field->IsVolatile(),
672 field->GetDexFieldIndex(),
673 field->GetDeclaringClass()->GetDexClassDefIndex(),
674 *field->GetDexFile(),
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000675 dex_pc);
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000676 // The class of a field is effectively final, and does not have any memory dependencies.
677 result->SetSideEffects(SideEffects::None());
678 return result;
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000679}
680
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000681static ArtMethod* ResolveMethodFromInlineCache(Handle<mirror::Class> klass,
682 ArtMethod* resolved_method,
683 HInstruction* invoke_instruction,
684 PointerSize pointer_size)
685 REQUIRES_SHARED(Locks::mutator_lock_) {
686 if (Runtime::Current()->IsAotCompiler()) {
687 // We can get unrelated types when working with profiles (corruption,
688 // systme updates, or anyone can write to it). So first check if the class
689 // actually implements the declaring class of the method that is being
690 // called in bytecode.
691 // Note: the lookup methods used below require to have assignable types.
692 if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(klass.Get())) {
693 return nullptr;
694 }
695 }
696
697 if (invoke_instruction->IsInvokeInterface()) {
698 resolved_method = klass->FindVirtualMethodForInterface(resolved_method, pointer_size);
699 } else {
700 DCHECK(invoke_instruction->IsInvokeVirtual());
701 resolved_method = klass->FindVirtualMethodForVirtual(resolved_method, pointer_size);
702 }
703 DCHECK(resolved_method != nullptr);
704 return resolved_method;
705}
706
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100707bool HInliner::TryInlineMonomorphicCall(HInvoke* invoke_instruction,
708 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000709 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000710 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
711 << invoke_instruction->DebugName();
712
Andreas Gampea5b09a62016-11-17 15:21:22 -0800713 dex::TypeIndex class_index = FindClassIndexIn(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000714 GetMonomorphicType(classes), caller_compilation_unit_);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800715 if (!class_index.IsValid()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000716 LOG_FAIL(kNotInlinedDexCache)
717 << "Call to " << ArtMethod::PrettyMethod(resolved_method)
718 << " from inline cache is not inlined because its class is not"
719 << " accessible to the caller";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100720 return false;
721 }
722
723 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700724 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000725 Handle<mirror::Class> monomorphic_type = handles_->NewHandle(GetMonomorphicType(classes));
726 resolved_method = ResolveMethodFromInlineCache(
727 monomorphic_type, resolved_method, invoke_instruction, pointer_size);
728
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000729 LOG_NOTE() << "Try inline monomorphic call to " << resolved_method->PrettyMethod();
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000730 if (resolved_method == nullptr) {
731 // Bogus AOT profile, bail.
732 DCHECK(Runtime::Current()->IsAotCompiler());
733 return false;
734 }
735
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100736 HInstruction* receiver = invoke_instruction->InputAt(0);
737 HInstruction* cursor = invoke_instruction->GetPrevious();
738 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Mingyao Yang063fc772016-08-02 11:02:54 -0700739 if (!TryInlineAndReplace(invoke_instruction,
740 resolved_method,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000741 ReferenceTypeInfo::Create(monomorphic_type, /* is_exact */ true),
Mingyao Yang063fc772016-08-02 11:02:54 -0700742 /* do_rtp */ false,
743 /* cha_devirtualize */ false)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100744 return false;
745 }
746
747 // We successfully inlined, now add a guard.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000748 AddTypeGuard(receiver,
749 cursor,
750 bb_cursor,
751 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000752 monomorphic_type,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000753 invoke_instruction,
754 /* with_deoptimization */ true);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100755
756 // Run type propagation to get the guard typed, and eventually propagate the
757 // type of the receiver.
Vladimir Marko456307a2016-04-19 14:12:13 +0000758 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000759 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +0000760 outer_compilation_unit_.GetDexCache(),
761 handles_,
762 /* is_first_run */ false);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100763 rtp_fixup.Run();
764
765 MaybeRecordStat(kInlinedMonomorphicCall);
766 return true;
767}
768
Mingyao Yang063fc772016-08-02 11:02:54 -0700769void HInliner::AddCHAGuard(HInstruction* invoke_instruction,
770 uint32_t dex_pc,
771 HInstruction* cursor,
772 HBasicBlock* bb_cursor) {
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800773 HShouldDeoptimizeFlag* deopt_flag = new (graph_->GetArena())
774 HShouldDeoptimizeFlag(graph_->GetArena(), dex_pc);
775 HInstruction* compare = new (graph_->GetArena()) HNotEqual(
Mingyao Yang063fc772016-08-02 11:02:54 -0700776 deopt_flag, graph_->GetIntConstant(0, dex_pc));
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000777 HInstruction* deopt = new (graph_->GetArena()) HDeoptimize(
778 graph_->GetArena(), compare, HDeoptimize::Kind::kInline, dex_pc);
Mingyao Yang063fc772016-08-02 11:02:54 -0700779
780 if (cursor != nullptr) {
781 bb_cursor->InsertInstructionAfter(deopt_flag, cursor);
782 } else {
783 bb_cursor->InsertInstructionBefore(deopt_flag, bb_cursor->GetFirstInstruction());
784 }
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800785 bb_cursor->InsertInstructionAfter(compare, deopt_flag);
786 bb_cursor->InsertInstructionAfter(deopt, compare);
787
788 // Add receiver as input to aid CHA guard optimization later.
789 deopt_flag->AddInput(invoke_instruction->InputAt(0));
790 DCHECK_EQ(deopt_flag->InputCount(), 1u);
Mingyao Yang063fc772016-08-02 11:02:54 -0700791 deopt->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800792 outermost_graph_->IncrementNumberOfCHAGuards();
Mingyao Yang063fc772016-08-02 11:02:54 -0700793}
794
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000795HInstruction* HInliner::AddTypeGuard(HInstruction* receiver,
796 HInstruction* cursor,
797 HBasicBlock* bb_cursor,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800798 dex::TypeIndex class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000799 Handle<mirror::Class> klass,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000800 HInstruction* invoke_instruction,
801 bool with_deoptimization) {
802 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
803 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
804 class_linker, receiver, invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000805 if (cursor != nullptr) {
806 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
807 } else {
808 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
809 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000810
811 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000812 bool is_referrer = (klass.Get() == outermost_graph_->GetArtMethod()->GetDeclaringClass());
Nicolas Geoffray56876342016-12-16 16:09:08 +0000813 // Note that we will just compare the classes, so we don't need Java semantics access checks.
814 // Note that the type index and the dex file are relative to the method this type guard is
815 // inlined into.
816 HLoadClass* load_class = new (graph_->GetArena()) HLoadClass(graph_->GetCurrentMethod(),
817 class_index,
818 caller_dex_file,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000819 klass,
Nicolas Geoffray56876342016-12-16 16:09:08 +0000820 is_referrer,
821 invoke_instruction->GetDexPc(),
822 /* needs_access_check */ false);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000823 HLoadClass::LoadKind kind = HSharpening::ComputeLoadClassKind(
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000824 load_class, codegen_, compiler_driver_, caller_compilation_unit_);
825 DCHECK(kind != HLoadClass::LoadKind::kInvalid)
826 << "We should always be able to reference a class for inline caches";
827 // Insert before setting the kind, as setting the kind affects the inputs.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000828 bb_cursor->InsertInstructionAfter(load_class, receiver_class);
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000829 load_class->SetLoadKind(kind);
Calin Juravle13439f02017-02-21 01:17:21 -0800830 // In AOT mode, we will most likely load the class from BSS, which will involve a call
831 // to the runtime. In this case, the load instruction will need an environment so copy
832 // it from the invoke instruction.
833 if (load_class->NeedsEnvironment()) {
834 DCHECK(Runtime::Current()->IsAotCompiler());
835 load_class->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
836 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000837
Nicolas Geoffray56876342016-12-16 16:09:08 +0000838 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(load_class, receiver_class);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000839 bb_cursor->InsertInstructionAfter(compare, load_class);
840 if (with_deoptimization) {
841 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000842 graph_->GetArena(),
843 compare,
844 receiver,
845 HDeoptimize::Kind::kInline,
846 invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000847 bb_cursor->InsertInstructionAfter(deoptimize, compare);
848 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000849 DCHECK_EQ(invoke_instruction->InputAt(0), receiver);
850 receiver->ReplaceUsesDominatedBy(deoptimize, deoptimize);
851 deoptimize->SetReferenceTypeInfo(receiver->GetReferenceTypeInfo());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000852 }
853 return compare;
854}
855
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000856bool HInliner::TryInlinePolymorphicCall(HInvoke* invoke_instruction,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100857 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000858 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000859 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
860 << invoke_instruction->DebugName();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000861
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000862 if (TryInlinePolymorphicCallToSameTarget(invoke_instruction, resolved_method, classes)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000863 return true;
864 }
865
866 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700867 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000868
869 bool all_targets_inlined = true;
870 bool one_target_inlined = false;
871 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000872 if (classes->Get(i) == nullptr) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000873 break;
874 }
875 ArtMethod* method = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000876
877 Handle<mirror::Class> handle = handles_->NewHandle(classes->Get(i));
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000878 method = ResolveMethodFromInlineCache(
879 handle, resolved_method, invoke_instruction, pointer_size);
880 if (method == nullptr) {
881 DCHECK(Runtime::Current()->IsAotCompiler());
882 // AOT profile is bogus. This loop expects to iterate over all entries,
883 // so just just continue.
884 all_targets_inlined = false;
885 continue;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000886 }
887
888 HInstruction* receiver = invoke_instruction->InputAt(0);
889 HInstruction* cursor = invoke_instruction->GetPrevious();
890 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
891
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000892 dex::TypeIndex class_index = FindClassIndexIn(handle.Get(), caller_compilation_unit_);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000893 HInstruction* return_replacement = nullptr;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000894 LOG_NOTE() << "Try inline polymorphic call to " << method->PrettyMethod();
Andreas Gampea5b09a62016-11-17 15:21:22 -0800895 if (!class_index.IsValid() ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000896 !TryBuildAndInline(invoke_instruction,
897 method,
898 ReferenceTypeInfo::Create(handle, /* is_exact */ true),
899 &return_replacement)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000900 all_targets_inlined = false;
901 } else {
902 one_target_inlined = true;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000903
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000904 LOG_SUCCESS() << "Polymorphic call to " << ArtMethod::PrettyMethod(resolved_method)
905 << " has inlined " << ArtMethod::PrettyMethod(method);
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000906
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000907 // If we have inlined all targets before, and this receiver is the last seen,
908 // we deoptimize instead of keeping the original invoke instruction.
909 bool deoptimize = all_targets_inlined &&
910 (i != InlineCache::kIndividualCacheSize - 1) &&
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000911 (classes->Get(i + 1) == nullptr);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100912
913 if (outermost_graph_->IsCompilingOsr()) {
914 // We do not support HDeoptimize in OSR methods.
915 deoptimize = false;
916 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000917 HInstruction* compare = AddTypeGuard(receiver,
918 cursor,
919 bb_cursor,
920 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000921 handle,
Nicolas Geoffray56876342016-12-16 16:09:08 +0000922 invoke_instruction,
923 deoptimize);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000924 if (deoptimize) {
925 if (return_replacement != nullptr) {
926 invoke_instruction->ReplaceWith(return_replacement);
927 }
928 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
929 // Because the inline cache data can be populated concurrently, we force the end of the
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000930 // iteration. Otherwise, we could see a new receiver type.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000931 break;
932 } else {
933 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
934 }
935 }
936 }
937
938 if (!one_target_inlined) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000939 LOG_FAIL_NO_STAT()
940 << "Call to " << ArtMethod::PrettyMethod(resolved_method)
941 << " from inline cache is not inlined because none"
942 << " of its targets could be inlined";
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000943 return false;
944 }
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000945
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000946 MaybeRecordStat(kInlinedPolymorphicCall);
947
948 // Run type propagation to get the guards typed.
Vladimir Marko456307a2016-04-19 14:12:13 +0000949 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000950 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +0000951 outer_compilation_unit_.GetDexCache(),
952 handles_,
953 /* is_first_run */ false);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000954 rtp_fixup.Run();
955 return true;
956}
957
958void HInliner::CreateDiamondPatternForPolymorphicInline(HInstruction* compare,
959 HInstruction* return_replacement,
960 HInstruction* invoke_instruction) {
961 uint32_t dex_pc = invoke_instruction->GetDexPc();
962 HBasicBlock* cursor_block = compare->GetBlock();
963 HBasicBlock* original_invoke_block = invoke_instruction->GetBlock();
964 ArenaAllocator* allocator = graph_->GetArena();
965
966 // Spit the block after the compare: `cursor_block` will now be the start of the diamond,
967 // and the returned block is the start of the then branch (that could contain multiple blocks).
968 HBasicBlock* then = cursor_block->SplitAfterForInlining(compare);
969
970 // Split the block containing the invoke before and after the invoke. The returned block
971 // of the split before will contain the invoke and will be the otherwise branch of
972 // the diamond. The returned block of the split after will be the merge block
973 // of the diamond.
974 HBasicBlock* end_then = invoke_instruction->GetBlock();
975 HBasicBlock* otherwise = end_then->SplitBeforeForInlining(invoke_instruction);
976 HBasicBlock* merge = otherwise->SplitAfterForInlining(invoke_instruction);
977
978 // If the methods we are inlining return a value, we create a phi in the merge block
979 // that will have the `invoke_instruction and the `return_replacement` as inputs.
980 if (return_replacement != nullptr) {
981 HPhi* phi = new (allocator) HPhi(
982 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke_instruction->GetType()), dex_pc);
983 merge->AddPhi(phi);
984 invoke_instruction->ReplaceWith(phi);
985 phi->AddInput(return_replacement);
986 phi->AddInput(invoke_instruction);
987 }
988
989 // Add the control flow instructions.
990 otherwise->AddInstruction(new (allocator) HGoto(dex_pc));
991 end_then->AddInstruction(new (allocator) HGoto(dex_pc));
992 cursor_block->AddInstruction(new (allocator) HIf(compare, dex_pc));
993
994 // Add the newly created blocks to the graph.
995 graph_->AddBlock(then);
996 graph_->AddBlock(otherwise);
997 graph_->AddBlock(merge);
998
999 // Set up successor (and implictly predecessor) relations.
1000 cursor_block->AddSuccessor(otherwise);
1001 cursor_block->AddSuccessor(then);
1002 end_then->AddSuccessor(merge);
1003 otherwise->AddSuccessor(merge);
1004
1005 // Set up dominance information.
1006 then->SetDominator(cursor_block);
1007 cursor_block->AddDominatedBlock(then);
1008 otherwise->SetDominator(cursor_block);
1009 cursor_block->AddDominatedBlock(otherwise);
1010 merge->SetDominator(cursor_block);
1011 cursor_block->AddDominatedBlock(merge);
1012
1013 // Update the revert post order.
1014 size_t index = IndexOfElement(graph_->reverse_post_order_, cursor_block);
1015 MakeRoomFor(&graph_->reverse_post_order_, 1, index);
1016 graph_->reverse_post_order_[++index] = then;
1017 index = IndexOfElement(graph_->reverse_post_order_, end_then);
1018 MakeRoomFor(&graph_->reverse_post_order_, 2, index);
1019 graph_->reverse_post_order_[++index] = otherwise;
1020 graph_->reverse_post_order_[++index] = merge;
1021
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001022
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001023 graph_->UpdateLoopAndTryInformationOfNewBlock(
1024 then, original_invoke_block, /* replace_if_back_edge */ false);
1025 graph_->UpdateLoopAndTryInformationOfNewBlock(
1026 otherwise, original_invoke_block, /* replace_if_back_edge */ false);
1027
1028 // In case the original invoke location was a back edge, we need to update
1029 // the loop to now have the merge block as a back edge.
1030 graph_->UpdateLoopAndTryInformationOfNewBlock(
1031 merge, original_invoke_block, /* replace_if_back_edge */ true);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001032}
1033
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001034bool HInliner::TryInlinePolymorphicCallToSameTarget(
1035 HInvoke* invoke_instruction,
1036 ArtMethod* resolved_method,
1037 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001038 // This optimization only works under JIT for now.
Calin Juravle13439f02017-02-21 01:17:21 -08001039 if (!Runtime::Current()->UseJitCompilation()) {
1040 return false;
1041 }
1042
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001043 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -07001044 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001045
1046 DCHECK(resolved_method != nullptr);
1047 ArtMethod* actual_method = nullptr;
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001048 size_t method_index = invoke_instruction->IsInvokeVirtual()
1049 ? invoke_instruction->AsInvokeVirtual()->GetVTableIndex()
1050 : invoke_instruction->AsInvokeInterface()->GetImtIndex();
1051
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001052 // Check whether we are actually calling the same method among
1053 // the different types seen.
1054 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001055 if (classes->Get(i) == nullptr) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001056 break;
1057 }
1058 ArtMethod* new_method = nullptr;
1059 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001060 new_method = classes->Get(i)->GetImt(pointer_size)->Get(
Matthew Gharrity465ecc82016-07-19 21:32:52 +00001061 method_index, pointer_size);
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001062 if (new_method->IsRuntimeMethod()) {
1063 // Bail out as soon as we see a conflict trampoline in one of the target's
1064 // interface table.
1065 return false;
1066 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001067 } else {
1068 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001069 new_method = classes->Get(i)->GetEmbeddedVTableEntry(method_index, pointer_size);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001070 }
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001071 DCHECK(new_method != nullptr);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001072 if (actual_method == nullptr) {
1073 actual_method = new_method;
1074 } else if (actual_method != new_method) {
1075 // Different methods, bailout.
1076 return false;
1077 }
1078 }
1079
1080 HInstruction* receiver = invoke_instruction->InputAt(0);
1081 HInstruction* cursor = invoke_instruction->GetPrevious();
1082 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
1083
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001084 HInstruction* return_replacement = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001085 if (!TryBuildAndInline(invoke_instruction,
1086 actual_method,
1087 ReferenceTypeInfo::CreateInvalid(),
1088 &return_replacement)) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001089 return false;
1090 }
1091
1092 // We successfully inlined, now add a guard.
1093 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
1094 class_linker, receiver, invoke_instruction->GetDexPc());
1095
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001096 Primitive::Type type = Is64BitInstructionSet(graph_->GetInstructionSet())
1097 ? Primitive::kPrimLong
1098 : Primitive::kPrimInt;
1099 HClassTableGet* class_table_get = new (graph_->GetArena()) HClassTableGet(
1100 receiver_class,
1101 type,
Vladimir Markoa1de9182016-02-25 11:37:38 +00001102 invoke_instruction->IsInvokeVirtual() ? HClassTableGet::TableKind::kVTable
1103 : HClassTableGet::TableKind::kIMTable,
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001104 method_index,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001105 invoke_instruction->GetDexPc());
1106
1107 HConstant* constant;
1108 if (type == Primitive::kPrimLong) {
1109 constant = graph_->GetLongConstant(
1110 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
1111 } else {
1112 constant = graph_->GetIntConstant(
1113 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
1114 }
1115
1116 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(class_table_get, constant);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001117 if (cursor != nullptr) {
1118 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
1119 } else {
1120 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
1121 }
1122 bb_cursor->InsertInstructionAfter(class_table_get, receiver_class);
1123 bb_cursor->InsertInstructionAfter(compare, class_table_get);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001124
1125 if (outermost_graph_->IsCompilingOsr()) {
1126 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
1127 } else {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001128 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001129 graph_->GetArena(),
1130 compare,
1131 receiver,
1132 HDeoptimize::Kind::kInline,
1133 invoke_instruction->GetDexPc());
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001134 bb_cursor->InsertInstructionAfter(deoptimize, compare);
1135 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
1136 if (return_replacement != nullptr) {
1137 invoke_instruction->ReplaceWith(return_replacement);
1138 }
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001139 receiver->ReplaceUsesDominatedBy(deoptimize, deoptimize);
Nicolas Geoffray1be7cbd2016-04-29 13:56:01 +01001140 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001141 deoptimize->SetReferenceTypeInfo(receiver->GetReferenceTypeInfo());
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001142 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001143
1144 // Run type propagation to get the guard typed.
Vladimir Marko456307a2016-04-19 14:12:13 +00001145 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001146 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +00001147 outer_compilation_unit_.GetDexCache(),
1148 handles_,
1149 /* is_first_run */ false);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001150 rtp_fixup.Run();
1151
1152 MaybeRecordStat(kInlinedPolymorphicCall);
1153
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001154 LOG_SUCCESS() << "Inlined same polymorphic target " << actual_method->PrettyMethod();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001155 return true;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001156}
1157
Mingyao Yang063fc772016-08-02 11:02:54 -07001158bool HInliner::TryInlineAndReplace(HInvoke* invoke_instruction,
1159 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001160 ReferenceTypeInfo receiver_type,
Mingyao Yang063fc772016-08-02 11:02:54 -07001161 bool do_rtp,
1162 bool cha_devirtualize) {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001163 HInstruction* return_replacement = nullptr;
Mingyao Yang063fc772016-08-02 11:02:54 -07001164 uint32_t dex_pc = invoke_instruction->GetDexPc();
1165 HInstruction* cursor = invoke_instruction->GetPrevious();
1166 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001167 if (!TryBuildAndInline(invoke_instruction, method, receiver_type, &return_replacement)) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001168 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +00001169 DCHECK(!method->IsProxyMethod());
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001170 // Turn an invoke-interface into an invoke-virtual. An invoke-virtual is always
1171 // better than an invoke-interface because:
1172 // 1) In the best case, the interface call has one more indirection (to fetch the IMT).
1173 // 2) We will not go to the conflict trampoline with an invoke-virtual.
1174 // TODO: Consider sharpening once it is not dependent on the compiler driver.
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +00001175
1176 if (method->IsDefault() && !method->IsCopied()) {
1177 // Changing to invoke-virtual cannot be done on an original default method
1178 // since it's not in any vtable. Devirtualization by exact type/inline-cache
1179 // always uses a method in the iftable which is never an original default
1180 // method.
1181 // On the other hand, inlining an original default method by CHA is fine.
1182 DCHECK(cha_devirtualize);
1183 return false;
1184 }
1185
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001186 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001187 uint32_t dex_method_index = FindMethodIndexIn(
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001188 method, caller_dex_file, invoke_instruction->GetDexMethodIndex());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001189 if (dex_method_index == DexFile::kDexNoIndex) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001190 return false;
1191 }
1192 HInvokeVirtual* new_invoke = new (graph_->GetArena()) HInvokeVirtual(
1193 graph_->GetArena(),
1194 invoke_instruction->GetNumberOfArguments(),
1195 invoke_instruction->GetType(),
1196 invoke_instruction->GetDexPc(),
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001197 dex_method_index,
1198 method,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001199 method->GetMethodIndex());
1200 HInputsRef inputs = invoke_instruction->GetInputs();
1201 for (size_t index = 0; index != inputs.size(); ++index) {
1202 new_invoke->SetArgumentAt(index, inputs[index]);
1203 }
1204 invoke_instruction->GetBlock()->InsertInstructionBefore(new_invoke, invoke_instruction);
1205 new_invoke->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
1206 if (invoke_instruction->GetType() == Primitive::kPrimNot) {
1207 new_invoke->SetReferenceTypeInfo(invoke_instruction->GetReferenceTypeInfo());
1208 }
1209 return_replacement = new_invoke;
1210 } else {
1211 // TODO: Consider sharpening an invoke virtual once it is not dependent on the
1212 // compiler driver.
1213 return false;
1214 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001215 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001216 if (cha_devirtualize) {
1217 AddCHAGuard(invoke_instruction, dex_pc, cursor, bb_cursor);
1218 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001219 if (return_replacement != nullptr) {
1220 invoke_instruction->ReplaceWith(return_replacement);
1221 }
1222 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
David Brazdil94ab38f2016-06-21 17:48:19 +01001223 FixUpReturnReferenceType(method, return_replacement);
1224 if (do_rtp && ReturnTypeMoreSpecific(invoke_instruction, return_replacement)) {
1225 // Actual return value has a more specific type than the method's declared
1226 // return type. Run RTP again on the outer graph to propagate it.
1227 ReferenceTypePropagation(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001228 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +01001229 outer_compilation_unit_.GetDexCache(),
1230 handles_,
1231 /* is_first_run */ false).Run();
1232 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001233 return true;
1234}
1235
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001236size_t HInliner::CountRecursiveCallsOf(ArtMethod* method) const {
1237 const HInliner* current = this;
1238 size_t count = 0;
1239 do {
1240 if (current->graph_->GetArtMethod() == method) {
1241 ++count;
1242 }
1243 current = current->parent_;
1244 } while (current != nullptr);
1245 return count;
1246}
1247
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001248bool HInliner::TryBuildAndInline(HInvoke* invoke_instruction,
1249 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001250 ReferenceTypeInfo receiver_type,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001251 HInstruction** return_replacement) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001252 if (method->IsProxyMethod()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001253 LOG_FAIL(kNotInlinedProxy)
1254 << "Method " << method->PrettyMethod()
1255 << " is not inlined because of unimplemented inline support for proxy methods.";
1256 return false;
1257 }
1258
1259 if (CountRecursiveCallsOf(method) > kMaximumNumberOfRecursiveCalls) {
1260 LOG_FAIL(kNotInlinedRecursiveBudget)
1261 << "Method "
1262 << method->PrettyMethod()
1263 << " is not inlined because it has reached its recursive call budget.";
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001264 return false;
1265 }
1266
Jeff Haodcdc85b2015-12-04 14:06:18 -08001267 // Check whether we're allowed to inline. The outermost compilation unit is the relevant
1268 // dex file here (though the transitivity of an inline chain would allow checking the calller).
1269 if (!compiler_driver_->MayInline(method->GetDexFile(),
1270 outer_compilation_unit_.GetDexFile())) {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001271 if (TryPatternSubstitution(invoke_instruction, method, return_replacement)) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001272 LOG_SUCCESS() << "Successfully replaced pattern of invoke "
1273 << method->PrettyMethod();
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001274 MaybeRecordStat(kReplacedInvokeWithSimplePattern);
1275 return true;
1276 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001277 LOG_FAIL(kNotInlinedWont)
1278 << "Won't inline " << method->PrettyMethod() << " in "
1279 << outer_compilation_unit_.GetDexFile()->GetLocation() << " ("
1280 << caller_compilation_unit_.GetDexFile()->GetLocation() << ") from "
1281 << method->GetDexFile()->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001282 return false;
1283 }
1284
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001285 bool same_dex_file = IsSameDexFile(*outer_compilation_unit_.GetDexFile(), *method->GetDexFile());
1286
1287 const DexFile::CodeItem* code_item = method->GetCodeItem();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001288
1289 if (code_item == nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001290 LOG_FAIL_NO_STAT()
1291 << "Method " << method->PrettyMethod() << " is not inlined because it is native";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001292 return false;
1293 }
1294
Calin Juravleec748352015-07-29 13:52:12 +01001295 size_t inline_max_code_units = compiler_driver_->GetCompilerOptions().GetInlineMaxCodeUnits();
1296 if (code_item->insns_size_in_code_units_ > inline_max_code_units) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001297 LOG_FAIL(kNotInlinedCodeItem)
1298 << "Method " << method->PrettyMethod()
1299 << " is not inlined because its code item is too big: "
1300 << code_item->insns_size_in_code_units_
1301 << " > "
1302 << inline_max_code_units;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001303 return false;
1304 }
1305
1306 if (code_item->tries_size_ != 0) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001307 LOG_FAIL(kNotInlinedTryCatch)
1308 << "Method " << method->PrettyMethod() << " is not inlined because of try block";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001309 return false;
1310 }
1311
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001312 if (!method->IsCompilable()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001313 LOG_FAIL(kNotInlinedNotVerified)
1314 << "Method " << method->PrettyMethod()
1315 << " has soft failures un-handled by the compiler, so it cannot be inlined";
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001316 }
1317
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001318 if (!method->GetDeclaringClass()->IsVerified()) {
1319 uint16_t class_def_idx = method->GetDeclaringClass()->GetDexClassDefIndex();
Calin Juravleffc87072016-04-20 14:22:09 +01001320 if (Runtime::Current()->UseJitCompilation() ||
Nicolas Geoffray5b82d332016-02-18 14:22:32 +00001321 !compiler_driver_->IsMethodVerifiedWithoutFailures(
1322 method->GetDexMethodIndex(), class_def_idx, *method->GetDexFile())) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001323 LOG_FAIL(kNotInlinedNotVerified)
1324 << "Method " << method->PrettyMethod()
1325 << " couldn't be verified, so it cannot be inlined";
Nicolas Geoffrayccc61972015-10-01 14:34:20 +01001326 return false;
1327 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001328 }
1329
Roland Levillain4c0eb422015-04-24 16:43:49 +01001330 if (invoke_instruction->IsInvokeStaticOrDirect() &&
1331 invoke_instruction->AsInvokeStaticOrDirect()->IsStaticWithImplicitClinitCheck()) {
1332 // Case of a static method that cannot be inlined because it implicitly
1333 // requires an initialization check of its declaring class.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001334 LOG_FAIL(kNotInlinedDexCache) << "Method " << method->PrettyMethod()
1335 << " is not inlined because it is static and requires a clinit"
1336 << " check that cannot be emitted due to Dex cache limitations";
Roland Levillain4c0eb422015-04-24 16:43:49 +01001337 return false;
1338 }
1339
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001340 if (!TryBuildAndInlineHelper(
1341 invoke_instruction, method, receiver_type, same_dex_file, return_replacement)) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001342 return false;
1343 }
1344
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001345 LOG_SUCCESS() << method->PrettyMethod();
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001346 MaybeRecordStat(kInlinedInvoke);
1347 return true;
1348}
1349
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001350static HInstruction* GetInvokeInputForArgVRegIndex(HInvoke* invoke_instruction,
1351 size_t arg_vreg_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001352 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001353 size_t input_index = 0;
1354 for (size_t i = 0; i < arg_vreg_index; ++i, ++input_index) {
1355 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
1356 if (Primitive::Is64BitType(invoke_instruction->InputAt(input_index)->GetType())) {
1357 ++i;
1358 DCHECK_NE(i, arg_vreg_index);
1359 }
1360 }
1361 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
1362 return invoke_instruction->InputAt(input_index);
1363}
1364
1365// Try to recognize known simple patterns and replace invoke call with appropriate instructions.
1366bool HInliner::TryPatternSubstitution(HInvoke* invoke_instruction,
1367 ArtMethod* resolved_method,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001368 HInstruction** return_replacement) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001369 InlineMethod inline_method;
1370 if (!InlineMethodAnalyser::AnalyseMethodCode(resolved_method, &inline_method)) {
1371 return false;
1372 }
1373
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001374 switch (inline_method.opcode) {
1375 case kInlineOpNop:
1376 DCHECK_EQ(invoke_instruction->GetType(), Primitive::kPrimVoid);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001377 *return_replacement = nullptr;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001378 break;
1379 case kInlineOpReturnArg:
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001380 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction,
1381 inline_method.d.return_data.arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001382 break;
1383 case kInlineOpNonWideConst:
1384 if (resolved_method->GetShorty()[0] == 'L') {
1385 DCHECK_EQ(inline_method.d.data, 0u);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001386 *return_replacement = graph_->GetNullConstant();
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001387 } else {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001388 *return_replacement = graph_->GetIntConstant(static_cast<int32_t>(inline_method.d.data));
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001389 }
1390 break;
1391 case kInlineOpIGet: {
1392 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1393 if (data.method_is_static || data.object_arg != 0u) {
1394 // TODO: Needs null check.
1395 return false;
1396 }
1397 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001398 HInstanceFieldGet* iget = CreateInstanceFieldGet(data.field_idx, resolved_method, obj);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001399 DCHECK_EQ(iget->GetFieldOffset().Uint32Value(), data.field_offset);
1400 DCHECK_EQ(iget->IsVolatile() ? 1u : 0u, data.is_volatile);
1401 invoke_instruction->GetBlock()->InsertInstructionBefore(iget, invoke_instruction);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001402 *return_replacement = iget;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001403 break;
1404 }
1405 case kInlineOpIPut: {
1406 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1407 if (data.method_is_static || data.object_arg != 0u) {
1408 // TODO: Needs null check.
1409 return false;
1410 }
1411 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
1412 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, data.src_arg);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001413 HInstanceFieldSet* iput = CreateInstanceFieldSet(data.field_idx, resolved_method, obj, value);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001414 DCHECK_EQ(iput->GetFieldOffset().Uint32Value(), data.field_offset);
1415 DCHECK_EQ(iput->IsVolatile() ? 1u : 0u, data.is_volatile);
1416 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1417 if (data.return_arg_plus1 != 0u) {
1418 size_t return_arg = data.return_arg_plus1 - 1u;
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001419 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction, return_arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001420 }
1421 break;
1422 }
Vladimir Marko354efa62016-02-04 19:46:56 +00001423 case kInlineOpConstructor: {
1424 const InlineConstructorData& data = inline_method.d.constructor_data;
1425 // Get the indexes to arrays for easier processing.
1426 uint16_t iput_field_indexes[] = {
1427 data.iput0_field_index, data.iput1_field_index, data.iput2_field_index
1428 };
1429 uint16_t iput_args[] = { data.iput0_arg, data.iput1_arg, data.iput2_arg };
1430 static_assert(arraysize(iput_args) == arraysize(iput_field_indexes), "Size mismatch");
1431 // Count valid field indexes.
1432 size_t number_of_iputs = 0u;
1433 while (number_of_iputs != arraysize(iput_field_indexes) &&
1434 iput_field_indexes[number_of_iputs] != DexFile::kDexNoIndex16) {
1435 // Check that there are no duplicate valid field indexes.
1436 DCHECK_EQ(0, std::count(iput_field_indexes + number_of_iputs + 1,
1437 iput_field_indexes + arraysize(iput_field_indexes),
1438 iput_field_indexes[number_of_iputs]));
1439 ++number_of_iputs;
1440 }
1441 // Check that there are no valid field indexes in the rest of the array.
1442 DCHECK_EQ(0, std::count_if(iput_field_indexes + number_of_iputs,
1443 iput_field_indexes + arraysize(iput_field_indexes),
1444 [](uint16_t index) { return index != DexFile::kDexNoIndex16; }));
1445
1446 // Create HInstanceFieldSet for each IPUT that stores non-zero data.
Vladimir Marko354efa62016-02-04 19:46:56 +00001447 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, /* this */ 0u);
1448 bool needs_constructor_barrier = false;
1449 for (size_t i = 0; i != number_of_iputs; ++i) {
1450 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, iput_args[i]);
Roland Levillain1a653882016-03-18 18:05:57 +00001451 if (!value->IsConstant() || !value->AsConstant()->IsZeroBitPattern()) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001452 uint16_t field_index = iput_field_indexes[i];
Vladimir Markof44d36c2017-03-14 14:18:46 +00001453 bool is_final;
1454 HInstanceFieldSet* iput =
1455 CreateInstanceFieldSet(field_index, resolved_method, obj, value, &is_final);
Vladimir Marko354efa62016-02-04 19:46:56 +00001456 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1457
1458 // Check whether the field is final. If it is, we need to add a barrier.
Vladimir Markof44d36c2017-03-14 14:18:46 +00001459 if (is_final) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001460 needs_constructor_barrier = true;
1461 }
1462 }
1463 }
1464 if (needs_constructor_barrier) {
1465 HMemoryBarrier* barrier = new (graph_->GetArena()) HMemoryBarrier(kStoreStore, kNoDexPc);
1466 invoke_instruction->GetBlock()->InsertInstructionBefore(barrier, invoke_instruction);
1467 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001468 *return_replacement = nullptr;
Vladimir Marko354efa62016-02-04 19:46:56 +00001469 break;
1470 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001471 default:
1472 LOG(FATAL) << "UNREACHABLE";
1473 UNREACHABLE();
1474 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001475 return true;
1476}
1477
Vladimir Markof44d36c2017-03-14 14:18:46 +00001478HInstanceFieldGet* HInliner::CreateInstanceFieldGet(uint32_t field_index,
1479 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001480 HInstruction* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001481 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001482 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1483 ArtField* resolved_field =
1484 class_linker->LookupResolvedField(field_index, referrer, /* is_static */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001485 DCHECK(resolved_field != nullptr);
1486 HInstanceFieldGet* iget = new (graph_->GetArena()) HInstanceFieldGet(
1487 obj,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001488 resolved_field,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001489 resolved_field->GetTypeAsPrimitiveType(),
1490 resolved_field->GetOffset(),
1491 resolved_field->IsVolatile(),
1492 field_index,
1493 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001494 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001495 // Read barrier generates a runtime call in slow path and we need a valid
1496 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1497 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001498 if (iget->GetType() == Primitive::kPrimNot) {
Vladimir Marko456307a2016-04-19 14:12:13 +00001499 // Use the same dex_cache that we used for field lookup as the hint_dex_cache.
Vladimir Markof44d36c2017-03-14 14:18:46 +00001500 Handle<mirror::DexCache> dex_cache = handles_->NewHandle(referrer->GetDexCache());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001501 ReferenceTypePropagation rtp(graph_,
1502 outer_compilation_unit_.GetClassLoader(),
1503 dex_cache,
1504 handles_,
1505 /* is_first_run */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001506 rtp.Visit(iget);
1507 }
1508 return iget;
1509}
1510
Vladimir Markof44d36c2017-03-14 14:18:46 +00001511HInstanceFieldSet* HInliner::CreateInstanceFieldSet(uint32_t field_index,
1512 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001513 HInstruction* obj,
Vladimir Markof44d36c2017-03-14 14:18:46 +00001514 HInstruction* value,
1515 bool* is_final)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001516 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001517 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1518 ArtField* resolved_field =
1519 class_linker->LookupResolvedField(field_index, referrer, /* is_static */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001520 DCHECK(resolved_field != nullptr);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001521 if (is_final != nullptr) {
1522 // This information is needed only for constructors.
1523 DCHECK(referrer->IsConstructor());
1524 *is_final = resolved_field->IsFinal();
1525 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001526 HInstanceFieldSet* iput = new (graph_->GetArena()) HInstanceFieldSet(
1527 obj,
1528 value,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001529 resolved_field,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001530 resolved_field->GetTypeAsPrimitiveType(),
1531 resolved_field->GetOffset(),
1532 resolved_field->IsVolatile(),
1533 field_index,
1534 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001535 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001536 // Read barrier generates a runtime call in slow path and we need a valid
1537 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1538 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001539 return iput;
1540}
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001541
Vladimir Markob1d0ee12017-04-20 19:50:32 +01001542template <typename T>
1543static inline Handle<T> NewHandleIfDifferent(T* object,
1544 Handle<T> hint,
1545 VariableSizedHandleScope* handles)
1546 REQUIRES_SHARED(Locks::mutator_lock_) {
1547 return (object != hint.Get()) ? handles->NewHandle(object) : hint;
1548}
1549
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001550bool HInliner::TryBuildAndInlineHelper(HInvoke* invoke_instruction,
1551 ArtMethod* resolved_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001552 ReferenceTypeInfo receiver_type,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001553 bool same_dex_file,
1554 HInstruction** return_replacement) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001555 DCHECK(!(resolved_method->IsStatic() && receiver_type.IsValid()));
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001556 ScopedObjectAccess soa(Thread::Current());
1557 const DexFile::CodeItem* code_item = resolved_method->GetCodeItem();
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001558 const DexFile& callee_dex_file = *resolved_method->GetDexFile();
1559 uint32_t method_index = resolved_method->GetDexMethodIndex();
Calin Juravle2e768302015-07-28 14:41:11 +00001560 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Vladimir Markob1d0ee12017-04-20 19:50:32 +01001561 Handle<mirror::DexCache> dex_cache = NewHandleIfDifferent(resolved_method->GetDexCache(),
1562 caller_compilation_unit_.GetDexCache(),
1563 handles_);
1564 Handle<mirror::ClassLoader> class_loader =
1565 NewHandleIfDifferent(resolved_method->GetDeclaringClass()->GetClassLoader(),
1566 caller_compilation_unit_.GetClassLoader(),
1567 handles_);
Nicolas Geoffrayf1aedb12016-07-28 03:49:14 +01001568
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001569 DexCompilationUnit dex_compilation_unit(
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001570 class_loader,
Nicolas Geoffray5b82d332016-02-18 14:22:32 +00001571 class_linker,
1572 callee_dex_file,
1573 code_item,
1574 resolved_method->GetDeclaringClass()->GetDexClassDefIndex(),
1575 method_index,
1576 resolved_method->GetAccessFlags(),
1577 /* verified_method */ nullptr,
1578 dex_cache);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001579
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001580 InvokeType invoke_type = invoke_instruction->GetInvokeType();
Nicolas Geoffray35071052015-06-09 15:43:38 +01001581 if (invoke_type == kInterface) {
1582 // We have statically resolved the dispatch. To please the class linker
1583 // at runtime, we change this call as if it was a virtual call.
1584 invoke_type = kVirtual;
1585 }
David Brazdil3f523062016-02-29 16:53:33 +00001586
1587 const int32_t caller_instruction_counter = graph_->GetCurrentInstructionId();
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +00001588 HGraph* callee_graph = new (graph_->GetArena()) HGraph(
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001589 graph_->GetArena(),
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001590 callee_dex_file,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001591 method_index,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001592 compiler_driver_->GetInstructionSet(),
Nicolas Geoffray35071052015-06-09 15:43:38 +01001593 invoke_type,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001594 graph_->IsDebuggable(),
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001595 /* osr */ false,
David Brazdil3f523062016-02-29 16:53:33 +00001596 caller_instruction_counter);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001597 callee_graph->SetArtMethod(resolved_method);
David Brazdil5e8b1372015-01-23 14:39:08 +00001598
Vladimir Marko438709f2017-02-23 18:56:13 +00001599 // When they are needed, allocate `inline_stats_` on the Arena instead
Roland Levillaina8013fd2016-04-04 15:34:31 +01001600 // of on the stack, as Clang might produce a stack frame too large
1601 // for this function, that would not fit the requirements of the
1602 // `-Wframe-larger-than` option.
Vladimir Marko438709f2017-02-23 18:56:13 +00001603 if (stats_ != nullptr) {
1604 // Reuse one object for all inline attempts from this caller to keep Arena memory usage low.
1605 if (inline_stats_ == nullptr) {
1606 void* storage = graph_->GetArena()->Alloc<OptimizingCompilerStats>(kArenaAllocMisc);
1607 inline_stats_ = new (storage) OptimizingCompilerStats;
1608 } else {
1609 inline_stats_->Reset();
1610 }
1611 }
David Brazdil5e8b1372015-01-23 14:39:08 +00001612 HGraphBuilder builder(callee_graph,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001613 &dex_compilation_unit,
1614 &outer_compilation_unit_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001615 resolved_method->GetDexFile(),
David Brazdil86ea7ee2016-02-16 09:26:07 +00001616 *code_item,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001617 compiler_driver_,
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00001618 codegen_,
Vladimir Marko438709f2017-02-23 18:56:13 +00001619 inline_stats_,
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001620 resolved_method->GetQuickenedInfo(class_linker->GetImagePointerSize()),
David Brazdildee58d62016-04-07 09:54:26 +00001621 dex_cache,
1622 handles_);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001623
David Brazdildee58d62016-04-07 09:54:26 +00001624 if (builder.BuildGraph() != kAnalysisSuccess) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001625 LOG_FAIL(kNotInlinedCannotBuild)
1626 << "Method " << callee_dex_file.PrettyMethod(method_index)
1627 << " could not be built, so cannot be inlined";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001628 return false;
1629 }
1630
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001631 if (!RegisterAllocator::CanAllocateRegistersFor(*callee_graph,
1632 compiler_driver_->GetInstructionSet())) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001633 LOG_FAIL(kNotInlinedRegisterAllocator)
1634 << "Method " << callee_dex_file.PrettyMethod(method_index)
1635 << " cannot be inlined because of the register allocator";
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001636 return false;
1637 }
1638
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001639 size_t parameter_index = 0;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001640 bool run_rtp = false;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001641 for (HInstructionIterator instructions(callee_graph->GetEntryBlock()->GetInstructions());
1642 !instructions.Done();
1643 instructions.Advance()) {
1644 HInstruction* current = instructions.Current();
1645 if (current->IsParameterValue()) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001646 HInstruction* argument = invoke_instruction->InputAt(parameter_index);
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001647 if (argument->IsNullConstant()) {
1648 current->ReplaceWith(callee_graph->GetNullConstant());
1649 } else if (argument->IsIntConstant()) {
1650 current->ReplaceWith(callee_graph->GetIntConstant(argument->AsIntConstant()->GetValue()));
1651 } else if (argument->IsLongConstant()) {
1652 current->ReplaceWith(callee_graph->GetLongConstant(argument->AsLongConstant()->GetValue()));
1653 } else if (argument->IsFloatConstant()) {
1654 current->ReplaceWith(
1655 callee_graph->GetFloatConstant(argument->AsFloatConstant()->GetValue()));
1656 } else if (argument->IsDoubleConstant()) {
1657 current->ReplaceWith(
1658 callee_graph->GetDoubleConstant(argument->AsDoubleConstant()->GetValue()));
1659 } else if (argument->GetType() == Primitive::kPrimNot) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001660 if (!resolved_method->IsStatic() && parameter_index == 0 && receiver_type.IsValid()) {
1661 run_rtp = true;
1662 current->SetReferenceTypeInfo(receiver_type);
1663 } else {
1664 current->SetReferenceTypeInfo(argument->GetReferenceTypeInfo());
1665 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001666 current->AsParameterValue()->SetCanBeNull(argument->CanBeNull());
1667 }
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001668 ++parameter_index;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001669 }
1670 }
1671
David Brazdil94ab38f2016-06-21 17:48:19 +01001672 // We have replaced formal arguments with actual arguments. If actual types
1673 // are more specific than the declared ones, run RTP again on the inner graph.
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001674 if (run_rtp || ArgumentTypesMoreSpecific(invoke_instruction, resolved_method)) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001675 ReferenceTypePropagation(callee_graph,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001676 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +01001677 dex_compilation_unit.GetDexCache(),
1678 handles_,
1679 /* is_first_run */ false).Run();
1680 }
1681
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001682 RunOptimizations(callee_graph, code_item, dex_compilation_unit);
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +00001683
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001684 HBasicBlock* exit_block = callee_graph->GetExitBlock();
1685 if (exit_block == nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001686 LOG_FAIL(kNotInlinedInfiniteLoop)
1687 << "Method " << callee_dex_file.PrettyMethod(method_index)
1688 << " could not be inlined because it has an infinite loop";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001689 return false;
1690 }
1691
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001692 bool has_one_return = false;
Vladimir Marko60584552015-09-03 13:35:12 +00001693 for (HBasicBlock* predecessor : exit_block->GetPredecessors()) {
1694 if (predecessor->GetLastInstruction()->IsThrow()) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001695 if (invoke_instruction->GetBlock()->IsTryBlock()) {
1696 // TODO(ngeoffray): Support adding HTryBoundary in Hgraph::InlineInto.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001697 LOG_FAIL(kNotInlinedTryCatch)
1698 << "Method " << callee_dex_file.PrettyMethod(method_index)
1699 << " could not be inlined because one branch always throws and"
1700 << " caller is in a try/catch block";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001701 return false;
1702 } else if (graph_->GetExitBlock() == nullptr) {
1703 // TODO(ngeoffray): Support adding HExit in the caller graph.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001704 LOG_FAIL(kNotInlinedInfiniteLoop)
1705 << "Method " << callee_dex_file.PrettyMethod(method_index)
1706 << " could not be inlined because one branch always throws and"
1707 << " caller does not have an exit block";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001708 return false;
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00001709 } else if (graph_->HasIrreducibleLoops()) {
1710 // TODO(ngeoffray): Support re-computing loop information to graphs with
1711 // irreducible loops?
1712 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1713 << " could not be inlined because one branch always throws and"
1714 << " caller has irreducible loops";
1715 return false;
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001716 }
1717 } else {
1718 has_one_return = true;
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001719 }
1720 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001721
1722 if (!has_one_return) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001723 LOG_FAIL(kNotInlinedAlwaysThrows)
1724 << "Method " << callee_dex_file.PrettyMethod(method_index)
1725 << " could not be inlined because it always throws";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001726 return false;
1727 }
1728
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001729 size_t number_of_instructions = 0;
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001730 // Skip the entry block, it does not contain instructions that prevent inlining.
1731 for (HBasicBlock* block : callee_graph->GetReversePostOrderSkipEntryBlock()) {
David Sehrc757dec2016-11-04 15:48:34 -07001732 if (block->IsLoopHeader()) {
1733 if (block->GetLoopInformation()->IsIrreducible()) {
1734 // Don't inline methods with irreducible loops, they could prevent some
1735 // optimizations to run.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001736 LOG_FAIL(kNotInlinedIrreducibleLoop)
1737 << "Method " << callee_dex_file.PrettyMethod(method_index)
1738 << " could not be inlined because it contains an irreducible loop";
David Sehrc757dec2016-11-04 15:48:34 -07001739 return false;
1740 }
1741 if (!block->GetLoopInformation()->HasExitEdge()) {
1742 // Don't inline methods with loops without exit, since they cause the
1743 // loop information to be computed incorrectly when updating after
1744 // inlining.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001745 LOG_FAIL(kNotInlinedLoopWithoutExit)
1746 << "Method " << callee_dex_file.PrettyMethod(method_index)
1747 << " could not be inlined because it contains a loop with no exit";
David Sehrc757dec2016-11-04 15:48:34 -07001748 return false;
1749 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001750 }
1751
1752 for (HInstructionIterator instr_it(block->GetInstructions());
1753 !instr_it.Done();
1754 instr_it.Advance()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001755 if (++number_of_instructions >= inlining_budget_) {
1756 LOG_FAIL(kNotInlinedInstructionBudget)
1757 << "Method " << callee_dex_file.PrettyMethod(method_index)
1758 << " is not inlined because the outer method has reached"
1759 << " its instruction budget limit.";
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001760 return false;
1761 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001762 HInstruction* current = instr_it.Current();
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001763 if (current->NeedsEnvironment() &&
1764 (total_number_of_dex_registers_ >= kMaximumNumberOfCumulatedDexRegisters)) {
1765 LOG_FAIL(kNotInlinedEnvironmentBudget)
1766 << "Method " << callee_dex_file.PrettyMethod(method_index)
1767 << " is not inlined because its caller has reached"
1768 << " its environment budget limit.";
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001769 return false;
1770 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001771
Nicolas Geoffrayfbdfa6d2017-02-03 10:43:13 +00001772 if (current->NeedsEnvironment() &&
1773 !CanEncodeInlinedMethodInStackMap(*caller_compilation_unit_.GetDexFile(),
1774 resolved_method)) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001775 LOG_FAIL(kNotInlinedStackMaps)
1776 << "Method " << callee_dex_file.PrettyMethod(method_index)
1777 << " could not be inlined because " << current->DebugName()
1778 << " needs an environment, is in a different dex file"
1779 << ", and cannot be encoded in the stack maps.";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001780 return false;
1781 }
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001782
Vladimir Markodc151b22015-10-15 18:02:30 +01001783 if (!same_dex_file && current->NeedsDexCacheOfDeclaringClass()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001784 LOG_FAIL(kNotInlinedDexCache)
1785 << "Method " << callee_dex_file.PrettyMethod(method_index)
1786 << " could not be inlined because " << current->DebugName()
1787 << " it is in a different dex file and requires access to the dex cache";
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001788 return false;
1789 }
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001790
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001791 if (current->IsUnresolvedStaticFieldGet() ||
1792 current->IsUnresolvedInstanceFieldGet() ||
1793 current->IsUnresolvedStaticFieldSet() ||
1794 current->IsUnresolvedInstanceFieldSet()) {
1795 // Entrypoint for unresolved fields does not handle inlined frames.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001796 LOG_FAIL(kNotInlinedUnresolvedEntrypoint)
1797 << "Method " << callee_dex_file.PrettyMethod(method_index)
1798 << " could not be inlined because it is using an unresolved"
1799 << " entrypoint";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001800 return false;
1801 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001802 }
1803 }
David Brazdil3f523062016-02-29 16:53:33 +00001804 DCHECK_EQ(caller_instruction_counter, graph_->GetCurrentInstructionId())
1805 << "No instructions can be added to the outer graph while inner graph is being built";
1806
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001807 // Inline the callee graph inside the caller graph.
David Brazdil3f523062016-02-29 16:53:33 +00001808 const int32_t callee_instruction_counter = callee_graph->GetCurrentInstructionId();
1809 graph_->SetCurrentInstructionId(callee_instruction_counter);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001810 *return_replacement = callee_graph->InlineInto(graph_, invoke_instruction);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001811 // Update our budget for other inlining attempts in `caller_graph`.
1812 total_number_of_instructions_ += number_of_instructions;
1813 UpdateInliningBudget();
David Brazdil3f523062016-02-29 16:53:33 +00001814
1815 DCHECK_EQ(callee_instruction_counter, callee_graph->GetCurrentInstructionId())
1816 << "No instructions can be added to the inner graph during inlining into the outer graph";
1817
Vladimir Marko438709f2017-02-23 18:56:13 +00001818 if (stats_ != nullptr) {
1819 DCHECK(inline_stats_ != nullptr);
1820 inline_stats_->AddTo(stats_);
1821 }
1822
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001823 return true;
1824}
Calin Juravle2e768302015-07-28 14:41:11 +00001825
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001826void HInliner::RunOptimizations(HGraph* callee_graph,
1827 const DexFile::CodeItem* code_item,
1828 const DexCompilationUnit& dex_compilation_unit) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001829 // Note: if the outermost_graph_ is being compiled OSR, we should not run any
1830 // optimization that could lead to a HDeoptimize. The following optimizations do not.
Vladimir Marko438709f2017-02-23 18:56:13 +00001831 HDeadCodeElimination dce(callee_graph, inline_stats_, "dead_code_elimination$inliner");
Andreas Gampeca620d72016-11-08 08:09:33 -08001832 HConstantFolding fold(callee_graph, "constant_folding$inliner");
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001833 HSharpening sharpening(callee_graph, codegen_, dex_compilation_unit, compiler_driver_, handles_);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001834 InstructionSimplifier simplify(callee_graph, codegen_, inline_stats_);
Vladimir Marko438709f2017-02-23 18:56:13 +00001835 IntrinsicsRecognizer intrinsics(callee_graph, inline_stats_);
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001836
1837 HOptimization* optimizations[] = {
1838 &intrinsics,
1839 &sharpening,
1840 &simplify,
1841 &fold,
1842 &dce,
1843 };
1844
1845 for (size_t i = 0; i < arraysize(optimizations); ++i) {
1846 HOptimization* optimization = optimizations[i];
1847 optimization->Run();
1848 }
1849
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001850 // Bail early for pathological cases on the environment (for example recursive calls,
1851 // or too large environment).
1852 if (total_number_of_dex_registers_ >= kMaximumNumberOfCumulatedDexRegisters) {
1853 LOG_NOTE() << "Calls in " << callee_graph->GetArtMethod()->PrettyMethod()
1854 << " will not be inlined because the outer method has reached"
1855 << " its environment budget limit.";
1856 return;
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001857 }
1858
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001859 // Bail early if we know we already are over the limit.
1860 size_t number_of_instructions = CountNumberOfInstructions(callee_graph);
1861 if (number_of_instructions > inlining_budget_) {
1862 LOG_NOTE() << "Calls in " << callee_graph->GetArtMethod()->PrettyMethod()
1863 << " will not be inlined because the outer method has reached"
1864 << " its instruction budget limit. " << number_of_instructions;
1865 return;
1866 }
1867
1868 HInliner inliner(callee_graph,
1869 outermost_graph_,
1870 codegen_,
1871 outer_compilation_unit_,
1872 dex_compilation_unit,
1873 compiler_driver_,
1874 handles_,
1875 inline_stats_,
1876 total_number_of_dex_registers_ + code_item->registers_size_,
1877 total_number_of_instructions_ + number_of_instructions,
1878 this,
1879 depth_ + 1);
1880 inliner.Run();
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001881}
1882
David Brazdil94ab38f2016-06-21 17:48:19 +01001883static bool IsReferenceTypeRefinement(ReferenceTypeInfo declared_rti,
1884 bool declared_can_be_null,
1885 HInstruction* actual_obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001886 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001887 if (declared_can_be_null && !actual_obj->CanBeNull()) {
1888 return true;
1889 }
1890
1891 ReferenceTypeInfo actual_rti = actual_obj->GetReferenceTypeInfo();
1892 return (actual_rti.IsExact() && !declared_rti.IsExact()) ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001893 declared_rti.IsStrictSupertypeOf(actual_rti);
David Brazdil94ab38f2016-06-21 17:48:19 +01001894}
1895
1896ReferenceTypeInfo HInliner::GetClassRTI(mirror::Class* klass) {
1897 return ReferenceTypePropagation::IsAdmissible(klass)
1898 ? ReferenceTypeInfo::Create(handles_->NewHandle(klass))
1899 : graph_->GetInexactObjectRti();
1900}
1901
1902bool HInliner::ArgumentTypesMoreSpecific(HInvoke* invoke_instruction, ArtMethod* resolved_method) {
1903 // If this is an instance call, test whether the type of the `this` argument
1904 // is more specific than the class which declares the method.
1905 if (!resolved_method->IsStatic()) {
1906 if (IsReferenceTypeRefinement(GetClassRTI(resolved_method->GetDeclaringClass()),
1907 /* declared_can_be_null */ false,
1908 invoke_instruction->InputAt(0u))) {
1909 return true;
1910 }
1911 }
1912
David Brazdil94ab38f2016-06-21 17:48:19 +01001913 // Iterate over the list of parameter types and test whether any of the
1914 // actual inputs has a more specific reference type than the type declared in
1915 // the signature.
1916 const DexFile::TypeList* param_list = resolved_method->GetParameterTypeList();
1917 for (size_t param_idx = 0,
1918 input_idx = resolved_method->IsStatic() ? 0 : 1,
1919 e = (param_list == nullptr ? 0 : param_list->Size());
1920 param_idx < e;
1921 ++param_idx, ++input_idx) {
1922 HInstruction* input = invoke_instruction->InputAt(input_idx);
1923 if (input->GetType() == Primitive::kPrimNot) {
Vladimir Marko942fd312017-01-16 20:52:19 +00001924 mirror::Class* param_cls = resolved_method->GetClassFromTypeIndex(
David Brazdil94ab38f2016-06-21 17:48:19 +01001925 param_list->GetTypeItem(param_idx).type_idx_,
Vladimir Marko942fd312017-01-16 20:52:19 +00001926 /* resolve */ false);
David Brazdil94ab38f2016-06-21 17:48:19 +01001927 if (IsReferenceTypeRefinement(GetClassRTI(param_cls),
1928 /* declared_can_be_null */ true,
1929 input)) {
1930 return true;
1931 }
1932 }
1933 }
1934
1935 return false;
1936}
1937
1938bool HInliner::ReturnTypeMoreSpecific(HInvoke* invoke_instruction,
1939 HInstruction* return_replacement) {
Alex Light68289a52015-12-15 17:30:30 -08001940 // Check the integrity of reference types and run another type propagation if needed.
David Brazdil4833f5a2015-12-16 10:37:39 +00001941 if (return_replacement != nullptr) {
1942 if (return_replacement->GetType() == Primitive::kPrimNot) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001943 // Test if the return type is a refinement of the declared return type.
1944 if (IsReferenceTypeRefinement(invoke_instruction->GetReferenceTypeInfo(),
1945 /* declared_can_be_null */ true,
1946 return_replacement)) {
1947 return true;
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001948 } else if (return_replacement->IsInstanceFieldGet()) {
1949 HInstanceFieldGet* field_get = return_replacement->AsInstanceFieldGet();
1950 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1951 if (field_get->GetFieldInfo().GetField() ==
1952 class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0)) {
1953 return true;
1954 }
David Brazdil94ab38f2016-06-21 17:48:19 +01001955 }
1956 } else if (return_replacement->IsInstanceOf()) {
1957 // Inlining InstanceOf into an If may put a tighter bound on reference types.
1958 return true;
1959 }
1960 }
1961
1962 return false;
1963}
1964
1965void HInliner::FixUpReturnReferenceType(ArtMethod* resolved_method,
1966 HInstruction* return_replacement) {
1967 if (return_replacement != nullptr) {
1968 if (return_replacement->GetType() == Primitive::kPrimNot) {
David Brazdil4833f5a2015-12-16 10:37:39 +00001969 if (!return_replacement->GetReferenceTypeInfo().IsValid()) {
1970 // Make sure that we have a valid type for the return. We may get an invalid one when
1971 // we inline invokes with multiple branches and create a Phi for the result.
1972 // TODO: we could be more precise by merging the phi inputs but that requires
1973 // some functionality from the reference type propagation.
1974 DCHECK(return_replacement->IsPhi());
Vladimir Marko942fd312017-01-16 20:52:19 +00001975 mirror::Class* cls = resolved_method->GetReturnType(false /* resolve */);
David Brazdil94ab38f2016-06-21 17:48:19 +01001976 return_replacement->SetReferenceTypeInfo(GetClassRTI(cls));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001977 }
Calin Juravlecdfed3d2015-10-26 14:05:01 +00001978 }
Calin Juravle2e768302015-07-28 14:41:11 +00001979 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001980}
1981
1982} // namespace art