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 #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 ark {
42 
43 using compiler::RuntimeInterface;
44 using compiler::UnresolvedTypesInterface;
45 
MethodCast(RuntimeInterface::MethodPtr method)46 inline ark::Method *MethodCast(RuntimeInterface::MethodPtr method)
47 {
48     return static_cast<ark::Method *>(method);
49 }
50 
51 struct ScopedMutatorLock : public os::memory::ReadLockHolder<MutatorLock> {
ScopedMutatorLockark::ScopedMutatorLock52     ScopedMutatorLock() : os::memory::ReadLockHolder<MutatorLock>(*PandaVM::GetCurrent()->GetMutatorLock()) {}
53 };
54 
55 class PANDA_PUBLIC_API ClassHierarchyAnalysisWrapper : public compiler::IClassHierarchyAnalysis {
56 public:
57     RuntimeInterface::MethodPtr GetSingleImplementation(RuntimeInterface::MethodPtr method) override
58     {
59         return static_cast<Method *>(method)->GetSingleImplementation();
60     }
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:
85     void *GetRuntimeEntry() override
86     {
87         return nullptr;
88     }
89 
90     compiler::IClassHierarchyAnalysis *GetCha() override
91     {
92         return &cha_;
93     }
94 
95     compiler::InlineCachesInterface *GetInlineCaches() override
96     {
97         return &inlineCaches_;
98     }
99 
100     compiler::UnresolvedTypesInterface *GetUnresolvedTypes() override
101     {
102         return &unresolvedTypes_;
103     }
104 
105     unsigned GetReturnReasonOk() const override
106     {
107         return static_cast<unsigned>(CompilerInterface::ReturnReason::RET_OK);
108     }
109     unsigned GetReturnReasonDeopt() const override
110     {
111         return static_cast<unsigned>(CompilerInterface::ReturnReason::RET_DEOPTIMIZATION);
112     }
113 
ClassCast(ClassPtr cls) const114     ark::Class *ClassCast(ClassPtr cls) const
115     {
116         return static_cast<ark::Class *>(cls);
117     }
118 
119     size_t GetStackOverflowCheckOffset() const override
120     {
121         return ManagedThread::GetStackOverflowCheckOffset();
122     }
123 
124     /**********************************************************************************/
125     /// Binary file information
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 
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 
159     compiler::DataType::Type GetMethodTotalArgumentType(MethodPtr method, size_t index) const override
160     {
161         return ToCompilerType(MethodCast(method)->GetEffectiveArgType(index));
162     }
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;
175     size_t GetMethodArgumentsCount(MethodPtr method) const override
176     {
177         return MethodCast(method)->GetNumArgs();
178     }
179     size_t GetMethodRegistersCount(MethodPtr method) const override
180     {
181         return MethodCast(method)->GetNumVregs();
182     }
183     const uint8_t *GetMethodCode(MethodPtr method) const override
184     {
185         return MethodCast(method)->GetInstructions();
186     }
187     size_t GetMethodCodeSize(MethodPtr method) const override
188     {
189         return MethodCast(method)->GetCodeSize();
190     }
191     SourceLanguage GetMethodSourceLanguage(MethodPtr method) const override
192     {
193         return static_cast<SourceLanguage>(MethodCast(method)->GetClass()->GetSourceLang());
194     }
195     void SetCompiledEntryPoint(MethodPtr method, void *ep) override
196     {
197         MethodCast(method)->SetCompiledEntryPoint(ep);
198     }
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     }
211     void *GetOsrCode(MethodPtr method) override
212     {
213         return Thread::GetCurrent()->GetVM()->GetCompiler()->GetOsrCode(static_cast<const Method *>(method));
214     }
215     bool HasCompiledCode(MethodPtr method) override
216     {
217         return MethodCast(method)->HasCompiledCode();
218     }
219 
220     bool IsInstantiable(ClassPtr klass) const override
221     {
222         return ClassCast(klass)->IsInstantiable();
223     }
224 
225     uint32_t GetAccessFlagAbstractMask() const override
226     {
227         return ark::ACC_ABSTRACT;
228     }
229 
230     uint32_t GetVTableIndex(MethodPtr method) const override
231     {
232         return MethodCast(method)->GetVTableIndex();
233     }
234 
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 
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 
249     uint32_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 
255     uint32_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 
265     bool IsMethodIntrinsic(MethodPtr method) const override
266     {
267         return MethodCast(method)->IsIntrinsic();
268     }
269 
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 
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 
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 
297     std::string GetFileName(MethodPtr method) const override
298     {
299         return MethodCast(method)->GetPandaFile()->GetFilename();
300     }
301 
302     std::string GetFullFileName(MethodPtr method) const override
303     {
304         return MethodCast(method)->GetPandaFile()->GetFullFileName();
305     }
306 
307     std::string GetClassNameFromMethod(MethodPtr method) const override
308     {
309         ScopedMutatorLock lock;
310         return MethodCast(method)->GetClass()->GetName();
311     }
312 
313     std::string GetClassName(ClassPtr cls) const override
314     {
315         ScopedMutatorLock lock;
316         return ClassCast(cls)->GetName();
317     }
318 
319     std::string GetMethodName(MethodPtr method) const override
320     {
321         return utf::Mutf8AsCString(MethodCast(method)->GetName().data);
322     }
323 
324     std::string GetLineNumberAndSourceFile(MethodPtr method, uint32_t pc) const override
325     {
326         return std::string(MethodCast(method)->GetLineNumberAndSourceFile(pc));
327     }
328 
329     int64_t GetBranchTakenCounter(MethodPtr method, uint32_t pc) const override
330     {
331         return MethodCast(method)->GetBranchTakenCounter(pc);
332     }
333 
334     int64_t GetBranchNotTakenCounter(MethodPtr method, uint32_t pc) const override
335     {
336         return MethodCast(method)->GetBranchNotTakenCounter(pc);
337     }
338 
339     int64_t GetThrowTakenCounter(MethodPtr method, uint32_t pc) const override
340     {
341         return MethodCast(method)->GetThrowTakenCounter(pc);
342     }
343 
344     std::string GetMethodFullName(MethodPtr method, bool withSignature) const override
345     {
346         return std::string(MethodCast(method)->GetFullName(withSignature));
347     }
348 
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     ark::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 
363     bool IsInstanceConstructor(MethodPtr method) const override
364     {
365         return MethodCast(method)->IsInstanceConstructor();
366     }
367 
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     Method *GetMethod(MethodPtr caller, RuntimeInterface::IdType id) const;
377 
378     /**********************************************************************************/
379     /// Thread information
380     ::ark::mem::BarrierType GetPreType() const override;
381 
382     ::ark::mem::BarrierType GetPostType() const override;
383 
384     ::ark::mem::BarrierOperand GetBarrierOperand(::ark::mem::BarrierPosition barrierPosition,
385                                                  std::string_view operandName) const override;
386 
387     /**********************************************************************************/
388     /// Array information
389     uint32_t GetArrayElementSize(MethodPtr method, IdType id) const override;
390 
391     uint32_t GetMaxArrayLength(ClassPtr klass) const override;
392 
393     uintptr_t GetPointerToConstArrayData(MethodPtr method, IdType id) const override;
394 
395     size_t GetOffsetToConstArrayData(MethodPtr method, IdType id) const override;
396 
397     ClassPtr GetArrayU16Class(MethodPtr method) const override;
398     ClassPtr GetArrayU8Class(MethodPtr method) const override;
399     /**********************************************************************************/
400     /// String information
401     bool IsCompressedStringsEnabled() const override
402     {
403         return ark::coretypes::String::GetCompressedStringsEnabled();
404     }
405 
406     ObjectPointerType GetNonMovableString(MethodPtr method, StringId id) const override;
407 
408     ClassPtr GetStringClass(MethodPtr method, uint32_t *typeId) const override;
409     ClassPtr GetNumberClass(MethodPtr method, const char *name, uint32_t *typeId) const override;
410 
411     std::string GetStringValue(MethodPtr method, size_t id) const override
412     {
413         ScopedMutatorLock lock;
414         panda_file::File::EntityId cid(id);
415         auto *pf = MethodCast(method)->GetPandaFile();
416         return utf::Mutf8AsCString(pf->GetStringData(cid).data);
417     }
418 
419     /**********************************************************************************/
420     /// TLAB information
421     size_t GetTLABMaxSize() const override;
422 
423     size_t GetTLABAlignment() const override
424     {
425         return DEFAULT_ALIGNMENT_IN_BYTES;
426     }
427 
428     bool IsTrackTlabAlloc() const override
429     {
430         return ark::mem::PANDA_TRACK_TLAB_ALLOCATIONS ||
431                Logger::IsLoggingOn(Logger::Level::DEBUG, Logger::Component::MM_OBJECT_EVENTS);
432     }
433 
434     /**********************************************************************************/
435     /// Object information
436     ClassPtr GetClass(MethodPtr method, IdType id) const override;
437 
438     compiler::ClassType GetClassType(MethodPtr method, IdType id) const override;
439     compiler::ClassType GetClassType(ClassPtr klassPtr) const override;
440 
441     bool IsArrayClass(MethodPtr method, IdType id) const override;
442 
443     bool IsStringClass(MethodPtr method, IdType id) const override;
444 
445     bool IsArrayClass(ClassPtr cls) const override
446     {
447         return ClassCast(cls)->IsArrayClass();
448     }
449 
450     ClassPtr GetArrayElementClass(ClassPtr cls) const override;
451 
452     bool CheckStoreArray(ClassPtr arrayCls, ClassPtr strCls) const override;
453 
454     bool IsAssignableFrom(ClassPtr cls1, ClassPtr cls2) const override;
455 
456     size_t GetObjectHashedStatusBitNum() const override
457     {
458         static_assert(MarkWord::MarkWordRepresentation::STATUS_SIZE == 2);
459         static_assert(MarkWord::MarkWordRepresentation::STATUS_HASHED == 2);
460         // preconditions above allow just check one bit
461         return MarkWord::MarkWordRepresentation::STATUS_SHIFT + 1;
462     }
463 
464     size_t GetObjectHashShift() const override
465     {
466         return MarkWord::MarkWordRepresentation::HASH_SHIFT;
467     }
468 
469     size_t GetObjectHashMask() const override
470     {
471         return MarkWord::MarkWordRepresentation::HASH_MASK;
472     }
473 
474     compiler::StringCtorType GetStringCtorType(MethodPtr ctorMethod) const override
475     {
476         return (std::strcmp(utf::Mutf8AsCString(MethodCast(ctorMethod)->GetRefArgType(1).data), "[C") == 0)
477                    ? compiler::StringCtorType::CHAR_ARRAY
478                    : compiler::StringCtorType::STRING;
479     }
480 
481     /**********************************************************************************/
482     /// Class information
483     uint8_t GetClassInitializedValue() const override
484     {
485         return static_cast<uint8_t>(ark::Class::State::INITIALIZED);
486     }
487 
488     std::optional<IdType> FindClassIdInFile(MethodPtr method, ClassPtr cls) const;
489     IdType GetClassIdWithinFile(MethodPtr method, ClassPtr cls) const override;
490     IdType GetLiteralArrayClassIdWithinFile(MethodPtr method, panda_file::LiteralTag tag) const override;
491     bool CanUseTlabForClass(ClassPtr klass) const override;
492 
493     size_t GetClassSize(ClassPtr klass) const override
494     {
495         return ClassCast(klass)->GetObjectSize();
496     }
497 
498     bool CanScalarReplaceObject(ClassPtr klass) const override;
499 
500     /**********************************************************************************/
501     /// Field information
502 
503     FieldPtr ResolveField(MethodPtr method, size_t id, bool allowExternal, uint32_t *classId) override;
504     compiler::DataType::Type GetFieldType(FieldPtr field) const override;
505     compiler::DataType::Type GetArrayComponentType(ClassPtr klass) const override;
506     compiler::DataType::Type GetFieldTypeById(MethodPtr parentMethod, IdType id) const override;
507     IdType GetFieldValueTypeId(MethodPtr method, IdType id) const override;
508     size_t GetFieldOffset(FieldPtr field) const override;
509     FieldPtr GetFieldByOffset(size_t offset) const override;
510     uintptr_t GetFieldClass(FieldPtr field) const override;
511     bool IsFieldVolatile(FieldPtr field) const override;
512     bool IsFieldFinal(FieldPtr field) const override;
513     bool IsFieldReadonly(FieldPtr field) const override;
514     bool HasFieldMetadata(FieldPtr field) const override;
515     uint64_t GetStaticFieldValue(FieldPtr fieldPtr) const override;
516 
517     std::string GetFieldName(FieldPtr field) const override
518     {
519         return utf::Mutf8AsCString(FieldCast(field)->GetName().data);
520     }
521 
FieldCast(FieldPtr field) const522     ark::Field *FieldCast(FieldPtr field) const
523     {
524         ASSERT(HasFieldMetadata(field));
525         return static_cast<ark::Field *>(field);
526     }
527 
528     FieldId GetFieldId(FieldPtr field) const override;
529     Field *GetField(MethodPtr method, RuntimeInterface::IdType id) const;
530 
531     /**********************************************************************************/
532     /// Type information
533 
534     PandaRuntimeInterface::ClassPtr ResolveType(MethodPtr method, size_t id) const override;
535 
536     bool IsClassInitialized(uintptr_t klass) const override;
537 
538     bool IsClassFinal(ClassPtr klass) const override
539     {
540         return ClassCast(klass)->IsFinal();
541     }
542 
543     bool IsInterface(ClassPtr klass) const override
544     {
545         return ClassCast(klass)->IsInterface();
546     }
547 
548     uintptr_t GetManagedType(uintptr_t klass) const override;
549 
TypeCast(uintptr_t klass) const550     ark::Class *TypeCast(uintptr_t klass) const
551     {
552         return reinterpret_cast<ark::Class *>(klass);
553     }
554 
555     uint8_t GetReferenceTypeMask() const override
556     {
557         return static_cast<uint8_t>(panda_file::Type::TypeId::REFERENCE);
558     }
559 
560     /**********************************************************************************/
561     /// Entrypoints
562     uintptr_t GetIntrinsicAddress(bool runtimeCall, SourceLanguage lang, IntrinsicId id) const override;
563 
564     /**********************************************************************************/
565     /// Dynamic object information
566 
567     uint32_t GetFunctionTargetOffset(Arch arch) const override;
568 
569     uint64_t GetDynamicPrimitiveUndefined() const override
570     {
571         return static_cast<uint64_t>(coretypes::TaggedValue::Undefined().GetRawData());
572     }
573 
574     uint64_t GetDynamicPrimitiveFalse() const override
575     {
576         return static_cast<uint64_t>(coretypes::TaggedValue::False().GetRawData());
577     }
578 
579     uint64_t GetDynamicPrimitiveTrue() const override
580     {
581         return static_cast<uint64_t>(coretypes::TaggedValue::True().GetRawData());
582     }
583 
584     uint32_t GetNativePointerTargetOffset(Arch arch) const override;
585 
586     bool HasSafepointDuringCall() const override;
587 
588     bool IsGcValidForFastPath(SourceLanguage lang) const;
589 
590     ThreadPtr CreateCompilerThread() override;
591 
592     void DestroyCompilerThread([[maybe_unused]] ThreadPtr thread) override;
593 
594     void SetCurrentThread(ThreadPtr thread) const override
595     {
596         ASSERT(thread != Thread::GetCurrent());
597         Thread::SetCurrent(static_cast<ark::Thread *>(thread));
598     }
599 
600     ThreadPtr GetCurrentThread() const override
601     {
602         return Thread::GetCurrent();
603     }
604 
605 private:
ToCompilerType(panda_file::Type type)606     static compiler::DataType::Type ToCompilerType(panda_file::Type type)
607     {
608         switch (type.GetId()) {
609             case panda_file::Type::TypeId::VOID:
610                 return compiler::DataType::VOID;
611             case panda_file::Type::TypeId::U1:
612                 return compiler::DataType::BOOL;
613             case panda_file::Type::TypeId::I8:
614                 return compiler::DataType::INT8;
615             case panda_file::Type::TypeId::U8:
616                 return compiler::DataType::UINT8;
617             case panda_file::Type::TypeId::I16:
618                 return compiler::DataType::INT16;
619             case panda_file::Type::TypeId::U16:
620                 return compiler::DataType::UINT16;
621             case panda_file::Type::TypeId::I32:
622                 return compiler::DataType::INT32;
623             case panda_file::Type::TypeId::U32:
624                 return compiler::DataType::UINT32;
625             case panda_file::Type::TypeId::I64:
626                 return compiler::DataType::INT64;
627             case panda_file::Type::TypeId::U64:
628                 return compiler::DataType::UINT64;
629             case panda_file::Type::TypeId::F32:
630                 return compiler::DataType::FLOAT32;
631             case panda_file::Type::TypeId::F64:
632                 return compiler::DataType::FLOAT64;
633             case panda_file::Type::TypeId::REFERENCE:
634                 return compiler::DataType::REFERENCE;
635             case panda_file::Type::TypeId::TAGGED:
636                 return compiler::DataType::ANY;
637             default:
638                 break;
639         }
640         UNREACHABLE();
641     }
642 
643 private:
644     ClassHierarchyAnalysisWrapper cha_;
645     InlineCachesWrapper inlineCaches_;
646     UnresolvedTypesWrapper unresolvedTypes_;
647 };
648 
649 class Compiler : public CompilerInterface {
650 public:
Compiler(CodeAllocator *codeAllocator, mem::InternalAllocatorPtr internalAllocator, const RuntimeOptions &options, mem::MemStatsType *memStats, compiler::RuntimeInterface *runtimeIface)651     explicit Compiler(CodeAllocator *codeAllocator, mem::InternalAllocatorPtr internalAllocator,
652                       const RuntimeOptions &options, mem::MemStatsType *memStats,
653                       compiler::RuntimeInterface *runtimeIface)
654         : codeAllocator_(codeAllocator),
655           internalAllocator_(internalAllocator),
656           gdbDebugInfoAllocator_(ark::SpaceType::SPACE_TYPE_COMPILER, memStats),
657           runtimeIface_(runtimeIface)
658     {
659         noAsyncJit_ = options.IsNoAsyncJit();
660         if (options.IsArkAot()) {
661             return;
662         }
663 
664         if ((Runtime::GetTaskScheduler() == nullptr) || noAsyncJit_) {
665             compilerWorker_ =
666                 internalAllocator_->New<CompilerThreadPoolWorker>(internalAllocator_, this, noAsyncJit_, options);
667         } else {
668             compilerWorker_ = internalAllocator_->New<CompilerTaskManagerWorker>(internalAllocator_, this);
669         }
670         InitializeWorker();
671         if (compiler::g_options.WasSetCompilerDumpJitStatsCsv()) {
672             jitStats_ = internalAllocator_->New<compiler::JITStats>(internalAllocator_);
673         }
674     }
675 
676     void PreZygoteFork() override
677     {
678         FinalizeWorker();
679     }
680 
681     void PostZygoteFork() override
682     {
683         InitializeWorker();
684     }
685 
686     void FinalizeWorker() override
687     {
688         if (compilerWorker_ != nullptr) {
689             compilerWorker_->FinalizeWorker();
690         }
691     }
692 
693     void JoinWorker() override;
694 
695     bool IsCompilationExpired(Method *method, bool isOsr);
696 
697     ~Compiler() override
698     {
699         // We need to join thread first if runtime initialization fails and Destroy is not called
700         FinalizeWorker();
701         if (compilerWorker_ != nullptr) {
702             internalAllocator_->Delete(compilerWorker_);
703             compilerWorker_ = nullptr;
704         }
705         internalAllocator_->Delete(jitStats_);
706     }
707 
708     bool CompileMethod(Method *method, uintptr_t bytecodeOffset, bool osr, TaggedValue func) override;
709 
AddTask(CompilerTask &&ctx, [[maybe_unused]] TaggedValue func)710     virtual void AddTask(CompilerTask &&ctx, [[maybe_unused]] TaggedValue func)
711     {
712         compilerWorker_->AddTask(std::move(ctx));
713     }
714 
715     template <compiler::TaskRunnerMode RUNNER_MODE>
716     void CompileMethodLocked(compiler::CompilerTaskRunner<RUNNER_MODE> taskRunner);
717 
718     /// Basic method, which starts compilation. Do not use.
719     template <compiler::TaskRunnerMode RUNNER_MODE>
720     void StartCompileMethod(compiler::CompilerTaskRunner<RUNNER_MODE> taskRunner);
721 
ScaleThreadPool(size_t numberOfThreads)722     void ScaleThreadPool(size_t numberOfThreads)
723     {
724         // Required for testing
725         GetThreadPool()->Scale(numberOfThreads);
726     }
727 
728     void *GetOsrCode(const Method *method) override
729     {
730         return osrCodeMap_.Get(method);
731     }
732 
733     void SetOsrCode(const Method *method, void *ptr) override
734     {
735         osrCodeMap_.Set(method, ptr);
736     }
737 
738     void RemoveOsrCode(const Method *method) override
739     {
740         osrCodeMap_.Remove(method);
741     }
742 
743     void SetNoAsyncJit(bool v) override
744     {
745         noAsyncJit_ = v;
746     }
747 
748     bool IsNoAsyncJit() override
749     {
750         return noAsyncJit_;
751     }
752 
GetRuntimeInterface()753     compiler::RuntimeInterface *GetRuntimeInterface()
754     {
755         return runtimeIface_;
756     }
757 
758 protected:
GetInternalAllocator()759     mem::InternalAllocatorPtr GetInternalAllocator()
760     {
761         return internalAllocator_;
762     }
763 
GetThreadPool()764     ThreadPool<CompilerTask, CompilerProcessor, Compiler *> *GetThreadPool()
765     {
766         ASSERT(Runtime::GetTaskScheduler() == nullptr || noAsyncJit_);
767         if (compilerWorker_ != nullptr) {
768             return static_cast<CompilerThreadPoolWorker *>(compilerWorker_)->GetThreadPool();
769         }
770         return nullptr;
771     }
772 
773 private:
InitializeWorker()774     void InitializeWorker()
775     {
776         if (compilerWorker_ != nullptr) {
777             compilerWorker_->InitializeWorker();
778         }
779     }
780 
781     CodeAllocator *codeAllocator_;
782     OsrCodeMap osrCodeMap_;
783     mem::InternalAllocatorPtr internalAllocator_;
784     // This allocator is used for GDB debug structures in context of JIT unwind info.
785     ArenaAllocator gdbDebugInfoAllocator_;
786     compiler::RuntimeInterface *runtimeIface_;
787     // The lock is used for compiler thread synchronization
788     os::memory::Mutex compilationLock_;
789     bool noAsyncJit_;
790     CompilerWorker *compilerWorker_ {nullptr};
791     compiler::JITStats *jitStats_ {nullptr};
792     NO_COPY_SEMANTIC(Compiler);
793     NO_MOVE_SEMANTIC(Compiler);
794 };
795 
796 #ifndef PANDA_PRODUCT_BUILD
797 uint8_t CompileMethodImpl(coretypes::String *fullMethodName, panda_file::SourceLang sourceLang);
798 #endif
799 
800 }  // namespace ark
801 
802 #endif  // PANDA_RUNTIME_COMPILER_H_
803