raw_ostream: Add the capability for subclasses to manually install an external
[oota-llvm.git] / lib / Support / raw_ostream.cpp
1 //===--- raw_ostream.cpp - Implement the raw_ostream classes --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements support for bulk buffered stream output.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Support/raw_ostream.h"
15 #include "llvm/Support/Format.h"
16 #include "llvm/System/Program.h"
17 #include "llvm/System/Process.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/Config/config.h"
20 #include "llvm/Support/Compiler.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include <ostream>
23 #include <sys/stat.h>
24 #include <sys/types.h>
25
26 #if defined(HAVE_UNISTD_H)
27 # include <unistd.h>
28 #endif
29 #if defined(HAVE_FCNTL_H)
30 # include <fcntl.h>
31 #endif
32
33 #if defined(_MSC_VER)
34 #include <io.h>
35 #include <fcntl.h>
36 #ifndef STDIN_FILENO
37 # define STDIN_FILENO 0
38 #endif
39 #ifndef STDOUT_FILENO
40 # define STDOUT_FILENO 1
41 #endif
42 #ifndef STDERR_FILENO
43 # define STDERR_FILENO 2
44 #endif
45 #endif
46
47 using namespace llvm;
48
49 raw_ostream::~raw_ostream() {
50   // raw_ostream's subclasses should take care to flush the buffer
51   // in their destructors.
52   assert(OutBufCur == OutBufStart &&
53          "raw_ostream destructor called with non-empty buffer!");
54
55   if (BufferMode == InternalBuffer)
56     delete [] OutBufStart;
57
58   // If there are any pending errors, report them now. Clients wishing
59   // to avoid llvm_report_error calls should check for errors with
60   // has_error() and clear the error flag with clear_error() before
61   // destructing raw_ostream objects which may have errors.
62   if (Error)
63     llvm_report_error("IO failure on output stream.");
64 }
65
66 // An out of line virtual method to provide a home for the class vtable.
67 void raw_ostream::handle() {}
68
69 size_t raw_ostream::preferred_buffer_size() {
70   // BUFSIZ is intended to be a reasonable default.
71   return BUFSIZ;
72 }
73
74 void raw_ostream::SetBuffered() {
75   // Ask the subclass to determine an appropriate buffer size.
76   if (size_t Size = preferred_buffer_size())
77     SetBufferSize(Size);
78   else
79     // It may return 0, meaning this stream should be unbuffered.
80     SetUnbuffered();
81 }
82
83 void raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size, 
84                                     BufferKind Mode) {
85   assert(((Mode == Unbuffered && BufferStart == 0 && Size == 0) || 
86           (Mode != Unbuffered && BufferStart && Size >= 64)) &&
87          "stream must be unbuffered, or have >= 64 bytes of buffer");
88   // Make sure the current buffer is free of content (we can't flush here; the
89   // child buffer management logic will be in write_impl).
90   assert(GetNumBytesInBuffer() == 0 && "Current buffer is non-empty!");
91
92   if (BufferMode == InternalBuffer)
93     delete [] OutBufStart;
94   OutBufStart = BufferStart;
95   OutBufEnd = OutBufStart+Size;
96   OutBufCur = OutBufStart;
97   BufferMode = Mode;
98 }
99
100 raw_ostream &raw_ostream::operator<<(unsigned long N) {
101   // Zero is a special case.
102   if (N == 0)
103     return *this << '0';
104   
105   char NumberBuffer[20];
106   char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
107   char *CurPtr = EndPtr;
108   
109   while (N) {
110     *--CurPtr = '0' + char(N % 10);
111     N /= 10;
112   }
113   return write(CurPtr, EndPtr-CurPtr);
114 }
115
116 raw_ostream &raw_ostream::operator<<(long N) {
117   if (N <  0) {
118     *this << '-';
119     N = -N;
120   }
121   
122   return this->operator<<(static_cast<unsigned long>(N));
123 }
124
125 raw_ostream &raw_ostream::operator<<(unsigned long long N) {
126   // Handle simple case when value fits in long already.
127   if (N == static_cast<unsigned long>(N))
128     return this->operator<<(static_cast<unsigned long>(N));
129
130   // Otherwise divide into at two or three 10**9 chunks and write out using
131   // long div/mod, this is substantially faster on a 32-bit system.
132   unsigned long Top = 0, Mid = 0, Bot = N % 1000000000;
133   N /= 1000000000;
134   if (N > 1000000000) {
135     Mid = N % 1000000000;
136     Top = N / 1000000000;
137   } else
138     Mid = N;
139
140   if (Top)
141     this->operator<<(static_cast<unsigned long>(Top));
142   this->operator<<(static_cast<unsigned long>(Mid));
143   return this->operator<<(static_cast<unsigned long>(Bot));
144 }
145
146 raw_ostream &raw_ostream::operator<<(long long N) {
147   if (N <  0) {
148     *this << '-';
149     N = -N;
150   }
151   
152   return this->operator<<(static_cast<unsigned long long>(N));
153 }
154
155 raw_ostream &raw_ostream::write_hex(unsigned long long N) {
156   // Zero is a special case.
157   if (N == 0)
158     return *this << '0';
159
160   char NumberBuffer[20];
161   char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
162   char *CurPtr = EndPtr;
163
164   while (N) {
165     uintptr_t x = N % 16;
166     *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
167     N /= 16;
168   }
169
170   return write(CurPtr, EndPtr-CurPtr);
171 }
172
173 raw_ostream &raw_ostream::operator<<(const void *P) {
174   *this << '0' << 'x';
175
176   return write_hex((uintptr_t) P);
177 }
178
179 void raw_ostream::flush_nonempty() {
180   assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
181   size_t Length = OutBufCur - OutBufStart;
182   OutBufCur = OutBufStart;
183   write_impl(OutBufStart, Length);
184 }
185
186 raw_ostream &raw_ostream::write(unsigned char C) {
187   // Group exceptional cases into a single branch.
188   if (OutBufCur >= OutBufEnd) {
189     if (BufferMode == Unbuffered) {
190       write_impl(reinterpret_cast<char*>(&C), 1);
191       return *this;
192     }
193     
194     if (OutBufStart)
195       flush_nonempty();
196     else {
197       SetBuffered();
198       // It's possible for the underlying stream to decline
199       // buffering, so check this condition again.
200       if (BufferMode == Unbuffered) {
201         write_impl(reinterpret_cast<char*>(&C), 1);
202         return *this;
203       }
204     }
205   }
206
207   *OutBufCur++ = C;
208   return *this;
209 }
210
211 raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
212   // Group exceptional cases into a single branch.
213   if (BUILTIN_EXPECT(OutBufCur+Size > OutBufEnd, false)) {
214     if (BUILTIN_EXPECT(!OutBufStart, false)) {
215       if (BufferMode == Unbuffered) {
216         write_impl(Ptr, Size);
217         return *this;
218       }
219       // Set up a buffer and start over.
220       SetBuffered();
221       return write(Ptr, Size);
222     }
223     // Write out the data in buffer-sized blocks until the remainder
224     // fits within the buffer.
225     do {
226       size_t NumBytes = OutBufEnd - OutBufCur;
227       copy_to_buffer(Ptr, NumBytes);
228       flush_nonempty();
229       Ptr += NumBytes;
230       Size -= NumBytes;
231     } while (OutBufCur+Size > OutBufEnd);
232   }
233
234   copy_to_buffer(Ptr, Size);
235
236   return *this;
237 }
238
239 void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
240   assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
241
242   // Handle short strings specially, memcpy isn't very good at very short
243   // strings.
244   switch (Size) {
245   case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
246   case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
247   case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
248   case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
249   case 0: break;
250   default:
251     memcpy(OutBufCur, Ptr, Size);
252     break;
253   }
254
255   OutBufCur += Size;
256 }
257
258 // Formatted output.
259 raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
260   // If we have more than a few bytes left in our output buffer, try
261   // formatting directly onto its end.
262   //
263   // FIXME: This test is a bit silly, since if we don't have enough
264   // space in the buffer we will have to flush the formatted output
265   // anyway. We should just flush upfront in such cases, and use the
266   // whole buffer as our scratch pad. Note, however, that this case is
267   // also necessary for correctness on unbuffered streams.
268   size_t NextBufferSize = 127;
269   if (OutBufEnd-OutBufCur > 3) {
270     size_t BufferBytesLeft = OutBufEnd-OutBufCur;
271     size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
272     
273     // Common case is that we have plenty of space.
274     if (BytesUsed < BufferBytesLeft) {
275       OutBufCur += BytesUsed;
276       return *this;
277     }
278     
279     // Otherwise, we overflowed and the return value tells us the size to try
280     // again with.
281     NextBufferSize = BytesUsed;
282   }
283   
284   // If we got here, we didn't have enough space in the output buffer for the
285   // string.  Try printing into a SmallVector that is resized to have enough
286   // space.  Iterate until we win.
287   SmallVector<char, 128> V;
288   
289   while (1) {
290     V.resize(NextBufferSize);
291     
292     // Try formatting into the SmallVector.
293     size_t BytesUsed = Fmt.print(&V[0], NextBufferSize);
294     
295     // If BytesUsed fit into the vector, we win.
296     if (BytesUsed <= NextBufferSize)
297       return write(&V[0], BytesUsed);
298     
299     // Otherwise, try again with a new size.
300     assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
301     NextBufferSize = BytesUsed;
302   }
303 }
304
305 //===----------------------------------------------------------------------===//
306 //  Formatted Output
307 //===----------------------------------------------------------------------===//
308
309 // Out of line virtual method.
310 void format_object_base::home() {
311 }
312
313 //===----------------------------------------------------------------------===//
314 //  raw_fd_ostream
315 //===----------------------------------------------------------------------===//
316
317 /// raw_fd_ostream - Open the specified file for writing. If an error
318 /// occurs, information about the error is put into ErrorInfo, and the
319 /// stream should be immediately destroyed; the string will be empty
320 /// if no error occurred.
321 raw_fd_ostream::raw_fd_ostream(const char *Filename, bool Binary, bool Force,
322                                std::string &ErrorInfo) : pos(0) {
323   ErrorInfo.clear();
324
325   // Handle "-" as stdout.
326   if (Filename[0] == '-' && Filename[1] == 0) {
327     FD = STDOUT_FILENO;
328     // If user requested binary then put stdout into binary mode if
329     // possible.
330     if (Binary)
331       sys::Program::ChangeStdoutToBinary();
332     ShouldClose = false;
333     return;
334   }
335   
336   int Flags = O_WRONLY|O_CREAT|O_TRUNC;
337 #ifdef O_BINARY
338   if (Binary)
339     Flags |= O_BINARY;
340 #endif
341   if (!Force)
342     Flags |= O_EXCL;
343   FD = open(Filename, Flags, 0664);
344   if (FD < 0) {
345     ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
346     ShouldClose = false;
347   } else {
348     ShouldClose = true;
349   }
350 }
351
352 raw_fd_ostream::~raw_fd_ostream() {
353   if (FD >= 0) {
354     flush();
355     if (ShouldClose)
356       if (::close(FD) != 0)
357         error_detected();
358   }
359 }
360
361 void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
362   assert (FD >= 0 && "File already closed.");
363   pos += Size;
364   if (::write(FD, Ptr, Size) != (ssize_t) Size)
365     error_detected();
366 }
367
368 void raw_fd_ostream::close() {
369   assert (ShouldClose);
370   ShouldClose = false;
371   flush();
372   if (::close(FD) != 0)
373     error_detected();
374   FD = -1;
375 }
376
377 uint64_t raw_fd_ostream::seek(uint64_t off) {
378   flush();
379   pos = ::lseek(FD, off, SEEK_SET);
380   if (pos != off)
381     error_detected();
382   return pos;  
383 }
384
385 size_t raw_fd_ostream::preferred_buffer_size() {
386 #if !defined(_MSC_VER) && !defined(__MINGW32__) // Windows has no st_blksize.
387   assert(FD >= 0 && "File not yet open!");
388   struct stat statbuf;
389   if (fstat(FD, &statbuf) == 0) {
390     // If this is a terminal, don't use buffering. Line buffering
391     // would be a more traditional thing to do, but it's not worth
392     // the complexity.
393     if (S_ISCHR(statbuf.st_mode) && isatty(FD))
394       return 0;
395     // Return the preferred block size.
396     return statbuf.st_blksize;
397   }
398   error_detected();
399 #endif
400   return raw_ostream::preferred_buffer_size();
401 }
402
403 raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
404                                          bool bg) {
405   if (sys::Process::ColorNeedsFlush())
406     flush();
407   const char *colorcode =
408     (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
409     : sys::Process::OutputColor(colors, bold, bg);
410   if (colorcode) {
411     size_t len = strlen(colorcode);
412     write(colorcode, len);
413     // don't account colors towards output characters
414     pos -= len;
415   }
416   return *this;
417 }
418
419 raw_ostream &raw_fd_ostream::resetColor() {
420   if (sys::Process::ColorNeedsFlush())
421     flush();
422   const char *colorcode = sys::Process::ResetColor();
423   if (colorcode) {
424     size_t len = strlen(colorcode);
425     write(colorcode, len);
426     // don't account colors towards output characters
427     pos -= len;
428   }
429   return *this;
430 }
431
432 //===----------------------------------------------------------------------===//
433 //  raw_stdout/err_ostream
434 //===----------------------------------------------------------------------===//
435
436 // Set buffer settings to model stdout and stderr behavior.
437 // Set standard error to be unbuffered by default.
438 raw_stdout_ostream::raw_stdout_ostream():raw_fd_ostream(STDOUT_FILENO, false) {}
439 raw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO, false,
440                                                         true) {}
441
442 // An out of line virtual method to provide a home for the class vtable.
443 void raw_stdout_ostream::handle() {}
444 void raw_stderr_ostream::handle() {}
445
446 /// outs() - This returns a reference to a raw_ostream for standard output.
447 /// Use it like: outs() << "foo" << "bar";
448 raw_ostream &llvm::outs() {
449   static raw_stdout_ostream S;
450   return S;
451 }
452
453 /// errs() - This returns a reference to a raw_ostream for standard error.
454 /// Use it like: errs() << "foo" << "bar";
455 raw_ostream &llvm::errs() {
456   static raw_stderr_ostream S;
457   return S;
458 }
459
460 /// nulls() - This returns a reference to a raw_ostream which discards output.
461 raw_ostream &llvm::nulls() {
462   static raw_null_ostream S;
463   return S;
464 }
465
466 //===----------------------------------------------------------------------===//
467 //  raw_os_ostream
468 //===----------------------------------------------------------------------===//
469
470 raw_os_ostream::~raw_os_ostream() {
471   flush();
472 }
473
474 void raw_os_ostream::write_impl(const char *Ptr, size_t Size) {
475   OS.write(Ptr, Size);
476 }
477
478 uint64_t raw_os_ostream::current_pos() { return OS.tellp(); }
479
480 uint64_t raw_os_ostream::tell() { 
481   return (uint64_t)OS.tellp() + GetNumBytesInBuffer(); 
482 }
483
484 //===----------------------------------------------------------------------===//
485 //  raw_string_ostream
486 //===----------------------------------------------------------------------===//
487
488 raw_string_ostream::~raw_string_ostream() {
489   flush();
490 }
491
492 void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
493   OS.append(Ptr, Size);
494 }
495
496 //===----------------------------------------------------------------------===//
497 //  raw_svector_ostream
498 //===----------------------------------------------------------------------===//
499
500 raw_svector_ostream::raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {
501 }
502
503 raw_svector_ostream::~raw_svector_ostream() {
504   flush();
505 }
506
507 void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
508   OS.append(Ptr, Ptr + Size);
509 }
510
511 uint64_t raw_svector_ostream::current_pos() { return OS.size(); }
512
513 uint64_t raw_svector_ostream::tell() { 
514   return OS.size() + GetNumBytesInBuffer(); 
515 }
516
517 //===----------------------------------------------------------------------===//
518 //  raw_null_ostream
519 //===----------------------------------------------------------------------===//
520
521 raw_null_ostream::~raw_null_ostream() {
522 #ifndef NDEBUG
523   // ~raw_ostream asserts that the buffer is empty. This isn't necessary
524   // with raw_null_ostream, but it's better to have raw_null_ostream follow
525   // the rules than to change the rules just for raw_null_ostream.
526   flush();
527 #endif
528 }
529
530 void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
531 }
532
533 uint64_t raw_null_ostream::current_pos() {
534   return 0;
535 }