LLVM  5.0.0
raw_ostream.cpp
Go to the documentation of this file.
1 //===--- raw_ostream.cpp - Implement the raw_ostream classes --------------===//
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 implements support for bulk buffered stream output.
11 //
12 //===----------------------------------------------------------------------===//
13 
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Config/config.h"
19 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/Format.h"
26 #include "llvm/Support/Process.h"
27 #include "llvm/Support/Program.h"
28 #include <algorithm>
29 #include <cctype>
30 #include <cerrno>
31 #include <cstdio>
32 #include <iterator>
33 #include <sys/stat.h>
34 #include <system_error>
35 
36 // <fcntl.h> may provide O_BINARY.
37 #if defined(HAVE_FCNTL_H)
38 # include <fcntl.h>
39 #endif
40 
41 #if defined(HAVE_UNISTD_H)
42 # include <unistd.h>
43 #endif
44 #if defined(HAVE_SYS_UIO_H) && defined(HAVE_WRITEV)
45 # include <sys/uio.h>
46 #endif
47 
48 #if defined(__CYGWIN__)
49 #include <io.h>
50 #endif
51 
52 #if defined(_MSC_VER)
53 #include <io.h>
54 #ifndef STDIN_FILENO
55 # define STDIN_FILENO 0
56 #endif
57 #ifndef STDOUT_FILENO
58 # define STDOUT_FILENO 1
59 #endif
60 #ifndef STDERR_FILENO
61 # define STDERR_FILENO 2
62 #endif
63 #endif
64 
65 #ifdef LLVM_ON_WIN32
66 #include "Windows/WindowsSupport.h"
67 #endif
68 
69 using namespace llvm;
70 
72  // raw_ostream's subclasses should take care to flush the buffer
73  // in their destructors.
74  assert(OutBufCur == OutBufStart &&
75  "raw_ostream destructor called with non-empty buffer!");
76 
77  if (BufferMode == InternalBuffer)
78  delete [] OutBufStart;
79 }
80 
81 // An out of line virtual method to provide a home for the class vtable.
82 void raw_ostream::handle() {}
83 
85  // BUFSIZ is intended to be a reasonable default.
86  return BUFSIZ;
87 }
88 
90  // Ask the subclass to determine an appropriate buffer size.
91  if (size_t Size = preferred_buffer_size())
93  else
94  // It may return 0, meaning this stream should be unbuffered.
95  SetUnbuffered();
96 }
97 
98 void raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size,
99  BufferKind Mode) {
100  assert(((Mode == Unbuffered && !BufferStart && Size == 0) ||
101  (Mode != Unbuffered && BufferStart && Size != 0)) &&
102  "stream must be unbuffered or have at least one byte");
103  // Make sure the current buffer is free of content (we can't flush here; the
104  // child buffer management logic will be in write_impl).
105  assert(GetNumBytesInBuffer() == 0 && "Current buffer is non-empty!");
106 
107  if (BufferMode == InternalBuffer)
108  delete [] OutBufStart;
109  OutBufStart = BufferStart;
110  OutBufEnd = OutBufStart+Size;
111  OutBufCur = OutBufStart;
112  BufferMode = Mode;
113 
114  assert(OutBufStart <= OutBufEnd && "Invalid size!");
115 }
116 
118  write_integer(*this, static_cast<uint64_t>(N), 0, IntegerStyle::Integer);
119  return *this;
120 }
121 
123  write_integer(*this, static_cast<int64_t>(N), 0, IntegerStyle::Integer);
124  return *this;
125 }
126 
127 raw_ostream &raw_ostream::operator<<(unsigned long long N) {
128  write_integer(*this, static_cast<uint64_t>(N), 0, IntegerStyle::Integer);
129  return *this;
130 }
131 
133  write_integer(*this, static_cast<int64_t>(N), 0, IntegerStyle::Integer);
134  return *this;
135 }
136 
137 raw_ostream &raw_ostream::write_hex(unsigned long long N) {
139  return *this;
140 }
141 
143  bool UseHexEscapes) {
144  for (unsigned char c : Str) {
145  switch (c) {
146  case '\\':
147  *this << '\\' << '\\';
148  break;
149  case '\t':
150  *this << '\\' << 't';
151  break;
152  case '\n':
153  *this << '\\' << 'n';
154  break;
155  case '"':
156  *this << '\\' << '"';
157  break;
158  default:
159  if (std::isprint(c)) {
160  *this << c;
161  break;
162  }
163 
164  // Write out the escaped representation.
165  if (UseHexEscapes) {
166  *this << '\\' << 'x';
167  *this << hexdigit((c >> 4 & 0xF));
168  *this << hexdigit((c >> 0) & 0xF);
169  } else {
170  // Always use a full 3-character octal escape.
171  *this << '\\';
172  *this << char('0' + ((c >> 6) & 7));
173  *this << char('0' + ((c >> 3) & 7));
174  *this << char('0' + ((c >> 0) & 7));
175  }
176  }
177  }
178 
179  return *this;
180 }
181 
183  llvm::write_hex(*this, (uintptr_t)P, HexPrintStyle::PrefixLower);
184  return *this;
185 }
186 
189  return *this;
190 }
191 
192 void raw_ostream::flush_nonempty() {
193  assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
194  size_t Length = OutBufCur - OutBufStart;
195  OutBufCur = OutBufStart;
196  write_impl(OutBufStart, Length);
197 }
198 
200  // Group exceptional cases into a single branch.
201  if (LLVM_UNLIKELY(OutBufCur >= OutBufEnd)) {
202  if (LLVM_UNLIKELY(!OutBufStart)) {
203  if (BufferMode == Unbuffered) {
204  write_impl(reinterpret_cast<char*>(&C), 1);
205  return *this;
206  }
207  // Set up a buffer and start over.
208  SetBuffered();
209  return write(C);
210  }
211 
212  flush_nonempty();
213  }
214 
215  *OutBufCur++ = C;
216  return *this;
217 }
218 
219 raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
220  // Group exceptional cases into a single branch.
221  if (LLVM_UNLIKELY(size_t(OutBufEnd - OutBufCur) < Size)) {
222  if (LLVM_UNLIKELY(!OutBufStart)) {
223  if (BufferMode == Unbuffered) {
224  write_impl(Ptr, Size);
225  return *this;
226  }
227  // Set up a buffer and start over.
228  SetBuffered();
229  return write(Ptr, Size);
230  }
231 
232  size_t NumBytes = OutBufEnd - OutBufCur;
233 
234  // If the buffer is empty at this point we have a string that is larger
235  // than the buffer. Directly write the chunk that is a multiple of the
236  // preferred buffer size and put the remainder in the buffer.
237  if (LLVM_UNLIKELY(OutBufCur == OutBufStart)) {
238  assert(NumBytes != 0 && "undefined behavior");
239  size_t BytesToWrite = Size - (Size % NumBytes);
240  write_impl(Ptr, BytesToWrite);
241  size_t BytesRemaining = Size - BytesToWrite;
242  if (BytesRemaining > size_t(OutBufEnd - OutBufCur)) {
243  // Too much left over to copy into our buffer.
244  return write(Ptr + BytesToWrite, BytesRemaining);
245  }
246  copy_to_buffer(Ptr + BytesToWrite, BytesRemaining);
247  return *this;
248  }
249 
250  // We don't have enough space in the buffer to fit the string in. Insert as
251  // much as possible, flush and start over with the remainder.
252  copy_to_buffer(Ptr, NumBytes);
253  flush_nonempty();
254  return write(Ptr + NumBytes, Size - NumBytes);
255  }
256 
257  copy_to_buffer(Ptr, Size);
258 
259  return *this;
260 }
261 
262 void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
263  assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
264 
265  // Handle short strings specially, memcpy isn't very good at very short
266  // strings.
267  switch (Size) {
268  case 4: OutBufCur[3] = Ptr[3]; LLVM_FALLTHROUGH;
269  case 3: OutBufCur[2] = Ptr[2]; LLVM_FALLTHROUGH;
270  case 2: OutBufCur[1] = Ptr[1]; LLVM_FALLTHROUGH;
271  case 1: OutBufCur[0] = Ptr[0]; LLVM_FALLTHROUGH;
272  case 0: break;
273  default:
274  memcpy(OutBufCur, Ptr, Size);
275  break;
276  }
277 
278  OutBufCur += Size;
279 }
280 
281 // Formatted output.
283  // If we have more than a few bytes left in our output buffer, try
284  // formatting directly onto its end.
285  size_t NextBufferSize = 127;
286  size_t BufferBytesLeft = OutBufEnd - OutBufCur;
287  if (BufferBytesLeft > 3) {
288  size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
289 
290  // Common case is that we have plenty of space.
291  if (BytesUsed <= BufferBytesLeft) {
292  OutBufCur += BytesUsed;
293  return *this;
294  }
295 
296  // Otherwise, we overflowed and the return value tells us the size to try
297  // again with.
298  NextBufferSize = BytesUsed;
299  }
300 
301  // If we got here, we didn't have enough space in the output buffer for the
302  // string. Try printing into a SmallVector that is resized to have enough
303  // space. Iterate until we win.
305 
306  while (true) {
307  V.resize(NextBufferSize);
308 
309  // Try formatting into the SmallVector.
310  size_t BytesUsed = Fmt.print(V.data(), NextBufferSize);
311 
312  // If BytesUsed fit into the vector, we win.
313  if (BytesUsed <= NextBufferSize)
314  return write(V.data(), BytesUsed);
315 
316  // Otherwise, try again with a new size.
317  assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
318  NextBufferSize = BytesUsed;
319  }
320 }
321 
324  Obj.format(*this);
325  return *this;
326 }
327 
329  if (FS.Str.size() >= FS.Width || FS.Justify == FormattedString::JustifyNone) {
330  this->operator<<(FS.Str);
331  return *this;
332  }
333  const size_t Difference = FS.Width - FS.Str.size();
334  switch (FS.Justify) {
336  this->operator<<(FS.Str);
337  this->indent(Difference);
338  break;
340  this->indent(Difference);
341  this->operator<<(FS.Str);
342  break;
344  int PadAmount = Difference / 2;
345  this->indent(PadAmount);
346  this->operator<<(FS.Str);
347  this->indent(Difference - PadAmount);
348  break;
349  }
350  default:
351  llvm_unreachable("Bad Justification");
352  }
353  return *this;
354 }
355 
357  if (FN.Hex) {
359  if (FN.Upper && FN.HexPrefix)
361  else if (FN.Upper && !FN.HexPrefix)
362  Style = HexPrintStyle::Upper;
363  else if (!FN.Upper && FN.HexPrefix)
365  else
366  Style = HexPrintStyle::Lower;
367  llvm::write_hex(*this, FN.HexValue, Style, FN.Width);
368  } else {
369  llvm::SmallString<16> Buffer;
370  llvm::raw_svector_ostream Stream(Buffer);
371  llvm::write_integer(Stream, FN.DecValue, 0, IntegerStyle::Integer);
372  if (Buffer.size() < FN.Width)
373  indent(FN.Width - Buffer.size());
374  (*this) << Buffer;
375  }
376  return *this;
377 }
378 
380  if (FB.Bytes.empty())
381  return *this;
382 
383  size_t LineIndex = 0;
384  auto Bytes = FB.Bytes;
385  const size_t Size = Bytes.size();
387  uint64_t OffsetWidth = 0;
388  if (FB.FirstByteOffset.hasValue()) {
389  // Figure out how many nibbles are needed to print the largest offset
390  // represented by this data set, so that we can align the offset field
391  // to the right width.
392  size_t Lines = Size / FB.NumPerLine;
393  uint64_t MaxOffset = *FB.FirstByteOffset + Lines * FB.NumPerLine;
394  unsigned Power = 0;
395  if (MaxOffset > 0)
396  Power = llvm::Log2_64_Ceil(MaxOffset);
397  OffsetWidth = std::max<uint64_t>(4, llvm::alignTo(Power, 4) / 4);
398  }
399 
400  // The width of a block of data including all spaces for group separators.
401  unsigned NumByteGroups =
402  alignTo(FB.NumPerLine, FB.ByteGroupSize) / FB.ByteGroupSize;
403  unsigned BlockCharWidth = FB.NumPerLine * 2 + NumByteGroups - 1;
404 
405  while (!Bytes.empty()) {
406  indent(FB.IndentLevel);
407 
408  if (FB.FirstByteOffset.hasValue()) {
409  uint64_t Offset = FB.FirstByteOffset.getValue();
410  llvm::write_hex(*this, Offset + LineIndex, HPS, OffsetWidth);
411  *this << ": ";
412  }
413 
414  auto Line = Bytes.take_front(FB.NumPerLine);
415 
416  size_t CharsPrinted = 0;
417  // Print the hex bytes for this line in groups
418  for (size_t I = 0; I < Line.size(); ++I, CharsPrinted += 2) {
419  if (I && (I % FB.ByteGroupSize) == 0) {
420  ++CharsPrinted;
421  *this << " ";
422  }
423  llvm::write_hex(*this, Line[I], HPS, 2);
424  }
425 
426  if (FB.ASCII) {
427  // Print any spaces needed for any bytes that we didn't print on this
428  // line so that the ASCII bytes are correctly aligned.
429  assert(BlockCharWidth >= CharsPrinted);
430  indent(BlockCharWidth - CharsPrinted + 2);
431  *this << "|";
432 
433  // Print the ASCII char values for each byte on this line
434  for (uint8_t Byte : Line) {
435  if (isprint(Byte))
436  *this << static_cast<char>(Byte);
437  else
438  *this << '.';
439  }
440  *this << '|';
441  }
442 
443  Bytes = Bytes.drop_front(Line.size());
444  LineIndex += Line.size();
445  if (LineIndex < Size)
446  *this << '\n';
447  }
448  return *this;
449 }
450 
451 /// indent - Insert 'NumSpaces' spaces.
452 raw_ostream &raw_ostream::indent(unsigned NumSpaces) {
453  static const char Spaces[] = " "
454  " "
455  " ";
456 
457  // Usually the indentation is small, handle it with a fastpath.
458  if (NumSpaces < array_lengthof(Spaces))
459  return write(Spaces, NumSpaces);
460 
461  while (NumSpaces) {
462  unsigned NumToWrite = std::min(NumSpaces,
463  (unsigned)array_lengthof(Spaces)-1);
464  write(Spaces, NumToWrite);
465  NumSpaces -= NumToWrite;
466  }
467  return *this;
468 }
469 
470 //===----------------------------------------------------------------------===//
471 // Formatted Output
472 //===----------------------------------------------------------------------===//
473 
474 // Out of line virtual method.
476 }
477 
478 //===----------------------------------------------------------------------===//
479 // raw_fd_ostream
480 //===----------------------------------------------------------------------===//
481 
482 static int getFD(StringRef Filename, std::error_code &EC,
484  // Handle "-" as stdout. Note that when we do this, we consider ourself
485  // the owner of stdout and may set the "binary" flag globally based on Flags.
486  if (Filename == "-") {
487  EC = std::error_code();
488  // If user requested binary then put stdout into binary mode if
489  // possible.
490  if (!(Flags & sys::fs::F_Text))
492  return STDOUT_FILENO;
493  }
494 
495  int FD;
496  EC = sys::fs::openFileForWrite(Filename, FD, Flags);
497  if (EC)
498  return -1;
499 
500  return FD;
501 }
502 
503 raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC,
505  : raw_fd_ostream(getFD(Filename, EC, Flags), true) {}
506 
507 /// FD is the file descriptor that this writes to. If ShouldClose is true, this
508 /// closes the file when the stream is destroyed.
509 raw_fd_ostream::raw_fd_ostream(int fd, bool shouldClose, bool unbuffered)
510  : raw_pwrite_stream(unbuffered), FD(fd), ShouldClose(shouldClose),
511  Error(false) {
512  if (FD < 0 ) {
513  ShouldClose = false;
514  return;
515  }
516  // We do not want to close STDOUT as there may have been several uses of it
517  // such as the case: llc %s -o=- -pass-remarks-output=- -filetype=asm
518  // which cause multiple closes of STDOUT_FILENO and/or use-after-close of it.
519  // Using dup() in getFD doesn't work as we end up with original STDOUT_FILENO
520  // open anyhow.
521  if (FD <= STDERR_FILENO)
522  ShouldClose = false;
523 
524  // Get the starting position.
525  off_t loc = ::lseek(FD, 0, SEEK_CUR);
526 #ifdef LLVM_ON_WIN32
527  // MSVCRT's _lseek(SEEK_CUR) doesn't return -1 for pipes.
528  sys::fs::file_status Status;
529  std::error_code EC = status(FD, Status);
530  SupportsSeeking = !EC && Status.type() == sys::fs::file_type::regular_file;
531 #else
532  SupportsSeeking = loc != (off_t)-1;
533 #endif
534  if (!SupportsSeeking)
535  pos = 0;
536  else
537  pos = static_cast<uint64_t>(loc);
538 }
539 
541  if (FD >= 0) {
542  flush();
543  if (ShouldClose && sys::Process::SafelyCloseFileDescriptor(FD))
544  error_detected();
545  }
546 
547 #ifdef __MINGW32__
548  // On mingw, global dtors should not call exit().
549  // report_fatal_error() invokes exit(). We know report_fatal_error()
550  // might not write messages to stderr when any errors were detected
551  // on FD == 2.
552  if (FD == 2) return;
553 #endif
554 
555  // If there are any pending errors, report them now. Clients wishing
556  // to avoid report_fatal_error calls should check for errors with
557  // has_error() and clear the error flag with clear_error() before
558  // destructing raw_ostream objects which may have errors.
559  if (has_error())
560  report_fatal_error("IO failure on output stream.", /*GenCrashDiag=*/false);
561 }
562 
563 void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
564  assert(FD >= 0 && "File already closed.");
565  pos += Size;
566 
567 #ifndef LLVM_ON_WIN32
568 #if defined(__linux__)
569  bool ShouldWriteInChunks = true;
570 #else
571  bool ShouldWriteInChunks = false;
572 #endif
573 #else
574  // Writing a large size of output to Windows console returns ENOMEM. It seems
575  // that, prior to Windows 8, WriteFile() is redirecting to WriteConsole(), and
576  // the latter has a size limit (66000 bytes or less, depending on heap usage).
577  bool ShouldWriteInChunks = !!::_isatty(FD) && !RunningWindows8OrGreater();
578 #endif
579 
580  do {
581  size_t ChunkSize = Size;
582  if (ChunkSize > 32767 && ShouldWriteInChunks)
583  ChunkSize = 32767;
584 
585  ssize_t ret = ::write(FD, Ptr, ChunkSize);
586 
587  if (ret < 0) {
588  // If it's a recoverable error, swallow it and retry the write.
589  //
590  // Ideally we wouldn't ever see EAGAIN or EWOULDBLOCK here, since
591  // raw_ostream isn't designed to do non-blocking I/O. However, some
592  // programs, such as old versions of bjam, have mistakenly used
593  // O_NONBLOCK. For compatibility, emulate blocking semantics by
594  // spinning until the write succeeds. If you don't want spinning,
595  // don't use O_NONBLOCK file descriptors with raw_ostream.
596  if (errno == EINTR || errno == EAGAIN
597 #ifdef EWOULDBLOCK
598  || errno == EWOULDBLOCK
599 #endif
600  )
601  continue;
602 
603  // Otherwise it's a non-recoverable error. Note it and quit.
604  error_detected();
605  break;
606  }
607 
608  // The write may have written some or all of the data. Update the
609  // size and buffer pointer to reflect the remainder that needs
610  // to be written. If there are no bytes left, we're done.
611  Ptr += ret;
612  Size -= ret;
613  } while (Size > 0);
614 }
615 
617  assert(ShouldClose);
618  ShouldClose = false;
619  flush();
621  error_detected();
622  FD = -1;
623 }
624 
625 uint64_t raw_fd_ostream::seek(uint64_t off) {
626  assert(SupportsSeeking && "Stream does not support seeking!");
627  flush();
628 #ifdef LLVM_ON_WIN32
629  pos = ::_lseeki64(FD, off, SEEK_SET);
630 #elif defined(HAVE_LSEEK64)
631  pos = ::lseek64(FD, off, SEEK_SET);
632 #else
633  pos = ::lseek(FD, off, SEEK_SET);
634 #endif
635  if (pos == (uint64_t)-1)
636  error_detected();
637  return pos;
638 }
639 
640 void raw_fd_ostream::pwrite_impl(const char *Ptr, size_t Size,
641  uint64_t Offset) {
642  uint64_t Pos = tell();
643  seek(Offset);
644  write(Ptr, Size);
645  seek(Pos);
646 }
647 
648 size_t raw_fd_ostream::preferred_buffer_size() const {
649 #if !defined(_MSC_VER) && !defined(__MINGW32__) && !defined(__minix)
650  // Windows and Minix have no st_blksize.
651  assert(FD >= 0 && "File not yet open!");
652  struct stat statbuf;
653  if (fstat(FD, &statbuf) != 0)
654  return 0;
655 
656  // If this is a terminal, don't use buffering. Line buffering
657  // would be a more traditional thing to do, but it's not worth
658  // the complexity.
659  if (S_ISCHR(statbuf.st_mode) && isatty(FD))
660  return 0;
661  // Return the preferred block size.
662  return statbuf.st_blksize;
663 #else
665 #endif
666 }
667 
669  bool bg) {
671  flush();
672  const char *colorcode =
673  (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
674  : sys::Process::OutputColor(colors, bold, bg);
675  if (colorcode) {
676  size_t len = strlen(colorcode);
677  write(colorcode, len);
678  // don't account colors towards output characters
679  pos -= len;
680  }
681  return *this;
682 }
683 
686  flush();
687  const char *colorcode = sys::Process::ResetColor();
688  if (colorcode) {
689  size_t len = strlen(colorcode);
690  write(colorcode, len);
691  // don't account colors towards output characters
692  pos -= len;
693  }
694  return *this;
695 }
696 
699  flush();
700  const char *colorcode = sys::Process::OutputReverse();
701  if (colorcode) {
702  size_t len = strlen(colorcode);
703  write(colorcode, len);
704  // don't account colors towards output characters
705  pos -= len;
706  }
707  return *this;
708 }
709 
712 }
713 
716 }
717 
718 //===----------------------------------------------------------------------===//
719 // outs(), errs(), nulls()
720 //===----------------------------------------------------------------------===//
721 
722 /// outs() - This returns a reference to a raw_ostream for standard output.
723 /// Use it like: outs() << "foo" << "bar";
725  // Set buffer settings to model stdout behavior. Delete the file descriptor
726  // when the program exits, forcing error detection. This means that if you
727  // ever call outs(), you can't open another raw_fd_ostream on stdout, as we'll
728  // close stdout twice and print an error the second time.
729  std::error_code EC;
730  static raw_fd_ostream S("-", EC, sys::fs::F_None);
731  assert(!EC);
732  return S;
733 }
734 
735 /// errs() - This returns a reference to a raw_ostream for standard error.
736 /// Use it like: errs() << "foo" << "bar";
738  // Set standard error to be unbuffered by default.
739  static raw_fd_ostream S(STDERR_FILENO, false, true);
740  return S;
741 }
742 
743 /// nulls() - This returns a reference to a raw_ostream which discards output.
745  static raw_null_ostream S;
746  return S;
747 }
748 
749 //===----------------------------------------------------------------------===//
750 // raw_string_ostream
751 //===----------------------------------------------------------------------===//
752 
754  flush();
755 }
756 
757 void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
758  OS.append(Ptr, Size);
759 }
760 
761 //===----------------------------------------------------------------------===//
762 // raw_svector_ostream
763 //===----------------------------------------------------------------------===//
764 
765 uint64_t raw_svector_ostream::current_pos() const { return OS.size(); }
766 
767 void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
768  OS.append(Ptr, Ptr + Size);
769 }
770 
771 void raw_svector_ostream::pwrite_impl(const char *Ptr, size_t Size,
772  uint64_t Offset) {
773  memcpy(OS.data() + Offset, Ptr, Size);
774 }
775 
776 //===----------------------------------------------------------------------===//
777 // raw_null_ostream
778 //===----------------------------------------------------------------------===//
779 
781 #ifndef NDEBUG
782  // ~raw_ostream asserts that the buffer is empty. This isn't necessary
783  // with raw_null_ostream, but it's better to have raw_null_ostream follow
784  // the rules than to change the rules just for raw_null_ostream.
785  flush();
786 #endif
787 }
788 
789 void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
790 }
791 
792 uint64_t raw_null_ostream::current_pos() const {
793  return 0;
794 }
795 
796 void raw_null_ostream::pwrite_impl(const char *Ptr, size_t Size,
797  uint64_t Offset) {}
bool has_colors() const override
This function determines if this stream is displayed and supports colors.
bool is_displayed() const override
This function determines if this stream is connected to a "tty" or "console" window.
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
SI Whole Quad Mode
bool hasValue() const
Definition: Optional.h:133
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:103
static const char * ResetColor()
Resets the terminals colors, or returns an escape sequence to do so.
#define LLVM_UNLIKELY(EXPR)
Definition: Compiler.h:176
static const char * OutputColor(char c, bool bold, bool bg)
This function returns the colorcode escape sequences.
std::error_code ChangeStdoutToBinary()
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with tries to cleanse the provided crash input to make it contain fewer original bytes Use with exact_artifact_path to specify the output Experimental Use value profile to guide fuzzing Number of jobs to run If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
A raw_ostream that discards all output.
Definition: raw_ostream.h:519
virtual ~raw_ostream()
Definition: raw_ostream.cpp:71
uint64_t seek(uint64_t off)
Flushes the stream and repositions the underlying file descriptor position to the offset specified fr...
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
static bool FileDescriptorHasColors(int fd)
This function determines if the given file descriptor is displayd and supports colors.
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:490
static bool FileDescriptorIsDisplayed(int fd)
This function determines if the given file descriptor is connected to a "tty" or "console" window...
uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the next integer (mod 2**64) that is greater than or equal to Value and is a multiple of Alig...
Definition: MathExtras.h:677
file_status - Represents the result of a call to stat and friends.
Definition: FileSystem.h:146
void write_double(raw_ostream &S, double D, FloatStyle Style, Optional< size_t > Precision=None)
This is a helper class for left_justify, right_justify, and center_justify.
Definition: Format.h:129
static bool ColorNeedsFlush()
Whether changing colors requires the output to be flushed.
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:428
static const char * OutputReverse()
This function returns the escape sequence to reverse forground and background colors.
uint64_t tell() const
tell - Return the current offset with the file.
Definition: raw_ostream.h:98
const T & getValue() const LLVM_LVALUE_FUNCTION
Definition: Optional.h:129
raw_ostream & write_hex(unsigned long long N)
Output N in hexadecimal, without any prefix or padding.
void format(raw_ostream &S) const
~raw_fd_ostream() override
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
Definition: StringRef.h:138
This is a helper class used for handling formatted output.
Definition: Format.h:38
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:149
raw_ostream & operator<<(char C)
Definition: raw_ostream.h:145
unsigned print(char *Buffer, unsigned BufferSize) const
Format the object into the specified buffer.
Definition: Format.h:54
raw_ostream & outs()
This returns a reference to a raw_ostream for standard output.
Function Alias Analysis false
#define P(N)
static int getFD(StringRef Filename, std::error_code &EC, sys::fs::OpenFlags Flags)
raw_ostream & resetColor() override
Resets the colors to terminal defaults.
std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
void SetUnbuffered()
Set the stream to be unbuffered.
Definition: raw_ostream.h:127
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:144
raw_fd_ostream(StringRef Filename, std::error_code &EC, sys::fs::OpenFlags Flags)
Open the specified file for writing.
void SetBufferSize(size_t Size)
Set the stream to be buffered, using the specified buffer size.
Definition: raw_ostream.h:109
~raw_null_ostream() override
bool RunningWindows8OrGreater()
Determines if the program is running on Windows 8 or newer.
raw_ostream & write(unsigned char C)
raw_ostream & write_escaped(StringRef Str, bool UseHexEscapes=false)
Output Str, turning '\', '', ' ', '"', and anything that doesn't satisfy std::isprint into an escape...
This is a helper class used for format_hex() and format_decimal().
Definition: Format.h:164
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
constexpr size_t array_lengthof(T(&)[N])
Find the length of an array.
Definition: STLExtras.h:731
const size_t N
virtual size_t preferred_buffer_size() const
Return an efficient buffer size for the underlying output mechanism.
Definition: raw_ostream.cpp:84
unsigned Log2_64_Ceil(uint64_t Value)
Return the ceil log base 2 of the specified value, 64 if the value is zero.
Definition: MathExtras.h:550
The file should be opened in text mode on platforms that make this distinction.
Definition: FileSystem.h:708
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:395
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
llvm_unreachable("Unknown RegBank!")
void SetBuffered()
Set the stream to be buffered, with an automatically determined buffer size.
Definition: raw_ostream.cpp:89
static std::vector< std::string > Flags
Definition: FlagsTest.cpp:8
Basic Alias true
Provides a library for accessing information about this process and other processes on the operating ...
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:357
pointer data()
Return a pointer to the vector's buffer, even if empty().
Definition: SmallVector.h:142
#define C
Definition: LargeTest.cpp:25
#define I(x, y, z)
Definition: MD5.cpp:58
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:135
void close()
Manually flush the stream and close the file.
An abstract base class for streams implementations that also support a pwrite operation.
Definition: raw_ostream.h:333
static const char * OutputBold(bool bg)
Same as OutputColor, but only enables the bold attribute.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Definition: Compiler.h:235
Lightweight error class with error context and mandatory checking.
Definition: Error.h:156
raw_ostream & nulls()
This returns a reference to a raw_ostream which simply discards output.
raw_ostream & changeColor(enum Colors colors, bool bold=false, bool bg=false) override
Changes the foreground color of text that will be output from this point forward. ...
static std::error_code SafelyCloseFileDescriptor(int FD)
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:44
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
int * Ptr
void write_integer(raw_ostream &S, unsigned int N, size_t MinDigits, IntegerStyle Style)
file_type type() const
Definition: FileSystem.h:206
raw_ostream & reverseColor() override
Reverses the foreground and background colors.
size_t GetNumBytesInBuffer() const
Definition: raw_ostream.h:132
void resize(size_type N)
Definition: SmallVector.h:352
std::error_code openFileForWrite(const Twine &Name, int &ResultFD, OpenFlags Flags, unsigned Mode=0666)