Skip to content

Commit fdf0d85

Browse files
committed
[Support] mmap when possible in getSTDIN.
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.
1 parent 5401210 commit fdf0d85

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

llvm/lib/Support/MemoryBuffer.cpp

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -573,6 +573,27 @@ ErrorOr<std::unique_ptr<MemoryBuffer>> MemoryBuffer::getSTDIN() {
573573
// FIXME: That isn't necessarily true, we should try to mmap stdin and
574574
// fallback if it fails.
575575
sys::ChangeStdinMode(sys::fs::OF_Text);
576+
std::error_code EC;
577+
sys::fs::file_type Type;
578+
sys::fs::file_status Status;
579+
EC = sys::fs::status(sys::fs::getStdinHandle(), Status);
580+
if (EC)
581+
return EC;
582+
583+
Type = Status.type();
584+
585+
/*
586+
* If the FD is regular file or block file,
587+
* we try to create a mmap buffer first.
588+
* If failed, rollback to read and copy.
589+
*/
590+
if (Type == sys::fs::file_type::regular_file ||
591+
Type == sys::fs::file_type::block_file) {
592+
std::unique_ptr<MemoryBuffer> Result(new MemoryBufferMMapFile<MemoryBuffer>(
593+
false, sys::fs::getStdinHandle(), Status.getSize(), 0, EC));
594+
if (!EC && *Result->getBufferEnd() == '\0')
595+
return std::move(Result);
596+
}
576597

577598
return getMemoryBufferForStream(sys::fs::getStdinHandle(), "<stdin>");
578599
}

0 commit comments

Comments
 (0)