LLVM 20.0.0git
raw_ostream.h
Go to the documentation of this file.
1//===--- raw_ostream.h - Raw output stream ----------------------*- C++ -*-===//
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 defines the raw_ostream class.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_SUPPORT_RAW_OSTREAM_H
14#define LLVM_SUPPORT_RAW_OSTREAM_H
15
17#include "llvm/ADT/StringRef.h"
19#include <cassert>
20#include <cstddef>
21#include <cstdint>
22#include <cstring>
23#include <optional>
24#include <string>
25#include <string_view>
26#include <system_error>
27#include <type_traits>
28
29namespace llvm {
30
31class Duration;
34class FormattedString;
35class FormattedNumber;
36class FormattedBytes;
37template <class T> class [[nodiscard]] Expected;
38
39namespace sys {
40namespace fs {
41enum FileAccess : unsigned;
42enum OpenFlags : unsigned;
44class FileLocker;
45} // end namespace fs
46} // end namespace sys
47
48/// This class implements an extremely fast bulk output stream that can *only*
49/// output to a stream. It does not support seeking, reopening, rewinding, line
50/// buffered disciplines etc. It is a simple buffer that outputs
51/// a chunk at a time.
53public:
54 // Class kinds to support LLVM-style RTTI.
55 enum class OStreamKind {
59 };
60
61private:
62 OStreamKind Kind;
63
64 /// The buffer is handled in such a way that the buffer is
65 /// uninitialized, unbuffered, or out of space when OutBufCur >=
66 /// OutBufEnd. Thus a single comparison suffices to determine if we
67 /// need to take the slow path to write a single character.
68 ///
69 /// The buffer is in one of three states:
70 /// 1. Unbuffered (BufferMode == Unbuffered)
71 /// 1. Uninitialized (BufferMode != Unbuffered && OutBufStart == 0).
72 /// 2. Buffered (BufferMode != Unbuffered && OutBufStart != 0 &&
73 /// OutBufEnd - OutBufStart >= 1).
74 ///
75 /// If buffered, then the raw_ostream owns the buffer if (BufferMode ==
76 /// InternalBuffer); otherwise the buffer has been set via SetBuffer and is
77 /// managed by the subclass.
78 ///
79 /// If a subclass installs an external buffer using SetBuffer then it can wait
80 /// for a \see write_impl() call to handle the data which has been put into
81 /// this buffer.
82 char *OutBufStart, *OutBufEnd, *OutBufCur;
83 bool ColorEnabled = false;
84
85 enum class BufferKind {
86 Unbuffered = 0,
87 InternalBuffer,
88 ExternalBuffer
89 } BufferMode;
90
91public:
92 // color order matches ANSI escape sequence, don't change
93 enum class Colors {
94 BLACK = 0,
95 RED,
96 GREEN,
97 YELLOW,
98 BLUE,
99 MAGENTA,
100 CYAN,
101 WHITE,
111 RESET,
112 };
113
114 static constexpr Colors BLACK = Colors::BLACK;
115 static constexpr Colors RED = Colors::RED;
116 static constexpr Colors GREEN = Colors::GREEN;
117 static constexpr Colors YELLOW = Colors::YELLOW;
118 static constexpr Colors BLUE = Colors::BLUE;
119 static constexpr Colors MAGENTA = Colors::MAGENTA;
120 static constexpr Colors CYAN = Colors::CYAN;
121 static constexpr Colors WHITE = Colors::WHITE;
131 static constexpr Colors RESET = Colors::RESET;
132
133 explicit raw_ostream(bool unbuffered = false,
135 : Kind(K), BufferMode(unbuffered ? BufferKind::Unbuffered
136 : BufferKind::InternalBuffer) {
137 // Start out ready to flush.
138 OutBufStart = OutBufEnd = OutBufCur = nullptr;
139 }
140
141 raw_ostream(const raw_ostream &) = delete;
142 void operator=(const raw_ostream &) = delete;
143
144 virtual ~raw_ostream();
145
146 /// tell - Return the current offset with the file.
147 uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); }
148
149 OStreamKind get_kind() const { return Kind; }
150
151 //===--------------------------------------------------------------------===//
152 // Configuration Interface
153 //===--------------------------------------------------------------------===//
154
155 /// If possible, pre-allocate \p ExtraSize bytes for stream data.
156 /// i.e. it extends internal buffers to keep additional ExtraSize bytes.
157 /// So that the stream could keep at least tell() + ExtraSize bytes
158 /// without re-allocations. reserveExtraSpace() does not change
159 /// the size/data of the stream.
160 virtual void reserveExtraSpace(uint64_t ExtraSize) {}
161
162 /// Set the stream to be buffered, with an automatically determined buffer
163 /// size.
164 void SetBuffered();
165
166 /// Set the stream to be buffered, using the specified buffer size.
167 void SetBufferSize(size_t Size) {
168 flush();
169 SetBufferAndMode(new char[Size], Size, BufferKind::InternalBuffer);
170 }
171
172 size_t GetBufferSize() const {
173 // If we're supposed to be buffered but haven't actually gotten around
174 // to allocating the buffer yet, return the value that would be used.
175 if (BufferMode != BufferKind::Unbuffered && OutBufStart == nullptr)
176 return preferred_buffer_size();
177
178 // Otherwise just return the size of the allocated buffer.
179 return OutBufEnd - OutBufStart;
180 }
181
182 /// Set the stream to be unbuffered. When unbuffered, the stream will flush
183 /// after every write. This routine will also flush the buffer immediately
184 /// when the stream is being set to unbuffered.
186 flush();
187 SetBufferAndMode(nullptr, 0, BufferKind::Unbuffered);
188 }
189
190 size_t GetNumBytesInBuffer() const {
191 return OutBufCur - OutBufStart;
192 }
193
194 //===--------------------------------------------------------------------===//
195 // Data Output Interface
196 //===--------------------------------------------------------------------===//
197
198 void flush() {
199 if (OutBufCur != OutBufStart)
200 flush_nonempty();
201 }
202
204 if (OutBufCur >= OutBufEnd)
205 return write(C);
206 *OutBufCur++ = C;
207 return *this;
208 }
209
210 raw_ostream &operator<<(unsigned char C) {
211 if (OutBufCur >= OutBufEnd)
212 return write(C);
213 *OutBufCur++ = C;
214 return *this;
215 }
216
217 raw_ostream &operator<<(signed char C) {
218 if (OutBufCur >= OutBufEnd)
219 return write(C);
220 *OutBufCur++ = C;
221 return *this;
222 }
223
225 // Inline fast path, particularly for strings with a known length.
226 size_t Size = Str.size();
227
228 // Make sure we can use the fast path.
229 if (Size > (size_t)(OutBufEnd - OutBufCur))
230 return write(Str.data(), Size);
231
232 if (Size) {
233 memcpy(OutBufCur, Str.data(), Size);
234 OutBufCur += Size;
235 }
236 return *this;
237 }
238
239#if defined(__cpp_char8_t)
240 // When using `char8_t *` integers or pointers are written to the ostream
241 // instead of UTF-8 code as one might expect. This might lead to unexpected
242 // behavior, especially as `u8""` literals are of type `char8_t*` instead of
243 // type `char_t*` from C++20 onwards. Thus we disallow using them with
244 // raw_ostreams.
245 // If you have u8"" literals to stream, you can rewrite them as ordinary
246 // literals with escape sequences
247 // e.g. replace `u8"\u00a0"` by `"\xc2\xa0"`
248 // or use `reinterpret_cast`:
249 // e.g. replace `u8"\u00a0"` by `reinterpret_cast<const char *>(u8"\u00a0")`
250 raw_ostream &operator<<(const char8_t *Str) = delete;
251#endif
252
253 raw_ostream &operator<<(const char *Str) {
254 // Inline fast path, particularly for constant strings where a sufficiently
255 // smart compiler will simplify strlen.
256
257 return this->operator<<(StringRef(Str));
258 }
259
260 raw_ostream &operator<<(const std::string &Str) {
261 // Avoid the fast path, it would only increase code size for a marginal win.
262 return write(Str.data(), Str.length());
263 }
264
265 raw_ostream &operator<<(const std::string_view &Str) {
266 return write(Str.data(), Str.length());
267 }
268
270 return write(Str.data(), Str.size());
271 }
272
273 raw_ostream &operator<<(unsigned long N);
274 raw_ostream &operator<<(long N);
275 raw_ostream &operator<<(unsigned long long N);
276 raw_ostream &operator<<(long long N);
277 raw_ostream &operator<<(const void *P);
278
279 raw_ostream &operator<<(unsigned int N) {
280 return this->operator<<(static_cast<unsigned long>(N));
281 }
282
284 return this->operator<<(static_cast<long>(N));
285 }
286
287 raw_ostream &operator<<(double N);
288
289 /// Output \p N in hexadecimal, without any prefix or padding.
290 raw_ostream &write_hex(unsigned long long N);
291
292 // Change the foreground color of text.
294
295 /// Output a formatted UUID with dash separators.
296 using uuid_t = uint8_t[16];
298
299 /// Output \p Str, turning '\\', '\t', '\n', '"', and anything that doesn't
300 /// satisfy llvm::isPrint into an escape sequence.
301 raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false);
302
303 raw_ostream &write(unsigned char C);
304 raw_ostream &write(const char *Ptr, size_t Size);
305
306 // Formatted output, see the format() function in Support/Format.h.
308
309 // Formatted output, see the leftJustify() function in Support/Format.h.
311
312 // Formatted output, see the formatHex() function in Support/Format.h.
314
315 // Formatted output, see the formatv() function in Support/FormatVariadic.h.
317
318 // Formatted output, see the format_bytes() function in Support/Format.h.
320
321 /// indent - Insert 'NumSpaces' spaces.
322 raw_ostream &indent(unsigned NumSpaces);
323
324 /// write_zeros - Insert 'NumZeros' nulls.
325 raw_ostream &write_zeros(unsigned NumZeros);
326
327 /// Changes the foreground color of text that will be output from this point
328 /// forward.
329 /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to
330 /// change only the bold attribute, and keep colors untouched
331 /// @param Bold bold/brighter text, default false
332 /// @param BG if true change the background, default: change foreground
333 /// @returns itself so it can be used within << invocations
334 virtual raw_ostream &changeColor(enum Colors Color, bool Bold = false,
335 bool BG = false);
336
337 /// Resets the colors to terminal defaults. Call this when you are done
338 /// outputting colored text, or before program exit.
339 virtual raw_ostream &resetColor();
340
341 /// Reverses the foreground and background colors.
342 virtual raw_ostream &reverseColor();
343
344 /// This function determines if this stream is connected to a "tty" or
345 /// "console" window. That is, the output would be displayed to the user
346 /// rather than being put on a pipe or stored in a file.
347 virtual bool is_displayed() const { return false; }
348
349 /// This function determines if this stream is displayed and supports colors.
350 /// The result is unaffected by calls to enable_color().
351 virtual bool has_colors() const { return is_displayed(); }
352
353 // Enable or disable colors. Once enable_colors(false) is called,
354 // changeColor() has no effect until enable_colors(true) is called.
355 virtual void enable_colors(bool enable) { ColorEnabled = enable; }
356
357 bool colors_enabled() const { return ColorEnabled; }
358
359 //===--------------------------------------------------------------------===//
360 // Subclass Interface
361 //===--------------------------------------------------------------------===//
362
363private:
364 /// The is the piece of the class that is implemented by subclasses. This
365 /// writes the \p Size bytes starting at
366 /// \p Ptr to the underlying stream.
367 ///
368 /// This function is guaranteed to only be called at a point at which it is
369 /// safe for the subclass to install a new buffer via SetBuffer.
370 ///
371 /// \param Ptr The start of the data to be written. For buffered streams this
372 /// is guaranteed to be the start of the buffer.
373 ///
374 /// \param Size The number of bytes to be written.
375 ///
376 /// \invariant { Size > 0 }
377 virtual void write_impl(const char *Ptr, size_t Size) = 0;
378
379 /// Return the current position within the stream, not counting the bytes
380 /// currently in the buffer.
381 virtual uint64_t current_pos() const = 0;
382
383protected:
384 /// Use the provided buffer as the raw_ostream buffer. This is intended for
385 /// use only by subclasses which can arrange for the output to go directly
386 /// into the desired output buffer, instead of being copied on each flush.
387 void SetBuffer(char *BufferStart, size_t Size) {
388 SetBufferAndMode(BufferStart, Size, BufferKind::ExternalBuffer);
389 }
390
391 /// Return an efficient buffer size for the underlying output mechanism.
392 virtual size_t preferred_buffer_size() const;
393
394 /// Return the beginning of the current stream buffer, or 0 if the stream is
395 /// unbuffered.
396 const char *getBufferStart() const { return OutBufStart; }
397
398 //===--------------------------------------------------------------------===//
399 // Private Interface
400 //===--------------------------------------------------------------------===//
401private:
402 /// Install the given buffer and mode.
403 void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode);
404
405 /// Flush the current buffer, which is known to be non-empty. This outputs the
406 /// currently buffered data and resets the buffer to empty.
407 void flush_nonempty();
408
409 /// Copy data into the buffer. Size must not be greater than the number of
410 /// unused bytes in the buffer.
411 void copy_to_buffer(const char *Ptr, size_t Size);
412
413 /// Compute whether colors should be used and do the necessary work such as
414 /// flushing. The result is affected by calls to enable_color().
415 bool prepare_colors();
416
417 virtual void anchor();
418};
419
420/// Call the appropriate insertion operator, given an rvalue reference to a
421/// raw_ostream object and return a stream of the same type as the argument.
422template <typename OStream, typename T>
423std::enable_if_t<!std::is_reference_v<OStream> &&
424 std::is_base_of_v<raw_ostream, OStream>,
425 OStream &&>
426operator<<(OStream &&OS, const T &Value) {
427 OS << Value;
428 return std::move(OS);
429}
430
431/// An abstract base class for streams implementations that also support a
432/// pwrite operation. This is useful for code that can mostly stream out data,
433/// but needs to patch in a header that needs to know the output size.
435 virtual void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) = 0;
436 void anchor() override;
437
438public:
439 explicit raw_pwrite_stream(bool Unbuffered = false,
441 : raw_ostream(Unbuffered, K) {}
442 void pwrite(const char *Ptr, size_t Size, uint64_t Offset) {
443#ifndef NDEBUG
444 uint64_t Pos = tell();
445 // /dev/null always reports a pos of 0, so we cannot perform this check
446 // in that case.
447 if (Pos)
448 assert(Size + Offset <= Pos && "We don't support extending the stream");
449#endif
450 pwrite_impl(Ptr, Size, Offset);
451 }
452};
453
454//===----------------------------------------------------------------------===//
455// File Output Streams
456//===----------------------------------------------------------------------===//
457
458/// A raw_ostream that writes to a file descriptor.
459///
461 int FD;
462 bool ShouldClose;
463 bool SupportsSeeking = false;
464 bool IsRegularFile = false;
465 mutable std::optional<bool> HasColors;
466
467 /// Optional stream this stream is tied to. If this stream is written to, the
468 /// tied-to stream will be flushed first.
469 raw_ostream *TiedStream = nullptr;
470
471#ifdef _WIN32
472 /// True if this fd refers to a Windows console device. Mintty and other
473 /// terminal emulators are TTYs, but they are not consoles.
474 bool IsWindowsConsole = false;
475#endif
476
477 std::error_code EC;
478
479 uint64_t pos = 0;
480
481 /// See raw_ostream::write_impl.
482 void write_impl(const char *Ptr, size_t Size) override;
483
484 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
485
486 /// Return the current position within the stream, not counting the bytes
487 /// currently in the buffer.
488 uint64_t current_pos() const override { return pos; }
489
490 /// Determine an efficient buffer size.
491 size_t preferred_buffer_size() const override;
492
493 void anchor() override;
494
495protected:
496 /// Set the flag indicating that an output error has been encountered.
497 void error_detected(std::error_code EC) { this->EC = EC; }
498
499 /// Return the file descriptor.
500 int get_fd() const { return FD; }
501
502 // Update the file position by increasing \p Delta.
503 void inc_pos(uint64_t Delta) { pos += Delta; }
504
505public:
506 /// Open the specified file for writing. If an error occurs, information
507 /// about the error is put into EC, and the stream should be immediately
508 /// destroyed;
509 /// \p Flags allows optional flags to control how the file will be opened.
510 ///
511 /// As a special case, if Filename is "-", then the stream will use
512 /// STDOUT_FILENO instead of opening a file. This will not close the stdout
513 /// descriptor.
514 raw_fd_ostream(StringRef Filename, std::error_code &EC);
515 raw_fd_ostream(StringRef Filename, std::error_code &EC,
517 raw_fd_ostream(StringRef Filename, std::error_code &EC,
518 sys::fs::FileAccess Access);
519 raw_fd_ostream(StringRef Filename, std::error_code &EC,
520 sys::fs::OpenFlags Flags);
521 raw_fd_ostream(StringRef Filename, std::error_code &EC,
523 sys::fs::OpenFlags Flags);
524
525 /// FD is the file descriptor that this writes to. If ShouldClose is true,
526 /// this closes the file when the stream is destroyed. If FD is for stdout or
527 /// stderr, it will not be closed.
528 raw_fd_ostream(int fd, bool shouldClose, bool unbuffered = false,
530
531 ~raw_fd_ostream() override;
532
533 /// Manually flush the stream and close the file. Note that this does not call
534 /// fsync.
535 void close();
536
537 bool supportsSeeking() const { return SupportsSeeking; }
538
539 bool isRegularFile() const { return IsRegularFile; }
540
541 /// Flushes the stream and repositions the underlying file descriptor position
542 /// to the offset specified from the beginning of the file.
544
545 bool is_displayed() const override;
546
547 bool has_colors() const override;
548
549 /// Tie this stream to the specified stream. Replaces any existing tied-to
550 /// stream. Specifying a nullptr unties the stream. This is intended for to
551 /// tie errs() to outs(), so that outs() is flushed whenever something is
552 /// written to errs(), preventing weird and hard-to-test output when stderr
553 /// is redirected to stdout.
554 void tie(raw_ostream *TieTo) { TiedStream = TieTo; }
555
556 std::error_code error() const { return EC; }
557
558 /// Return the value of the flag in this raw_fd_ostream indicating whether an
559 /// output error has been encountered.
560 /// This doesn't implicitly flush any pending output. Also, it doesn't
561 /// guarantee to detect all errors unless the stream has been closed.
562 bool has_error() const { return bool(EC); }
563
564 /// Set the flag read by has_error() to false. If the error flag is set at the
565 /// time when this raw_ostream's destructor is called, report_fatal_error is
566 /// called to report the error. Use clear_error() after handling the error to
567 /// avoid this behavior.
568 ///
569 /// "Errors should never pass silently.
570 /// Unless explicitly silenced."
571 /// - from The Zen of Python, by Tim Peters
572 ///
573 void clear_error() { EC = std::error_code(); }
574
575 /// Locks the underlying file.
576 ///
577 /// @returns RAII object that releases the lock upon leaving the scope, if the
578 /// locking was successful. Otherwise returns corresponding
579 /// error code.
580 ///
581 /// The function blocks the current thread until the lock become available or
582 /// error occurs.
583 ///
584 /// Possible use of this function may be as follows:
585 ///
586 /// @code{.cpp}
587 /// if (auto L = stream.lock()) {
588 /// // ... do action that require file to be locked.
589 /// } else {
590 /// handleAllErrors(std::move(L.takeError()), [&](ErrorInfoBase &EIB) {
591 /// // ... handle lock error.
592 /// });
593 /// }
594 /// @endcode
595 [[nodiscard]] Expected<sys::fs::FileLocker> lock();
596
597 /// Tries to lock the underlying file within the specified period.
598 ///
599 /// @returns RAII object that releases the lock upon leaving the scope, if the
600 /// locking was successful. Otherwise returns corresponding
601 /// error code.
602 ///
603 /// It is used as @ref lock.
605 tryLockFor(Duration const &Timeout);
606};
607
608/// This returns a reference to a raw_fd_ostream for standard output. Use it
609/// like: outs() << "foo" << "bar";
610raw_fd_ostream &outs();
611
612/// This returns a reference to a raw_ostream for standard error.
613/// Use it like: errs() << "foo" << "bar";
614/// By default, the stream is tied to stdout to ensure stdout is flushed before
615/// stderr is written, to ensure the error messages are written in their
616/// expected place.
617raw_fd_ostream &errs();
618
619/// This returns a reference to a raw_ostream which simply discards output.
620raw_ostream &nulls();
621
622//===----------------------------------------------------------------------===//
623// File Streams
624//===----------------------------------------------------------------------===//
625
626/// A raw_ostream of a file for reading/writing/seeking.
627///
629public:
630 /// Open the specified file for reading/writing/seeking. If an error occurs,
631 /// information about the error is put into EC, and the stream should be
632 /// immediately destroyed.
633 raw_fd_stream(StringRef Filename, std::error_code &EC);
634
635 raw_fd_stream(int fd, bool shouldClose);
636
637 /// This reads the \p Size bytes into a buffer pointed by \p Ptr.
638 ///
639 /// \param Ptr The start of the buffer to hold data to be read.
640 ///
641 /// \param Size The number of bytes to be read.
642 ///
643 /// On success, the number of bytes read is returned, and the file position is
644 /// advanced by this number. On error, -1 is returned, use error() to get the
645 /// error code.
646 ssize_t read(char *Ptr, size_t Size);
647
648 /// Check if \p OS is a pointer of type raw_fd_stream*.
649 static bool classof(const raw_ostream *OS);
650};
651
652//===----------------------------------------------------------------------===//
653// Output Stream Adaptors
654//===----------------------------------------------------------------------===//
655
656/// A raw_ostream that writes to an std::string. This is a simple adaptor
657/// class. This class does not encounter output errors.
658/// raw_string_ostream operates without a buffer, delegating all memory
659/// management to the std::string. Thus the std::string is always up-to-date,
660/// may be used directly and there is no need to call flush().
662 std::string &OS;
663
664 /// See raw_ostream::write_impl.
665 void write_impl(const char *Ptr, size_t Size) override;
666
667 /// Return the current position within the stream, not counting the bytes
668 /// currently in the buffer.
669 uint64_t current_pos() const override { return OS.size(); }
670
671public:
672 explicit raw_string_ostream(std::string &O) : OS(O) {
674 }
675
676 /// Returns the string's reference. In most cases it is better to simply use
677 /// the underlying std::string directly.
678 /// TODO: Consider removing this API.
679 std::string &str() { return OS; }
680
681 void reserveExtraSpace(uint64_t ExtraSize) override {
682 OS.reserve(tell() + ExtraSize);
683 }
684};
685
686/// A raw_ostream that writes to an SmallVector or SmallString. This is a
687/// simple adaptor class. This class does not encounter output errors.
688/// raw_svector_ostream operates without a buffer, delegating all memory
689/// management to the SmallString. Thus the SmallString is always up-to-date,
690/// may be used directly and there is no need to call flush().
693
694 /// See raw_ostream::write_impl.
695 void write_impl(const char *Ptr, size_t Size) override;
696
697 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
698
699 /// Return the current position within the stream.
700 uint64_t current_pos() const override;
701
702public:
703 /// Construct a new raw_svector_ostream.
704 ///
705 /// \param O The vector to write to; this should generally have at least 128
706 /// bytes free to avoid any extraneous memory overhead.
709 OS(O) {
710 // FIXME: here and in a few other places, set directly to unbuffered in the
711 // ctor.
713 }
714
715 ~raw_svector_ostream() override = default;
716
717 void flush() = delete;
718
719 /// Return a StringRef for the vector contents.
720 StringRef str() const { return StringRef(OS.data(), OS.size()); }
722
723 void reserveExtraSpace(uint64_t ExtraSize) override {
724 OS.reserve(tell() + ExtraSize);
725 }
726
727 static bool classof(const raw_ostream *OS);
728};
729
730/// A raw_ostream that discards all output.
732 /// See raw_ostream::write_impl.
733 void write_impl(const char *Ptr, size_t size) override;
734 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
735
736 /// Return the current position within the stream, not counting the bytes
737 /// currently in the buffer.
738 uint64_t current_pos() const override;
739
740public:
741 explicit raw_null_ostream() = default;
742 ~raw_null_ostream() override;
743};
744
746 raw_ostream &OS;
748
749 void anchor() override;
750
751public:
753 ~buffer_ostream() override { OS << str(); }
754};
755
757 std::unique_ptr<raw_ostream> OS;
759
760 void anchor() override;
761
762public:
763 buffer_unique_ostream(std::unique_ptr<raw_ostream> OS)
764 : raw_svector_ostream(Buffer), OS(std::move(OS)) {
765 // Turn off buffering on OS, which we now own, to avoid allocating a buffer
766 // when the destructor writes only to be immediately flushed again.
767 this->OS->SetUnbuffered();
768 }
769 ~buffer_unique_ostream() override { *OS << str(); }
770};
771
772class Error;
773
774/// This helper creates an output stream and then passes it to \p Write.
775/// The stream created is based on the specified \p OutputFileName:
776/// llvm::outs for "-", raw_null_ostream for "/dev/null", and raw_fd_ostream
777/// for other names. For raw_fd_ostream instances, the stream writes to
778/// a temporary file. The final output file is atomically replaced with the
779/// temporary file after the \p Write function is finished.
780Error writeToOutput(StringRef OutputFileName,
781 std::function<Error(raw_ostream &)> Write);
782
783raw_ostream &operator<<(raw_ostream &OS, std::nullopt_t);
784
785template <typename T, typename = decltype(std::declval<raw_ostream &>()
786 << std::declval<const T &>())>
787raw_ostream &operator<<(raw_ostream &OS, const std::optional<T> &O) {
788 if (O)
789 OS << *O;
790 else
791 OS << std::nullopt;
792 return OS;
793}
794
795} // end namespace llvm
796
797#endif // LLVM_SUPPORT_RAW_OSTREAM_H
uint64_t Size
#define P(N)
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())
raw_pwrite_stream & OS
This file defines the SmallVector class.
std::pair< llvm::MachO::Target, std::string > UUID
Tagged union holding either a T or a Error.
Definition: Error.h:481
This is a helper class used for format_hex() and format_decimal().
Definition: Format.h:165
This is a helper class for left_justify, right_justify, and center_justify.
Definition: Format.h:130
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
buffer_ostream(raw_ostream &OS)
Definition: raw_ostream.h:752
~buffer_ostream() override
Definition: raw_ostream.h:753
buffer_unique_ostream(std::unique_ptr< raw_ostream > OS)
Definition: raw_ostream.h:763
This is a helper class used for handling formatted output.
Definition: Format.h:39
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:460
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...
Definition: raw_ostream.h:562
std::error_code error() const
Definition: raw_ostream.h:556
void close()
Manually flush the stream and close the file.
void inc_pos(uint64_t Delta)
Definition: raw_ostream.h:503
Expected< sys::fs::FileLocker > lock()
Locks the underlying file.
void tie(raw_ostream *TieTo)
Tie this stream to the specified stream.
Definition: raw_ostream.h:554
bool supportsSeeking() const
Definition: raw_ostream.h:537
~raw_fd_ostream() override
void clear_error()
Set the flag read by has_error() to false.
Definition: raw_ostream.h:573
bool has_colors() const override
This function determines if this stream is displayed and supports colors.
bool isRegularFile() const
Definition: raw_ostream.h:539
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.
Definition: raw_ostream.h:500
Expected< sys::fs::FileLocker > tryLockFor(Duration const &Timeout)
Tries to lock the underlying file within the specified period.
void error_detected(std::error_code EC)
Set the flag indicating that an output error has been encountered.
Definition: raw_ostream.h:497
A raw_ostream of a file for reading/writing/seeking.
Definition: raw_ostream.h:628
static bool classof(const raw_ostream *OS)
Check if OS is a pointer of type raw_fd_stream*.
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.
Definition: raw_ostream.h:731
~raw_null_ostream() override
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
static constexpr Colors YELLOW
Definition: raw_ostream.h:117
raw_ostream & write_zeros(unsigned NumZeros)
write_zeros - Insert 'NumZeros' nulls.
raw_ostream & operator<<(unsigned char C)
Definition: raw_ostream.h:210
raw_ostream(bool unbuffered=false, OStreamKind K=OStreamKind::OK_OStream)
Definition: raw_ostream.h:133
uint64_t tell() const
tell - Return the current offset with the file.
Definition: raw_ostream.h:147
raw_ostream & operator<<(const std::string_view &Str)
Definition: raw_ostream.h:265
static constexpr Colors BRIGHT_RED
Definition: raw_ostream.h:123
void SetBufferSize(size_t Size)
Set the stream to be buffered, using the specified buffer size.
Definition: raw_ostream.h:167
static constexpr Colors CYAN
Definition: raw_ostream.h:120
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.
size_t GetBufferSize() const
Definition: raw_ostream.h:172
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)
Definition: raw_ostream.h:203
virtual ~raw_ostream()
Definition: raw_ostream.cpp:77
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.
void SetBuffer(char *BufferStart, size_t Size)
Use the provided buffer as the raw_ostream buffer.
Definition: raw_ostream.h:387
static constexpr Colors BLUE
Definition: raw_ostream.h:118
virtual size_t preferred_buffer_size() const
Return an efficient buffer size for the underlying output mechanism.
Definition: raw_ostream.cpp:87
raw_ostream & write(unsigned char C)
void SetUnbuffered()
Set the stream to be unbuffered.
Definition: raw_ostream.h:185
virtual bool is_displayed() const
This function determines if this stream is connected to a "tty" or "console" window.
Definition: raw_ostream.h:347
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
const char * getBufferStart() const
Return the beginning of the current stream buffer, or 0 if the stream is unbuffered.
Definition: raw_ostream.h:396
static constexpr Colors RESET
Definition: raw_ostream.h:131
raw_ostream & operator<<(signed char C)
Definition: raw_ostream.h:217
static constexpr Colors BRIGHT_MAGENTA
Definition: raw_ostream.h:127
uint8_t[16] uuid_t
Output a formatted UUID with dash separators.
Definition: raw_ostream.h:296
static constexpr Colors MAGENTA
Definition: raw_ostream.h:119
virtual void enable_colors(bool enable)
Definition: raw_ostream.h:355
raw_ostream & operator<<(int N)
Definition: raw_ostream.h:283
raw_ostream & operator<<(const char *Str)
Definition: raw_ostream.h:253
raw_ostream(const raw_ostream &)=delete
void operator=(const raw_ostream &)=delete
static constexpr Colors BRIGHT_YELLOW
Definition: raw_ostream.h:125
raw_ostream & operator<<(const SmallVectorImpl< char > &Str)
Definition: raw_ostream.h:269
raw_ostream & operator<<(StringRef Str)
Definition: raw_ostream.h:224
static constexpr Colors BRIGHT_CYAN
Definition: raw_ostream.h:128
static constexpr Colors SAVEDCOLOR
Definition: raw_ostream.h:130
virtual void reserveExtraSpace(uint64_t ExtraSize)
If possible, pre-allocate ExtraSize bytes for stream data.
Definition: raw_ostream.h:160
size_t GetNumBytesInBuffer() const
Definition: raw_ostream.h:190
static constexpr Colors BLACK
Definition: raw_ostream.h:114
raw_ostream & operator<<(const std::string &Str)
Definition: raw_ostream.h:260
raw_ostream & operator<<(unsigned int N)
Definition: raw_ostream.h:279
static constexpr Colors BRIGHT_BLACK
Definition: raw_ostream.h:122
static constexpr Colors BRIGHT_WHITE
Definition: raw_ostream.h:129
static constexpr Colors GREEN
Definition: raw_ostream.h:116
virtual bool has_colors() const
This function determines if this stream is displayed and supports colors.
Definition: raw_ostream.h:351
static constexpr Colors RED
Definition: raw_ostream.h:115
static constexpr Colors BRIGHT_GREEN
Definition: raw_ostream.h:124
static constexpr Colors BRIGHT_BLUE
Definition: raw_ostream.h:126
OStreamKind get_kind() const
Definition: raw_ostream.h:149
void SetBuffered()
Set the stream to be buffered, with an automatically determined buffer size.
Definition: raw_ostream.cpp:99
static constexpr Colors WHITE
Definition: raw_ostream.h:121
bool colors_enabled() const
Definition: raw_ostream.h:357
An abstract base class for streams implementations that also support a pwrite operation.
Definition: raw_ostream.h:434
raw_pwrite_stream(bool Unbuffered=false, OStreamKind K=OStreamKind::OK_OStream)
Definition: raw_ostream.h:439
void pwrite(const char *Ptr, size_t Size, uint64_t Offset)
Definition: raw_ostream.h:442
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:661
std::string & str()
Returns the string's reference.
Definition: raw_ostream.h:679
void reserveExtraSpace(uint64_t ExtraSize) override
If possible, pre-allocate ExtraSize bytes for stream data.
Definition: raw_ostream.h:681
raw_string_ostream(std::string &O)
Definition: raw_ostream.h:672
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:691
static bool classof(const raw_ostream *OS)
~raw_svector_ostream() override=default
SmallVectorImpl< char > & buffer()
Definition: raw_ostream.h:721
void reserveExtraSpace(uint64_t ExtraSize) override
If possible, pre-allocate ExtraSize bytes for stream data.
Definition: raw_ostream.h:723
StringRef str() const
Return a StringRef for the vector contents.
Definition: raw_ostream.h:720
raw_svector_ostream(SmallVectorImpl< char > &O)
Construct a new raw_svector_ostream.
Definition: raw_ostream.h:707
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:480
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition: STLExtras.h:1680
@ Write
Definition: CodeGenData.h:103
raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
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.
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
Definition: APFixedPoint.h:292
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1856
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
#define N