3e1a8a9765c313abe8188d8cd1afe1ae7ea7277d
[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
24 #if defined(HAVE_UNISTD_H)
25 # include <unistd.h>
26 #endif
27 #if defined(HAVE_FCNTL_H)
28 # include <fcntl.h>
29 #endif
30
31 #if defined(_MSC_VER)
32 #include <io.h>
33 #include <fcntl.h>
34 #ifndef STDIN_FILENO
35 # define STDIN_FILENO 0
36 #endif
37 #ifndef STDOUT_FILENO
38 # define STDOUT_FILENO 1
39 #endif
40 #ifndef STDERR_FILENO
41 # define STDERR_FILENO 2
42 #endif
43 #endif
44
45 using namespace llvm;
46
47
48 // An out of line virtual method to provide a home for the class vtable.
49 void raw_ostream::handle() {}
50
51 raw_ostream &raw_ostream::operator<<(unsigned long N) {
52   // Zero is a special case.
53   if (N == 0)
54     return *this << '0';
55   
56   char NumberBuffer[20];
57   char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
58   char *CurPtr = EndPtr;
59   
60   while (N) {
61     *--CurPtr = '0' + char(N % 10);
62     N /= 10;
63   }
64   return write(CurPtr, EndPtr-CurPtr);
65 }
66
67 raw_ostream &raw_ostream::operator<<(long N) {
68   if (N <  0) {
69     *this << '-';
70     N = -N;
71   }
72   
73   return this->operator<<(static_cast<unsigned long>(N));
74 }
75
76 raw_ostream &raw_ostream::operator<<(unsigned long long N) {
77   // Zero is a special case.
78   if (N == 0)
79     return *this << '0';
80   
81   char NumberBuffer[20];
82   char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
83   char *CurPtr = EndPtr;
84   
85   while (N) {
86     *--CurPtr = '0' + char(N % 10);
87     N /= 10;
88   }
89   return write(CurPtr, EndPtr-CurPtr);
90 }
91
92 raw_ostream &raw_ostream::operator<<(long long N) {
93   if (N <  0) {
94     *this << '-';
95     N = -N;
96   }
97   
98   return this->operator<<(static_cast<unsigned long long>(N));
99 }
100
101 raw_ostream &raw_ostream::operator<<(const void *P) {
102   uintptr_t N = (uintptr_t) P;
103   *this << '0' << 'x';
104   
105   // Zero is a special case.
106   if (N == 0)
107     return *this << '0';
108
109   char NumberBuffer[20];
110   char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
111   char *CurPtr = EndPtr;
112
113   while (N) {
114     unsigned x = N % 16;
115     *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
116     N /= 16;
117   }
118
119   return write(CurPtr, EndPtr-CurPtr);
120 }
121
122 void raw_ostream::flush_nonempty() {
123   assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
124   write_impl(OutBufStart, OutBufCur - OutBufStart);
125   OutBufCur = OutBufStart;    
126 }
127
128 raw_ostream &raw_ostream::write(unsigned char C) {
129   // Group exceptional cases into a single branch.
130   if (OutBufCur >= OutBufEnd) {
131     if (Unbuffered) {
132       write_impl(reinterpret_cast<char*>(&C), 1);
133       return *this;
134     }
135     
136     if (!OutBufStart)
137       SetBufferSize();
138     else
139       flush_nonempty();
140   }
141
142   *OutBufCur++ = C;
143   return *this;
144 }
145
146 raw_ostream &raw_ostream::write(const char *Ptr, unsigned Size) {
147   // Group exceptional cases into a single branch.
148   if (BUILTIN_EXPECT(OutBufCur+Size > OutBufEnd, false)) {
149     if (Unbuffered) {
150       write_impl(Ptr, Size);
151       return *this;
152     }
153     
154     if (!OutBufStart)
155       SetBufferSize();
156     else
157       flush_nonempty();
158   }
159   
160   // Handle short strings specially, memcpy isn't very good at very short
161   // strings.
162   switch (Size) {
163   case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
164   case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
165   case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
166   case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
167   case 0: break;
168   default:
169     // Normally the string to emit is shorter than the buffer.
170     if (Size <= unsigned(OutBufEnd-OutBufCur)) {
171       memcpy(OutBufCur, Ptr, Size);
172       break;
173     } 
174
175     // Otherwise we are emitting a string larger than our buffer. We
176     // know we already flushed, so just write it out directly.
177     write_impl(Ptr, Size);
178     Size = 0;
179     break;
180   }
181   OutBufCur += Size;
182
183   return *this;
184 }
185
186 // Formatted output.
187 raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
188   // If we have more than a few bytes left in our output buffer, try
189   // formatting directly onto its end.
190   //
191   // FIXME: This test is a bit silly, since if we don't have enough
192   // space in the buffer we will have to flush the formatted output
193   // anyway. We should just flush upfront in such cases, and use the
194   // whole buffer as our scratch pad. Note, however, that this case is
195   // also necessary for correctness on unbuffered streams.
196   unsigned NextBufferSize = 127;
197   if (OutBufEnd-OutBufCur > 3) {
198     unsigned BufferBytesLeft = OutBufEnd-OutBufCur;
199     unsigned BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
200     
201     // Common case is that we have plenty of space.
202     if (BytesUsed < BufferBytesLeft) {
203       OutBufCur += BytesUsed;
204       return *this;
205     }
206     
207     // Otherwise, we overflowed and the return value tells us the size to try
208     // again with.
209     NextBufferSize = BytesUsed;
210   }
211   
212   // If we got here, we didn't have enough space in the output buffer for the
213   // string.  Try printing into a SmallVector that is resized to have enough
214   // space.  Iterate until we win.
215   SmallVector<char, 128> V;
216   
217   while (1) {
218     V.resize(NextBufferSize);
219     
220     // Try formatting into the SmallVector.
221     unsigned BytesUsed = Fmt.print(&V[0], NextBufferSize);
222     
223     // If BytesUsed fit into the vector, we win.
224     if (BytesUsed <= NextBufferSize)
225       return write(&V[0], BytesUsed);
226     
227     // Otherwise, try again with a new size.
228     assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
229     NextBufferSize = BytesUsed;
230   }
231 }
232
233 //===----------------------------------------------------------------------===//
234 //  Formatted Output
235 //===----------------------------------------------------------------------===//
236
237 // Out of line virtual method.
238 void format_object_base::home() {
239 }
240
241 //===----------------------------------------------------------------------===//
242 //  raw_fd_ostream
243 //===----------------------------------------------------------------------===//
244
245 /// raw_fd_ostream - Open the specified file for writing. If an error
246 /// occurs, information about the error is put into ErrorInfo, and the
247 /// stream should be immediately destroyed; the string will be empty
248 /// if no error occurred.
249 raw_fd_ostream::raw_fd_ostream(const char *Filename, bool Binary,
250                                std::string &ErrorInfo) : pos(0) {
251   ErrorInfo.clear();
252
253   // Handle "-" as stdout.
254   if (Filename[0] == '-' && Filename[1] == 0) {
255     FD = STDOUT_FILENO;
256     // If user requested binary then put stdout into binary mode if
257     // possible.
258     if (Binary)
259       sys::Program::ChangeStdoutToBinary();
260     ShouldClose = false;
261     return;
262   }
263   
264   int Flags = O_WRONLY|O_CREAT|O_TRUNC;
265 #ifdef O_BINARY
266   if (Binary)
267     Flags |= O_BINARY;
268 #endif
269   FD = open(Filename, Flags, 0664);
270   if (FD < 0) {
271     ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
272     ShouldClose = false;
273   } else {
274     ShouldClose = true;
275   }
276 }
277
278 raw_fd_ostream::~raw_fd_ostream() {
279   if (FD >= 0) {
280     flush();
281     if (ShouldClose)
282       ::close(FD);
283   }
284 }
285
286 void raw_fd_ostream::write_impl(const char *Ptr, unsigned Size) {
287   assert (FD >= 0 && "File already closed.");
288   pos += Size;
289   if (::write(FD, Ptr, Size) != (ssize_t) Size)
290     llvm_report_error("IO failure writing to output stream.");
291 }
292
293 void raw_fd_ostream::close() {
294   assert (ShouldClose);
295   ShouldClose = false;
296   flush();
297   ::close(FD);
298   FD = -1;
299 }
300
301 uint64_t raw_fd_ostream::seek(uint64_t off) {
302   flush();
303   pos = ::lseek(FD, off, SEEK_SET);
304   return pos;  
305 }
306
307 raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
308                                          bool bg) {
309   if (sys::Process::ColorNeedsFlush())
310     flush();
311   const char *colorcode =
312     (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
313     : sys::Process::OutputColor(colors, bold, bg);
314   if (colorcode) {
315     unsigned len = strlen(colorcode);
316     write(colorcode, len);
317     // don't account colors towards output characters
318     pos -= len;
319   }
320   return *this;
321 }
322
323 raw_ostream &raw_fd_ostream::resetColor() {
324   if (sys::Process::ColorNeedsFlush())
325     flush();
326   const char *colorcode = sys::Process::ResetColor();
327   if (colorcode) {
328     unsigned len = strlen(colorcode);
329     write(colorcode, len);
330     // don't account colors towards output characters
331     pos -= len;
332   }
333   return *this;
334 }
335
336 //===----------------------------------------------------------------------===//
337 //  raw_stdout/err_ostream
338 //===----------------------------------------------------------------------===//
339
340 raw_stdout_ostream::raw_stdout_ostream():raw_fd_ostream(STDOUT_FILENO, false) {}
341 raw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO, false, 
342                                                         true) {}
343
344 // An out of line virtual method to provide a home for the class vtable.
345 void raw_stdout_ostream::handle() {}
346 void raw_stderr_ostream::handle() {}
347
348 /// outs() - This returns a reference to a raw_ostream for standard output.
349 /// Use it like: outs() << "foo" << "bar";
350 raw_ostream &llvm::outs() {
351   static raw_stdout_ostream S;
352   return S;
353 }
354
355 /// errs() - This returns a reference to a raw_ostream for standard error.
356 /// Use it like: errs() << "foo" << "bar";
357 raw_ostream &llvm::errs() {
358   static raw_stderr_ostream S;
359   return S;
360 }
361
362 //===----------------------------------------------------------------------===//
363 //  raw_os_ostream
364 //===----------------------------------------------------------------------===//
365
366 raw_os_ostream::~raw_os_ostream() {
367   flush();
368 }
369
370 void raw_os_ostream::write_impl(const char *Ptr, unsigned Size) {
371   OS.write(Ptr, Size);
372 }
373
374 uint64_t raw_os_ostream::current_pos() { return OS.tellp(); }
375
376 uint64_t raw_os_ostream::tell() { 
377   return (uint64_t)OS.tellp() + GetNumBytesInBuffer(); 
378 }
379
380 //===----------------------------------------------------------------------===//
381 //  raw_string_ostream
382 //===----------------------------------------------------------------------===//
383
384 raw_string_ostream::~raw_string_ostream() {
385   flush();
386 }
387
388 void raw_string_ostream::write_impl(const char *Ptr, unsigned Size) {
389   OS.append(Ptr, Size);
390 }
391
392 //===----------------------------------------------------------------------===//
393 //  raw_svector_ostream
394 //===----------------------------------------------------------------------===//
395
396 raw_svector_ostream::~raw_svector_ostream() {
397   flush();
398 }
399
400 void raw_svector_ostream::write_impl(const char *Ptr, unsigned Size) {
401   OS.append(Ptr, Ptr + Size);
402 }
403
404 uint64_t raw_svector_ostream::current_pos() { return OS.size(); }
405
406 uint64_t raw_svector_ostream::tell() { 
407   return OS.size() + GetNumBytesInBuffer(); 
408 }