[llvm] [Support] mmap when possible in getSTDIN. (PR #162013)
via llvm-commits
llvm-commits at lists.llvm.org
Sun Oct 5 06:23:11 PDT 2025
llvmbot wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-llvm-support
Author: None (aokblast)
<details>
<summary>Changes</summary>
When stdin is executed like ./prog < file, we are able to mmap the buffer so that we can reduce the total memory usage if we try to open a large file.
---
Full diff: https://github.com/llvm/llvm-project/pull/162013.diff
1 Files Affected:
- (modified) llvm/lib/Support/MemoryBuffer.cpp (+21)
``````````diff
diff --git a/llvm/lib/Support/MemoryBuffer.cpp b/llvm/lib/Support/MemoryBuffer.cpp
index 1c4645ad83641..97ea5f205b0ee 100644
--- a/llvm/lib/Support/MemoryBuffer.cpp
+++ b/llvm/lib/Support/MemoryBuffer.cpp
@@ -573,6 +573,27 @@ ErrorOr<std::unique_ptr<MemoryBuffer>> MemoryBuffer::getSTDIN() {
// FIXME: That isn't necessarily true, we should try to mmap stdin and
// fallback if it fails.
sys::ChangeStdinMode(sys::fs::OF_Text);
+ std::error_code EC;
+ sys::fs::file_type Type;
+ sys::fs::file_status Status;
+ EC = sys::fs::status(sys::fs::getStdinHandle(), Status);
+ if (EC)
+ return EC;
+
+ Type = Status.type();
+
+ /*
+ * If the FD is regular file or block file,
+ * we try to create a mmap buffer first.
+ * If failed, rollback to read and copy.
+ */
+ if (Type == sys::fs::file_type::regular_file ||
+ Type == sys::fs::file_type::block_file) {
+ std::unique_ptr<MemoryBuffer> Result(new MemoryBufferMMapFile<MemoryBuffer>(
+ false, sys::fs::getStdinHandle(), Status.getSize(), 0, EC));
+ if (!EC)
+ return std::move(Result);
+ }
return getMemoryBufferForStream(sys::fs::getStdinHandle(), "<stdin>");
}
``````````
</details>
https://github.com/llvm/llvm-project/pull/162013
More information about the llvm-commits
mailing list