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