LLVM 24.0.0git
Caching.h
Go to the documentation of this file.
1//===- Caching.h - LLVM Local File Cache ------------------------*- 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// This file defines the CachedFileStream and the localCache function, which
10// simplifies caching files on the local filesystem in a directory whose
11// contents are managed by a CachePruningPolicy.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_SUPPORT_CACHING_H
16#define LLVM_SUPPORT_CACHING_H
17
19#include "llvm/Support/Error.h"
21
22namespace llvm {
23
24/// This class wraps an output stream for a file. Most clients should just be
25/// able to return an instance of this base class from the stream callback, but
26/// if a client needs to perform some action after the stream is written to,
27/// that can be done by deriving from this class and overriding the destructor
28/// or the commit() method.
29/// Before destruction of this class, either commit() or abort() must be called.
31public:
32 CachedFileStream(std::unique_ptr<raw_pwrite_stream> OS,
33 std::string OSPath = "")
34 : OS(std::move(OS)), ObjectPathName(OSPath) {}
35
36 /// Must be called after the writes to OS have been completed successfully
37 /// but before the CachedFileStream object is destroyed.
38 virtual Error commit() {
39 if (Committed)
40 return createStringError(make_error_code(std::errc::invalid_argument),
41 Twine("CacheStream already committed."));
42 if (Aborted)
43 return createStringError(make_error_code(std::errc::invalid_argument),
44 "CacheStream already aborted.");
45 Committed = true;
46
47 return Error::success();
48 }
49
50 virtual Error commit(std::unique_ptr<MemoryBuffer> MemBuf) {
51 return commit();
52 }
53
54 /// Must be called if the file was not committed before its destroyed (for
55 /// example if some writes didn't complete).
56 virtual Error abort() {
57 if (Committed)
58 return createStringError(make_error_code(std::errc::invalid_argument),
59 "CacheStream already committed.");
60
61 OS.reset();
62 Aborted = true;
63 return Error::success();
64 }
65
66 bool Committed = false;
67 bool Aborted = false;
68 std::unique_ptr<raw_pwrite_stream> OS;
69 std::string ObjectPathName;
71 if (!Committed && !Aborted)
72 report_fatal_error("CachedFileStream was not committed or aborted.\n");
73 }
74};
75
76/// This type defines the callback to add a file that is generated on the fly.
77///
78/// Stream callbacks must be thread safe.
79using AddStreamFn = std::function<Expected<std::unique_ptr<CachedFileStream>>(
80 unsigned Task, const Twine &ModuleName)>;
81
82/// This is a callable that manages file caching operations. It accepts a task
83/// ID \p Task, a unique key \p Key, and a module name \p ModuleName, and
84/// returns AddStreamFn(). This function determines whether a cache hit or miss
85/// occurs and handles the appropriate actions.
86using FileCacheFunction = std::function<Expected<AddStreamFn>(
87 unsigned Task, StringRef Key, const Twine &ModuleName)>;
88
89/// This type represents a file cache system that manages caching of files.
90/// It encapsulates a caching function and the directory path where the cache is
91/// stored. To request an item from the cache, pass a unique string as the Key.
92/// For hits, the cached file will be added to the link and this function will
93/// return AddStreamFn(). For misses, the cache will return a stream callback
94/// which must be called at most once to produce content for the stream. The
95/// file stream produced by the stream callback will add the file to the link
96/// after the stream is written to. ModuleName is the unique module identifier
97/// for the bitcode module the cache is being checked for.
98///
99/// Clients generally look like this:
100///
101/// if (AddStreamFn AddStream = Cache(Task, Key, ModuleName))
102/// ProduceContent(AddStream);
103///
104/// CacheDirectoryPath stores the directory path where cached files are kept.
105struct FileCache {
106 FileCache(FileCacheFunction CacheFn, const std::string &DirectoryPath)
107 : CacheFunction(std::move(CacheFn)), CacheDirectoryPath(DirectoryPath) {}
108 FileCache() = default;
109
111 const Twine &ModuleName) {
112 assert(isValid() && "Invalid cache function");
113 return CacheFunction(Task, Key, ModuleName);
114 }
115 const std::string &getCacheDirectoryPath() const {
116 return CacheDirectoryPath;
117 }
118 bool isValid() const { return static_cast<bool>(CacheFunction); }
119
120private:
121 FileCacheFunction CacheFunction = nullptr;
122 std::string CacheDirectoryPath;
123};
124
125/// This type defines the callback to add a pre-existing file (e.g. in a cache).
126///
127/// Buffer callbacks must be thread safe.
128using AddBufferFn = std::function<void(unsigned Task, const Twine &ModuleName,
129 std::unique_ptr<MemoryBuffer> MB)>;
130
131/// Create a local file system cache which uses the given cache name, temporary
132/// file prefix, cache directory and file callback. This function does not
133/// immediately create the cache directory if it does not yet exist; this is
134/// done lazily the first time a file is added. The cache name appears in error
135/// messages for errors during caching. The temporary file prefix is used in the
136/// temporary file naming scheme used when writing files atomically.
137/// If \p CacheFileRename is true, move or rename an existing file into the
138/// cache instead of writing via a temporary stream.
140 const Twine &CacheNameRef, const Twine &TempFilePrefixRef,
141 const Twine &CacheDirectoryPathRef,
142 AddBufferFn AddBuffer = [](size_t Task, const Twine &ModuleName,
143 std::unique_ptr<MemoryBuffer> MB) {},
144 bool CacheFileRename = false);
145} // namespace llvm
146
147#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_ABI
Definition Compiler.h:215
CachedFileStream(std::unique_ptr< raw_pwrite_stream > OS, std::string OSPath="")
Definition Caching.h:32
virtual Error abort()
Must be called if the file was not committed before its destroyed (for example if some writes didn't ...
Definition Caching.h:56
std::string ObjectPathName
Definition Caching.h:69
virtual ~CachedFileStream()
Definition Caching.h:70
std::unique_ptr< raw_pwrite_stream > OS
Definition Caching.h:68
virtual Error commit(std::unique_ptr< MemoryBuffer > MemBuf)
Definition Caching.h:50
virtual Error commit()
Must be called after the writes to OS have been completed successfully but before the CachedFileStrea...
Definition Caching.h:38
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
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
This is an optimization pass for GlobalISel generic memory operations.
std::error_code make_error_code(BitcodeError E)
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
std::function< Expected< AddStreamFn >( unsigned Task, StringRef Key, const Twine &ModuleName)> FileCacheFunction
This is a callable that manages file caching operations.
Definition Caching.h:86
std::function< void(unsigned Task, const Twine &ModuleName, std::unique_ptr< MemoryBuffer > MB)> AddBufferFn
This type defines the callback to add a pre-existing file (e.g.
Definition Caching.h:128
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
LLVM_ABI Expected< FileCache > localCache(const Twine &CacheNameRef, const Twine &TempFilePrefixRef, const Twine &CacheDirectoryPathRef, AddBufferFn AddBuffer=[](size_t Task, const Twine &ModuleName, std::unique_ptr< MemoryBuffer > MB) {}, bool CacheFileRename=false)
Create a local file system cache which uses the given cache name, temporary file prefix,...
Definition Caching.cpp:30
std::function< Expected< std::unique_ptr< CachedFileStream > >( unsigned Task, const Twine &ModuleName)> AddStreamFn
This type defines the callback to add a file that is generated on the fly.
Definition Caching.h:79
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
Expected< AddStreamFn > operator()(unsigned Task, StringRef Key, const Twine &ModuleName)
Definition Caching.h:110
FileCache()=default
const std::string & getCacheDirectoryPath() const
Definition Caching.h:115
bool isValid() const
Definition Caching.h:118
FileCache(FileCacheFunction CacheFn, const std::string &DirectoryPath)
Definition Caching.h:106