blob: d2d0f4ef2a2bbbe0c3152ae0b8c54703ba46f694 [file] [log] [blame]
Chris Lattner60d39622008-08-17 01:35:29 +00001//===--- 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"
Chris Lattner42f77ab2008-08-23 20:34:06 +000015#include "llvm/Support/Format.h"
Daniel Dunbar0d9eb9b2008-11-13 05:01:07 +000016#include "llvm/System/Program.h"
Torok Edwine8ebb0f2009-06-04 07:09:50 +000017#include "llvm/System/Process.h"
Chris Lattner097af7f2008-08-23 19:23:10 +000018#include "llvm/ADT/SmallVector.h"
Chris Lattner969a46a2008-08-22 15:45:00 +000019#include "llvm/Config/config.h"
Daniel Dunbarb372c112009-03-17 21:15:18 +000020#include "llvm/Support/Compiler.h"
Daniel Dunbar579fb872009-07-15 08:11:46 +000021#include "llvm/Support/ErrorHandling.h"
Chris Lattner07f51f72008-08-17 04:13:37 +000022#include <ostream>
Chris Lattner60d39622008-08-17 01:35:29 +000023
Chris Lattner969a46a2008-08-22 15:45:00 +000024#if defined(HAVE_UNISTD_H)
25# include <unistd.h>
26#endif
27#if defined(HAVE_FCNTL_H)
28# include <fcntl.h>
29#endif
Argyrios Kyrtzidisb68dc362008-08-17 09:25:21 +000030
31#if defined(_MSC_VER)
Chris Lattner60d39622008-08-17 01:35:29 +000032#include <io.h>
Cedric Veneta3f343f2008-08-24 11:56:40 +000033#include <fcntl.h>
Owen Andersoncb371882008-08-21 00:14:44 +000034#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
Chris Lattner60d39622008-08-17 01:35:29 +000043#endif
44
Chris Lattner969a46a2008-08-22 15:45:00 +000045using namespace llvm;
46
Dan Gohmane87b2ab2009-07-15 23:25:33 +000047raw_ostream::~raw_ostream() {
Dan Gohman9a312542009-07-27 20:49:44 +000048 // raw_ostream's subclasses should take care to flush the buffer
49 // in their destructors.
50 assert(OutBufCur == OutBufStart &&
51 "raw_ostream destructor called with non-empty buffer!");
52
Dan Gohmane87b2ab2009-07-15 23:25:33 +000053 delete [] OutBufStart;
54
55 // If there are any pending errors, report them now. Clients wishing
56 // to avoid llvm_report_error calls should check for errors with
57 // has_error() and clear the error flag with clear_error() before
58 // destructing raw_ostream objects which may have errors.
59 if (Error)
60 llvm_report_error("IO failure on output stream.");
61}
Chris Lattner969a46a2008-08-22 15:45:00 +000062
Chris Lattner60d39622008-08-17 01:35:29 +000063// An out of line virtual method to provide a home for the class vtable.
64void raw_ostream::handle() {}
65
Owen Anderson66b17ba2008-08-21 20:58:52 +000066raw_ostream &raw_ostream::operator<<(unsigned long N) {
67 // Zero is a special case.
68 if (N == 0)
69 return *this << '0';
70
71 char NumberBuffer[20];
72 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
73 char *CurPtr = EndPtr;
74
75 while (N) {
76 *--CurPtr = '0' + char(N % 10);
77 N /= 10;
78 }
79 return write(CurPtr, EndPtr-CurPtr);
80}
81
82raw_ostream &raw_ostream::operator<<(long N) {
83 if (N < 0) {
Daniel Dunbarde75d7f2009-03-16 22:00:17 +000084 *this << '-';
Owen Anderson66b17ba2008-08-21 20:58:52 +000085 N = -N;
86 }
87
88 return this->operator<<(static_cast<unsigned long>(N));
89}
90
91raw_ostream &raw_ostream::operator<<(unsigned long long N) {
Daniel Dunbar78a3dd82009-07-29 06:45:14 +000092 // Output using 32-bit div/mod when possible.
93 if (N == static_cast<unsigned long>(N))
94 return this->operator<<(static_cast<unsigned long>(N));
95
Owen Anderson66b17ba2008-08-21 20:58:52 +000096 // Zero is a special case.
97 if (N == 0)
98 return *this << '0';
99
100 char NumberBuffer[20];
101 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
102 char *CurPtr = EndPtr;
103
104 while (N) {
105 *--CurPtr = '0' + char(N % 10);
106 N /= 10;
107 }
108 return write(CurPtr, EndPtr-CurPtr);
109}
110
111raw_ostream &raw_ostream::operator<<(long long N) {
112 if (N < 0) {
Daniel Dunbarde75d7f2009-03-16 22:00:17 +0000113 *this << '-';
Owen Anderson66b17ba2008-08-21 20:58:52 +0000114 N = -N;
115 }
116
117 return this->operator<<(static_cast<unsigned long long>(N));
118}
119
Chris Lattner944fac72008-08-23 22:23:09 +0000120raw_ostream &raw_ostream::operator<<(const void *P) {
Daniel Dunbarb451a0c2009-03-16 22:08:44 +0000121 uintptr_t N = (uintptr_t) P;
122 *this << '0' << 'x';
123
124 // Zero is a special case.
125 if (N == 0)
126 return *this << '0';
127
128 char NumberBuffer[20];
129 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
130 char *CurPtr = EndPtr;
131
132 while (N) {
Dan Gohmanad60f662009-07-16 15:24:40 +0000133 uintptr_t x = N % 16;
Daniel Dunbarb451a0c2009-03-16 22:08:44 +0000134 *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
135 N /= 16;
136 }
137
138 return write(CurPtr, EndPtr-CurPtr);
Chris Lattner944fac72008-08-23 22:23:09 +0000139}
140
Daniel Dunbarcf2a2c62009-03-16 22:55:06 +0000141void raw_ostream::flush_nonempty() {
142 assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
Daniel Dunbar89a66a92009-03-16 23:29:31 +0000143 write_impl(OutBufStart, OutBufCur - OutBufStart);
Daniel Dunbarcf2a2c62009-03-16 22:55:06 +0000144 OutBufCur = OutBufStart;
145}
146
Daniel Dunbarde75d7f2009-03-16 22:00:17 +0000147raw_ostream &raw_ostream::write(unsigned char C) {
Daniel Dunbar262541b2009-03-17 01:36:56 +0000148 // Group exceptional cases into a single branch.
149 if (OutBufCur >= OutBufEnd) {
150 if (Unbuffered) {
151 write_impl(reinterpret_cast<char*>(&C), 1);
152 return *this;
153 }
154
155 if (!OutBufStart)
156 SetBufferSize();
157 else
158 flush_nonempty();
Daniel Dunbard17d74b2009-03-17 01:13:35 +0000159 }
160
Daniel Dunbarde75d7f2009-03-16 22:00:17 +0000161 *OutBufCur++ = C;
Daniel Dunbarb451a0c2009-03-16 22:08:44 +0000162 return *this;
Daniel Dunbarde75d7f2009-03-16 22:00:17 +0000163}
Chris Lattner944fac72008-08-23 22:23:09 +0000164
Dan Gohmanad60f662009-07-16 15:24:40 +0000165raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
Daniel Dunbar262541b2009-03-17 01:36:56 +0000166 // Group exceptional cases into a single branch.
Daniel Dunbarb372c112009-03-17 21:15:18 +0000167 if (BUILTIN_EXPECT(OutBufCur+Size > OutBufEnd, false)) {
Daniel Dunbar262541b2009-03-17 01:36:56 +0000168 if (Unbuffered) {
169 write_impl(Ptr, Size);
170 return *this;
171 }
Daniel Dunbard17d74b2009-03-17 01:13:35 +0000172
Daniel Dunbar262541b2009-03-17 01:36:56 +0000173 if (!OutBufStart)
174 SetBufferSize();
175 else
176 flush_nonempty();
177 }
Owen Anderson66b17ba2008-08-21 20:58:52 +0000178
179 // Handle short strings specially, memcpy isn't very good at very short
180 // strings.
181 switch (Size) {
182 case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
183 case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
184 case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
185 case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
186 case 0: break;
187 default:
188 // Normally the string to emit is shorter than the buffer.
David Greene71847812009-07-14 20:18:05 +0000189 if (Size <= unsigned(OutBufEnd-OutBufCur)) {
Owen Anderson66b17ba2008-08-21 20:58:52 +0000190 memcpy(OutBufCur, Ptr, Size);
191 break;
Daniel Dunbar89a66a92009-03-16 23:29:31 +0000192 }
Owen Anderson66b17ba2008-08-21 20:58:52 +0000193
Daniel Dunbar89a66a92009-03-16 23:29:31 +0000194 // Otherwise we are emitting a string larger than our buffer. We
195 // know we already flushed, so just write it out directly.
196 write_impl(Ptr, Size);
197 Size = 0;
Owen Anderson66b17ba2008-08-21 20:58:52 +0000198 break;
199 }
200 OutBufCur += Size;
Daniel Dunbare77e4342009-03-10 16:21:55 +0000201
Owen Anderson66b17ba2008-08-21 20:58:52 +0000202 return *this;
203}
204
Chris Lattner097af7f2008-08-23 19:23:10 +0000205// Formatted output.
206raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
Daniel Dunbar262541b2009-03-17 01:36:56 +0000207 // If we have more than a few bytes left in our output buffer, try
208 // formatting directly onto its end.
209 //
210 // FIXME: This test is a bit silly, since if we don't have enough
211 // space in the buffer we will have to flush the formatted output
212 // anyway. We should just flush upfront in such cases, and use the
213 // whole buffer as our scratch pad. Note, however, that this case is
214 // also necessary for correctness on unbuffered streams.
Dan Gohmanad60f662009-07-16 15:24:40 +0000215 size_t NextBufferSize = 127;
Chris Lattner097af7f2008-08-23 19:23:10 +0000216 if (OutBufEnd-OutBufCur > 3) {
Dan Gohmanad60f662009-07-16 15:24:40 +0000217 size_t BufferBytesLeft = OutBufEnd-OutBufCur;
218 size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
Chris Lattner097af7f2008-08-23 19:23:10 +0000219
220 // Common case is that we have plenty of space.
221 if (BytesUsed < BufferBytesLeft) {
222 OutBufCur += BytesUsed;
223 return *this;
224 }
225
226 // Otherwise, we overflowed and the return value tells us the size to try
227 // again with.
228 NextBufferSize = BytesUsed;
229 }
230
231 // If we got here, we didn't have enough space in the output buffer for the
232 // string. Try printing into a SmallVector that is resized to have enough
233 // space. Iterate until we win.
234 SmallVector<char, 128> V;
235
236 while (1) {
237 V.resize(NextBufferSize);
238
239 // Try formatting into the SmallVector.
Dan Gohmanad60f662009-07-16 15:24:40 +0000240 size_t BytesUsed = Fmt.print(&V[0], NextBufferSize);
Chris Lattner097af7f2008-08-23 19:23:10 +0000241
242 // If BytesUsed fit into the vector, we win.
Chris Lattnerf61ca1e2008-10-26 19:20:47 +0000243 if (BytesUsed <= NextBufferSize)
Chris Lattner097af7f2008-08-23 19:23:10 +0000244 return write(&V[0], BytesUsed);
245
246 // Otherwise, try again with a new size.
247 assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
248 NextBufferSize = BytesUsed;
249 }
250}
251
252//===----------------------------------------------------------------------===//
253// Formatted Output
254//===----------------------------------------------------------------------===//
255
256// Out of line virtual method.
257void format_object_base::home() {
258}
259
Chris Lattner60d39622008-08-17 01:35:29 +0000260//===----------------------------------------------------------------------===//
261// raw_fd_ostream
262//===----------------------------------------------------------------------===//
263
Daniel Dunbar48534b32008-10-21 19:53:10 +0000264/// raw_fd_ostream - Open the specified file for writing. If an error
265/// occurs, information about the error is put into ErrorInfo, and the
266/// stream should be immediately destroyed; the string will be empty
267/// if no error occurred.
Dan Gohmana1bdced2009-07-15 17:29:42 +0000268raw_fd_ostream::raw_fd_ostream(const char *Filename, bool Binary, bool Force,
Ted Kremenekd75ba1c2008-12-04 22:51:11 +0000269 std::string &ErrorInfo) : pos(0) {
Daniel Dunbar48534b32008-10-21 19:53:10 +0000270 ErrorInfo.clear();
271
Chris Lattnerc52b1282008-08-17 03:53:23 +0000272 // Handle "-" as stdout.
273 if (Filename[0] == '-' && Filename[1] == 0) {
274 FD = STDOUT_FILENO;
Daniel Dunbar0d9eb9b2008-11-13 05:01:07 +0000275 // If user requested binary then put stdout into binary mode if
276 // possible.
277 if (Binary)
278 sys::Program::ChangeStdoutToBinary();
Chris Lattnerc52b1282008-08-17 03:53:23 +0000279 ShouldClose = false;
280 return;
281 }
282
Daniel Dunbar0d9eb9b2008-11-13 05:01:07 +0000283 int Flags = O_WRONLY|O_CREAT|O_TRUNC;
284#ifdef O_BINARY
285 if (Binary)
286 Flags |= O_BINARY;
287#endif
Dan Gohmana1bdced2009-07-15 17:29:42 +0000288 if (!Force)
289 Flags |= O_EXCL;
Dan Gohman9f79d3e2009-07-15 16:39:40 +0000290 FD = open(Filename, Flags, 0664);
Chris Lattner60d39622008-08-17 01:35:29 +0000291 if (FD < 0) {
292 ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
293 ShouldClose = false;
294 } else {
295 ShouldClose = true;
296 }
297}
298
299raw_fd_ostream::~raw_fd_ostream() {
Ted Kremenek43d1f022008-10-23 23:49:09 +0000300 if (FD >= 0) {
301 flush();
302 if (ShouldClose)
Dan Gohmand3a974f2009-07-15 16:43:01 +0000303 if (::close(FD) != 0)
Dan Gohmane87b2ab2009-07-15 23:25:33 +0000304 error_detected();
Ted Kremenek43d1f022008-10-23 23:49:09 +0000305 }
Chris Lattner60d39622008-08-17 01:35:29 +0000306}
307
Dan Gohmanad60f662009-07-16 15:24:40 +0000308void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
Ted Kremenek43d1f022008-10-23 23:49:09 +0000309 assert (FD >= 0 && "File already closed.");
Daniel Dunbar89a66a92009-03-16 23:29:31 +0000310 pos += Size;
Daniel Dunbar579fb872009-07-15 08:11:46 +0000311 if (::write(FD, Ptr, Size) != (ssize_t) Size)
Dan Gohmane87b2ab2009-07-15 23:25:33 +0000312 error_detected();
Chris Lattner60d39622008-08-17 01:35:29 +0000313}
314
Ted Kremenek43d1f022008-10-23 23:49:09 +0000315void raw_fd_ostream::close() {
316 assert (ShouldClose);
317 ShouldClose = false;
318 flush();
Dan Gohmand3a974f2009-07-15 16:43:01 +0000319 if (::close(FD) != 0)
Dan Gohmane87b2ab2009-07-15 23:25:33 +0000320 error_detected();
Ted Kremenek43d1f022008-10-23 23:49:09 +0000321 FD = -1;
322}
323
Ted Kremenek9c278862009-01-26 21:42:04 +0000324uint64_t raw_fd_ostream::seek(uint64_t off) {
325 flush();
Daniel Dunbar579fb872009-07-15 08:11:46 +0000326 pos = ::lseek(FD, off, SEEK_SET);
Dan Gohmand3a974f2009-07-15 16:43:01 +0000327 if (pos != off)
Dan Gohmane87b2ab2009-07-15 23:25:33 +0000328 error_detected();
Ted Kremenek9c278862009-01-26 21:42:04 +0000329 return pos;
330}
331
Torok Edwine8ebb0f2009-06-04 07:09:50 +0000332raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
333 bool bg) {
334 if (sys::Process::ColorNeedsFlush())
335 flush();
336 const char *colorcode =
337 (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
338 : sys::Process::OutputColor(colors, bold, bg);
339 if (colorcode) {
Dan Gohmanad60f662009-07-16 15:24:40 +0000340 size_t len = strlen(colorcode);
Torok Edwine8ebb0f2009-06-04 07:09:50 +0000341 write(colorcode, len);
342 // don't account colors towards output characters
343 pos -= len;
344 }
345 return *this;
346}
347
348raw_ostream &raw_fd_ostream::resetColor() {
349 if (sys::Process::ColorNeedsFlush())
350 flush();
351 const char *colorcode = sys::Process::ResetColor();
352 if (colorcode) {
Dan Gohmanad60f662009-07-16 15:24:40 +0000353 size_t len = strlen(colorcode);
Torok Edwine8ebb0f2009-06-04 07:09:50 +0000354 write(colorcode, len);
355 // don't account colors towards output characters
356 pos -= len;
357 }
358 return *this;
359}
360
Chris Lattner07f51f72008-08-17 04:13:37 +0000361//===----------------------------------------------------------------------===//
362// raw_stdout/err_ostream
363//===----------------------------------------------------------------------===//
Chris Lattner60d39622008-08-17 01:35:29 +0000364
365raw_stdout_ostream::raw_stdout_ostream():raw_fd_ostream(STDOUT_FILENO, false) {}
Daniel Dunbare77e4342009-03-10 16:21:55 +0000366raw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO, false,
367 true) {}
Chris Lattner60d39622008-08-17 01:35:29 +0000368
369// An out of line virtual method to provide a home for the class vtable.
370void raw_stdout_ostream::handle() {}
371void raw_stderr_ostream::handle() {}
Chris Lattner07f51f72008-08-17 04:13:37 +0000372
373/// outs() - This returns a reference to a raw_ostream for standard output.
374/// Use it like: outs() << "foo" << "bar";
Owen Andersoncb371882008-08-21 00:14:44 +0000375raw_ostream &llvm::outs() {
Chris Lattner07f51f72008-08-17 04:13:37 +0000376 static raw_stdout_ostream S;
377 return S;
378}
379
380/// errs() - This returns a reference to a raw_ostream for standard error.
381/// Use it like: errs() << "foo" << "bar";
Owen Andersoncb371882008-08-21 00:14:44 +0000382raw_ostream &llvm::errs() {
Chris Lattner07f51f72008-08-17 04:13:37 +0000383 static raw_stderr_ostream S;
384 return S;
385}
386
Daniel Dunbar34ccf032009-07-16 21:17:53 +0000387/// nulls() - This returns a reference to a raw_ostream which discards output.
388raw_ostream &llvm::nulls() {
389 static raw_null_ostream S;
390 return S;
391}
392
Chris Lattner07f51f72008-08-17 04:13:37 +0000393//===----------------------------------------------------------------------===//
394// raw_os_ostream
395//===----------------------------------------------------------------------===//
396
Chris Lattner944fac72008-08-23 22:23:09 +0000397raw_os_ostream::~raw_os_ostream() {
398 flush();
399}
400
Dan Gohmanad60f662009-07-16 15:24:40 +0000401void raw_os_ostream::write_impl(const char *Ptr, size_t Size) {
Daniel Dunbar89a66a92009-03-16 23:29:31 +0000402 OS.write(Ptr, Size);
Chris Lattner07f51f72008-08-17 04:13:37 +0000403}
Chris Lattner78a28122008-08-23 22:43:04 +0000404
Douglas Gregor8f7be472009-04-20 07:34:17 +0000405uint64_t raw_os_ostream::current_pos() { return OS.tellp(); }
406
407uint64_t raw_os_ostream::tell() {
408 return (uint64_t)OS.tellp() + GetNumBytesInBuffer();
409}
410
Chris Lattner78a28122008-08-23 22:43:04 +0000411//===----------------------------------------------------------------------===//
412// raw_string_ostream
413//===----------------------------------------------------------------------===//
414
415raw_string_ostream::~raw_string_ostream() {
416 flush();
417}
418
Dan Gohmanad60f662009-07-16 15:24:40 +0000419void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
Daniel Dunbar89a66a92009-03-16 23:29:31 +0000420 OS.append(Ptr, Size);
Chris Lattner78a28122008-08-23 22:43:04 +0000421}
422
423//===----------------------------------------------------------------------===//
424// raw_svector_ostream
425//===----------------------------------------------------------------------===//
426
427raw_svector_ostream::~raw_svector_ostream() {
428 flush();
429}
430
Dan Gohmanad60f662009-07-16 15:24:40 +0000431void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
Daniel Dunbar89a66a92009-03-16 23:29:31 +0000432 OS.append(Ptr, Ptr + Size);
Chris Lattner78a28122008-08-23 22:43:04 +0000433}
434
Douglas Gregor8f7be472009-04-20 07:34:17 +0000435uint64_t raw_svector_ostream::current_pos() { return OS.size(); }
436
437uint64_t raw_svector_ostream::tell() {
438 return OS.size() + GetNumBytesInBuffer();
439}
Daniel Dunbar34ccf032009-07-16 21:17:53 +0000440
441//===----------------------------------------------------------------------===//
442// raw_null_ostream
443//===----------------------------------------------------------------------===//
444
Dan Gohmanf78c8352009-07-27 21:46:02 +0000445raw_null_ostream::~raw_null_ostream() {
446#ifndef NDEBUG
447 // ~raw_ostream asserts that the buffer is empty. This isn't necessary
448 // with raw_null_ostream, but it's better to have raw_null_ostream follow
449 // the rules than to change the rules just for raw_null_ostream.
450 flush();
451#endif
452}
453
Daniel Dunbar34ccf032009-07-16 21:17:53 +0000454void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
455}
456
457uint64_t raw_null_ostream::current_pos() {
458 return 0;
459}