15#include "llvm/Config/config.h"
33#if defined(HAVE_FCNTL_H)
37#if defined(HAVE_UNISTD_H)
41#if defined(__CYGWIN__)
48# define STDIN_FILENO 0
51# define STDOUT_FILENO 1
54# define STDERR_FILENO 2
80 assert(OutBufCur == OutBufStart &&
81 "raw_ostream destructor called with non-empty buffer!");
83 if (BufferMode == BufferKind::InternalBuffer)
84 delete [] OutBufStart;
108void raw_ostream::SetBufferAndMode(
char *BufferStart,
size_t Size,
110 assert(((Mode == BufferKind::Unbuffered && !BufferStart &&
Size == 0) ||
111 (Mode != BufferKind::Unbuffered && BufferStart &&
Size != 0)) &&
112 "stream must be unbuffered or have at least one byte");
117 if (BufferMode == BufferKind::InternalBuffer)
118 delete [] OutBufStart;
119 OutBufStart = BufferStart;
120 OutBufEnd = OutBufStart+
Size;
121 OutBufCur = OutBufStart;
124 assert(OutBufStart <= OutBufEnd &&
"Invalid size!");
171 bool UseHexEscapes) {
172 for (
unsigned char c : Str) {
175 *
this <<
'\\' <<
'\\';
178 *
this <<
'\\' <<
't';
181 *
this <<
'\\' <<
'n';
184 *
this <<
'\\' <<
'"';
194 *
this <<
'\\' <<
'x';
195 *
this << hexdigit((c >> 4) & 0xF);
196 *
this << hexdigit((c >> 0) & 0xF);
200 *
this <<
char(
'0' + ((c >> 6) & 7));
201 *
this <<
char(
'0' + ((c >> 3) & 7));
202 *
this <<
char(
'0' + ((c >> 0) & 7));
220void raw_ostream::flush_nonempty() {
221 assert(OutBufCur > OutBufStart &&
"Invalid call to flush_nonempty.");
222 size_t Length = OutBufCur - OutBufStart;
223 OutBufCur = OutBufStart;
224 write_impl(OutBufStart,
Length);
231 if (BufferMode == BufferKind::Unbuffered) {
232 write_impl(
reinterpret_cast<char *
>(&
C), 1);
251 if (BufferMode == BufferKind::Unbuffered) {
260 size_t NumBytes = OutBufEnd - OutBufCur;
266 assert(NumBytes != 0 &&
"undefined behavior");
267 size_t BytesToWrite =
Size - (
Size % NumBytes);
268 write_impl(
Ptr, BytesToWrite);
269 size_t BytesRemaining =
Size - BytesToWrite;
270 if (BytesRemaining >
size_t(OutBufEnd - OutBufCur)) {
272 return write(
Ptr + BytesToWrite, BytesRemaining);
274 copy_to_buffer(
Ptr + BytesToWrite, BytesRemaining);
280 copy_to_buffer(
Ptr, NumBytes);
290void raw_ostream::copy_to_buffer(
const char *
Ptr,
size_t Size) {
291 assert(
Size <=
size_t(OutBufEnd - OutBufCur) &&
"Buffer overrun!");
296 case 4: OutBufCur[3] =
Ptr[3]; [[fallthrough]];
297 case 3: OutBufCur[2] =
Ptr[2]; [[fallthrough]];
298 case 2: OutBufCur[1] =
Ptr[1]; [[fallthrough]];
299 case 1: OutBufCur[0] =
Ptr[0]; [[fallthrough]];
313 size_t NextBufferSize = 127;
314 size_t BufferBytesLeft = OutBufEnd - OutBufCur;
315 if (BufferBytesLeft > 3) {
316 size_t BytesUsed = Fmt.
print(OutBufCur, BufferBytesLeft);
319 if (BytesUsed <= BufferBytesLeft) {
320 OutBufCur += BytesUsed;
326 NextBufferSize = BytesUsed;
335 V.resize(NextBufferSize);
338 size_t BytesUsed = Fmt.
print(V.data(), NextBufferSize);
341 if (BytesUsed <= NextBufferSize)
342 return write(V.data(), BytesUsed);
345 assert(BytesUsed > NextBufferSize &&
"Didn't grow buffer!?");
346 NextBufferSize = BytesUsed;
356 unsigned LeftIndent = 0;
357 unsigned RightIndent = 0;
358 const ssize_t Difference = FS.Width - FS.Str.size();
359 if (Difference > 0) {
360 switch (FS.Justify) {
364 RightIndent = Difference;
367 LeftIndent = Difference;
370 LeftIndent = Difference / 2;
371 RightIndent = Difference - LeftIndent;
384 if (FN.Upper && FN.HexPrefix)
386 else if (FN.Upper && !FN.HexPrefix)
388 else if (!FN.Upper && FN.HexPrefix)
397 if (Buffer.
size() < FN.Width)
405 if (FB.Bytes.
empty())
408 size_t LineIndex = 0;
409 auto Bytes = FB.Bytes;
410 const size_t Size = Bytes.size();
413 if (FB.FirstByteOffset) {
417 size_t Lines =
Size / FB.NumPerLine;
418 uint64_t MaxOffset = *FB.FirstByteOffset + Lines * FB.NumPerLine;
422 OffsetWidth = std::max<uint64_t>(4,
llvm::alignTo(Power, 4) / 4);
426 unsigned NumByteGroups =
427 alignTo(FB.NumPerLine, FB.ByteGroupSize) / FB.ByteGroupSize;
428 unsigned BlockCharWidth = FB.NumPerLine * 2 + NumByteGroups - 1;
430 while (!Bytes.empty()) {
433 if (FB.FirstByteOffset) {
439 auto Line = Bytes.take_front(FB.NumPerLine);
441 size_t CharsPrinted = 0;
443 for (
size_t I = 0;
I < Line.size(); ++
I, CharsPrinted += 2) {
444 if (
I && (
I % FB.ByteGroupSize) == 0) {
454 assert(BlockCharWidth >= CharsPrinted);
455 indent(BlockCharWidth - CharsPrinted + 2);
461 *this << static_cast<char>(Byte);
468 Bytes = Bytes.drop_front(Line.size());
469 LineIndex += Line.size();
470 if (LineIndex <
Size)
478 static const char Chars[] = {
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
479 C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
480 C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
481 C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
482 C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C};
485 if (NumChars < std::size(Chars))
486 return OS.
write(Chars, NumChars);
489 unsigned NumToWrite = std::min(NumChars, (
unsigned)std::size(Chars) - 1);
491 NumChars -= NumToWrite;
498 return write_padding<' '>(*
this, NumSpaces);
503 return write_padding<'\0'>(*
this, NumZeros);
506bool raw_ostream::prepare_colors() {
523 if (!prepare_colors())
526 const char *colorcode =
531 write(colorcode, strlen(colorcode));
536 if (!prepare_colors())
540 write(colorcode, strlen(colorcode));
545 if (!prepare_colors())
549 write(colorcode, strlen(colorcode));
553void raw_ostream::anchor() {}
571 "Cannot make a raw_ostream from a read-only descriptor!");
575 if (Filename ==
"-") {
576 EC = std::error_code();
579 return STDOUT_FILENO;
594 :
raw_fd_ostream(Filename, EC, sys::fs::CD_CreateAlways, sys::fs::FA_Write,
599 :
raw_fd_ostream(Filename, EC, Disp, sys::fs::FA_Write, sys::fs::OF_None) {}
608 :
raw_fd_ostream(Filename, EC, sys::fs::CD_CreateAlways, sys::fs::FA_Write,
635 if (FD <= STDERR_FILENO)
641 ::GetFileType((HANDLE)::_get_osfhandle(fd)) == FILE_TYPE_CHAR;
645 off_t loc = ::lseek(FD, 0, SEEK_CUR);
647 std::error_code EC = status(FD,
Status);
651 SupportsSeeking = !EC && IsRegularFile;
653 SupportsSeeking = !EC && loc != (off_t)-1;
655 if (!SupportsSeeking)
707 if (
auto EC = sys::windows::UTF8ToUTF16(
Data, WideText))
712 size_t MaxWriteSize = WideText.
size();
714 MaxWriteSize = 32767;
716 size_t WCharsWritten = 0;
718 size_t WCharsToWrite =
719 std::min(MaxWriteSize, WideText.
size() - WCharsWritten);
720 DWORD ActuallyWritten;
722 ::WriteConsoleW((HANDLE)::_get_osfhandle(FD), &WideText[WCharsWritten],
723 WCharsToWrite, &ActuallyWritten,
732 WCharsWritten += ActuallyWritten;
733 }
while (WCharsWritten != WideText.
size());
738void raw_fd_ostream::write_impl(
const char *
Ptr,
size_t Size) {
742 assert(FD >= 0 &&
"File already closed.");
748 if (IsWindowsConsole)
756 size_t MaxWriteSize = INT32_MAX;
758#if defined(__linux__)
761 MaxWriteSize = 1024 * 1024 * 1024;
765 size_t ChunkSize = std::min(
Size, MaxWriteSize);
777 if (errno == EINTR || errno == EAGAIN
779 || errno == EWOULDBLOCK
786 DWORD WinLastError = GetLastError();
787 if (WinLastError == ERROR_BROKEN_PIPE ||
788 (WinLastError == ERROR_NO_DATA && errno == EINVAL)) {
789 llvm::sys::CallOneShotPipeSignalHandler();
816 assert(SupportsSeeking &&
"Stream does not support seeking!");
819 pos = ::_lseeki64(FD, off, SEEK_SET);
821 pos = ::lseek(FD, off, SEEK_SET);
828void raw_fd_ostream::pwrite_impl(
const char *
Ptr,
size_t Size,
836size_t raw_fd_ostream::preferred_buffer_size()
const {
843 if (IsWindowsConsole)
846#elif defined(__MVS__)
851 assert(FD >= 0 &&
"File not yet open!");
853 if (fstat(FD, &statbuf) != 0)
862 return statbuf.st_blksize;
891void raw_fd_ostream::anchor() {}
901 EC = enablezOSAutoConversion(STDOUT_FILENO);
912 std::error_code EC = enablezOSAutoConversion(STDERR_FILENO);
931 sys::fs::FA_Write | sys::fs::FA_Read,
938 EC = std::make_error_code(std::errc::invalid_argument);
962void raw_string_ostream::write_impl(
const char *
Ptr,
size_t Size) {
970uint64_t raw_svector_ostream::current_pos()
const {
return OS.size(); }
972void raw_svector_ostream::write_impl(
const char *
Ptr,
size_t Size) {
976void raw_svector_ostream::pwrite_impl(
const char *
Ptr,
size_t Size,
998void raw_null_ostream::write_impl(
const char *
Ptr,
size_t Size) {
1001uint64_t raw_null_ostream::current_pos()
const {
1005void raw_null_ostream::pwrite_impl(
const char *
Ptr,
size_t Size,
1008void raw_pwrite_stream::anchor() {}
1010void buffer_ostream::anchor() {}
1012void buffer_unique_ostream::anchor() {}
1016 if (OutputFileName ==
"-")
1019 if (OutputFileName ==
"/dev/null") {
1033 if (
Error DiscardError = Temp->discard())
1034 return joinErrors(std::move(
E), std::move(DiscardError));
1039 return Temp->keep(OutputFileName);
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_UNLIKELY(EXPR)
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
Provides a library for accessing information about this process and other processes on the operating ...
static cl::opt< RegAllocEvictionAdvisorAnalysis::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Development, "development", "for training")))
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
std::pair< llvm::MachO::Target, std::string > UUID
bool empty() const
empty - Check if the array is empty.
std::chrono::milliseconds getDuration() const
Lightweight error class with error context and mandatory checking.
Tagged union holding either a T or a Error.
Error takeError()
Take ownership of the stored error.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
A raw_ostream that writes to a file descriptor.
bool is_displayed() const override
This function determines if this stream is connected to a "tty" or "console" window.
bool has_error() const
Return the value of the flag in this raw_fd_ostream indicating whether an output error has been encou...
std::error_code error() const
void close()
Manually flush the stream and close the file.
void inc_pos(uint64_t Delta)
Expected< sys::fs::FileLocker > lock()
Locks the underlying file.
~raw_fd_ostream() override
bool has_colors() const override
This function determines if this stream is displayed and supports colors.
bool isRegularFile() const
uint64_t seek(uint64_t off)
Flushes the stream and repositions the underlying file descriptor position to the offset specified fr...
int get_fd() const
Return the file descriptor.
Expected< sys::fs::FileLocker > tryLockFor(Duration const &Timeout)
Tries to lock the underlying file within the specified period.
raw_fd_ostream(StringRef Filename, std::error_code &EC)
Open the specified file for writing.
void error_detected(std::error_code EC)
Set the flag indicating that an output error has been encountered.
static bool classof(const raw_ostream *OS)
Check if OS is a pointer of type raw_fd_stream*.
raw_fd_stream(StringRef Filename, std::error_code &EC)
Open the specified file for reading/writing/seeking.
ssize_t read(char *Ptr, size_t Size)
This reads the Size bytes into a buffer pointed by Ptr.
A raw_ostream that discards all output.
~raw_null_ostream() override
This class implements an extremely fast bulk output stream that can only output to a stream.
static constexpr Colors YELLOW
raw_ostream & write_zeros(unsigned NumZeros)
write_zeros - Insert 'NumZeros' nulls.
uint64_t tell() const
tell - Return the current offset with the file.
void SetBufferSize(size_t Size)
Set the stream to be buffered, using the specified buffer size.
static constexpr Colors CYAN
virtual raw_ostream & changeColor(enum Colors Color, bool Bold=false, bool BG=false)
Changes the foreground color of text that will be output from this point forward.
raw_ostream & write_hex(unsigned long long N)
Output N in hexadecimal, without any prefix or padding.
virtual raw_ostream & resetColor()
Resets the colors to terminal defaults.
raw_ostream & write_uuid(const uuid_t UUID)
raw_ostream & operator<<(char C)
raw_ostream & write_escaped(StringRef Str, bool UseHexEscapes=false)
Output Str, turning '\', '\t', ' ', '"', and anything that doesn't satisfy llvm::isPrint into an esca...
virtual raw_ostream & reverseColor()
Reverses the foreground and background colors.
static constexpr Colors BLUE
virtual size_t preferred_buffer_size() const
Return an efficient buffer size for the underlying output mechanism.
raw_ostream & write(unsigned char C)
void SetUnbuffered()
Set the stream to be unbuffered.
virtual bool is_displayed() const
This function determines if this stream is connected to a "tty" or "console" window.
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
static constexpr Colors RESET
uint8_t[16] uuid_t
Output a formatted UUID with dash separators.
static constexpr Colors MAGENTA
virtual void enable_colors(bool enable)
static constexpr Colors SAVEDCOLOR
size_t GetNumBytesInBuffer() const
static constexpr Colors BLACK
static constexpr Colors GREEN
static constexpr Colors RED
OStreamKind get_kind() const
void SetBuffered()
Set the stream to be buffered, with an automatically determined buffer size.
static constexpr Colors WHITE
An abstract base class for streams implementations that also support a pwrite operation.
A raw_ostream that writes to an SmallVector or SmallString.
static bool classof(const raw_ostream *OS)
static std::error_code SafelyCloseFileDescriptor(int FD)
static const char * OutputColor(char c, bool bold, bool bg)
This function returns the colorcode escape sequences.
static bool FileDescriptorIsDisplayed(int fd)
This function determines if the given file descriptor is connected to a "tty" or "console" window.
static const char * OutputBold(bool bg)
Same as OutputColor, but only enables the bold attribute.
static bool FileDescriptorHasColors(int fd)
This function determines if the given file descriptor is displayd and supports colors.
static const char * OutputReverse()
This function returns the escape sequence to reverse forground and background colors.
static const char * ResetColor()
Resets the terminals colors, or returns an escape sequence to do so.
static bool ColorNeedsFlush()
Whether changing colors requires the output to be flushed.
RAII class that facilitates file locking.
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...
Represents the result of a call to sys::fs::status().
@ C
The default llvm calling convention, compatible with C.
std::error_code openFileForReadWrite(const Twine &Name, int &ResultFD, CreationDisposition Disp, OpenFlags Flags, unsigned Mode=0666)
Opens the file with the given name in a write-only or read-write mode, returning its open file descri...
std::error_code tryLockFile(int FD, std::chrono::milliseconds Timeout=std::chrono::milliseconds(0))
Try to locks the file during the specified time.
std::error_code lockFile(int FD)
Lock the file.
std::error_code openFileForWrite(const Twine &Name, int &ResultFD, CreationDisposition Disp=CD_CreateAlways, OpenFlags Flags=OF_None, unsigned Mode=0666)
Opens the file with the given name in a write-only or read-write mode, returning its open file descri...
std::error_code ChangeStdoutMode(fs::OpenFlags Flags)
This is an optimization pass for GlobalISel generic memory operations.
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
unsigned Log2_64_Ceil(uint64_t Value)
Return the ceil log base 2 of the specified value, 64 if the value is zero.
raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
bool RunningWindows8OrGreater()
Determines if the program is running on Windows 8 or newer.
void write_integer(raw_ostream &S, unsigned int N, size_t MinDigits, IntegerStyle Style)
Error joinErrors(Error E1, Error E2)
Concatenate errors.
Error write(MCStreamer &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue)
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Error writeToOutput(StringRef OutputFileName, std::function< Error(raw_ostream &)> Write)
This helper creates an output stream and then passes it to Write.
raw_ostream & nulls()
This returns a reference to a raw_ostream which simply discards output.
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
void write_hex(raw_ostream &S, uint64_t N, HexPrintStyle Style, std::optional< size_t > Width=std::nullopt)
void write_double(raw_ostream &S, double D, FloatStyle Style, std::optional< size_t > Precision=std::nullopt)
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
std::error_code errnoAsErrorCode()
Helper to get errno as an std::error_code.
static int getFD(StringRef Filename, std::error_code &EC, sys::fs::CreationDisposition Disp, sys::fs::FileAccess Access, sys::fs::OpenFlags Flags)
static raw_ostream & write_padding(raw_ostream &OS, unsigned NumChars)