[llvm] r337573 - Add llvm::Any.

Zachary Turner via llvm-commits llvm-commits at lists.llvm.org
Fri Jul 20 09:39:32 PDT 2018


Author: zturner
Date: Fri Jul 20 09:39:32 2018
New Revision: 337573

URL: http://llvm.org/viewvc/llvm-project?rev=337573&view=rev
Log:
Add llvm::Any.

This is analogous to std::any which is only available in C++17.

Differential Revision: https://reviews.llvm.org/D48807

Added:
    llvm/trunk/include/llvm/ADT/Any.h
    llvm/trunk/unittests/ADT/AnyTest.cpp
Modified:
    llvm/trunk/include/llvm/ADT/STLExtras.h
    llvm/trunk/unittests/ADT/CMakeLists.txt

Added: llvm/trunk/include/llvm/ADT/Any.h
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/ADT/Any.h?rev=337573&view=auto
==============================================================================
--- llvm/trunk/include/llvm/ADT/Any.h (added)
+++ llvm/trunk/include/llvm/ADT/Any.h Fri Jul 20 09:39:32 2018
@@ -0,0 +1,147 @@
+//===- Any.h - Generic type erased holder of any type -----------*- C++ -*-===//
+//
+//                     The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+//  This file provides Any, a non-template class modeled in the spirit of
+//  std::any.  The idea is to provide a type-safe replacement for C's void*.
+//  It can hold a value of any copy-constructible copy-assignable type
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_ANY_H
+#define LLVM_ADT_ANY_H
+
+#include "llvm/ADT/STLExtras.h"
+
+#include <cassert>
+#include <memory>
+#include <type_traits>
+
+namespace llvm {
+
+class Any {
+  template <typename T> struct TypeId { static const char Id = 0; };
+
+  struct StorageBase {
+    virtual ~StorageBase() = default;
+    virtual std::unique_ptr<StorageBase> clone() const = 0;
+    virtual const void *id() const = 0;
+  };
+
+  template <typename T> struct StorageImpl : public StorageBase {
+    explicit StorageImpl(const T &Value) : Value(Value) {}
+
+    explicit StorageImpl(T &&Value) : Value(std::move(Value)) {}
+
+    std::unique_ptr<StorageBase> clone() const override {
+      return llvm::make_unique<StorageImpl<T>>(Value);
+    }
+
+    const void *id() const override { return &TypeId<T>::Id; }
+
+    T Value;
+
+  private:
+    StorageImpl &operator=(const StorageImpl &Other) = delete;
+    StorageImpl(const StorageImpl &Other) = delete;
+  };
+
+public:
+  Any() = default;
+
+  Any(const Any &Other)
+      : Storage(Other.Storage ? Other.Storage->clone() : nullptr) {}
+
+  // When T is Any or T is not copy-constructible we need to explicitly disable
+  // the forwarding constructor so that the copy constructor gets selected
+  // instead.
+  template <
+      typename T,
+      typename std::enable_if<
+          llvm::conjunction<
+              llvm::negation<std::is_same<typename std::decay<T>::type, Any>>,
+              std::is_copy_constructible<typename std::decay<T>::type>>::value,
+          int>::type = 0>
+  Any(T &&Value) {
+    using U = typename std::decay<T>::type;
+    Storage = llvm::make_unique<StorageImpl<U>>(std::forward<T>(Value));
+  }
+
+  Any(Any &&Other) : Storage(std::move(Other.Storage)) {}
+
+  Any &swap(Any &Other) {
+    std::swap(Storage, Other.Storage);
+    return *this;
+  }
+
+  Any &operator=(Any Other) {
+    Storage = std::move(Other.Storage);
+    return *this;
+  }
+
+  bool hasValue() const { return !!Storage; }
+
+  void reset() { Storage.reset(); }
+
+private:
+  template <class T> friend T any_cast(const Any &Value);
+  template <class T> friend T any_cast(Any &Value);
+  template <class T> friend T any_cast(Any &&Value);
+  template <class T> friend const T *any_cast(const Any *Value);
+  template <class T> friend T *any_cast(Any *Value);
+  template <typename T> friend bool any_isa(const Any &Value);
+
+  std::unique_ptr<StorageBase> Storage;
+};
+
+template <typename T> bool any_isa(const Any &Value) {
+  if (!Value.Storage)
+    return false;
+  using U =
+      typename std::remove_cv<typename std::remove_reference<T>::type>::type;
+  return Value.Storage->id() == &Any::TypeId<U>::Id;
+}
+
+template <class T> T any_cast(const Any &Value) {
+  using U =
+      typename std::remove_cv<typename std::remove_reference<T>::type>::type;
+  return static_cast<T>(*any_cast<U>(&operand));
+}
+
+template <class T> T any_cast(Any &Value) {
+  using U =
+      typename std::remove_cv<typename std::remove_reference<T>::type>::type;
+  return static_cast<T>(*any_cast<U>(&Value));
+}
+
+template <class T> T any_cast(Any &&Value) {
+  using U =
+      typename std::remove_cv<typename std::remove_reference<T>::type>::type;
+  return static_cast<T>(std::move(*any_cast<U>(&Value)));
+}
+
+template <class T> const T *any_cast(const Any *Value) {
+  using U =
+      typename std::remove_cv<typename std::remove_reference<T>::type>::type;
+  assert(Value && any_isa<T>(*Value) && "Bad any cast!");
+  if (!Value || !any_isa<U>(*Value))
+    return nullptr;
+  return &static_cast<Any::StorageImpl<U> &>(*Value->Storage).Value;
+}
+
+template <class T> T *any_cast(Any *Value) {
+  using U = typename std::decay<T>::type;
+  assert(Value && any_isa<U>(*Value) && "Bad any cast!");
+  if (!Value || !any_isa<U>(*Value))
+    return nullptr;
+  return &static_cast<Any::StorageImpl<U> &>(*Value->Storage).Value;
+}
+
+} // end namespace llvm
+
+#endif // LLVM_ADT_ANY_H

Modified: llvm/trunk/include/llvm/ADT/STLExtras.h
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/ADT/STLExtras.h?rev=337573&r1=337572&r2=337573&view=diff
==============================================================================
--- llvm/trunk/include/llvm/ADT/STLExtras.h (original)
+++ llvm/trunk/include/llvm/ADT/STLExtras.h Fri Jul 20 09:39:32 2018
@@ -58,6 +58,18 @@ using ValueOfRange = typename std::remov
 } // end namespace detail
 
 //===----------------------------------------------------------------------===//
+//     Extra additions to <type_traits>
+//===----------------------------------------------------------------------===//
+
+template <typename T> struct negation : std::bool_constant<!bool(T::value)> {};
+
+template <typename...> struct conjunction : std::true_type {};
+template <typename B1> struct conjunction<B1> : B1 {};
+template <typename B1, typename... Bn>
+struct conjunction<B1, Bn...>
+    : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};
+
+//===----------------------------------------------------------------------===//
 //     Extra additions to <functional>
 //===----------------------------------------------------------------------===//
 

Added: llvm/trunk/unittests/ADT/AnyTest.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/unittests/ADT/AnyTest.cpp?rev=337573&view=auto
==============================================================================
--- llvm/trunk/unittests/ADT/AnyTest.cpp (added)
+++ llvm/trunk/unittests/ADT/AnyTest.cpp Fri Jul 20 09:39:32 2018
@@ -0,0 +1,173 @@
+//===- llvm/unittest/Support/AnyTest.cpp - Any tests ---===//
+//
+//                     The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include "llvm/ADT/Any.h"
+#include "gtest/gtest.h"
+#include <cstdlib>
+
+using namespace llvm;
+
+namespace {
+
+// Make sure we can construct, copy-construct, move-construct, and assign Any's.
+TEST(AnyTest, ConstructionAndAssignment) {
+  llvm::Any A;
+  llvm::Any B{7};
+  llvm::Any C{8};
+  llvm::Any D{"hello"};
+  llvm::Any E{3.7};
+
+  // An empty Any is not anything.
+  EXPECT_FALSE(A.hasValue());
+  EXPECT_FALSE(any_isa<int>(A));
+
+  // An int is an int but not something else.
+  EXPECT_TRUE(B.hasValue());
+  EXPECT_TRUE(any_isa<int>(B));
+  EXPECT_FALSE(any_isa<float>(B));
+
+  EXPECT_TRUE(C.hasValue());
+  EXPECT_TRUE(any_isa<int>(C));
+
+  // A const char * is a const char * but not an int.
+  EXPECT_TRUE(D.hasValue());
+  EXPECT_TRUE(any_isa<const char *>(D));
+  EXPECT_FALSE(any_isa<int>(D));
+
+  // A double is a double but not a float.
+  EXPECT_TRUE(E.hasValue());
+  EXPECT_TRUE(any_isa<double>(E));
+  EXPECT_FALSE(any_isa<float>(E));
+
+  // After copy constructing from an int, the new item and old item are both
+  // ints.
+  llvm::Any F(B);
+  EXPECT_TRUE(B.hasValue());
+  EXPECT_TRUE(F.hasValue());
+  EXPECT_TRUE(any_isa<int>(F));
+  EXPECT_TRUE(any_isa<int>(B));
+
+  // After move constructing from an int, the new item is an int and the old one
+  // isn't.
+  llvm::Any G(std::move(C));
+  EXPECT_FALSE(C.hasValue());
+  EXPECT_TRUE(G.hasValue());
+  EXPECT_TRUE(any_isa<int>(G));
+  EXPECT_FALSE(any_isa<int>(C));
+
+  // After copy-assigning from an int, the new item and old item are both ints.
+  A = F;
+  EXPECT_TRUE(A.hasValue());
+  EXPECT_TRUE(F.hasValue());
+  EXPECT_TRUE(any_isa<int>(A));
+  EXPECT_TRUE(any_isa<int>(F));
+
+  // After move-assigning from an int, the new item and old item are both ints.
+  B = std::move(G);
+  EXPECT_TRUE(B.hasValue());
+  EXPECT_FALSE(G.hasValue());
+  EXPECT_TRUE(any_isa<int>(B));
+  EXPECT_FALSE(any_isa<int>(G));
+}
+
+TEST(AnyTest, GoodAnyCast) {
+  llvm::Any A;
+  llvm::Any B{7};
+  llvm::Any C{8};
+  llvm::Any D{"hello"};
+  llvm::Any E{'x'};
+
+  // Check each value twice to make sure it isn't damaged by the cast.
+  EXPECT_EQ(7, llvm::any_cast<int>(B));
+  EXPECT_EQ(7, llvm::any_cast<int>(B));
+
+  EXPECT_STREQ("hello", llvm::any_cast<const char *>(D));
+  EXPECT_STREQ("hello", llvm::any_cast<const char *>(D));
+
+  EXPECT_EQ('x', llvm::any_cast<char>(E));
+  EXPECT_EQ('x', llvm::any_cast<char>(E));
+
+  llvm::Any F(B);
+  EXPECT_EQ(7, llvm::any_cast<int>(F));
+  EXPECT_EQ(7, llvm::any_cast<int>(F));
+
+  llvm::Any G(std::move(C));
+  EXPECT_EQ(8, llvm::any_cast<int>(G));
+  EXPECT_EQ(8, llvm::any_cast<int>(G));
+
+  A = F;
+  EXPECT_EQ(7, llvm::any_cast<int>(A));
+  EXPECT_EQ(7, llvm::any_cast<int>(A));
+
+  E = std::move(G);
+  EXPECT_EQ(8, llvm::any_cast<int>(E));
+  EXPECT_EQ(8, llvm::any_cast<int>(E));
+
+  // Make sure we can any_cast from an rvalue and that it's properly destroyed
+  // in the process.
+  EXPECT_EQ(8, llvm::any_cast<int>(std::move(E)));
+  EXPECT_TRUE(E.hasValue());
+
+  // Make sure moving from pointers gives back pointers, and that we can modify
+  // the underlying value through those pointers.
+  EXPECT_EQ(7, *llvm::any_cast<int>(&A));
+  int *N = llvm::any_cast<int>(&A);
+  *N = 42;
+  EXPECT_EQ(42, llvm::any_cast<int>(A));
+
+  // Make sure that we can any_cast to a reference and this is considered a good
+  // cast, resulting in an lvalue which can be modified.
+  llvm::any_cast<int &>(A) = 43;
+  EXPECT_EQ(43, llvm::any_cast<int>(A));
+}
+
+TEST(AnyTest, CopiesAndMoves) {
+  struct TestType {
+    TestType() = default;
+    TestType(const TestType &Other)
+        : Copies(Other.Copies + 1), Moves(Other.Moves) {}
+    TestType(TestType &&Other) : Copies(Other.Copies), Moves(Other.Moves + 1) {}
+    int Copies = 0;
+    int Moves = 0;
+  };
+
+  // One move to get TestType into the Any, and one move on the cast.
+  TestType T1 = llvm::any_cast<TestType>(Any{TestType()});
+  EXPECT_EQ(0, T1.Copies);
+  EXPECT_EQ(2, T1.Moves);
+
+  // One move to get TestType into the Any, and one copy on the cast.
+  Any A{TestType()};
+  TestType T2 = llvm::any_cast<TestType>(A);
+  EXPECT_EQ(1, T2.Copies);
+  EXPECT_EQ(1, T2.Moves);
+
+  // One move to get TestType into the Any, and one move on the cast.
+  TestType T3 = llvm::any_cast<TestType>(std::move(A));
+  EXPECT_EQ(0, T3.Copies);
+  EXPECT_EQ(2, T3.Moves);
+}
+
+TEST(AnyTest, BadAnyCast) {
+  llvm::Any A;
+  llvm::Any B{7};
+  llvm::Any C{"hello"};
+  llvm::Any D{'x'};
+
+  EXPECT_DEBUG_DEATH(llvm::any_cast<int>(A), "");
+
+  EXPECT_DEBUG_DEATH(llvm::any_cast<float>(B), "");
+  EXPECT_DEBUG_DEATH(llvm::any_cast<int *>(B), "");
+
+  EXPECT_DEBUG_DEATH(llvm::any_cast<std::string>(C), "");
+
+  EXPECT_DEBUG_DEATH(llvm::any_cast<unsigned char>(D), "");
+}
+
+} // anonymous namespace

Modified: llvm/trunk/unittests/ADT/CMakeLists.txt
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/unittests/ADT/CMakeLists.txt?rev=337573&r1=337572&r2=337573&view=diff
==============================================================================
--- llvm/trunk/unittests/ADT/CMakeLists.txt (original)
+++ llvm/trunk/unittests/ADT/CMakeLists.txt Fri Jul 20 09:39:32 2018
@@ -3,6 +3,7 @@ set(LLVM_LINK_COMPONENTS
   )
 
 add_llvm_unittest(ADTTests
+  AnyTest.cpp
   APFloatTest.cpp
   APIntTest.cpp
   APSIntTest.cpp




More information about the llvm-commits mailing list