LLVM  mainline
raw_ostream.cpp
Go to the documentation of this file.
00001 //===--- raw_ostream.cpp - Implement the raw_ostream classes --------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This implements support for bulk buffered stream output.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/Support/raw_ostream.h"
00015 #include "llvm/ADT/STLExtras.h"
00016 #include "llvm/ADT/SmallVector.h"
00017 #include "llvm/ADT/StringExtras.h"
00018 #include "llvm/Config/config.h"
00019 #include "llvm/Support/Compiler.h"
00020 #include "llvm/Support/ErrorHandling.h"
00021 #include "llvm/Support/FileSystem.h"
00022 #include "llvm/Support/Format.h"
00023 #include "llvm/Support/MathExtras.h"
00024 #include "llvm/Support/Process.h"
00025 #include "llvm/Support/Program.h"
00026 #include <cctype>
00027 #include <cerrno>
00028 #include <sys/stat.h>
00029 #include <system_error>
00030 
00031 // <fcntl.h> may provide O_BINARY.
00032 #if defined(HAVE_FCNTL_H)
00033 # include <fcntl.h>
00034 #endif
00035 
00036 #if defined(HAVE_UNISTD_H)
00037 # include <unistd.h>
00038 #endif
00039 #if defined(HAVE_SYS_UIO_H) && defined(HAVE_WRITEV)
00040 #  include <sys/uio.h>
00041 #endif
00042 
00043 #if defined(__CYGWIN__)
00044 #include <io.h>
00045 #endif
00046 
00047 #if defined(_MSC_VER)
00048 #include <io.h>
00049 #ifndef STDIN_FILENO
00050 # define STDIN_FILENO 0
00051 #endif
00052 #ifndef STDOUT_FILENO
00053 # define STDOUT_FILENO 1
00054 #endif
00055 #ifndef STDERR_FILENO
00056 # define STDERR_FILENO 2
00057 #endif
00058 #endif
00059 
00060 #ifdef LLVM_ON_WIN32
00061 #include "Windows/WindowsSupport.h"
00062 #endif
00063 
00064 using namespace llvm;
00065 
00066 raw_ostream::~raw_ostream() {
00067   // raw_ostream's subclasses should take care to flush the buffer
00068   // in their destructors.
00069   assert(OutBufCur == OutBufStart &&
00070          "raw_ostream destructor called with non-empty buffer!");
00071 
00072   if (BufferMode == InternalBuffer)
00073     delete [] OutBufStart;
00074 }
00075 
00076 // An out of line virtual method to provide a home for the class vtable.
00077 void raw_ostream::handle() {}
00078 
00079 size_t raw_ostream::preferred_buffer_size() const {
00080   // BUFSIZ is intended to be a reasonable default.
00081   return BUFSIZ;
00082 }
00083 
00084 void raw_ostream::SetBuffered() {
00085   // Ask the subclass to determine an appropriate buffer size.
00086   if (size_t Size = preferred_buffer_size())
00087     SetBufferSize(Size);
00088   else
00089     // It may return 0, meaning this stream should be unbuffered.
00090     SetUnbuffered();
00091 }
00092 
00093 void raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size,
00094                                    BufferKind Mode) {
00095   assert(((Mode == Unbuffered && !BufferStart && Size == 0) ||
00096           (Mode != Unbuffered && BufferStart && Size != 0)) &&
00097          "stream must be unbuffered or have at least one byte");
00098   // Make sure the current buffer is free of content (we can't flush here; the
00099   // child buffer management logic will be in write_impl).
00100   assert(GetNumBytesInBuffer() == 0 && "Current buffer is non-empty!");
00101 
00102   if (BufferMode == InternalBuffer)
00103     delete [] OutBufStart;
00104   OutBufStart = BufferStart;
00105   OutBufEnd = OutBufStart+Size;
00106   OutBufCur = OutBufStart;
00107   BufferMode = Mode;
00108 
00109   assert(OutBufStart <= OutBufEnd && "Invalid size!");
00110 }
00111 
00112 raw_ostream &raw_ostream::operator<<(unsigned long N) {
00113   // Zero is a special case.
00114   if (N == 0)
00115     return *this << '0';
00116 
00117   char NumberBuffer[20];
00118   char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
00119   char *CurPtr = EndPtr;
00120 
00121   while (N) {
00122     *--CurPtr = '0' + char(N % 10);
00123     N /= 10;
00124   }
00125   return write(CurPtr, EndPtr-CurPtr);
00126 }
00127 
00128 raw_ostream &raw_ostream::operator<<(long N) {
00129   if (N <  0) {
00130     *this << '-';
00131     // Avoid undefined behavior on LONG_MIN with a cast.
00132     N = -(unsigned long)N;
00133   }
00134 
00135   return this->operator<<(static_cast<unsigned long>(N));
00136 }
00137 
00138 raw_ostream &raw_ostream::operator<<(unsigned long long N) {
00139   // Output using 32-bit div/mod when possible.
00140   if (N == static_cast<unsigned long>(N))
00141     return this->operator<<(static_cast<unsigned long>(N));
00142 
00143   char NumberBuffer[20];
00144   char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
00145   char *CurPtr = EndPtr;
00146 
00147   while (N) {
00148     *--CurPtr = '0' + char(N % 10);
00149     N /= 10;
00150   }
00151   return write(CurPtr, EndPtr-CurPtr);
00152 }
00153 
00154 raw_ostream &raw_ostream::operator<<(long long N) {
00155   if (N < 0) {
00156     *this << '-';
00157     // Avoid undefined behavior on INT64_MIN with a cast.
00158     N = -(unsigned long long)N;
00159   }
00160 
00161   return this->operator<<(static_cast<unsigned long long>(N));
00162 }
00163 
00164 raw_ostream &raw_ostream::write_hex(unsigned long long N) {
00165   // Zero is a special case.
00166   if (N == 0)
00167     return *this << '0';
00168 
00169   char NumberBuffer[20];
00170   char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
00171   char *CurPtr = EndPtr;
00172 
00173   while (N) {
00174     uintptr_t x = N % 16;
00175     *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
00176     N /= 16;
00177   }
00178 
00179   return write(CurPtr, EndPtr-CurPtr);
00180 }
00181 
00182 raw_ostream &raw_ostream::write_escaped(StringRef Str,
00183                                         bool UseHexEscapes) {
00184   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
00185     unsigned char c = Str[i];
00186 
00187     switch (c) {
00188     case '\\':
00189       *this << '\\' << '\\';
00190       break;
00191     case '\t':
00192       *this << '\\' << 't';
00193       break;
00194     case '\n':
00195       *this << '\\' << 'n';
00196       break;
00197     case '"':
00198       *this << '\\' << '"';
00199       break;
00200     default:
00201       if (std::isprint(c)) {
00202         *this << c;
00203         break;
00204       }
00205 
00206       // Write out the escaped representation.
00207       if (UseHexEscapes) {
00208         *this << '\\' << 'x';
00209         *this << hexdigit((c >> 4 & 0xF));
00210         *this << hexdigit((c >> 0) & 0xF);
00211       } else {
00212         // Always use a full 3-character octal escape.
00213         *this << '\\';
00214         *this << char('0' + ((c >> 6) & 7));
00215         *this << char('0' + ((c >> 3) & 7));
00216         *this << char('0' + ((c >> 0) & 7));
00217       }
00218     }
00219   }
00220 
00221   return *this;
00222 }
00223 
00224 raw_ostream &raw_ostream::operator<<(const void *P) {
00225   *this << '0' << 'x';
00226 
00227   return write_hex((uintptr_t) P);
00228 }
00229 
00230 raw_ostream &raw_ostream::operator<<(double N) {
00231 #ifdef _WIN32
00232   // On MSVCRT and compatible, output of %e is incompatible to Posix
00233   // by default. Number of exponent digits should be at least 2. "%+03d"
00234   // FIXME: Implement our formatter to here or Support/Format.h!
00235 #if __cplusplus >= 201103L && defined(__MINGW32__)
00236   // FIXME: It should be generic to C++11.
00237   if (N == 0.0 && std::signbit(N))
00238     return *this << "-0.000000e+00";
00239 #else
00240   int fpcl = _fpclass(N);
00241 
00242   // negative zero
00243   if (fpcl == _FPCLASS_NZ)
00244     return *this << "-0.000000e+00";
00245 #endif
00246 
00247   char buf[16];
00248   unsigned len;
00249   len = format("%e", N).snprint(buf, sizeof(buf));
00250   if (len <= sizeof(buf) - 2) {
00251     if (len >= 5 && buf[len - 5] == 'e' && buf[len - 3] == '0') {
00252       int cs = buf[len - 4];
00253       if (cs == '+' || cs == '-') {
00254         int c1 = buf[len - 2];
00255         int c0 = buf[len - 1];
00256         if (isdigit(static_cast<unsigned char>(c1)) &&
00257             isdigit(static_cast<unsigned char>(c0))) {
00258           // Trim leading '0': "...e+012" -> "...e+12\0"
00259           buf[len - 3] = c1;
00260           buf[len - 2] = c0;
00261           buf[--len] = 0;
00262         }
00263       }
00264     }
00265     return this->operator<<(buf);
00266   }
00267 #endif
00268   return this->operator<<(format("%e", N));
00269 }
00270 
00271 
00272 
00273 void raw_ostream::flush_nonempty() {
00274   assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
00275   size_t Length = OutBufCur - OutBufStart;
00276   OutBufCur = OutBufStart;
00277   write_impl(OutBufStart, Length);
00278 }
00279 
00280 raw_ostream &raw_ostream::write(unsigned char C) {
00281   // Group exceptional cases into a single branch.
00282   if (LLVM_UNLIKELY(OutBufCur >= OutBufEnd)) {
00283     if (LLVM_UNLIKELY(!OutBufStart)) {
00284       if (BufferMode == Unbuffered) {
00285         write_impl(reinterpret_cast<char*>(&C), 1);
00286         return *this;
00287       }
00288       // Set up a buffer and start over.
00289       SetBuffered();
00290       return write(C);
00291     }
00292 
00293     flush_nonempty();
00294   }
00295 
00296   *OutBufCur++ = C;
00297   return *this;
00298 }
00299 
00300 raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
00301   // Group exceptional cases into a single branch.
00302   if (LLVM_UNLIKELY(size_t(OutBufEnd - OutBufCur) < Size)) {
00303     if (LLVM_UNLIKELY(!OutBufStart)) {
00304       if (BufferMode == Unbuffered) {
00305         write_impl(Ptr, Size);
00306         return *this;
00307       }
00308       // Set up a buffer and start over.
00309       SetBuffered();
00310       return write(Ptr, Size);
00311     }
00312 
00313     size_t NumBytes = OutBufEnd - OutBufCur;
00314 
00315     // If the buffer is empty at this point we have a string that is larger
00316     // than the buffer. Directly write the chunk that is a multiple of the
00317     // preferred buffer size and put the remainder in the buffer.
00318     if (LLVM_UNLIKELY(OutBufCur == OutBufStart)) {
00319       assert(NumBytes != 0 && "undefined behavior");
00320       size_t BytesToWrite = Size - (Size % NumBytes);
00321       write_impl(Ptr, BytesToWrite);
00322       size_t BytesRemaining = Size - BytesToWrite;
00323       if (BytesRemaining > size_t(OutBufEnd - OutBufCur)) {
00324         // Too much left over to copy into our buffer.
00325         return write(Ptr + BytesToWrite, BytesRemaining);
00326       }
00327       copy_to_buffer(Ptr + BytesToWrite, BytesRemaining);
00328       return *this;
00329     }
00330 
00331     // We don't have enough space in the buffer to fit the string in. Insert as
00332     // much as possible, flush and start over with the remainder.
00333     copy_to_buffer(Ptr, NumBytes);
00334     flush_nonempty();
00335     return write(Ptr + NumBytes, Size - NumBytes);
00336   }
00337 
00338   copy_to_buffer(Ptr, Size);
00339 
00340   return *this;
00341 }
00342 
00343 void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
00344   assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
00345 
00346   // Handle short strings specially, memcpy isn't very good at very short
00347   // strings.
00348   switch (Size) {
00349   case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
00350   case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
00351   case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
00352   case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
00353   case 0: break;
00354   default:
00355     memcpy(OutBufCur, Ptr, Size);
00356     break;
00357   }
00358 
00359   OutBufCur += Size;
00360 }
00361 
00362 // Formatted output.
00363 raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
00364   // If we have more than a few bytes left in our output buffer, try
00365   // formatting directly onto its end.
00366   size_t NextBufferSize = 127;
00367   size_t BufferBytesLeft = OutBufEnd - OutBufCur;
00368   if (BufferBytesLeft > 3) {
00369     size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
00370 
00371     // Common case is that we have plenty of space.
00372     if (BytesUsed <= BufferBytesLeft) {
00373       OutBufCur += BytesUsed;
00374       return *this;
00375     }
00376 
00377     // Otherwise, we overflowed and the return value tells us the size to try
00378     // again with.
00379     NextBufferSize = BytesUsed;
00380   }
00381 
00382   // If we got here, we didn't have enough space in the output buffer for the
00383   // string.  Try printing into a SmallVector that is resized to have enough
00384   // space.  Iterate until we win.
00385   SmallVector<char, 128> V;
00386 
00387   while (1) {
00388     V.resize(NextBufferSize);
00389 
00390     // Try formatting into the SmallVector.
00391     size_t BytesUsed = Fmt.print(V.data(), NextBufferSize);
00392 
00393     // If BytesUsed fit into the vector, we win.
00394     if (BytesUsed <= NextBufferSize)
00395       return write(V.data(), BytesUsed);
00396 
00397     // Otherwise, try again with a new size.
00398     assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
00399     NextBufferSize = BytesUsed;
00400   }
00401 }
00402 
00403 raw_ostream &raw_ostream::operator<<(const FormattedString &FS) {
00404   unsigned Len = FS.Str.size(); 
00405   int PadAmount = FS.Width - Len;
00406   if (FS.RightJustify && (PadAmount > 0))
00407     this->indent(PadAmount);
00408   this->operator<<(FS.Str);
00409   if (!FS.RightJustify && (PadAmount > 0))
00410     this->indent(PadAmount);
00411   return *this;
00412 }
00413 
00414 raw_ostream &raw_ostream::operator<<(const FormattedNumber &FN) {
00415   if (FN.Hex) {
00416     unsigned Nibbles = (64 - countLeadingZeros(FN.HexValue)+3)/4;
00417     unsigned PrefixChars = FN.HexPrefix ? 2 : 0;
00418     unsigned Width = std::max(FN.Width, Nibbles + PrefixChars);
00419 
00420     char NumberBuffer[20] = "0x0000000000000000";
00421     if (!FN.HexPrefix)
00422       NumberBuffer[1] = '0';
00423     char *EndPtr = NumberBuffer+Width;
00424     char *CurPtr = EndPtr;
00425     const char A = FN.Upper ? 'A' : 'a';
00426     unsigned long long N = FN.HexValue;
00427     while (N) {
00428       uintptr_t x = N % 16;
00429       *--CurPtr = (x < 10 ? '0' + x : A + x - 10);
00430       N /= 16;
00431     }
00432 
00433     return write(NumberBuffer, Width);
00434   } else {
00435     // Zero is a special case.
00436     if (FN.DecValue == 0) {
00437       this->indent(FN.Width-1);
00438       return *this << '0';
00439     }
00440     char NumberBuffer[32];
00441     char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
00442     char *CurPtr = EndPtr;
00443     bool Neg = (FN.DecValue < 0);
00444     uint64_t N = Neg ? -static_cast<uint64_t>(FN.DecValue) : FN.DecValue;
00445     while (N) {
00446       *--CurPtr = '0' + char(N % 10);
00447       N /= 10;
00448     }
00449     int Len = EndPtr - CurPtr;
00450     int Pad = FN.Width - Len;
00451     if (Neg) 
00452       --Pad;
00453     if (Pad > 0)
00454       this->indent(Pad);
00455     if (Neg)
00456       *this << '-';
00457     return write(CurPtr, Len);
00458   }
00459 }
00460 
00461 
00462 /// indent - Insert 'NumSpaces' spaces.
00463 raw_ostream &raw_ostream::indent(unsigned NumSpaces) {
00464   static const char Spaces[] = "                                "
00465                                "                                "
00466                                "                ";
00467 
00468   // Usually the indentation is small, handle it with a fastpath.
00469   if (NumSpaces < array_lengthof(Spaces))
00470     return write(Spaces, NumSpaces);
00471 
00472   while (NumSpaces) {
00473     unsigned NumToWrite = std::min(NumSpaces,
00474                                    (unsigned)array_lengthof(Spaces)-1);
00475     write(Spaces, NumToWrite);
00476     NumSpaces -= NumToWrite;
00477   }
00478   return *this;
00479 }
00480 
00481 
00482 //===----------------------------------------------------------------------===//
00483 //  Formatted Output
00484 //===----------------------------------------------------------------------===//
00485 
00486 // Out of line virtual method.
00487 void format_object_base::home() {
00488 }
00489 
00490 //===----------------------------------------------------------------------===//
00491 //  raw_fd_ostream
00492 //===----------------------------------------------------------------------===//
00493 
00494 static int getFD(StringRef Filename, std::error_code &EC,
00495                  sys::fs::OpenFlags Flags) {
00496   // Handle "-" as stdout. Note that when we do this, we consider ourself
00497   // the owner of stdout. This means that we can do things like close the
00498   // file descriptor when we're done and set the "binary" flag globally.
00499   if (Filename == "-") {
00500     EC = std::error_code();
00501     // If user requested binary then put stdout into binary mode if
00502     // possible.
00503     if (!(Flags & sys::fs::F_Text))
00504       sys::ChangeStdoutToBinary();
00505     return STDOUT_FILENO;
00506   }
00507 
00508   int FD;
00509   EC = sys::fs::openFileForWrite(Filename, FD, Flags);
00510   if (EC)
00511     return -1;
00512 
00513   return FD;
00514 }
00515 
00516 raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC,
00517                                sys::fs::OpenFlags Flags)
00518     : raw_fd_ostream(getFD(Filename, EC, Flags), true) {}
00519 
00520 /// FD is the file descriptor that this writes to.  If ShouldClose is true, this
00521 /// closes the file when the stream is destroyed.
00522 raw_fd_ostream::raw_fd_ostream(int fd, bool shouldClose, bool unbuffered)
00523     : raw_pwrite_stream(unbuffered), FD(fd), ShouldClose(shouldClose),
00524       Error(false) {
00525   if (FD < 0 ) {
00526     ShouldClose = false;
00527     return;
00528   }
00529 
00530   // Get the starting position.
00531   off_t loc = ::lseek(FD, 0, SEEK_CUR);
00532 #ifdef LLVM_ON_WIN32
00533   // MSVCRT's _lseek(SEEK_CUR) doesn't return -1 for pipes.
00534   sys::fs::file_status Status;
00535   std::error_code EC = status(FD, Status);
00536   SupportsSeeking = !EC && Status.type() == sys::fs::file_type::regular_file;
00537 #else
00538   SupportsSeeking = loc != (off_t)-1;
00539 #endif
00540   if (!SupportsSeeking)
00541     pos = 0;
00542   else
00543     pos = static_cast<uint64_t>(loc);
00544 }
00545 
00546 raw_fd_ostream::~raw_fd_ostream() {
00547   if (FD >= 0) {
00548     flush();
00549     if (ShouldClose && sys::Process::SafelyCloseFileDescriptor(FD))
00550       error_detected();
00551   }
00552 
00553 #ifdef __MINGW32__
00554   // On mingw, global dtors should not call exit().
00555   // report_fatal_error() invokes exit(). We know report_fatal_error()
00556   // might not write messages to stderr when any errors were detected
00557   // on FD == 2.
00558   if (FD == 2) return;
00559 #endif
00560 
00561   // If there are any pending errors, report them now. Clients wishing
00562   // to avoid report_fatal_error calls should check for errors with
00563   // has_error() and clear the error flag with clear_error() before
00564   // destructing raw_ostream objects which may have errors.
00565   if (has_error())
00566     report_fatal_error("IO failure on output stream.", /*GenCrashDiag=*/false);
00567 }
00568 
00569 
00570 void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
00571   assert(FD >= 0 && "File already closed.");
00572   pos += Size;
00573 
00574 #ifndef LLVM_ON_WIN32
00575   bool ShouldWriteInChunks = false;
00576 #else
00577   // Writing a large size of output to Windows console returns ENOMEM. It seems
00578   // that, prior to Windows 8, WriteFile() is redirecting to WriteConsole(), and
00579   // the latter has a size limit (66000 bytes or less, depending on heap usage).
00580   bool ShouldWriteInChunks = !!::_isatty(FD) && !RunningWindows8OrGreater();
00581 #endif
00582 
00583   do {
00584     size_t ChunkSize = Size;
00585     if (ChunkSize > 32767 && ShouldWriteInChunks)
00586         ChunkSize = 32767;
00587 
00588     ssize_t ret = ::write(FD, Ptr, ChunkSize);
00589 
00590     if (ret < 0) {
00591       // If it's a recoverable error, swallow it and retry the write.
00592       //
00593       // Ideally we wouldn't ever see EAGAIN or EWOULDBLOCK here, since
00594       // raw_ostream isn't designed to do non-blocking I/O. However, some
00595       // programs, such as old versions of bjam, have mistakenly used
00596       // O_NONBLOCK. For compatibility, emulate blocking semantics by
00597       // spinning until the write succeeds. If you don't want spinning,
00598       // don't use O_NONBLOCK file descriptors with raw_ostream.
00599       if (errno == EINTR || errno == EAGAIN
00600 #ifdef EWOULDBLOCK
00601           || errno == EWOULDBLOCK
00602 #endif
00603           )
00604         continue;
00605 
00606       // Otherwise it's a non-recoverable error. Note it and quit.
00607       error_detected();
00608       break;
00609     }
00610 
00611     // The write may have written some or all of the data. Update the
00612     // size and buffer pointer to reflect the remainder that needs
00613     // to be written. If there are no bytes left, we're done.
00614     Ptr += ret;
00615     Size -= ret;
00616   } while (Size > 0);
00617 }
00618 
00619 void raw_fd_ostream::close() {
00620   assert(ShouldClose);
00621   ShouldClose = false;
00622   flush();
00623   if (sys::Process::SafelyCloseFileDescriptor(FD))
00624     error_detected();
00625   FD = -1;
00626 }
00627 
00628 uint64_t raw_fd_ostream::seek(uint64_t off) {
00629   flush();
00630   pos = ::lseek(FD, off, SEEK_SET);
00631   if (pos == (uint64_t)-1)
00632     error_detected();
00633   return pos;
00634 }
00635 
00636 void raw_fd_ostream::pwrite_impl(const char *Ptr, size_t Size,
00637                                  uint64_t Offset) {
00638   uint64_t Pos = tell();
00639   seek(Offset);
00640   write(Ptr, Size);
00641   seek(Pos);
00642 }
00643 
00644 size_t raw_fd_ostream::preferred_buffer_size() const {
00645 #if !defined(_MSC_VER) && !defined(__MINGW32__) && !defined(__minix)
00646   // Windows and Minix have no st_blksize.
00647   assert(FD >= 0 && "File not yet open!");
00648   struct stat statbuf;
00649   if (fstat(FD, &statbuf) != 0)
00650     return 0;
00651 
00652   // If this is a terminal, don't use buffering. Line buffering
00653   // would be a more traditional thing to do, but it's not worth
00654   // the complexity.
00655   if (S_ISCHR(statbuf.st_mode) && isatty(FD))
00656     return 0;
00657   // Return the preferred block size.
00658   return statbuf.st_blksize;
00659 #else
00660   return raw_ostream::preferred_buffer_size();
00661 #endif
00662 }
00663 
00664 raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
00665                                          bool bg) {
00666   if (sys::Process::ColorNeedsFlush())
00667     flush();
00668   const char *colorcode =
00669     (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
00670     : sys::Process::OutputColor(colors, bold, bg);
00671   if (colorcode) {
00672     size_t len = strlen(colorcode);
00673     write(colorcode, len);
00674     // don't account colors towards output characters
00675     pos -= len;
00676   }
00677   return *this;
00678 }
00679 
00680 raw_ostream &raw_fd_ostream::resetColor() {
00681   if (sys::Process::ColorNeedsFlush())
00682     flush();
00683   const char *colorcode = sys::Process::ResetColor();
00684   if (colorcode) {
00685     size_t len = strlen(colorcode);
00686     write(colorcode, len);
00687     // don't account colors towards output characters
00688     pos -= len;
00689   }
00690   return *this;
00691 }
00692 
00693 raw_ostream &raw_fd_ostream::reverseColor() {
00694   if (sys::Process::ColorNeedsFlush())
00695     flush();
00696   const char *colorcode = sys::Process::OutputReverse();
00697   if (colorcode) {
00698     size_t len = strlen(colorcode);
00699     write(colorcode, len);
00700     // don't account colors towards output characters
00701     pos -= len;
00702   }
00703   return *this;
00704 }
00705 
00706 bool raw_fd_ostream::is_displayed() const {
00707   return sys::Process::FileDescriptorIsDisplayed(FD);
00708 }
00709 
00710 bool raw_fd_ostream::has_colors() const {
00711   return sys::Process::FileDescriptorHasColors(FD);
00712 }
00713 
00714 //===----------------------------------------------------------------------===//
00715 //  outs(), errs(), nulls()
00716 //===----------------------------------------------------------------------===//
00717 
00718 /// outs() - This returns a reference to a raw_ostream for standard output.
00719 /// Use it like: outs() << "foo" << "bar";
00720 raw_ostream &llvm::outs() {
00721   // Set buffer settings to model stdout behavior.
00722   // Delete the file descriptor when the program exits, forcing error
00723   // detection. If you don't want this behavior, don't use outs().
00724   std::error_code EC;
00725   static raw_fd_ostream S("-", EC, sys::fs::F_None);
00726   assert(!EC);
00727   return S;
00728 }
00729 
00730 /// errs() - This returns a reference to a raw_ostream for standard error.
00731 /// Use it like: errs() << "foo" << "bar";
00732 raw_ostream &llvm::errs() {
00733   // Set standard error to be unbuffered by default.
00734   static raw_fd_ostream S(STDERR_FILENO, false, true);
00735   return S;
00736 }
00737 
00738 /// nulls() - This returns a reference to a raw_ostream which discards output.
00739 raw_ostream &llvm::nulls() {
00740   static raw_null_ostream S;
00741   return S;
00742 }
00743 
00744 
00745 //===----------------------------------------------------------------------===//
00746 //  raw_string_ostream
00747 //===----------------------------------------------------------------------===//
00748 
00749 raw_string_ostream::~raw_string_ostream() {
00750   flush();
00751 }
00752 
00753 void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
00754   OS.append(Ptr, Size);
00755 }
00756 
00757 //===----------------------------------------------------------------------===//
00758 //  raw_svector_ostream
00759 //===----------------------------------------------------------------------===//
00760 
00761 uint64_t raw_svector_ostream::current_pos() const { return OS.size(); }
00762 
00763 void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
00764   OS.append(Ptr, Ptr + Size);
00765 }
00766 
00767 void raw_svector_ostream::pwrite_impl(const char *Ptr, size_t Size,
00768                                       uint64_t Offset) {
00769   memcpy(OS.data() + Offset, Ptr, Size);
00770 }
00771 
00772 //===----------------------------------------------------------------------===//
00773 //  raw_null_ostream
00774 //===----------------------------------------------------------------------===//
00775 
00776 raw_null_ostream::~raw_null_ostream() {
00777 #ifndef NDEBUG
00778   // ~raw_ostream asserts that the buffer is empty. This isn't necessary
00779   // with raw_null_ostream, but it's better to have raw_null_ostream follow
00780   // the rules than to change the rules just for raw_null_ostream.
00781   flush();
00782 #endif
00783 }
00784 
00785 void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
00786 }
00787 
00788 uint64_t raw_null_ostream::current_pos() const {
00789   return 0;
00790 }
00791 
00792 void raw_null_ostream::pwrite_impl(const char *Ptr, size_t Size,
00793                                    uint64_t Offset) {}