LCOV - code coverage report
Current view: top level - lib/Support - raw_ostream.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 311 341 91.2 %
Date: 2018-06-17 00:07:59 Functions: 54 64 84.4 %
Legend: Lines: hit not hit

          Line data    Source code
       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/ADT/STLExtras.h"
      16             : #include "llvm/ADT/SmallVector.h"
      17             : #include "llvm/ADT/StringExtras.h"
      18             : #include "llvm/Config/config.h"
      19             : #include "llvm/Support/Compiler.h"
      20             : #include "llvm/Support/ErrorHandling.h"
      21             : #include "llvm/Support/FileSystem.h"
      22             : #include "llvm/Support/Format.h"
      23             : #include "llvm/Support/FormatVariadic.h"
      24             : #include "llvm/Support/MathExtras.h"
      25             : #include "llvm/Support/NativeFormatting.h"
      26             : #include "llvm/Support/Process.h"
      27             : #include "llvm/Support/Program.h"
      28             : #include <algorithm>
      29             : #include <cctype>
      30             : #include <cerrno>
      31             : #include <cstdio>
      32             : #include <iterator>
      33             : #include <sys/stat.h>
      34             : #include <system_error>
      35             : 
      36             : // <fcntl.h> may provide O_BINARY.
      37             : #if defined(HAVE_FCNTL_H)
      38             : # include <fcntl.h>
      39             : #endif
      40             : 
      41             : #if defined(HAVE_UNISTD_H)
      42             : # include <unistd.h>
      43             : #endif
      44             : 
      45             : #if defined(__CYGWIN__)
      46             : #include <io.h>
      47             : #endif
      48             : 
      49             : #if defined(_MSC_VER)
      50             : #include <io.h>
      51             : #ifndef STDIN_FILENO
      52             : # define STDIN_FILENO 0
      53             : #endif
      54             : #ifndef STDOUT_FILENO
      55             : # define STDOUT_FILENO 1
      56             : #endif
      57             : #ifndef STDERR_FILENO
      58             : # define STDERR_FILENO 2
      59             : #endif
      60             : #endif
      61             : 
      62             : #ifdef _WIN32
      63             : #include "Windows/WindowsSupport.h"
      64             : #endif
      65             : 
      66             : using namespace llvm;
      67             : 
      68    98246872 : raw_ostream::~raw_ostream() {
      69             :   // raw_ostream's subclasses should take care to flush the buffer
      70             :   // in their destructors.
      71             :   assert(OutBufCur == OutBufStart &&
      72             :          "raw_ostream destructor called with non-empty buffer!");
      73             : 
      74    49123436 :   if (BufferMode == InternalBuffer)
      75     6285955 :     delete [] OutBufStart;
      76    49123436 : }
      77             : 
      78     5999329 : size_t raw_ostream::preferred_buffer_size() const {
      79             :   // BUFSIZ is intended to be a reasonable default.
      80     5999329 :   return BUFSIZ;
      81             : }
      82             : 
      83     6032923 : void raw_ostream::SetBuffered() {
      84             :   // Ask the subclass to determine an appropriate buffer size.
      85     6032923 :   if (size_t Size = preferred_buffer_size())
      86     6032923 :     SetBufferSize(Size);
      87             :   else
      88             :     // It may return 0, meaning this stream should be unbuffered.
      89           0 :     SetUnbuffered();
      90     6032923 : }
      91             : 
      92    48947928 : void raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size,
      93             :                                    BufferKind Mode) {
      94             :   assert(((Mode == Unbuffered && !BufferStart && Size == 0) ||
      95             :           (Mode != Unbuffered && BufferStart && Size != 0)) &&
      96             :          "stream must be unbuffered or have at least one byte");
      97             :   // Make sure the current buffer is free of content (we can't flush here; the
      98             :   // child buffer management logic will be in write_impl).
      99             :   assert(GetNumBytesInBuffer() == 0 && "Current buffer is non-empty!");
     100             : 
     101    48947928 :   if (BufferMode == InternalBuffer)
     102    48864655 :     delete [] OutBufStart;
     103    48947928 :   OutBufStart = BufferStart;
     104    48947928 :   OutBufEnd = OutBufStart+Size;
     105    48947928 :   OutBufCur = OutBufStart;
     106    48947928 :   BufferMode = Mode;
     107             : 
     108             :   assert(OutBufStart <= OutBufEnd && "Invalid size!");
     109    48947928 : }
     110             : 
     111    37657280 : raw_ostream &raw_ostream::operator<<(unsigned long N) {
     112    37657280 :   write_integer(*this, static_cast<uint64_t>(N), 0, IntegerStyle::Integer);
     113    37657281 :   return *this;
     114             : }
     115             : 
     116     8768683 : raw_ostream &raw_ostream::operator<<(long N) {
     117     8768683 :   write_integer(*this, static_cast<int64_t>(N), 0, IntegerStyle::Integer);
     118     8768680 :   return *this;
     119             : }
     120             : 
     121           5 : raw_ostream &raw_ostream::operator<<(unsigned long long N) {
     122           5 :   write_integer(*this, static_cast<uint64_t>(N), 0, IntegerStyle::Integer);
     123           5 :   return *this;
     124             : }
     125             : 
     126       20419 : raw_ostream &raw_ostream::operator<<(long long N) {
     127       20419 :   write_integer(*this, static_cast<int64_t>(N), 0, IntegerStyle::Integer);
     128       20419 :   return *this;
     129             : }
     130             : 
     131      406430 : raw_ostream &raw_ostream::write_hex(unsigned long long N) {
     132      406430 :   llvm::write_hex(*this, N, HexPrintStyle::Lower);
     133      406430 :   return *this;
     134             : }
     135             : 
     136          38 : raw_ostream &raw_ostream::write_uuid(const uuid_t UUID) {
     137        1254 :   for (int Idx = 0; Idx < 16; ++Idx) {
     138        1216 :     *this << format("%02" PRIX32, UUID[Idx]);
     139         608 :     if (Idx == 3 || Idx == 5 || Idx == 7 || Idx == 9)
     140         152 :       *this << "-";
     141             :   }
     142          38 :   return *this;
     143             : }
     144             : 
     145             : 
     146      157191 : raw_ostream &raw_ostream::write_escaped(StringRef Str,
     147             :                                         bool UseHexEscapes) {
     148     2389123 :   for (unsigned char c : Str) {
     149     1115966 :     switch (c) {
     150             :     case '\\':
     151             :       *this << '\\' << '\\';
     152             :       break;
     153             :     case '\t':
     154             :       *this << '\\' << 't';
     155             :       break;
     156             :     case '\n':
     157             :       *this << '\\' << 'n';
     158             :       break;
     159             :     case '"':
     160             :       *this << '\\' << '"';
     161             :       break;
     162     1114778 :     default:
     163     1114778 :       if (std::isprint(c)) {
     164             :         *this << c;
     165             :         break;
     166             :       }
     167             : 
     168             :       // Write out the escaped representation.
     169       16138 :       if (UseHexEscapes) {
     170             :         *this << '\\' << 'x';
     171         164 :         *this << hexdigit((c >> 4 & 0xF));
     172         164 :         *this << hexdigit((c >> 0) & 0xF);
     173             :       } else {
     174             :         // Always use a full 3-character octal escape.
     175             :         *this << '\\';
     176       15974 :         *this << char('0' + ((c >> 6) & 7));
     177       15974 :         *this << char('0' + ((c >> 3) & 7));
     178       15974 :         *this << char('0' + ((c >> 0) & 7));
     179             :       }
     180             :     }
     181             :   }
     182             : 
     183      157191 :   return *this;
     184             : }
     185             : 
     186       16201 : raw_ostream &raw_ostream::operator<<(const void *P) {
     187       16201 :   llvm::write_hex(*this, (uintptr_t)P, HexPrintStyle::PrefixLower);
     188       16201 :   return *this;
     189             : }
     190             : 
     191       30282 : raw_ostream &raw_ostream::operator<<(double N) {
     192       30282 :   llvm::write_double(*this, N, FloatStyle::Exponent);
     193       30282 :   return *this;
     194             : }
     195             : 
     196     6789512 : void raw_ostream::flush_nonempty() {
     197             :   assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
     198     6789512 :   size_t Length = OutBufCur - OutBufStart;
     199     6789512 :   OutBufCur = OutBufStart;
     200     6789512 :   write_impl(OutBufStart, Length);
     201     6789512 : }
     202             : 
     203   128602568 : raw_ostream &raw_ostream::write(unsigned char C) {
     204             :   // Group exceptional cases into a single branch.
     205   128602568 :   if (LLVM_UNLIKELY(OutBufCur >= OutBufEnd)) {
     206   125839754 :     if (LLVM_UNLIKELY(!OutBufStart)) {
     207   125809005 :       if (BufferMode == Unbuffered) {
     208   123122797 :         write_impl(reinterpret_cast<char*>(&C), 1);
     209   123122797 :         return *this;
     210             :       }
     211             :       // Set up a buffer and start over.
     212     2686208 :       SetBuffered();
     213     2686208 :       return write(C);
     214             :     }
     215             : 
     216       30749 :     flush_nonempty();
     217             :   }
     218             : 
     219     2793563 :   *OutBufCur++ = C;
     220     2793563 :   return *this;
     221             : }
     222             : 
     223   391062080 : raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
     224             :   // Group exceptional cases into a single branch.
     225   395053404 :   if (LLVM_UNLIKELY(size_t(OutBufEnd - OutBufCur) < Size)) {
     226   299243536 :     if (LLVM_UNLIKELY(!OutBufStart)) {
     227   298591058 :       if (BufferMode == Unbuffered) {
     228   295244343 :         write_impl(Ptr, Size);
     229   295244778 :         return *this;
     230             :       }
     231             :       // Set up a buffer and start over.
     232     3346715 :       SetBuffered();
     233     3346715 :       return write(Ptr, Size);
     234             :     }
     235             : 
     236             :     size_t NumBytes = OutBufEnd - OutBufCur;
     237             : 
     238             :     // If the buffer is empty at this point we have a string that is larger
     239             :     // than the buffer. Directly write the chunk that is a multiple of the
     240             :     // preferred buffer size and put the remainder in the buffer.
     241      652478 :     if (LLVM_UNLIKELY(OutBufCur == OutBufStart)) {
     242             :       assert(NumBytes != 0 && "undefined behavior");
     243        7869 :       size_t BytesToWrite = Size - (Size % NumBytes);
     244        7869 :       write_impl(Ptr, BytesToWrite);
     245             :       size_t BytesRemaining = Size - BytesToWrite;
     246        7869 :       if (BytesRemaining > size_t(OutBufEnd - OutBufCur)) {
     247             :         // Too much left over to copy into our buffer.
     248           0 :         return write(Ptr + BytesToWrite, BytesRemaining);
     249             :       }
     250        7869 :       copy_to_buffer(Ptr + BytesToWrite, BytesRemaining);
     251        7869 :       return *this;
     252             :     }
     253             : 
     254             :     // We don't have enough space in the buffer to fit the string in. Insert as
     255             :     // much as possible, flush and start over with the remainder.
     256      644609 :     copy_to_buffer(Ptr, NumBytes);
     257      644609 :     flush_nonempty();
     258      644609 :     return write(Ptr + NumBytes, Size - NumBytes);
     259             :   }
     260             : 
     261    95809868 :   copy_to_buffer(Ptr, Size);
     262             : 
     263    95809867 :   return *this;
     264             : }
     265             : 
     266    96462344 : void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
     267             :   assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
     268             : 
     269             :   // Handle short strings specially, memcpy isn't very good at very short
     270             :   // strings.
     271    96462344 :   switch (Size) {
     272     9549481 :   case 4: OutBufCur[3] = Ptr[3]; LLVM_FALLTHROUGH;
     273    11518127 :   case 3: OutBufCur[2] = Ptr[2]; LLVM_FALLTHROUGH;
     274    52907901 :   case 2: OutBufCur[1] = Ptr[1]; LLVM_FALLTHROUGH;
     275    69651044 :   case 1: OutBufCur[0] = Ptr[0]; LLVM_FALLTHROUGH;
     276             :   case 0: break;
     277    24980192 :   default:
     278    24980192 :     memcpy(OutBufCur, Ptr, Size);
     279    24980192 :     break;
     280             :   }
     281             : 
     282    96462344 :   OutBufCur += Size;
     283    96462344 : }
     284             : 
     285             : // Formatted output.
     286     7016952 : raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
     287             :   // If we have more than a few bytes left in our output buffer, try
     288             :   // formatting directly onto its end.
     289             :   size_t NextBufferSize = 127;
     290     7016952 :   size_t BufferBytesLeft = OutBufEnd - OutBufCur;
     291     7016952 :   if (BufferBytesLeft > 3) {
     292     8003556 :     size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
     293             : 
     294             :     // Common case is that we have plenty of space.
     295     4001778 :     if (BytesUsed <= BufferBytesLeft) {
     296     3997773 :       OutBufCur += BytesUsed;
     297     3997773 :       return *this;
     298             :     }
     299             : 
     300             :     // Otherwise, we overflowed and the return value tells us the size to try
     301             :     // again with.
     302             :     NextBufferSize = BytesUsed;
     303             :   }
     304             : 
     305             :   // If we got here, we didn't have enough space in the output buffer for the
     306             :   // string.  Try printing into a SmallVector that is resized to have enough
     307             :   // space.  Iterate until we win.
     308             :   SmallVector<char, 128> V;
     309             : 
     310             :   while (true) {
     311     3019244 :     V.resize(NextBufferSize);
     312             : 
     313             :     // Try formatting into the SmallVector.
     314     6038488 :     size_t BytesUsed = Fmt.print(V.data(), NextBufferSize);
     315             : 
     316             :     // If BytesUsed fit into the vector, we win.
     317     3019244 :     if (BytesUsed <= NextBufferSize)
     318     3019179 :       return write(V.data(), BytesUsed);
     319             : 
     320             :     // Otherwise, try again with a new size.
     321             :     assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
     322             :     NextBufferSize = BytesUsed;
     323             :   }
     324             : }
     325             : 
     326      119026 : raw_ostream &raw_ostream::operator<<(const formatv_object_base &Obj) {
     327             :   SmallString<128> S;
     328      119026 :   Obj.format(*this);
     329      119026 :   return *this;
     330             : }
     331             : 
     332        3765 : raw_ostream &raw_ostream::operator<<(const FormattedString &FS) {
     333        3765 :   if (FS.Str.size() >= FS.Width || FS.Justify == FormattedString::JustifyNone) {
     334         106 :     this->operator<<(FS.Str);
     335         106 :     return *this;
     336             :   }
     337        3659 :   const size_t Difference = FS.Width - FS.Str.size();
     338        3659 :   switch (FS.Justify) {
     339        1035 :   case FormattedString::JustifyLeft:
     340        1035 :     this->operator<<(FS.Str);
     341        1035 :     this->indent(Difference);
     342        1035 :     break;
     343        2621 :   case FormattedString::JustifyRight:
     344        2621 :     this->indent(Difference);
     345        2621 :     this->operator<<(FS.Str);
     346        2621 :     break;
     347           3 :   case FormattedString::JustifyCenter: {
     348           3 :     int PadAmount = Difference / 2;
     349           3 :     this->indent(PadAmount);
     350           3 :     this->operator<<(FS.Str);
     351           3 :     this->indent(Difference - PadAmount);
     352           3 :     break;
     353             :   }
     354           0 :   default:
     355           0 :     llvm_unreachable("Bad Justification");
     356             :   }
     357             :   return *this;
     358             : }
     359             : 
     360    10312507 : raw_ostream &raw_ostream::operator<<(const FormattedNumber &FN) {
     361    10312507 :   if (FN.Hex) {
     362             :     HexPrintStyle Style;
     363      648844 :     if (FN.Upper && FN.HexPrefix)
     364             :       Style = HexPrintStyle::PrefixUpper;
     365      646727 :     else if (FN.Upper && !FN.HexPrefix)
     366             :       Style = HexPrintStyle::Upper;
     367        5315 :     else if (!FN.Upper && FN.HexPrefix)
     368             :       Style = HexPrintStyle::PrefixLower;
     369             :     else
     370             :       Style = HexPrintStyle::Lower;
     371     1297688 :     llvm::write_hex(*this, FN.HexValue, Style, FN.Width);
     372             :   } else {
     373             :     llvm::SmallString<16> Buffer;
     374             :     llvm::raw_svector_ostream Stream(Buffer);
     375     9663663 :     llvm::write_integer(Stream, FN.DecValue, 0, IntegerStyle::Integer);
     376     9663663 :     if (Buffer.size() < FN.Width)
     377     3154504 :       indent(FN.Width - Buffer.size());
     378             :     (*this) << Buffer;
     379             :   }
     380    10312507 :   return *this;
     381             : }
     382             : 
     383        4265 : raw_ostream &raw_ostream::operator<<(const FormattedBytes &FB) {
     384        4265 :   if (FB.Bytes.empty())
     385             :     return *this;
     386             : 
     387             :   size_t LineIndex = 0;
     388        4208 :   auto Bytes = FB.Bytes;
     389             :   const size_t Size = Bytes.size();
     390        4208 :   HexPrintStyle HPS = FB.Upper ? HexPrintStyle::Upper : HexPrintStyle::Lower;
     391             :   uint64_t OffsetWidth = 0;
     392        4208 :   if (FB.FirstByteOffset.hasValue()) {
     393             :     // Figure out how many nibbles are needed to print the largest offset
     394             :     // represented by this data set, so that we can align the offset field
     395             :     // to the right width.
     396        2023 :     size_t Lines = Size / FB.NumPerLine;
     397        2023 :     uint64_t MaxOffset = *FB.FirstByteOffset + Lines * FB.NumPerLine;
     398             :     unsigned Power = 0;
     399        2023 :     if (MaxOffset > 0)
     400             :       Power = llvm::Log2_64_Ceil(MaxOffset);
     401        6069 :     OffsetWidth = std::max<uint64_t>(4, llvm::alignTo(Power, 4) / 4);
     402             :   }
     403             : 
     404             :   // The width of a block of data including all spaces for group separators.
     405             :   unsigned NumByteGroups =
     406        8416 :       alignTo(FB.NumPerLine, FB.ByteGroupSize) / FB.ByteGroupSize;
     407        4208 :   unsigned BlockCharWidth = FB.NumPerLine * 2 + NumByteGroups - 1;
     408             : 
     409     1712863 :   while (!Bytes.empty()) {
     410     1708655 :     indent(FB.IndentLevel);
     411             : 
     412     1708655 :     if (FB.FirstByteOffset.hasValue()) {
     413     1706448 :       uint64_t Offset = FB.FirstByteOffset.getValue();
     414     1706448 :       llvm::write_hex(*this, Offset + LineIndex, HPS, OffsetWidth);
     415     1706448 :       *this << ": ";
     416             :     }
     417             : 
     418     1708655 :     auto Line = Bytes.take_front(FB.NumPerLine);
     419             : 
     420             :     size_t CharsPrinted = 0;
     421             :     // Print the hex bytes for this line in groups
     422    56367629 :     for (size_t I = 0; I < Line.size(); ++I, CharsPrinted += 2) {
     423    27329487 :       if (I && (I % FB.ByteGroupSize) == 0) {
     424     5141381 :         ++CharsPrinted;
     425     5141381 :         *this << " ";
     426             :       }
     427    27329487 :       llvm::write_hex(*this, Line[I], HPS, 2);
     428             :     }
     429             : 
     430     1708655 :     if (FB.ASCII) {
     431             :       // Print any spaces needed for any bytes that we didn't print on this
     432             :       // line so that the ASCII bytes are correctly aligned.
     433             :       assert(BlockCharWidth >= CharsPrinted);
     434     1706450 :       indent(BlockCharWidth - CharsPrinted + 2);
     435     1706450 :       *this << "|";
     436             : 
     437             :       // Print the ASCII char values for each byte on this line
     438    56318916 :       for (uint8_t Byte : Line) {
     439    27306233 :         if (isprint(Byte))
     440       30848 :           *this << static_cast<char>(Byte);
     441             :         else
     442             :           *this << '.';
     443             :       }
     444             :       *this << '|';
     445             :     }
     446             : 
     447             :     Bytes = Bytes.drop_front(Line.size());
     448     1708655 :     LineIndex += Line.size();
     449     1708655 :     if (LineIndex < Size)
     450             :       *this << '\n';
     451             :   }
     452             :   return *this;
     453             : }
     454             : 
     455             : template <char C>
     456    24251674 : static raw_ostream &write_padding(raw_ostream &OS, unsigned NumChars) {
     457             :   static const char Chars[] = {C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C,
     458             :                                C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C,
     459             :                                C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C,
     460             :                                C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C,
     461             :                                C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C};
     462             : 
     463             :   // Usually the indentation is small, handle it with a fastpath.
     464    24251674 :   if (NumChars < array_lengthof(Chars))
     465    24251098 :     return OS.write(Chars, NumChars);
     466             : 
     467     8206848 :   while (NumChars) {
     468     4103136 :     unsigned NumToWrite = std::min(NumChars,
     469     8206272 :                                    (unsigned)array_lengthof(Chars)-1);
     470     4103136 :     OS.write(Chars, NumToWrite);
     471     4103136 :     NumChars -= NumToWrite;
     472             :   }
     473             :   return OS;
     474             : }
     475             : 
     476             : /// indent - Insert 'NumSpaces' spaces.
     477    23677105 : raw_ostream &raw_ostream::indent(unsigned NumSpaces) {
     478    23677105 :   return write_padding<' '>(*this, NumSpaces);
     479             : }
     480             : 
     481             : /// write_zeros - Insert 'NumZeros' nulls.
     482      574569 : raw_ostream &raw_ostream::write_zeros(unsigned NumZeros) {
     483      574569 :   return write_padding<'\0'>(*this, NumZeros);
     484             : }
     485             : 
     486           0 : void raw_ostream::anchor() {}
     487             : 
     488             : //===----------------------------------------------------------------------===//
     489             : //  Formatted Output
     490             : //===----------------------------------------------------------------------===//
     491             : 
     492             : // Out of line virtual method.
     493           0 : void format_object_base::home() {
     494           0 : }
     495             : 
     496             : //===----------------------------------------------------------------------===//
     497             : //  raw_fd_ostream
     498             : //===----------------------------------------------------------------------===//
     499             : 
     500       66831 : static int getFD(StringRef Filename, std::error_code &EC,
     501             :                  sys::fs::CreationDisposition Disp, sys::fs::FileAccess Access,
     502             :                  sys::fs::OpenFlags Flags) {
     503             :   assert((Access & sys::fs::FA_Write) &&
     504             :          "Cannot make a raw_ostream from a read-only descriptor!");
     505             : 
     506             :   // Handle "-" as stdout. Note that when we do this, we consider ourself
     507             :   // the owner of stdout and may set the "binary" flag globally based on Flags.
     508             :   if (Filename == "-") {
     509       56090 :     EC = std::error_code();
     510             :     // If user requested binary then put stdout into binary mode if
     511             :     // possible.
     512       56090 :     if (!(Flags & sys::fs::OF_Text))
     513       27207 :       sys::ChangeStdoutToBinary();
     514             :     return STDOUT_FILENO;
     515             :   }
     516             : 
     517             :   int FD;
     518       10741 :   if (Access & sys::fs::FA_Read)
     519         160 :     EC = sys::fs::openFileForReadWrite(Filename, FD, Disp, Flags);
     520             :   else
     521       10581 :     EC = sys::fs::openFileForWrite(Filename, FD, Disp, Flags);
     522       10741 :   if (EC)
     523             :     return -1;
     524             : 
     525        9847 :   return FD;
     526             : }
     527             : 
     528           0 : raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC)
     529             :     : raw_fd_ostream(Filename, EC, sys::fs::CD_CreateAlways, sys::fs::FA_Write,
     530           0 :                      sys::fs::OF_None) {}
     531             : 
     532          14 : raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC,
     533          14 :                                sys::fs::CreationDisposition Disp)
     534          14 :     : raw_fd_ostream(Filename, EC, Disp, sys::fs::FA_Write, sys::fs::OF_None) {}
     535             : 
     536         160 : raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC,
     537         160 :                                sys::fs::FileAccess Access)
     538             :     : raw_fd_ostream(Filename, EC, sys::fs::CD_CreateAlways, Access,
     539         160 :                      sys::fs::OF_None) {}
     540             : 
     541       66657 : raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC,
     542       66657 :                                sys::fs::OpenFlags Flags)
     543             :     : raw_fd_ostream(Filename, EC, sys::fs::CD_CreateAlways, sys::fs::FA_Write,
     544       66657 :                      Flags) {}
     545             : 
     546       66831 : raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC,
     547             :                                sys::fs::CreationDisposition Disp,
     548             :                                sys::fs::FileAccess Access,
     549       66831 :                                sys::fs::OpenFlags Flags)
     550       66831 :     : raw_fd_ostream(getFD(Filename, EC, Disp, Access, Flags), true) {}
     551             : 
     552             : /// FD is the file descriptor that this writes to.  If ShouldClose is true, this
     553             : /// closes the file when the stream is destroyed.
     554      232830 : raw_fd_ostream::raw_fd_ostream(int fd, bool shouldClose, bool unbuffered)
     555      232830 :     : raw_pwrite_stream(unbuffered), FD(fd), ShouldClose(shouldClose) {
     556      232830 :   if (FD < 0 ) {
     557         894 :     ShouldClose = false;
     558         894 :     return;
     559             :   }
     560             : 
     561             :   // Do not attempt to close stdout or stderr. We used to try to maintain the
     562             :   // property that tools that support writing file to stdout should not also
     563             :   // write informational output to stdout, but in practice we were never able to
     564             :   // maintain this invariant. Many features have been added to LLVM and clang
     565             :   // (-fdump-record-layouts, optimization remarks, etc) that print to stdout, so
     566             :   // users must simply be aware that mixed output and remarks is a possibility.
     567      231936 :   if (FD <= STDERR_FILENO)
     568      211688 :     ShouldClose = false;
     569             : 
     570             :   // Get the starting position.
     571      231936 :   off_t loc = ::lseek(FD, 0, SEEK_CUR);
     572             : #ifdef _WIN32
     573             :   // MSVCRT's _lseek(SEEK_CUR) doesn't return -1 for pipes.
     574             :   sys::fs::file_status Status;
     575             :   std::error_code EC = status(FD, Status);
     576             :   SupportsSeeking = !EC && Status.type() == sys::fs::file_type::regular_file;
     577             : #else
     578      231936 :   SupportsSeeking = loc != (off_t)-1;
     579             : #endif
     580      231936 :   if (!SupportsSeeking)
     581      207449 :     pos = 0;
     582             :   else
     583       24487 :     pos = static_cast<uint64_t>(loc);
     584             : }
     585             : 
     586      482001 : raw_fd_ostream::~raw_fd_ostream() {
     587      232518 :   if (FD >= 0) {
     588      228314 :     flush();
     589      228314 :     if (ShouldClose) {
     590       16307 :       if (auto EC = sys::Process::SafelyCloseFileDescriptor(FD))
     591             :         error_detected(EC);
     592             :     }
     593             :   }
     594             : 
     595             : #ifdef __MINGW32__
     596             :   // On mingw, global dtors should not call exit().
     597             :   // report_fatal_error() invokes exit(). We know report_fatal_error()
     598             :   // might not write messages to stderr when any errors were detected
     599             :   // on FD == 2.
     600             :   if (FD == 2) return;
     601             : #endif
     602             : 
     603             :   // If there are any pending errors, report them now. Clients wishing
     604             :   // to avoid report_fatal_error calls should check for errors with
     605             :   // has_error() and clear the error flag with clear_error() before
     606             :   // destructing raw_ostream objects which may have errors.
     607      232518 :   if (has_error())
     608          10 :     report_fatal_error("IO failure on output stream: " + error().message(),
     609             :                        /*GenCrashDiag=*/false);
     610      249483 : }
     611             : 
     612    21427830 : void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
     613             :   assert(FD >= 0 && "File already closed.");
     614    21427830 :   pos += Size;
     615             : 
     616             :   // The maximum write size is limited to SSIZE_MAX because a write
     617             :   // greater than SSIZE_MAX is implementation-defined in POSIX.
     618             :   // Since SSIZE_MAX is not portable, we use SIZE_MAX >> 1 instead.
     619             :   size_t MaxWriteSize = SIZE_MAX >> 1;
     620             : 
     621             : #if defined(__linux__)
     622             :   // It is observed that Linux returns EINVAL for a very large write (>2G).
     623             :   // Make it a reasonably small value.
     624    21427830 :   MaxWriteSize = 1024 * 1024 * 1024;
     625             : #elif defined(_WIN32)
     626             :   // Writing a large size of output to Windows console returns ENOMEM. It seems
     627             :   // that, prior to Windows 8, WriteFile() is redirecting to WriteConsole(), and
     628             :   // the latter has a size limit (66000 bytes or less, depending on heap usage).
     629             :   if (::_isatty(FD) && !RunningWindows8OrGreater())
     630             :     MaxWriteSize = 32767;
     631             : #endif
     632             : 
     633             :   do {
     634    21427830 :     size_t ChunkSize = std::min(Size, MaxWriteSize);
     635    21427830 :     ssize_t ret = ::write(FD, Ptr, ChunkSize);
     636             : 
     637    21427830 :     if (ret < 0) {
     638             :       // If it's a recoverable error, swallow it and retry the write.
     639             :       //
     640             :       // Ideally we wouldn't ever see EAGAIN or EWOULDBLOCK here, since
     641             :       // raw_ostream isn't designed to do non-blocking I/O. However, some
     642             :       // programs, such as old versions of bjam, have mistakenly used
     643             :       // O_NONBLOCK. For compatibility, emulate blocking semantics by
     644             :       // spinning until the write succeeds. If you don't want spinning,
     645             :       // don't use O_NONBLOCK file descriptors with raw_ostream.
     646       16570 :       if (errno == EINTR || errno == EAGAIN
     647             : #ifdef EWOULDBLOCK
     648       16570 :           || errno == EWOULDBLOCK
     649             : #endif
     650             :           )
     651           0 :         continue;
     652             : 
     653             :       // Otherwise it's a non-recoverable error. Note it and quit.
     654       16570 :       error_detected(std::error_code(errno, std::generic_category()));
     655       16570 :       break;
     656             :     }
     657             : 
     658             :     // The write may have written some or all of the data. Update the
     659             :     // size and buffer pointer to reflect the remainder that needs
     660             :     // to be written. If there are no bytes left, we're done.
     661    21411260 :     Ptr += ret;
     662    21411260 :     Size -= ret;
     663    21411260 :   } while (Size > 0);
     664    21427830 : }
     665             : 
     666        3310 : void raw_fd_ostream::close() {
     667             :   assert(ShouldClose);
     668        3310 :   ShouldClose = false;
     669        3310 :   flush();
     670        3310 :   if (auto EC = sys::Process::SafelyCloseFileDescriptor(FD))
     671             :     error_detected(EC);
     672        3310 :   FD = -1;
     673        3310 : }
     674             : 
     675       23720 : uint64_t raw_fd_ostream::seek(uint64_t off) {
     676             :   assert(SupportsSeeking && "Stream does not support seeking!");
     677       23720 :   flush();
     678             : #ifdef _WIN32
     679             :   pos = ::_lseeki64(FD, off, SEEK_SET);
     680             : #elif defined(HAVE_LSEEK64)
     681       23720 :   pos = ::lseek64(FD, off, SEEK_SET);
     682             : #else
     683             :   pos = ::lseek(FD, off, SEEK_SET);
     684             : #endif
     685       23720 :   if (pos == (uint64_t)-1)
     686           0 :     error_detected(std::error_code(errno, std::generic_category()));
     687       23720 :   return pos;
     688             : }
     689             : 
     690       11701 : void raw_fd_ostream::pwrite_impl(const char *Ptr, size_t Size,
     691             :                                  uint64_t Offset) {
     692       11701 :   uint64_t Pos = tell();
     693       11701 :   seek(Offset);
     694       11701 :   write(Ptr, Size);
     695       11701 :   seek(Pos);
     696       11701 : }
     697             : 
     698       74906 : size_t raw_fd_ostream::preferred_buffer_size() const {
     699             : #if !defined(_MSC_VER) && !defined(__MINGW32__) && !defined(__minix)
     700             :   // Windows and Minix have no st_blksize.
     701             :   assert(FD >= 0 && "File not yet open!");
     702             :   struct stat statbuf;
     703      149812 :   if (fstat(FD, &statbuf) != 0)
     704             :     return 0;
     705             : 
     706             :   // If this is a terminal, don't use buffering. Line buffering
     707             :   // would be a more traditional thing to do, but it's not worth
     708             :   // the complexity.
     709       74906 :   if (S_ISCHR(statbuf.st_mode) && isatty(FD))
     710             :     return 0;
     711             :   // Return the preferred block size.
     712       74906 :   return statbuf.st_blksize;
     713             : #else
     714             :   return raw_ostream::preferred_buffer_size();
     715             : #endif
     716             : }
     717             : 
     718         784 : raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
     719             :                                          bool bg) {
     720         784 :   if (sys::Process::ColorNeedsFlush())
     721           0 :     flush();
     722             :   const char *colorcode =
     723        1458 :     (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
     724         674 :     : sys::Process::OutputColor(colors, bold, bg);
     725         784 :   if (colorcode) {
     726         784 :     size_t len = strlen(colorcode);
     727         784 :     write(colorcode, len);
     728             :     // don't account colors towards output characters
     729         784 :     pos -= len;
     730             :   }
     731         784 :   return *this;
     732             : }
     733             : 
     734         777 : raw_ostream &raw_fd_ostream::resetColor() {
     735         777 :   if (sys::Process::ColorNeedsFlush())
     736           0 :     flush();
     737         777 :   const char *colorcode = sys::Process::ResetColor();
     738         777 :   if (colorcode) {
     739         777 :     size_t len = strlen(colorcode);
     740         777 :     write(colorcode, len);
     741             :     // don't account colors towards output characters
     742         777 :     pos -= len;
     743             :   }
     744         777 :   return *this;
     745             : }
     746             : 
     747           0 : raw_ostream &raw_fd_ostream::reverseColor() {
     748           0 :   if (sys::Process::ColorNeedsFlush())
     749           0 :     flush();
     750           0 :   const char *colorcode = sys::Process::OutputReverse();
     751           0 :   if (colorcode) {
     752           0 :     size_t len = strlen(colorcode);
     753           0 :     write(colorcode, len);
     754             :     // don't account colors towards output characters
     755           0 :     pos -= len;
     756             :   }
     757           0 :   return *this;
     758             : }
     759             : 
     760        1752 : bool raw_fd_ostream::is_displayed() const {
     761        1752 :   return sys::Process::FileDescriptorIsDisplayed(FD);
     762             : }
     763             : 
     764      206037 : bool raw_fd_ostream::has_colors() const {
     765      206037 :   return sys::Process::FileDescriptorHasColors(FD);
     766             : }
     767             : 
     768           0 : void raw_fd_ostream::anchor() {}
     769             : 
     770             : //===----------------------------------------------------------------------===//
     771             : //  outs(), errs(), nulls()
     772             : //===----------------------------------------------------------------------===//
     773             : 
     774             : /// outs() - This returns a reference to a raw_ostream for standard output.
     775             : /// Use it like: outs() << "foo" << "bar";
     776     8073587 : raw_ostream &llvm::outs() {
     777             :   // Set buffer settings to model stdout behavior.
     778             :   std::error_code EC;
     779     8083112 :   static raw_fd_ostream S("-", EC, sys::fs::F_None);
     780             :   assert(!EC);
     781     8073587 :   return S;
     782             : }
     783             : 
     784             : /// errs() - This returns a reference to a raw_ostream for standard error.
     785             : /// Use it like: errs() << "foo" << "bar";
     786      516265 : raw_ostream &llvm::errs() {
     787             :   // Set standard error to be unbuffered by default.
     788      516265 :   static raw_fd_ostream S(STDERR_FILENO, false, true);
     789      516265 :   return S;
     790             : }
     791             : 
     792             : /// nulls() - This returns a reference to a raw_ostream which discards output.
     793     8904059 : raw_ostream &llvm::nulls() {
     794     8906148 :   static raw_null_ostream S;
     795     8904059 :   return S;
     796             : }
     797             : 
     798             : //===----------------------------------------------------------------------===//
     799             : //  raw_string_ostream
     800             : //===----------------------------------------------------------------------===//
     801             : 
     802     4428068 : raw_string_ostream::~raw_string_ostream() {
     803     2214030 :   flush();
     804     2214038 : }
     805             : 
     806     2222063 : void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
     807     2222063 :   OS.append(Ptr, Size);
     808     2222063 : }
     809             : 
     810             : //===----------------------------------------------------------------------===//
     811             : //  raw_svector_ostream
     812             : //===----------------------------------------------------------------------===//
     813             : 
     814    19307882 : uint64_t raw_svector_ostream::current_pos() const { return OS.size(); }
     815             : 
     816   397434013 : void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
     817   397434013 :   OS.append(Ptr, Ptr + Size);
     818   397434320 : }
     819             : 
     820        4539 : void raw_svector_ostream::pwrite_impl(const char *Ptr, size_t Size,
     821             :                                       uint64_t Offset) {
     822        4539 :   memcpy(OS.data() + Offset, Ptr, Size);
     823        4539 : }
     824             : 
     825             : //===----------------------------------------------------------------------===//
     826             : //  raw_null_ostream
     827             : //===----------------------------------------------------------------------===//
     828             : 
     829     1606494 : raw_null_ostream::~raw_null_ostream() {
     830             : #ifndef NDEBUG
     831             :   // ~raw_ostream asserts that the buffer is empty. This isn't necessary
     832             :   // with raw_null_ostream, but it's better to have raw_null_ostream follow
     833             :   // the rules than to change the rules just for raw_null_ostream.
     834             :   flush();
     835             : #endif
     836      803253 : }
     837             : 
     838           0 : void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
     839           0 : }
     840             : 
     841           0 : uint64_t raw_null_ostream::current_pos() const {
     842           0 :   return 0;
     843             : }
     844             : 
     845           0 : void raw_null_ostream::pwrite_impl(const char *Ptr, size_t Size,
     846           0 :                                    uint64_t Offset) {}
     847             : 
     848           0 : void raw_pwrite_stream::anchor() {}

Generated by: LCOV version 1.13