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 #if defined(HAVE_UNISTD_H)
27 #if defined(HAVE_FCNTL_H)
35 # define STDIN_FILENO 0
38 # define STDOUT_FILENO 1
41 # define STDERR_FILENO 2
47 raw_ostream::~raw_ostream() {
48 // raw_ostream's subclasses should take care to flush the buffer
49 // in their destructors.
50 assert(OutBufCur == OutBufStart &&
51 "raw_ostream destructor called with non-empty buffer!");
53 delete [] OutBufStart;
55 // If there are any pending errors, report them now. Clients wishing
56 // to avoid llvm_report_error calls should check for errors with
57 // has_error() and clear the error flag with clear_error() before
58 // destructing raw_ostream objects which may have errors.
60 llvm_report_error("IO failure on output stream.");
63 // An out of line virtual method to provide a home for the class vtable.
64 void raw_ostream::handle() {}
66 raw_ostream &raw_ostream::operator<<(unsigned long N) {
67 // Zero is a special case.
71 char NumberBuffer[20];
72 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
73 char *CurPtr = EndPtr;
76 *--CurPtr = '0' + char(N % 10);
79 return write(CurPtr, EndPtr-CurPtr);
82 raw_ostream &raw_ostream::operator<<(long N) {
88 return this->operator<<(static_cast<unsigned long>(N));
91 raw_ostream &raw_ostream::operator<<(unsigned long long N) {
92 // Zero is a special case.
96 char NumberBuffer[20];
97 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
98 char *CurPtr = EndPtr;
101 *--CurPtr = '0' + char(N % 10);
104 return write(CurPtr, EndPtr-CurPtr);
107 raw_ostream &raw_ostream::operator<<(long long N) {
113 return this->operator<<(static_cast<unsigned long long>(N));
116 raw_ostream &raw_ostream::operator<<(const void *P) {
117 uintptr_t N = (uintptr_t) P;
120 // Zero is a special case.
124 char NumberBuffer[20];
125 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
126 char *CurPtr = EndPtr;
129 uintptr_t x = N % 16;
130 *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
134 return write(CurPtr, EndPtr-CurPtr);
137 void raw_ostream::flush_nonempty() {
138 assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
139 write_impl(OutBufStart, OutBufCur - OutBufStart);
140 OutBufCur = OutBufStart;
143 raw_ostream &raw_ostream::write(unsigned char C) {
144 // Group exceptional cases into a single branch.
145 if (OutBufCur >= OutBufEnd) {
147 write_impl(reinterpret_cast<char*>(&C), 1);
161 raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
162 // Group exceptional cases into a single branch.
163 if (BUILTIN_EXPECT(OutBufCur+Size > OutBufEnd, false)) {
165 write_impl(Ptr, Size);
175 // Handle short strings specially, memcpy isn't very good at very short
178 case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
179 case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
180 case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
181 case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
184 // Normally the string to emit is shorter than the buffer.
185 if (Size <= unsigned(OutBufEnd-OutBufCur)) {
186 memcpy(OutBufCur, Ptr, Size);
190 // Otherwise we are emitting a string larger than our buffer. We
191 // know we already flushed, so just write it out directly.
192 write_impl(Ptr, Size);
202 raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
203 // If we have more than a few bytes left in our output buffer, try
204 // formatting directly onto its end.
206 // FIXME: This test is a bit silly, since if we don't have enough
207 // space in the buffer we will have to flush the formatted output
208 // anyway. We should just flush upfront in such cases, and use the
209 // whole buffer as our scratch pad. Note, however, that this case is
210 // also necessary for correctness on unbuffered streams.
211 size_t NextBufferSize = 127;
212 if (OutBufEnd-OutBufCur > 3) {
213 size_t BufferBytesLeft = OutBufEnd-OutBufCur;
214 size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
216 // Common case is that we have plenty of space.
217 if (BytesUsed < BufferBytesLeft) {
218 OutBufCur += BytesUsed;
222 // Otherwise, we overflowed and the return value tells us the size to try
224 NextBufferSize = BytesUsed;
227 // If we got here, we didn't have enough space in the output buffer for the
228 // string. Try printing into a SmallVector that is resized to have enough
229 // space. Iterate until we win.
230 SmallVector<char, 128> V;
233 V.resize(NextBufferSize);
235 // Try formatting into the SmallVector.
236 size_t BytesUsed = Fmt.print(&V[0], NextBufferSize);
238 // If BytesUsed fit into the vector, we win.
239 if (BytesUsed <= NextBufferSize)
240 return write(&V[0], BytesUsed);
242 // Otherwise, try again with a new size.
243 assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
244 NextBufferSize = BytesUsed;
248 //===----------------------------------------------------------------------===//
250 //===----------------------------------------------------------------------===//
252 // Out of line virtual method.
253 void format_object_base::home() {
256 //===----------------------------------------------------------------------===//
258 //===----------------------------------------------------------------------===//
260 /// raw_fd_ostream - Open the specified file for writing. If an error
261 /// occurs, information about the error is put into ErrorInfo, and the
262 /// stream should be immediately destroyed; the string will be empty
263 /// if no error occurred.
264 raw_fd_ostream::raw_fd_ostream(const char *Filename, bool Binary, bool Force,
265 std::string &ErrorInfo) : pos(0) {
268 // Handle "-" as stdout.
269 if (Filename[0] == '-' && Filename[1] == 0) {
271 // If user requested binary then put stdout into binary mode if
274 sys::Program::ChangeStdoutToBinary();
279 int Flags = O_WRONLY|O_CREAT|O_TRUNC;
286 FD = open(Filename, Flags, 0664);
288 ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
295 raw_fd_ostream::~raw_fd_ostream() {
299 if (::close(FD) != 0)
304 void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
305 assert (FD >= 0 && "File already closed.");
307 if (::write(FD, Ptr, Size) != (ssize_t) Size)
311 void raw_fd_ostream::close() {
312 assert (ShouldClose);
315 if (::close(FD) != 0)
320 uint64_t raw_fd_ostream::seek(uint64_t off) {
322 pos = ::lseek(FD, off, SEEK_SET);
328 raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
330 if (sys::Process::ColorNeedsFlush())
332 const char *colorcode =
333 (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
334 : sys::Process::OutputColor(colors, bold, bg);
336 size_t len = strlen(colorcode);
337 write(colorcode, len);
338 // don't account colors towards output characters
344 raw_ostream &raw_fd_ostream::resetColor() {
345 if (sys::Process::ColorNeedsFlush())
347 const char *colorcode = sys::Process::ResetColor();
349 size_t len = strlen(colorcode);
350 write(colorcode, len);
351 // don't account colors towards output characters
357 //===----------------------------------------------------------------------===//
358 // raw_stdout/err_ostream
359 //===----------------------------------------------------------------------===//
361 raw_stdout_ostream::raw_stdout_ostream():raw_fd_ostream(STDOUT_FILENO, false) {}
362 raw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO, false,
365 // An out of line virtual method to provide a home for the class vtable.
366 void raw_stdout_ostream::handle() {}
367 void raw_stderr_ostream::handle() {}
369 /// outs() - This returns a reference to a raw_ostream for standard output.
370 /// Use it like: outs() << "foo" << "bar";
371 raw_ostream &llvm::outs() {
372 static raw_stdout_ostream S;
376 /// errs() - This returns a reference to a raw_ostream for standard error.
377 /// Use it like: errs() << "foo" << "bar";
378 raw_ostream &llvm::errs() {
379 static raw_stderr_ostream S;
383 /// nulls() - This returns a reference to a raw_ostream which discards output.
384 raw_ostream &llvm::nulls() {
385 static raw_null_ostream S;
389 //===----------------------------------------------------------------------===//
391 //===----------------------------------------------------------------------===//
393 raw_os_ostream::~raw_os_ostream() {
397 void raw_os_ostream::write_impl(const char *Ptr, size_t Size) {
401 uint64_t raw_os_ostream::current_pos() { return OS.tellp(); }
403 uint64_t raw_os_ostream::tell() {
404 return (uint64_t)OS.tellp() + GetNumBytesInBuffer();
407 //===----------------------------------------------------------------------===//
408 // raw_string_ostream
409 //===----------------------------------------------------------------------===//
411 raw_string_ostream::~raw_string_ostream() {
415 void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
416 OS.append(Ptr, Size);
419 //===----------------------------------------------------------------------===//
420 // raw_svector_ostream
421 //===----------------------------------------------------------------------===//
423 raw_svector_ostream::~raw_svector_ostream() {
427 void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
428 OS.append(Ptr, Ptr + Size);
431 uint64_t raw_svector_ostream::current_pos() { return OS.size(); }
433 uint64_t raw_svector_ostream::tell() {
434 return OS.size() + GetNumBytesInBuffer();
437 //===----------------------------------------------------------------------===//
439 //===----------------------------------------------------------------------===//
441 raw_null_ostream::~raw_null_ostream() {
443 // ~raw_ostream asserts that the buffer is empty. This isn't necessary
444 // with raw_null_ostream, but it's better to have raw_null_ostream follow
445 // the rules than to change the rules just for raw_null_ostream.
450 void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
453 uint64_t raw_null_ostream::current_pos() {