LLVM 22.0.0git
OnDiskKeyValueDB.cpp
Go to the documentation of this file.
1//===- OnDiskKeyValueDB.cpp -------------------------------------*- 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 implements OnDiskKeyValueDB, an ondisk key value database.
11///
12/// The KeyValue database file is named `actions.<version>` inside the CAS
13/// directory. The database stores a mapping between a fixed-sized key and a
14/// fixed-sized value, where the size of key and value can be configured when
15/// opening the database.
16///
17//
18//===----------------------------------------------------------------------===//
19
21#include "OnDiskCommon.h"
26#include "llvm/Support/Errc.h"
27#include "llvm/Support/Path.h"
28
29using namespace llvm;
30using namespace llvm::cas;
31using namespace llvm::cas::ondisk;
32
33static constexpr StringLiteral ActionCacheFile = "actions.";
34
37 if (LLVM_UNLIKELY(Value.size() != ValueSize))
39 "expected value size of " + itostr(ValueSize) +
40 ", got: " + itostr(Value.size()));
41 assert(Value.size() == ValueSize);
42 auto ActionP = Cache.insertLazy(
43 Key, [&](FileOffset TentativeOffset,
44 OnDiskTrieRawHashMap::ValueProxy TentativeValue) {
45 assert(TentativeValue.Data.size() == ValueSize);
46 llvm::copy(Value, TentativeValue.Data.data());
47 });
48 if (LLVM_UNLIKELY(!ActionP))
49 return ActionP.takeError();
50 return (*ActionP)->Data;
51}
52
55 // Check the result cache.
56 OnDiskTrieRawHashMap::ConstOnDiskPtr ActionP = Cache.find(Key);
57 if (ActionP) {
58 assert(isAddrAligned(Align(8), ActionP->Data.data()));
59 return ActionP->Data;
60 }
61 if (!UnifiedCache || !UnifiedCache->UpstreamKVDB)
62 return std::nullopt;
63
64 // Try to fault in from upstream.
65 return UnifiedCache->faultInFromUpstreamKV(Key);
66}
67
69OnDiskKeyValueDB::open(StringRef Path, StringRef HashName, unsigned KeySize,
70 StringRef ValueName, size_t ValueSize,
71 UnifiedOnDiskCache *Cache) {
72 if (std::error_code EC = sys::fs::create_directories(Path))
73 return createFileError(Path, EC);
74
75 SmallString<256> CachePath(Path);
77 constexpr uint64_t MB = 1024ull * 1024ull;
78 constexpr uint64_t GB = 1024ull * 1024ull * 1024ull;
79
80 uint64_t MaxFileSize = GB;
81 auto CustomSize = getOverriddenMaxMappingSize();
82 if (!CustomSize)
83 return CustomSize.takeError();
84 if (*CustomSize)
85 MaxFileSize = **CustomSize;
86
87 std::optional<OnDiskTrieRawHashMap> ActionCache;
89 CachePath,
90 "llvm.actioncache[" + HashName + "->" + ValueName + "]",
91 KeySize * 8,
92 /*DataSize=*/ValueSize, MaxFileSize, /*MinFileSize=*/MB)
93 .moveInto(ActionCache))
94 return std::move(E);
95
96 return std::unique_ptr<OnDiskKeyValueDB>(
97 new OnDiskKeyValueDB(ValueSize, std::move(*ActionCache), Cache));
98}
99
101 if (UnifiedCache && UnifiedCache->UpstreamKVDB) {
102 if (auto E = UnifiedCache->UpstreamKVDB->validate(CheckValue))
103 return E;
104 }
105 return Cache.validate(
106 [&](FileOffset Offset,
108 auto formatError = [&](Twine Msg) {
109 return createStringError(
111 "bad cache value at 0x" +
112 utohexstr((unsigned)Offset.get(), /*LowerCase=*/true) + ": " +
113 Msg.str());
114 };
115
116 if (Record.Data.size() != ValueSize)
117 return formatError("wrong cache value size");
118 if (!isAddrAligned(Align(8), Record.Data.data()))
119 return formatError("wrong cache value alignment");
120 if (CheckValue)
121 return CheckValue(Offset, Record.Data);
122 return Error::success();
123 });
124}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_UNLIKELY(EXPR)
Definition Compiler.h:336
static constexpr StringLiteral ActionCacheFile
This declares OnDiskKeyValueDB, a key value storage database of fixed size key and value.
This file contains some functions that are useful when dealing with strings.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition ArrayRef.h:143
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
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
Definition StringRef.h:854
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM Value Representation.
Definition Value.h:75
A cache from a key (that describes an action) to the result of performing that action.
Definition ActionCache.h:49
FileOffset is a wrapper around uint64_t to represent the offset of data from the beginning of the fil...
Definition FileOffset.h:24
static Expected< OnDiskTrieRawHashMap > create(const Twine &Path, const Twine &TrieName, size_t NumHashBits, uint64_t DataSize, uint64_t MaxFileSize, std::optional< uint64_t > NewFileInitialSize, std::optional< size_t > NewTableNumRootBits=std::nullopt, std::optional< size_t > NewTableNumSubtrieBits=std::nullopt)
Gets or creates a file at Path with a hash-mapped trie named TrieName.
static Expected< std::unique_ptr< OnDiskKeyValueDB > > open(StringRef Path, StringRef HashName, unsigned KeySize, StringRef ValueName, size_t ValueSize, UnifiedOnDiskCache *UnifiedCache=nullptr)
Open the on-disk store from a directory.
Expected< ArrayRef< char > > put(ArrayRef< uint8_t > Key, ArrayRef< char > Value)
Associate a value with a key.
Expected< std::optional< ArrayRef< char > > > get(ArrayRef< uint8_t > Key)
function_ref< Error(FileOffset Offset, ArrayRef< char > Data)> CheckValueT
Error validate(CheckValueT CheckValue) const
Validate the storage with a callback CheckValue to check the stored value.
A unified CAS nodes and key-value database, using on-disk storage for both.
constexpr StringLiteral CASFormatVersion
The version for all the ondisk database files.
Expected< std::optional< uint64_t > > getOverriddenMaxMappingSize()
Retrieves an overridden maximum mapping size for CAS files, if any, speicified by LLVM_CAS_MAX_MAPPIN...
LLVM_ABI std::error_code create_directories(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create all the non-existent directories in path.
Definition Path.cpp:967
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition Path.cpp:456
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:477
StringMapEntry< Value * > ValueName
Definition Value.h:56
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
Definition Error.h:1399
std::string utohexstr(uint64_t X, bool LowerCase=false, unsigned Width=0)
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1305
@ illegal_byte_sequence
Definition Errc.h:52
@ invalid_argument
Definition Errc.h:56
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1835
std::string itostr(int64_t X)
bool isAddrAligned(Align Lhs, const void *Addr)
Checks that Addr is a multiple of the alignment.
Definition Alignment.h:139
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Const value proxy to access the records stored in TrieRawHashMap.
Value proxy to access the records stored in TrieRawHashMap.