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