[clang] [clang] Implement a bitwise_copyable builtin type trait. (PR #86512)

Ilya Biryukov via cfe-commits cfe-commits at lists.llvm.org
Tue May 14 09:24:10 PDT 2024


================
@@ -3958,6 +3958,50 @@ Note that the `size` argument must be a compile time constant.
 
 Note that this intrinsic cannot yet be called in a ``constexpr`` context.
 
+``__is_bitwise_cloneable``
+-------------------------
+
+A type trait is used to check whether a type can be safely copied by memcpy.
+
+**Syntax**:
+
+.. code-block:: c++
+
+  bool __is_bitwise_cloneable(Type)
+
+** Example of Use**:
+
+.. code-block:: c++
+
+  // Return a cloned object of the given default instance.
+  Foo* Clone(const Foo* default_instance, char* buffer, unsigned size) {
+    if constexpr __is_bitwise_cloneable(decltype(*default_instance)) {
+      // Fast path via memcopy, without calling class constructor.
+      memcpy(buffer, default_instance, size);
+      // Explicitly start the lifetime of the cloned object.
+      return __builtin_start_object_lifetime(reinterpret_cast<Foo*>(buffer));
+    }
+    // Fallback the operator new, which invoke the class constructor.
+    return new(buffer) Foo(*default_instance);
+  }
+
+**Description**:
+
+It is common for library owners to perform memcpy/memmove on types that aren't
+trivally copyable for performance reason. However, according to the C++ standard,
----------------
ilya-biryukov wrote:

NIT: I think it would be useful to explain the differences between this and is_trivially_copyable.

Something like:

```cpp
This trait is similar to `std::is_trivially_copyable`, but additionally allows to have user-defined constructors,
 virtual functions and virtual bases. It is up to the user code to guarantee that a bitwise copy results in 
non-broken object and that the lifetime of an object is properly started.
```

https://github.com/llvm/llvm-project/pull/86512


More information about the cfe-commits mailing list