xref: /llvm-project/mlir/unittests/Support/StorageUniquerTest.cpp (revision 31bb8efd698304a8385ff79229ffbaa5613efdfb)
1 //===- StorageUniquerTest.cpp - StorageUniquer Tests ----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "mlir/Support/StorageUniquer.h"
10 #include "gmock/gmock.h"
11 
12 using namespace mlir;
13 
14 namespace {
15 /// Simple storage class used for testing.
16 template <typename ConcreteT, typename... Args>
17 struct SimpleStorage : public StorageUniquer::BaseStorage {
18   using Base = SimpleStorage<ConcreteT, Args...>;
19   using KeyTy = std::tuple<Args...>;
20 
SimpleStorage__anon4a5492a20111::SimpleStorage21   SimpleStorage(KeyTy key) : key(key) {}
22 
23   /// Get an instance of this storage instance.
24   template <typename... ParamsT>
get__anon4a5492a20111::SimpleStorage25   static ConcreteT *get(StorageUniquer &uniquer, ParamsT &&...params) {
26     return uniquer.get<ConcreteT>(
27         /*initFn=*/{}, std::make_tuple(std::forward<ParamsT>(params)...));
28   }
29 
30   /// Construct an instance with the given storage allocator.
construct__anon4a5492a20111::SimpleStorage31   static ConcreteT *construct(StorageUniquer::StorageAllocator &alloc,
32                               KeyTy key) {
33     return new (alloc.allocate<ConcreteT>())
34         ConcreteT(std::forward<KeyTy>(key));
35   }
operator ==__anon4a5492a20111::SimpleStorage36   bool operator==(const KeyTy &key) const { return this->key == key; }
37 
38   KeyTy key;
39 };
40 } // namespace
41 
TEST(StorageUniquerTest,NonTrivialDestructor)42 TEST(StorageUniquerTest, NonTrivialDestructor) {
43   struct NonTrivialStorage : public SimpleStorage<NonTrivialStorage, bool *> {
44     using Base::Base;
45     ~NonTrivialStorage() {
46       bool *wasDestructed = std::get<0>(key);
47       *wasDestructed = true;
48     }
49   };
50 
51   // Verify that the storage instance destructor was properly called.
52   bool wasDestructed = false;
53   {
54     StorageUniquer uniquer;
55     uniquer.registerParametricStorageType<NonTrivialStorage>();
56     NonTrivialStorage::get(uniquer, &wasDestructed);
57   }
58 
59   EXPECT_TRUE(wasDestructed);
60 }
61