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