LLVM  7.0.0svn
raw_ostream.h
Go to the documentation of this file.
1 //===--- raw_ostream.h - Raw output stream ----------------------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the raw_ostream class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_SUPPORT_RAW_OSTREAM_H
15 #define LLVM_SUPPORT_RAW_OSTREAM_H
16 
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringRef.h"
19 #include <cassert>
20 #include <cstddef>
21 #include <cstdint>
22 #include <cstring>
23 #include <string>
24 #include <system_error>
25 
26 namespace llvm {
27 
28 class formatv_object_base;
29 class format_object_base;
30 class FormattedString;
31 class FormattedNumber;
32 class FormattedBytes;
33 
34 namespace sys {
35 namespace fs {
36 enum OpenFlags : unsigned;
37 } // end namespace fs
38 } // end namespace sys
39 
40 /// This class implements an extremely fast bulk output stream that can *only*
41 /// output to a stream. It does not support seeking, reopening, rewinding, line
42 /// buffered disciplines etc. It is a simple buffer that outputs
43 /// a chunk at a time.
44 class raw_ostream {
45 private:
46  /// The buffer is handled in such a way that the buffer is
47  /// uninitialized, unbuffered, or out of space when OutBufCur >=
48  /// OutBufEnd. Thus a single comparison suffices to determine if we
49  /// need to take the slow path to write a single character.
50  ///
51  /// The buffer is in one of three states:
52  /// 1. Unbuffered (BufferMode == Unbuffered)
53  /// 1. Uninitialized (BufferMode != Unbuffered && OutBufStart == 0).
54  /// 2. Buffered (BufferMode != Unbuffered && OutBufStart != 0 &&
55  /// OutBufEnd - OutBufStart >= 1).
56  ///
57  /// If buffered, then the raw_ostream owns the buffer if (BufferMode ==
58  /// InternalBuffer); otherwise the buffer has been set via SetBuffer and is
59  /// managed by the subclass.
60  ///
61  /// If a subclass installs an external buffer using SetBuffer then it can wait
62  /// for a \see write_impl() call to handle the data which has been put into
63  /// this buffer.
64  char *OutBufStart, *OutBufEnd, *OutBufCur;
65 
66  enum BufferKind {
67  Unbuffered = 0,
68  InternalBuffer,
69  ExternalBuffer
70  } BufferMode;
71 
72 public:
73  // color order matches ANSI escape sequence, don't change
74  enum Colors {
75  BLACK = 0,
76  RED,
83  SAVEDCOLOR
84  };
85 
86  explicit raw_ostream(bool unbuffered = false)
87  : BufferMode(unbuffered ? Unbuffered : InternalBuffer) {
88  // Start out ready to flush.
89  OutBufStart = OutBufEnd = OutBufCur = nullptr;
90  }
91 
92  raw_ostream(const raw_ostream &) = delete;
93  void operator=(const raw_ostream &) = delete;
94 
95  virtual ~raw_ostream();
96 
97  /// tell - Return the current offset with the file.
98  uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); }
99 
100  //===--------------------------------------------------------------------===//
101  // Configuration Interface
102  //===--------------------------------------------------------------------===//
103 
104  /// Set the stream to be buffered, with an automatically determined buffer
105  /// size.
106  void SetBuffered();
107 
108  /// Set the stream to be buffered, using the specified buffer size.
109  void SetBufferSize(size_t Size) {
110  flush();
111  SetBufferAndMode(new char[Size], Size, InternalBuffer);
112  }
113 
114  size_t GetBufferSize() const {
115  // If we're supposed to be buffered but haven't actually gotten around
116  // to allocating the buffer yet, return the value that would be used.
117  if (BufferMode != Unbuffered && OutBufStart == nullptr)
118  return preferred_buffer_size();
119 
120  // Otherwise just return the size of the allocated buffer.
121  return OutBufEnd - OutBufStart;
122  }
123 
124  /// Set the stream to be unbuffered. When unbuffered, the stream will flush
125  /// after every write. This routine will also flush the buffer immediately
126  /// when the stream is being set to unbuffered.
127  void SetUnbuffered() {
128  flush();
129  SetBufferAndMode(nullptr, 0, Unbuffered);
130  }
131 
132  size_t GetNumBytesInBuffer() const {
133  return OutBufCur - OutBufStart;
134  }
135 
136  //===--------------------------------------------------------------------===//
137  // Data Output Interface
138  //===--------------------------------------------------------------------===//
139 
140  void flush() {
141  if (OutBufCur != OutBufStart)
142  flush_nonempty();
143  }
144 
146  if (OutBufCur >= OutBufEnd)
147  return write(C);
148  *OutBufCur++ = C;
149  return *this;
150  }
151 
152  raw_ostream &operator<<(unsigned char C) {
153  if (OutBufCur >= OutBufEnd)
154  return write(C);
155  *OutBufCur++ = C;
156  return *this;
157  }
158 
159  raw_ostream &operator<<(signed char C) {
160  if (OutBufCur >= OutBufEnd)
161  return write(C);
162  *OutBufCur++ = C;
163  return *this;
164  }
165 
167  // Inline fast path, particularly for strings with a known length.
168  size_t Size = Str.size();
169 
170  // Make sure we can use the fast path.
171  if (Size > (size_t)(OutBufEnd - OutBufCur))
172  return write(Str.data(), Size);
173 
174  if (Size) {
175  memcpy(OutBufCur, Str.data(), Size);
176  OutBufCur += Size;
177  }
178  return *this;
179  }
180 
181  raw_ostream &operator<<(const char *Str) {
182  // Inline fast path, particularly for constant strings where a sufficiently
183  // smart compiler will simplify strlen.
184 
185  return this->operator<<(StringRef(Str));
186  }
187 
188  raw_ostream &operator<<(const std::string &Str) {
189  // Avoid the fast path, it would only increase code size for a marginal win.
190  return write(Str.data(), Str.length());
191  }
192 
193  raw_ostream &operator<<(const SmallVectorImpl<char> &Str) {
194  return write(Str.data(), Str.size());
195  }
196 
197  raw_ostream &operator<<(unsigned long N);
198  raw_ostream &operator<<(long N);
199  raw_ostream &operator<<(unsigned long long N);
200  raw_ostream &operator<<(long long N);
201  raw_ostream &operator<<(const void *P);
202 
203  raw_ostream &operator<<(unsigned int N) {
204  return this->operator<<(static_cast<unsigned long>(N));
205  }
206 
208  return this->operator<<(static_cast<long>(N));
209  }
210 
211  raw_ostream &operator<<(double N);
212 
213  /// Output \p N in hexadecimal, without any prefix or padding.
214  raw_ostream &write_hex(unsigned long long N);
215 
216  /// Output a formatted UUID with dash separators.
217  using uuid_t = uint8_t[16];
218  raw_ostream &write_uuid(const uuid_t UUID);
219 
220  /// Output \p Str, turning '\\', '\t', '\n', '"', and anything that doesn't
221  /// satisfy std::isprint into an escape sequence.
222  raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false);
223 
224  raw_ostream &write(unsigned char C);
225  raw_ostream &write(const char *Ptr, size_t Size);
226 
227  // Formatted output, see the format() function in Support/Format.h.
229 
230  // Formatted output, see the leftJustify() function in Support/Format.h.
232 
233  // Formatted output, see the formatHex() function in Support/Format.h.
235 
236  // Formatted output, see the formatv() function in Support/FormatVariadic.h.
238 
239  // Formatted output, see the format_bytes() function in Support/Format.h.
241 
242  /// indent - Insert 'NumSpaces' spaces.
243  raw_ostream &indent(unsigned NumSpaces);
244 
245  /// write_zeros - Insert 'NumZeros' nulls.
246  raw_ostream &write_zeros(unsigned NumZeros);
247 
248  /// Changes the foreground color of text that will be output from this point
249  /// forward.
250  /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to
251  /// change only the bold attribute, and keep colors untouched
252  /// @param Bold bold/brighter text, default false
253  /// @param BG if true change the background, default: change foreground
254  /// @returns itself so it can be used within << invocations
256  bool Bold = false,
257  bool BG = false) {
258  (void)Color;
259  (void)Bold;
260  (void)BG;
261  return *this;
262  }
263 
264  /// Resets the colors to terminal defaults. Call this when you are done
265  /// outputting colored text, or before program exit.
266  virtual raw_ostream &resetColor() { return *this; }
267 
268  /// Reverses the foreground and background colors.
269  virtual raw_ostream &reverseColor() { return *this; }
270 
271  /// This function determines if this stream is connected to a "tty" or
272  /// "console" window. That is, the output would be displayed to the user
273  /// rather than being put on a pipe or stored in a file.
274  virtual bool is_displayed() const { return false; }
275 
276  /// This function determines if this stream is displayed and supports colors.
277  virtual bool has_colors() const { return is_displayed(); }
278 
279  //===--------------------------------------------------------------------===//
280  // Subclass Interface
281  //===--------------------------------------------------------------------===//
282 
283 private:
284  /// The is the piece of the class that is implemented by subclasses. This
285  /// writes the \p Size bytes starting at
286  /// \p Ptr to the underlying stream.
287  ///
288  /// This function is guaranteed to only be called at a point at which it is
289  /// safe for the subclass to install a new buffer via SetBuffer.
290  ///
291  /// \param Ptr The start of the data to be written. For buffered streams this
292  /// is guaranteed to be the start of the buffer.
293  ///
294  /// \param Size The number of bytes to be written.
295  ///
296  /// \invariant { Size > 0 }
297  virtual void write_impl(const char *Ptr, size_t Size) = 0;
298 
299  // An out of line virtual method to provide a home for the class vtable.
300  virtual void handle();
301 
302  /// Return the current position within the stream, not counting the bytes
303  /// currently in the buffer.
304  virtual uint64_t current_pos() const = 0;
305 
306 protected:
307  /// Use the provided buffer as the raw_ostream buffer. This is intended for
308  /// use only by subclasses which can arrange for the output to go directly
309  /// into the desired output buffer, instead of being copied on each flush.
310  void SetBuffer(char *BufferStart, size_t Size) {
311  SetBufferAndMode(BufferStart, Size, ExternalBuffer);
312  }
313 
314  /// Return an efficient buffer size for the underlying output mechanism.
315  virtual size_t preferred_buffer_size() const;
316 
317  /// Return the beginning of the current stream buffer, or 0 if the stream is
318  /// unbuffered.
319  const char *getBufferStart() const { return OutBufStart; }
320 
321  //===--------------------------------------------------------------------===//
322  // Private Interface
323  //===--------------------------------------------------------------------===//
324 private:
325  /// Install the given buffer and mode.
326  void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode);
327 
328  /// Flush the current buffer, which is known to be non-empty. This outputs the
329  /// currently buffered data and resets the buffer to empty.
330  void flush_nonempty();
331 
332  /// Copy data into the buffer. Size must not be greater than the number of
333  /// unused bytes in the buffer.
334  void copy_to_buffer(const char *Ptr, size_t Size);
335 
336  virtual void anchor();
337 };
338 
339 /// An abstract base class for streams implementations that also support a
340 /// pwrite operation. This is useful for code that can mostly stream out data,
341 /// but needs to patch in a header that needs to know the output size.
343  virtual void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) = 0;
344  void anchor() override;
345 
346 public:
347  explicit raw_pwrite_stream(bool Unbuffered = false)
348  : raw_ostream(Unbuffered) {}
349  void pwrite(const char *Ptr, size_t Size, uint64_t Offset) {
350 #ifndef NDBEBUG
351  uint64_t Pos = tell();
352  // /dev/null always reports a pos of 0, so we cannot perform this check
353  // in that case.
354  if (Pos)
355  assert(Size + Offset <= Pos && "We don't support extending the stream");
356 #endif
357  pwrite_impl(Ptr, Size, Offset);
358  }
359 };
360 
361 //===----------------------------------------------------------------------===//
362 // File Output Streams
363 //===----------------------------------------------------------------------===//
364 
365 /// A raw_ostream that writes to a file descriptor.
366 ///
368  int FD;
369  bool ShouldClose;
370 
371  std::error_code EC;
372 
373  uint64_t pos;
374 
375  bool SupportsSeeking;
376 
377  /// See raw_ostream::write_impl.
378  void write_impl(const char *Ptr, size_t Size) override;
379 
380  void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
381 
382  /// Return the current position within the stream, not counting the bytes
383  /// currently in the buffer.
384  uint64_t current_pos() const override { return pos; }
385 
386  /// Determine an efficient buffer size.
387  size_t preferred_buffer_size() const override;
388 
389  /// Set the flag indicating that an output error has been encountered.
390  void error_detected(std::error_code EC) { this->EC = EC; }
391 
392  void anchor() override;
393 
394 public:
395  /// Open the specified file for writing. If an error occurs, information
396  /// about the error is put into EC, and the stream should be immediately
397  /// destroyed;
398  /// \p Flags allows optional flags to control how the file will be opened.
399  ///
400  /// As a special case, if Filename is "-", then the stream will use
401  /// STDOUT_FILENO instead of opening a file. This will not close the stdout
402  /// descriptor.
403  raw_fd_ostream(StringRef Filename, std::error_code &EC,
404  sys::fs::OpenFlags Flags);
405 
406  /// FD is the file descriptor that this writes to. If ShouldClose is true,
407  /// this closes the file when the stream is destroyed. If FD is for stdout or
408  /// stderr, it will not be closed.
409  raw_fd_ostream(int fd, bool shouldClose, bool unbuffered=false);
410 
411  ~raw_fd_ostream() override;
412 
413  /// Manually flush the stream and close the file. Note that this does not call
414  /// fsync.
415  void close();
416 
417  bool supportsSeeking() { return SupportsSeeking; }
418 
419  /// Flushes the stream and repositions the underlying file descriptor position
420  /// to the offset specified from the beginning of the file.
421  uint64_t seek(uint64_t off);
422 
423  raw_ostream &changeColor(enum Colors colors, bool bold=false,
424  bool bg=false) override;
425  raw_ostream &resetColor() override;
426 
427  raw_ostream &reverseColor() override;
428 
429  bool is_displayed() const override;
430 
431  bool has_colors() const override;
432 
433  std::error_code error() const { return EC; }
434 
435  /// Return the value of the flag in this raw_fd_ostream indicating whether an
436  /// output error has been encountered.
437  /// This doesn't implicitly flush any pending output. Also, it doesn't
438  /// guarantee to detect all errors unless the stream has been closed.
439  bool has_error() const { return bool(EC); }
440 
441  /// Set the flag read by has_error() to false. If the error flag is set at the
442  /// time when this raw_ostream's destructor is called, report_fatal_error is
443  /// called to report the error. Use clear_error() after handling the error to
444  /// avoid this behavior.
445  ///
446  /// "Errors should never pass silently.
447  /// Unless explicitly silenced."
448  /// - from The Zen of Python, by Tim Peters
449  ///
450  void clear_error() { EC = std::error_code(); }
451 };
452 
453 /// This returns a reference to a raw_ostream for standard output. Use it like:
454 /// outs() << "foo" << "bar";
455 raw_ostream &outs();
456 
457 /// This returns a reference to a raw_ostream for standard error. Use it like:
458 /// errs() << "foo" << "bar";
459 raw_ostream &errs();
460 
461 /// This returns a reference to a raw_ostream which simply discards output.
462 raw_ostream &nulls();
463 
464 //===----------------------------------------------------------------------===//
465 // Output Stream Adaptors
466 //===----------------------------------------------------------------------===//
467 
468 /// A raw_ostream that writes to an std::string. This is a simple adaptor
469 /// class. This class does not encounter output errors.
471  std::string &OS;
472 
473  /// See raw_ostream::write_impl.
474  void write_impl(const char *Ptr, size_t Size) override;
475 
476  /// Return the current position within the stream, not counting the bytes
477  /// currently in the buffer.
478  uint64_t current_pos() const override { return OS.size(); }
479 
480 public:
481  explicit raw_string_ostream(std::string &O) : OS(O) {}
482  ~raw_string_ostream() override;
483 
484  /// Flushes the stream contents to the target string and returns the string's
485  /// reference.
486  std::string& str() {
487  flush();
488  return OS;
489  }
490 };
491 
492 /// A raw_ostream that writes to an SmallVector or SmallString. This is a
493 /// simple adaptor class. This class does not encounter output errors.
494 /// raw_svector_ostream operates without a buffer, delegating all memory
495 /// management to the SmallString. Thus the SmallString is always up-to-date,
496 /// may be used directly and there is no need to call flush().
499 
500  /// See raw_ostream::write_impl.
501  void write_impl(const char *Ptr, size_t Size) override;
502 
503  void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
504 
505  /// Return the current position within the stream.
506  uint64_t current_pos() const override;
507 
508 public:
509  /// Construct a new raw_svector_ostream.
510  ///
511  /// \param O The vector to write to; this should generally have at least 128
512  /// bytes free to avoid any extraneous memory overhead.
514  SetUnbuffered();
515  }
516 
517  ~raw_svector_ostream() override = default;
518 
519  void flush() = delete;
520 
521  /// Return a StringRef for the vector contents.
522  StringRef str() { return StringRef(OS.data(), OS.size()); }
523 };
524 
525 /// A raw_ostream that discards all output.
527  /// See raw_ostream::write_impl.
528  void write_impl(const char *Ptr, size_t size) override;
529  void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
530 
531  /// Return the current position within the stream, not counting the bytes
532  /// currently in the buffer.
533  uint64_t current_pos() const override;
534 
535 public:
536  explicit raw_null_ostream() = default;
537  ~raw_null_ostream() override;
538 };
539 
541  raw_ostream &OS;
542  SmallVector<char, 0> Buffer;
543 
544 public:
546  ~buffer_ostream() override { OS << str(); }
547 };
548 
549 } // end namespace llvm
550 
551 #endif // LLVM_SUPPORT_RAW_OSTREAM_H
uint64_t CallInst * C
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
uint8_t[16] uuid_t
Output a formatted UUID with dash separators.
Definition: raw_ostream.h:217
SI Whole Quad Mode
raw_string_ostream(std::string &O)
Definition: raw_ostream.h:481
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
buffer_ostream(raw_ostream &OS)
Definition: raw_ostream.h:545
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:136
A raw_ostream that discards all output.
Definition: raw_ostream.h:526
size_t GetBufferSize() const
Definition: raw_ostream.h:114
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
Definition: StringRef.h:138
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. ...
Definition: raw_ostream.h:255
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:497
raw_ostream & operator<<(const std::string &Str)
Definition: raw_ostream.h:188
std::error_code error() const
Definition: raw_ostream.h:433
raw_ostream & operator<<(const char *Str)
Definition: raw_ostream.h:181
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:128
This is a helper class for left_justify, right_justify, and center_justify.
Definition: Format.h:129
raw_ostream & operator<<(int N)
Definition: raw_ostream.h:207
void SetBuffer(char *BufferStart, size_t Size)
Use the provided buffer as the raw_ostream buffer.
Definition: raw_ostream.h:310
This is a helper class used for handling formatted output.
Definition: Format.h:38
raw_ostream & operator<<(char C)
Definition: raw_ostream.h:145
raw_ostream & outs()
This returns a reference to a raw_ostream for standard output.
#define P(N)
void SetUnbuffered()
Set the stream to be unbuffered.
Definition: raw_ostream.h:127
raw_ostream & operator<<(unsigned char C)
Definition: raw_ostream.h:152
void pwrite(const char *Ptr, size_t Size, uint64_t Offset)
Definition: raw_ostream.h:349
virtual raw_ostream & reverseColor()
Reverses the foreground and background colors.
Definition: raw_ostream.h:269
const char * getBufferStart() const
Return the beginning of the current stream buffer, or 0 if the stream is unbuffered.
Definition: raw_ostream.h:319
raw_ostream(bool unbuffered=false)
Definition: raw_ostream.h:86
static void write(bool isBE, void *P, T V)
virtual bool has_colors() const
This function determines if this stream is displayed and supports colors.
Definition: raw_ostream.h:277
void SetBufferSize(size_t Size)
Set the stream to be buffered, using the specified buffer size.
Definition: raw_ostream.h:109
std::string & str()
Flushes the stream contents to the target string and returns the string&#39;s reference.
Definition: raw_ostream.h:486
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:439
This is a helper class used for format_hex() and format_decimal().
Definition: Format.h:164
Color
A "color", which is either even or odd.
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
Definition: STLExtras.h:1032
virtual bool is_displayed() const
This function determines if this stream is connected to a "tty" or "console" window.
Definition: raw_ostream.h:274
StringRef str()
Return a StringRef for the vector contents.
Definition: raw_ostream.h:522
raw_ostream & operator<<(unsigned int N)
Definition: raw_ostream.h:203
size_t GetNumBytesInBuffer() const
Definition: raw_ostream.h:132
raw_pwrite_stream(bool Unbuffered=false)
Definition: raw_ostream.h:347
void write_hex(raw_ostream &S, uint64_t N, HexPrintStyle Style, Optional< size_t > Width=None)
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:367
pointer data()
Return a pointer to the vector&#39;s buffer, even if empty().
Definition: SmallVector.h:143
#define N
raw_ostream & operator<<(StringRef Str)
Definition: raw_ostream.h:166
~buffer_ostream() override
Definition: raw_ostream.h:546
raw_ostream & operator<<(raw_ostream &OS, const APInt &I)
Definition: APInt.h:2023
An abstract base class for streams implementations that also support a pwrite operation.
Definition: raw_ostream.h:342
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:470
virtual raw_ostream & resetColor()
Resets the colors to terminal defaults.
Definition: raw_ostream.h:266
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
raw_ostream & nulls()
This returns a reference to a raw_ostream which simply discards output.
uint64_t tell() const
tell - Return the current offset with the file.
Definition: raw_ostream.h:98
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:44
raw_svector_ostream(SmallVectorImpl< char > &O)
Construct a new raw_svector_ostream.
Definition: raw_ostream.h:513
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
raw_ostream & operator<<(signed char C)
Definition: raw_ostream.h:159
void clear_error()
Set the flag read by has_error() to false.
Definition: raw_ostream.h:450