chromium/v8/src/compiler/turboshaft/zone-with-name.h

// Copyright 2024 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef V8_COMPILER_TURBOSHAFT_ZONE_WITH_NAME_H_
#define V8_COMPILER_TURBOSHAFT_ZONE_WITH_NAME_H_

#include "src/base/template-meta-programming/string-literal.h"
#include "src/compiler/zone-stats.h"

namespace v8::internal::compiler::turboshaft {

// In debug builds, `ZoneWithNamePointer` is a lightweight wrapper around a raw
// pointer to a zone-allocated object that encodes the identity of the zone (in
// terms of the zone's name) in its C++ type. This makes it more explicit what
// the lifetime of the respective object is (aka until the corresponding zone is
// gone) and provides an additional layer of safety against misuse with other
// pointer types. Such pointers are typically created by the respective zone.
// Example:
//
//   ZoneWithName<kGraphZoneName> graph_zone;
//   ZoneWithNamePointer<Graph, kGraphZoneName> graph = graph_zone.New<Graph>();
//   foo(graph_zone, graph);
//
// Both `ZoneWithName` as well as `ZoneWithNamePointer` will implicitly convert
// to the underlying raw `Zone*` and `Graph*` to make its use as smooth as
// possible, even when `foo`'s arguments expects raw types. NOTE: In release
// builds, `ZoneWithNamePointer<T, Name>` is merely an alias to `T*`.
#if defined(DEBUG) && defined(HAS_CPP_CLASS_TYPES_AS_TEMPLATE_ARGS)
template <typename T, base::tmp::StringLiteral Name>
class ZoneWithNamePointerImpl final {};

template <typename T, base::tmp::StringLiteral Name>
using ZoneWithNamePointer = ZoneWithNamePointerImpl<T, Name>;
#else
template <typename T, auto>
using ZoneWithNamePointer = T*;
#endif

#ifdef HAS_CPP_CLASS_TYPES_AS_TEMPLATE_ARGS
template <base::tmp::StringLiteral Name>
#else
template <auto Name>
#endif
class ZoneWithName final {};

}  // namespace v8::internal::compiler::turboshaft

#endif  // V8_COMPILER_TURBOSHAFT_ZONE_WITH_NAME_H_