1 //===--- raw_ostream.cpp - Implement the raw_ostream classes --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements support for bulk buffered stream output.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Support/raw_ostream.h"
15 #include "llvm/Support/Format.h"
16 #include "llvm/System/Program.h"
17 #include "llvm/System/Process.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/Config/config.h"
20 #include "llvm/Support/Compiler.h"
21 #include "llvm/Support/ErrorHandling.h"
24 #include <sys/types.h>
26 #if defined(HAVE_UNISTD_H)
29 #if defined(HAVE_FCNTL_H)
37 # define STDIN_FILENO 0
40 # define STDOUT_FILENO 1
43 # define STDERR_FILENO 2
49 raw_ostream::~raw_ostream() {
50 // raw_ostream's subclasses should take care to flush the buffer
51 // in their destructors.
52 assert(OutBufCur == OutBufStart &&
53 "raw_ostream destructor called with non-empty buffer!");
55 if (BufferMode == InternalBuffer)
56 delete [] OutBufStart;
58 // If there are any pending errors, report them now. Clients wishing
59 // to avoid llvm_report_error calls should check for errors with
60 // has_error() and clear the error flag with clear_error() before
61 // destructing raw_ostream objects which may have errors.
63 llvm_report_error("IO failure on output stream.");
66 // An out of line virtual method to provide a home for the class vtable.
67 void raw_ostream::handle() {}
69 size_t raw_ostream::preferred_buffer_size() {
70 // BUFSIZ is intended to be a reasonable default.
74 void raw_ostream::SetBuffered() {
75 // Ask the subclass to determine an appropriate buffer size.
76 if (size_t Size = preferred_buffer_size())
79 // It may return 0, meaning this stream should be unbuffered.
83 void raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size,
85 assert(((Mode == Unbuffered && BufferStart == 0 && Size == 0) ||
86 (Mode != Unbuffered && BufferStart && Size >= 64)) &&
87 "stream must be unbuffered, or have >= 64 bytes of buffer");
88 // Make sure the current buffer is free of content (we can't flush here; the
89 // child buffer management logic will be in write_impl).
90 assert(GetNumBytesInBuffer() == 0 && "Current buffer is non-empty!");
92 if (BufferMode == InternalBuffer)
93 delete [] OutBufStart;
94 OutBufStart = BufferStart;
95 OutBufEnd = OutBufStart+Size;
96 OutBufCur = OutBufStart;
99 assert(OutBufStart <= OutBufEnd && "Invalid size!");
102 raw_ostream &raw_ostream::operator<<(unsigned long N) {
103 // Zero is a special case.
107 char NumberBuffer[20];
108 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
109 char *CurPtr = EndPtr;
112 *--CurPtr = '0' + char(N % 10);
115 return write(CurPtr, EndPtr-CurPtr);
118 raw_ostream &raw_ostream::operator<<(long N) {
124 return this->operator<<(static_cast<unsigned long>(N));
127 raw_ostream &raw_ostream::operator<<(unsigned long long N) {
128 // Output using 32-bit div/mod when possible.
129 if (N == static_cast<unsigned long>(N))
130 return this->operator<<(static_cast<unsigned long>(N));
132 char NumberBuffer[20];
133 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
134 char *CurPtr = EndPtr;
137 *--CurPtr = '0' + char(N % 10);
140 return write(CurPtr, EndPtr-CurPtr);
143 raw_ostream &raw_ostream::operator<<(long long N) {
149 return this->operator<<(static_cast<unsigned long long>(N));
152 raw_ostream &raw_ostream::write_hex(unsigned long long N) {
153 // Zero is a special case.
157 char NumberBuffer[20];
158 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
159 char *CurPtr = EndPtr;
162 uintptr_t x = N % 16;
163 *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
167 return write(CurPtr, EndPtr-CurPtr);
170 raw_ostream &raw_ostream::operator<<(const void *P) {
173 return write_hex((uintptr_t) P);
176 void raw_ostream::flush_nonempty() {
177 assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
178 size_t Length = OutBufCur - OutBufStart;
179 OutBufCur = OutBufStart;
180 write_impl(OutBufStart, Length);
183 raw_ostream &raw_ostream::write(unsigned char C) {
184 // Group exceptional cases into a single branch.
185 if (BUILTIN_EXPECT(OutBufCur >= OutBufEnd, false)) {
186 if (BUILTIN_EXPECT(!OutBufStart, false)) {
187 if (BufferMode == Unbuffered) {
188 write_impl(reinterpret_cast<char*>(&C), 1);
191 // Set up a buffer and start over.
203 raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
204 // Group exceptional cases into a single branch.
205 if (BUILTIN_EXPECT(OutBufCur+Size > OutBufEnd, false)) {
206 if (BUILTIN_EXPECT(!OutBufStart, false)) {
207 if (BufferMode == Unbuffered) {
208 write_impl(Ptr, Size);
211 // Set up a buffer and start over.
213 return write(Ptr, Size);
216 // Write out the data in buffer-sized blocks until the remainder
217 // fits within the buffer.
219 size_t NumBytes = OutBufEnd - OutBufCur;
220 copy_to_buffer(Ptr, NumBytes);
224 } while (OutBufCur+Size > OutBufEnd);
227 copy_to_buffer(Ptr, Size);
232 void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
233 assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
235 // Handle short strings specially, memcpy isn't very good at very short
238 case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
239 case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
240 case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
241 case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
244 memcpy(OutBufCur, Ptr, Size);
252 raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
253 // If we have more than a few bytes left in our output buffer, try
254 // formatting directly onto its end.
255 size_t NextBufferSize = 127;
256 if (OutBufEnd-OutBufCur > 3) {
257 size_t BufferBytesLeft = OutBufEnd-OutBufCur;
258 size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
260 // Common case is that we have plenty of space.
261 if (BytesUsed < BufferBytesLeft) {
262 OutBufCur += BytesUsed;
266 // Otherwise, we overflowed and the return value tells us the size to try
268 NextBufferSize = BytesUsed;
271 // If we got here, we didn't have enough space in the output buffer for the
272 // string. Try printing into a SmallVector that is resized to have enough
273 // space. Iterate until we win.
274 SmallVector<char, 128> V;
277 V.resize(NextBufferSize);
279 // Try formatting into the SmallVector.
280 size_t BytesUsed = Fmt.print(&V[0], NextBufferSize);
282 // If BytesUsed fit into the vector, we win.
283 if (BytesUsed <= NextBufferSize)
284 return write(&V[0], BytesUsed);
286 // Otherwise, try again with a new size.
287 assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
288 NextBufferSize = BytesUsed;
292 /// indent - Insert 'NumSpaces' spaces.
293 raw_ostream &raw_ostream::indent(unsigned NumSpaces) {
294 const char *Spaces = " ";
296 // Usually the indentation is small, handle it with a fastpath.
298 return write(Spaces, NumSpaces);
301 unsigned NumToWrite = std::min(NumSpaces, 16U);
302 write(Spaces, NumToWrite);
303 NumSpaces -= NumToWrite;
309 //===----------------------------------------------------------------------===//
311 //===----------------------------------------------------------------------===//
313 // Out of line virtual method.
314 void format_object_base::home() {
317 //===----------------------------------------------------------------------===//
319 //===----------------------------------------------------------------------===//
321 /// raw_fd_ostream - Open the specified file for writing. If an error
322 /// occurs, information about the error is put into ErrorInfo, and the
323 /// stream should be immediately destroyed; the string will be empty
324 /// if no error occurred.
325 raw_fd_ostream::raw_fd_ostream(const char *Filename, std::string &ErrorInfo,
326 unsigned Flags) : pos(0) {
327 // Verify that we don't have both "append" and "force".
328 assert((!(Flags & F_Force) || !(Flags & F_Append)) &&
329 "Cannot specify both 'force' and 'append' file creation flags!");
333 // Handle "-" as stdout.
334 if (Filename[0] == '-' && Filename[1] == 0) {
336 // If user requested binary then put stdout into binary mode if
338 if (Flags & F_Binary)
339 sys::Program::ChangeStdoutToBinary();
344 int OpenFlags = O_WRONLY|O_CREAT;
346 if (Flags & F_Binary)
347 OpenFlags |= O_BINARY;
351 OpenFlags |= O_TRUNC;
352 else if (Flags & F_Append)
353 OpenFlags |= O_APPEND;
357 FD = open(Filename, OpenFlags, 0664);
359 ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
366 raw_fd_ostream::~raw_fd_ostream() {
370 if (::close(FD) != 0)
375 void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
376 assert (FD >= 0 && "File already closed.");
378 if (::write(FD, Ptr, Size) != (ssize_t) Size)
382 void raw_fd_ostream::close() {
383 assert (ShouldClose);
386 if (::close(FD) != 0)
391 uint64_t raw_fd_ostream::seek(uint64_t off) {
393 pos = ::lseek(FD, off, SEEK_SET);
399 size_t raw_fd_ostream::preferred_buffer_size() {
400 #if !defined(_MSC_VER) && !defined(__MINGW32__) // Windows has no st_blksize.
401 assert(FD >= 0 && "File not yet open!");
403 if (fstat(FD, &statbuf) == 0) {
404 // If this is a terminal, don't use buffering. Line buffering
405 // would be a more traditional thing to do, but it's not worth
407 if (S_ISCHR(statbuf.st_mode) && isatty(FD))
409 // Return the preferred block size.
410 return statbuf.st_blksize;
414 return raw_ostream::preferred_buffer_size();
417 raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
419 if (sys::Process::ColorNeedsFlush())
421 const char *colorcode =
422 (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
423 : sys::Process::OutputColor(colors, bold, bg);
425 size_t len = strlen(colorcode);
426 write(colorcode, len);
427 // don't account colors towards output characters
433 raw_ostream &raw_fd_ostream::resetColor() {
434 if (sys::Process::ColorNeedsFlush())
436 const char *colorcode = sys::Process::ResetColor();
438 size_t len = strlen(colorcode);
439 write(colorcode, len);
440 // don't account colors towards output characters
446 //===----------------------------------------------------------------------===//
447 // raw_stdout/err_ostream
448 //===----------------------------------------------------------------------===//
450 // Set buffer settings to model stdout and stderr behavior.
451 // Set standard error to be unbuffered by default.
452 raw_stdout_ostream::raw_stdout_ostream():raw_fd_ostream(STDOUT_FILENO, false) {}
453 raw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO, false,
456 // An out of line virtual method to provide a home for the class vtable.
457 void raw_stdout_ostream::handle() {}
458 void raw_stderr_ostream::handle() {}
460 /// outs() - This returns a reference to a raw_ostream for standard output.
461 /// Use it like: outs() << "foo" << "bar";
462 raw_ostream &llvm::outs() {
463 static raw_stdout_ostream S;
467 /// errs() - This returns a reference to a raw_ostream for standard error.
468 /// Use it like: errs() << "foo" << "bar";
469 raw_ostream &llvm::errs() {
470 static raw_stderr_ostream S;
474 /// nulls() - This returns a reference to a raw_ostream which discards output.
475 raw_ostream &llvm::nulls() {
476 static raw_null_ostream S;
480 //===----------------------------------------------------------------------===//
482 //===----------------------------------------------------------------------===//
484 raw_os_ostream::~raw_os_ostream() {
488 void raw_os_ostream::write_impl(const char *Ptr, size_t Size) {
492 uint64_t raw_os_ostream::current_pos() { return OS.tellp(); }
494 //===----------------------------------------------------------------------===//
495 // raw_string_ostream
496 //===----------------------------------------------------------------------===//
498 raw_string_ostream::~raw_string_ostream() {
502 void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
503 OS.append(Ptr, Size);
506 //===----------------------------------------------------------------------===//
507 // raw_svector_ostream
508 //===----------------------------------------------------------------------===//
510 // The raw_svector_ostream implementation uses the SmallVector itself as the
511 // buffer for the raw_ostream. We guarantee that the raw_ostream buffer is
512 // always pointing past the end of the vector, but within the vector
513 // capacity. This allows raw_ostream to write directly into the correct place,
514 // and we only need to set the vector size when the data is flushed.
516 raw_svector_ostream::raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {
517 // Set up the initial external buffer. We make sure that the buffer has at
518 // least 128 bytes free; raw_ostream itself only requires 64, but we want to
519 // make sure that we don't grow the buffer unnecessarily on destruction (when
520 // the data is flushed). See the FIXME below.
521 OS.reserve(OS.size() + 128);
522 SetBuffer(OS.end(), OS.capacity() - OS.size());
525 raw_svector_ostream::~raw_svector_ostream() {
526 // FIXME: Prevent resizing during this flush().
530 void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
531 assert(Ptr == OS.end() && OS.size() + Size <= OS.capacity() &&
532 "Invalid write_impl() call!");
534 // We don't need to copy the bytes, just commit the bytes to the
536 OS.set_size(OS.size() + Size);
538 // Grow the vector if necessary.
539 if (OS.capacity() - OS.size() < 64)
540 OS.reserve(OS.capacity() * 2);
542 // Update the buffer position.
543 SetBuffer(OS.end(), OS.capacity() - OS.size());
546 uint64_t raw_svector_ostream::current_pos() { return OS.size(); }
548 StringRef raw_svector_ostream::str() {
550 return StringRef(OS.begin(), OS.size());
553 //===----------------------------------------------------------------------===//
555 //===----------------------------------------------------------------------===//
557 raw_null_ostream::~raw_null_ostream() {
559 // ~raw_ostream asserts that the buffer is empty. This isn't necessary
560 // with raw_null_ostream, but it's better to have raw_null_ostream follow
561 // the rules than to change the rules just for raw_null_ostream.
566 void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
569 uint64_t raw_null_ostream::current_pos() {