LLVM 20.0.0git
Caching.cpp
Go to the documentation of this file.
1//===-Caching.cpp - LLVM Local File Cache ---------------------------------===//
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 implements the localCache function, which simplifies creating,
10// adding to, and querying a local file system cache. localCache takes care of
11// periodically pruning older files from the cache using a CachePruningPolicy.
12//
13//===----------------------------------------------------------------------===//
14
16#include "llvm/Support/Errc.h"
19#include "llvm/Support/Path.h"
20
21#if !defined(_MSC_VER) && !defined(__MINGW32__)
22#include <unistd.h>
23#else
24#include <io.h>
25#endif
26
27using namespace llvm;
28
30 const Twine &TempFilePrefixRef,
31 const Twine &CacheDirectoryPathRef,
32 AddBufferFn AddBuffer) {
33
34 // Create local copies which are safely captured-by-copy in lambdas
35 SmallString<64> CacheName, TempFilePrefix, CacheDirectoryPath;
36 CacheNameRef.toVector(CacheName);
37 TempFilePrefixRef.toVector(TempFilePrefix);
38 CacheDirectoryPathRef.toVector(CacheDirectoryPath);
39
40 return [=](unsigned Task, StringRef Key,
42 // This choice of file name allows the cache to be pruned (see pruneCache()
43 // in include/llvm/Support/CachePruning.h).
44 SmallString<64> EntryPath;
45 sys::path::append(EntryPath, CacheDirectoryPath, "llvmcache-" + Key);
46 // First, see if we have a cache hit.
47 SmallString<64> ResultPath;
49 Twine(EntryPath), sys::fs::OF_UpdateAtime, &ResultPath);
50 std::error_code EC;
51 if (FDOrErr) {
53 MemoryBuffer::getOpenFile(*FDOrErr, EntryPath,
54 /*FileSize=*/-1,
55 /*RequiresNullTerminator=*/false);
56 sys::fs::closeFile(*FDOrErr);
57 if (MBOrErr) {
58 AddBuffer(Task, ModuleName, std::move(*MBOrErr));
59 return AddStreamFn();
60 }
61 EC = MBOrErr.getError();
62 } else {
63 EC = errorToErrorCode(FDOrErr.takeError());
64 }
65
66 // On Windows we can fail to open a cache file with a permission denied
67 // error. This generally means that another process has requested to delete
68 // the file while it is still open, but it could also mean that another
69 // process has opened the file without the sharing permissions we need.
70 // Since the file is probably being deleted we handle it in the same way as
71 // if the file did not exist at all.
72 if (EC != errc::no_such_file_or_directory && EC != errc::permission_denied)
73 return createStringError(EC, Twine("Failed to open cache file ") +
74 EntryPath + ": " + EC.message() + "\n");
75
76 // This file stream is responsible for commiting the resulting file to the
77 // cache and calling AddBuffer to add it to the link.
78 struct CacheStream : CachedFileStream {
79 AddBufferFn AddBuffer;
80 sys::fs::TempFile TempFile;
81 std::string ModuleName;
82 unsigned Task;
83
84 CacheStream(std::unique_ptr<raw_pwrite_stream> OS, AddBufferFn AddBuffer,
85 sys::fs::TempFile TempFile, std::string EntryPath,
86 std::string ModuleName, unsigned Task)
87 : CachedFileStream(std::move(OS), std::move(EntryPath)),
88 AddBuffer(std::move(AddBuffer)), TempFile(std::move(TempFile)),
89 ModuleName(ModuleName), Task(Task) {}
90
91 ~CacheStream() {
92 // TODO: Manually commit rather than using non-trivial destructor,
93 // allowing to replace report_fatal_errors with a return Error.
94
95 // Make sure the stream is closed before committing it.
96 OS.reset();
97
98 // Open the file first to avoid racing with a cache pruner.
101 sys::fs::convertFDToNativeFile(TempFile.FD), ObjectPathName,
102 /*FileSize=*/-1, /*RequiresNullTerminator=*/false);
103 if (!MBOrErr)
104 report_fatal_error(Twine("Failed to open new cache file ") +
105 TempFile.TmpName + ": " +
106 MBOrErr.getError().message() + "\n");
107
108 // On POSIX systems, this will atomically replace the destination if
109 // it already exists. We try to emulate this on Windows, but this may
110 // fail with a permission denied error (for example, if the destination
111 // is currently opened by another process that does not give us the
112 // sharing permissions we need). Since the existing file should be
113 // semantically equivalent to the one we are trying to write, we give
114 // AddBuffer a copy of the bytes we wrote in that case. We do this
115 // instead of just using the existing file, because the pruner might
116 // delete the file before we get a chance to use it.
117 Error E = TempFile.keep(ObjectPathName);
118 E = handleErrors(std::move(E), [&](const ECError &E) -> Error {
119 std::error_code EC = E.convertToErrorCode();
120 if (EC != errc::permission_denied)
121 return errorCodeToError(EC);
122
123 auto MBCopy = MemoryBuffer::getMemBufferCopy((*MBOrErr)->getBuffer(),
124 ObjectPathName);
125 MBOrErr = std::move(MBCopy);
126
127 // FIXME: should we consume the discard error?
128 consumeError(TempFile.discard());
129
130 return Error::success();
131 });
132
133 if (E)
134 report_fatal_error(Twine("Failed to rename temporary file ") +
135 TempFile.TmpName + " to " + ObjectPathName + ": " +
136 toString(std::move(E)) + "\n");
137
138 AddBuffer(Task, ModuleName, std::move(*MBOrErr));
139 }
140 };
141
142 return [=](size_t Task, const Twine &ModuleName)
143 -> Expected<std::unique_ptr<CachedFileStream>> {
144 // Create the cache directory if not already done. Doing this lazily
145 // ensures the filesystem isn't mutated until the cache is.
146 if (std::error_code EC = sys::fs::create_directories(
147 CacheDirectoryPath, /*IgnoreExisting=*/true))
148 return createStringError(EC, Twine("can't create cache directory ") +
149 CacheDirectoryPath + ": " +
150 EC.message());
151
152 // Write to a temporary to avoid race condition
153 SmallString<64> TempFilenameModel;
154 sys::path::append(TempFilenameModel, CacheDirectoryPath,
155 TempFilePrefix + "-%%%%%%.tmp.o");
157 TempFilenameModel, sys::fs::owner_read | sys::fs::owner_write);
158 if (!Temp)
159 return createStringError(errc::io_error,
160 toString(Temp.takeError()) + ": " + CacheName +
161 ": Can't get a temporary file");
162
163 // This CacheStream will move the temporary file into the cache when done.
164 return std::make_unique<CacheStream>(
165 std::make_unique<raw_fd_ostream>(Temp->FD, /* ShouldClose */ false),
166 AddBuffer, std::move(*Temp), std::string(EntryPath), ModuleName.str(),
167 Task);
168 };
169 };
170}
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
raw_pwrite_stream & OS
This class wraps an output stream for a file.
Definition: Caching.h:28
This class wraps a std::error_code in a Error.
Definition: Error.h:1174
Represents either an error or a value T.
Definition: ErrorOr.h:56
std::error_code getError() const
Definition: ErrorOr.h:152
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:337
Tagged union holding either a T or a Error.
Definition: Error.h:481
Error takeError()
Take ownership of the stored error.
Definition: Error.h:608
static ErrorOr< std::unique_ptr< MemoryBuffer > > getOpenFile(sys::fs::file_t FD, const Twine &Filename, uint64_t FileSize, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Given an already-open file descriptor, read the file and return a MemoryBuffer.
static std::unique_ptr< MemoryBuffer > getMemBufferCopy(StringRef InputData, const Twine &BufferName="")
Open the specified memory range as a MemoryBuffer, copying the contents and taking ownership of it.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
void toVector(SmallVectorImpl< char > &Out) const
Append the concatenated string into the given SmallString or SmallVector.
Definition: Twine.cpp:32
Represents a temporary file.
Definition: FileSystem.h:847
Error keep(const Twine &Name)
Definition: Path.cpp:1255
static Expected< TempFile > create(const Twine &Model, unsigned Mode=all_read|all_write, OpenFlags ExtraFlags=OF_None)
This creates a temporary file with createUniqueFile and schedules it for deletion with sys::RemoveFil...
Definition: Path.cpp:1326
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
std::error_code closeFile(file_t &F)
Close the file object.
@ OF_UpdateAtime
Force files Atime to be updated on access.
Definition: FileSystem.h:782
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:968
file_t convertFDToNativeFile(int FD)
Converts from a Posix file descriptor number to a native file handle.
Definition: FileSystem.h:990
Expected< file_t > openNativeFileForRead(const Twine &Name, OpenFlags Flags=OF_None, SmallVectorImpl< char > *RealPath=nullptr)
Opens the file with the given name in a read-only mode, returning its open file descriptor.
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition: Path.cpp:457
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
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:64
Error handleErrors(Error E, HandlerTs &&... Hs)
Pass the ErrorInfo(s) contained in E to their respective handlers.
Definition: Error.h:954
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:42
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1286
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:167
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:111
std::error_code errorToErrorCode(Error Err)
Helper for converting an ECError to a std::error_code.
Definition: Error.cpp:117
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1069
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) {})
Create a local file system cache which uses the given cache name, temporary file prefix,...
Definition: Caching.cpp:29