raw_ostream.cpp revision 203954
1203356Sjoerg//===--- raw_ostream.cpp - Implement the raw_ostream classes --------------===//
2203356Sjoerg//
3203356Sjoerg//                     The LLVM Compiler Infrastructure
4203356Sjoerg//
5203356Sjoerg// This file is distributed under the University of Illinois Open Source
6203356Sjoerg// License. See LICENSE.TXT for details.
7203356Sjoerg//
8203356Sjoerg//===----------------------------------------------------------------------===//
9203356Sjoerg//
10203356Sjoerg// This implements support for bulk buffered stream output.
11203356Sjoerg//
12203356Sjoerg//===----------------------------------------------------------------------===//
13203356Sjoerg
14203356Sjoerg#include "llvm/Support/raw_ostream.h"
15203356Sjoerg#include "llvm/Support/Format.h"
16203356Sjoerg#include "llvm/System/Program.h"
17203356Sjoerg#include "llvm/System/Process.h"
18203356Sjoerg#include "llvm/ADT/SmallVector.h"
19203356Sjoerg#include "llvm/Config/config.h"
20203356Sjoerg#include "llvm/Support/Compiler.h"
21203356Sjoerg#include "llvm/Support/ErrorHandling.h"
22203356Sjoerg#include "llvm/ADT/STLExtras.h"
23203356Sjoerg#include <cctype>
24203356Sjoerg#include <sys/stat.h>
25203356Sjoerg#include <sys/types.h>
26203356Sjoerg
27203356Sjoerg#if defined(HAVE_UNISTD_H)
28203356Sjoerg# include <unistd.h>
29203356Sjoerg#endif
30203356Sjoerg#if defined(HAVE_FCNTL_H)
31203356Sjoerg# include <fcntl.h>
32203356Sjoerg#endif
33203356Sjoerg
34203356Sjoerg#if defined(_MSC_VER)
35203356Sjoerg#include <io.h>
36203356Sjoerg#include <fcntl.h>
37203356Sjoerg#ifndef STDIN_FILENO
38203356Sjoerg# define STDIN_FILENO 0
39203356Sjoerg#endif
40203356Sjoerg#ifndef STDOUT_FILENO
41203356Sjoerg# define STDOUT_FILENO 1
42203356Sjoerg#endif
43203356Sjoerg#ifndef STDERR_FILENO
44203356Sjoerg# define STDERR_FILENO 2
45203356Sjoerg#endif
46203356Sjoerg#endif
47203356Sjoerg
48203356Sjoergusing namespace llvm;
49203356Sjoerg
50203356Sjoergraw_ostream::~raw_ostream() {
51203356Sjoerg  // raw_ostream's subclasses should take care to flush the buffer
52203356Sjoerg  // in their destructors.
53203356Sjoerg  assert(OutBufCur == OutBufStart &&
54203356Sjoerg         "raw_ostream destructor called with non-empty buffer!");
55203356Sjoerg
56203356Sjoerg  if (BufferMode == InternalBuffer)
57203356Sjoerg    delete [] OutBufStart;
58203356Sjoerg
59203356Sjoerg  // If there are any pending errors, report them now. Clients wishing
60203356Sjoerg  // to avoid llvm_report_error calls should check for errors with
61203356Sjoerg  // has_error() and clear the error flag with clear_error() before
62203356Sjoerg  // destructing raw_ostream objects which may have errors.
63203356Sjoerg  if (Error)
64203356Sjoerg    llvm_report_error("IO failure on output stream.");
65203356Sjoerg}
66203356Sjoerg
67203356Sjoerg// An out of line virtual method to provide a home for the class vtable.
68203356Sjoergvoid raw_ostream::handle() {}
69203356Sjoerg
70203356Sjoergsize_t raw_ostream::preferred_buffer_size() const {
71203356Sjoerg  // BUFSIZ is intended to be a reasonable default.
72203356Sjoerg  return BUFSIZ;
73203356Sjoerg}
74203356Sjoerg
75203356Sjoergvoid raw_ostream::SetBuffered() {
76203356Sjoerg  // Ask the subclass to determine an appropriate buffer size.
77203356Sjoerg  if (size_t Size = preferred_buffer_size())
78203356Sjoerg    SetBufferSize(Size);
79203356Sjoerg  else
80203356Sjoerg    // It may return 0, meaning this stream should be unbuffered.
81203356Sjoerg    SetUnbuffered();
82203356Sjoerg}
83203356Sjoerg
84203356Sjoergvoid raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size,
85203356Sjoerg                                    BufferKind Mode) {
86203356Sjoerg  assert(((Mode == Unbuffered && BufferStart == 0 && Size == 0) ||
87203356Sjoerg          (Mode != Unbuffered && BufferStart && Size)) &&
88203356Sjoerg         "stream must be unbuffered or have at least one byte");
89203356Sjoerg  // Make sure the current buffer is free of content (we can't flush here; the
90203356Sjoerg  // child buffer management logic will be in write_impl).
91203356Sjoerg  assert(GetNumBytesInBuffer() == 0 && "Current buffer is non-empty!");
92203356Sjoerg
93203356Sjoerg  if (BufferMode == InternalBuffer)
94203356Sjoerg    delete [] OutBufStart;
95203356Sjoerg  OutBufStart = BufferStart;
96203356Sjoerg  OutBufEnd = OutBufStart+Size;
97203356Sjoerg  OutBufCur = OutBufStart;
98203356Sjoerg  BufferMode = Mode;
99203356Sjoerg
100203356Sjoerg  assert(OutBufStart <= OutBufEnd && "Invalid size!");
101203356Sjoerg}
102203356Sjoerg
103203356Sjoergraw_ostream &raw_ostream::operator<<(unsigned long N) {
104203356Sjoerg  // Zero is a special case.
105203356Sjoerg  if (N == 0)
106203356Sjoerg    return *this << '0';
107203356Sjoerg
108203356Sjoerg  char NumberBuffer[20];
109203356Sjoerg  char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
110203356Sjoerg  char *CurPtr = EndPtr;
111203356Sjoerg
112203356Sjoerg  while (N) {
113203356Sjoerg    *--CurPtr = '0' + char(N % 10);
114203356Sjoerg    N /= 10;
115203356Sjoerg  }
116203356Sjoerg  return write(CurPtr, EndPtr-CurPtr);
117203356Sjoerg}
118203356Sjoerg
119203356Sjoergraw_ostream &raw_ostream::operator<<(long N) {
120203356Sjoerg  if (N <  0) {
121203356Sjoerg    *this << '-';
122203356Sjoerg    N = -N;
123203356Sjoerg  }
124203356Sjoerg
125203356Sjoerg  return this->operator<<(static_cast<unsigned long>(N));
126203356Sjoerg}
127203356Sjoerg
128203356Sjoergraw_ostream &raw_ostream::operator<<(unsigned long long N) {
129203356Sjoerg  // Output using 32-bit div/mod when possible.
130203356Sjoerg  if (N == static_cast<unsigned long>(N))
131203356Sjoerg    return this->operator<<(static_cast<unsigned long>(N));
132203356Sjoerg
133203356Sjoerg  char NumberBuffer[20];
134203356Sjoerg  char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
135203356Sjoerg  char *CurPtr = EndPtr;
136203356Sjoerg
137203356Sjoerg  while (N) {
138203356Sjoerg    *--CurPtr = '0' + char(N % 10);
139203356Sjoerg    N /= 10;
140203356Sjoerg  }
141203356Sjoerg  return write(CurPtr, EndPtr-CurPtr);
142203356Sjoerg}
143203356Sjoerg
144203356Sjoergraw_ostream &raw_ostream::operator<<(long long N) {
145203356Sjoerg  if (N <  0) {
146203356Sjoerg    *this << '-';
147203356Sjoerg    N = -N;
148203356Sjoerg  }
149203356Sjoerg
150203356Sjoerg  return this->operator<<(static_cast<unsigned long long>(N));
151203356Sjoerg}
152203356Sjoerg
153203356Sjoergraw_ostream &raw_ostream::write_hex(unsigned long long N) {
154203356Sjoerg  // Zero is a special case.
155203356Sjoerg  if (N == 0)
156203356Sjoerg    return *this << '0';
157203356Sjoerg
158203356Sjoerg  char NumberBuffer[20];
159203356Sjoerg  char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
160203356Sjoerg  char *CurPtr = EndPtr;
161203356Sjoerg
162203356Sjoerg  while (N) {
163203356Sjoerg    uintptr_t x = N % 16;
164203356Sjoerg    *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
165203356Sjoerg    N /= 16;
166203356Sjoerg  }
167203356Sjoerg
168203356Sjoerg  return write(CurPtr, EndPtr-CurPtr);
169203356Sjoerg}
170203356Sjoerg
171203356Sjoergraw_ostream &raw_ostream::write_escaped(StringRef Str) {
172203356Sjoerg  for (unsigned i = 0, e = Str.size(); i != e; ++i) {
173203356Sjoerg    unsigned char c = Str[i];
174203356Sjoerg
175203356Sjoerg    switch (c) {
176203356Sjoerg    case '\\':
177203356Sjoerg      *this << '\\' << '\\';
178203356Sjoerg      break;
179203356Sjoerg    case '\t':
180203356Sjoerg      *this << '\\' << 't';
181203356Sjoerg      break;
182203356Sjoerg    case '\n':
183203356Sjoerg      *this << '\\' << 'n';
184203356Sjoerg      break;
185203356Sjoerg    case '"':
186203356Sjoerg      *this << '\\' << '"';
187203356Sjoerg      break;
188203356Sjoerg    default:
189203356Sjoerg      if (std::isprint(c)) {
190203356Sjoerg        *this << c;
191203356Sjoerg        break;
192203356Sjoerg      }
193203356Sjoerg
194203356Sjoerg      // Always expand to a 3-character octal escape.
195203356Sjoerg      *this << '\\';
196203356Sjoerg      *this << char('0' + ((c >> 6) & 7));
197203356Sjoerg      *this << char('0' + ((c >> 3) & 7));
198203356Sjoerg      *this << char('0' + ((c >> 0) & 7));
199203356Sjoerg    }
200203356Sjoerg  }
201203356Sjoerg
202203356Sjoerg  return *this;
203203356Sjoerg}
204203356Sjoerg
205203356Sjoergraw_ostream &raw_ostream::operator<<(const void *P) {
206203356Sjoerg  *this << '0' << 'x';
207203356Sjoerg
208203356Sjoerg  return write_hex((uintptr_t) P);
209203356Sjoerg}
210236438Sjoel
211236438Sjoelraw_ostream &raw_ostream::operator<<(double N) {
212203356Sjoerg  return this->operator<<(format("%e", N));
213203356Sjoerg}
214203356Sjoerg
215203356Sjoerg
216203356Sjoerg
217203356Sjoergvoid raw_ostream::flush_nonempty() {
218203356Sjoerg  assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
219203356Sjoerg  size_t Length = OutBufCur - OutBufStart;
220203356Sjoerg  OutBufCur = OutBufStart;
221203356Sjoerg  write_impl(OutBufStart, Length);
222203356Sjoerg}
223203356Sjoerg
224203356Sjoergraw_ostream &raw_ostream::write(unsigned char C) {
225203356Sjoerg  // Group exceptional cases into a single branch.
226203356Sjoerg  if (BUILTIN_EXPECT(OutBufCur >= OutBufEnd, false)) {
227203356Sjoerg    if (BUILTIN_EXPECT(!OutBufStart, false)) {
228203356Sjoerg      if (BufferMode == Unbuffered) {
229203356Sjoerg        write_impl(reinterpret_cast<char*>(&C), 1);
230203356Sjoerg        return *this;
231203356Sjoerg      }
232203356Sjoerg      // Set up a buffer and start over.
233203356Sjoerg      SetBuffered();
234203356Sjoerg      return write(C);
235203356Sjoerg    }
236203356Sjoerg
237203356Sjoerg    flush_nonempty();
238203356Sjoerg  }
239203356Sjoerg
240203356Sjoerg  *OutBufCur++ = C;
241203356Sjoerg  return *this;
242203356Sjoerg}
243203356Sjoerg
244203356Sjoergraw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
245203356Sjoerg  // Group exceptional cases into a single branch.
246203356Sjoerg  if (BUILTIN_EXPECT(OutBufCur+Size > OutBufEnd, false)) {
247203356Sjoerg    if (BUILTIN_EXPECT(!OutBufStart, false)) {
248236438Sjoel      if (BufferMode == Unbuffered) {
249236438Sjoel        write_impl(Ptr, Size);
250203356Sjoerg        return *this;
251203356Sjoerg      }
252203356Sjoerg      // Set up a buffer and start over.
253203356Sjoerg      SetBuffered();
254203356Sjoerg      return write(Ptr, Size);
255203356Sjoerg    }
256203356Sjoerg
257203356Sjoerg    // Write out the data in buffer-sized blocks until the remainder
258203356Sjoerg    // fits within the buffer.
259203356Sjoerg    do {
260203356Sjoerg      size_t NumBytes = OutBufEnd - OutBufCur;
261203356Sjoerg      copy_to_buffer(Ptr, NumBytes);
262203356Sjoerg      flush_nonempty();
263210933Sjoel      Ptr += NumBytes;
264203356Sjoerg      Size -= NumBytes;
265203356Sjoerg    } while (OutBufCur+Size > OutBufEnd);
266203356Sjoerg  }
267203356Sjoerg
268203356Sjoerg  copy_to_buffer(Ptr, Size);
269203356Sjoerg
270203356Sjoerg  return *this;
271203356Sjoerg}
272203356Sjoerg
273203356Sjoergvoid raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
274203356Sjoerg  assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
275203356Sjoerg
276203356Sjoerg  // Handle short strings specially, memcpy isn't very good at very short
277203356Sjoerg  // strings.
278203356Sjoerg  switch (Size) {
279203356Sjoerg  case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
280203356Sjoerg  case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
281203356Sjoerg  case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
282203356Sjoerg  case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
283203356Sjoerg  case 0: break;
284203356Sjoerg  default:
285203356Sjoerg    memcpy(OutBufCur, Ptr, Size);
286203356Sjoerg    break;
287203356Sjoerg  }
288203356Sjoerg
289203356Sjoerg  OutBufCur += Size;
290203356Sjoerg}
291203356Sjoerg
292203356Sjoerg// Formatted output.
293203356Sjoergraw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
294203356Sjoerg  // If we have more than a few bytes left in our output buffer, try
295203356Sjoerg  // formatting directly onto its end.
296203356Sjoerg  size_t NextBufferSize = 127;
297203356Sjoerg  size_t BufferBytesLeft = OutBufEnd - OutBufCur;
298203356Sjoerg  if (BufferBytesLeft > 3) {
299203356Sjoerg    size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
300203356Sjoerg
301203356Sjoerg    // Common case is that we have plenty of space.
302203356Sjoerg    if (BytesUsed <= BufferBytesLeft) {
303203356Sjoerg      OutBufCur += BytesUsed;
304203356Sjoerg      return *this;
305203356Sjoerg    }
306203356Sjoerg
307203356Sjoerg    // Otherwise, we overflowed and the return value tells us the size to try
308203356Sjoerg    // again with.
309203356Sjoerg    NextBufferSize = BytesUsed;
310203356Sjoerg  }
311203356Sjoerg
312203356Sjoerg  // If we got here, we didn't have enough space in the output buffer for the
313203356Sjoerg  // string.  Try printing into a SmallVector that is resized to have enough
314203356Sjoerg  // space.  Iterate until we win.
315203356Sjoerg  SmallVector<char, 128> V;
316203356Sjoerg
317203356Sjoerg  while (1) {
318203356Sjoerg    V.resize(NextBufferSize);
319203356Sjoerg
320203356Sjoerg    // Try formatting into the SmallVector.
321203356Sjoerg    size_t BytesUsed = Fmt.print(V.data(), NextBufferSize);
322203356Sjoerg
323203356Sjoerg    // If BytesUsed fit into the vector, we win.
324203356Sjoerg    if (BytesUsed <= NextBufferSize)
325203356Sjoerg      return write(V.data(), BytesUsed);
326203356Sjoerg
327203356Sjoerg    // Otherwise, try again with a new size.
328203356Sjoerg    assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
329203356Sjoerg    NextBufferSize = BytesUsed;
330203356Sjoerg  }
331203356Sjoerg}
332203356Sjoerg
333203356Sjoerg/// indent - Insert 'NumSpaces' spaces.
334236438Sjoelraw_ostream &raw_ostream::indent(unsigned NumSpaces) {
335236438Sjoel  static const char Spaces[] = "                                "
336203356Sjoerg                               "                                "
337203356Sjoerg                               "                ";
338203356Sjoerg
339203356Sjoerg  // Usually the indentation is small, handle it with a fastpath.
340203356Sjoerg  if (NumSpaces < array_lengthof(Spaces))
341203356Sjoerg    return write(Spaces, NumSpaces);
342203356Sjoerg
343203356Sjoerg  while (NumSpaces) {
344203356Sjoerg    unsigned NumToWrite = std::min(NumSpaces,
345203356Sjoerg                                   (unsigned)array_lengthof(Spaces)-1);
346203356Sjoerg    write(Spaces, NumToWrite);
347203356Sjoerg    NumSpaces -= NumToWrite;
348203356Sjoerg  }
349203356Sjoerg  return *this;
350203356Sjoerg}
351203356Sjoerg
352203356Sjoerg
353203356Sjoerg//===----------------------------------------------------------------------===//
354236438Sjoel//  Formatted Output
355203356Sjoerg//===----------------------------------------------------------------------===//
356203356Sjoerg
357203356Sjoerg// Out of line virtual method.
358203356Sjoergvoid format_object_base::home() {
359203356Sjoerg}
360203356Sjoerg
361203356Sjoerg//===----------------------------------------------------------------------===//
362203356Sjoerg//  raw_fd_ostream
363203356Sjoerg//===----------------------------------------------------------------------===//
364203356Sjoerg
365203356Sjoerg/// raw_fd_ostream - Open the specified file for writing. If an error
366203356Sjoerg/// occurs, information about the error is put into ErrorInfo, and the
367203356Sjoerg/// stream should be immediately destroyed; the string will be empty
368203356Sjoerg/// if no error occurred.
369203356Sjoergraw_fd_ostream::raw_fd_ostream(const char *Filename, std::string &ErrorInfo,
370203356Sjoerg                               unsigned Flags) : pos(0) {
371203356Sjoerg  // Verify that we don't have both "append" and "excl".
372203356Sjoerg  assert((!(Flags & F_Excl) || !(Flags & F_Append)) &&
373203356Sjoerg         "Cannot specify both 'excl' and 'append' file creation flags!");
374203356Sjoerg
375203356Sjoerg  ErrorInfo.clear();
376203356Sjoerg
377203356Sjoerg  // Handle "-" as stdout.
378203356Sjoerg  if (Filename[0] == '-' && Filename[1] == 0) {
379203356Sjoerg    FD = STDOUT_FILENO;
380203356Sjoerg    // If user requested binary then put stdout into binary mode if
381203356Sjoerg    // possible.
382203356Sjoerg    if (Flags & F_Binary)
383203356Sjoerg      sys::Program::ChangeStdoutToBinary();
384203356Sjoerg    ShouldClose = false;
385203356Sjoerg    return;
386203356Sjoerg  }
387203356Sjoerg
388203356Sjoerg  int OpenFlags = O_WRONLY|O_CREAT;
389203356Sjoerg#ifdef O_BINARY
390203356Sjoerg  if (Flags & F_Binary)
391203356Sjoerg    OpenFlags |= O_BINARY;
392203356Sjoerg#endif
393203356Sjoerg
394203356Sjoerg  if (Flags & F_Append)
395203356Sjoerg    OpenFlags |= O_APPEND;
396203356Sjoerg  else
397203356Sjoerg    OpenFlags |= O_TRUNC;
398203356Sjoerg  if (Flags & F_Excl)
399203356Sjoerg    OpenFlags |= O_EXCL;
400203356Sjoerg
401203356Sjoerg  FD = open(Filename, OpenFlags, 0664);
402203356Sjoerg  if (FD < 0) {
403203356Sjoerg    ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
404203356Sjoerg    ShouldClose = false;
405203356Sjoerg  } else {
406203356Sjoerg    ShouldClose = true;
407203356Sjoerg  }
408203356Sjoerg}
409203356Sjoerg
410203356Sjoergraw_fd_ostream::~raw_fd_ostream() {
411203356Sjoerg  if (FD < 0) return;
412203356Sjoerg  flush();
413203356Sjoerg  if (ShouldClose)
414203356Sjoerg    if (::close(FD) != 0)
415203356Sjoerg      error_detected();
416203356Sjoerg}
417203356Sjoerg
418203356Sjoerg
419203356Sjoergvoid raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
420203356Sjoerg  assert (FD >= 0 && "File already closed.");
421203356Sjoerg  pos += Size;
422203356Sjoerg  if (::write(FD, Ptr, Size) != (ssize_t) Size)
423203356Sjoerg    error_detected();
424203356Sjoerg}
425203356Sjoerg
426203356Sjoergvoid raw_fd_ostream::close() {
427203356Sjoerg  assert (ShouldClose);
428203356Sjoerg  ShouldClose = false;
429203356Sjoerg  flush();
430203356Sjoerg  if (::close(FD) != 0)
431203356Sjoerg    error_detected();
432203356Sjoerg  FD = -1;
433203356Sjoerg}
434203356Sjoerg
435203356Sjoerguint64_t raw_fd_ostream::seek(uint64_t off) {
436203356Sjoerg  flush();
437203356Sjoerg  pos = ::lseek(FD, off, SEEK_SET);
438203356Sjoerg  if (pos != off)
439203356Sjoerg    error_detected();
440203356Sjoerg  return pos;
441203356Sjoerg}
442203356Sjoerg
443203356Sjoergsize_t raw_fd_ostream::preferred_buffer_size() const {
444203356Sjoerg#if !defined(_MSC_VER) && !defined(__MINGW32__) // Windows has no st_blksize.
445203356Sjoerg  assert(FD >= 0 && "File not yet open!");
446203356Sjoerg  struct stat statbuf;
447203356Sjoerg  if (fstat(FD, &statbuf) != 0)
448203356Sjoerg    return 0;
449203356Sjoerg
450203356Sjoerg  // If this is a terminal, don't use buffering. Line buffering
451203356Sjoerg  // would be a more traditional thing to do, but it's not worth
452203356Sjoerg  // the complexity.
453203356Sjoerg  if (S_ISCHR(statbuf.st_mode) && isatty(FD))
454203356Sjoerg    return 0;
455203356Sjoerg  // Return the preferred block size.
456203356Sjoerg  return statbuf.st_blksize;
457203356Sjoerg#endif
458203356Sjoerg  return raw_ostream::preferred_buffer_size();
459203356Sjoerg}
460203356Sjoerg
461203356Sjoergraw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
462203356Sjoerg                                         bool bg) {
463203356Sjoerg  if (sys::Process::ColorNeedsFlush())
464203356Sjoerg    flush();
465203356Sjoerg  const char *colorcode =
466203356Sjoerg    (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
467203356Sjoerg    : sys::Process::OutputColor(colors, bold, bg);
468203356Sjoerg  if (colorcode) {
469203356Sjoerg    size_t len = strlen(colorcode);
470203356Sjoerg    write(colorcode, len);
471203356Sjoerg    // don't account colors towards output characters
472203356Sjoerg    pos -= len;
473203356Sjoerg  }
474203356Sjoerg  return *this;
475203356Sjoerg}
476203356Sjoerg
477203356Sjoergraw_ostream &raw_fd_ostream::resetColor() {
478203356Sjoerg  if (sys::Process::ColorNeedsFlush())
479203356Sjoerg    flush();
480203356Sjoerg  const char *colorcode = sys::Process::ResetColor();
481203356Sjoerg  if (colorcode) {
482203356Sjoerg    size_t len = strlen(colorcode);
483203356Sjoerg    write(colorcode, len);
484203356Sjoerg    // don't account colors towards output characters
485203356Sjoerg    pos -= len;
486203356Sjoerg  }
487203356Sjoerg  return *this;
488203356Sjoerg}
489203356Sjoerg
490203356Sjoergbool raw_fd_ostream::is_displayed() const {
491203356Sjoerg  return sys::Process::FileDescriptorIsDisplayed(FD);
492203356Sjoerg}
493203356Sjoerg
494203356Sjoerg//===----------------------------------------------------------------------===//
495203356Sjoerg//  raw_stdout/err_ostream
496203356Sjoerg//===----------------------------------------------------------------------===//
497203356Sjoerg
498203356Sjoerg// Set buffer settings to model stdout and stderr behavior.
499203356Sjoerg// Set standard error to be unbuffered by default.
500203356Sjoergraw_stdout_ostream::raw_stdout_ostream():raw_fd_ostream(STDOUT_FILENO, false) {}
501203356Sjoergraw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO, false,
502203356Sjoerg                                                        true) {}
503203356Sjoerg
504203356Sjoerg// An out of line virtual method to provide a home for the class vtable.
505203356Sjoergvoid raw_stdout_ostream::handle() {}
506203356Sjoergvoid raw_stderr_ostream::handle() {}
507203356Sjoerg
508203356Sjoerg/// outs() - This returns a reference to a raw_ostream for standard output.
509203356Sjoerg/// Use it like: outs() << "foo" << "bar";
510203356Sjoergraw_ostream &llvm::outs() {
511203356Sjoerg  static raw_stdout_ostream S;
512203356Sjoerg  return S;
513203356Sjoerg}
514203356Sjoerg
515203356Sjoerg/// errs() - This returns a reference to a raw_ostream for standard error.
516203356Sjoerg/// Use it like: errs() << "foo" << "bar";
517203356Sjoergraw_ostream &llvm::errs() {
518203356Sjoerg  static raw_stderr_ostream S;
519203356Sjoerg  return S;
520203356Sjoerg}
521203356Sjoerg
522203356Sjoerg/// nulls() - This returns a reference to a raw_ostream which discards output.
523203356Sjoergraw_ostream &llvm::nulls() {
524203356Sjoerg  static raw_null_ostream S;
525203356Sjoerg  return S;
526203356Sjoerg}
527203356Sjoerg
528203356Sjoerg
529203356Sjoerg//===----------------------------------------------------------------------===//
530211397Sjoel//  raw_string_ostream
531203356Sjoerg//===----------------------------------------------------------------------===//
532203356Sjoerg
533203356Sjoergraw_string_ostream::~raw_string_ostream() {
534203356Sjoerg  flush();
535203356Sjoerg}
536203356Sjoerg
537203356Sjoergvoid raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
538203356Sjoerg  OS.append(Ptr, Size);
539203356Sjoerg}
540203356Sjoerg
541203356Sjoerg//===----------------------------------------------------------------------===//
542203356Sjoerg//  raw_svector_ostream
543203356Sjoerg//===----------------------------------------------------------------------===//
544203356Sjoerg
545203356Sjoerg// The raw_svector_ostream implementation uses the SmallVector itself as the
546203356Sjoerg// buffer for the raw_ostream. We guarantee that the raw_ostream buffer is
547203356Sjoerg// always pointing past the end of the vector, but within the vector
548203356Sjoerg// capacity. This allows raw_ostream to write directly into the correct place,
549203356Sjoerg// and we only need to set the vector size when the data is flushed.
550203356Sjoerg
551203356Sjoergraw_svector_ostream::raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {
552203356Sjoerg  // Set up the initial external buffer. We make sure that the buffer has at
553203356Sjoerg  // least 128 bytes free; raw_ostream itself only requires 64, but we want to
554203356Sjoerg  // make sure that we don't grow the buffer unnecessarily on destruction (when
555203356Sjoerg  // the data is flushed). See the FIXME below.
556203356Sjoerg  OS.reserve(OS.size() + 128);
557203356Sjoerg  SetBuffer(OS.end(), OS.capacity() - OS.size());
558203356Sjoerg}
559203356Sjoerg
560203356Sjoergraw_svector_ostream::~raw_svector_ostream() {
561203356Sjoerg  // FIXME: Prevent resizing during this flush().
562203356Sjoerg  flush();
563203356Sjoerg}
564203356Sjoerg
565203356Sjoerg/// resync - This is called when the SmallVector we're appending to is changed
566203356Sjoerg/// outside of the raw_svector_ostream's control.  It is only safe to do this
567203356Sjoerg/// if the raw_svector_ostream has previously been flushed.
568203356Sjoergvoid raw_svector_ostream::resync() {
569203356Sjoerg  assert(GetNumBytesInBuffer() == 0 && "Didn't flush before mutating vector");
570203356Sjoerg
571203356Sjoerg  if (OS.capacity() - OS.size() < 64)
572203356Sjoerg    OS.reserve(OS.capacity() * 2);
573203356Sjoerg  SetBuffer(OS.end(), OS.capacity() - OS.size());
574203356Sjoerg}
575203356Sjoerg
576203356Sjoergvoid raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
577203356Sjoerg  // If we're writing bytes from the end of the buffer into the smallvector, we
578203356Sjoerg  // don't need to copy the bytes, just commit the bytes because they are
579203356Sjoerg  // already in the right place.
580203356Sjoerg  if (Ptr == OS.end()) {
581203356Sjoerg    assert(OS.size() + Size <= OS.capacity() && "Invalid write_impl() call!");
582203356Sjoerg    OS.set_size(OS.size() + Size);
583203356Sjoerg  } else {
584203356Sjoerg    assert(GetNumBytesInBuffer() == 0 &&
585203356Sjoerg           "Should be writing from buffer if some bytes in it");
586203356Sjoerg    // Otherwise, do copy the bytes.
587203356Sjoerg    OS.append(Ptr, Ptr+Size);
588203356Sjoerg  }
589203356Sjoerg
590203356Sjoerg  // Grow the vector if necessary.
591203356Sjoerg  if (OS.capacity() - OS.size() < 64)
592203356Sjoerg    OS.reserve(OS.capacity() * 2);
593203356Sjoerg
594203356Sjoerg  // Update the buffer position.
595203356Sjoerg  SetBuffer(OS.end(), OS.capacity() - OS.size());
596203356Sjoerg}
597203356Sjoerg
598203356Sjoerguint64_t raw_svector_ostream::current_pos() const {
599203356Sjoerg   return OS.size();
600203356Sjoerg}
601203356Sjoerg
602203356SjoergStringRef raw_svector_ostream::str() {
603203356Sjoerg  flush();
604203356Sjoerg  return StringRef(OS.begin(), OS.size());
605203356Sjoerg}
606203356Sjoerg
607203356Sjoerg//===----------------------------------------------------------------------===//
608203356Sjoerg//  raw_null_ostream
609203356Sjoerg//===----------------------------------------------------------------------===//
610203356Sjoerg
611203356Sjoergraw_null_ostream::~raw_null_ostream() {
612203356Sjoerg#ifndef NDEBUG
613203356Sjoerg  // ~raw_ostream asserts that the buffer is empty. This isn't necessary
614203356Sjoerg  // with raw_null_ostream, but it's better to have raw_null_ostream follow
615203356Sjoerg  // the rules than to change the rules just for raw_null_ostream.
616203356Sjoerg  flush();
617203356Sjoerg#endif
618203356Sjoerg}
619203356Sjoerg
620203356Sjoergvoid raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
621203356Sjoerg}
622203356Sjoerg
623203356Sjoerguint64_t raw_null_ostream::current_pos() const {
624203356Sjoerg  return 0;
625203356Sjoerg}
626203356Sjoerg