LLVM API Documentation

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