LLVM 24.0.0git
ObjectStore.h
Go to the documentation of this file.
1//===- llvm/CAS/ObjectStore.h -----------------------------------*- C++ -*-===//
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/// \file
10/// This file contains the declaration of the ObjectStore class.
11///
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CAS_OBJECTSTORE_H
15#define LLVM_CAS_OBJECTSTORE_H
16
17#include "llvm/ADT/StringRef.h"
18#include "llvm/CAS/CASID.h"
20#include "llvm/Support/Error.h"
22#include <cstddef>
23
24namespace llvm {
25
26class MemoryBuffer;
27template <typename T> class unique_function;
28
29namespace cas {
30
31class ObjectStore;
32class ObjectProxy;
33class ActionCache;
34
35/// Content-addressable storage for objects.
36///
37/// Conceptually, objects are stored in a "unique set".
38///
39/// - Objects are immutable ("value objects") that are defined by their
40/// content. They are implicitly deduplicated by content.
41/// - Each object has a unique identifier (UID) that's derived from its content,
42/// called a \a CASID.
43/// - This UID is a fixed-size (strong) hash of the transitive content of a
44/// CAS object.
45/// - It's comparable between any two CAS instances that have the same \a
46/// CASIDContext::getHashSchemaIdentifier().
47/// - The UID can be printed (e.g., \a CASID::toString()) and it can parsed
48/// by the same or a different CAS instance with \a
49/// ObjectStore::parseID().
50/// - An object can be looked up by content or by UID.
51/// - \a store() is "get-or-create" methods, writing an object if it
52/// doesn't exist yet, and return a ref to it in any case.
53/// - \a loadObject(const CASID&) looks up an object by its UID.
54/// - Objects can reference other objects, forming an arbitrary DAG.
55///
56/// The \a ObjectStore interface has a few ways of referencing objects:
57///
58/// - \a ObjectRef encapsulates a reference to something in the CAS. It is an
59/// opaque type that references an object inside a specific CAS. It is
60/// implementation defined if the underlying object exists or not for an
61/// ObjectRef, and it can used to speed up CAS lookup as an implementation
62/// detail. However, you don't know anything about the underlying objects.
63/// "Loading" the object is a separate step that may not have happened
64/// yet, and which can fail (e.g. due to filesystem corruption) or introduce
65/// latency (if downloading from a remote store).
66/// - \a ObjectHandle encapulates a *loaded* object in the CAS. You need one of
67/// these to inspect the content of an object: to look at its stored
68/// data and references. This is internal to CAS implementation and not
69/// availble from CAS public APIs.
70/// - \a CASID: the UID for an object in the CAS, obtained through \a
71/// ObjectStore::getID() or \a ObjectStore::parseID(). This is a valid CAS
72/// identifier, but may reference an object that is unknown to this CAS
73/// instance.
74/// - \a ObjectProxy pairs an ObjectHandle (subclass) with a ObjectStore, and
75/// wraps access APIs to avoid having to pass extra parameters. It is the
76/// object used for accessing underlying data and refs by CAS users.
77///
78/// Both ObjectRef and ObjectHandle are lightweight, wrapping a `uint64_t` and
79/// are only valid with the associated ObjectStore instance.
80///
81/// There are a few options for accessing content of objects, with different
82/// lifetime tradeoffs:
83///
84/// - \a getData() accesses data without exposing lifetime at all.
85/// - \a getMemoryBuffer() returns a \a MemoryBuffer whose lifetime
86/// is independent of the CAS (it can live longer).
87/// - \a getDataString() return StringRef with lifetime is guaranteed to last as
88/// long as \a ObjectStore.
89/// - \a readRef() and \a forEachRef() iterate through the references in an
90/// object. There is no lifetime assumption.
92 friend class ObjectProxy;
93 void anchor();
94
95public:
96 /// Get a \p CASID from a \p ID, which should have been generated by \a
97 /// CASID::print(). This succeeds as long as \a validateID() would pass. The
98 /// object may be unknown to this CAS instance.
99 ///
100 /// TODO: Remove, and update callers to use \a validateID() or \a
101 /// extractHashFromID().
103
104 /// Store object into ObjectStore.
106 ArrayRef<char> Data) = 0;
107 /// Get an ID for \p Ref.
108 virtual CASID getID(ObjectRef Ref) const = 0;
109
110 /// Stores the data of a file into ObjectStore.
111 ///
112 /// An underlying implementation could perform optimizations that reduce I/O
113 /// and disk space consumption.
114 ///
115 /// If there are any concurrent modifications to the file, the contents in the
116 /// CAS may be corrupt.
117 ///
118 /// \param FilePath the path of the file data.
120
121 /// Exports the data of an object to a file path. It does not include any
122 /// references of the object.
123 ///
124 /// An underlying implementation could perform optimizations that reduce I/O
125 /// and disk space consumption.
126 ///
127 /// \param Node the object to read data from.
128 /// \param FilePath the path of the file data.
129 virtual Error exportDataToFile(ObjectHandle Node, StringRef Path) const;
130
131 /// Get an existing reference to the object called \p ID.
132 ///
133 /// Returns \c None if the object is not stored in this CAS.
134 virtual std::optional<ObjectRef> getReference(const CASID &ID) const = 0;
135
136 /// \returns true if the object is directly available from the local CAS, for
137 /// implementations that have this kind of distinction.
139
140 /// Validate the underlying object referred by CASID.
141 virtual Error validateObject(const CASID &ID) = 0;
142
143 /// Validate the entire ObjectStore.
144 virtual Error validate(bool CheckHash) const = 0;
145
146protected:
147 /// Load the object referenced by \p Ref.
148 ///
149 /// Errors if the object cannot be loaded.
150 /// \returns \c std::nullopt if the object is missing from the CAS.
152
153 /// Like \c loadIfExists but returns an error if the object is missing.
155
156 /// Get the size of some data.
158
159 /// Methods for handling objects. CAS implementations need to override to
160 /// provide functions to access stored CAS objects and references.
162 function_ref<Error(ObjectRef)> Callback) const = 0;
163 virtual ObjectRef readRef(ObjectHandle Node, size_t I) const = 0;
164 virtual size_t getNumRefs(ObjectHandle Node) const = 0;
166 bool RequiresNullTerminator = false) const = 0;
167
168 /// Get ObjectRef from open file.
169 virtual Expected<ObjectRef>
171 std::optional<sys::fs::file_status> Status);
172
173 /// Get a lifetime-extended StringRef pointing at \p Data.
174 ///
175 /// Depending on the CAS implementation, this may involve in-memory storage
176 /// overhead.
180
181 /// Get a lifetime-extended MemoryBuffer pointing at \p Data.
182 ///
183 /// Depending on the CAS implementation, this may involve in-memory storage
184 /// overhead.
185 std::unique_ptr<MemoryBuffer>
186 getMemoryBuffer(ObjectHandle Node, StringRef Name = "",
187 bool RequiresNullTerminator = true);
188
189 /// Read all the refs from object in a SmallVector.
190 virtual void readRefs(ObjectHandle Node,
191 SmallVectorImpl<ObjectRef> &Refs) const;
192
193 /// Allow ObjectStore implementations to create internal handles.
194#define MAKE_CAS_HANDLE_CONSTRUCTOR(HandleKind) \
195 HandleKind make##HandleKind(uint64_t InternalRef) const { \
196 return HandleKind(*this, InternalRef); \
197 }
198 MAKE_CAS_HANDLE_CONSTRUCTOR(ObjectHandle)
200#undef MAKE_CAS_HANDLE_CONSTRUCTOR
201
202public:
203 /// Helper functions to store object and returns a ObjectProxy.
204 Expected<ObjectProxy> createProxy(ArrayRef<ObjectRef> Refs, StringRef Data);
205
206 /// Store object from StringRef.
211
212 /// Default implementation reads \p FD and calls \a storeNode(). Does not
213 /// take ownership of \p FD; the caller is responsible for closing it.
214 ///
215 /// If \p Status is sent in it is to be treated as a hint. Implementations
216 /// must protect against the file size potentially growing after the status
217 /// was taken (i.e., they cannot assume that an mmap will be null-terminated
218 /// where \p Status implies).
219 ///
220 /// Returns the \a CASID and the size of the file.
223 std::optional<sys::fs::file_status> Status = std::nullopt) {
224 return storeFromOpenFileImpl(FD, Status);
225 }
226
227 static Error createUnknownObjectError(const CASID &ID);
228
229 /// Create ObjectProxy from CASID. If the object doesn't exist, get an error.
230 Expected<ObjectProxy> getProxy(const CASID &ID);
231 /// Create ObjectProxy from ObjectRef. If the object can't be loaded, get an
232 /// error.
234
235 /// \returns \c std::nullopt if the object is missing from the CAS.
237
238 /// Read the data from \p Data into \p OS.
240 uint64_t MaxBytes = -1ULL) const {
242 assert(Offset < Data.size() && "Expected valid offset");
243 Data = Data.drop_front(Offset).take_front(MaxBytes);
244 OS << toStringRef(Data);
245 return Data.size();
246 }
247
248 /// Set the size for limiting growth of on-disk storage. This has an effect
249 /// for when the instance is closed.
250 ///
251 /// Implementations may leave this unimplemented.
252 virtual Error setSizeLimit(std::optional<uint64_t> SizeLimit) {
253 return Error::success();
254 }
255
256 /// \returns the storage size of the on-disk CAS data.
257 ///
258 /// Implementations that don't have an implementation for this should return
259 /// \p std::nullopt.
261 return std::nullopt;
262 }
263
264 /// Prune local storage to reduce its size according to the desired size
265 /// limit. Pruning can happen concurrently with other operations.
266 ///
267 /// Implementations may leave this unimplemented.
268 virtual Error pruneStorageData() { return Error::success(); }
269
270 /// Validate the whole node tree.
271 Error validateTree(ObjectRef Ref);
272
273 /// Import object from another CAS. This will import the full tree from the
274 /// other CAS.
275 Expected<ObjectRef> importObject(ObjectStore &Upstream, ObjectRef Other);
276
277 /// Print the ObjectStore internals for debugging purpose.
278 virtual void print(raw_ostream &) const {}
279 void dump() const;
280
281 /// Get CASContext
282 const CASContext &getContext() const { return Context; }
283
284 virtual ~ObjectStore() = default;
285
286protected:
287 ObjectStore(const CASContext &Context) : Context(Context) {}
288
289private:
290 const CASContext &Context;
291};
292
293/// Reference to an abstract hierarchical node, with data and references.
294/// Reference is passed by value and is expected to be valid as long as the \a
295/// ObjectStore is.
297public:
298 ObjectStore &getCAS() const { return *CAS; }
299 CASID getID() const { return CAS->getID(Ref); }
300 ObjectRef getRef() const { return Ref; }
301 size_t getNumReferences() const { return CAS->getNumRefs(H); }
302 ObjectRef getReference(size_t I) const { return CAS->readRef(H, I); }
303
304 operator CASID() const { return getID(); }
305 CASID getReferenceID(size_t I) const {
306 std::optional<CASID> ID = getCAS().getID(getReference(I));
307 assert(ID && "Expected reference to be first-class object");
308 return *ID;
309 }
310
311 /// Visit each reference in order, returning an error from \p Callback to
312 /// stop early.
314 return CAS->forEachRef(H, Callback);
315 }
316
317 LLVM_ABI std::unique_ptr<MemoryBuffer>
318 getMemoryBuffer(StringRef Name = "",
319 bool RequiresNullTerminator = true) const;
320
321 /// Get the content of the node. Valid as long as the CAS is valid.
322 StringRef getData() const { return CAS->getDataString(H); }
323
324 /// Exports the data of an object to a file path.
326 return CAS->exportDataToFile(H, Path);
327 }
328
329 friend bool operator==(const ObjectProxy &Proxy, ObjectRef Ref) {
330 return Proxy.getRef() == Ref;
331 }
332 friend bool operator==(ObjectRef Ref, const ObjectProxy &Proxy) {
333 return Proxy.getRef() == Ref;
334 }
335 friend bool operator!=(const ObjectProxy &Proxy, ObjectRef Ref) {
336 return !(Proxy.getRef() == Ref);
337 }
338 friend bool operator!=(ObjectRef Ref, const ObjectProxy &Proxy) {
339 return !(Proxy.getRef() == Ref);
340 }
341
342public:
343 ObjectProxy() = delete;
344
346 return ObjectProxy(CAS, Ref, Node);
347 }
348
349private:
351 : CAS(&CAS), Ref(Ref), H(H) {}
352
353 ObjectStore *CAS;
354 ObjectRef Ref;
355 ObjectHandle H;
356};
357
358/// Create an in memory CAS.
359LLVM_ABI std::unique_ptr<ObjectStore> createInMemoryCAS();
360
361/// \returns true if \c LLVM_ENABLE_ONDISK_CAS configuration was enabled.
363
364/// Create a persistent on-disk path at \p Path.
365LLVM_ABI Expected<std::unique_ptr<ObjectStore>>
366createOnDiskCAS(const Twine &Path);
367
368/// Create \c ObjectStore and \c ActionCache instances backed by a plugin that
369/// implements the C API in \c "llvm-c/CAS/PluginAPI_functions.h".
370///
371/// \param PluginPath path of the dynamic library to load.
372/// \param OnDiskPath local path that the plugin should use for any on-disk
373/// resources/caches.
374/// \param PluginArgs name/value pairs passed to the plugin as custom options;
375/// they are opaque to the client.
376LLVM_ABI Expected<
377 std::pair<std::shared_ptr<ObjectStore>, std::shared_ptr<ActionCache>>>
379 StringRef PluginPath, StringRef OnDiskPath,
380 ArrayRef<std::pair<std::string, std::string>> PluginArgs);
381
382} // namespace cas
383} // namespace llvm
384
385#endif // LLVM_CAS_OBJECTSTORE_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Mark last scratch load
#define LLVM_ABI
Definition Compiler.h:215
static cl::opt< unsigned > SizeLimit("eif-limit", cl::init(6), cl::Hidden, cl::desc("Size limit in Hexagon early if-conversion"))
#define I(x, y, z)
Definition MD5.cpp:57
#define H(x, y, z)
Definition MD5.cpp:56
#define MAKE_CAS_HANDLE_CONSTRUCTOR(HandleKind)
Allow ObjectStore implementations to create internal handles.
static StringRef toStringRef(llcas_digest_t c_digest)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
This interface provides simple read-only access to a block of memory, and provides simple methods for...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
A cache from a key (that describes an action) to the result of performing that action.
Definition ActionCache.h:49
Context for CAS identifiers.
Definition CASID.h:28
Unique identifier for a CAS object.
Definition CASID.h:58
Handle to a loaded object in a ObjectStore instance.
Reference to an abstract hierarchical node, with data and references.
static ObjectProxy load(ObjectStore &CAS, ObjectRef Ref, ObjectHandle Node)
friend bool operator==(ObjectRef Ref, const ObjectProxy &Proxy)
LLVM_ABI std::unique_ptr< MemoryBuffer > getMemoryBuffer(StringRef Name="", bool RequiresNullTerminator=true) const
size_t getNumReferences() const
friend bool operator!=(const ObjectProxy &Proxy, ObjectRef Ref)
friend bool operator==(const ObjectProxy &Proxy, ObjectRef Ref)
Error exportDataToFile(StringRef Path) const
Exports the data of an object to a file path.
Error forEachReference(function_ref< Error(ObjectRef)> Callback) const
Visit each reference in order, returning an error from Callback to stop early.
StringRef getData() const
Get the content of the node. Valid as long as the CAS is valid.
friend bool operator!=(ObjectRef Ref, const ObjectProxy &Proxy)
CASID getReferenceID(size_t I) const
ObjectStore & getCAS() const
ObjectRef getRef() const
ObjectRef getReference(size_t I) const
Reference to an object in an ObjectStore instance.
Content-addressable storage for objects.
Definition ObjectStore.h:91
virtual void print(raw_ostream &) const
Print the ObjectStore internals for debugging purpose.
virtual Error validateObject(const CASID &ID)=0
Validate the underlying object referred by CASID.
virtual Expected< std::optional< uint64_t > > getStorageSize() const
Expected< ObjectRef > storeFromOpenFile(sys::fs::file_t FD, std::optional< sys::fs::file_status > Status=std::nullopt)
Default implementation reads FD and calls storeNode().
virtual Expected< bool > isMaterialized(ObjectRef Ref) const =0
virtual Expected< ObjectRef > store(ArrayRef< ObjectRef > Refs, ArrayRef< char > Data)=0
Store object into ObjectStore.
virtual ArrayRef< char > getData(ObjectHandle Node, bool RequiresNullTerminator=false) const =0
virtual Error exportDataToFile(ObjectHandle Node, StringRef Path) const
Exports the data of an object to a file path.
virtual CASID getID(ObjectRef Ref) const =0
Get an ID for Ref.
virtual Expected< std::optional< ObjectHandle > > loadIfExists(ObjectRef Ref)=0
Load the object referenced by Ref.
const CASContext & getContext() const
Get CASContext.
virtual Error setSizeLimit(std::optional< uint64_t > SizeLimit)
Set the size for limiting growth of on-disk storage.
virtual ~ObjectStore()=default
virtual Expected< ObjectRef > storeFromFile(StringRef Path)
Stores the data of a file into ObjectStore.
Expected< ObjectRef > storeFromString(ArrayRef< ObjectRef > Refs, StringRef String)
Store object from StringRef.
virtual Error pruneStorageData()
Prune local storage to reduce its size according to the desired size limit.
uint64_t readData(ObjectHandle Node, raw_ostream &OS, uint64_t Offset=0, uint64_t MaxBytes=-1ULL) const
Read the data from Data into OS.
virtual ObjectRef readRef(ObjectHandle Node, size_t I) const =0
ObjectStore(const CASContext &Context)
virtual Expected< CASID > parseID(StringRef ID)=0
Get a CASID from a ID, which should have been generated by CASID::print().
virtual uint64_t getDataSize(ObjectHandle Node) const =0
Get the size of some data.
virtual Expected< ObjectRef > storeFromOpenFileImpl(sys::fs::file_t FD, std::optional< sys::fs::file_status > Status)
Get ObjectRef from open file.
StringRef getDataString(ObjectHandle Node)
Get a lifetime-extended StringRef pointing at Data.
virtual Error validate(bool CheckHash) const =0
Validate the entire ObjectStore.
virtual size_t getNumRefs(ObjectHandle Node) const =0
virtual std::optional< ObjectRef > getReference(const CASID &ID) const =0
Get an existing reference to the object called ID.
friend class ObjectProxy
Definition ObjectStore.h:92
virtual Error forEachRef(ObjectHandle Node, function_ref< Error(ObjectRef)> Callback) const =0
Methods for handling objects.
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
unique_function is a type-erasing functor similar to std::function.
LLVM_ABI bool isOnDiskCASEnabled()
LLVM_ABI std::unique_ptr< ObjectStore > createInMemoryCAS()
Create an in memory CAS.
LLVM_ABI Expected< std::unique_ptr< ObjectStore > > createOnDiskCAS(const Twine &Path)
Create a persistent on-disk path at Path.
LLVM_ABI Expected< std::pair< std::shared_ptr< ObjectStore >, std::shared_ptr< ActionCache > > > createPluginCASDatabases(StringRef PluginPath, StringRef OnDiskPath, ArrayRef< std::pair< std::string, std::string > > PluginArgs)
Create ObjectStore and ActionCache instances backed by a plugin that implements the C API in "llvm-c/...
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
@ Offset
Definition DWP.cpp:578
ArrayRef< CharT > arrayRefFromStringRef(StringRef Input)
Construct an array ref of bytes from a string ref.
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
@ Other
Any other memory.
Definition ModRef.h:68
ArrayRef(const T &OneElt) -> ArrayRef< T >