1 /* 2 * Copyright (c) 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 16 #ifndef ECMASCRIPT_MEM_HEAP_REGION_ALLOCATOR_H 17 #define ECMASCRIPT_MEM_HEAP_REGION_ALLOCATOR_H 18 19 #include <atomic> 20 21 #include "ecmascript/mem/mem.h" 22 23 namespace panda::ecmascript { 24 class JSThread; 25 class Region; 26 class Space; 27 28 class HeapRegionAllocator { 29 public: 30 HeapRegionAllocator() = default; 31 virtual ~HeapRegionAllocator() = default; 32 33 Region *AllocateAlignedRegion(Space *space, size_t capacity, JSThread* thread); 34 void FreeRegion(Region *region); 35 IncreaseAnnoMemoryUsage(size_t bytes)36 void IncreaseAnnoMemoryUsage(size_t bytes) 37 { 38 size_t current = annoMemoryUsage_.fetch_add(bytes, std::memory_order_relaxed) + bytes; 39 size_t max = maxAnnoMemoryUsage_.load(std::memory_order_relaxed); 40 while (current > max && !maxAnnoMemoryUsage_.compare_exchange_weak(max, current, std::memory_order_relaxed)) { 41 } 42 } 43 DecreaseAnnoMemoryUsage(size_t bytes)44 void DecreaseAnnoMemoryUsage(size_t bytes) 45 { 46 annoMemoryUsage_.fetch_sub(bytes, std::memory_order_relaxed); 47 } 48 GetAnnoMemoryUsage()49 size_t GetAnnoMemoryUsage() const 50 { 51 return annoMemoryUsage_.load(std::memory_order_relaxed); 52 } 53 GetMaxAnnoMemoryUsage()54 size_t GetMaxAnnoMemoryUsage() const 55 { 56 return maxAnnoMemoryUsage_.load(std::memory_order_relaxed); 57 } 58 59 private: 60 NO_COPY_SEMANTIC(HeapRegionAllocator); 61 NO_MOVE_SEMANTIC(HeapRegionAllocator); 62 63 std::atomic<size_t> annoMemoryUsage_ {0}; 64 std::atomic<size_t> maxAnnoMemoryUsage_ {0}; 65 }; 66 } // namespace panda::ecmascript 67 68 #endif // ECMASCRIPT_MEM_HEAP_REGION_ALLOCATOR_H 69