blob: 7659c6c9a74851bf828be608328e0a61f94baab9 [file] [log] [blame]
John Stiles5c7bb322020-10-22 11:09:15 -04001/*
2 * Copyright 2020 Google LLC
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#ifndef SKSL_POOL
9#define SKSL_POOL
10
11#include <memory>
12
13namespace SkSL {
14
15class IRNode;
16struct PoolData;
17
18class Pool {
19public:
20 ~Pool();
21
John Stiles2d68ea32020-10-22 15:42:27 -040022 // Creates a pool to store IRNodes during program creation. Call attachToThread() to start using
23 // the pool for IRNode allocations. When your program is complete, call pool->detachFromThread()
24 // to take ownership of the pool and its nodes. Before destroying any of the program's nodes,
25 // make sure to reattach the pool by calling pool->attachToThread() again.
26 static std::unique_ptr<Pool> Create();
John Stiles5c7bb322020-10-22 11:09:15 -040027
John Stiles2d68ea32020-10-22 15:42:27 -040028 // Gives up ownership of a pool; conceptually, this deletes it. In practice, on some platforms,
29 // it is expensive to free and reallocate pools, so this gives us an opportunity to reuse the
John Stiles15bfe382020-10-27 19:07:05 -040030 // allocation for future Create calls.
John Stiles2d68ea32020-10-22 15:42:27 -040031 static void Recycle(std::unique_ptr<Pool> pool);
32
33 // Explicitly frees a previously recycled pool (if any), reclaiming the memory.
34 static void FreeRecycledPool() { Recycle(nullptr); }
35
36 // Attaches a pool to the current thread.
37 // It is an error to call this while a pool is already attached.
38 void attachToThread();
39
40 // Once you are done creating or destroying IRNodes in the pool, detach it from the thread.
John Stiles5c7bb322020-10-22 11:09:15 -040041 // It is an error to call this while no pool is attached.
42 void detachFromThread();
43
John Stiles270b5c02020-10-27 17:49:37 -040044 // Retrieves a node from the thread pool. If the pool is exhausted, or if the requested size
45 // exceeds the size that we can deliver from a pool, this will just allocate memory.
46 static void* AllocIRNode(size_t size);
John Stiles5c7bb322020-10-22 11:09:15 -040047
48 // Releases a node that was created by AllocIRNode. This will return it to the pool, or free it,
49 // as appropriate. Make sure to free all nodes, since some of them may be real allocations.
50 static void FreeIRNode(void* node_v);
51
52private:
John Stiles2d68ea32020-10-22 15:42:27 -040053 void checkForLeaks();
54
John Stiles15bfe382020-10-27 19:07:05 -040055 Pool() = default; // use Create to make a pool
John Stiles5c7bb322020-10-22 11:09:15 -040056 PoolData* fData = nullptr;
57};
58
59} // namespace SkSL
60
61#endif