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