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 delete [] OutBufStart;
57 // If there are any pending errors, report them now. Clients wishing
58 // to avoid llvm_report_error calls should check for errors with
59 // has_error() and clear the error flag with clear_error() before
60 // destructing raw_ostream objects which may have errors.
62 llvm_report_error("IO failure on output stream.");
65 // An out of line virtual method to provide a home for the class vtable.
66 void raw_ostream::handle() {}
68 size_t raw_ostream::preferred_buffer_size() {
69 // BUFSIZ is intended to be a reasonable default.
73 void raw_ostream::SetBuffered() {
74 // Ask the subclass to determine an appropriate buffer size.
75 SetBufferSize(preferred_buffer_size());
78 void raw_ostream::SetBufferSize(size_t Size) {
80 "Buffer size must be somewhat large for invariants to hold");
83 delete [] OutBufStart;
84 OutBufStart = new char[Size];
85 OutBufEnd = OutBufStart+Size;
86 OutBufCur = OutBufStart;
90 void raw_ostream::SetUnbuffered() {
93 delete [] OutBufStart;
94 OutBufStart = OutBufEnd = OutBufCur = 0;
98 raw_ostream &raw_ostream::operator<<(unsigned long N) {
99 // Zero is a special case.
103 char NumberBuffer[20];
104 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
105 char *CurPtr = EndPtr;
108 *--CurPtr = '0' + char(N % 10);
111 return write(CurPtr, EndPtr-CurPtr);
114 raw_ostream &raw_ostream::operator<<(long N) {
120 return this->operator<<(static_cast<unsigned long>(N));
123 raw_ostream &raw_ostream::operator<<(unsigned long long N) {
124 // Output using 32-bit div/mod when possible.
125 if (N == static_cast<unsigned long>(N))
126 return this->operator<<(static_cast<unsigned long>(N));
128 char NumberBuffer[20];
129 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
130 char *CurPtr = EndPtr;
133 *--CurPtr = '0' + char(N % 10);
136 return write(CurPtr, EndPtr-CurPtr);
139 raw_ostream &raw_ostream::operator<<(long long N) {
145 return this->operator<<(static_cast<unsigned long long>(N));
148 raw_ostream &raw_ostream::write_hex(unsigned long long N) {
149 // Zero is a special case.
153 char NumberBuffer[20];
154 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
155 char *CurPtr = EndPtr;
158 uintptr_t x = N % 16;
159 *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
163 return write(CurPtr, EndPtr-CurPtr);
166 raw_ostream &raw_ostream::operator<<(const void *P) {
169 return write_hex((uintptr_t) P);
172 void raw_ostream::flush_nonempty() {
173 assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
174 write_impl(OutBufStart, OutBufCur - OutBufStart);
175 OutBufCur = OutBufStart;
178 raw_ostream &raw_ostream::write(unsigned char C) {
179 // Group exceptional cases into a single branch.
180 if (OutBufCur >= OutBufEnd) {
182 write_impl(reinterpret_cast<char*>(&C), 1);
196 raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
197 // Group exceptional cases into a single branch.
198 if (BUILTIN_EXPECT(OutBufCur+Size > OutBufEnd, false)) {
199 if (BUILTIN_EXPECT(!OutBufStart, false)) {
201 write_impl(Ptr, Size);
204 // Set up a buffer and start over.
206 return write(Ptr, Size);
208 // Write out the data in buffer-sized blocks until the remainder
209 // fits within the buffer.
211 size_t NumBytes = OutBufEnd - OutBufCur;
212 copy_to_buffer(Ptr, NumBytes);
216 } while (OutBufCur+Size > OutBufEnd);
219 copy_to_buffer(Ptr, Size);
224 void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
225 assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
227 // Handle short strings specially, memcpy isn't very good at very short
230 case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
231 case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
232 case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
233 case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
236 memcpy(OutBufCur, Ptr, Size);
244 raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
245 // If we have more than a few bytes left in our output buffer, try
246 // formatting directly onto its end.
248 // FIXME: This test is a bit silly, since if we don't have enough
249 // space in the buffer we will have to flush the formatted output
250 // anyway. We should just flush upfront in such cases, and use the
251 // whole buffer as our scratch pad. Note, however, that this case is
252 // also necessary for correctness on unbuffered streams.
253 size_t NextBufferSize = 127;
254 if (OutBufEnd-OutBufCur > 3) {
255 size_t BufferBytesLeft = OutBufEnd-OutBufCur;
256 size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
258 // Common case is that we have plenty of space.
259 if (BytesUsed < BufferBytesLeft) {
260 OutBufCur += BytesUsed;
264 // Otherwise, we overflowed and the return value tells us the size to try
266 NextBufferSize = BytesUsed;
269 // If we got here, we didn't have enough space in the output buffer for the
270 // string. Try printing into a SmallVector that is resized to have enough
271 // space. Iterate until we win.
272 SmallVector<char, 128> V;
275 V.resize(NextBufferSize);
277 // Try formatting into the SmallVector.
278 size_t BytesUsed = Fmt.print(&V[0], NextBufferSize);
280 // If BytesUsed fit into the vector, we win.
281 if (BytesUsed <= NextBufferSize)
282 return write(&V[0], BytesUsed);
284 // Otherwise, try again with a new size.
285 assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
286 NextBufferSize = BytesUsed;
290 //===----------------------------------------------------------------------===//
292 //===----------------------------------------------------------------------===//
294 // Out of line virtual method.
295 void format_object_base::home() {
298 //===----------------------------------------------------------------------===//
300 //===----------------------------------------------------------------------===//
302 /// raw_fd_ostream - Open the specified file for writing. If an error
303 /// occurs, information about the error is put into ErrorInfo, and the
304 /// stream should be immediately destroyed; the string will be empty
305 /// if no error occurred.
306 raw_fd_ostream::raw_fd_ostream(const char *Filename, bool Binary, bool Force,
307 std::string &ErrorInfo) : pos(0) {
310 // Handle "-" as stdout.
311 if (Filename[0] == '-' && Filename[1] == 0) {
313 // If user requested binary then put stdout into binary mode if
316 sys::Program::ChangeStdoutToBinary();
321 int Flags = O_WRONLY|O_CREAT|O_TRUNC;
328 FD = open(Filename, Flags, 0664);
330 ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
337 raw_fd_ostream::~raw_fd_ostream() {
341 if (::close(FD) != 0)
346 void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
347 assert (FD >= 0 && "File already closed.");
349 if (::write(FD, Ptr, Size) != (ssize_t) Size)
353 void raw_fd_ostream::close() {
354 assert (ShouldClose);
357 if (::close(FD) != 0)
362 uint64_t raw_fd_ostream::seek(uint64_t off) {
364 pos = ::lseek(FD, off, SEEK_SET);
370 size_t raw_fd_ostream::preferred_buffer_size() {
371 #if !defined(_MSC_VER) // Windows reportedly doesn't have st_blksize.
372 assert(FD >= 0 && "File not yet open!");
374 if (fstat(FD, &statbuf) == 0)
375 return statbuf.st_blksize;
378 return raw_ostream::preferred_buffer_size();
381 raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
383 if (sys::Process::ColorNeedsFlush())
385 const char *colorcode =
386 (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
387 : sys::Process::OutputColor(colors, bold, bg);
389 size_t len = strlen(colorcode);
390 write(colorcode, len);
391 // don't account colors towards output characters
397 raw_ostream &raw_fd_ostream::resetColor() {
398 if (sys::Process::ColorNeedsFlush())
400 const char *colorcode = sys::Process::ResetColor();
402 size_t len = strlen(colorcode);
403 write(colorcode, len);
404 // don't account colors towards output characters
410 //===----------------------------------------------------------------------===//
411 // raw_stdout/err_ostream
412 //===----------------------------------------------------------------------===//
414 raw_stdout_ostream::raw_stdout_ostream():raw_fd_ostream(STDOUT_FILENO, false) {}
415 raw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO, false,
418 // An out of line virtual method to provide a home for the class vtable.
419 void raw_stdout_ostream::handle() {}
420 void raw_stderr_ostream::handle() {}
422 /// outs() - This returns a reference to a raw_ostream for standard output.
423 /// Use it like: outs() << "foo" << "bar";
424 raw_ostream &llvm::outs() {
425 static raw_stdout_ostream S;
429 /// errs() - This returns a reference to a raw_ostream for standard error.
430 /// Use it like: errs() << "foo" << "bar";
431 raw_ostream &llvm::errs() {
432 static raw_stderr_ostream S;
436 /// nulls() - This returns a reference to a raw_ostream which discards output.
437 raw_ostream &llvm::nulls() {
438 static raw_null_ostream S;
442 //===----------------------------------------------------------------------===//
444 //===----------------------------------------------------------------------===//
446 void raw_os_ostream::write_impl(const char *Ptr, size_t Size) {
450 uint64_t raw_os_ostream::current_pos() { return OS.tellp(); }
452 uint64_t raw_os_ostream::tell() {
453 return (uint64_t)OS.tellp() + GetNumBytesInBuffer();
456 //===----------------------------------------------------------------------===//
457 // raw_string_ostream
458 //===----------------------------------------------------------------------===//
460 void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
461 OS.append(Ptr, Size);
464 //===----------------------------------------------------------------------===//
465 // raw_svector_ostream
466 //===----------------------------------------------------------------------===//
468 void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
469 OS.append(Ptr, Ptr + Size);
472 uint64_t raw_svector_ostream::current_pos() { return OS.size(); }
474 uint64_t raw_svector_ostream::tell() {
475 return OS.size() + GetNumBytesInBuffer();
478 //===----------------------------------------------------------------------===//
480 //===----------------------------------------------------------------------===//
482 raw_null_ostream::~raw_null_ostream() {
484 // ~raw_ostream asserts that the buffer is empty. This isn't necessary
485 // with raw_null_ostream, but it's better to have raw_null_ostream follow
486 // the rules than to change the rules just for raw_null_ostream.
491 void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
494 uint64_t raw_null_ostream::current_pos() {