blob: eda26f11276259296f40a52f9ddc84ac01c79a55 [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"
Vladimir Markobe10e8e2016-01-22 12:09:44 +000025#include "dex/verified_method.h"
26#include "dex/verification_results.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000027#include "driver/compiler_driver-inl.h"
Calin Juravleec748352015-07-29 13:52:12 +010028#include "driver/compiler_options.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000029#include "driver/dex_compilation_unit.h"
30#include "instruction_simplifier.h"
Scott Wakelingd60a1af2015-07-22 14:32:44 +010031#include "intrinsics.h"
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +000032#include "jit/jit.h"
33#include "jit/jit_code_cache.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000034#include "mirror/class_loader.h"
35#include "mirror/dex_cache.h"
36#include "nodes.h"
Nicolas Geoffray335005e2015-06-25 10:01:47 +010037#include "optimizing_compiler.h"
Nicolas Geoffray454a4812015-06-09 10:37:32 +010038#include "reference_type_propagation.h"
Matthew Gharritye9288852016-07-14 14:08:16 -070039#include "register_allocator_linear_scan.h"
Vladimir Markobe10e8e2016-01-22 12:09:44 +000040#include "quick/inline_method_analyser.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.
66static constexpr bool kUseAOTInlineCaches = false;
67
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 Geoffray27ef25f2017-03-24 08:59:22 +0000363 return resolved_method->GetSingleImplementation(pointer_size);
Mingyao Yang063fc772016-08-02 11:02:54 -0700364}
365
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700366bool HInliner::TryInline(HInvoke* invoke_instruction) {
Orion Hodsonac141392017-01-13 11:53:47 +0000367 if (invoke_instruction->IsInvokeUnresolved() ||
368 invoke_instruction->IsInvokePolymorphic()) {
369 return false; // Don't bother to move further if we know the method is unresolved or an
370 // invoke-polymorphic.
Calin Juravle175dc732015-08-25 15:42:32 +0100371 }
372
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000373 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100374 uint32_t method_index = invoke_instruction->GetDexMethodIndex();
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000375 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000376 LOG_TRY() << caller_dex_file.PrettyMethod(method_index);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000377
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100378 ArtMethod* resolved_method = invoke_instruction->GetResolvedMethod();
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100379 if (resolved_method == nullptr) {
380 DCHECK(invoke_instruction->IsInvokeStaticOrDirect());
381 DCHECK(invoke_instruction->AsInvokeStaticOrDirect()->IsStringInit());
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000382 LOG_FAIL_NO_STAT() << "Not inlining a String.<init> method";
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100383 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000384 }
385 ArtMethod* actual_method = nullptr;
386
387 if (invoke_instruction->IsInvokeStaticOrDirect()) {
Andreas Gampefd2140f2015-12-23 16:30:44 -0800388 actual_method = resolved_method;
Vladimir Marko58155012015-08-19 12:49:41 +0000389 } else {
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100390 // Check if we can statically find the method.
391 actual_method = FindVirtualOrInterfaceTarget(invoke_instruction, resolved_method);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000392 }
393
Mingyao Yang063fc772016-08-02 11:02:54 -0700394 bool cha_devirtualize = false;
395 if (actual_method == nullptr) {
396 ArtMethod* method = TryCHADevirtualization(resolved_method);
397 if (method != nullptr) {
398 cha_devirtualize = true;
399 actual_method = method;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000400 LOG_NOTE() << "Try CHA-based inlining of " << actual_method->PrettyMethod();
Mingyao Yang063fc772016-08-02 11:02:54 -0700401 }
402 }
403
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100404 if (actual_method != nullptr) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700405 bool result = TryInlineAndReplace(invoke_instruction,
406 actual_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000407 ReferenceTypeInfo::CreateInvalid(),
Mingyao Yang063fc772016-08-02 11:02:54 -0700408 /* do_rtp */ true,
409 cha_devirtualize);
Calin Juravle69158982016-03-16 11:53:41 +0000410 if (result && !invoke_instruction->IsInvokeStaticOrDirect()) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700411 if (cha_devirtualize) {
412 // Add dependency due to devirtulization. We've assumed resolved_method
413 // has single implementation.
414 outermost_graph_->AddCHASingleImplementationDependency(resolved_method);
415 MaybeRecordStat(kCHAInline);
416 } else {
417 MaybeRecordStat(kInlinedInvokeVirtualOrInterface);
418 }
Calin Juravle69158982016-03-16 11:53:41 +0000419 }
420 return result;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100421 }
Andreas Gampefd2140f2015-12-23 16:30:44 -0800422 DCHECK(!invoke_instruction->IsInvokeStaticOrDirect());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100423
Calin Juravle13439f02017-02-21 01:17:21 -0800424 // Try using inline caches.
425 return TryInlineFromInlineCache(caller_dex_file, invoke_instruction, resolved_method);
426}
427
428static Handle<mirror::ObjectArray<mirror::Class>> AllocateInlineCacheHolder(
429 const DexCompilationUnit& compilation_unit,
430 StackHandleScope<1>* hs)
431 REQUIRES_SHARED(Locks::mutator_lock_) {
432 Thread* self = Thread::Current();
433 ClassLinker* class_linker = compilation_unit.GetClassLinker();
434 Handle<mirror::ObjectArray<mirror::Class>> inline_cache = hs->NewHandle(
435 mirror::ObjectArray<mirror::Class>::Alloc(
436 self,
437 class_linker->GetClassRoot(ClassLinker::kClassArrayClass),
438 InlineCache::kIndividualCacheSize));
439 if (inline_cache == nullptr) {
440 // We got an OOME. Just clear the exception, and don't inline.
441 DCHECK(self->IsExceptionPending());
442 self->ClearException();
443 VLOG(compiler) << "Out of memory in the compiler when trying to inline";
444 }
445 return inline_cache;
446}
447
448bool HInliner::TryInlineFromInlineCache(const DexFile& caller_dex_file,
449 HInvoke* invoke_instruction,
450 ArtMethod* resolved_method)
451 REQUIRES_SHARED(Locks::mutator_lock_) {
Calin Juravlee2492d42017-03-20 11:42:13 -0700452 if (Runtime::Current()->IsAotCompiler() && !kUseAOTInlineCaches) {
453 return false;
454 }
455
Calin Juravle13439f02017-02-21 01:17:21 -0800456 StackHandleScope<1> hs(Thread::Current());
457 Handle<mirror::ObjectArray<mirror::Class>> inline_cache;
458 InlineCacheType inline_cache_type = Runtime::Current()->IsAotCompiler()
459 ? GetInlineCacheAOT(caller_dex_file, invoke_instruction, &hs, &inline_cache)
460 : GetInlineCacheJIT(invoke_instruction, &hs, &inline_cache);
461
462 switch (inline_cache_type) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000463 case kInlineCacheNoData: {
464 LOG_FAIL_NO_STAT()
465 << "Interface or virtual call to "
466 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
467 << " could not be statically determined";
Calin Juravle13439f02017-02-21 01:17:21 -0800468 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000469 }
Calin Juravle13439f02017-02-21 01:17:21 -0800470
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000471 case kInlineCacheUninitialized: {
472 LOG_FAIL_NO_STAT()
473 << "Interface or virtual call to "
474 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
475 << " is not hit and not inlined";
476 return false;
477 }
478
479 case kInlineCacheMonomorphic: {
Calin Juravle13439f02017-02-21 01:17:21 -0800480 MaybeRecordStat(kMonomorphicCall);
481 if (outermost_graph_->IsCompilingOsr()) {
482 // If we are compiling OSR, we pretend this call is polymorphic, as we may come from the
483 // interpreter and it may have seen different receiver types.
484 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000485 } else {
Calin Juravle13439f02017-02-21 01:17:21 -0800486 return TryInlineMonomorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000487 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000488 }
Calin Juravle13439f02017-02-21 01:17:21 -0800489
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000490 case kInlineCachePolymorphic: {
Calin Juravle13439f02017-02-21 01:17:21 -0800491 MaybeRecordStat(kPolymorphicCall);
492 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000493 }
Calin Juravle13439f02017-02-21 01:17:21 -0800494
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000495 case kInlineCacheMegamorphic: {
496 LOG_FAIL_NO_STAT()
497 << "Interface or virtual call to "
498 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
499 << " is megamorphic and not inlined";
Calin Juravle13439f02017-02-21 01:17:21 -0800500 MaybeRecordStat(kMegamorphicCall);
501 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000502 }
Calin Juravle13439f02017-02-21 01:17:21 -0800503
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000504 case kInlineCacheMissingTypes: {
505 LOG_FAIL_NO_STAT()
506 << "Interface or virtual call to "
507 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
508 << " is missing types and not inlined";
Calin Juravle13439f02017-02-21 01:17:21 -0800509 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000510 }
Calin Juravle13439f02017-02-21 01:17:21 -0800511 }
512 UNREACHABLE();
513}
514
515HInliner::InlineCacheType HInliner::GetInlineCacheJIT(
516 HInvoke* invoke_instruction,
517 StackHandleScope<1>* hs,
518 /*out*/Handle<mirror::ObjectArray<mirror::Class>>* inline_cache)
519 REQUIRES_SHARED(Locks::mutator_lock_) {
520 DCHECK(Runtime::Current()->UseJitCompilation());
521
522 ArtMethod* caller = graph_->GetArtMethod();
523 // Under JIT, we should always know the caller.
524 DCHECK(caller != nullptr);
525 ScopedProfilingInfoInlineUse spiis(caller, Thread::Current());
526 ProfilingInfo* profiling_info = spiis.GetProfilingInfo();
527
528 if (profiling_info == nullptr) {
529 return kInlineCacheNoData;
530 }
531
532 *inline_cache = AllocateInlineCacheHolder(caller_compilation_unit_, hs);
533 if (inline_cache->Get() == nullptr) {
534 // We can't extract any data if we failed to allocate;
535 return kInlineCacheNoData;
536 } else {
537 Runtime::Current()->GetJit()->GetCodeCache()->CopyInlineCacheInto(
538 *profiling_info->GetInlineCache(invoke_instruction->GetDexPc()),
539 *inline_cache);
540 return GetInlineCacheType(*inline_cache);
541 }
542}
543
544HInliner::InlineCacheType HInliner::GetInlineCacheAOT(
545 const DexFile& caller_dex_file,
546 HInvoke* invoke_instruction,
547 StackHandleScope<1>* hs,
548 /*out*/Handle<mirror::ObjectArray<mirror::Class>>* inline_cache)
549 REQUIRES_SHARED(Locks::mutator_lock_) {
550 DCHECK(Runtime::Current()->IsAotCompiler());
551 const ProfileCompilationInfo* pci = compiler_driver_->GetProfileCompilationInfo();
552 if (pci == nullptr) {
553 return kInlineCacheNoData;
554 }
555
556 ProfileCompilationInfo::OfflineProfileMethodInfo offline_profile;
557 bool found = pci->GetMethod(caller_dex_file.GetLocation(),
558 caller_dex_file.GetLocationChecksum(),
559 caller_compilation_unit_.GetDexMethodIndex(),
560 &offline_profile);
561 if (!found) {
562 return kInlineCacheNoData; // no profile information for this invocation.
563 }
564
565 *inline_cache = AllocateInlineCacheHolder(caller_compilation_unit_, hs);
566 if (inline_cache == nullptr) {
567 // We can't extract any data if we failed to allocate;
568 return kInlineCacheNoData;
569 } else {
570 return ExtractClassesFromOfflineProfile(invoke_instruction,
571 offline_profile,
572 *inline_cache);
573 }
574}
575
576HInliner::InlineCacheType HInliner::ExtractClassesFromOfflineProfile(
577 const HInvoke* invoke_instruction,
578 const ProfileCompilationInfo::OfflineProfileMethodInfo& offline_profile,
579 /*out*/Handle<mirror::ObjectArray<mirror::Class>> inline_cache)
580 REQUIRES_SHARED(Locks::mutator_lock_) {
581 const auto it = offline_profile.inline_caches.find(invoke_instruction->GetDexPc());
582 if (it == offline_profile.inline_caches.end()) {
583 return kInlineCacheUninitialized;
584 }
585
586 const ProfileCompilationInfo::DexPcData& dex_pc_data = it->second;
587
588 if (dex_pc_data.is_missing_types) {
589 return kInlineCacheMissingTypes;
590 }
591 if (dex_pc_data.is_megamorphic) {
592 return kInlineCacheMegamorphic;
593 }
594
595 DCHECK_LE(dex_pc_data.classes.size(), InlineCache::kIndividualCacheSize);
596 Thread* self = Thread::Current();
597 // We need to resolve the class relative to the containing dex file.
598 // So first, build a mapping from the index of dex file in the profile to
599 // its dex cache. This will avoid repeating the lookup when walking over
600 // the inline cache types.
601 std::vector<ObjPtr<mirror::DexCache>> dex_profile_index_to_dex_cache(
602 offline_profile.dex_references.size());
603 for (size_t i = 0; i < offline_profile.dex_references.size(); i++) {
604 bool found = false;
605 for (const DexFile* dex_file : compiler_driver_->GetDexFilesForOatFile()) {
606 if (offline_profile.dex_references[i].MatchesDex(dex_file)) {
607 dex_profile_index_to_dex_cache[i] =
608 caller_compilation_unit_.GetClassLinker()->FindDexCache(self, *dex_file);
609 found = true;
610 }
611 }
612 if (!found) {
613 VLOG(compiler) << "Could not find profiled dex file: "
614 << offline_profile.dex_references[i].dex_location;
615 return kInlineCacheMissingTypes;
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100616 }
617 }
618
Calin Juravle13439f02017-02-21 01:17:21 -0800619 // Walk over the classes and resolve them. If we cannot find a type we return
620 // kInlineCacheMissingTypes.
621 int ic_index = 0;
622 for (const ProfileCompilationInfo::ClassReference& class_ref : dex_pc_data.classes) {
623 ObjPtr<mirror::DexCache> dex_cache =
624 dex_profile_index_to_dex_cache[class_ref.dex_profile_index];
625 DCHECK(dex_cache != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000626 ObjPtr<mirror::Class> clazz = ClassLinker::LookupResolvedType(
627 class_ref.type_index,
628 dex_cache,
629 caller_compilation_unit_.GetClassLoader().Get());
Calin Juravle13439f02017-02-21 01:17:21 -0800630 if (clazz != nullptr) {
631 inline_cache->Set(ic_index++, clazz);
632 } else {
633 VLOG(compiler) << "Could not resolve class from inline cache in AOT mode "
634 << caller_compilation_unit_.GetDexFile()->PrettyMethod(
635 invoke_instruction->GetDexMethodIndex()) << " : "
636 << caller_compilation_unit_
637 .GetDexFile()->StringByTypeIdx(class_ref.type_index);
638 return kInlineCacheMissingTypes;
639 }
640 }
641 return GetInlineCacheType(inline_cache);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100642}
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000643
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000644HInstanceFieldGet* HInliner::BuildGetReceiverClass(ClassLinker* class_linker,
645 HInstruction* receiver,
646 uint32_t dex_pc) const {
647 ArtField* field = class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0);
648 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000649 HInstanceFieldGet* result = new (graph_->GetArena()) HInstanceFieldGet(
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000650 receiver,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000651 field,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000652 Primitive::kPrimNot,
653 field->GetOffset(),
654 field->IsVolatile(),
655 field->GetDexFieldIndex(),
656 field->GetDeclaringClass()->GetDexClassDefIndex(),
657 *field->GetDexFile(),
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000658 dex_pc);
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000659 // The class of a field is effectively final, and does not have any memory dependencies.
660 result->SetSideEffects(SideEffects::None());
661 return result;
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000662}
663
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100664bool HInliner::TryInlineMonomorphicCall(HInvoke* invoke_instruction,
665 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000666 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000667 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
668 << invoke_instruction->DebugName();
669
Andreas Gampea5b09a62016-11-17 15:21:22 -0800670 dex::TypeIndex class_index = FindClassIndexIn(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000671 GetMonomorphicType(classes), caller_compilation_unit_);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800672 if (!class_index.IsValid()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000673 LOG_FAIL(kNotInlinedDexCache)
674 << "Call to " << ArtMethod::PrettyMethod(resolved_method)
675 << " from inline cache is not inlined because its class is not"
676 << " accessible to the caller";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100677 return false;
678 }
679
680 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700681 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100682 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000683 resolved_method = GetMonomorphicType(classes)->FindVirtualMethodForInterface(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100684 resolved_method, pointer_size);
685 } else {
686 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000687 resolved_method = GetMonomorphicType(classes)->FindVirtualMethodForVirtual(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100688 resolved_method, pointer_size);
689 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000690 LOG_NOTE() << "Try inline monomorphic call to " << resolved_method->PrettyMethod();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100691 DCHECK(resolved_method != nullptr);
692 HInstruction* receiver = invoke_instruction->InputAt(0);
693 HInstruction* cursor = invoke_instruction->GetPrevious();
694 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000695 Handle<mirror::Class> monomorphic_type = handles_->NewHandle(GetMonomorphicType(classes));
Mingyao Yang063fc772016-08-02 11:02:54 -0700696 if (!TryInlineAndReplace(invoke_instruction,
697 resolved_method,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000698 ReferenceTypeInfo::Create(monomorphic_type, /* is_exact */ true),
Mingyao Yang063fc772016-08-02 11:02:54 -0700699 /* do_rtp */ false,
700 /* cha_devirtualize */ false)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100701 return false;
702 }
703
704 // We successfully inlined, now add a guard.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000705 AddTypeGuard(receiver,
706 cursor,
707 bb_cursor,
708 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000709 monomorphic_type,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000710 invoke_instruction,
711 /* with_deoptimization */ true);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100712
713 // Run type propagation to get the guard typed, and eventually propagate the
714 // type of the receiver.
Vladimir Marko456307a2016-04-19 14:12:13 +0000715 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000716 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +0000717 outer_compilation_unit_.GetDexCache(),
718 handles_,
719 /* is_first_run */ false);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100720 rtp_fixup.Run();
721
722 MaybeRecordStat(kInlinedMonomorphicCall);
723 return true;
724}
725
Mingyao Yang063fc772016-08-02 11:02:54 -0700726void HInliner::AddCHAGuard(HInstruction* invoke_instruction,
727 uint32_t dex_pc,
728 HInstruction* cursor,
729 HBasicBlock* bb_cursor) {
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800730 HShouldDeoptimizeFlag* deopt_flag = new (graph_->GetArena())
731 HShouldDeoptimizeFlag(graph_->GetArena(), dex_pc);
732 HInstruction* compare = new (graph_->GetArena()) HNotEqual(
Mingyao Yang063fc772016-08-02 11:02:54 -0700733 deopt_flag, graph_->GetIntConstant(0, dex_pc));
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800734 HInstruction* deopt = new (graph_->GetArena()) HDeoptimize(compare, dex_pc);
Mingyao Yang063fc772016-08-02 11:02:54 -0700735
736 if (cursor != nullptr) {
737 bb_cursor->InsertInstructionAfter(deopt_flag, cursor);
738 } else {
739 bb_cursor->InsertInstructionBefore(deopt_flag, bb_cursor->GetFirstInstruction());
740 }
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800741 bb_cursor->InsertInstructionAfter(compare, deopt_flag);
742 bb_cursor->InsertInstructionAfter(deopt, compare);
743
744 // Add receiver as input to aid CHA guard optimization later.
745 deopt_flag->AddInput(invoke_instruction->InputAt(0));
746 DCHECK_EQ(deopt_flag->InputCount(), 1u);
Mingyao Yang063fc772016-08-02 11:02:54 -0700747 deopt->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800748 outermost_graph_->IncrementNumberOfCHAGuards();
Mingyao Yang063fc772016-08-02 11:02:54 -0700749}
750
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000751HInstruction* HInliner::AddTypeGuard(HInstruction* receiver,
752 HInstruction* cursor,
753 HBasicBlock* bb_cursor,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800754 dex::TypeIndex class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000755 Handle<mirror::Class> klass,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000756 HInstruction* invoke_instruction,
757 bool with_deoptimization) {
758 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
759 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
760 class_linker, receiver, invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000761 if (cursor != nullptr) {
762 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
763 } else {
764 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
765 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000766
767 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000768 bool is_referrer = (klass.Get() == outermost_graph_->GetArtMethod()->GetDeclaringClass());
Nicolas Geoffray56876342016-12-16 16:09:08 +0000769 // Note that we will just compare the classes, so we don't need Java semantics access checks.
770 // Note that the type index and the dex file are relative to the method this type guard is
771 // inlined into.
772 HLoadClass* load_class = new (graph_->GetArena()) HLoadClass(graph_->GetCurrentMethod(),
773 class_index,
774 caller_dex_file,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000775 klass,
Nicolas Geoffray56876342016-12-16 16:09:08 +0000776 is_referrer,
777 invoke_instruction->GetDexPc(),
778 /* needs_access_check */ false);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000779 HLoadClass::LoadKind kind = HSharpening::ComputeLoadClassKind(
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000780 load_class, codegen_, compiler_driver_, caller_compilation_unit_);
781 DCHECK(kind != HLoadClass::LoadKind::kInvalid)
782 << "We should always be able to reference a class for inline caches";
783 // Insert before setting the kind, as setting the kind affects the inputs.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000784 bb_cursor->InsertInstructionAfter(load_class, receiver_class);
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000785 load_class->SetLoadKind(kind);
Calin Juravle13439f02017-02-21 01:17:21 -0800786 // In AOT mode, we will most likely load the class from BSS, which will involve a call
787 // to the runtime. In this case, the load instruction will need an environment so copy
788 // it from the invoke instruction.
789 if (load_class->NeedsEnvironment()) {
790 DCHECK(Runtime::Current()->IsAotCompiler());
791 load_class->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
792 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000793
Nicolas Geoffray56876342016-12-16 16:09:08 +0000794 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(load_class, receiver_class);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000795 bb_cursor->InsertInstructionAfter(compare, load_class);
796 if (with_deoptimization) {
797 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
798 compare, invoke_instruction->GetDexPc());
799 bb_cursor->InsertInstructionAfter(deoptimize, compare);
800 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
801 }
802 return compare;
803}
804
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000805bool HInliner::TryInlinePolymorphicCall(HInvoke* invoke_instruction,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100806 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000807 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000808 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
809 << invoke_instruction->DebugName();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000810
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000811 if (TryInlinePolymorphicCallToSameTarget(invoke_instruction, resolved_method, classes)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000812 return true;
813 }
814
815 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700816 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000817
818 bool all_targets_inlined = true;
819 bool one_target_inlined = false;
820 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000821 if (classes->Get(i) == nullptr) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000822 break;
823 }
824 ArtMethod* method = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000825
826 Handle<mirror::Class> handle = handles_->NewHandle(classes->Get(i));
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000827 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000828 method = handle->FindVirtualMethodForInterface(resolved_method, pointer_size);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000829 } else {
830 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000831 method = handle->FindVirtualMethodForVirtual(resolved_method, pointer_size);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000832 }
833
834 HInstruction* receiver = invoke_instruction->InputAt(0);
835 HInstruction* cursor = invoke_instruction->GetPrevious();
836 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
837
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000838 dex::TypeIndex class_index = FindClassIndexIn(handle.Get(), caller_compilation_unit_);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000839 HInstruction* return_replacement = nullptr;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000840 LOG_NOTE() << "Try inline polymorphic call to " << method->PrettyMethod();
Andreas Gampea5b09a62016-11-17 15:21:22 -0800841 if (!class_index.IsValid() ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000842 !TryBuildAndInline(invoke_instruction,
843 method,
844 ReferenceTypeInfo::Create(handle, /* is_exact */ true),
845 &return_replacement)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000846 all_targets_inlined = false;
847 } else {
848 one_target_inlined = true;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000849
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000850 LOG_SUCCESS() << "Polymorphic call to " << ArtMethod::PrettyMethod(resolved_method)
851 << " has inlined " << ArtMethod::PrettyMethod(method);
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000852
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000853 // If we have inlined all targets before, and this receiver is the last seen,
854 // we deoptimize instead of keeping the original invoke instruction.
855 bool deoptimize = all_targets_inlined &&
856 (i != InlineCache::kIndividualCacheSize - 1) &&
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000857 (classes->Get(i + 1) == nullptr);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100858
859 if (outermost_graph_->IsCompilingOsr()) {
860 // We do not support HDeoptimize in OSR methods.
861 deoptimize = false;
862 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000863 HInstruction* compare = AddTypeGuard(receiver,
864 cursor,
865 bb_cursor,
866 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000867 handle,
Nicolas Geoffray56876342016-12-16 16:09:08 +0000868 invoke_instruction,
869 deoptimize);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000870 if (deoptimize) {
871 if (return_replacement != nullptr) {
872 invoke_instruction->ReplaceWith(return_replacement);
873 }
874 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
875 // Because the inline cache data can be populated concurrently, we force the end of the
876 // iteration. Otherhwise, we could see a new receiver type.
877 break;
878 } else {
879 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
880 }
881 }
882 }
883
884 if (!one_target_inlined) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000885 LOG_FAIL_NO_STAT()
886 << "Call to " << ArtMethod::PrettyMethod(resolved_method)
887 << " from inline cache is not inlined because none"
888 << " of its targets could be inlined";
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000889 return false;
890 }
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000891
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000892 MaybeRecordStat(kInlinedPolymorphicCall);
893
894 // Run type propagation to get the guards typed.
Vladimir Marko456307a2016-04-19 14:12:13 +0000895 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000896 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +0000897 outer_compilation_unit_.GetDexCache(),
898 handles_,
899 /* is_first_run */ false);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000900 rtp_fixup.Run();
901 return true;
902}
903
904void HInliner::CreateDiamondPatternForPolymorphicInline(HInstruction* compare,
905 HInstruction* return_replacement,
906 HInstruction* invoke_instruction) {
907 uint32_t dex_pc = invoke_instruction->GetDexPc();
908 HBasicBlock* cursor_block = compare->GetBlock();
909 HBasicBlock* original_invoke_block = invoke_instruction->GetBlock();
910 ArenaAllocator* allocator = graph_->GetArena();
911
912 // Spit the block after the compare: `cursor_block` will now be the start of the diamond,
913 // and the returned block is the start of the then branch (that could contain multiple blocks).
914 HBasicBlock* then = cursor_block->SplitAfterForInlining(compare);
915
916 // Split the block containing the invoke before and after the invoke. The returned block
917 // of the split before will contain the invoke and will be the otherwise branch of
918 // the diamond. The returned block of the split after will be the merge block
919 // of the diamond.
920 HBasicBlock* end_then = invoke_instruction->GetBlock();
921 HBasicBlock* otherwise = end_then->SplitBeforeForInlining(invoke_instruction);
922 HBasicBlock* merge = otherwise->SplitAfterForInlining(invoke_instruction);
923
924 // If the methods we are inlining return a value, we create a phi in the merge block
925 // that will have the `invoke_instruction and the `return_replacement` as inputs.
926 if (return_replacement != nullptr) {
927 HPhi* phi = new (allocator) HPhi(
928 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke_instruction->GetType()), dex_pc);
929 merge->AddPhi(phi);
930 invoke_instruction->ReplaceWith(phi);
931 phi->AddInput(return_replacement);
932 phi->AddInput(invoke_instruction);
933 }
934
935 // Add the control flow instructions.
936 otherwise->AddInstruction(new (allocator) HGoto(dex_pc));
937 end_then->AddInstruction(new (allocator) HGoto(dex_pc));
938 cursor_block->AddInstruction(new (allocator) HIf(compare, dex_pc));
939
940 // Add the newly created blocks to the graph.
941 graph_->AddBlock(then);
942 graph_->AddBlock(otherwise);
943 graph_->AddBlock(merge);
944
945 // Set up successor (and implictly predecessor) relations.
946 cursor_block->AddSuccessor(otherwise);
947 cursor_block->AddSuccessor(then);
948 end_then->AddSuccessor(merge);
949 otherwise->AddSuccessor(merge);
950
951 // Set up dominance information.
952 then->SetDominator(cursor_block);
953 cursor_block->AddDominatedBlock(then);
954 otherwise->SetDominator(cursor_block);
955 cursor_block->AddDominatedBlock(otherwise);
956 merge->SetDominator(cursor_block);
957 cursor_block->AddDominatedBlock(merge);
958
959 // Update the revert post order.
960 size_t index = IndexOfElement(graph_->reverse_post_order_, cursor_block);
961 MakeRoomFor(&graph_->reverse_post_order_, 1, index);
962 graph_->reverse_post_order_[++index] = then;
963 index = IndexOfElement(graph_->reverse_post_order_, end_then);
964 MakeRoomFor(&graph_->reverse_post_order_, 2, index);
965 graph_->reverse_post_order_[++index] = otherwise;
966 graph_->reverse_post_order_[++index] = merge;
967
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000968
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +0000969 graph_->UpdateLoopAndTryInformationOfNewBlock(
970 then, original_invoke_block, /* replace_if_back_edge */ false);
971 graph_->UpdateLoopAndTryInformationOfNewBlock(
972 otherwise, original_invoke_block, /* replace_if_back_edge */ false);
973
974 // In case the original invoke location was a back edge, we need to update
975 // the loop to now have the merge block as a back edge.
976 graph_->UpdateLoopAndTryInformationOfNewBlock(
977 merge, original_invoke_block, /* replace_if_back_edge */ true);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000978}
979
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000980bool HInliner::TryInlinePolymorphicCallToSameTarget(
981 HInvoke* invoke_instruction,
982 ArtMethod* resolved_method,
983 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000984 // This optimization only works under JIT for now.
Calin Juravle13439f02017-02-21 01:17:21 -0800985 if (!Runtime::Current()->UseJitCompilation()) {
986 return false;
987 }
988
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000989 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700990 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000991
992 DCHECK(resolved_method != nullptr);
993 ArtMethod* actual_method = nullptr;
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000994 size_t method_index = invoke_instruction->IsInvokeVirtual()
995 ? invoke_instruction->AsInvokeVirtual()->GetVTableIndex()
996 : invoke_instruction->AsInvokeInterface()->GetImtIndex();
997
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000998 // Check whether we are actually calling the same method among
999 // the different types seen.
1000 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001001 if (classes->Get(i) == nullptr) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001002 break;
1003 }
1004 ArtMethod* new_method = nullptr;
1005 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001006 new_method = classes->Get(i)->GetImt(pointer_size)->Get(
Matthew Gharrity465ecc82016-07-19 21:32:52 +00001007 method_index, pointer_size);
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001008 if (new_method->IsRuntimeMethod()) {
1009 // Bail out as soon as we see a conflict trampoline in one of the target's
1010 // interface table.
1011 return false;
1012 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001013 } else {
1014 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001015 new_method = classes->Get(i)->GetEmbeddedVTableEntry(method_index, pointer_size);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001016 }
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001017 DCHECK(new_method != nullptr);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001018 if (actual_method == nullptr) {
1019 actual_method = new_method;
1020 } else if (actual_method != new_method) {
1021 // Different methods, bailout.
1022 return false;
1023 }
1024 }
1025
1026 HInstruction* receiver = invoke_instruction->InputAt(0);
1027 HInstruction* cursor = invoke_instruction->GetPrevious();
1028 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
1029
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001030 HInstruction* return_replacement = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001031 if (!TryBuildAndInline(invoke_instruction,
1032 actual_method,
1033 ReferenceTypeInfo::CreateInvalid(),
1034 &return_replacement)) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001035 return false;
1036 }
1037
1038 // We successfully inlined, now add a guard.
1039 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
1040 class_linker, receiver, invoke_instruction->GetDexPc());
1041
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001042 Primitive::Type type = Is64BitInstructionSet(graph_->GetInstructionSet())
1043 ? Primitive::kPrimLong
1044 : Primitive::kPrimInt;
1045 HClassTableGet* class_table_get = new (graph_->GetArena()) HClassTableGet(
1046 receiver_class,
1047 type,
Vladimir Markoa1de9182016-02-25 11:37:38 +00001048 invoke_instruction->IsInvokeVirtual() ? HClassTableGet::TableKind::kVTable
1049 : HClassTableGet::TableKind::kIMTable,
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001050 method_index,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001051 invoke_instruction->GetDexPc());
1052
1053 HConstant* constant;
1054 if (type == Primitive::kPrimLong) {
1055 constant = graph_->GetLongConstant(
1056 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
1057 } else {
1058 constant = graph_->GetIntConstant(
1059 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
1060 }
1061
1062 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(class_table_get, constant);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001063 if (cursor != nullptr) {
1064 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
1065 } else {
1066 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
1067 }
1068 bb_cursor->InsertInstructionAfter(class_table_get, receiver_class);
1069 bb_cursor->InsertInstructionAfter(compare, class_table_get);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001070
1071 if (outermost_graph_->IsCompilingOsr()) {
1072 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
1073 } else {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001074 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
1075 compare, invoke_instruction->GetDexPc());
1076 bb_cursor->InsertInstructionAfter(deoptimize, compare);
1077 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
1078 if (return_replacement != nullptr) {
1079 invoke_instruction->ReplaceWith(return_replacement);
1080 }
Nicolas Geoffray1be7cbd2016-04-29 13:56:01 +01001081 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001082 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001083
1084 // Run type propagation to get the guard typed.
Vladimir Marko456307a2016-04-19 14:12:13 +00001085 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001086 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +00001087 outer_compilation_unit_.GetDexCache(),
1088 handles_,
1089 /* is_first_run */ false);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001090 rtp_fixup.Run();
1091
1092 MaybeRecordStat(kInlinedPolymorphicCall);
1093
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001094 LOG_SUCCESS() << "Inlined same polymorphic target " << actual_method->PrettyMethod();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001095 return true;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001096}
1097
Mingyao Yang063fc772016-08-02 11:02:54 -07001098bool HInliner::TryInlineAndReplace(HInvoke* invoke_instruction,
1099 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001100 ReferenceTypeInfo receiver_type,
Mingyao Yang063fc772016-08-02 11:02:54 -07001101 bool do_rtp,
1102 bool cha_devirtualize) {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001103 HInstruction* return_replacement = nullptr;
Mingyao Yang063fc772016-08-02 11:02:54 -07001104 uint32_t dex_pc = invoke_instruction->GetDexPc();
1105 HInstruction* cursor = invoke_instruction->GetPrevious();
1106 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001107 if (!TryBuildAndInline(invoke_instruction, method, receiver_type, &return_replacement)) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001108 if (invoke_instruction->IsInvokeInterface()) {
1109 // Turn an invoke-interface into an invoke-virtual. An invoke-virtual is always
1110 // better than an invoke-interface because:
1111 // 1) In the best case, the interface call has one more indirection (to fetch the IMT).
1112 // 2) We will not go to the conflict trampoline with an invoke-virtual.
1113 // TODO: Consider sharpening once it is not dependent on the compiler driver.
1114 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001115 uint32_t dex_method_index = FindMethodIndexIn(
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001116 method, caller_dex_file, invoke_instruction->GetDexMethodIndex());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001117 if (dex_method_index == DexFile::kDexNoIndex) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001118 return false;
1119 }
1120 HInvokeVirtual* new_invoke = new (graph_->GetArena()) HInvokeVirtual(
1121 graph_->GetArena(),
1122 invoke_instruction->GetNumberOfArguments(),
1123 invoke_instruction->GetType(),
1124 invoke_instruction->GetDexPc(),
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001125 dex_method_index,
1126 method,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001127 method->GetMethodIndex());
1128 HInputsRef inputs = invoke_instruction->GetInputs();
1129 for (size_t index = 0; index != inputs.size(); ++index) {
1130 new_invoke->SetArgumentAt(index, inputs[index]);
1131 }
1132 invoke_instruction->GetBlock()->InsertInstructionBefore(new_invoke, invoke_instruction);
1133 new_invoke->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
1134 if (invoke_instruction->GetType() == Primitive::kPrimNot) {
1135 new_invoke->SetReferenceTypeInfo(invoke_instruction->GetReferenceTypeInfo());
1136 }
1137 return_replacement = new_invoke;
1138 } else {
1139 // TODO: Consider sharpening an invoke virtual once it is not dependent on the
1140 // compiler driver.
1141 return false;
1142 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001143 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001144 if (cha_devirtualize) {
1145 AddCHAGuard(invoke_instruction, dex_pc, cursor, bb_cursor);
1146 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001147 if (return_replacement != nullptr) {
1148 invoke_instruction->ReplaceWith(return_replacement);
1149 }
1150 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
David Brazdil94ab38f2016-06-21 17:48:19 +01001151 FixUpReturnReferenceType(method, return_replacement);
1152 if (do_rtp && ReturnTypeMoreSpecific(invoke_instruction, return_replacement)) {
1153 // Actual return value has a more specific type than the method's declared
1154 // return type. Run RTP again on the outer graph to propagate it.
1155 ReferenceTypePropagation(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001156 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +01001157 outer_compilation_unit_.GetDexCache(),
1158 handles_,
1159 /* is_first_run */ false).Run();
1160 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001161 return true;
1162}
1163
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001164size_t HInliner::CountRecursiveCallsOf(ArtMethod* method) const {
1165 const HInliner* current = this;
1166 size_t count = 0;
1167 do {
1168 if (current->graph_->GetArtMethod() == method) {
1169 ++count;
1170 }
1171 current = current->parent_;
1172 } while (current != nullptr);
1173 return count;
1174}
1175
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001176bool HInliner::TryBuildAndInline(HInvoke* invoke_instruction,
1177 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001178 ReferenceTypeInfo receiver_type,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001179 HInstruction** return_replacement) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001180 if (method->IsProxyMethod()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001181 LOG_FAIL(kNotInlinedProxy)
1182 << "Method " << method->PrettyMethod()
1183 << " is not inlined because of unimplemented inline support for proxy methods.";
1184 return false;
1185 }
1186
1187 if (CountRecursiveCallsOf(method) > kMaximumNumberOfRecursiveCalls) {
1188 LOG_FAIL(kNotInlinedRecursiveBudget)
1189 << "Method "
1190 << method->PrettyMethod()
1191 << " is not inlined because it has reached its recursive call budget.";
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001192 return false;
1193 }
1194
Jeff Haodcdc85b2015-12-04 14:06:18 -08001195 // Check whether we're allowed to inline. The outermost compilation unit is the relevant
1196 // dex file here (though the transitivity of an inline chain would allow checking the calller).
1197 if (!compiler_driver_->MayInline(method->GetDexFile(),
1198 outer_compilation_unit_.GetDexFile())) {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001199 if (TryPatternSubstitution(invoke_instruction, method, return_replacement)) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001200 LOG_SUCCESS() << "Successfully replaced pattern of invoke "
1201 << method->PrettyMethod();
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001202 MaybeRecordStat(kReplacedInvokeWithSimplePattern);
1203 return true;
1204 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001205 LOG_FAIL(kNotInlinedWont)
1206 << "Won't inline " << method->PrettyMethod() << " in "
1207 << outer_compilation_unit_.GetDexFile()->GetLocation() << " ("
1208 << caller_compilation_unit_.GetDexFile()->GetLocation() << ") from "
1209 << method->GetDexFile()->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001210 return false;
1211 }
1212
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001213 bool same_dex_file = IsSameDexFile(*outer_compilation_unit_.GetDexFile(), *method->GetDexFile());
1214
1215 const DexFile::CodeItem* code_item = method->GetCodeItem();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001216
1217 if (code_item == nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001218 LOG_FAIL_NO_STAT()
1219 << "Method " << method->PrettyMethod() << " is not inlined because it is native";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001220 return false;
1221 }
1222
Calin Juravleec748352015-07-29 13:52:12 +01001223 size_t inline_max_code_units = compiler_driver_->GetCompilerOptions().GetInlineMaxCodeUnits();
1224 if (code_item->insns_size_in_code_units_ > inline_max_code_units) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001225 LOG_FAIL(kNotInlinedCodeItem)
1226 << "Method " << method->PrettyMethod()
1227 << " is not inlined because its code item is too big: "
1228 << code_item->insns_size_in_code_units_
1229 << " > "
1230 << inline_max_code_units;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001231 return false;
1232 }
1233
1234 if (code_item->tries_size_ != 0) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001235 LOG_FAIL(kNotInlinedTryCatch)
1236 << "Method " << method->PrettyMethod() << " is not inlined because of try block";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001237 return false;
1238 }
1239
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001240 if (!method->IsCompilable()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001241 LOG_FAIL(kNotInlinedNotVerified)
1242 << "Method " << method->PrettyMethod()
1243 << " has soft failures un-handled by the compiler, so it cannot be inlined";
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001244 }
1245
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001246 if (!method->GetDeclaringClass()->IsVerified()) {
1247 uint16_t class_def_idx = method->GetDeclaringClass()->GetDexClassDefIndex();
Calin Juravleffc87072016-04-20 14:22:09 +01001248 if (Runtime::Current()->UseJitCompilation() ||
Nicolas Geoffray5b82d332016-02-18 14:22:32 +00001249 !compiler_driver_->IsMethodVerifiedWithoutFailures(
1250 method->GetDexMethodIndex(), class_def_idx, *method->GetDexFile())) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001251 LOG_FAIL(kNotInlinedNotVerified)
1252 << "Method " << method->PrettyMethod()
1253 << " couldn't be verified, so it cannot be inlined";
Nicolas Geoffrayccc61972015-10-01 14:34:20 +01001254 return false;
1255 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001256 }
1257
Roland Levillain4c0eb422015-04-24 16:43:49 +01001258 if (invoke_instruction->IsInvokeStaticOrDirect() &&
1259 invoke_instruction->AsInvokeStaticOrDirect()->IsStaticWithImplicitClinitCheck()) {
1260 // Case of a static method that cannot be inlined because it implicitly
1261 // requires an initialization check of its declaring class.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001262 LOG_FAIL(kNotInlinedDexCache) << "Method " << method->PrettyMethod()
1263 << " is not inlined because it is static and requires a clinit"
1264 << " check that cannot be emitted due to Dex cache limitations";
Roland Levillain4c0eb422015-04-24 16:43:49 +01001265 return false;
1266 }
1267
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001268 if (!TryBuildAndInlineHelper(
1269 invoke_instruction, method, receiver_type, same_dex_file, return_replacement)) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001270 return false;
1271 }
1272
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001273 LOG_SUCCESS() << method->PrettyMethod();
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001274 MaybeRecordStat(kInlinedInvoke);
1275 return true;
1276}
1277
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001278static HInstruction* GetInvokeInputForArgVRegIndex(HInvoke* invoke_instruction,
1279 size_t arg_vreg_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001280 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001281 size_t input_index = 0;
1282 for (size_t i = 0; i < arg_vreg_index; ++i, ++input_index) {
1283 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
1284 if (Primitive::Is64BitType(invoke_instruction->InputAt(input_index)->GetType())) {
1285 ++i;
1286 DCHECK_NE(i, arg_vreg_index);
1287 }
1288 }
1289 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
1290 return invoke_instruction->InputAt(input_index);
1291}
1292
1293// Try to recognize known simple patterns and replace invoke call with appropriate instructions.
1294bool HInliner::TryPatternSubstitution(HInvoke* invoke_instruction,
1295 ArtMethod* resolved_method,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001296 HInstruction** return_replacement) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001297 InlineMethod inline_method;
1298 if (!InlineMethodAnalyser::AnalyseMethodCode(resolved_method, &inline_method)) {
1299 return false;
1300 }
1301
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001302 switch (inline_method.opcode) {
1303 case kInlineOpNop:
1304 DCHECK_EQ(invoke_instruction->GetType(), Primitive::kPrimVoid);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001305 *return_replacement = nullptr;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001306 break;
1307 case kInlineOpReturnArg:
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001308 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction,
1309 inline_method.d.return_data.arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001310 break;
1311 case kInlineOpNonWideConst:
1312 if (resolved_method->GetShorty()[0] == 'L') {
1313 DCHECK_EQ(inline_method.d.data, 0u);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001314 *return_replacement = graph_->GetNullConstant();
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001315 } else {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001316 *return_replacement = graph_->GetIntConstant(static_cast<int32_t>(inline_method.d.data));
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001317 }
1318 break;
1319 case kInlineOpIGet: {
1320 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1321 if (data.method_is_static || data.object_arg != 0u) {
1322 // TODO: Needs null check.
1323 return false;
1324 }
1325 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001326 HInstanceFieldGet* iget = CreateInstanceFieldGet(data.field_idx, resolved_method, obj);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001327 DCHECK_EQ(iget->GetFieldOffset().Uint32Value(), data.field_offset);
1328 DCHECK_EQ(iget->IsVolatile() ? 1u : 0u, data.is_volatile);
1329 invoke_instruction->GetBlock()->InsertInstructionBefore(iget, invoke_instruction);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001330 *return_replacement = iget;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001331 break;
1332 }
1333 case kInlineOpIPut: {
1334 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1335 if (data.method_is_static || data.object_arg != 0u) {
1336 // TODO: Needs null check.
1337 return false;
1338 }
1339 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
1340 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, data.src_arg);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001341 HInstanceFieldSet* iput = CreateInstanceFieldSet(data.field_idx, resolved_method, obj, value);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001342 DCHECK_EQ(iput->GetFieldOffset().Uint32Value(), data.field_offset);
1343 DCHECK_EQ(iput->IsVolatile() ? 1u : 0u, data.is_volatile);
1344 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1345 if (data.return_arg_plus1 != 0u) {
1346 size_t return_arg = data.return_arg_plus1 - 1u;
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001347 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction, return_arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001348 }
1349 break;
1350 }
Vladimir Marko354efa62016-02-04 19:46:56 +00001351 case kInlineOpConstructor: {
1352 const InlineConstructorData& data = inline_method.d.constructor_data;
1353 // Get the indexes to arrays for easier processing.
1354 uint16_t iput_field_indexes[] = {
1355 data.iput0_field_index, data.iput1_field_index, data.iput2_field_index
1356 };
1357 uint16_t iput_args[] = { data.iput0_arg, data.iput1_arg, data.iput2_arg };
1358 static_assert(arraysize(iput_args) == arraysize(iput_field_indexes), "Size mismatch");
1359 // Count valid field indexes.
1360 size_t number_of_iputs = 0u;
1361 while (number_of_iputs != arraysize(iput_field_indexes) &&
1362 iput_field_indexes[number_of_iputs] != DexFile::kDexNoIndex16) {
1363 // Check that there are no duplicate valid field indexes.
1364 DCHECK_EQ(0, std::count(iput_field_indexes + number_of_iputs + 1,
1365 iput_field_indexes + arraysize(iput_field_indexes),
1366 iput_field_indexes[number_of_iputs]));
1367 ++number_of_iputs;
1368 }
1369 // Check that there are no valid field indexes in the rest of the array.
1370 DCHECK_EQ(0, std::count_if(iput_field_indexes + number_of_iputs,
1371 iput_field_indexes + arraysize(iput_field_indexes),
1372 [](uint16_t index) { return index != DexFile::kDexNoIndex16; }));
1373
1374 // Create HInstanceFieldSet for each IPUT that stores non-zero data.
Vladimir Marko354efa62016-02-04 19:46:56 +00001375 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, /* this */ 0u);
1376 bool needs_constructor_barrier = false;
1377 for (size_t i = 0; i != number_of_iputs; ++i) {
1378 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, iput_args[i]);
Roland Levillain1a653882016-03-18 18:05:57 +00001379 if (!value->IsConstant() || !value->AsConstant()->IsZeroBitPattern()) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001380 uint16_t field_index = iput_field_indexes[i];
Vladimir Markof44d36c2017-03-14 14:18:46 +00001381 bool is_final;
1382 HInstanceFieldSet* iput =
1383 CreateInstanceFieldSet(field_index, resolved_method, obj, value, &is_final);
Vladimir Marko354efa62016-02-04 19:46:56 +00001384 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1385
1386 // Check whether the field is final. If it is, we need to add a barrier.
Vladimir Markof44d36c2017-03-14 14:18:46 +00001387 if (is_final) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001388 needs_constructor_barrier = true;
1389 }
1390 }
1391 }
1392 if (needs_constructor_barrier) {
1393 HMemoryBarrier* barrier = new (graph_->GetArena()) HMemoryBarrier(kStoreStore, kNoDexPc);
1394 invoke_instruction->GetBlock()->InsertInstructionBefore(barrier, invoke_instruction);
1395 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001396 *return_replacement = nullptr;
Vladimir Marko354efa62016-02-04 19:46:56 +00001397 break;
1398 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001399 default:
1400 LOG(FATAL) << "UNREACHABLE";
1401 UNREACHABLE();
1402 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001403 return true;
1404}
1405
Vladimir Markof44d36c2017-03-14 14:18:46 +00001406HInstanceFieldGet* HInliner::CreateInstanceFieldGet(uint32_t field_index,
1407 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001408 HInstruction* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001409 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001410 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1411 ArtField* resolved_field =
1412 class_linker->LookupResolvedField(field_index, referrer, /* is_static */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001413 DCHECK(resolved_field != nullptr);
1414 HInstanceFieldGet* iget = new (graph_->GetArena()) HInstanceFieldGet(
1415 obj,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001416 resolved_field,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001417 resolved_field->GetTypeAsPrimitiveType(),
1418 resolved_field->GetOffset(),
1419 resolved_field->IsVolatile(),
1420 field_index,
1421 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001422 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001423 // Read barrier generates a runtime call in slow path and we need a valid
1424 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1425 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001426 if (iget->GetType() == Primitive::kPrimNot) {
Vladimir Marko456307a2016-04-19 14:12:13 +00001427 // Use the same dex_cache that we used for field lookup as the hint_dex_cache.
Vladimir Markof44d36c2017-03-14 14:18:46 +00001428 Handle<mirror::DexCache> dex_cache = handles_->NewHandle(referrer->GetDexCache());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001429 ReferenceTypePropagation rtp(graph_,
1430 outer_compilation_unit_.GetClassLoader(),
1431 dex_cache,
1432 handles_,
1433 /* is_first_run */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001434 rtp.Visit(iget);
1435 }
1436 return iget;
1437}
1438
Vladimir Markof44d36c2017-03-14 14:18:46 +00001439HInstanceFieldSet* HInliner::CreateInstanceFieldSet(uint32_t field_index,
1440 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001441 HInstruction* obj,
Vladimir Markof44d36c2017-03-14 14:18:46 +00001442 HInstruction* value,
1443 bool* is_final)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001444 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001445 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1446 ArtField* resolved_field =
1447 class_linker->LookupResolvedField(field_index, referrer, /* is_static */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001448 DCHECK(resolved_field != nullptr);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001449 if (is_final != nullptr) {
1450 // This information is needed only for constructors.
1451 DCHECK(referrer->IsConstructor());
1452 *is_final = resolved_field->IsFinal();
1453 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001454 HInstanceFieldSet* iput = new (graph_->GetArena()) HInstanceFieldSet(
1455 obj,
1456 value,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001457 resolved_field,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001458 resolved_field->GetTypeAsPrimitiveType(),
1459 resolved_field->GetOffset(),
1460 resolved_field->IsVolatile(),
1461 field_index,
1462 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001463 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001464 // Read barrier generates a runtime call in slow path and we need a valid
1465 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1466 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001467 return iput;
1468}
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001469
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001470bool HInliner::TryBuildAndInlineHelper(HInvoke* invoke_instruction,
1471 ArtMethod* resolved_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001472 ReferenceTypeInfo receiver_type,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001473 bool same_dex_file,
1474 HInstruction** return_replacement) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001475 DCHECK(!(resolved_method->IsStatic() && receiver_type.IsValid()));
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001476 ScopedObjectAccess soa(Thread::Current());
1477 const DexFile::CodeItem* code_item = resolved_method->GetCodeItem();
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001478 const DexFile& callee_dex_file = *resolved_method->GetDexFile();
1479 uint32_t method_index = resolved_method->GetDexMethodIndex();
Calin Juravle2e768302015-07-28 14:41:11 +00001480 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Mathieu Chartier736b5602015-09-02 14:54:11 -07001481 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Nicolas Geoffrayf1aedb12016-07-28 03:49:14 +01001482 Handle<mirror::ClassLoader> class_loader(handles_->NewHandle(
1483 resolved_method->GetDeclaringClass()->GetClassLoader()));
1484
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001485 DexCompilationUnit dex_compilation_unit(
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001486 class_loader,
Nicolas Geoffray5b82d332016-02-18 14:22:32 +00001487 class_linker,
1488 callee_dex_file,
1489 code_item,
1490 resolved_method->GetDeclaringClass()->GetDexClassDefIndex(),
1491 method_index,
1492 resolved_method->GetAccessFlags(),
1493 /* verified_method */ nullptr,
1494 dex_cache);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001495
Calin Juravle3cd4fc82015-05-14 15:15:42 +01001496 bool requires_ctor_barrier = false;
1497
1498 if (dex_compilation_unit.IsConstructor()) {
1499 // If it's a super invocation and we already generate a barrier there's no need
1500 // to generate another one.
1501 // We identify super calls by looking at the "this" pointer. If its value is the
1502 // same as the local "this" pointer then we must have a super invocation.
1503 bool is_super_invocation = invoke_instruction->InputAt(0)->IsParameterValue()
1504 && invoke_instruction->InputAt(0)->AsParameterValue()->IsThis();
1505 if (is_super_invocation && graph_->ShouldGenerateConstructorBarrier()) {
1506 requires_ctor_barrier = false;
1507 } else {
1508 Thread* self = Thread::Current();
1509 requires_ctor_barrier = compiler_driver_->RequiresConstructorBarrier(self,
1510 dex_compilation_unit.GetDexFile(),
1511 dex_compilation_unit.GetClassDefIndex());
1512 }
1513 }
1514
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001515 InvokeType invoke_type = invoke_instruction->GetInvokeType();
Nicolas Geoffray35071052015-06-09 15:43:38 +01001516 if (invoke_type == kInterface) {
1517 // We have statically resolved the dispatch. To please the class linker
1518 // at runtime, we change this call as if it was a virtual call.
1519 invoke_type = kVirtual;
1520 }
David Brazdil3f523062016-02-29 16:53:33 +00001521
1522 const int32_t caller_instruction_counter = graph_->GetCurrentInstructionId();
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +00001523 HGraph* callee_graph = new (graph_->GetArena()) HGraph(
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001524 graph_->GetArena(),
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001525 callee_dex_file,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001526 method_index,
Calin Juravle3cd4fc82015-05-14 15:15:42 +01001527 requires_ctor_barrier,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001528 compiler_driver_->GetInstructionSet(),
Nicolas Geoffray35071052015-06-09 15:43:38 +01001529 invoke_type,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001530 graph_->IsDebuggable(),
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001531 /* osr */ false,
David Brazdil3f523062016-02-29 16:53:33 +00001532 caller_instruction_counter);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001533 callee_graph->SetArtMethod(resolved_method);
David Brazdil5e8b1372015-01-23 14:39:08 +00001534
Vladimir Marko438709f2017-02-23 18:56:13 +00001535 // When they are needed, allocate `inline_stats_` on the Arena instead
Roland Levillaina8013fd2016-04-04 15:34:31 +01001536 // of on the stack, as Clang might produce a stack frame too large
1537 // for this function, that would not fit the requirements of the
1538 // `-Wframe-larger-than` option.
Vladimir Marko438709f2017-02-23 18:56:13 +00001539 if (stats_ != nullptr) {
1540 // Reuse one object for all inline attempts from this caller to keep Arena memory usage low.
1541 if (inline_stats_ == nullptr) {
1542 void* storage = graph_->GetArena()->Alloc<OptimizingCompilerStats>(kArenaAllocMisc);
1543 inline_stats_ = new (storage) OptimizingCompilerStats;
1544 } else {
1545 inline_stats_->Reset();
1546 }
1547 }
David Brazdil5e8b1372015-01-23 14:39:08 +00001548 HGraphBuilder builder(callee_graph,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001549 &dex_compilation_unit,
1550 &outer_compilation_unit_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001551 resolved_method->GetDexFile(),
David Brazdil86ea7ee2016-02-16 09:26:07 +00001552 *code_item,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001553 compiler_driver_,
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00001554 codegen_,
Vladimir Marko438709f2017-02-23 18:56:13 +00001555 inline_stats_,
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001556 resolved_method->GetQuickenedInfo(class_linker->GetImagePointerSize()),
David Brazdildee58d62016-04-07 09:54:26 +00001557 dex_cache,
1558 handles_);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001559
David Brazdildee58d62016-04-07 09:54:26 +00001560 if (builder.BuildGraph() != kAnalysisSuccess) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001561 LOG_FAIL(kNotInlinedCannotBuild)
1562 << "Method " << callee_dex_file.PrettyMethod(method_index)
1563 << " could not be built, so cannot be inlined";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001564 return false;
1565 }
1566
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001567 if (!RegisterAllocator::CanAllocateRegistersFor(*callee_graph,
1568 compiler_driver_->GetInstructionSet())) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001569 LOG_FAIL(kNotInlinedRegisterAllocator)
1570 << "Method " << callee_dex_file.PrettyMethod(method_index)
1571 << " cannot be inlined because of the register allocator";
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001572 return false;
1573 }
1574
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001575 size_t parameter_index = 0;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001576 bool run_rtp = false;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001577 for (HInstructionIterator instructions(callee_graph->GetEntryBlock()->GetInstructions());
1578 !instructions.Done();
1579 instructions.Advance()) {
1580 HInstruction* current = instructions.Current();
1581 if (current->IsParameterValue()) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001582 HInstruction* argument = invoke_instruction->InputAt(parameter_index);
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001583 if (argument->IsNullConstant()) {
1584 current->ReplaceWith(callee_graph->GetNullConstant());
1585 } else if (argument->IsIntConstant()) {
1586 current->ReplaceWith(callee_graph->GetIntConstant(argument->AsIntConstant()->GetValue()));
1587 } else if (argument->IsLongConstant()) {
1588 current->ReplaceWith(callee_graph->GetLongConstant(argument->AsLongConstant()->GetValue()));
1589 } else if (argument->IsFloatConstant()) {
1590 current->ReplaceWith(
1591 callee_graph->GetFloatConstant(argument->AsFloatConstant()->GetValue()));
1592 } else if (argument->IsDoubleConstant()) {
1593 current->ReplaceWith(
1594 callee_graph->GetDoubleConstant(argument->AsDoubleConstant()->GetValue()));
1595 } else if (argument->GetType() == Primitive::kPrimNot) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001596 if (!resolved_method->IsStatic() && parameter_index == 0 && receiver_type.IsValid()) {
1597 run_rtp = true;
1598 current->SetReferenceTypeInfo(receiver_type);
1599 } else {
1600 current->SetReferenceTypeInfo(argument->GetReferenceTypeInfo());
1601 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001602 current->AsParameterValue()->SetCanBeNull(argument->CanBeNull());
1603 }
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001604 ++parameter_index;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001605 }
1606 }
1607
David Brazdil94ab38f2016-06-21 17:48:19 +01001608 // We have replaced formal arguments with actual arguments. If actual types
1609 // are more specific than the declared ones, run RTP again on the inner graph.
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001610 if (run_rtp || ArgumentTypesMoreSpecific(invoke_instruction, resolved_method)) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001611 ReferenceTypePropagation(callee_graph,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001612 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +01001613 dex_compilation_unit.GetDexCache(),
1614 handles_,
1615 /* is_first_run */ false).Run();
1616 }
1617
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001618 RunOptimizations(callee_graph, code_item, dex_compilation_unit);
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +00001619
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001620 HBasicBlock* exit_block = callee_graph->GetExitBlock();
1621 if (exit_block == nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001622 LOG_FAIL(kNotInlinedInfiniteLoop)
1623 << "Method " << callee_dex_file.PrettyMethod(method_index)
1624 << " could not be inlined because it has an infinite loop";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001625 return false;
1626 }
1627
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001628 bool has_one_return = false;
Vladimir Marko60584552015-09-03 13:35:12 +00001629 for (HBasicBlock* predecessor : exit_block->GetPredecessors()) {
1630 if (predecessor->GetLastInstruction()->IsThrow()) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001631 if (invoke_instruction->GetBlock()->IsTryBlock()) {
1632 // TODO(ngeoffray): Support adding HTryBoundary in Hgraph::InlineInto.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001633 LOG_FAIL(kNotInlinedTryCatch)
1634 << "Method " << callee_dex_file.PrettyMethod(method_index)
1635 << " could not be inlined because one branch always throws and"
1636 << " caller is in a try/catch block";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001637 return false;
1638 } else if (graph_->GetExitBlock() == nullptr) {
1639 // TODO(ngeoffray): Support adding HExit in the caller graph.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001640 LOG_FAIL(kNotInlinedInfiniteLoop)
1641 << "Method " << callee_dex_file.PrettyMethod(method_index)
1642 << " could not be inlined because one branch always throws and"
1643 << " caller does not have an exit block";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001644 return false;
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00001645 } else if (graph_->HasIrreducibleLoops()) {
1646 // TODO(ngeoffray): Support re-computing loop information to graphs with
1647 // irreducible loops?
1648 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1649 << " could not be inlined because one branch always throws and"
1650 << " caller has irreducible loops";
1651 return false;
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001652 }
1653 } else {
1654 has_one_return = true;
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001655 }
1656 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001657
1658 if (!has_one_return) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001659 LOG_FAIL(kNotInlinedAlwaysThrows)
1660 << "Method " << callee_dex_file.PrettyMethod(method_index)
1661 << " could not be inlined because it always throws";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001662 return false;
1663 }
1664
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001665 size_t number_of_instructions = 0;
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001666 // Skip the entry block, it does not contain instructions that prevent inlining.
1667 for (HBasicBlock* block : callee_graph->GetReversePostOrderSkipEntryBlock()) {
David Sehrc757dec2016-11-04 15:48:34 -07001668 if (block->IsLoopHeader()) {
1669 if (block->GetLoopInformation()->IsIrreducible()) {
1670 // Don't inline methods with irreducible loops, they could prevent some
1671 // optimizations to run.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001672 LOG_FAIL(kNotInlinedIrreducibleLoop)
1673 << "Method " << callee_dex_file.PrettyMethod(method_index)
1674 << " could not be inlined because it contains an irreducible loop";
David Sehrc757dec2016-11-04 15:48:34 -07001675 return false;
1676 }
1677 if (!block->GetLoopInformation()->HasExitEdge()) {
1678 // Don't inline methods with loops without exit, since they cause the
1679 // loop information to be computed incorrectly when updating after
1680 // inlining.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001681 LOG_FAIL(kNotInlinedLoopWithoutExit)
1682 << "Method " << callee_dex_file.PrettyMethod(method_index)
1683 << " could not be inlined because it contains a loop with no exit";
David Sehrc757dec2016-11-04 15:48:34 -07001684 return false;
1685 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001686 }
1687
1688 for (HInstructionIterator instr_it(block->GetInstructions());
1689 !instr_it.Done();
1690 instr_it.Advance()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001691 if (++number_of_instructions >= inlining_budget_) {
1692 LOG_FAIL(kNotInlinedInstructionBudget)
1693 << "Method " << callee_dex_file.PrettyMethod(method_index)
1694 << " is not inlined because the outer method has reached"
1695 << " its instruction budget limit.";
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001696 return false;
1697 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001698 HInstruction* current = instr_it.Current();
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001699 if (current->NeedsEnvironment() &&
1700 (total_number_of_dex_registers_ >= kMaximumNumberOfCumulatedDexRegisters)) {
1701 LOG_FAIL(kNotInlinedEnvironmentBudget)
1702 << "Method " << callee_dex_file.PrettyMethod(method_index)
1703 << " is not inlined because its caller has reached"
1704 << " its environment budget limit.";
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001705 return false;
1706 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001707
Nicolas Geoffrayfbdfa6d2017-02-03 10:43:13 +00001708 if (current->NeedsEnvironment() &&
1709 !CanEncodeInlinedMethodInStackMap(*caller_compilation_unit_.GetDexFile(),
1710 resolved_method)) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001711 LOG_FAIL(kNotInlinedStackMaps)
1712 << "Method " << callee_dex_file.PrettyMethod(method_index)
1713 << " could not be inlined because " << current->DebugName()
1714 << " needs an environment, is in a different dex file"
1715 << ", and cannot be encoded in the stack maps.";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001716 return false;
1717 }
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001718
Vladimir Markodc151b22015-10-15 18:02:30 +01001719 if (!same_dex_file && current->NeedsDexCacheOfDeclaringClass()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001720 LOG_FAIL(kNotInlinedDexCache)
1721 << "Method " << callee_dex_file.PrettyMethod(method_index)
1722 << " could not be inlined because " << current->DebugName()
1723 << " it is in a different dex file and requires access to the dex cache";
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001724 return false;
1725 }
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001726
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001727 if (current->IsUnresolvedStaticFieldGet() ||
1728 current->IsUnresolvedInstanceFieldGet() ||
1729 current->IsUnresolvedStaticFieldSet() ||
1730 current->IsUnresolvedInstanceFieldSet()) {
1731 // Entrypoint for unresolved fields does not handle inlined frames.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001732 LOG_FAIL(kNotInlinedUnresolvedEntrypoint)
1733 << "Method " << callee_dex_file.PrettyMethod(method_index)
1734 << " could not be inlined because it is using an unresolved"
1735 << " entrypoint";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001736 return false;
1737 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001738 }
1739 }
David Brazdil3f523062016-02-29 16:53:33 +00001740 DCHECK_EQ(caller_instruction_counter, graph_->GetCurrentInstructionId())
1741 << "No instructions can be added to the outer graph while inner graph is being built";
1742
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001743 // Inline the callee graph inside the caller graph.
David Brazdil3f523062016-02-29 16:53:33 +00001744 const int32_t callee_instruction_counter = callee_graph->GetCurrentInstructionId();
1745 graph_->SetCurrentInstructionId(callee_instruction_counter);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001746 *return_replacement = callee_graph->InlineInto(graph_, invoke_instruction);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001747 // Update our budget for other inlining attempts in `caller_graph`.
1748 total_number_of_instructions_ += number_of_instructions;
1749 UpdateInliningBudget();
David Brazdil3f523062016-02-29 16:53:33 +00001750
1751 DCHECK_EQ(callee_instruction_counter, callee_graph->GetCurrentInstructionId())
1752 << "No instructions can be added to the inner graph during inlining into the outer graph";
1753
Vladimir Marko438709f2017-02-23 18:56:13 +00001754 if (stats_ != nullptr) {
1755 DCHECK(inline_stats_ != nullptr);
1756 inline_stats_->AddTo(stats_);
1757 }
1758
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001759 return true;
1760}
Calin Juravle2e768302015-07-28 14:41:11 +00001761
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001762void HInliner::RunOptimizations(HGraph* callee_graph,
1763 const DexFile::CodeItem* code_item,
1764 const DexCompilationUnit& dex_compilation_unit) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001765 // Note: if the outermost_graph_ is being compiled OSR, we should not run any
1766 // optimization that could lead to a HDeoptimize. The following optimizations do not.
Vladimir Marko438709f2017-02-23 18:56:13 +00001767 HDeadCodeElimination dce(callee_graph, inline_stats_, "dead_code_elimination$inliner");
Andreas Gampeca620d72016-11-08 08:09:33 -08001768 HConstantFolding fold(callee_graph, "constant_folding$inliner");
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001769 HSharpening sharpening(callee_graph, codegen_, dex_compilation_unit, compiler_driver_, handles_);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001770 InstructionSimplifier simplify(callee_graph, codegen_, inline_stats_);
Vladimir Marko438709f2017-02-23 18:56:13 +00001771 IntrinsicsRecognizer intrinsics(callee_graph, inline_stats_);
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001772
1773 HOptimization* optimizations[] = {
1774 &intrinsics,
1775 &sharpening,
1776 &simplify,
1777 &fold,
1778 &dce,
1779 };
1780
1781 for (size_t i = 0; i < arraysize(optimizations); ++i) {
1782 HOptimization* optimization = optimizations[i];
1783 optimization->Run();
1784 }
1785
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001786 // Bail early for pathological cases on the environment (for example recursive calls,
1787 // or too large environment).
1788 if (total_number_of_dex_registers_ >= kMaximumNumberOfCumulatedDexRegisters) {
1789 LOG_NOTE() << "Calls in " << callee_graph->GetArtMethod()->PrettyMethod()
1790 << " will not be inlined because the outer method has reached"
1791 << " its environment budget limit.";
1792 return;
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001793 }
1794
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001795 // Bail early if we know we already are over the limit.
1796 size_t number_of_instructions = CountNumberOfInstructions(callee_graph);
1797 if (number_of_instructions > inlining_budget_) {
1798 LOG_NOTE() << "Calls in " << callee_graph->GetArtMethod()->PrettyMethod()
1799 << " will not be inlined because the outer method has reached"
1800 << " its instruction budget limit. " << number_of_instructions;
1801 return;
1802 }
1803
1804 HInliner inliner(callee_graph,
1805 outermost_graph_,
1806 codegen_,
1807 outer_compilation_unit_,
1808 dex_compilation_unit,
1809 compiler_driver_,
1810 handles_,
1811 inline_stats_,
1812 total_number_of_dex_registers_ + code_item->registers_size_,
1813 total_number_of_instructions_ + number_of_instructions,
1814 this,
1815 depth_ + 1);
1816 inliner.Run();
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001817}
1818
David Brazdil94ab38f2016-06-21 17:48:19 +01001819static bool IsReferenceTypeRefinement(ReferenceTypeInfo declared_rti,
1820 bool declared_can_be_null,
1821 HInstruction* actual_obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001822 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001823 if (declared_can_be_null && !actual_obj->CanBeNull()) {
1824 return true;
1825 }
1826
1827 ReferenceTypeInfo actual_rti = actual_obj->GetReferenceTypeInfo();
1828 return (actual_rti.IsExact() && !declared_rti.IsExact()) ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001829 declared_rti.IsStrictSupertypeOf(actual_rti);
David Brazdil94ab38f2016-06-21 17:48:19 +01001830}
1831
1832ReferenceTypeInfo HInliner::GetClassRTI(mirror::Class* klass) {
1833 return ReferenceTypePropagation::IsAdmissible(klass)
1834 ? ReferenceTypeInfo::Create(handles_->NewHandle(klass))
1835 : graph_->GetInexactObjectRti();
1836}
1837
1838bool HInliner::ArgumentTypesMoreSpecific(HInvoke* invoke_instruction, ArtMethod* resolved_method) {
1839 // If this is an instance call, test whether the type of the `this` argument
1840 // is more specific than the class which declares the method.
1841 if (!resolved_method->IsStatic()) {
1842 if (IsReferenceTypeRefinement(GetClassRTI(resolved_method->GetDeclaringClass()),
1843 /* declared_can_be_null */ false,
1844 invoke_instruction->InputAt(0u))) {
1845 return true;
1846 }
1847 }
1848
David Brazdil94ab38f2016-06-21 17:48:19 +01001849 // Iterate over the list of parameter types and test whether any of the
1850 // actual inputs has a more specific reference type than the type declared in
1851 // the signature.
1852 const DexFile::TypeList* param_list = resolved_method->GetParameterTypeList();
1853 for (size_t param_idx = 0,
1854 input_idx = resolved_method->IsStatic() ? 0 : 1,
1855 e = (param_list == nullptr ? 0 : param_list->Size());
1856 param_idx < e;
1857 ++param_idx, ++input_idx) {
1858 HInstruction* input = invoke_instruction->InputAt(input_idx);
1859 if (input->GetType() == Primitive::kPrimNot) {
Vladimir Marko942fd312017-01-16 20:52:19 +00001860 mirror::Class* param_cls = resolved_method->GetClassFromTypeIndex(
David Brazdil94ab38f2016-06-21 17:48:19 +01001861 param_list->GetTypeItem(param_idx).type_idx_,
Vladimir Marko942fd312017-01-16 20:52:19 +00001862 /* resolve */ false);
David Brazdil94ab38f2016-06-21 17:48:19 +01001863 if (IsReferenceTypeRefinement(GetClassRTI(param_cls),
1864 /* declared_can_be_null */ true,
1865 input)) {
1866 return true;
1867 }
1868 }
1869 }
1870
1871 return false;
1872}
1873
1874bool HInliner::ReturnTypeMoreSpecific(HInvoke* invoke_instruction,
1875 HInstruction* return_replacement) {
Alex Light68289a52015-12-15 17:30:30 -08001876 // Check the integrity of reference types and run another type propagation if needed.
David Brazdil4833f5a2015-12-16 10:37:39 +00001877 if (return_replacement != nullptr) {
1878 if (return_replacement->GetType() == Primitive::kPrimNot) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001879 // Test if the return type is a refinement of the declared return type.
1880 if (IsReferenceTypeRefinement(invoke_instruction->GetReferenceTypeInfo(),
1881 /* declared_can_be_null */ true,
1882 return_replacement)) {
1883 return true;
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001884 } else if (return_replacement->IsInstanceFieldGet()) {
1885 HInstanceFieldGet* field_get = return_replacement->AsInstanceFieldGet();
1886 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1887 if (field_get->GetFieldInfo().GetField() ==
1888 class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0)) {
1889 return true;
1890 }
David Brazdil94ab38f2016-06-21 17:48:19 +01001891 }
1892 } else if (return_replacement->IsInstanceOf()) {
1893 // Inlining InstanceOf into an If may put a tighter bound on reference types.
1894 return true;
1895 }
1896 }
1897
1898 return false;
1899}
1900
1901void HInliner::FixUpReturnReferenceType(ArtMethod* resolved_method,
1902 HInstruction* return_replacement) {
1903 if (return_replacement != nullptr) {
1904 if (return_replacement->GetType() == Primitive::kPrimNot) {
David Brazdil4833f5a2015-12-16 10:37:39 +00001905 if (!return_replacement->GetReferenceTypeInfo().IsValid()) {
1906 // Make sure that we have a valid type for the return. We may get an invalid one when
1907 // we inline invokes with multiple branches and create a Phi for the result.
1908 // TODO: we could be more precise by merging the phi inputs but that requires
1909 // some functionality from the reference type propagation.
1910 DCHECK(return_replacement->IsPhi());
Vladimir Marko942fd312017-01-16 20:52:19 +00001911 mirror::Class* cls = resolved_method->GetReturnType(false /* resolve */);
David Brazdil94ab38f2016-06-21 17:48:19 +01001912 return_replacement->SetReferenceTypeInfo(GetClassRTI(cls));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001913 }
Calin Juravlecdfed3d2015-10-26 14:05:01 +00001914 }
Calin Juravle2e768302015-07-28 14:41:11 +00001915 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001916}
1917
1918} // namespace art