1 /**
2 * Copyright (c) 2021-2022 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 #ifndef PANDA_RUNTIME_COMPILER_H
16 #define PANDA_RUNTIME_COMPILER_H
17
18 #include "compiler/compile_method.h"
19 #include "compiler/compiler_task_runner.h"
20 #include "compiler/optimizer/ir/runtime_interface.h"
21 #include "libpandabase/mem/code_allocator.h"
22 #include "libpandabase/os/mutex.h"
23 #include "runtime/entrypoints/entrypoints.h"
24 #include "runtime/include/hclass.h"
25 #include "runtime/include/compiler_interface.h"
26 #include "runtime/include/coretypes/array.h"
27 #include "runtime/include/coretypes/tagged_value.h"
28 #include "runtime/include/locks.h"
29 #include "runtime/include/mem/panda_containers.h"
30 #include "runtime/include/method.h"
31 #include "runtime/include/runtime_options.h"
32 #include "runtime/interpreter/frame.h"
33 #include "runtime/mem/gc/gc_barrier_set.h"
34 #include "runtime/mem/tlab.h"
35 #include "runtime/compiler_thread_pool_worker.h"
36 #include "runtime/compiler_task_manager_worker.h"
37 #include "runtime/include/thread.h"
38
39 #include "runtime/osr.h"
40
41 namespace panda {
42
43 using compiler::RuntimeInterface;
44 using compiler::UnresolvedTypesInterface;
45
MethodCast(RuntimeInterface::MethodPtr method)46 inline panda::Method *MethodCast(RuntimeInterface::MethodPtr method)
47 {
48 return static_cast<panda::Method *>(method);
49 }
50
51 struct ScopedMutatorLock : public os::memory::ReadLockHolder<MutatorLock> {
ScopedMutatorLockScopedMutatorLock52 ScopedMutatorLock() : os::memory::ReadLockHolder<MutatorLock>(*PandaVM::GetCurrent()->GetMutatorLock()) {}
53 };
54
55 class PANDA_PUBLIC_API ClassHierarchyAnalysisWrapper : public compiler::IClassHierarchyAnalysis {
56 public:
GetSingleImplementation(RuntimeInterface::MethodPtr method)57 RuntimeInterface::MethodPtr GetSingleImplementation(RuntimeInterface::MethodPtr method) override
58 {
59 return static_cast<Method *>(method)->GetSingleImplementation();
60 }
IsSingleImplementation(RuntimeInterface::MethodPtr method)61 bool IsSingleImplementation(RuntimeInterface::MethodPtr method) override
62 {
63 return static_cast<Method *>(method)->HasSingleImplementation();
64 }
65 void AddDependency(RuntimeInterface::MethodPtr callee, RuntimeInterface::MethodPtr caller) override;
66 };
67
68 class PANDA_PUBLIC_API InlineCachesWrapper : public compiler::InlineCachesInterface {
69 public:
70 CallKind GetClasses(RuntimeInterface::MethodPtr m, uintptr_t pc,
71 ArenaVector<RuntimeInterface::ClassPtr> *classes) override;
72 };
73
74 class PANDA_PUBLIC_API UnresolvedTypesWrapper : public UnresolvedTypesInterface {
75 public:
76 bool AddTableSlot(RuntimeInterface::MethodPtr method, uint32_t typeId, SlotKind kind) override;
77 uintptr_t GetTableSlot(RuntimeInterface::MethodPtr method, uint32_t typeId, SlotKind kind) const override;
78
79 private:
80 PandaMap<RuntimeInterface::MethodPtr, PandaMap<std::pair<uint32_t, SlotKind>, uintptr_t>> slots_;
81 };
82
83 class PANDA_PUBLIC_API PandaRuntimeInterface : public RuntimeInterface {
84 public:
GetRuntimeEntry()85 void *GetRuntimeEntry() override
86 {
87 return nullptr;
88 }
89
GetCha()90 compiler::IClassHierarchyAnalysis *GetCha() override
91 {
92 return &cha_;
93 }
94
GetInlineCaches()95 compiler::InlineCachesInterface *GetInlineCaches() override
96 {
97 return &inlineCaches_;
98 }
99
GetUnresolvedTypes()100 compiler::UnresolvedTypesInterface *GetUnresolvedTypes() override
101 {
102 return &unresolvedTypes_;
103 }
104
GetReturnReasonOk()105 unsigned GetReturnReasonOk() const override
106 {
107 return static_cast<unsigned>(CompilerInterface::ReturnReason::RET_OK);
108 }
GetReturnReasonDeopt()109 unsigned GetReturnReasonDeopt() const override
110 {
111 return static_cast<unsigned>(CompilerInterface::ReturnReason::RET_DEOPTIMIZATION);
112 }
113
ClassCast(ClassPtr cls)114 panda::Class *ClassCast(ClassPtr cls) const
115 {
116 return static_cast<panda::Class *>(cls);
117 }
118
GetStackOverflowCheckOffset()119 size_t GetStackOverflowCheckOffset() const override
120 {
121 return ManagedThread::GetStackOverflowCheckOffset();
122 }
123
124 /**********************************************************************************/
125 /// Binary file information
GetBinaryFileForMethod(MethodPtr method)126 BinaryFilePtr GetBinaryFileForMethod(MethodPtr method) const override
127 {
128 return const_cast<panda_file::File *>(MethodCast(method)->GetPandaFile());
129 }
130
131 MethodId ResolveMethodIndex(MethodPtr parentMethod, MethodIndex index) const override;
132
133 FieldId ResolveFieldIndex(MethodPtr parentMethod, FieldIndex index) const override;
134
135 IdType ResolveTypeIndex(MethodPtr parentMethod, TypeIndex index) const override;
136
137 /**********************************************************************************/
138 /// Method information
139 MethodPtr GetMethodById(MethodPtr parentMethod, MethodId id) const override;
140
141 MethodId GetMethodId(MethodPtr method) const override;
142
143 IntrinsicId GetIntrinsicId([[maybe_unused]] MethodPtr method) const override;
144
145 uint64_t GetUniqMethodId(MethodPtr method) const override;
146
147 MethodPtr ResolveVirtualMethod(ClassPtr cls, MethodPtr method) const override;
148
149 MethodPtr ResolveInterfaceMethod(ClassPtr cls, MethodPtr method) const override;
150
GetMethodReturnType(MethodPtr method)151 compiler::DataType::Type GetMethodReturnType(MethodPtr method) const override
152 {
153 return ToCompilerType(MethodCast(method)->GetEffectiveReturnType());
154 }
155
156 IdType GetMethodReturnTypeId(MethodPtr method) const override;
157 IdType GetMethodArgReferenceTypeId(MethodPtr method, uint16_t num) const override;
158
GetMethodTotalArgumentType(MethodPtr method,size_t index)159 compiler::DataType::Type GetMethodTotalArgumentType(MethodPtr method, size_t index) const override
160 {
161 return ToCompilerType(MethodCast(method)->GetEffectiveArgType(index));
162 }
GetMethodTotalArgumentsCount(MethodPtr method)163 size_t GetMethodTotalArgumentsCount(MethodPtr method) const override
164 {
165 return MethodCast(method)->GetNumArgs();
166 }
167
168 bool IsMemoryBarrierRequired(MethodPtr method) const override;
169
170 compiler::DataType::Type GetMethodReturnType(MethodPtr parentMethod, MethodId id) const override;
171
172 compiler::DataType::Type GetMethodArgumentType(MethodPtr parentMethod, MethodId id, size_t index) const override;
173
174 size_t GetMethodArgumentsCount(MethodPtr parentMethod, MethodId id) const override;
GetMethodArgumentsCount(MethodPtr method)175 size_t GetMethodArgumentsCount(MethodPtr method) const override
176 {
177 return MethodCast(method)->GetNumArgs();
178 }
GetMethodRegistersCount(MethodPtr method)179 size_t GetMethodRegistersCount(MethodPtr method) const override
180 {
181 return MethodCast(method)->GetNumVregs();
182 }
GetMethodCode(MethodPtr method)183 const uint8_t *GetMethodCode(MethodPtr method) const override
184 {
185 return MethodCast(method)->GetInstructions();
186 }
GetMethodCodeSize(MethodPtr method)187 size_t GetMethodCodeSize(MethodPtr method) const override
188 {
189 return MethodCast(method)->GetCodeSize();
190 }
GetMethodSourceLanguage(MethodPtr method)191 SourceLanguage GetMethodSourceLanguage(MethodPtr method) const override
192 {
193 return static_cast<SourceLanguage>(MethodCast(method)->GetClass()->GetSourceLang());
194 }
SetCompiledEntryPoint(MethodPtr method,void * ep)195 void SetCompiledEntryPoint(MethodPtr method, void *ep) override
196 {
197 MethodCast(method)->SetCompiledEntryPoint(ep);
198 }
TrySetOsrCode(MethodPtr method,void * ep)199 bool TrySetOsrCode(MethodPtr method, void *ep) override
200 {
201 ScopedMutatorLock lock;
202 // Ignore OSR code if method was deoptimized during OSR compilation
203 if (!static_cast<const Method *>(method)->HasCompiledCode()) {
204 return false;
205 }
206 CompilerInterface *compiler = Thread::GetCurrent()->GetVM()->GetCompiler();
207 ASSERT(compiler->GetOsrCode(static_cast<const Method *>(method)) == nullptr);
208 compiler->SetOsrCode(static_cast<const Method *>(method), ep);
209 return true;
210 }
GetOsrCode(MethodPtr method)211 void *GetOsrCode(MethodPtr method) override
212 {
213 return Thread::GetCurrent()->GetVM()->GetCompiler()->GetOsrCode(static_cast<const Method *>(method));
214 }
HasCompiledCode(MethodPtr method)215 bool HasCompiledCode(MethodPtr method) override
216 {
217 return MethodCast(method)->HasCompiledCode();
218 }
219
IsInstantiable(ClassPtr klass)220 bool IsInstantiable(ClassPtr klass) const override
221 {
222 return ClassCast(klass)->IsInstantiable();
223 }
224
GetAccessFlagAbstractMask()225 uint32_t GetAccessFlagAbstractMask() const override
226 {
227 return panda::ACC_ABSTRACT;
228 }
229
GetVTableIndex(MethodPtr method)230 uint32_t GetVTableIndex(MethodPtr method) const override
231 {
232 return MethodCast(method)->GetVTableIndex();
233 }
234
GetClassIdForField(MethodPtr method,size_t fieldId)235 size_t GetClassIdForField(MethodPtr method, size_t fieldId) const override
236 {
237 auto fda =
238 panda_file::FieldDataAccessor(*MethodCast(method)->GetPandaFile(), panda_file::File::EntityId(fieldId));
239 return fda.GetClassId().GetOffset();
240 }
241
GetClassIdForField(FieldPtr field)242 size_t GetClassIdForField(FieldPtr field) const override
243 {
244 return FieldCast(field)->GetClass()->GetFileId().GetOffset();
245 }
246
247 ClassPtr GetClassForField(FieldPtr field) const override;
248
GetClassIdForMethod(MethodPtr method)249 size_t GetClassIdForMethod(MethodPtr method) const override
250 {
251 auto mda = panda_file::MethodDataAccessor(*MethodCast(method)->GetPandaFile(), MethodCast(method)->GetFileId());
252 return mda.GetClassId().GetOffset();
253 }
254
GetClassIdForMethod(MethodPtr parentMethod,size_t methodId)255 size_t GetClassIdForMethod(MethodPtr parentMethod, size_t methodId) const override
256 {
257 auto mda = panda_file::MethodDataAccessor(*MethodCast(parentMethod)->GetPandaFile(),
258 panda_file::File::EntityId(methodId));
259 return mda.GetClassId().GetOffset();
260 }
261
262 bool HasNativeException(MethodPtr method) const override;
263 bool IsMethodExternal(MethodPtr parentMethod, MethodPtr calleeMethod) const override;
264
IsMethodIntrinsic(MethodPtr method)265 bool IsMethodIntrinsic(MethodPtr method) const override
266 {
267 return MethodCast(method)->IsIntrinsic();
268 }
269
IsMethodAbstract(MethodPtr method)270 bool IsMethodAbstract(MethodPtr method) const override
271 {
272 return MethodCast(method)->IsAbstract();
273 }
274
275 bool IsMethodIntrinsic(MethodPtr parentMethod, MethodId id) const override;
276
IsMethodFinal(MethodPtr method)277 bool IsMethodFinal(MethodPtr method) const override
278 {
279 return MethodCast(method)->IsFinal();
280 }
281
282 bool IsMethodStatic(MethodPtr parentMethod, MethodId id) const override;
283 bool IsMethodStatic(MethodPtr method) const override;
284
IsMethodCanBeInlined(MethodPtr method)285 bool IsMethodCanBeInlined(MethodPtr method) const override
286 {
287 auto methodPtr = MethodCast(method);
288 if (Runtime::GetCurrent()->GetOptions().GetVerificationMode() == VerificationMode::ON_THE_FLY &&
289 methodPtr->GetVerificationStage() != Method::VerificationStage::VERIFIED_OK) {
290 return false;
291 }
292 return !(methodPtr->IsIntrinsic() || methodPtr->IsNative() || methodPtr->IsAbstract());
293 }
294
295 bool IsMethodStaticConstructor([[maybe_unused]] MethodPtr method) const override;
296
GetFileName(MethodPtr method)297 std::string GetFileName(MethodPtr method) const override
298 {
299 return MethodCast(method)->GetPandaFile()->GetFilename();
300 }
301
GetFullFileName(MethodPtr method)302 std::string GetFullFileName(MethodPtr method) const override
303 {
304 return MethodCast(method)->GetPandaFile()->GetFullFileName();
305 }
306
GetClassNameFromMethod(MethodPtr method)307 std::string GetClassNameFromMethod(MethodPtr method) const override
308 {
309 ScopedMutatorLock lock;
310 return MethodCast(method)->GetClass()->GetName();
311 }
312
GetClassName(ClassPtr cls)313 std::string GetClassName(ClassPtr cls) const override
314 {
315 ScopedMutatorLock lock;
316 return ClassCast(cls)->GetName();
317 }
318
GetMethodName(MethodPtr method)319 std::string GetMethodName(MethodPtr method) const override
320 {
321 return utf::Mutf8AsCString(MethodCast(method)->GetName().data);
322 }
323
GetLineNumberAndSourceFile(MethodPtr method,uint32_t pc)324 std::string GetLineNumberAndSourceFile(MethodPtr method, uint32_t pc) const override
325 {
326 return std::string(MethodCast(method)->GetLineNumberAndSourceFile(pc));
327 }
328
GetBranchTakenCounter(MethodPtr method,uint32_t pc)329 int64_t GetBranchTakenCounter(MethodPtr method, uint32_t pc) const override
330 {
331 return MethodCast(method)->GetBranchTakenCounter(pc);
332 }
333
GetBranchNotTakenCounter(MethodPtr method,uint32_t pc)334 int64_t GetBranchNotTakenCounter(MethodPtr method, uint32_t pc) const override
335 {
336 return MethodCast(method)->GetBranchNotTakenCounter(pc);
337 }
338
GetThrowTakenCounter(MethodPtr method,uint32_t pc)339 int64_t GetThrowTakenCounter(MethodPtr method, uint32_t pc) const override
340 {
341 return MethodCast(method)->GetThrowTakenCounter(pc);
342 }
343
GetMethodFullName(MethodPtr method,bool withSignature)344 std::string GetMethodFullName(MethodPtr method, bool withSignature) const override
345 {
346 return std::string(MethodCast(method)->GetFullName(withSignature));
347 }
348
GetClass(MethodPtr method)349 ClassPtr GetClass(MethodPtr method) const override
350 {
351 ScopedMutatorLock lock;
352 return reinterpret_cast<ClassPtr>(MethodCast(method)->GetClass());
353 }
354
355 std::string GetBytecodeString(MethodPtr method, uintptr_t pc) const override;
356
357 panda::pandasm::LiteralArray GetLiteralArray(MethodPtr method, LiteralArrayId id) const override;
358
359 bool IsInterfaceMethod(MethodPtr parentMethod, MethodId id) const override;
360
361 bool IsInterfaceMethod(MethodPtr method) const override;
362
IsInstanceConstructor(MethodPtr method)363 bool IsInstanceConstructor(MethodPtr method) const override
364 {
365 return MethodCast(method)->IsInstanceConstructor();
366 }
367
IsDestroyed(MethodPtr method)368 bool IsDestroyed(MethodPtr method) const override
369 {
370 return MethodCast(method)->IsDestroyed();
371 }
372
373 bool CanThrowException(MethodPtr method) const override;
374
375 uint32_t FindCatchBlock(MethodPtr method, ClassPtr cls, uint32_t pc) const override;
376
377 /**********************************************************************************/
378 /// Thread information
379 ::panda::mem::BarrierType GetPreType() const override;
380
381 ::panda::mem::BarrierType GetPostType() const override;
382
383 ::panda::mem::BarrierOperand GetBarrierOperand(::panda::mem::BarrierPosition barrierPosition,
384 std::string_view operandName) const override;
385
386 /**********************************************************************************/
387 /// Array information
388 uint32_t GetArrayElementSize(MethodPtr method, IdType id) const override;
389
390 uint32_t GetMaxArrayLength(ClassPtr klass) const override;
391
392 uintptr_t GetPointerToConstArrayData(MethodPtr method, IdType id) const override;
393
394 size_t GetOffsetToConstArrayData(MethodPtr method, IdType id) const override;
395
396 ClassPtr GetArrayU16Class(MethodPtr method) const override;
397 /**********************************************************************************/
398 /// String information
IsCompressedStringsEnabled()399 bool IsCompressedStringsEnabled() const override
400 {
401 return panda::coretypes::String::GetCompressedStringsEnabled();
402 }
403
404 ObjectPointerType GetNonMovableString(MethodPtr method, StringId id) const override;
405
406 ClassPtr GetStringClass(MethodPtr method) const override;
407
408 /**********************************************************************************/
409 /// TLAB information
410 size_t GetTLABMaxSize() const override;
411
GetTLABAlignment()412 size_t GetTLABAlignment() const override
413 {
414 return DEFAULT_ALIGNMENT_IN_BYTES;
415 }
416
IsTrackTlabAlloc()417 bool IsTrackTlabAlloc() const override
418 {
419 return panda::mem::PANDA_TRACK_TLAB_ALLOCATIONS ||
420 Logger::IsLoggingOn(Logger::Level::DEBUG, Logger::Component::MM_OBJECT_EVENTS);
421 }
422
423 /**********************************************************************************/
424 /// Object information
425 ClassPtr GetClass(MethodPtr method, IdType id) const override;
426
427 compiler::ClassType GetClassType(MethodPtr method, IdType id) const override;
428 compiler::ClassType GetClassType(ClassPtr klassPtr) const override;
429
430 bool IsArrayClass(MethodPtr method, IdType id) const override;
431
432 bool IsStringClass(MethodPtr method, IdType id) const override;
433
IsArrayClass(ClassPtr cls)434 bool IsArrayClass(ClassPtr cls) const override
435 {
436 return ClassCast(cls)->IsArrayClass();
437 }
438
439 ClassPtr GetArrayElementClass(ClassPtr cls) const override;
440
441 bool CheckStoreArray(ClassPtr arrayCls, ClassPtr strCls) const override;
442
443 bool IsAssignableFrom(ClassPtr cls1, ClassPtr cls2) const override;
444
GetObjectHashedStatusBitNum()445 size_t GetObjectHashedStatusBitNum() const override
446 {
447 static_assert(MarkWord::MarkWordRepresentation::STATUS_SIZE == 2);
448 static_assert(MarkWord::MarkWordRepresentation::STATUS_HASHED == 2);
449 // preconditions above allow just check one bit
450 return MarkWord::MarkWordRepresentation::STATUS_SHIFT + 1;
451 }
452
GetObjectHashShift()453 size_t GetObjectHashShift() const override
454 {
455 return MarkWord::MarkWordRepresentation::HASH_SHIFT;
456 }
457
GetObjectHashMask()458 size_t GetObjectHashMask() const override
459 {
460 return MarkWord::MarkWordRepresentation::HASH_MASK;
461 }
462
GetStringCtorType(MethodPtr ctorMethod)463 compiler::StringCtorType GetStringCtorType(MethodPtr ctorMethod) const override
464 {
465 return (std::strcmp(utf::Mutf8AsCString(MethodCast(ctorMethod)->GetRefArgType(1).data), "[C") == 0)
466 ? compiler::StringCtorType::CHAR_ARRAY
467 : compiler::StringCtorType::STRING;
468 }
469
470 /**********************************************************************************/
471 /// Class information
GetClassInitializedValue()472 uint8_t GetClassInitializedValue() const override
473 {
474 return static_cast<uint8_t>(panda::Class::State::INITIALIZED);
475 }
476
477 std::optional<IdType> FindClassIdInFile(MethodPtr method, ClassPtr cls) const;
478 IdType GetClassIdWithinFile(MethodPtr method, ClassPtr cls) const override;
479 IdType GetLiteralArrayClassIdWithinFile(MethodPtr method, panda_file::LiteralTag tag) const override;
480 bool CanUseTlabForClass(ClassPtr klass) const override;
481
GetClassSize(ClassPtr klass)482 size_t GetClassSize(ClassPtr klass) const override
483 {
484 return ClassCast(klass)->GetObjectSize();
485 }
486
487 bool CanScalarReplaceObject(ClassPtr klass) const override;
488
489 /**********************************************************************************/
490 /// Field information
491
492 FieldPtr ResolveField(MethodPtr method, size_t id, bool allowExternal, uint32_t *classId) override;
493 compiler::DataType::Type GetFieldType(FieldPtr field) const override;
494 compiler::DataType::Type GetFieldTypeById(MethodPtr parentMethod, IdType id) const override;
495 IdType GetFieldValueTypeId(MethodPtr method, IdType id) const override;
496 size_t GetFieldOffset(FieldPtr field) const override;
497 FieldPtr GetFieldByOffset(size_t offset) const override;
498 uintptr_t GetFieldClass(FieldPtr field) const override;
499 bool IsFieldVolatile(FieldPtr field) const override;
500 bool HasFieldMetadata(FieldPtr field) const override;
501
GetFieldName(FieldPtr field)502 std::string GetFieldName(FieldPtr field) const override
503 {
504 return utf::Mutf8AsCString(FieldCast(field)->GetName().data);
505 }
506
FieldCast(FieldPtr field)507 panda::Field *FieldCast(FieldPtr field) const
508 {
509 ASSERT(HasFieldMetadata(field));
510 return static_cast<panda::Field *>(field);
511 }
512
513 FieldId GetFieldId(FieldPtr field) const override;
514
515 /**********************************************************************************/
516 /// Type information
517
518 PandaRuntimeInterface::ClassPtr ResolveType(MethodPtr method, size_t id) const override;
519
520 bool IsClassInitialized(uintptr_t klass) const override;
521
IsClassFinal(ClassPtr klass)522 bool IsClassFinal(ClassPtr klass) const override
523 {
524 return ClassCast(klass)->IsFinal();
525 }
526
IsInterface(ClassPtr klass)527 bool IsInterface(ClassPtr klass) const override
528 {
529 return ClassCast(klass)->IsInterface();
530 }
531
532 uintptr_t GetManagedType(uintptr_t klass) const override;
533
TypeCast(uintptr_t klass)534 panda::Class *TypeCast(uintptr_t klass) const
535 {
536 return reinterpret_cast<panda::Class *>(klass);
537 }
538
GetReferenceTypeMask()539 uint8_t GetReferenceTypeMask() const override
540 {
541 return static_cast<uint8_t>(panda_file::Type::TypeId::REFERENCE);
542 }
543
544 /**********************************************************************************/
545 /// Entrypoints
546 uintptr_t GetIntrinsicAddress(bool runtimeCall, SourceLanguage lang, IntrinsicId id) const override;
547
548 /**********************************************************************************/
549 /// Dynamic object information
550
551 uint32_t GetFunctionTargetOffset(Arch arch) const override;
552
GetDynamicPrimitiveUndefined()553 uint64_t GetDynamicPrimitiveUndefined() const override
554 {
555 return static_cast<uint64_t>(coretypes::TaggedValue::Undefined().GetRawData());
556 }
557
GetDynamicPrimitiveFalse()558 uint64_t GetDynamicPrimitiveFalse() const override
559 {
560 return static_cast<uint64_t>(coretypes::TaggedValue::False().GetRawData());
561 }
562
GetDynamicPrimitiveTrue()563 uint64_t GetDynamicPrimitiveTrue() const override
564 {
565 return static_cast<uint64_t>(coretypes::TaggedValue::True().GetRawData());
566 }
567
568 uint32_t GetNativePointerTargetOffset(Arch arch) const override;
569
570 bool HasSafepointDuringCall() const override;
571
572 bool IsGcValidForFastPath(SourceLanguage lang) const;
573
SetCurrentThread(Thread * thread)574 void SetCurrentThread(Thread *thread) const override
575 {
576 ASSERT(thread != Thread::GetCurrent());
577 Thread::SetCurrent(thread);
578 }
579
580 private:
ToCompilerType(panda_file::Type type)581 static compiler::DataType::Type ToCompilerType(panda_file::Type type)
582 {
583 switch (type.GetId()) {
584 case panda_file::Type::TypeId::VOID:
585 return compiler::DataType::VOID;
586 case panda_file::Type::TypeId::U1:
587 return compiler::DataType::BOOL;
588 case panda_file::Type::TypeId::I8:
589 return compiler::DataType::INT8;
590 case panda_file::Type::TypeId::U8:
591 return compiler::DataType::UINT8;
592 case panda_file::Type::TypeId::I16:
593 return compiler::DataType::INT16;
594 case panda_file::Type::TypeId::U16:
595 return compiler::DataType::UINT16;
596 case panda_file::Type::TypeId::I32:
597 return compiler::DataType::INT32;
598 case panda_file::Type::TypeId::U32:
599 return compiler::DataType::UINT32;
600 case panda_file::Type::TypeId::I64:
601 return compiler::DataType::INT64;
602 case panda_file::Type::TypeId::U64:
603 return compiler::DataType::UINT64;
604 case panda_file::Type::TypeId::F32:
605 return compiler::DataType::FLOAT32;
606 case panda_file::Type::TypeId::F64:
607 return compiler::DataType::FLOAT64;
608 case panda_file::Type::TypeId::REFERENCE:
609 return compiler::DataType::REFERENCE;
610 case panda_file::Type::TypeId::TAGGED:
611 return compiler::DataType::ANY;
612 default:
613 break;
614 }
615 UNREACHABLE();
616 }
617
618 private:
619 ClassHierarchyAnalysisWrapper cha_;
620 InlineCachesWrapper inlineCaches_;
621 UnresolvedTypesWrapper unresolvedTypes_;
622 };
623
624 class Compiler : public CompilerInterface {
625 public:
Compiler(CodeAllocator * codeAllocator,mem::InternalAllocatorPtr internalAllocator,const RuntimeOptions & options,mem::MemStatsType * memStats,compiler::RuntimeInterface * runtimeIface)626 explicit Compiler(CodeAllocator *codeAllocator, mem::InternalAllocatorPtr internalAllocator,
627 const RuntimeOptions &options, mem::MemStatsType *memStats,
628 compiler::RuntimeInterface *runtimeIface)
629 : codeAllocator_(codeAllocator),
630 internalAllocator_(internalAllocator),
631 gdbDebugInfoAllocator_(panda::SpaceType::SPACE_TYPE_COMPILER, memStats),
632 runtimeIface_(runtimeIface)
633 {
634 noAsyncJit_ = options.IsNoAsyncJit();
635 if (options.IsArkAot()) {
636 return;
637 }
638
639 if ((Runtime::GetTaskScheduler() == nullptr) || noAsyncJit_) {
640 compilerWorker_ =
641 internalAllocator_->New<CompilerThreadPoolWorker>(internalAllocator_, this, noAsyncJit_, options);
642 } else {
643 compilerWorker_ = internalAllocator_->New<CompilerTaskManagerWorker>(internalAllocator_, this);
644 }
645 InitializeWorker();
646 if (compiler::g_options.WasSetCompilerDumpJitStatsCsv()) {
647 jitStats_ = internalAllocator_->New<compiler::JITStats>(internalAllocator_);
648 }
649 }
650
PreZygoteFork()651 void PreZygoteFork() override
652 {
653 FinalizeWorker();
654 }
655
PostZygoteFork()656 void PostZygoteFork() override
657 {
658 InitializeWorker();
659 }
660
FinalizeWorker()661 void FinalizeWorker() override
662 {
663 if (compilerWorker_ != nullptr) {
664 compilerWorker_->FinalizeWorker();
665 }
666 }
667
668 void JoinWorker() override;
669
670 bool IsCompilationExpired(Method *method, bool isOsr);
671
~Compiler()672 ~Compiler() override
673 {
674 // We need to join thread first if runtime initialization fails and Destroy is not called
675 FinalizeWorker();
676 if (compilerWorker_ != nullptr) {
677 internalAllocator_->Delete(compilerWorker_);
678 compilerWorker_ = nullptr;
679 }
680 internalAllocator_->Delete(jitStats_);
681 }
682
683 bool CompileMethod(Method *method, uintptr_t bytecodeOffset, bool osr, TaggedValue func) override;
684
AddTask(CompilerTask && ctx,TaggedValue func)685 virtual void AddTask(CompilerTask &&ctx, [[maybe_unused]] TaggedValue func)
686 {
687 compilerWorker_->AddTask(std::move(ctx));
688 }
689
690 template <compiler::TaskRunnerMode RUNNER_MODE>
691 void CompileMethodLocked(compiler::CompilerTaskRunner<RUNNER_MODE> taskRunner);
692
693 /// Basic method, which starts compilation. Do not use.
694 template <compiler::TaskRunnerMode RUNNER_MODE>
695 void StartCompileMethod(compiler::CompilerTaskRunner<RUNNER_MODE> taskRunner);
696
ScaleThreadPool(size_t numberOfThreads)697 void ScaleThreadPool(size_t numberOfThreads)
698 {
699 // Required for testing
700 GetThreadPool()->Scale(numberOfThreads);
701 }
702
GetOsrCode(const Method * method)703 void *GetOsrCode(const Method *method) override
704 {
705 return osrCodeMap_.Get(method);
706 }
707
SetOsrCode(const Method * method,void * ptr)708 void SetOsrCode(const Method *method, void *ptr) override
709 {
710 osrCodeMap_.Set(method, ptr);
711 }
712
RemoveOsrCode(const Method * method)713 void RemoveOsrCode(const Method *method) override
714 {
715 osrCodeMap_.Remove(method);
716 }
717
SetNoAsyncJit(bool v)718 void SetNoAsyncJit(bool v) override
719 {
720 noAsyncJit_ = v;
721 }
722
IsNoAsyncJit()723 bool IsNoAsyncJit() override
724 {
725 return noAsyncJit_;
726 }
727
GetRuntimeInterface()728 compiler::RuntimeInterface *GetRuntimeInterface()
729 {
730 return runtimeIface_;
731 }
732
733 protected:
GetInternalAllocator()734 mem::InternalAllocatorPtr GetInternalAllocator()
735 {
736 return internalAllocator_;
737 }
738
GetThreadPool()739 ThreadPool<CompilerTask, CompilerProcessor, Compiler *> *GetThreadPool()
740 {
741 ASSERT(Runtime::GetTaskScheduler() == nullptr || noAsyncJit_);
742 if (compilerWorker_ != nullptr) {
743 return static_cast<CompilerThreadPoolWorker *>(compilerWorker_)->GetThreadPool();
744 }
745 return nullptr;
746 }
747
748 private:
InitializeWorker()749 void InitializeWorker()
750 {
751 if (compilerWorker_ != nullptr) {
752 compilerWorker_->InitializeWorker();
753 }
754 }
755
756 CodeAllocator *codeAllocator_;
757 OsrCodeMap osrCodeMap_;
758 mem::InternalAllocatorPtr internalAllocator_;
759 // This allocator is used for GDB debug structures in context of JIT unwind info.
760 ArenaAllocator gdbDebugInfoAllocator_;
761 compiler::RuntimeInterface *runtimeIface_;
762 // The lock is used for compiler thread synchronization
763 os::memory::Mutex compilationLock_;
764 bool noAsyncJit_;
765 CompilerWorker *compilerWorker_ {nullptr};
766 compiler::JITStats *jitStats_ {nullptr};
767 NO_COPY_SEMANTIC(Compiler);
768 NO_MOVE_SEMANTIC(Compiler);
769 };
770
771 #ifndef PANDA_PRODUCT_BUILD
772 uint8_t CompileMethodImpl(coretypes::String *fullMethodName, panda_file::SourceLang sourceLang);
773 #endif
774
775 } // namespace panda
776
777 #endif // PANDA_RUNTIME_COMPILER_H
778