1 // Copyright 2022 the V8 project authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef V8_HEAP_ALLOCATION_RESULT_H_ 6 #define V8_HEAP_ALLOCATION_RESULT_H_ 7 8 #include "src/common/globals.h" 9 #include "src/objects/heap-object.h" 10 #include "src/objects/objects.h" 11 #include "src/objects/smi.h" 12 13 namespace v8 { 14 namespace internal { 15 16 enum class AllocationOrigin { 17 kGeneratedCode = 0, 18 kRuntime = 1, 19 kGC = 2, 20 kFirstAllocationOrigin = kGeneratedCode, 21 kLastAllocationOrigin = kGC, 22 kNumberOfAllocationOrigins = kLastAllocationOrigin + 1 23 }; 24 25 // The result of an allocation attempt. Either represents a successful 26 // allocation that can be turned into an object or a failed attempt. 27 class AllocationResult final { 28 public: Failure()29 static AllocationResult Failure() { return AllocationResult(); } 30 FromObject(HeapObject heap_object)31 static AllocationResult FromObject(HeapObject heap_object) { 32 return AllocationResult(heap_object); 33 } 34 35 // Empty constructor creates a failed result. The callsite determines which 36 // GC to invoke based on the requested allocation. 37 AllocationResult() = default; 38 IsFailure()39 bool IsFailure() const { return object_.is_null(); } 40 41 template <typename T> To(T * obj)42 bool To(T* obj) const { 43 if (IsFailure()) return false; 44 *obj = T::cast(object_); 45 return true; 46 } 47 ToObjectChecked()48 HeapObject ToObjectChecked() const { 49 CHECK(!IsFailure()); 50 return HeapObject::cast(object_); 51 } 52 ToObject()53 HeapObject ToObject() const { 54 DCHECK(!IsFailure()); 55 return HeapObject::cast(object_); 56 } 57 ToAddress()58 Address ToAddress() const { 59 DCHECK(!IsFailure()); 60 return HeapObject::cast(object_).address(); 61 } 62 63 private: AllocationResult(HeapObject heap_object)64 explicit AllocationResult(HeapObject heap_object) : object_(heap_object) {} 65 66 HeapObject object_; 67 }; 68 69 STATIC_ASSERT(sizeof(AllocationResult) == kSystemPointerSize); 70 71 } // namespace internal 72 } // namespace v8 73 74 #endif // V8_HEAP_ALLOCATION_RESULT_H_ 75