1 /*
2 * Copyright (c) 2021-2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "inlining.h"
17 #include <cstddef>
18 #include "compiler_logger.h"
19 #include "compiler_options.h"
20 #include "events_gen.h"
21 #include "optimizer/ir/graph.h"
22 #include "optimizer/ir/basicblock.h"
23 #include "optimizer/ir_builder/ir_builder.h"
24 #include "optimizer/analysis/alias_analysis.h"
25 #include "optimizer/analysis/rpo.h"
26 #include "optimizer/analysis/dominators_tree.h"
27 #include "optimizer/optimizations/cleanup.h"
28 #include "optimizer/optimizations/branch_elimination.h"
29 #include "optimizer/optimizations/object_type_check_elimination.h"
30 #include "optimizer/analysis/object_type_propagation.h"
31 #include "optimizer/optimizations/optimize_string_concat.h"
32 #include "optimizer/optimizations/peepholes.h"
33 #include "optimizer/optimizations/simplify_string_builder.h"
34 #include "events/events.h"
35
36 namespace ark::compiler {
37 using MethodPtr = RuntimeInterface::MethodPtr;
38
39 // Explicitly instantiate both versions of CheckMethodCanBeInlined since they can be used in subclasses
40 template bool Inlining::CheckMethodCanBeInlined<false, true>(const CallInst *, InlineContext *);
41 template bool Inlining::CheckMethodCanBeInlined<true, true>(const CallInst *, InlineContext *);
42 template bool Inlining::CheckMethodCanBeInlined<false, false>(const CallInst *, InlineContext *);
43 template bool Inlining::CheckMethodCanBeInlined<true, false>(const CallInst *, InlineContext *);
44
CanReplaceWithCallStatic(Opcode opcode)45 inline bool CanReplaceWithCallStatic(Opcode opcode)
46 {
47 switch (opcode) {
48 case Opcode::CallResolvedVirtual:
49 case Opcode::CallVirtual:
50 return true;
51 default:
52 return false;
53 }
54 }
55
CalculateInstructionsCount(Graph * graph)56 size_t Inlining::CalculateInstructionsCount(Graph *graph)
57 {
58 size_t count = 0;
59 for (auto bb : *graph) {
60 if (bb == nullptr || bb->IsStartBlock() || bb->IsEndBlock()) {
61 continue;
62 }
63 for (auto inst : bb->Insts()) {
64 if (inst->IsSaveState() || inst->IsPhi()) {
65 continue;
66 }
67 switch (inst->GetOpcode()) {
68 case Opcode::Return:
69 case Opcode::ReturnI:
70 case Opcode::ReturnVoid:
71 break;
72 default:
73 count++;
74 }
75 }
76 }
77 return count;
78 }
79
Inlining(Graph * graph,uint32_t instructionsCount,uint32_t methodsInlined,const ArenaVector<RuntimeInterface::MethodPtr> * inlinedStack)80 Inlining::Inlining(Graph *graph, uint32_t instructionsCount, uint32_t methodsInlined,
81 const ArenaVector<RuntimeInterface::MethodPtr> *inlinedStack)
82 : Optimization(graph),
83 methodsInlined_(methodsInlined),
84 instructionsCount_(instructionsCount != 0 ? instructionsCount : CalculateInstructionsCount(graph)),
85 instructionsLimit_(g_options.GetCompilerInliningMaxInsts()),
86 returnBlocks_(graph->GetLocalAllocator()->Adapter()),
87 blacklist_(graph->GetLocalAllocator()->Adapter()),
88 inlinedStack_(graph->GetLocalAllocator()->Adapter()),
89 vregsCount_(graph->GetVRegsCount()),
90 cha_(graph->GetRuntime()->GetCha())
91 {
92 if (inlinedStack != nullptr) {
93 inlinedStack_.reserve(inlinedStack->size() + 1U);
94 inlinedStack_ = *inlinedStack;
95 } else {
96 inlinedStack_.reserve(1U);
97 }
98 inlinedStack_.push_back(graph->GetMethod());
99 }
100
IsInlineCachesEnabled() const101 bool Inlining::IsInlineCachesEnabled() const
102 {
103 return DoesArchSupportDeoptimization(GetGraph()->GetArch()) && !g_options.IsCompilerNoPicInlining();
104 }
105
106 #ifdef PANDA_EVENTS_ENABLED
EmitEvent(const Graph * graph,const CallInst * callInst,const InlineContext & ctx,events::InlineResult res)107 static void EmitEvent(const Graph *graph, const CallInst *callInst, const InlineContext &ctx, events::InlineResult res)
108 {
109 auto runtime = graph->GetRuntime();
110 events::InlineKind kind;
111 if (ctx.chaDevirtualize) {
112 kind = events::InlineKind::VIRTUAL_CHA;
113 } else if (CanReplaceWithCallStatic(callInst->GetOpcode()) || ctx.replaceToStatic) {
114 kind = events::InlineKind::VIRTUAL;
115 } else {
116 kind = events::InlineKind::STATIC;
117 }
118 EVENT_INLINE(runtime->GetMethodFullName(graph->GetMethod()),
119 ctx.method != nullptr ? runtime->GetMethodFullName(ctx.method) : "null", callInst->GetId(), kind, res);
120 }
121 #else
122 // NOLINTNEXTLINE(readability-named-parameter)
EmitEvent(const Graph *,const CallInst *,const InlineContext &,events::InlineResult)123 static void EmitEvent(const Graph *, const CallInst *, const InlineContext &, events::InlineResult) {}
124 #endif
125
RunImpl()126 bool Inlining::RunImpl()
127 {
128 GetGraph()->RunPass<LoopAnalyzer>();
129
130 auto blacklistNames = g_options.GetCompilerInliningBlacklist();
131 blacklist_.reserve(blacklistNames.size());
132
133 for (const auto &methodName : blacklistNames) {
134 blacklist_.insert(methodName);
135 }
136 return Do();
137 }
138
RunOptimizations() const139 void Inlining::RunOptimizations() const
140 {
141 if (GetGraph()->GetParentGraph() == nullptr && GetGraph()->RunPass<ObjectTypeCheckElimination>() &&
142 GetGraph()->RunPass<Peepholes>()) {
143 GetGraph()->RunPass<BranchElimination>();
144 }
145 }
146
Do()147 bool Inlining::Do()
148 {
149 bool inlined = false;
150 RunOptimizations();
151
152 ArenaVector<BasicBlock *> hotBlocks(GetGraph()->GetLocalAllocator()->Adapter());
153
154 hotBlocks = GetGraph()->GetVectorBlocks();
155 if (GetGraph()->IsAotMode()) {
156 std::stable_sort(hotBlocks.begin(), hotBlocks.end(), [](BasicBlock *a, BasicBlock *b) {
157 auto ad = (a == nullptr) ? 0 : a->GetLoop()->GetDepth();
158 auto bd = (b == nullptr) ? 0 : b->GetLoop()->GetDepth();
159 return ad > bd;
160 });
161 } else {
162 std::stable_sort(hotBlocks.begin(), hotBlocks.end(), [](BasicBlock *a, BasicBlock *b) {
163 auto ahtn = (a == nullptr) ? 0 : a->GetHotness();
164 auto bhtn = (b == nullptr) ? 0 : b->GetHotness();
165 return ahtn > bhtn;
166 });
167 }
168
169 LOG_INLINING(DEBUG) << "Process blocks (" << hotBlocks.size() << " blocks):";
170 auto lastId = hotBlocks.size();
171 for (size_t i = 0; i < lastId; i++) {
172 if (SkipBlock(hotBlocks[i])) {
173 LOG_INLINING(DEBUG) << "-skip (" << i << '/' << hotBlocks.size() << ")";
174 continue;
175 }
176
177 [[maybe_unused]] auto hotIdx = std::find(hotBlocks.begin(), hotBlocks.end(), hotBlocks[i]) - hotBlocks.begin();
178 [[maybe_unused]] auto bbId = hotBlocks[i]->GetId();
179 LOG_INLINING(DEBUG) << "-process BB" << bbId << " (" << i << '/' << hotBlocks.size() << "): htn_"
180 << hotBlocks[i]->GetHotness() << " (" << hotIdx << '/' << hotBlocks.size() << ")";
181
182 for (auto inst : hotBlocks[i]->InstsSafe()) {
183 if (GetGraph()->GetVectorBlocks()[inst->GetBasicBlock()->GetId()] == nullptr) {
184 break;
185 }
186
187 if (!IsInstSuitableForInline(inst)) {
188 continue;
189 }
190
191 inlined |= TryInline(static_cast<CallInst *>(inst));
192 }
193 }
194
195 #ifndef NDEBUG
196 GetGraph()->SetInliningComplete();
197 #endif // NDEBUG
198
199 return inlined;
200 }
201
IsInstSuitableForInline(Inst * inst) const202 bool Inlining::IsInstSuitableForInline(Inst *inst) const
203 {
204 if (!inst->IsCall()) {
205 return false;
206 }
207 auto callInst = static_cast<CallInst *>(inst);
208 ASSERT(!callInst->IsDynamicCall());
209 if (callInst->IsInlined() || callInst->IsLaunchCall()) {
210 return false;
211 }
212 if (callInst->IsUnresolved() || callInst->GetCallMethod() == nullptr) {
213 LOG_INLINING(DEBUG) << "Unknown method " << callInst->GetCallMethodId();
214 return false;
215 }
216 ASSERT(callInst->GetCallMethod() != nullptr);
217 return true;
218 }
219
InvalidateAnalyses()220 void Inlining::InvalidateAnalyses()
221 {
222 GetGraph()->InvalidateAnalysis<BoundsAnalysis>();
223 GetGraph()->InvalidateAnalysis<AliasAnalysis>();
224 GetGraph()->InvalidateAnalysis<LoopAnalyzer>();
225 GetGraph()->InvalidateAnalysis<ObjectTypePropagation>();
226 InvalidateBlocksOrderAnalyzes(GetGraph());
227 }
228
229 /**
230 * Get next Parameter instruction.
231 * NOTE(msherstennikov): this is temporary solution, need to find out better approach
232 * @param inst current param instruction
233 * @return next Parameter instruction, nullptr if there no more Parameter instructions
234 */
GetNextParam(Inst * inst)235 Inst *GetNextParam(Inst *inst)
236 {
237 for (auto nextInst = inst->GetNext(); nextInst != nullptr; nextInst = nextInst->GetNext()) {
238 if (nextInst->GetOpcode() == Opcode::Parameter) {
239 return nextInst;
240 }
241 }
242 return nullptr;
243 }
244
TryInline(CallInst * callInst)245 bool Inlining::TryInline(CallInst *callInst)
246 {
247 InlineContext ctx;
248 if (!ResolveTarget(callInst, &ctx)) {
249 if (IsInlineCachesEnabled()) {
250 return TryInlineWithInlineCaches(callInst);
251 }
252 return false;
253 }
254
255 ASSERT(!callInst->IsInlined());
256
257 LOG_INLINING(DEBUG) << "Try to inline(id=" << callInst->GetId() << (callInst->IsVirtualCall() ? ", virtual" : "")
258 << ", size=" << GetGraph()->GetRuntime()->GetMethodCodeSize(ctx.method) << ", vregs="
259 << GetGraph()->GetRuntime()->GetMethodArgumentsCount(ctx.method) +
260 GetGraph()->GetRuntime()->GetMethodRegistersCount(ctx.method) + 1
261 << (ctx.chaDevirtualize ? ", CHA" : "")
262 << "): " << GetGraph()->GetRuntime()->GetMethodFullName(ctx.method, true);
263
264 if (DoInline(callInst, &ctx)) {
265 if (IsIntrinsic(&ctx)) {
266 callInst->GetBasicBlock()->RemoveInst(callInst);
267 }
268 EmitEvent(GetGraph(), callInst, ctx, events::InlineResult::SUCCESS);
269 return true;
270 }
271 if (ctx.replaceToStatic && !ctx.chaDevirtualize) {
272 ASSERT(ctx.method != nullptr);
273 if (callInst->GetCallMethod() != ctx.method) {
274 // Replace method id only if the methods are different.
275 // Otherwise, leave the method id as is because:
276 // 1. In aot mode the new method id can refer to a method from a different file
277 // 2. In jit mode the method id does not matter
278 callInst->SetCallMethodId(GetGraph()->GetRuntime()->GetMethodId(ctx.method));
279 }
280 callInst->SetCallMethod(ctx.method);
281 if (callInst->GetOpcode() == Opcode::CallResolvedVirtual) {
282 // Drop the first argument - the resolved method
283 ASSERT(!callInst->GetInputs().empty());
284 for (size_t i = 0; i < callInst->GetInputsCount() - 1; i++) {
285 callInst->SetInput(i, callInst->GetInput(i + 1).GetInst());
286 }
287 callInst->RemoveInput(callInst->GetInputsCount() - 1);
288 ASSERT(!callInst->GetInputTypes()->empty());
289 callInst->GetInputTypes()->erase(callInst->GetInputTypes()->begin());
290 }
291 callInst->SetOpcode(Opcode::CallStatic);
292 EmitEvent(GetGraph(), callInst, ctx, events::InlineResult::DEVIRTUALIZED);
293 return true;
294 }
295
296 return false;
297 }
298
TryInlineWithInlineCaches(CallInst * callInst)299 bool Inlining::TryInlineWithInlineCaches(CallInst *callInst)
300 {
301 if (GetGraph()->IsAotMode()) {
302 // We don't support offline inline caches yet.
303 return false;
304 }
305 auto runtime = GetGraph()->GetRuntime();
306 auto pic = runtime->GetInlineCaches();
307 if (pic == nullptr) {
308 return false;
309 }
310
311 ArenaVector<RuntimeInterface::ClassPtr> receivers(GetGraph()->GetLocalAllocator()->Adapter());
312 auto callKind = pic->GetClasses(GetGraph()->GetMethod(), callInst->GetPc(), &receivers);
313 switch (callKind) {
314 case InlineCachesInterface::CallKind::MEGAMORPHIC:
315 EVENT_INLINE(runtime->GetMethodFullName(GetGraph()->GetMethod()), "-", callInst->GetId(),
316 events::InlineKind::VIRTUAL_POLYMORPHIC, events::InlineResult::FAIL_MEGAMORPHIC);
317 return false;
318 case InlineCachesInterface::CallKind::UNKNOWN:
319 return false;
320 case InlineCachesInterface::CallKind::MONOMORPHIC:
321 return DoInlineMonomorphic(callInst, receivers[0]);
322 case InlineCachesInterface::CallKind::POLYMORPHIC:
323 ASSERT(callKind == InlineCachesInterface::CallKind::POLYMORPHIC);
324 return DoInlinePolymorphic(callInst, &receivers);
325 default:
326 break;
327 }
328 return false;
329 }
330
DoInlineMonomorphic(CallInst * callInst,RuntimeInterface::ClassPtr receiver)331 bool Inlining::DoInlineMonomorphic(CallInst *callInst, RuntimeInterface::ClassPtr receiver)
332 {
333 auto runtime = GetGraph()->GetRuntime();
334 InlineContext ctx;
335 ctx.method = runtime->ResolveVirtualMethod(receiver, callInst->GetCallMethod());
336
337 auto callBb = callInst->GetBasicBlock();
338 auto saveState = callInst->GetSaveState();
339 auto objInst = callInst->GetObjectInst();
340
341 LOG_INLINING(DEBUG) << "Try to inline monomorphic(size=" << runtime->GetMethodCodeSize(ctx.method)
342 << "): " << GetMethodFullName(GetGraph(), ctx.method);
343
344 if (!DoInline(callInst, &ctx)) {
345 return false;
346 }
347
348 // Add type guard
349 auto getClsInst = GetGraph()->CreateInstGetInstanceClass(DataType::REFERENCE, callInst->GetPc(), objInst);
350 auto loadClsInst = GetGraph()->CreateInstLoadImmediate(DataType::REFERENCE, callInst->GetPc(), receiver);
351 auto cmpInst = GetGraph()->CreateInstCompare(DataType::BOOL, callInst->GetPc(), getClsInst, loadClsInst,
352 DataType::REFERENCE, ConditionCode::CC_NE);
353 auto deoptInst =
354 GetGraph()->CreateInstDeoptimizeIf(callInst->GetPc(), cmpInst, saveState, DeoptimizeType::INLINE_IC);
355 if (IsIntrinsic(&ctx)) {
356 callInst->InsertBefore(loadClsInst);
357 callInst->InsertBefore(getClsInst);
358 callInst->InsertBefore(cmpInst);
359 callInst->InsertBefore(deoptInst);
360 callInst->GetBasicBlock()->RemoveInst(callInst);
361 } else {
362 callBb->AppendInst(loadClsInst);
363 callBb->AppendInst(getClsInst);
364 callBb->AppendInst(cmpInst);
365 callBb->AppendInst(deoptInst);
366 }
367
368 EVENT_INLINE(runtime->GetMethodFullName(GetGraph()->GetMethod()), runtime->GetMethodFullName(ctx.method),
369 callInst->GetId(), events::InlineKind::VIRTUAL_MONOMORPHIC, events::InlineResult::SUCCESS);
370 return true;
371 }
372
CreateCompareClass(CallInst * callInst,Inst * getClsInst,RuntimeInterface::ClassPtr receiver,BasicBlock * callBb)373 void Inlining::CreateCompareClass(CallInst *callInst, Inst *getClsInst, RuntimeInterface::ClassPtr receiver,
374 BasicBlock *callBb)
375 {
376 auto loadClsInst = GetGraph()->CreateInstLoadImmediate(DataType::REFERENCE, callInst->GetPc(), receiver);
377 auto cmpInst = GetGraph()->CreateInstCompare(DataType::BOOL, callInst->GetPc(), loadClsInst, getClsInst,
378 DataType::REFERENCE, ConditionCode::CC_EQ);
379 auto ifInst = GetGraph()->CreateInstIfImm(DataType::BOOL, callInst->GetPc(), cmpInst, 0, DataType::BOOL,
380 ConditionCode::CC_NE);
381 callBb->AppendInst(loadClsInst);
382 callBb->AppendInst(cmpInst);
383 callBb->AppendInst(ifInst);
384 }
385
InsertDeoptimizeInst(CallInst * callInst,BasicBlock * callBb,DeoptimizeType deoptType)386 void Inlining::InsertDeoptimizeInst(CallInst *callInst, BasicBlock *callBb, DeoptimizeType deoptType)
387 {
388 // If last class compare returns false we need to deoptimize the method.
389 // So we construct instruction DeoptimizeIf and insert instead of IfImm inst.
390 auto ifInst = callBb->GetLastInst();
391 ASSERT(ifInst != nullptr && ifInst->GetOpcode() == Opcode::IfImm);
392 ASSERT(ifInst->CastToIfImm()->GetImm() == 0 && ifInst->CastToIfImm()->GetCc() == ConditionCode::CC_NE);
393
394 auto compareInst = ifInst->GetInput(0).GetInst()->CastToCompare();
395 ASSERT(compareInst != nullptr && compareInst->GetCc() == ConditionCode::CC_EQ);
396 compareInst->SetCc(ConditionCode::CC_NE);
397
398 auto deoptInst =
399 GetGraph()->CreateInstDeoptimizeIf(callInst->GetPc(), compareInst, callInst->GetSaveState(), deoptType);
400
401 callBb->RemoveInst(ifInst);
402 callBb->AppendInst(deoptInst);
403 }
404
InsertCallInst(CallInst * callInst,BasicBlock * callBb,BasicBlock * retBb,Inst * phiInst)405 void Inlining::InsertCallInst(CallInst *callInst, BasicBlock *callBb, BasicBlock *retBb, Inst *phiInst)
406 {
407 ASSERT(phiInst == nullptr || phiInst->GetBasicBlock() == retBb);
408 // Insert new BB
409 auto newCallBb = GetGraph()->CreateEmptyBlock(callBb);
410 callBb->GetLoop()->AppendBlock(newCallBb);
411 callBb->AddSucc(newCallBb);
412 newCallBb->AddSucc(retBb);
413
414 // Copy SaveState inst
415 auto ss = callInst->GetSaveState();
416 auto cloneSs = static_cast<SaveStateInst *>(ss->Clone(GetGraph()));
417 for (size_t inputIdx = 0; inputIdx < ss->GetInputsCount(); inputIdx++) {
418 cloneSs->AppendInput(ss->GetInput(inputIdx));
419 cloneSs->SetVirtualRegister(inputIdx, ss->GetVirtualRegister(inputIdx));
420 }
421 newCallBb->AppendInst(cloneSs);
422
423 // Copy Call inst
424 auto cloneCall = callInst->Clone(GetGraph());
425 for (auto input : callInst->GetInputs()) {
426 cloneCall->AppendInput(input.GetInst());
427 }
428 cloneCall->SetSaveState(cloneSs);
429 newCallBb->AppendInst(cloneCall);
430
431 // Set return value in phi inst
432 if (phiInst != nullptr) {
433 phiInst->AppendInput(cloneCall);
434 }
435 }
436
UpdateParameterDataflow(Graph * graphInl,Inst * callInst)437 void Inlining::UpdateParameterDataflow(Graph *graphInl, Inst *callInst)
438 {
439 // Replace inlined graph incoming dataflow edges
440 auto startBb = graphInl->GetStartBlock();
441 // Last input is SaveState
442 if (callInst->GetInputsCount() > 1) {
443 Inst *paramInst = *startBb->Insts().begin();
444 if (paramInst != nullptr && paramInst->GetOpcode() != Opcode::Parameter) {
445 paramInst = GetNextParam(paramInst);
446 }
447 while (paramInst != nullptr) {
448 ASSERT(paramInst);
449 auto argNum = paramInst->CastToParameter()->GetArgNumber();
450 if (callInst->GetOpcode() == Opcode::CallResolvedVirtual ||
451 callInst->GetOpcode() == Opcode::CallResolvedStatic) {
452 ASSERT(argNum != ParameterInst::DYNAMIC_NUM_ARGS);
453 argNum += 1; // skip method_reg
454 }
455 Inst *input = nullptr;
456 if (argNum < callInst->GetInputsCount() - 1) {
457 input = callInst->GetInput(argNum).GetInst();
458 } else if (argNum == ParameterInst::DYNAMIC_NUM_ARGS) {
459 input = GetGraph()->FindOrCreateConstant(callInst->GetInputsCount() - 1);
460 } else {
461 input = GetGraph()->FindOrCreateConstant(DataType::Any(coretypes::TaggedValue::VALUE_UNDEFINED));
462 }
463 paramInst->ReplaceUsers(input);
464 paramInst = GetNextParam(paramInst);
465 }
466 }
467 }
468
UpdateExternalParameterDataflow(Graph * graphInl,Inst * callInst)469 void UpdateExternalParameterDataflow(Graph *graphInl, Inst *callInst)
470 {
471 // Replace inlined graph incoming dataflow edges
472 auto startBb = graphInl->GetStartBlock();
473 // Last input is SaveState
474 if (callInst->GetInputsCount() <= 1) {
475 return;
476 }
477 Inst *paramInst = *startBb->Insts().begin();
478 if (paramInst != nullptr && paramInst->GetOpcode() != Opcode::Parameter) {
479 paramInst = GetNextParam(paramInst);
480 }
481 ArenaVector<Inst *> worklist {graphInl->GetLocalAllocator()->Adapter()};
482 while (paramInst != nullptr) {
483 auto argNum = paramInst->CastToParameter()->GetArgNumber();
484 ASSERT(argNum != ParameterInst::DYNAMIC_NUM_ARGS);
485 if (callInst->GetOpcode() == Opcode::CallResolvedVirtual ||
486 callInst->GetOpcode() == Opcode::CallResolvedStatic) {
487 argNum += 1; // skip method_reg
488 }
489 ASSERT(argNum < callInst->GetInputsCount() - 1);
490 auto input = callInst->GetInput(argNum);
491 for (auto &user : paramInst->GetUsers()) {
492 if (user.GetInst()->GetOpcode() == Opcode::NullCheck) {
493 user.GetInst()->ReplaceUsers(input.GetInst());
494 worklist.push_back(user.GetInst());
495 }
496 }
497 paramInst->ReplaceUsers(input.GetInst());
498 paramInst = GetNextParam(paramInst);
499 }
500 for (auto inst : worklist) {
501 auto ss = inst->GetInput(1).GetInst();
502 inst->RemoveInputs();
503 inst->GetBasicBlock()->EraseInst(inst);
504 ss->RemoveInputs();
505 ss->GetBasicBlock()->EraseInst(ss);
506 }
507 }
508
CloneVirtualCallInst(CallInst * call,Graph * graph)509 static inline CallInst *CloneVirtualCallInst(CallInst *call, Graph *graph)
510 {
511 if (call->GetOpcode() == Opcode::CallVirtual) {
512 return call->Clone(graph)->CastToCallVirtual();
513 }
514 if (call->GetOpcode() == Opcode::CallResolvedVirtual) {
515 return call->Clone(graph)->CastToCallResolvedVirtual();
516 }
517 UNREACHABLE();
518 }
519
DoInlinePolymorphic(CallInst * callInst,ArenaVector<RuntimeInterface::ClassPtr> * receivers)520 bool Inlining::DoInlinePolymorphic(CallInst *callInst, ArenaVector<RuntimeInterface::ClassPtr> *receivers)
521 {
522 LOG_INLINING(DEBUG) << "Try inline polymorphic call(" << receivers->size() << " receivers):";
523 LOG_INLINING(DEBUG) << " instruction: " << *callInst;
524
525 bool hasUnreachableBlocks = false;
526 bool hasRuntimeCalls = false;
527 auto runtime = GetGraph()->GetRuntime();
528 auto getClsInst = GetGraph()->CreateInstGetInstanceClass(DataType::REFERENCE, callInst->GetPc());
529 PhiInst *phiInst = nullptr;
530 BasicBlock *callBb = nullptr;
531 BasicBlock *callContBb = nullptr;
532 auto inlinedMethods = methodsInlined_;
533
534 // For each receiver we construct BB for CallVirtual inlined, and BB for Return.Inlined
535 // Inlined graph we inserts between the blocks:
536 // BEFORE:
537 // call_bb:
538 // call_inst
539 // succs [call_cont_bb]
540 // call_cont_bb:
541 //
542 // AFTER:
543 // call_bb:
544 // compare_classes
545 // succs [new_call_bb, call_inlined_block]
546 //
547 // call_inlined_block:
548 // call_inst.inlined
549 // succs [inlined_graph]
550 //
551 // inlined graph:
552 // succs [return_inlined_block]
553 //
554 // return_inlined_block:
555 // return.inlined
556 // succs [call_cont_bb]
557 //
558 // new_call_bb:
559 // succs [call_cont_bb]
560 //
561 // call_cont_bb
562 // phi(new_call_bb, return_inlined_block)
563 for (auto receiver : *receivers) {
564 InlineContext ctx;
565 ctx.method = runtime->ResolveVirtualMethod(receiver, callInst->GetCallMethod());
566 ASSERT(ctx.method != nullptr && !runtime->IsMethodAbstract(ctx.method));
567 LOG_INLINING(DEBUG) << "Inline receiver " << runtime->GetMethodFullName(ctx.method);
568 if (!CheckMethodCanBeInlined<true, false>(callInst, &ctx)) {
569 continue;
570 }
571 ASSERT(ctx.intrinsicId == RuntimeInterface::IntrinsicId::INVALID);
572
573 // Create Call.inlined
574 CallInst *newCallInst = CloneVirtualCallInst(callInst, GetGraph());
575 newCallInst->SetCallMethodId(runtime->GetMethodId(ctx.method));
576 newCallInst->SetCallMethod(ctx.method);
577 auto inlGraph = BuildGraph(&ctx, callInst, newCallInst);
578 if (inlGraph.graph == nullptr) {
579 continue;
580 }
581 vregsCount_ += inlGraph.graph->GetVRegsCount();
582 if (callBb == nullptr) {
583 // Split block by call instruction
584 callBb = callInst->GetBasicBlock();
585 callContBb = callBb->SplitBlockAfterInstruction(callInst, false);
586 callBb->AppendInst(getClsInst);
587 if (callInst->GetType() != DataType::VOID) {
588 phiInst = GetGraph()->CreateInstPhi(callInst->GetType(), callInst->GetPc());
589 phiInst->ReserveInputs(receivers->size() << 1U);
590 callContBb->AppendPhi(phiInst);
591 }
592 } else {
593 auto newCallBb = GetGraph()->CreateEmptyBlock(callBb);
594 callBb->GetLoop()->AppendBlock(newCallBb);
595 callBb->AddSucc(newCallBb);
596 callBb = newCallBb;
597 }
598
599 CreateCompareClass(callInst, getClsInst, receiver, callBb);
600
601 // Create call_inlined_block
602 auto callInlinedBlock = GetGraph()->CreateEmptyBlock(callBb);
603 callBb->GetLoop()->AppendBlock(callInlinedBlock);
604 callBb->AddSucc(callInlinedBlock);
605
606 // Insert Call.inlined in call_inlined_block
607 newCallInst->AppendInput(callInst->GetObjectInst());
608 newCallInst->AppendInput(callInst->GetSaveState());
609 newCallInst->SetInlined(true);
610 newCallInst->SetFlag(inst_flags::NO_DST);
611 // Set NO_DCE flag, since some call instructions might not have one after inlining
612 newCallInst->SetFlag(inst_flags::NO_DCE);
613 callInlinedBlock->PrependInst(newCallInst);
614
615 // Create return_inlined_block and inster PHI for non void functions
616 auto returnInlinedBlock = GetGraph()->CreateEmptyBlock(callBb);
617 callBb->GetLoop()->AppendBlock(returnInlinedBlock);
618 PhiInst *localPhiInst = nullptr;
619 if (callInst->GetType() != DataType::VOID) {
620 localPhiInst = GetGraph()->CreateInstPhi(callInst->GetType(), callInst->GetPc());
621 localPhiInst->ReserveInputs(receivers->size() << 1U);
622 returnInlinedBlock->AppendPhi(localPhiInst);
623 }
624
625 // Inlined graph between call_inlined_block and return_inlined_block
626 GetGraph()->SetMaxMarkerIdx(inlGraph.graph->GetCurrentMarkerIdx());
627 UpdateParameterDataflow(inlGraph.graph, callInst);
628 UpdateDataflow(inlGraph.graph, callInst, localPhiInst, phiInst);
629 MoveConstants(inlGraph.graph);
630 UpdateControlflow(inlGraph.graph, callInlinedBlock, returnInlinedBlock);
631
632 if (!returnInlinedBlock->GetPredsBlocks().empty()) {
633 if (inlGraph.hasRuntimeCalls) {
634 auto inlinedReturn =
635 GetGraph()->CreateInstReturnInlined(DataType::VOID, INVALID_PC, newCallInst->GetSaveState());
636 returnInlinedBlock->PrependInst(inlinedReturn);
637 }
638 if (callInst->GetType() != DataType::VOID) {
639 ASSERT(phiInst);
640 // clang-tidy think that phi_inst can be nullptr
641 phiInst->AppendInput(localPhiInst); // NOLINT
642 }
643 returnInlinedBlock->AddSucc(callContBb);
644 } else {
645 // We need remove return_inlined_block if inlined graph doesn't have Return inst(only Throw or Deoptimize)
646 hasUnreachableBlocks = true;
647 }
648
649 if (inlGraph.hasRuntimeCalls) {
650 hasRuntimeCalls = true;
651 } else {
652 newCallInst->GetBasicBlock()->RemoveInst(newCallInst);
653 }
654
655 GetGraph()->GetPassManager()->GetStatistics()->AddInlinedMethods(1);
656 EVENT_INLINE(runtime->GetMethodFullName(GetGraph()->GetMethod()), runtime->GetMethodFullName(ctx.method),
657 callInst->GetId(), events::InlineKind::VIRTUAL_POLYMORPHIC, events::InlineResult::SUCCESS);
658 LOG_INLINING(DEBUG) << "Successfully inlined: " << GetMethodFullName(GetGraph(), ctx.method);
659 methodsInlined_++;
660 }
661 if (callBb == nullptr) {
662 // Nothing was inlined
663 return false;
664 }
665 if (callContBb->GetPredsBlocks().empty() || hasUnreachableBlocks) {
666 GetGraph()->RemoveUnreachableBlocks();
667 }
668
669 getClsInst->SetInput(0, callInst->GetObjectInst());
670
671 if (methodsInlined_ - inlinedMethods == receivers->size()) {
672 InsertDeoptimizeInst(callInst, callBb);
673 } else {
674 InsertCallInst(callInst, callBb, callContBb, phiInst);
675 }
676 if (callInst->GetType() != DataType::VOID) {
677 callInst->ReplaceUsers(phiInst);
678 }
679
680 ProcessCallReturnInstructions(callInst, callContBb, hasRuntimeCalls);
681
682 if (hasRuntimeCalls) {
683 callInst->GetBasicBlock()->RemoveInst(callInst);
684 }
685
686 return true;
687 }
688
689 #ifndef NDEBUG
CheckExternalGraph(Graph * graph)690 void CheckExternalGraph(Graph *graph)
691 {
692 for (auto bb : graph->GetVectorBlocks()) {
693 if (bb != nullptr) {
694 for (auto inst : bb->AllInstsSafe()) {
695 ASSERT(!inst->RequireState());
696 }
697 }
698 }
699 }
700 #endif
701
GetNewDefAndCorrectDF(Inst * callInst,Inst * oldDef)702 Inst *Inlining::GetNewDefAndCorrectDF(Inst *callInst, Inst *oldDef)
703 {
704 if (oldDef->IsConst()) {
705 auto constant = oldDef->CastToConstant();
706 auto exisingConstant = GetGraph()->FindOrAddConstant(constant);
707 return exisingConstant;
708 }
709 if (oldDef->IsParameter()) {
710 auto argNum = oldDef->CastToParameter()->GetArgNumber();
711 ASSERT(argNum < callInst->GetInputsCount() - 1);
712 auto input = callInst->GetInput(argNum).GetInst();
713 return input;
714 }
715 ASSERT(oldDef->GetOpcode() == Opcode::NullPtr);
716 auto exisingNullptr = GetGraph()->GetOrCreateNullPtr();
717 return exisingNullptr;
718 }
719
TryInlineExternal(CallInst * callInst,InlineContext * ctx)720 bool Inlining::TryInlineExternal(CallInst *callInst, InlineContext *ctx)
721 {
722 if (TryInlineExternalAot(callInst, ctx)) {
723 return true;
724 }
725 // Skip external methods
726 EmitEvent(GetGraph(), callInst, *ctx, events::InlineResult::SKIP_EXTERNAL);
727 LOG_INLINING(DEBUG) << "We can't inline external method: " << GetMethodFullName(GetGraph(), ctx->method);
728 return false;
729 }
730
731 /*
732 * External methods could be inlined only if there are no instructions requiring state.
733 * The only exception are NullChecks that check parameters and used by LoadObject/StoreObject.
734 */
CheckExternalMethodInstructions(Graph * graph,CallInst * callInst)735 bool CheckExternalMethodInstructions(Graph *graph, CallInst *callInst)
736 {
737 ArenaUnorderedSet<Inst *> suspiciousInstructions(graph->GetLocalAllocator()->Adapter());
738 for (auto bb : graph->GetVectorBlocks()) {
739 if (bb == nullptr) {
740 continue;
741 }
742 for (auto inst : bb->InstsSafe()) {
743 bool isRtCall = inst->RequireState() || inst->IsRuntimeCall();
744 auto opcode = inst->GetOpcode();
745 if (isRtCall && opcode == Opcode::NullCheck) {
746 suspiciousInstructions.insert(inst);
747 } else if (isRtCall && opcode != Opcode::NullCheck) {
748 return false;
749 }
750 if (opcode != Opcode::LoadObject && opcode != Opcode::StoreObject) {
751 continue;
752 }
753 auto nc = inst->GetInput(0).GetInst();
754 if (nc->GetOpcode() == Opcode::NullCheck && nc->HasSingleUser()) {
755 suspiciousInstructions.erase(nc);
756 }
757 // If LoadObject/StoreObject first input (i.e. object to load data from / store data to)
758 // is a method parameter and corresponding call instruction's input is either NullCheck
759 // or NewObject then the NullCheck could be removed from external method's body because
760 // the parameter is known to be not null at the time load/store will be executed.
761 // If we can't prove that the input is not-null then NullCheck could not be eliminated
762 // and a method could not be inlined.
763 auto objInput = inst->GetDataFlowInput(0);
764 if (objInput->GetOpcode() != Opcode::Parameter) {
765 return false;
766 }
767 auto paramId = objInput->CastToParameter()->GetArgNumber() + callInst->GetObjectIndex();
768 if (callInst->GetInput(paramId).GetInst()->GetOpcode() != Opcode::NullCheck &&
769 callInst->GetDataFlowInput(paramId)->GetOpcode() != Opcode::NewObject) {
770 return false;
771 }
772 }
773 }
774 return suspiciousInstructions.empty();
775 }
776
777 /*
778 * We can only inline external methods that don't have runtime calls.
779 * The only exception from this rule are methods performing LoadObject/StoreObject
780 * to/from a parameter for which we can prove that it can't be null. In that case
781 * NullChecks preceding LoadObject/StoreObject are removed from inlined graph.
782 */
TryInlineExternalAot(CallInst * callInst,InlineContext * ctx)783 bool Inlining::TryInlineExternalAot(CallInst *callInst, InlineContext *ctx)
784 {
785 // We can't guarantee without cha that runtime will use this external file.
786 if (!GetGraph()->GetAotData()->GetUseCha()) {
787 return false;
788 }
789 IrBuilderExternalInliningAnalysis bytecodeAnalysis(GetGraph(), ctx->method);
790 if (!GetGraph()->RunPass(&bytecodeAnalysis)) {
791 EmitEvent(GetGraph(), callInst, *ctx, events::InlineResult::UNSUITABLE);
792 LOG_INLINING(DEBUG) << "We can't inline external method: " << GetMethodFullName(GetGraph(), ctx->method);
793 return false;
794 }
795 auto graphInl = GetGraph()->CreateChildGraph(ctx->method);
796 graphInl->SetCurrentInstructionId(GetGraph()->GetCurrentInstructionId());
797
798 auto stats = GetGraph()->GetPassManager()->GetStatistics();
799 auto savedPbcInstNum = stats->GetPbcInstNum();
800 if (!TryBuildGraph(*ctx, graphInl, callInst, nullptr)) {
801 stats->SetPbcInstNum(savedPbcInstNum);
802 return false;
803 }
804
805 graphInl->RunPass<Cleanup>();
806
807 // External method could be inlined only if there are no instructions requiring state
808 // because compiler saves method id into stack map's inline info and there is no way
809 // to distinguish id of an external method from id of some method from the same translation unit.
810 // Following check ensures that there are no instructions requiring state within parsed
811 // external method except NullChecks used by LoadObject/StoreObject that checks nullness
812 // of parameters that known to be non-null at the call time. In that case NullChecks
813 // will be eliminated and there will no instruction requiring state.
814 if (!CheckExternalMethodInstructions(graphInl, callInst)) {
815 stats->SetPbcInstNum(savedPbcInstNum);
816 return false;
817 }
818
819 vregsCount_ += graphInl->GetVRegsCount();
820
821 auto method = ctx->method;
822 auto runtime = GetGraph()->GetRuntime();
823 // Call instruction is already inlined, so change its call id to the resolved method.
824 callInst->SetCallMethodId(runtime->GetMethodId(method));
825 callInst->SetCallMethod(method);
826
827 auto callBb = callInst->GetBasicBlock();
828 auto callContBb = callBb->SplitBlockAfterInstruction(callInst, false);
829
830 GetGraph()->SetMaxMarkerIdx(graphInl->GetCurrentMarkerIdx());
831 // Adjust instruction id counter for parent graph, thereby avoid situation when two instructions have same id.
832 GetGraph()->SetCurrentInstructionId(graphInl->GetCurrentInstructionId());
833
834 UpdateExternalParameterDataflow(graphInl, callInst);
835 UpdateDataflow(graphInl, callInst, callContBb);
836 MoveConstants(graphInl);
837 UpdateControlflow(graphInl, callBb, callContBb);
838
839 if (callContBb->GetPredsBlocks().empty()) {
840 GetGraph()->RemoveUnreachableBlocks();
841 } else {
842 returnBlocks_.push_back(callContBb);
843 }
844
845 bool needBarriers = runtime->IsMemoryBarrierRequired(method);
846 ProcessCallReturnInstructions(callInst, callContBb, false, needBarriers);
847
848 #ifndef NDEBUG
849 CheckExternalGraph(graphInl);
850 #endif
851
852 LOG_INLINING(DEBUG) << "Successfully inlined external method: " << GetMethodFullName(GetGraph(), ctx->method);
853 methodsInlined_++;
854 return true;
855 }
856
DoInlineIntrinsic(CallInst * callInst,InlineContext * ctx)857 bool Inlining::DoInlineIntrinsic(CallInst *callInst, InlineContext *ctx)
858 {
859 auto intrinsicId = ctx->intrinsicId;
860 ASSERT(intrinsicId != RuntimeInterface::IntrinsicId::INVALID);
861 ASSERT(callInst != nullptr);
862 if (!EncodesBuiltin(GetGraph()->GetRuntime(), intrinsicId, GetGraph()->GetArch())) {
863 return false;
864 }
865 IntrinsicInst *inst = GetGraph()->CreateInstIntrinsic(callInst->GetType(), callInst->GetPc(), intrinsicId);
866 bool needSaveState = inst->RequireState();
867
868 size_t inputsCount = callInst->GetInputsCount() - (needSaveState ? 0 : 1);
869
870 inst->ReserveInputs(inputsCount);
871 inst->AllocateInputTypes(GetGraph()->GetAllocator(), inputsCount);
872
873 auto inputs = callInst->GetInputs();
874 for (size_t i = 0; i < inputsCount; ++i) {
875 inst->AppendInput(inputs[i].GetInst(), callInst->GetInputType(i));
876 }
877
878 auto method = ctx->method;
879 if (ctx->chaDevirtualize) {
880 InsertChaGuard(callInst);
881 GetCha()->AddDependency(method, GetGraph()->GetOutermostParentGraph()->GetMethod());
882 GetGraph()->GetOutermostParentGraph()->AddSingleImplementationMethod(method);
883 }
884
885 callInst->InsertAfter(inst);
886 callInst->ReplaceUsers(inst);
887 LOG_INLINING(DEBUG) << "The method: " << GetMethodFullName(GetGraph(), method) << "replaced to the intrinsic"
888 << GetIntrinsicName(intrinsicId);
889
890 return true;
891 }
892
DoInlineMethod(CallInst * callInst,InlineContext * ctx)893 bool Inlining::DoInlineMethod(CallInst *callInst, InlineContext *ctx)
894 {
895 ASSERT(ctx->intrinsicId == RuntimeInterface::IntrinsicId::INVALID);
896 auto method = ctx->method;
897
898 auto runtime = GetGraph()->GetRuntime();
899
900 if (resolveWoInline_) {
901 // Return, don't inline anything
902 // At this point we:
903 // 1. Gave a chance to inline external method
904 // 2. Set replace_to_static to true where possible
905 return false;
906 }
907
908 ASSERT(!runtime->IsMethodAbstract(method));
909
910 // Split block by call instruction
911 auto callBb = callInst->GetBasicBlock();
912 // NOTE (a.popov) Support inlining to the catch blocks
913 if (callBb->IsCatch()) {
914 return false;
915 }
916
917 auto graphInl = BuildGraph(ctx, callInst);
918 if (graphInl.graph == nullptr) {
919 return false;
920 }
921
922 vregsCount_ += graphInl.graph->GetVRegsCount();
923
924 // Call instruction is already inlined, so change its call id to the resolved method.
925 callInst->SetCallMethodId(runtime->GetMethodId(method));
926 callInst->SetCallMethod(method);
927
928 auto callContBb = callBb->SplitBlockAfterInstruction(callInst, false);
929
930 GetGraph()->SetMaxMarkerIdx(graphInl.graph->GetCurrentMarkerIdx());
931 UpdateParameterDataflow(graphInl.graph, callInst);
932 UpdateDataflow(graphInl.graph, callInst, callContBb);
933
934 MoveConstants(graphInl.graph);
935
936 UpdateControlflow(graphInl.graph, callBb, callContBb);
937
938 if (callContBb->GetPredsBlocks().empty()) {
939 GetGraph()->RemoveUnreachableBlocks();
940 } else {
941 returnBlocks_.push_back(callContBb);
942 }
943
944 if (ctx->chaDevirtualize) {
945 InsertChaGuard(callInst);
946 GetCha()->AddDependency(method, GetGraph()->GetOutermostParentGraph()->GetMethod());
947 GetGraph()->GetOutermostParentGraph()->AddSingleImplementationMethod(method);
948 }
949
950 bool needBarriers = runtime->IsMemoryBarrierRequired(method);
951 ProcessCallReturnInstructions(callInst, callContBb, graphInl.hasRuntimeCalls, needBarriers);
952
953 LOG_INLINING(DEBUG) << "Successfully inlined: " << GetMethodFullName(GetGraph(), method);
954 GetGraph()->GetPassManager()->GetStatistics()->AddInlinedMethods(1);
955 methodsInlined_++;
956
957 return true;
958 }
959
DoInline(CallInst * callInst,InlineContext * ctx)960 bool Inlining::DoInline(CallInst *callInst, InlineContext *ctx)
961 {
962 ASSERT(!callInst->IsInlined());
963
964 auto method = ctx->method;
965
966 auto runtime = GetGraph()->GetRuntime();
967
968 if (!CheckMethodCanBeInlined<false, true>(callInst, ctx)) {
969 return false;
970 }
971 if (runtime->IsMethodExternal(GetGraph()->GetMethod(), method) && !IsIntrinsic(ctx)) {
972 if (!g_options.IsCompilerInlineExternalMethods()) {
973 // Skip external methods
974 EmitEvent(GetGraph(), callInst, *ctx, events::InlineResult::SKIP_EXTERNAL);
975 LOG_INLINING(DEBUG) << "We can't inline external method: " << GetMethodFullName(GetGraph(), ctx->method);
976 return false;
977 }
978 if (GetGraph()->IsAotMode()) {
979 return TryInlineExternal(callInst, ctx);
980 }
981 }
982
983 if (IsIntrinsic(ctx)) {
984 return DoInlineIntrinsic(callInst, ctx);
985 }
986 return DoInlineMethod(callInst, ctx);
987 }
988
ProcessCallReturnInstructions(CallInst * callInst,BasicBlock * callContBb,bool hasRuntimeCalls,bool needBarriers)989 void Inlining::ProcessCallReturnInstructions(CallInst *callInst, BasicBlock *callContBb, bool hasRuntimeCalls,
990 bool needBarriers)
991 {
992 if (hasRuntimeCalls || needBarriers) {
993 // In case if inlined graph contains call to runtime we need to preserve call instruction with special `Inlined`
994 // flag and create new `ReturnInlined` instruction, hereby codegen can properly handle method frames.
995 callInst->SetInlined(true);
996 callInst->SetFlag(inst_flags::NO_DST);
997 // Set NO_DCE flag, since some call instructions might not have one after inlining
998 callInst->SetFlag(inst_flags::NO_DCE);
999 // Remove callInst's all inputs except SaveState and NullCheck(if exist)
1000 // Do not remove function (first) input for dynamic calls
1001 auto saveState = callInst->GetSaveState();
1002 ASSERT(saveState->GetOpcode() == Opcode::SaveState);
1003 if (callInst->GetOpcode() != Opcode::CallDynamic) {
1004 auto nullcheckInst = callInst->GetObjectInst();
1005 callInst->RemoveInputs();
1006 if (nullcheckInst->GetOpcode() == Opcode::NullCheck) {
1007 callInst->AppendInput(nullcheckInst);
1008 }
1009 } else {
1010 auto func = callInst->GetInput(0).GetInst();
1011 callInst->RemoveInputs();
1012 callInst->AppendInput(func);
1013 }
1014 callInst->AppendInput(saveState);
1015 callInst->SetType(DataType::VOID);
1016 for (auto bb : returnBlocks_) {
1017 auto inlinedReturn =
1018 GetGraph()->CreateInstReturnInlined(DataType::VOID, INVALID_PC, callInst->GetSaveState());
1019 if (bb != callContBb && (bb->IsEndWithThrowOrDeoptimize() ||
1020 (bb->IsEmpty() && bb->GetPredsBlocks()[0]->IsEndWithThrowOrDeoptimize()))) {
1021 auto lastInst = !bb->IsEmpty() ? bb->GetLastInst() : bb->GetPredsBlocks()[0]->GetLastInst();
1022 lastInst->InsertBefore(inlinedReturn);
1023 inlinedReturn->SetExtendedLiveness();
1024 } else {
1025 bb->PrependInst(inlinedReturn);
1026 }
1027 if (needBarriers) {
1028 inlinedReturn->SetFlag(inst_flags::MEM_BARRIER);
1029 }
1030 }
1031 } else {
1032 // Otherwise we remove call instruction
1033 auto saveState = callInst->GetSaveState();
1034 // Remove SaveState if it has only Call instruction in the users
1035 if (saveState->GetUsers().Front().GetNext() == nullptr) {
1036 saveState->GetBasicBlock()->RemoveInst(saveState);
1037 }
1038 callInst->GetBasicBlock()->RemoveInst(callInst);
1039 }
1040 returnBlocks_.clear();
1041 }
1042
CheckBytecode(CallInst * callInst,const InlineContext & ctx,bool * calleeCallRuntime)1043 bool Inlining::CheckBytecode(CallInst *callInst, const InlineContext &ctx, bool *calleeCallRuntime)
1044 {
1045 auto vregsNum = GetGraph()->GetRuntime()->GetMethodArgumentsCount(ctx.method) +
1046 GetGraph()->GetRuntime()->GetMethodRegistersCount(ctx.method) + 1;
1047 if ((vregsCount_ + vregsNum) >= g_options.GetCompilerMaxVregsNum()) {
1048 EmitEvent(GetGraph(), callInst, ctx, events::InlineResult::LIMIT);
1049 LOG_INLINING(DEBUG) << "Reached vregs limit: current=" << vregsCount_ << ", inlined=" << vregsNum;
1050 return false;
1051 }
1052 IrBuilderInliningAnalysis bytecodeAnalysis(GetGraph(), ctx.method);
1053 if (!GetGraph()->RunPass(&bytecodeAnalysis)) {
1054 EmitEvent(GetGraph(), callInst, ctx, events::InlineResult::UNSUITABLE);
1055 LOG_INLINING(DEBUG) << "Method contains unsuitable bytecode";
1056 return false;
1057 }
1058
1059 if (bytecodeAnalysis.HasRuntimeCalls() && g_options.IsCompilerInlineSimpleOnly()) {
1060 EmitEvent(GetGraph(), callInst, ctx, events::InlineResult::UNSUITABLE);
1061 return false;
1062 }
1063 if (calleeCallRuntime != nullptr) {
1064 *calleeCallRuntime = bytecodeAnalysis.HasRuntimeCalls();
1065 }
1066 return true;
1067 }
1068
TryBuildGraph(const InlineContext & ctx,Graph * graphInl,CallInst * callInst,CallInst * polyCallInst)1069 bool Inlining::TryBuildGraph(const InlineContext &ctx, Graph *graphInl, CallInst *callInst, CallInst *polyCallInst)
1070 {
1071 if (!graphInl->RunPass<IrBuilder>(ctx.method, polyCallInst != nullptr ? polyCallInst : callInst,
1072 GetCurrentDepth() + 1)) {
1073 EmitEvent(GetGraph(), callInst, ctx, events::InlineResult::FAIL);
1074 LOG_INLINING(WARNING) << "Graph building failed";
1075 return false;
1076 }
1077
1078 if (graphInl->HasInfiniteLoop()) {
1079 EmitEvent(GetGraph(), callInst, ctx, events::InlineResult::INF_LOOP);
1080 COMPILER_LOG(INFO, INLINING) << "Inlining of the methods with infinite loop is not supported";
1081 return false;
1082 }
1083
1084 if (!g_options.IsCompilerInliningSkipAlwaysThrowMethods()) {
1085 return true;
1086 }
1087
1088 bool alwaysThrow = true;
1089 // check that end block could be reached only through throw-blocks
1090 for (auto pred : graphInl->GetEndBlock()->GetPredsBlocks()) {
1091 auto returnInst = pred->GetLastInst();
1092 if (returnInst == nullptr) {
1093 ASSERT(pred->IsTryEnd());
1094 ASSERT(pred->GetPredsBlocks().size() == 1);
1095 pred = pred->GetPredBlockByIndex(0);
1096 }
1097 if (!pred->IsEndWithThrowOrDeoptimize()) {
1098 alwaysThrow = false;
1099 break;
1100 }
1101 }
1102 if (!alwaysThrow) {
1103 return true;
1104 }
1105 EmitEvent(GetGraph(), callInst, ctx, events::InlineResult::UNSUITABLE);
1106 LOG_INLINING(DEBUG) << "Method always throw an expection, skip inlining: "
1107 << GetMethodFullName(GetGraph(), ctx.method);
1108 return false;
1109 }
1110
RemoveDeadSafePoints(Graph * graphInl)1111 void RemoveDeadSafePoints(Graph *graphInl)
1112 {
1113 for (auto bb : *graphInl) {
1114 if (bb == nullptr || bb->IsStartBlock() || bb->IsEndBlock()) {
1115 continue;
1116 }
1117 for (auto inst : bb->InstsSafe()) {
1118 if (!inst->IsSaveState()) {
1119 continue;
1120 }
1121 ASSERT(inst->GetOpcode() == Opcode::SafePoint || inst->GetOpcode() == Opcode::SaveStateDeoptimize);
1122 ASSERT(inst->GetUsers().Empty());
1123 bb->RemoveInst(inst);
1124 }
1125 }
1126 }
1127
CheckLoops(bool * calleeCallRuntime,Graph * graphInl)1128 bool Inlining::CheckLoops(bool *calleeCallRuntime, Graph *graphInl)
1129 {
1130 // Check that inlined graph hasn't loops
1131 graphInl->RunPass<LoopAnalyzer>();
1132 if (graphInl->HasLoop()) {
1133 if (g_options.IsCompilerInlineSimpleOnly()) {
1134 LOG_INLINING(INFO) << "Inlining of the methods with loops is disabled";
1135 return false;
1136 }
1137 *calleeCallRuntime = true;
1138 } else if (!*calleeCallRuntime) {
1139 RemoveDeadSafePoints(graphInl);
1140 }
1141 return true;
1142 }
1143
1144 /* static */
PropagateObjectInfo(Graph * graphInl,CallInst * callInst)1145 void Inlining::PropagateObjectInfo(Graph *graphInl, CallInst *callInst)
1146 {
1147 // Propagate object type information to the parameters of the inlined graph
1148 auto index = callInst->GetObjectIndex();
1149 // NOLINTNEXTLINE(readability-static-accessed-through-instance)
1150 for (auto paramInst : graphInl->GetParameters()) {
1151 auto inputInst = callInst->GetDataFlowInput(index);
1152 paramInst->SetObjectTypeInfo(inputInst->GetObjectTypeInfo());
1153 index++;
1154 }
1155 }
1156
BuildGraph(InlineContext * ctx,CallInst * callInst,CallInst * polyCallInst)1157 InlinedGraph Inlining::BuildGraph(InlineContext *ctx, CallInst *callInst, CallInst *polyCallInst)
1158 {
1159 bool calleeCallRuntime = false;
1160 if (!CheckBytecode(callInst, *ctx, &calleeCallRuntime)) {
1161 return InlinedGraph();
1162 }
1163
1164 auto graphInl = GetGraph()->CreateChildGraph(ctx->method);
1165
1166 // Propagate instruction id counter to inlined graph, thereby avoid instructions id duplication
1167 graphInl->SetCurrentInstructionId(GetGraph()->GetCurrentInstructionId());
1168
1169 auto stats = GetGraph()->GetPassManager()->GetStatistics();
1170 auto savedPbcInstNum = stats->GetPbcInstNum();
1171 if (!TryBuildGraph(*ctx, graphInl, callInst, polyCallInst)) {
1172 stats->SetPbcInstNum(savedPbcInstNum);
1173 return InlinedGraph();
1174 }
1175
1176 PropagateObjectInfo(graphInl, callInst);
1177
1178 // Run basic optimizations
1179 graphInl->RunPass<Cleanup>(false);
1180 auto peepholeApplied = graphInl->RunPass<Peepholes>();
1181 auto objectTypeApplied = graphInl->RunPass<ObjectTypeCheckElimination>();
1182 if (peepholeApplied || objectTypeApplied) {
1183 graphInl->RunPass<BranchElimination>();
1184 graphInl->RunPass<Cleanup>();
1185 }
1186 graphInl->RunPass<OptimizeStringConcat>();
1187 graphInl->RunPass<SimplifyStringBuilder>();
1188
1189 auto inlinedInstsCount = CalculateInstructionsCount(graphInl);
1190 LOG_INLINING(DEBUG) << "Actual insts-bc ratio: (" << inlinedInstsCount << " insts) / ("
1191 << GetGraph()->GetRuntime()->GetMethodCodeSize(ctx->method) << ") = "
1192 << (double)inlinedInstsCount / GetGraph()->GetRuntime()->GetMethodCodeSize(ctx->method);
1193
1194 graphInl->RunPass<Inlining>(instructionsCount_ + inlinedInstsCount, methodsInlined_ + 1, &inlinedStack_);
1195
1196 instructionsCount_ += CalculateInstructionsCount(graphInl);
1197
1198 GetGraph()->SetMaxMarkerIdx(graphInl->GetCurrentMarkerIdx());
1199
1200 // Adjust instruction id counter for parent graph, thereby avoid situation when two instructions have same id.
1201 GetGraph()->SetCurrentInstructionId(graphInl->GetCurrentInstructionId());
1202
1203 if (ctx->chaDevirtualize && !GetCha()->IsSingleImplementation(ctx->method)) {
1204 EmitEvent(GetGraph(), callInst, *ctx, events::InlineResult::LOST_SINGLE_IMPL);
1205 LOG_INLINING(WARNING) << "Method lost single implementation property while we build IR for it";
1206 stats->SetPbcInstNum(savedPbcInstNum);
1207 return InlinedGraph();
1208 }
1209
1210 if (!CheckLoops(&calleeCallRuntime, graphInl)) {
1211 stats->SetPbcInstNum(savedPbcInstNum);
1212 return InlinedGraph();
1213 }
1214 return {graphInl, calleeCallRuntime};
1215 }
1216
1217 template <bool CHECK_EXTERNAL>
CheckMethodSize(const CallInst * callInst,InlineContext * ctx)1218 bool Inlining::CheckMethodSize(const CallInst *callInst, InlineContext *ctx)
1219 {
1220 size_t methodSize = GetGraph()->GetRuntime()->GetMethodCodeSize(ctx->method);
1221 size_t expectedInlinedInstsCount = g_options.GetCompilerInliningInstsBcRatio() * methodSize;
1222 bool methodIsTooBig = (expectedInlinedInstsCount + instructionsCount_) > instructionsLimit_;
1223 methodIsTooBig |= methodSize >= g_options.GetCompilerInliningMaxBcSize();
1224 if (methodIsTooBig) {
1225 if (methodSize <= g_options.GetCompilerInliningAlwaysInlineBcSize()) {
1226 methodIsTooBig = false;
1227 EmitEvent(GetGraph(), callInst, *ctx, events::InlineResult::IGNORE_LIMIT);
1228 LOG_INLINING(DEBUG) << "Ignore instructions limit: ";
1229 } else {
1230 EmitEvent(GetGraph(), callInst, *ctx, events::InlineResult::LIMIT);
1231 LOG_INLINING(DEBUG) << "Method is too big (d_" << inlinedStack_.size() << "):";
1232 }
1233 LOG_INLINING(DEBUG) << "instructions_count_ = " << instructionsCount_
1234 << ", expected_inlined_insts_count = " << expectedInlinedInstsCount
1235 << ", instructions_limit_ = " << instructionsLimit_
1236 << ", (method = " << GetMethodFullName(GetGraph(), ctx->method) << ")";
1237 }
1238
1239 if (methodIsTooBig || resolveWoInline_) {
1240 return CheckTooBigMethodCanBeInlined<CHECK_EXTERNAL>(callInst, ctx, methodIsTooBig);
1241 }
1242 return true;
1243 }
1244
1245 template <bool CHECK_EXTERNAL>
CheckTooBigMethodCanBeInlined(const CallInst * callInst,InlineContext * ctx,bool methodIsTooBig)1246 bool Inlining::CheckTooBigMethodCanBeInlined(const CallInst *callInst, InlineContext *ctx, bool methodIsTooBig)
1247 {
1248 ctx->replaceToStatic = CanReplaceWithCallStatic(callInst->GetOpcode());
1249 if constexpr (!CHECK_EXTERNAL) {
1250 if (GetGraph()->GetRuntime()->IsMethodExternal(GetGraph()->GetMethod(), ctx->method)) {
1251 // Do not replace to call static if --compiler-inline-external-methods=false
1252 ctx->replaceToStatic &= g_options.IsCompilerInlineExternalMethods();
1253 ASSERT(ctx->method != nullptr);
1254 // Allow to replace CallVirtual with CallStatic if the resolved method is same as the called method
1255 // In AOT mode the resolved method id can be different from the method id in the callInst,
1256 // but we'll keep the method id from the callInst because the resolved method id can be not correct
1257 // for aot compiled method
1258 ctx->replaceToStatic &= ctx->method == callInst->GetCallMethod()
1259 // Or if it's not aot mode. That is, just replace in other modes
1260 || !GetGraph()->IsAotMode();
1261 }
1262 }
1263 if (methodIsTooBig) {
1264 return false;
1265 }
1266 ASSERT(resolveWoInline_);
1267 // Continue and return true to give a change to TryInlineExternalAot
1268 return true;
1269 }
1270
CheckDepthLimit(InlineContext * ctx)1271 bool Inlining::CheckDepthLimit(InlineContext *ctx)
1272 {
1273 size_t recInlinedCount = std::count(inlinedStack_.begin(), inlinedStack_.end(), ctx->method);
1274 if ((recInlinedCount >= g_options.GetCompilerInliningRecursiveCallsLimit()) ||
1275 (inlinedStack_.size() >= MAX_CALL_DEPTH)) {
1276 LOG_INLINING(DEBUG) << "Recursive-calls-depth limit reached, method: '"
1277 << GetMethodFullName(GetGraph(), ctx->method) << "', depth: " << recInlinedCount;
1278 return false;
1279 }
1280 bool isDepthLimitIgnored = GetCurrentDepth() >= g_options.GetCompilerInliningMaxDepth();
1281 bool isSmallMethod =
1282 GetGraph()->GetRuntime()->GetMethodCodeSize(ctx->method) <= g_options.GetCompilerInliningAlwaysInlineBcSize();
1283 if (isDepthLimitIgnored && !isSmallMethod) {
1284 LOG_INLINING(DEBUG) << "Small-method-depth limit reached, method: '"
1285 << GetMethodFullName(GetGraph(), ctx->method)
1286 << "', size: " << GetGraph()->GetRuntime()->GetMethodCodeSize(ctx->method);
1287 return false;
1288 }
1289 return true;
1290 }
1291
1292 template <bool CHECK_EXTERNAL, bool CHECK_INTRINSICS>
CheckMethodCanBeInlined(const CallInst * callInst,InlineContext * ctx)1293 bool Inlining::CheckMethodCanBeInlined(const CallInst *callInst, InlineContext *ctx)
1294 {
1295 if (ctx->method == nullptr) {
1296 return false;
1297 }
1298
1299 if (!CheckDepthLimit(ctx)) {
1300 return false;
1301 }
1302
1303 if constexpr (CHECK_EXTERNAL) {
1304 ASSERT(!GetGraph()->IsAotMode());
1305 if (!g_options.IsCompilerInlineExternalMethods() &&
1306 GetGraph()->GetRuntime()->IsMethodExternal(GetGraph()->GetMethod(), ctx->method)) {
1307 // Skip external methods
1308 EmitEvent(GetGraph(), callInst, *ctx, events::InlineResult::SKIP_EXTERNAL);
1309 LOG_INLINING(DEBUG) << "We can't inline external method: " << GetMethodFullName(GetGraph(), ctx->method);
1310 return false;
1311 }
1312 }
1313
1314 if (!blacklist_.empty()) {
1315 std::string methodName = GetGraph()->GetRuntime()->GetMethodFullName(ctx->method);
1316 if (blacklist_.find(methodName) != blacklist_.end()) {
1317 EmitEvent(GetGraph(), callInst, *ctx, events::InlineResult::NOINLINE);
1318 LOG_INLINING(DEBUG) << "Method is in the blacklist: " << GetMethodFullName(GetGraph(), ctx->method);
1319 return false;
1320 }
1321 }
1322
1323 if (!GetGraph()->GetRuntime()->IsMethodCanBeInlined(ctx->method)) {
1324 if constexpr (CHECK_INTRINSICS) {
1325 if (GetGraph()->GetRuntime()->IsMethodIntrinsic(ctx->method)) {
1326 ctx->intrinsicId = GetGraph()->GetRuntime()->GetIntrinsicId(ctx->method);
1327 return true;
1328 }
1329 }
1330 EmitEvent(GetGraph(), callInst, *ctx, events::InlineResult::UNSUITABLE);
1331 return false;
1332 }
1333
1334 if (GetGraph()->GetRuntime()->GetMethodName(ctx->method).find("__noinline__") != std::string::npos) {
1335 EmitEvent(GetGraph(), callInst, *ctx, events::InlineResult::NOINLINE);
1336 return false;
1337 }
1338 return CheckMethodSize<CHECK_EXTERNAL>(callInst, ctx);
1339 }
1340
RemoveReturnVoidInst(BasicBlock * endBlock)1341 void RemoveReturnVoidInst(BasicBlock *endBlock)
1342 {
1343 for (auto &pred : endBlock->GetPredsBlocks()) {
1344 auto returnInst = pred->GetLastInst();
1345 if (returnInst->GetOpcode() == Opcode::Throw || returnInst->GetOpcode() == Opcode::Deoptimize) {
1346 continue;
1347 }
1348 ASSERT(returnInst->GetOpcode() == Opcode::ReturnVoid);
1349 pred->RemoveInst(returnInst);
1350 }
1351 }
1352
1353 /// Embed inlined dataflow graph into the caller graph. A special case where the graph is empty
UpdateDataflowForEmptyGraph(Inst * callInst,std::variant<BasicBlock *,PhiInst * > use,BasicBlock * endBlock)1354 void Inlining::UpdateDataflowForEmptyGraph(Inst *callInst, std::variant<BasicBlock *, PhiInst *> use,
1355 BasicBlock *endBlock)
1356 {
1357 auto predBlock = endBlock->GetPredsBlocks().front();
1358 auto returnInst = predBlock->GetLastInst();
1359 ASSERT(returnInst->GetOpcode() == Opcode::Return || returnInst->GetOpcode() == Opcode::ReturnVoid ||
1360 predBlock->IsEndWithThrowOrDeoptimize());
1361 if (returnInst->GetOpcode() == Opcode::Return) {
1362 ASSERT(returnInst->GetInputsCount() == 1);
1363 auto inputInst = returnInst->GetInput(0).GetInst();
1364 if (std::holds_alternative<PhiInst *>(use)) {
1365 auto phiInst = std::get<PhiInst *>(use);
1366 phiInst->AppendInput(inputInst);
1367 } else {
1368 callInst->ReplaceUsers(inputInst);
1369 }
1370 }
1371 if (!predBlock->IsEndWithThrowOrDeoptimize()) {
1372 predBlock->RemoveInst(returnInst);
1373 }
1374 }
1375
1376 /// Embed inlined dataflow graph into the caller graph.
UpdateDataflow(Graph * graphInl,Inst * callInst,std::variant<BasicBlock *,PhiInst * > use,Inst * newDef)1377 void Inlining::UpdateDataflow(Graph *graphInl, Inst *callInst, std::variant<BasicBlock *, PhiInst *> use, Inst *newDef)
1378 {
1379 // Replace inlined graph outcoming dataflow edges
1380 auto endBlock = graphInl->GetEndBlock();
1381 if (endBlock->GetPredsBlocks().size() > 1) {
1382 if (callInst->GetType() == DataType::VOID) {
1383 RemoveReturnVoidInst(endBlock);
1384 return;
1385 }
1386 PhiInst *phiInst = nullptr;
1387 if (std::holds_alternative<BasicBlock *>(use)) {
1388 phiInst = GetGraph()->CreateInstPhi(GetGraph()->GetRuntime()->GetMethodReturnType(graphInl->GetMethod()),
1389 INVALID_PC);
1390 phiInst->ReserveInputs(endBlock->GetPredsBlocks().size());
1391 std::get<BasicBlock *>(use)->AppendPhi(phiInst);
1392 } else {
1393 phiInst = std::get<PhiInst *>(use);
1394 ASSERT(phiInst != nullptr);
1395 }
1396 for (auto pred : endBlock->GetPredsBlocks()) {
1397 auto returnInst = pred->GetLastInst();
1398 if (returnInst == nullptr) {
1399 ASSERT(pred->IsTryEnd());
1400 ASSERT(pred->GetPredsBlocks().size() == 1);
1401 pred = pred->GetPredBlockByIndex(0);
1402 returnInst = pred->GetLastInst();
1403 }
1404 if (pred->IsEndWithThrowOrDeoptimize()) {
1405 continue;
1406 }
1407 ASSERT(returnInst->GetOpcode() == Opcode::Return);
1408 ASSERT(returnInst->GetInputsCount() == 1);
1409 phiInst->AppendInput(returnInst->GetInput(0).GetInst());
1410 pred->RemoveInst(returnInst);
1411 }
1412 if (newDef == nullptr) {
1413 newDef = phiInst;
1414 }
1415 callInst->ReplaceUsers(newDef);
1416 } else {
1417 UpdateDataflowForEmptyGraph(callInst, use, endBlock);
1418 }
1419 }
1420
1421 /// Embed inlined controlflow graph into the caller graph.
UpdateControlflow(Graph * graphInl,BasicBlock * callBb,BasicBlock * callContBb)1422 void Inlining::UpdateControlflow(Graph *graphInl, BasicBlock *callBb, BasicBlock *callContBb)
1423 {
1424 // Move all blocks from inlined graph to parent
1425 auto currentLoop = callBb->GetLoop();
1426 for (auto bb : graphInl->GetVectorBlocks()) {
1427 if (bb != nullptr && !bb->IsStartBlock() && !bb->IsEndBlock()) {
1428 bb->ClearMarkers();
1429 GetGraph()->AddBlock(bb);
1430 bb->CopyTryCatchProps(callBb);
1431 }
1432 }
1433 callContBb->CopyTryCatchProps(callBb);
1434
1435 // Fix loop tree
1436 for (auto loop : graphInl->GetRootLoop()->GetInnerLoops()) {
1437 currentLoop->AppendInnerLoop(loop);
1438 loop->SetOuterLoop(currentLoop);
1439 }
1440 for (auto bb : graphInl->GetRootLoop()->GetBlocks()) {
1441 bb->SetLoop(currentLoop);
1442 currentLoop->AppendBlock(bb);
1443 }
1444
1445 // Connect inlined graph as successor of the first part of call continuation block
1446 auto startBb = graphInl->GetStartBlock();
1447 ASSERT(startBb->GetSuccsBlocks().size() == 1);
1448 auto succ = startBb->GetSuccessor(0);
1449 succ->ReplacePred(startBb, callBb);
1450 startBb->GetSuccsBlocks().clear();
1451
1452 ASSERT(graphInl->HasEndBlock());
1453 auto endBlock = graphInl->GetEndBlock();
1454 for (auto pred : endBlock->GetPredsBlocks()) {
1455 endBlock->RemovePred(pred);
1456 if (pred->IsEndWithThrowOrDeoptimize() ||
1457 (pred->IsEmpty() && pred->GetPredsBlocks()[0]->IsEndWithThrowOrDeoptimize())) {
1458 if (!GetGraph()->HasEndBlock()) {
1459 GetGraph()->CreateEndBlock();
1460 }
1461 returnBlocks_.push_back(pred);
1462 pred->ReplaceSucc(endBlock, GetGraph()->GetEndBlock());
1463 } else {
1464 pred->ReplaceSucc(endBlock, callContBb);
1465 }
1466 }
1467 }
1468
1469 /**
1470 * Move constants of the inlined graph to the current one if same constant doesn't already exist.
1471 * If constant exists just fix callee graph's dataflow to use existing constants.
1472 */
MoveConstants(Graph * graphInl)1473 void Inlining::MoveConstants(Graph *graphInl)
1474 {
1475 auto startBb = graphInl->GetStartBlock();
1476 for (ConstantInst *constant = graphInl->GetFirstConstInst(), *nextConstant = nullptr; constant != nullptr;
1477 constant = nextConstant) {
1478 nextConstant = constant->GetNextConst();
1479 startBb->EraseInst(constant);
1480 auto exisingConstant = GetGraph()->FindOrAddConstant(constant);
1481 if (exisingConstant != constant) {
1482 constant->ReplaceUsers(exisingConstant);
1483 }
1484 }
1485
1486 // Move NullPtr instruction
1487 if (graphInl->HasNullPtrInst()) {
1488 startBb->EraseInst(graphInl->GetNullPtrInst());
1489 auto exisingNullptr = GetGraph()->GetOrCreateNullPtr();
1490 graphInl->GetNullPtrInst()->ReplaceUsers(exisingNullptr);
1491 }
1492 // Move LoadUndefined instruction
1493 if (graphInl->HasUndefinedInst()) {
1494 startBb->EraseInst(graphInl->GetUndefinedInst());
1495 auto exisingUndefined = GetGraph()->GetOrCreateUndefinedInst();
1496 graphInl->GetUndefinedInst()->ReplaceUsers(exisingUndefined);
1497 }
1498 }
1499
ResolveTarget(CallInst * callInst,InlineContext * ctx)1500 bool Inlining::ResolveTarget(CallInst *callInst, InlineContext *ctx)
1501 {
1502 auto runtime = GetGraph()->GetRuntime();
1503 auto method = callInst->GetCallMethod();
1504 if (callInst->GetOpcode() == Opcode::CallStatic) {
1505 ctx->method = method;
1506 return true;
1507 }
1508
1509 if (g_options.IsCompilerNoVirtualInlining()) {
1510 return false;
1511 }
1512
1513 // If class or method are final we can resolve the method
1514 if (runtime->IsMethodFinal(method) || runtime->IsClassFinal(runtime->GetClass(method))) {
1515 ctx->method = method;
1516 return true;
1517 }
1518
1519 auto objectInst = callInst->GetDataFlowInput(callInst->GetObjectIndex());
1520 auto typeInfo = objectInst->GetObjectTypeInfo();
1521 if (CanUseTypeInfo(typeInfo, method)) {
1522 auto receiver = typeInfo.GetClass();
1523 MethodPtr resolvedMethod;
1524 if (runtime->IsInterfaceMethod(method)) {
1525 resolvedMethod = runtime->ResolveInterfaceMethod(receiver, method);
1526 } else {
1527 resolvedMethod = runtime->ResolveVirtualMethod(receiver, method);
1528 }
1529 if (resolvedMethod != nullptr && (typeInfo.IsExact() || runtime->IsMethodFinal(resolvedMethod))) {
1530 ctx->method = resolvedMethod;
1531 return true;
1532 }
1533 if (typeInfo.IsExact()) {
1534 LOG_INLINING(WARNING) << "Runtime failed to resolve method";
1535 return false;
1536 }
1537 }
1538
1539 if (ArchTraits<RUNTIME_ARCH>::SUPPORT_DEOPTIMIZATION && !g_options.IsCompilerNoChaInlining() &&
1540 !GetGraph()->IsAotMode()) {
1541 // Try resolve via CHA
1542 auto cha = GetCha();
1543 if (cha != nullptr && cha->IsSingleImplementation(method)) {
1544 auto klass = runtime->GetClass(method);
1545 ctx->method = runtime->ResolveVirtualMethod(klass, callInst->GetCallMethod());
1546 if (ctx->method == nullptr) {
1547 return false;
1548 }
1549 ctx->chaDevirtualize = true;
1550 return true;
1551 }
1552 }
1553
1554 return false;
1555 }
1556
CanUseTypeInfo(ObjectTypeInfo typeInfo,RuntimeInterface::MethodPtr method)1557 bool Inlining::CanUseTypeInfo(ObjectTypeInfo typeInfo, RuntimeInterface::MethodPtr method)
1558 {
1559 auto runtime = GetGraph()->GetRuntime();
1560 if (!typeInfo || runtime->IsInterface(typeInfo.GetClass())) {
1561 return false;
1562 }
1563 return runtime->IsAssignableFrom(runtime->GetClass(method), typeInfo.GetClass());
1564 }
1565
InsertChaGuard(CallInst * callInst)1566 void Inlining::InsertChaGuard(CallInst *callInst)
1567 {
1568 auto saveState = callInst->GetSaveState();
1569 auto checkDeopt = GetGraph()->CreateInstIsMustDeoptimize(DataType::BOOL, callInst->GetPc());
1570 auto deopt =
1571 GetGraph()->CreateInstDeoptimizeIf(callInst->GetPc(), checkDeopt, saveState, DeoptimizeType::INLINE_CHA);
1572 callInst->InsertBefore(deopt);
1573 deopt->InsertBefore(checkDeopt);
1574 }
1575
SkipBlock(const BasicBlock * block) const1576 bool Inlining::SkipBlock(const BasicBlock *block) const
1577 {
1578 if (block == nullptr || block->IsEmpty()) {
1579 return true;
1580 }
1581 if (!g_options.IsCompilerInliningSkipThrowBlocks() || (GetGraph()->GetThrowCounter(block) > 0)) {
1582 return false;
1583 }
1584 return block->IsEndWithThrowOrDeoptimize();
1585 }
1586 } // namespace ark::compiler
1587