blob: 7b3fc020d6e95a0a4aaee12b7d4e44f6d1500ed8 [file] [log] [blame]
Mehdi Aminiadc0e262016-08-23 21:30:12 +00001//===-Caching.cpp - LLVM Link Time Optimizer Cache Handling ---------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Mehdi Aminiadc0e262016-08-23 21:30:12 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Caching for ThinLTO.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/LTO/Caching.h"
Mehdi Aminiadc0e262016-08-23 21:30:12 +000014#include "llvm/ADT/StringExtras.h"
Peter Collingbourned7860472017-03-20 18:19:41 +000015#include "llvm/Support/Errc.h"
Peter Collingbourne80186a52016-09-23 21:33:43 +000016#include "llvm/Support/MemoryBuffer.h"
Mehdi Aminiadc0e262016-08-23 21:30:12 +000017#include "llvm/Support/Path.h"
Bob Haarmana17bd1212017-11-10 17:08:21 +000018#include "llvm/Support/Process.h"
Mehdi Aminiadc0e262016-08-23 21:30:12 +000019#include "llvm/Support/raw_ostream.h"
20
Andrew Ng089303d2018-07-04 14:17:10 +000021#if !defined(_MSC_VER) && !defined(__MINGW32__)
22#include <unistd.h>
23#else
24#include <io.h>
25#endif
26
Mehdi Aminiadc0e262016-08-23 21:30:12 +000027using namespace llvm;
28using namespace llvm::lto;
29
Peter Collingbourneab76a192017-03-02 02:02:38 +000030Expected<NativeObjectCache> lto::localCache(StringRef CacheDirectoryPath,
Peter Collingbourne128423f2017-03-17 00:34:07 +000031 AddBufferFn AddBuffer) {
Peter Collingbourneab76a192017-03-02 02:02:38 +000032 if (std::error_code EC = sys::fs::create_directories(CacheDirectoryPath))
33 return errorCodeToError(EC);
34
Peter Collingbourne80186a52016-09-23 21:33:43 +000035 return [=](unsigned Task, StringRef Key) -> AddStreamFn {
Peter Collingbourne25a17ba2017-03-20 16:41:57 +000036 // This choice of file name allows the cache to be pruned (see pruneCache()
37 // in include/llvm/Support/CachePruning.h).
Peter Collingbourne80186a52016-09-23 21:33:43 +000038 SmallString<64> EntryPath;
Peter Collingbourne25a17ba2017-03-20 16:41:57 +000039 sys::path::append(EntryPath, CacheDirectoryPath, "llvmcache-" + Key);
40 // First, see if we have a cache hit.
Andrew Ng089303d2018-07-04 14:17:10 +000041 int FD;
42 SmallString<64> ResultPath;
43 std::error_code EC = sys::fs::openFileForRead(
44 Twine(EntryPath), FD, sys::fs::OF_UpdateAtime, &ResultPath);
45 if (!EC) {
46 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
Reid Klecknercc418a32019-07-10 00:34:13 +000047 MemoryBuffer::getOpenFile(sys::fs::convertFDToNativeFile(FD),
48 EntryPath,
Andrew Ng089303d2018-07-04 14:17:10 +000049 /*FileSize*/ -1,
50 /*RequiresNullTerminator*/ false);
51 close(FD);
52 if (MBOrErr) {
53 AddBuffer(Task, std::move(*MBOrErr));
54 return AddStreamFn();
55 }
56 EC = MBOrErr.getError();
Peter Collingbourne80186a52016-09-23 21:33:43 +000057 }
Mehdi Aminiadc0e262016-08-23 21:30:12 +000058
Peter Collingbourne881ba102018-06-13 18:03:14 +000059 // On Windows we can fail to open a cache file with a permission denied
60 // error. This generally means that another process has requested to delete
61 // the file while it is still open, but it could also mean that another
62 // process has opened the file without the sharing permissions we need.
63 // Since the file is probably being deleted we handle it in the same way as
64 // if the file did not exist at all.
Andrew Ng089303d2018-07-04 14:17:10 +000065 if (EC != errc::no_such_file_or_directory && EC != errc::permission_denied)
Peter Collingbourne128423f2017-03-17 00:34:07 +000066 report_fatal_error(Twine("Failed to open cache file ") + EntryPath +
Andrew Ng089303d2018-07-04 14:17:10 +000067 ": " + EC.message() + "\n");
Peter Collingbourne128423f2017-03-17 00:34:07 +000068
Peter Collingbourne80186a52016-09-23 21:33:43 +000069 // This native object stream is responsible for commiting the resulting
Peter Collingbourne128423f2017-03-17 00:34:07 +000070 // file to the cache and calling AddBuffer to add it to the link.
Peter Collingbourne80186a52016-09-23 21:33:43 +000071 struct CacheStream : NativeObjectStream {
Peter Collingbourne128423f2017-03-17 00:34:07 +000072 AddBufferFn AddBuffer;
Rafael Espindolaa17fca02017-11-15 19:09:22 +000073 sys::fs::TempFile TempFile;
Peter Collingbourne80186a52016-09-23 21:33:43 +000074 std::string EntryPath;
75 unsigned Task;
Mehdi Aminiadc0e262016-08-23 21:30:12 +000076
Peter Collingbourne128423f2017-03-17 00:34:07 +000077 CacheStream(std::unique_ptr<raw_pwrite_stream> OS, AddBufferFn AddBuffer,
Rafael Espindolaa17fca02017-11-15 19:09:22 +000078 sys::fs::TempFile TempFile, std::string EntryPath,
Peter Collingbourne80186a52016-09-23 21:33:43 +000079 unsigned Task)
Peter Collingbourne128423f2017-03-17 00:34:07 +000080 : NativeObjectStream(std::move(OS)), AddBuffer(std::move(AddBuffer)),
Rafael Espindolaa17fca02017-11-15 19:09:22 +000081 TempFile(std::move(TempFile)), EntryPath(std::move(EntryPath)),
82 Task(Task) {}
Peter Collingbourne80186a52016-09-23 21:33:43 +000083
84 ~CacheStream() {
Rafael Espindolaa17fca02017-11-15 19:09:22 +000085 // Make sure the stream is closed before committing it.
Peter Collingbourne80186a52016-09-23 21:33:43 +000086 OS.reset();
Peter Collingbourned0e9c162017-09-05 19:51:38 +000087
Peter Collingbourned0e9c162017-09-05 19:51:38 +000088 // Open the file first to avoid racing with a cache pruner.
89 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
Reid Klecknercc418a32019-07-10 00:34:13 +000090 MemoryBuffer::getOpenFile(
91 sys::fs::convertFDToNativeFile(TempFile.FD), TempFile.TmpName,
92 /*FileSize=*/-1, /*RequiresNullTerminator=*/false);
Peter Collingbourned5fc37c2017-10-03 00:44:21 +000093 if (!MBOrErr)
94 report_fatal_error(Twine("Failed to open new cache file ") +
Rafael Espindolaa17fca02017-11-15 19:09:22 +000095 TempFile.TmpName + ": " +
Peter Collingbourned5fc37c2017-10-03 00:44:21 +000096 MBOrErr.getError().message() + "\n");
Peter Collingbourned0e9c162017-09-05 19:51:38 +000097
Bob Haarman847a77f2017-11-16 01:16:52 +000098 // On POSIX systems, this will atomically replace the destination if
99 // it already exists. We try to emulate this on Windows, but this may
100 // fail with a permission denied error (for example, if the destination
101 // is currently opened by another process that does not give us the
102 // sharing permissions we need). Since the existing file should be
103 // semantically equivalent to the one we are trying to write, we give
104 // AddBuffer a copy of the bytes we wrote in that case. We do this
105 // instead of just using the existing file, because the pruner might
106 // delete the file before we get a chance to use it.
Rafael Espindolaa17fca02017-11-15 19:09:22 +0000107 Error E = TempFile.keep(EntryPath);
108 E = handleErrors(std::move(E), [&](const ECError &E) -> Error {
109 std::error_code EC = E.convertToErrorCode();
110 if (EC != errc::permission_denied)
111 return errorCodeToError(EC);
112
113 auto MBCopy = MemoryBuffer::getMemBufferCopy((*MBOrErr)->getBuffer(),
114 EntryPath);
Bob Haarmana17bd1212017-11-10 17:08:21 +0000115 MBOrErr = std::move(MBCopy);
Rafael Espindolaa17fca02017-11-15 19:09:22 +0000116
117 // FIXME: should we consume the discard error?
118 consumeError(TempFile.discard());
119
120 return Error::success();
121 });
122
123 if (E)
Peter Collingbourned0e9c162017-09-05 19:51:38 +0000124 report_fatal_error(Twine("Failed to rename temporary file ") +
Rafael Espindolaa17fca02017-11-15 19:09:22 +0000125 TempFile.TmpName + " to " + EntryPath + ": " +
126 toString(std::move(E)) + "\n");
Peter Collingbourned0e9c162017-09-05 19:51:38 +0000127
Teresa Johnsona344fd32018-02-20 20:21:53 +0000128 AddBuffer(Task, std::move(*MBOrErr));
Peter Collingbourne80186a52016-09-23 21:33:43 +0000129 }
130 };
131
132 return [=](size_t Task) -> std::unique_ptr<NativeObjectStream> {
133 // Write to a temporary to avoid race condition
Rafael Espindolaa17fca02017-11-15 19:09:22 +0000134 SmallString<64> TempFilenameModel;
Peter Collingbournecb46a6b2017-03-16 18:20:06 +0000135 sys::path::append(TempFilenameModel, CacheDirectoryPath, "Thin-%%%%%%.tmp.o");
Rafael Espindolaa17fca02017-11-15 19:09:22 +0000136 Expected<sys::fs::TempFile> Temp = sys::fs::TempFile::create(
137 TempFilenameModel, sys::fs::owner_read | sys::fs::owner_write);
138 if (!Temp) {
139 errs() << "Error: " << toString(Temp.takeError()) << "\n";
Peter Collingbourne80186a52016-09-23 21:33:43 +0000140 report_fatal_error("ThinLTO: Can't get a temporary file");
141 }
142
143 // This CacheStream will move the temporary file into the cache when done.
Peter Collingbournea638fe02016-09-23 23:23:23 +0000144 return llvm::make_unique<CacheStream>(
Rafael Espindolaa17fca02017-11-15 19:09:22 +0000145 llvm::make_unique<raw_fd_ostream>(Temp->FD, /* ShouldClose */ false),
146 AddBuffer, std::move(*Temp), EntryPath.str(), Task);
Peter Collingbourne80186a52016-09-23 21:33:43 +0000147 };
148 };
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000149}