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 // Handle short strings specially, memcpy isn't very good at very short
228 case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
229 case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
230 case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
231 case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
234 memcpy(OutBufCur, Ptr, Size);
242 raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
243 // If we have more than a few bytes left in our output buffer, try
244 // formatting directly onto its end.
246 // FIXME: This test is a bit silly, since if we don't have enough
247 // space in the buffer we will have to flush the formatted output
248 // anyway. We should just flush upfront in such cases, and use the
249 // whole buffer as our scratch pad. Note, however, that this case is
250 // also necessary for correctness on unbuffered streams.
251 size_t NextBufferSize = 127;
252 if (OutBufEnd-OutBufCur > 3) {
253 size_t BufferBytesLeft = OutBufEnd-OutBufCur;
254 size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
256 // Common case is that we have plenty of space.
257 if (BytesUsed < BufferBytesLeft) {
258 OutBufCur += BytesUsed;
262 // Otherwise, we overflowed and the return value tells us the size to try
264 NextBufferSize = BytesUsed;
267 // If we got here, we didn't have enough space in the output buffer for the
268 // string. Try printing into a SmallVector that is resized to have enough
269 // space. Iterate until we win.
270 SmallVector<char, 128> V;
273 V.resize(NextBufferSize);
275 // Try formatting into the SmallVector.
276 size_t BytesUsed = Fmt.print(&V[0], NextBufferSize);
278 // If BytesUsed fit into the vector, we win.
279 if (BytesUsed <= NextBufferSize)
280 return write(&V[0], BytesUsed);
282 // Otherwise, try again with a new size.
283 assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
284 NextBufferSize = BytesUsed;
288 //===----------------------------------------------------------------------===//
290 //===----------------------------------------------------------------------===//
292 // Out of line virtual method.
293 void format_object_base::home() {
296 //===----------------------------------------------------------------------===//
298 //===----------------------------------------------------------------------===//
300 /// raw_fd_ostream - Open the specified file for writing. If an error
301 /// occurs, information about the error is put into ErrorInfo, and the
302 /// stream should be immediately destroyed; the string will be empty
303 /// if no error occurred.
304 raw_fd_ostream::raw_fd_ostream(const char *Filename, bool Binary, bool Force,
305 std::string &ErrorInfo) : pos(0) {
308 // Handle "-" as stdout.
309 if (Filename[0] == '-' && Filename[1] == 0) {
311 // If user requested binary then put stdout into binary mode if
314 sys::Program::ChangeStdoutToBinary();
319 int Flags = O_WRONLY|O_CREAT|O_TRUNC;
326 FD = open(Filename, Flags, 0664);
328 ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
335 raw_fd_ostream::~raw_fd_ostream() {
339 if (::close(FD) != 0)
344 void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
345 assert (FD >= 0 && "File already closed.");
347 if (::write(FD, Ptr, Size) != (ssize_t) Size)
351 void raw_fd_ostream::close() {
352 assert (ShouldClose);
355 if (::close(FD) != 0)
360 uint64_t raw_fd_ostream::seek(uint64_t off) {
362 pos = ::lseek(FD, off, SEEK_SET);
368 size_t raw_fd_ostream::preferred_buffer_size() {
369 #if !defined(_MSC_VER) // Windows reportedly doesn't have st_blksize.
370 assert(FD >= 0 && "File not yet open!");
372 if (fstat(FD, &statbuf) == 0)
373 return statbuf.st_blksize;
376 return raw_ostream::preferred_buffer_size();
379 raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
381 if (sys::Process::ColorNeedsFlush())
383 const char *colorcode =
384 (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
385 : sys::Process::OutputColor(colors, bold, bg);
387 size_t len = strlen(colorcode);
388 write(colorcode, len);
389 // don't account colors towards output characters
395 raw_ostream &raw_fd_ostream::resetColor() {
396 if (sys::Process::ColorNeedsFlush())
398 const char *colorcode = sys::Process::ResetColor();
400 size_t len = strlen(colorcode);
401 write(colorcode, len);
402 // don't account colors towards output characters
408 //===----------------------------------------------------------------------===//
409 // raw_stdout/err_ostream
410 //===----------------------------------------------------------------------===//
412 raw_stdout_ostream::raw_stdout_ostream():raw_fd_ostream(STDOUT_FILENO, false) {}
413 raw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO, false,
416 // An out of line virtual method to provide a home for the class vtable.
417 void raw_stdout_ostream::handle() {}
418 void raw_stderr_ostream::handle() {}
420 /// outs() - This returns a reference to a raw_ostream for standard output.
421 /// Use it like: outs() << "foo" << "bar";
422 raw_ostream &llvm::outs() {
423 static raw_stdout_ostream S;
427 /// errs() - This returns a reference to a raw_ostream for standard error.
428 /// Use it like: errs() << "foo" << "bar";
429 raw_ostream &llvm::errs() {
430 static raw_stderr_ostream S;
434 /// nulls() - This returns a reference to a raw_ostream which discards output.
435 raw_ostream &llvm::nulls() {
436 static raw_null_ostream S;
440 //===----------------------------------------------------------------------===//
442 //===----------------------------------------------------------------------===//
444 void raw_os_ostream::write_impl(const char *Ptr, size_t Size) {
448 uint64_t raw_os_ostream::current_pos() { return OS.tellp(); }
450 uint64_t raw_os_ostream::tell() {
451 return (uint64_t)OS.tellp() + GetNumBytesInBuffer();
454 //===----------------------------------------------------------------------===//
455 // raw_string_ostream
456 //===----------------------------------------------------------------------===//
458 void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
459 OS.append(Ptr, Size);
462 //===----------------------------------------------------------------------===//
463 // raw_svector_ostream
464 //===----------------------------------------------------------------------===//
466 void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
467 OS.append(Ptr, Ptr + Size);
470 uint64_t raw_svector_ostream::current_pos() { return OS.size(); }
472 uint64_t raw_svector_ostream::tell() {
473 return OS.size() + GetNumBytesInBuffer();
476 //===----------------------------------------------------------------------===//
478 //===----------------------------------------------------------------------===//
480 raw_null_ostream::~raw_null_ostream() {
482 // ~raw_ostream asserts that the buffer is empty. This isn't necessary
483 // with raw_null_ostream, but it's better to have raw_null_ostream follow
484 // the rules than to change the rules just for raw_null_ostream.
489 void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
492 uint64_t raw_null_ostream::current_pos() {