xref: /netbsd-src/external/apache2/llvm/dist/clang/lib/Basic/SourceManager.cpp (revision e038c9c4676b0f19b1b7dd08a940c6ed64a6d5ae)
17330f729Sjoerg //===- SourceManager.cpp - Track and cache source files -------------------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg //  This file implements the SourceManager interface.
107330f729Sjoerg //
117330f729Sjoerg //===----------------------------------------------------------------------===//
127330f729Sjoerg 
137330f729Sjoerg #include "clang/Basic/SourceManager.h"
147330f729Sjoerg #include "clang/Basic/Diagnostic.h"
157330f729Sjoerg #include "clang/Basic/FileManager.h"
167330f729Sjoerg #include "clang/Basic/LLVM.h"
177330f729Sjoerg #include "clang/Basic/SourceLocation.h"
187330f729Sjoerg #include "clang/Basic/SourceManagerInternals.h"
197330f729Sjoerg #include "llvm/ADT/DenseMap.h"
207330f729Sjoerg #include "llvm/ADT/None.h"
21*e038c9c4Sjoerg #include "llvm/ADT/Optional.h"
227330f729Sjoerg #include "llvm/ADT/STLExtras.h"
237330f729Sjoerg #include "llvm/ADT/SmallVector.h"
247330f729Sjoerg #include "llvm/ADT/StringRef.h"
25*e038c9c4Sjoerg #include "llvm/ADT/StringSwitch.h"
267330f729Sjoerg #include "llvm/Support/Allocator.h"
277330f729Sjoerg #include "llvm/Support/Capacity.h"
287330f729Sjoerg #include "llvm/Support/Compiler.h"
29*e038c9c4Sjoerg #include "llvm/Support/Endian.h"
307330f729Sjoerg #include "llvm/Support/ErrorHandling.h"
317330f729Sjoerg #include "llvm/Support/FileSystem.h"
327330f729Sjoerg #include "llvm/Support/MathExtras.h"
337330f729Sjoerg #include "llvm/Support/MemoryBuffer.h"
347330f729Sjoerg #include "llvm/Support/Path.h"
357330f729Sjoerg #include "llvm/Support/raw_ostream.h"
367330f729Sjoerg #include <algorithm>
377330f729Sjoerg #include <cassert>
387330f729Sjoerg #include <cstddef>
397330f729Sjoerg #include <cstdint>
407330f729Sjoerg #include <memory>
417330f729Sjoerg #include <tuple>
427330f729Sjoerg #include <utility>
437330f729Sjoerg #include <vector>
447330f729Sjoerg 
457330f729Sjoerg using namespace clang;
467330f729Sjoerg using namespace SrcMgr;
477330f729Sjoerg using llvm::MemoryBuffer;
487330f729Sjoerg 
497330f729Sjoerg //===----------------------------------------------------------------------===//
507330f729Sjoerg // SourceManager Helper Classes
517330f729Sjoerg //===----------------------------------------------------------------------===//
527330f729Sjoerg 
537330f729Sjoerg /// getSizeBytesMapped - Returns the number of bytes actually mapped for this
547330f729Sjoerg /// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
getSizeBytesMapped() const557330f729Sjoerg unsigned ContentCache::getSizeBytesMapped() const {
56*e038c9c4Sjoerg   return Buffer ? Buffer->getBufferSize() : 0;
577330f729Sjoerg }
587330f729Sjoerg 
597330f729Sjoerg /// Returns the kind of memory used to back the memory buffer for
607330f729Sjoerg /// this content cache.  This is used for performance analysis.
getMemoryBufferKind() const617330f729Sjoerg llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
62*e038c9c4Sjoerg   assert(Buffer);
637330f729Sjoerg 
647330f729Sjoerg   // Should be unreachable, but keep for sanity.
65*e038c9c4Sjoerg   if (!Buffer)
667330f729Sjoerg     return llvm::MemoryBuffer::MemoryBuffer_Malloc;
677330f729Sjoerg 
68*e038c9c4Sjoerg   return Buffer->getBufferKind();
697330f729Sjoerg }
707330f729Sjoerg 
717330f729Sjoerg /// getSize - Returns the size of the content encapsulated by this ContentCache.
727330f729Sjoerg ///  This can be the size of the source file or the size of an arbitrary
737330f729Sjoerg ///  scratch buffer.  If the ContentCache encapsulates a source file, that
747330f729Sjoerg ///  file is not lazily brought in from disk to satisfy this query.
getSize() const757330f729Sjoerg unsigned ContentCache::getSize() const {
76*e038c9c4Sjoerg   return Buffer ? (unsigned)Buffer->getBufferSize()
777330f729Sjoerg                 : (unsigned)ContentsEntry->getSize();
787330f729Sjoerg }
797330f729Sjoerg 
getInvalidBOM(StringRef BufStr)807330f729Sjoerg const char *ContentCache::getInvalidBOM(StringRef BufStr) {
817330f729Sjoerg   // If the buffer is valid, check to see if it has a UTF Byte Order Mark
827330f729Sjoerg   // (BOM).  We only support UTF-8 with and without a BOM right now.  See
837330f729Sjoerg   // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
847330f729Sjoerg   const char *InvalidBOM =
857330f729Sjoerg       llvm::StringSwitch<const char *>(BufStr)
867330f729Sjoerg           .StartsWith(llvm::StringLiteral::withInnerNUL("\x00\x00\xFE\xFF"),
877330f729Sjoerg                       "UTF-32 (BE)")
887330f729Sjoerg           .StartsWith(llvm::StringLiteral::withInnerNUL("\xFF\xFE\x00\x00"),
897330f729Sjoerg                       "UTF-32 (LE)")
907330f729Sjoerg           .StartsWith("\xFE\xFF", "UTF-16 (BE)")
917330f729Sjoerg           .StartsWith("\xFF\xFE", "UTF-16 (LE)")
927330f729Sjoerg           .StartsWith("\x2B\x2F\x76", "UTF-7")
937330f729Sjoerg           .StartsWith("\xF7\x64\x4C", "UTF-1")
947330f729Sjoerg           .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
957330f729Sjoerg           .StartsWith("\x0E\xFE\xFF", "SCSU")
967330f729Sjoerg           .StartsWith("\xFB\xEE\x28", "BOCU-1")
977330f729Sjoerg           .StartsWith("\x84\x31\x95\x33", "GB-18030")
987330f729Sjoerg           .Default(nullptr);
997330f729Sjoerg 
1007330f729Sjoerg   return InvalidBOM;
1017330f729Sjoerg }
1027330f729Sjoerg 
103*e038c9c4Sjoerg llvm::Optional<llvm::MemoryBufferRef>
getBufferOrNone(DiagnosticsEngine & Diag,FileManager & FM,SourceLocation Loc) const104*e038c9c4Sjoerg ContentCache::getBufferOrNone(DiagnosticsEngine &Diag, FileManager &FM,
105*e038c9c4Sjoerg                               SourceLocation Loc) const {
1067330f729Sjoerg   // Lazily create the Buffer for ContentCaches that wrap files.  If we already
1077330f729Sjoerg   // computed it, just return what we have.
108*e038c9c4Sjoerg   if (IsBufferInvalid)
109*e038c9c4Sjoerg     return None;
110*e038c9c4Sjoerg   if (Buffer)
111*e038c9c4Sjoerg     return Buffer->getMemBufferRef();
112*e038c9c4Sjoerg   if (!ContentsEntry)
113*e038c9c4Sjoerg     return None;
1147330f729Sjoerg 
115*e038c9c4Sjoerg   // Start with the assumption that the buffer is invalid to simplify early
116*e038c9c4Sjoerg   // return paths.
117*e038c9c4Sjoerg   IsBufferInvalid = true;
1187330f729Sjoerg 
1197330f729Sjoerg   auto BufferOrError = FM.getBufferForFile(ContentsEntry, IsFileVolatile);
1207330f729Sjoerg 
1217330f729Sjoerg   // If we were unable to open the file, then we are in an inconsistent
1227330f729Sjoerg   // situation where the content cache referenced a file which no longer
1237330f729Sjoerg   // exists. Most likely, we were using a stat cache with an invalid entry but
1247330f729Sjoerg   // the file could also have been removed during processing. Since we can't
1257330f729Sjoerg   // really deal with this situation, just create an empty buffer.
1267330f729Sjoerg   if (!BufferOrError) {
1277330f729Sjoerg     if (Diag.isDiagnosticInFlight())
1287330f729Sjoerg       Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
1297330f729Sjoerg                                 ContentsEntry->getName(),
1307330f729Sjoerg                                 BufferOrError.getError().message());
1317330f729Sjoerg     else
1327330f729Sjoerg       Diag.Report(Loc, diag::err_cannot_open_file)
1337330f729Sjoerg           << ContentsEntry->getName() << BufferOrError.getError().message();
1347330f729Sjoerg 
135*e038c9c4Sjoerg     return None;
1367330f729Sjoerg   }
1377330f729Sjoerg 
138*e038c9c4Sjoerg   Buffer = std::move(*BufferOrError);
1397330f729Sjoerg 
140*e038c9c4Sjoerg   // Check that the file's size fits in an 'unsigned' (with room for a
141*e038c9c4Sjoerg   // past-the-end value). This is deeply regrettable, but various parts of
142*e038c9c4Sjoerg   // Clang (including elsewhere in this file!) use 'unsigned' to represent file
143*e038c9c4Sjoerg   // offsets, line numbers, string literal lengths, and so on, and fail
144*e038c9c4Sjoerg   // miserably on large source files.
145*e038c9c4Sjoerg   //
146*e038c9c4Sjoerg   // Note: ContentsEntry could be a named pipe, in which case
147*e038c9c4Sjoerg   // ContentsEntry::getSize() could have the wrong size. Use
148*e038c9c4Sjoerg   // MemoryBuffer::getBufferSize() instead.
149*e038c9c4Sjoerg   if (Buffer->getBufferSize() >= std::numeric_limits<unsigned>::max()) {
150*e038c9c4Sjoerg     if (Diag.isDiagnosticInFlight())
151*e038c9c4Sjoerg       Diag.SetDelayedDiagnostic(diag::err_file_too_large,
152*e038c9c4Sjoerg                                 ContentsEntry->getName());
153*e038c9c4Sjoerg     else
154*e038c9c4Sjoerg       Diag.Report(Loc, diag::err_file_too_large)
155*e038c9c4Sjoerg         << ContentsEntry->getName();
156*e038c9c4Sjoerg 
157*e038c9c4Sjoerg     return None;
158*e038c9c4Sjoerg   }
159*e038c9c4Sjoerg 
160*e038c9c4Sjoerg   // Unless this is a named pipe (in which case we can handle a mismatch),
161*e038c9c4Sjoerg   // check that the file's size is the same as in the file entry (which may
1627330f729Sjoerg   // have come from a stat cache).
163*e038c9c4Sjoerg   if (!ContentsEntry->isNamedPipe() &&
164*e038c9c4Sjoerg       Buffer->getBufferSize() != (size_t)ContentsEntry->getSize()) {
1657330f729Sjoerg     if (Diag.isDiagnosticInFlight())
1667330f729Sjoerg       Diag.SetDelayedDiagnostic(diag::err_file_modified,
1677330f729Sjoerg                                 ContentsEntry->getName());
1687330f729Sjoerg     else
1697330f729Sjoerg       Diag.Report(Loc, diag::err_file_modified)
1707330f729Sjoerg         << ContentsEntry->getName();
1717330f729Sjoerg 
172*e038c9c4Sjoerg     return None;
1737330f729Sjoerg   }
1747330f729Sjoerg 
1757330f729Sjoerg   // If the buffer is valid, check to see if it has a UTF Byte Order Mark
1767330f729Sjoerg   // (BOM).  We only support UTF-8 with and without a BOM right now.  See
1777330f729Sjoerg   // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
178*e038c9c4Sjoerg   StringRef BufStr = Buffer->getBuffer();
1797330f729Sjoerg   const char *InvalidBOM = getInvalidBOM(BufStr);
1807330f729Sjoerg 
1817330f729Sjoerg   if (InvalidBOM) {
1827330f729Sjoerg     Diag.Report(Loc, diag::err_unsupported_bom)
1837330f729Sjoerg       << InvalidBOM << ContentsEntry->getName();
184*e038c9c4Sjoerg     return None;
1857330f729Sjoerg   }
1867330f729Sjoerg 
187*e038c9c4Sjoerg   // Buffer has been validated.
188*e038c9c4Sjoerg   IsBufferInvalid = false;
189*e038c9c4Sjoerg   return Buffer->getMemBufferRef();
1907330f729Sjoerg }
1917330f729Sjoerg 
getLineTableFilenameID(StringRef Name)1927330f729Sjoerg unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
1937330f729Sjoerg   auto IterBool = FilenameIDs.try_emplace(Name, FilenamesByID.size());
1947330f729Sjoerg   if (IterBool.second)
1957330f729Sjoerg     FilenamesByID.push_back(&*IterBool.first);
1967330f729Sjoerg   return IterBool.first->second;
1977330f729Sjoerg }
1987330f729Sjoerg 
1997330f729Sjoerg /// Add a line note to the line table that indicates that there is a \#line or
2007330f729Sjoerg /// GNU line marker at the specified FID/Offset location which changes the
2017330f729Sjoerg /// presumed location to LineNo/FilenameID. If EntryExit is 0, then this doesn't
2027330f729Sjoerg /// change the presumed \#include stack.  If it is 1, this is a file entry, if
2037330f729Sjoerg /// it is 2 then this is a file exit. FileKind specifies whether this is a
2047330f729Sjoerg /// system header or extern C system header.
AddLineNote(FileID FID,unsigned Offset,unsigned LineNo,int FilenameID,unsigned EntryExit,SrcMgr::CharacteristicKind FileKind)2057330f729Sjoerg void LineTableInfo::AddLineNote(FileID FID, unsigned Offset, unsigned LineNo,
2067330f729Sjoerg                                 int FilenameID, unsigned EntryExit,
2077330f729Sjoerg                                 SrcMgr::CharacteristicKind FileKind) {
2087330f729Sjoerg   std::vector<LineEntry> &Entries = LineEntries[FID];
2097330f729Sjoerg 
2107330f729Sjoerg   // An unspecified FilenameID means use the last filename if available, or the
2117330f729Sjoerg   // main source file otherwise.
2127330f729Sjoerg   if (FilenameID == -1 && !Entries.empty())
2137330f729Sjoerg     FilenameID = Entries.back().FilenameID;
2147330f729Sjoerg 
2157330f729Sjoerg   assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
2167330f729Sjoerg          "Adding line entries out of order!");
2177330f729Sjoerg 
2187330f729Sjoerg   unsigned IncludeOffset = 0;
2197330f729Sjoerg   if (EntryExit == 0) {  // No #include stack change.
2207330f729Sjoerg     IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
2217330f729Sjoerg   } else if (EntryExit == 1) {
2227330f729Sjoerg     IncludeOffset = Offset-1;
2237330f729Sjoerg   } else if (EntryExit == 2) {
2247330f729Sjoerg     assert(!Entries.empty() && Entries.back().IncludeOffset &&
2257330f729Sjoerg        "PPDirectives should have caught case when popping empty include stack");
2267330f729Sjoerg 
2277330f729Sjoerg     // Get the include loc of the last entries' include loc as our include loc.
2287330f729Sjoerg     IncludeOffset = 0;
2297330f729Sjoerg     if (const LineEntry *PrevEntry =
2307330f729Sjoerg           FindNearestLineEntry(FID, Entries.back().IncludeOffset))
2317330f729Sjoerg       IncludeOffset = PrevEntry->IncludeOffset;
2327330f729Sjoerg   }
2337330f729Sjoerg 
2347330f729Sjoerg   Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
2357330f729Sjoerg                                    IncludeOffset));
2367330f729Sjoerg }
2377330f729Sjoerg 
2387330f729Sjoerg /// FindNearestLineEntry - Find the line entry nearest to FID that is before
2397330f729Sjoerg /// it.  If there is no line entry before Offset in FID, return null.
FindNearestLineEntry(FileID FID,unsigned Offset)2407330f729Sjoerg const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID,
2417330f729Sjoerg                                                      unsigned Offset) {
2427330f729Sjoerg   const std::vector<LineEntry> &Entries = LineEntries[FID];
2437330f729Sjoerg   assert(!Entries.empty() && "No #line entries for this FID after all!");
2447330f729Sjoerg 
2457330f729Sjoerg   // It is very common for the query to be after the last #line, check this
2467330f729Sjoerg   // first.
2477330f729Sjoerg   if (Entries.back().FileOffset <= Offset)
2487330f729Sjoerg     return &Entries.back();
2497330f729Sjoerg 
2507330f729Sjoerg   // Do a binary search to find the maximal element that is still before Offset.
2517330f729Sjoerg   std::vector<LineEntry>::const_iterator I = llvm::upper_bound(Entries, Offset);
2527330f729Sjoerg   if (I == Entries.begin())
2537330f729Sjoerg     return nullptr;
2547330f729Sjoerg   return &*--I;
2557330f729Sjoerg }
2567330f729Sjoerg 
2577330f729Sjoerg /// Add a new line entry that has already been encoded into
2587330f729Sjoerg /// the internal representation of the line table.
AddEntry(FileID FID,const std::vector<LineEntry> & Entries)2597330f729Sjoerg void LineTableInfo::AddEntry(FileID FID,
2607330f729Sjoerg                              const std::vector<LineEntry> &Entries) {
2617330f729Sjoerg   LineEntries[FID] = Entries;
2627330f729Sjoerg }
2637330f729Sjoerg 
2647330f729Sjoerg /// getLineTableFilenameID - Return the uniqued ID for the specified filename.
getLineTableFilenameID(StringRef Name)2657330f729Sjoerg unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
2667330f729Sjoerg   return getLineTable().getLineTableFilenameID(Name);
2677330f729Sjoerg }
2687330f729Sjoerg 
2697330f729Sjoerg /// AddLineNote - Add a line note to the line table for the FileID and offset
2707330f729Sjoerg /// specified by Loc.  If FilenameID is -1, it is considered to be
2717330f729Sjoerg /// unspecified.
AddLineNote(SourceLocation Loc,unsigned LineNo,int FilenameID,bool IsFileEntry,bool IsFileExit,SrcMgr::CharacteristicKind FileKind)2727330f729Sjoerg void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
2737330f729Sjoerg                                 int FilenameID, bool IsFileEntry,
2747330f729Sjoerg                                 bool IsFileExit,
2757330f729Sjoerg                                 SrcMgr::CharacteristicKind FileKind) {
2767330f729Sjoerg   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
2777330f729Sjoerg 
2787330f729Sjoerg   bool Invalid = false;
2797330f729Sjoerg   const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
2807330f729Sjoerg   if (!Entry.isFile() || Invalid)
2817330f729Sjoerg     return;
2827330f729Sjoerg 
2837330f729Sjoerg   const SrcMgr::FileInfo &FileInfo = Entry.getFile();
2847330f729Sjoerg 
2857330f729Sjoerg   // Remember that this file has #line directives now if it doesn't already.
2867330f729Sjoerg   const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
2877330f729Sjoerg 
2887330f729Sjoerg   (void) getLineTable();
2897330f729Sjoerg 
2907330f729Sjoerg   unsigned EntryExit = 0;
2917330f729Sjoerg   if (IsFileEntry)
2927330f729Sjoerg     EntryExit = 1;
2937330f729Sjoerg   else if (IsFileExit)
2947330f729Sjoerg     EntryExit = 2;
2957330f729Sjoerg 
2967330f729Sjoerg   LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,
2977330f729Sjoerg                          EntryExit, FileKind);
2987330f729Sjoerg }
2997330f729Sjoerg 
getLineTable()3007330f729Sjoerg LineTableInfo &SourceManager::getLineTable() {
3017330f729Sjoerg   if (!LineTable)
3027330f729Sjoerg     LineTable.reset(new LineTableInfo());
3037330f729Sjoerg   return *LineTable;
3047330f729Sjoerg }
3057330f729Sjoerg 
3067330f729Sjoerg //===----------------------------------------------------------------------===//
3077330f729Sjoerg // Private 'Create' methods.
3087330f729Sjoerg //===----------------------------------------------------------------------===//
3097330f729Sjoerg 
SourceManager(DiagnosticsEngine & Diag,FileManager & FileMgr,bool UserFilesAreVolatile)3107330f729Sjoerg SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
3117330f729Sjoerg                              bool UserFilesAreVolatile)
3127330f729Sjoerg   : Diag(Diag), FileMgr(FileMgr), UserFilesAreVolatile(UserFilesAreVolatile) {
3137330f729Sjoerg   clearIDTables();
3147330f729Sjoerg   Diag.setSourceManager(this);
3157330f729Sjoerg }
3167330f729Sjoerg 
~SourceManager()3177330f729Sjoerg SourceManager::~SourceManager() {
3187330f729Sjoerg   // Delete FileEntry objects corresponding to content caches.  Since the actual
3197330f729Sjoerg   // content cache objects are bump pointer allocated, we just have to run the
3207330f729Sjoerg   // dtors, but we call the deallocate method for completeness.
3217330f729Sjoerg   for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
3227330f729Sjoerg     if (MemBufferInfos[i]) {
3237330f729Sjoerg       MemBufferInfos[i]->~ContentCache();
3247330f729Sjoerg       ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
3257330f729Sjoerg     }
3267330f729Sjoerg   }
3277330f729Sjoerg   for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
3287330f729Sjoerg        I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
3297330f729Sjoerg     if (I->second) {
3307330f729Sjoerg       I->second->~ContentCache();
3317330f729Sjoerg       ContentCacheAlloc.Deallocate(I->second);
3327330f729Sjoerg     }
3337330f729Sjoerg   }
3347330f729Sjoerg }
3357330f729Sjoerg 
clearIDTables()3367330f729Sjoerg void SourceManager::clearIDTables() {
3377330f729Sjoerg   MainFileID = FileID();
3387330f729Sjoerg   LocalSLocEntryTable.clear();
3397330f729Sjoerg   LoadedSLocEntryTable.clear();
3407330f729Sjoerg   SLocEntryLoaded.clear();
3417330f729Sjoerg   LastLineNoFileIDQuery = FileID();
3427330f729Sjoerg   LastLineNoContentCache = nullptr;
3437330f729Sjoerg   LastFileIDLookup = FileID();
3447330f729Sjoerg 
3457330f729Sjoerg   if (LineTable)
3467330f729Sjoerg     LineTable->clear();
3477330f729Sjoerg 
3487330f729Sjoerg   // Use up FileID #0 as an invalid expansion.
3497330f729Sjoerg   NextLocalOffset = 0;
3507330f729Sjoerg   CurrentLoadedOffset = MaxLoadedOffset;
3517330f729Sjoerg   createExpansionLoc(SourceLocation(), SourceLocation(), SourceLocation(), 1);
3527330f729Sjoerg }
3537330f729Sjoerg 
isMainFile(const FileEntry & SourceFile)354*e038c9c4Sjoerg bool SourceManager::isMainFile(const FileEntry &SourceFile) {
355*e038c9c4Sjoerg   assert(MainFileID.isValid() && "expected initialized SourceManager");
356*e038c9c4Sjoerg   if (auto *FE = getFileEntryForID(MainFileID))
357*e038c9c4Sjoerg     return FE->getUID() == SourceFile.getUID();
358*e038c9c4Sjoerg   return false;
359*e038c9c4Sjoerg }
360*e038c9c4Sjoerg 
initializeForReplay(const SourceManager & Old)3617330f729Sjoerg void SourceManager::initializeForReplay(const SourceManager &Old) {
3627330f729Sjoerg   assert(MainFileID.isInvalid() && "expected uninitialized SourceManager");
3637330f729Sjoerg 
3647330f729Sjoerg   auto CloneContentCache = [&](const ContentCache *Cache) -> ContentCache * {
3657330f729Sjoerg     auto *Clone = new (ContentCacheAlloc.Allocate<ContentCache>()) ContentCache;
3667330f729Sjoerg     Clone->OrigEntry = Cache->OrigEntry;
3677330f729Sjoerg     Clone->ContentsEntry = Cache->ContentsEntry;
3687330f729Sjoerg     Clone->BufferOverridden = Cache->BufferOverridden;
3697330f729Sjoerg     Clone->IsFileVolatile = Cache->IsFileVolatile;
3707330f729Sjoerg     Clone->IsTransient = Cache->IsTransient;
371*e038c9c4Sjoerg     Clone->setUnownedBuffer(Cache->getBufferIfLoaded());
3727330f729Sjoerg     return Clone;
3737330f729Sjoerg   };
3747330f729Sjoerg 
3757330f729Sjoerg   // Ensure all SLocEntries are loaded from the external source.
3767330f729Sjoerg   for (unsigned I = 0, N = Old.LoadedSLocEntryTable.size(); I != N; ++I)
3777330f729Sjoerg     if (!Old.SLocEntryLoaded[I])
3787330f729Sjoerg       Old.loadSLocEntry(I, nullptr);
3797330f729Sjoerg 
3807330f729Sjoerg   // Inherit any content cache data from the old source manager.
3817330f729Sjoerg   for (auto &FileInfo : Old.FileInfos) {
3827330f729Sjoerg     SrcMgr::ContentCache *&Slot = FileInfos[FileInfo.first];
3837330f729Sjoerg     if (Slot)
3847330f729Sjoerg       continue;
3857330f729Sjoerg     Slot = CloneContentCache(FileInfo.second);
3867330f729Sjoerg   }
3877330f729Sjoerg }
3887330f729Sjoerg 
getOrCreateContentCache(FileEntryRef FileEnt,bool isSystemFile)389*e038c9c4Sjoerg ContentCache &SourceManager::getOrCreateContentCache(FileEntryRef FileEnt,
3907330f729Sjoerg                                                      bool isSystemFile) {
3917330f729Sjoerg   // Do we already have information about this file?
3927330f729Sjoerg   ContentCache *&Entry = FileInfos[FileEnt];
393*e038c9c4Sjoerg   if (Entry)
394*e038c9c4Sjoerg     return *Entry;
3957330f729Sjoerg 
3967330f729Sjoerg   // Nope, create a new Cache entry.
3977330f729Sjoerg   Entry = ContentCacheAlloc.Allocate<ContentCache>();
3987330f729Sjoerg 
3997330f729Sjoerg   if (OverriddenFilesInfo) {
4007330f729Sjoerg     // If the file contents are overridden with contents from another file,
4017330f729Sjoerg     // pass that file to ContentCache.
4027330f729Sjoerg     llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
4037330f729Sjoerg         overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
4047330f729Sjoerg     if (overI == OverriddenFilesInfo->OverriddenFiles.end())
4057330f729Sjoerg       new (Entry) ContentCache(FileEnt);
4067330f729Sjoerg     else
4077330f729Sjoerg       new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
4087330f729Sjoerg                                                               : overI->second,
4097330f729Sjoerg                                overI->second);
4107330f729Sjoerg   } else {
4117330f729Sjoerg     new (Entry) ContentCache(FileEnt);
4127330f729Sjoerg   }
4137330f729Sjoerg 
4147330f729Sjoerg   Entry->IsFileVolatile = UserFilesAreVolatile && !isSystemFile;
4157330f729Sjoerg   Entry->IsTransient = FilesAreTransient;
416*e038c9c4Sjoerg   Entry->BufferOverridden |= FileEnt.isNamedPipe();
4177330f729Sjoerg 
418*e038c9c4Sjoerg   return *Entry;
4197330f729Sjoerg }
4207330f729Sjoerg 
4217330f729Sjoerg /// Create a new ContentCache for the specified memory buffer.
4227330f729Sjoerg /// This does no caching.
createMemBufferContentCache(std::unique_ptr<llvm::MemoryBuffer> Buffer)423*e038c9c4Sjoerg ContentCache &SourceManager::createMemBufferContentCache(
424*e038c9c4Sjoerg     std::unique_ptr<llvm::MemoryBuffer> Buffer) {
4257330f729Sjoerg   // Add a new ContentCache to the MemBufferInfos list and return it.
4267330f729Sjoerg   ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
4277330f729Sjoerg   new (Entry) ContentCache();
4287330f729Sjoerg   MemBufferInfos.push_back(Entry);
429*e038c9c4Sjoerg   Entry->setBuffer(std::move(Buffer));
430*e038c9c4Sjoerg   return *Entry;
4317330f729Sjoerg }
4327330f729Sjoerg 
loadSLocEntry(unsigned Index,bool * Invalid) const4337330f729Sjoerg const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
4347330f729Sjoerg                                                       bool *Invalid) const {
4357330f729Sjoerg   assert(!SLocEntryLoaded[Index]);
4367330f729Sjoerg   if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
4377330f729Sjoerg     if (Invalid)
4387330f729Sjoerg       *Invalid = true;
4397330f729Sjoerg     // If the file of the SLocEntry changed we could still have loaded it.
4407330f729Sjoerg     if (!SLocEntryLoaded[Index]) {
4417330f729Sjoerg       // Try to recover; create a SLocEntry so the rest of clang can handle it.
442*e038c9c4Sjoerg       if (!FakeSLocEntryForRecovery)
443*e038c9c4Sjoerg         FakeSLocEntryForRecovery = std::make_unique<SLocEntry>(SLocEntry::get(
4447330f729Sjoerg             0, FileInfo::get(SourceLocation(), getFakeContentCacheForRecovery(),
445*e038c9c4Sjoerg                              SrcMgr::C_User, "")));
446*e038c9c4Sjoerg       return *FakeSLocEntryForRecovery;
4477330f729Sjoerg     }
4487330f729Sjoerg   }
4497330f729Sjoerg 
4507330f729Sjoerg   return LoadedSLocEntryTable[Index];
4517330f729Sjoerg }
4527330f729Sjoerg 
4537330f729Sjoerg std::pair<int, unsigned>
AllocateLoadedSLocEntries(unsigned NumSLocEntries,unsigned TotalSize)4547330f729Sjoerg SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
4557330f729Sjoerg                                          unsigned TotalSize) {
4567330f729Sjoerg   assert(ExternalSLocEntries && "Don't have an external sloc source");
4577330f729Sjoerg   // Make sure we're not about to run out of source locations.
4587330f729Sjoerg   if (CurrentLoadedOffset - TotalSize < NextLocalOffset)
4597330f729Sjoerg     return std::make_pair(0, 0);
4607330f729Sjoerg   LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
4617330f729Sjoerg   SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
4627330f729Sjoerg   CurrentLoadedOffset -= TotalSize;
4637330f729Sjoerg   int ID = LoadedSLocEntryTable.size();
4647330f729Sjoerg   return std::make_pair(-ID - 1, CurrentLoadedOffset);
4657330f729Sjoerg }
4667330f729Sjoerg 
4677330f729Sjoerg /// As part of recovering from missing or changed content, produce a
4687330f729Sjoerg /// fake, non-empty buffer.
getFakeBufferForRecovery() const469*e038c9c4Sjoerg llvm::MemoryBufferRef SourceManager::getFakeBufferForRecovery() const {
4707330f729Sjoerg   if (!FakeBufferForRecovery)
4717330f729Sjoerg     FakeBufferForRecovery =
4727330f729Sjoerg         llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
4737330f729Sjoerg 
474*e038c9c4Sjoerg   return *FakeBufferForRecovery;
4757330f729Sjoerg }
4767330f729Sjoerg 
4777330f729Sjoerg /// As part of recovering from missing or changed content, produce a
4787330f729Sjoerg /// fake content cache.
getFakeContentCacheForRecovery() const479*e038c9c4Sjoerg SrcMgr::ContentCache &SourceManager::getFakeContentCacheForRecovery() const {
4807330f729Sjoerg   if (!FakeContentCacheForRecovery) {
4817330f729Sjoerg     FakeContentCacheForRecovery = std::make_unique<SrcMgr::ContentCache>();
482*e038c9c4Sjoerg     FakeContentCacheForRecovery->setUnownedBuffer(getFakeBufferForRecovery());
4837330f729Sjoerg   }
484*e038c9c4Sjoerg   return *FakeContentCacheForRecovery;
4857330f729Sjoerg }
4867330f729Sjoerg 
4877330f729Sjoerg /// Returns the previous in-order FileID or an invalid FileID if there
4887330f729Sjoerg /// is no previous one.
getPreviousFileID(FileID FID) const4897330f729Sjoerg FileID SourceManager::getPreviousFileID(FileID FID) const {
4907330f729Sjoerg   if (FID.isInvalid())
4917330f729Sjoerg     return FileID();
4927330f729Sjoerg 
4937330f729Sjoerg   int ID = FID.ID;
4947330f729Sjoerg   if (ID == -1)
4957330f729Sjoerg     return FileID();
4967330f729Sjoerg 
4977330f729Sjoerg   if (ID > 0) {
4987330f729Sjoerg     if (ID-1 == 0)
4997330f729Sjoerg       return FileID();
5007330f729Sjoerg   } else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {
5017330f729Sjoerg     return FileID();
5027330f729Sjoerg   }
5037330f729Sjoerg 
5047330f729Sjoerg   return FileID::get(ID-1);
5057330f729Sjoerg }
5067330f729Sjoerg 
5077330f729Sjoerg /// Returns the next in-order FileID or an invalid FileID if there is
5087330f729Sjoerg /// no next one.
getNextFileID(FileID FID) const5097330f729Sjoerg FileID SourceManager::getNextFileID(FileID FID) const {
5107330f729Sjoerg   if (FID.isInvalid())
5117330f729Sjoerg     return FileID();
5127330f729Sjoerg 
5137330f729Sjoerg   int ID = FID.ID;
5147330f729Sjoerg   if (ID > 0) {
5157330f729Sjoerg     if (unsigned(ID+1) >= local_sloc_entry_size())
5167330f729Sjoerg       return FileID();
5177330f729Sjoerg   } else if (ID+1 >= -1) {
5187330f729Sjoerg     return FileID();
5197330f729Sjoerg   }
5207330f729Sjoerg 
5217330f729Sjoerg   return FileID::get(ID+1);
5227330f729Sjoerg }
5237330f729Sjoerg 
5247330f729Sjoerg //===----------------------------------------------------------------------===//
5257330f729Sjoerg // Methods to create new FileID's and macro expansions.
5267330f729Sjoerg //===----------------------------------------------------------------------===//
5277330f729Sjoerg 
528*e038c9c4Sjoerg /// Create a new FileID that represents the specified file
529*e038c9c4Sjoerg /// being \#included from the specified IncludePosition.
530*e038c9c4Sjoerg ///
531*e038c9c4Sjoerg /// This translates NULL into standard input.
createFileID(const FileEntry * SourceFile,SourceLocation IncludePos,SrcMgr::CharacteristicKind FileCharacter,int LoadedID,unsigned LoadedOffset)532*e038c9c4Sjoerg FileID SourceManager::createFileID(const FileEntry *SourceFile,
533*e038c9c4Sjoerg                                    SourceLocation IncludePos,
534*e038c9c4Sjoerg                                    SrcMgr::CharacteristicKind FileCharacter,
535*e038c9c4Sjoerg                                    int LoadedID, unsigned LoadedOffset) {
536*e038c9c4Sjoerg   return createFileID(SourceFile->getLastRef(), IncludePos, FileCharacter,
537*e038c9c4Sjoerg                       LoadedID, LoadedOffset);
538*e038c9c4Sjoerg }
539*e038c9c4Sjoerg 
createFileID(FileEntryRef SourceFile,SourceLocation IncludePos,SrcMgr::CharacteristicKind FileCharacter,int LoadedID,unsigned LoadedOffset)540*e038c9c4Sjoerg FileID SourceManager::createFileID(FileEntryRef SourceFile,
541*e038c9c4Sjoerg                                    SourceLocation IncludePos,
542*e038c9c4Sjoerg                                    SrcMgr::CharacteristicKind FileCharacter,
543*e038c9c4Sjoerg                                    int LoadedID, unsigned LoadedOffset) {
544*e038c9c4Sjoerg   SrcMgr::ContentCache &IR = getOrCreateContentCache(SourceFile,
545*e038c9c4Sjoerg                                                      isSystem(FileCharacter));
546*e038c9c4Sjoerg 
547*e038c9c4Sjoerg   // If this is a named pipe, immediately load the buffer to ensure subsequent
548*e038c9c4Sjoerg   // calls to ContentCache::getSize() are accurate.
549*e038c9c4Sjoerg   if (IR.ContentsEntry->isNamedPipe())
550*e038c9c4Sjoerg     (void)IR.getBufferOrNone(Diag, getFileManager(), SourceLocation());
551*e038c9c4Sjoerg 
552*e038c9c4Sjoerg   return createFileIDImpl(IR, SourceFile.getName(), IncludePos, FileCharacter,
553*e038c9c4Sjoerg                           LoadedID, LoadedOffset);
554*e038c9c4Sjoerg }
555*e038c9c4Sjoerg 
556*e038c9c4Sjoerg /// Create a new FileID that represents the specified memory buffer.
557*e038c9c4Sjoerg ///
558*e038c9c4Sjoerg /// This does no caching of the buffer and takes ownership of the
559*e038c9c4Sjoerg /// MemoryBuffer, so only pass a MemoryBuffer to this once.
createFileID(std::unique_ptr<llvm::MemoryBuffer> Buffer,SrcMgr::CharacteristicKind FileCharacter,int LoadedID,unsigned LoadedOffset,SourceLocation IncludeLoc)560*e038c9c4Sjoerg FileID SourceManager::createFileID(std::unique_ptr<llvm::MemoryBuffer> Buffer,
561*e038c9c4Sjoerg                                    SrcMgr::CharacteristicKind FileCharacter,
562*e038c9c4Sjoerg                                    int LoadedID, unsigned LoadedOffset,
563*e038c9c4Sjoerg                                    SourceLocation IncludeLoc) {
564*e038c9c4Sjoerg   StringRef Name = Buffer->getBufferIdentifier();
565*e038c9c4Sjoerg   return createFileIDImpl(createMemBufferContentCache(std::move(Buffer)), Name,
566*e038c9c4Sjoerg                           IncludeLoc, FileCharacter, LoadedID, LoadedOffset);
567*e038c9c4Sjoerg }
568*e038c9c4Sjoerg 
569*e038c9c4Sjoerg /// Create a new FileID that represents the specified memory buffer.
570*e038c9c4Sjoerg ///
571*e038c9c4Sjoerg /// This does not take ownership of the MemoryBuffer. The memory buffer must
572*e038c9c4Sjoerg /// outlive the SourceManager.
createFileID(const llvm::MemoryBufferRef & Buffer,SrcMgr::CharacteristicKind FileCharacter,int LoadedID,unsigned LoadedOffset,SourceLocation IncludeLoc)573*e038c9c4Sjoerg FileID SourceManager::createFileID(const llvm::MemoryBufferRef &Buffer,
574*e038c9c4Sjoerg                                    SrcMgr::CharacteristicKind FileCharacter,
575*e038c9c4Sjoerg                                    int LoadedID, unsigned LoadedOffset,
576*e038c9c4Sjoerg                                    SourceLocation IncludeLoc) {
577*e038c9c4Sjoerg   return createFileID(llvm::MemoryBuffer::getMemBuffer(Buffer), FileCharacter,
578*e038c9c4Sjoerg                       LoadedID, LoadedOffset, IncludeLoc);
579*e038c9c4Sjoerg }
580*e038c9c4Sjoerg 
581*e038c9c4Sjoerg /// Get the FileID for \p SourceFile if it exists. Otherwise, create a
582*e038c9c4Sjoerg /// new FileID for the \p SourceFile.
583*e038c9c4Sjoerg FileID
getOrCreateFileID(const FileEntry * SourceFile,SrcMgr::CharacteristicKind FileCharacter)584*e038c9c4Sjoerg SourceManager::getOrCreateFileID(const FileEntry *SourceFile,
585*e038c9c4Sjoerg                                  SrcMgr::CharacteristicKind FileCharacter) {
586*e038c9c4Sjoerg   FileID ID = translateFile(SourceFile);
587*e038c9c4Sjoerg   return ID.isValid() ? ID : createFileID(SourceFile, SourceLocation(),
588*e038c9c4Sjoerg 					  FileCharacter);
589*e038c9c4Sjoerg }
590*e038c9c4Sjoerg 
5917330f729Sjoerg /// createFileID - Create a new FileID for the specified ContentCache and
5927330f729Sjoerg /// include position.  This works regardless of whether the ContentCache
5937330f729Sjoerg /// corresponds to a file or some other input source.
createFileIDImpl(ContentCache & File,StringRef Filename,SourceLocation IncludePos,SrcMgr::CharacteristicKind FileCharacter,int LoadedID,unsigned LoadedOffset)594*e038c9c4Sjoerg FileID SourceManager::createFileIDImpl(ContentCache &File, StringRef Filename,
5957330f729Sjoerg                                        SourceLocation IncludePos,
5967330f729Sjoerg                                        SrcMgr::CharacteristicKind FileCharacter,
5977330f729Sjoerg                                        int LoadedID, unsigned LoadedOffset) {
5987330f729Sjoerg   if (LoadedID < 0) {
5997330f729Sjoerg     assert(LoadedID != -1 && "Loading sentinel FileID");
6007330f729Sjoerg     unsigned Index = unsigned(-LoadedID) - 2;
6017330f729Sjoerg     assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
6027330f729Sjoerg     assert(!SLocEntryLoaded[Index] && "FileID already loaded");
6037330f729Sjoerg     LoadedSLocEntryTable[Index] = SLocEntry::get(
6047330f729Sjoerg         LoadedOffset, FileInfo::get(IncludePos, File, FileCharacter, Filename));
6057330f729Sjoerg     SLocEntryLoaded[Index] = true;
6067330f729Sjoerg     return FileID::get(LoadedID);
6077330f729Sjoerg   }
608*e038c9c4Sjoerg   unsigned FileSize = File.getSize();
609*e038c9c4Sjoerg   if (!(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
610*e038c9c4Sjoerg         NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset)) {
611*e038c9c4Sjoerg     Diag.Report(IncludePos, diag::err_include_too_large);
612*e038c9c4Sjoerg     return FileID();
613*e038c9c4Sjoerg   }
6147330f729Sjoerg   LocalSLocEntryTable.push_back(
6157330f729Sjoerg       SLocEntry::get(NextLocalOffset,
6167330f729Sjoerg                      FileInfo::get(IncludePos, File, FileCharacter, Filename)));
6177330f729Sjoerg   // We do a +1 here because we want a SourceLocation that means "the end of the
6187330f729Sjoerg   // file", e.g. for the "no newline at the end of the file" diagnostic.
6197330f729Sjoerg   NextLocalOffset += FileSize + 1;
6207330f729Sjoerg 
6217330f729Sjoerg   // Set LastFileIDLookup to the newly created file.  The next getFileID call is
6227330f729Sjoerg   // almost guaranteed to be from that file.
6237330f729Sjoerg   FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
6247330f729Sjoerg   return LastFileIDLookup = FID;
6257330f729Sjoerg }
6267330f729Sjoerg 
6277330f729Sjoerg SourceLocation
createMacroArgExpansionLoc(SourceLocation SpellingLoc,SourceLocation ExpansionLoc,unsigned TokLength)6287330f729Sjoerg SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc,
6297330f729Sjoerg                                           SourceLocation ExpansionLoc,
6307330f729Sjoerg                                           unsigned TokLength) {
6317330f729Sjoerg   ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
6327330f729Sjoerg                                                         ExpansionLoc);
6337330f729Sjoerg   return createExpansionLocImpl(Info, TokLength);
6347330f729Sjoerg }
6357330f729Sjoerg 
6367330f729Sjoerg SourceLocation
createExpansionLoc(SourceLocation SpellingLoc,SourceLocation ExpansionLocStart,SourceLocation ExpansionLocEnd,unsigned TokLength,bool ExpansionIsTokenRange,int LoadedID,unsigned LoadedOffset)6377330f729Sjoerg SourceManager::createExpansionLoc(SourceLocation SpellingLoc,
6387330f729Sjoerg                                   SourceLocation ExpansionLocStart,
6397330f729Sjoerg                                   SourceLocation ExpansionLocEnd,
6407330f729Sjoerg                                   unsigned TokLength,
6417330f729Sjoerg                                   bool ExpansionIsTokenRange,
6427330f729Sjoerg                                   int LoadedID,
6437330f729Sjoerg                                   unsigned LoadedOffset) {
6447330f729Sjoerg   ExpansionInfo Info = ExpansionInfo::create(
6457330f729Sjoerg       SpellingLoc, ExpansionLocStart, ExpansionLocEnd, ExpansionIsTokenRange);
6467330f729Sjoerg   return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset);
6477330f729Sjoerg }
6487330f729Sjoerg 
createTokenSplitLoc(SourceLocation Spelling,SourceLocation TokenStart,SourceLocation TokenEnd)6497330f729Sjoerg SourceLocation SourceManager::createTokenSplitLoc(SourceLocation Spelling,
6507330f729Sjoerg                                                   SourceLocation TokenStart,
6517330f729Sjoerg                                                   SourceLocation TokenEnd) {
6527330f729Sjoerg   assert(getFileID(TokenStart) == getFileID(TokenEnd) &&
6537330f729Sjoerg          "token spans multiple files");
6547330f729Sjoerg   return createExpansionLocImpl(
6557330f729Sjoerg       ExpansionInfo::createForTokenSplit(Spelling, TokenStart, TokenEnd),
6567330f729Sjoerg       TokenEnd.getOffset() - TokenStart.getOffset());
6577330f729Sjoerg }
6587330f729Sjoerg 
6597330f729Sjoerg SourceLocation
createExpansionLocImpl(const ExpansionInfo & Info,unsigned TokLength,int LoadedID,unsigned LoadedOffset)6607330f729Sjoerg SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
6617330f729Sjoerg                                       unsigned TokLength,
6627330f729Sjoerg                                       int LoadedID,
6637330f729Sjoerg                                       unsigned LoadedOffset) {
6647330f729Sjoerg   if (LoadedID < 0) {
6657330f729Sjoerg     assert(LoadedID != -1 && "Loading sentinel FileID");
6667330f729Sjoerg     unsigned Index = unsigned(-LoadedID) - 2;
6677330f729Sjoerg     assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
6687330f729Sjoerg     assert(!SLocEntryLoaded[Index] && "FileID already loaded");
6697330f729Sjoerg     LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
6707330f729Sjoerg     SLocEntryLoaded[Index] = true;
6717330f729Sjoerg     return SourceLocation::getMacroLoc(LoadedOffset);
6727330f729Sjoerg   }
6737330f729Sjoerg   LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
6747330f729Sjoerg   assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&
6757330f729Sjoerg          NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&
6767330f729Sjoerg          "Ran out of source locations!");
6777330f729Sjoerg   // See createFileID for that +1.
6787330f729Sjoerg   NextLocalOffset += TokLength + 1;
6797330f729Sjoerg   return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
6807330f729Sjoerg }
6817330f729Sjoerg 
682*e038c9c4Sjoerg llvm::Optional<llvm::MemoryBufferRef>
getMemoryBufferForFileOrNone(const FileEntry * File)683*e038c9c4Sjoerg SourceManager::getMemoryBufferForFileOrNone(const FileEntry *File) {
684*e038c9c4Sjoerg   SrcMgr::ContentCache &IR = getOrCreateContentCache(File->getLastRef());
685*e038c9c4Sjoerg   return IR.getBufferOrNone(Diag, getFileManager(), SourceLocation());
6867330f729Sjoerg }
6877330f729Sjoerg 
overrideFileContents(const FileEntry * SourceFile,std::unique_ptr<llvm::MemoryBuffer> Buffer)688*e038c9c4Sjoerg void SourceManager::overrideFileContents(
689*e038c9c4Sjoerg     const FileEntry *SourceFile, std::unique_ptr<llvm::MemoryBuffer> Buffer) {
690*e038c9c4Sjoerg   SrcMgr::ContentCache &IR = getOrCreateContentCache(SourceFile->getLastRef());
6917330f729Sjoerg 
692*e038c9c4Sjoerg   IR.setBuffer(std::move(Buffer));
693*e038c9c4Sjoerg   IR.BufferOverridden = true;
6947330f729Sjoerg 
6957330f729Sjoerg   getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
6967330f729Sjoerg }
6977330f729Sjoerg 
overrideFileContents(const FileEntry * SourceFile,const FileEntry * NewFile)6987330f729Sjoerg void SourceManager::overrideFileContents(const FileEntry *SourceFile,
6997330f729Sjoerg                                          const FileEntry *NewFile) {
7007330f729Sjoerg   assert(SourceFile->getSize() == NewFile->getSize() &&
7017330f729Sjoerg          "Different sizes, use the FileManager to create a virtual file with "
7027330f729Sjoerg          "the correct size");
7037330f729Sjoerg   assert(FileInfos.count(SourceFile) == 0 &&
7047330f729Sjoerg          "This function should be called at the initialization stage, before "
7057330f729Sjoerg          "any parsing occurs.");
7067330f729Sjoerg   getOverriddenFilesInfo().OverriddenFiles[SourceFile] = NewFile;
7077330f729Sjoerg }
7087330f729Sjoerg 
709*e038c9c4Sjoerg Optional<FileEntryRef>
bypassFileContentsOverride(FileEntryRef File)710*e038c9c4Sjoerg SourceManager::bypassFileContentsOverride(FileEntryRef File) {
711*e038c9c4Sjoerg   assert(isFileOverridden(&File.getFileEntry()));
712*e038c9c4Sjoerg   llvm::Optional<FileEntryRef> BypassFile = FileMgr.getBypassFile(File);
7137330f729Sjoerg 
7147330f729Sjoerg   // If the file can't be found in the FS, give up.
7157330f729Sjoerg   if (!BypassFile)
716*e038c9c4Sjoerg     return None;
7177330f729Sjoerg 
718*e038c9c4Sjoerg   (void)getOrCreateContentCache(*BypassFile);
719*e038c9c4Sjoerg   return BypassFile;
7207330f729Sjoerg }
7217330f729Sjoerg 
setFileIsTransient(const FileEntry * File)7227330f729Sjoerg void SourceManager::setFileIsTransient(const FileEntry *File) {
723*e038c9c4Sjoerg   getOrCreateContentCache(File->getLastRef()).IsTransient = true;
724*e038c9c4Sjoerg }
725*e038c9c4Sjoerg 
726*e038c9c4Sjoerg Optional<StringRef>
getNonBuiltinFilenameForID(FileID FID) const727*e038c9c4Sjoerg SourceManager::getNonBuiltinFilenameForID(FileID FID) const {
728*e038c9c4Sjoerg   if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID))
729*e038c9c4Sjoerg     if (Entry->getFile().getContentCache().OrigEntry)
730*e038c9c4Sjoerg       return Entry->getFile().getName();
731*e038c9c4Sjoerg   return None;
7327330f729Sjoerg }
7337330f729Sjoerg 
getBufferData(FileID FID,bool * Invalid) const7347330f729Sjoerg StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
735*e038c9c4Sjoerg   auto B = getBufferDataOrNone(FID);
7367330f729Sjoerg   if (Invalid)
737*e038c9c4Sjoerg     *Invalid = !B;
738*e038c9c4Sjoerg   return B ? *B : "<<<<<INVALID SOURCE LOCATION>>>>>";
7397330f729Sjoerg }
7407330f729Sjoerg 
741*e038c9c4Sjoerg llvm::Optional<StringRef>
getBufferDataIfLoaded(FileID FID) const742*e038c9c4Sjoerg SourceManager::getBufferDataIfLoaded(FileID FID) const {
743*e038c9c4Sjoerg   if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID))
744*e038c9c4Sjoerg     return Entry->getFile().getContentCache().getBufferDataIfLoaded();
745*e038c9c4Sjoerg   return None;
746*e038c9c4Sjoerg }
7477330f729Sjoerg 
getBufferDataOrNone(FileID FID) const748*e038c9c4Sjoerg llvm::Optional<StringRef> SourceManager::getBufferDataOrNone(FileID FID) const {
749*e038c9c4Sjoerg   if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID))
750*e038c9c4Sjoerg     if (auto B = Entry->getFile().getContentCache().getBufferOrNone(
751*e038c9c4Sjoerg             Diag, getFileManager(), SourceLocation()))
752*e038c9c4Sjoerg       return B->getBuffer();
753*e038c9c4Sjoerg   return None;
7547330f729Sjoerg }
7557330f729Sjoerg 
7567330f729Sjoerg //===----------------------------------------------------------------------===//
7577330f729Sjoerg // SourceLocation manipulation methods.
7587330f729Sjoerg //===----------------------------------------------------------------------===//
7597330f729Sjoerg 
7607330f729Sjoerg /// Return the FileID for a SourceLocation.
7617330f729Sjoerg ///
7627330f729Sjoerg /// This is the cache-miss path of getFileID. Not as hot as that function, but
7637330f729Sjoerg /// still very important. It is responsible for finding the entry in the
7647330f729Sjoerg /// SLocEntry tables that contains the specified location.
getFileIDSlow(unsigned SLocOffset) const7657330f729Sjoerg FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
7667330f729Sjoerg   if (!SLocOffset)
7677330f729Sjoerg     return FileID::get(0);
7687330f729Sjoerg 
7697330f729Sjoerg   // Now it is time to search for the correct file. See where the SLocOffset
7707330f729Sjoerg   // sits in the global view and consult local or loaded buffers for it.
7717330f729Sjoerg   if (SLocOffset < NextLocalOffset)
7727330f729Sjoerg     return getFileIDLocal(SLocOffset);
7737330f729Sjoerg   return getFileIDLoaded(SLocOffset);
7747330f729Sjoerg }
7757330f729Sjoerg 
7767330f729Sjoerg /// Return the FileID for a SourceLocation with a low offset.
7777330f729Sjoerg ///
7787330f729Sjoerg /// This function knows that the SourceLocation is in a local buffer, not a
7797330f729Sjoerg /// loaded one.
getFileIDLocal(unsigned SLocOffset) const7807330f729Sjoerg FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const {
7817330f729Sjoerg   assert(SLocOffset < NextLocalOffset && "Bad function choice");
7827330f729Sjoerg 
7837330f729Sjoerg   // After the first and second level caches, I see two common sorts of
7847330f729Sjoerg   // behavior: 1) a lot of searched FileID's are "near" the cached file
7857330f729Sjoerg   // location or are "near" the cached expansion location. 2) others are just
7867330f729Sjoerg   // completely random and may be a very long way away.
7877330f729Sjoerg   //
7887330f729Sjoerg   // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
7897330f729Sjoerg   // then we fall back to a less cache efficient, but more scalable, binary
7907330f729Sjoerg   // search to find the location.
7917330f729Sjoerg 
7927330f729Sjoerg   // See if this is near the file point - worst case we start scanning from the
7937330f729Sjoerg   // most newly created FileID.
7947330f729Sjoerg   const SrcMgr::SLocEntry *I;
7957330f729Sjoerg 
7967330f729Sjoerg   if (LastFileIDLookup.ID < 0 ||
7977330f729Sjoerg       LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
7987330f729Sjoerg     // Neither loc prunes our search.
7997330f729Sjoerg     I = LocalSLocEntryTable.end();
8007330f729Sjoerg   } else {
8017330f729Sjoerg     // Perhaps it is near the file point.
8027330f729Sjoerg     I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
8037330f729Sjoerg   }
8047330f729Sjoerg 
8057330f729Sjoerg   // Find the FileID that contains this.  "I" is an iterator that points to a
8067330f729Sjoerg   // FileID whose offset is known to be larger than SLocOffset.
8077330f729Sjoerg   unsigned NumProbes = 0;
8087330f729Sjoerg   while (true) {
8097330f729Sjoerg     --I;
8107330f729Sjoerg     if (I->getOffset() <= SLocOffset) {
8117330f729Sjoerg       FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
812*e038c9c4Sjoerg       // Remember it.  We have good locality across FileID lookups.
8137330f729Sjoerg       LastFileIDLookup = Res;
8147330f729Sjoerg       NumLinearScans += NumProbes+1;
8157330f729Sjoerg       return Res;
8167330f729Sjoerg     }
8177330f729Sjoerg     if (++NumProbes == 8)
8187330f729Sjoerg       break;
8197330f729Sjoerg   }
8207330f729Sjoerg 
8217330f729Sjoerg   // Convert "I" back into an index.  We know that it is an entry whose index is
8227330f729Sjoerg   // larger than the offset we are looking for.
8237330f729Sjoerg   unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
8247330f729Sjoerg   // LessIndex - This is the lower bound of the range that we're searching.
8257330f729Sjoerg   // We know that the offset corresponding to the FileID is is less than
8267330f729Sjoerg   // SLocOffset.
8277330f729Sjoerg   unsigned LessIndex = 0;
8287330f729Sjoerg   NumProbes = 0;
8297330f729Sjoerg   while (true) {
8307330f729Sjoerg     unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
831*e038c9c4Sjoerg     unsigned MidOffset = getLocalSLocEntry(MiddleIndex).getOffset();
8327330f729Sjoerg 
8337330f729Sjoerg     ++NumProbes;
8347330f729Sjoerg 
8357330f729Sjoerg     // If the offset of the midpoint is too large, chop the high side of the
8367330f729Sjoerg     // range to the midpoint.
8377330f729Sjoerg     if (MidOffset > SLocOffset) {
8387330f729Sjoerg       GreaterIndex = MiddleIndex;
8397330f729Sjoerg       continue;
8407330f729Sjoerg     }
8417330f729Sjoerg 
8427330f729Sjoerg     // If the middle index contains the value, succeed and return.
843*e038c9c4Sjoerg     if (MiddleIndex + 1 == LocalSLocEntryTable.size() ||
844*e038c9c4Sjoerg         SLocOffset < getLocalSLocEntry(MiddleIndex + 1).getOffset()) {
8457330f729Sjoerg       FileID Res = FileID::get(MiddleIndex);
8467330f729Sjoerg 
847*e038c9c4Sjoerg       // Remember it.  We have good locality across FileID lookups.
8487330f729Sjoerg       LastFileIDLookup = Res;
8497330f729Sjoerg       NumBinaryProbes += NumProbes;
8507330f729Sjoerg       return Res;
8517330f729Sjoerg     }
8527330f729Sjoerg 
8537330f729Sjoerg     // Otherwise, move the low-side up to the middle index.
8547330f729Sjoerg     LessIndex = MiddleIndex;
8557330f729Sjoerg   }
8567330f729Sjoerg }
8577330f729Sjoerg 
8587330f729Sjoerg /// Return the FileID for a SourceLocation with a high offset.
8597330f729Sjoerg ///
8607330f729Sjoerg /// This function knows that the SourceLocation is in a loaded buffer, not a
8617330f729Sjoerg /// local one.
getFileIDLoaded(unsigned SLocOffset) const8627330f729Sjoerg FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
8637330f729Sjoerg   // Sanity checking, otherwise a bug may lead to hanging in release build.
8647330f729Sjoerg   if (SLocOffset < CurrentLoadedOffset) {
8657330f729Sjoerg     assert(0 && "Invalid SLocOffset or bad function choice");
8667330f729Sjoerg     return FileID();
8677330f729Sjoerg   }
8687330f729Sjoerg 
8697330f729Sjoerg   // Essentially the same as the local case, but the loaded array is sorted
8707330f729Sjoerg   // in the other direction.
8717330f729Sjoerg 
8727330f729Sjoerg   // First do a linear scan from the last lookup position, if possible.
8737330f729Sjoerg   unsigned I;
8747330f729Sjoerg   int LastID = LastFileIDLookup.ID;
8757330f729Sjoerg   if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
8767330f729Sjoerg     I = 0;
8777330f729Sjoerg   else
8787330f729Sjoerg     I = (-LastID - 2) + 1;
8797330f729Sjoerg 
8807330f729Sjoerg   unsigned NumProbes;
8817330f729Sjoerg   for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
8827330f729Sjoerg     // Make sure the entry is loaded!
8837330f729Sjoerg     const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
8847330f729Sjoerg     if (E.getOffset() <= SLocOffset) {
8857330f729Sjoerg       FileID Res = FileID::get(-int(I) - 2);
8867330f729Sjoerg       LastFileIDLookup = Res;
8877330f729Sjoerg       NumLinearScans += NumProbes + 1;
8887330f729Sjoerg       return Res;
8897330f729Sjoerg     }
8907330f729Sjoerg   }
8917330f729Sjoerg 
8927330f729Sjoerg   // Linear scan failed. Do the binary search. Note the reverse sorting of the
8937330f729Sjoerg   // table: GreaterIndex is the one where the offset is greater, which is
8947330f729Sjoerg   // actually a lower index!
8957330f729Sjoerg   unsigned GreaterIndex = I;
8967330f729Sjoerg   unsigned LessIndex = LoadedSLocEntryTable.size();
8977330f729Sjoerg   NumProbes = 0;
8987330f729Sjoerg   while (true) {
8997330f729Sjoerg     ++NumProbes;
9007330f729Sjoerg     unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
9017330f729Sjoerg     const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
9027330f729Sjoerg     if (E.getOffset() == 0)
9037330f729Sjoerg       return FileID(); // invalid entry.
9047330f729Sjoerg 
9057330f729Sjoerg     ++NumProbes;
9067330f729Sjoerg 
9077330f729Sjoerg     if (E.getOffset() > SLocOffset) {
9087330f729Sjoerg       // Sanity checking, otherwise a bug may lead to hanging in release build.
9097330f729Sjoerg       if (GreaterIndex == MiddleIndex) {
9107330f729Sjoerg         assert(0 && "binary search missed the entry");
9117330f729Sjoerg         return FileID();
9127330f729Sjoerg       }
9137330f729Sjoerg       GreaterIndex = MiddleIndex;
9147330f729Sjoerg       continue;
9157330f729Sjoerg     }
9167330f729Sjoerg 
9177330f729Sjoerg     if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
9187330f729Sjoerg       FileID Res = FileID::get(-int(MiddleIndex) - 2);
9197330f729Sjoerg       LastFileIDLookup = Res;
9207330f729Sjoerg       NumBinaryProbes += NumProbes;
9217330f729Sjoerg       return Res;
9227330f729Sjoerg     }
9237330f729Sjoerg 
9247330f729Sjoerg     // Sanity checking, otherwise a bug may lead to hanging in release build.
9257330f729Sjoerg     if (LessIndex == MiddleIndex) {
9267330f729Sjoerg       assert(0 && "binary search missed the entry");
9277330f729Sjoerg       return FileID();
9287330f729Sjoerg     }
9297330f729Sjoerg     LessIndex = MiddleIndex;
9307330f729Sjoerg   }
9317330f729Sjoerg }
9327330f729Sjoerg 
9337330f729Sjoerg SourceLocation SourceManager::
getExpansionLocSlowCase(SourceLocation Loc) const9347330f729Sjoerg getExpansionLocSlowCase(SourceLocation Loc) const {
9357330f729Sjoerg   do {
9367330f729Sjoerg     // Note: If Loc indicates an offset into a token that came from a macro
9377330f729Sjoerg     // expansion (e.g. the 5th character of the token) we do not want to add
9387330f729Sjoerg     // this offset when going to the expansion location.  The expansion
9397330f729Sjoerg     // location is the macro invocation, which the offset has nothing to do
9407330f729Sjoerg     // with.  This is unlike when we get the spelling loc, because the offset
9417330f729Sjoerg     // directly correspond to the token whose spelling we're inspecting.
9427330f729Sjoerg     Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
9437330f729Sjoerg   } while (!Loc.isFileID());
9447330f729Sjoerg 
9457330f729Sjoerg   return Loc;
9467330f729Sjoerg }
9477330f729Sjoerg 
getSpellingLocSlowCase(SourceLocation Loc) const9487330f729Sjoerg SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
9497330f729Sjoerg   do {
9507330f729Sjoerg     std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
9517330f729Sjoerg     Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
9527330f729Sjoerg     Loc = Loc.getLocWithOffset(LocInfo.second);
9537330f729Sjoerg   } while (!Loc.isFileID());
9547330f729Sjoerg   return Loc;
9557330f729Sjoerg }
9567330f729Sjoerg 
getFileLocSlowCase(SourceLocation Loc) const9577330f729Sjoerg SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
9587330f729Sjoerg   do {
9597330f729Sjoerg     if (isMacroArgExpansion(Loc))
9607330f729Sjoerg       Loc = getImmediateSpellingLoc(Loc);
9617330f729Sjoerg     else
9627330f729Sjoerg       Loc = getImmediateExpansionRange(Loc).getBegin();
9637330f729Sjoerg   } while (!Loc.isFileID());
9647330f729Sjoerg   return Loc;
9657330f729Sjoerg }
9667330f729Sjoerg 
9677330f729Sjoerg 
9687330f729Sjoerg std::pair<FileID, unsigned>
getDecomposedExpansionLocSlowCase(const SrcMgr::SLocEntry * E) const9697330f729Sjoerg SourceManager::getDecomposedExpansionLocSlowCase(
9707330f729Sjoerg                                              const SrcMgr::SLocEntry *E) const {
9717330f729Sjoerg   // If this is an expansion record, walk through all the expansion points.
9727330f729Sjoerg   FileID FID;
9737330f729Sjoerg   SourceLocation Loc;
9747330f729Sjoerg   unsigned Offset;
9757330f729Sjoerg   do {
9767330f729Sjoerg     Loc = E->getExpansion().getExpansionLocStart();
9777330f729Sjoerg 
9787330f729Sjoerg     FID = getFileID(Loc);
9797330f729Sjoerg     E = &getSLocEntry(FID);
9807330f729Sjoerg     Offset = Loc.getOffset()-E->getOffset();
9817330f729Sjoerg   } while (!Loc.isFileID());
9827330f729Sjoerg 
9837330f729Sjoerg   return std::make_pair(FID, Offset);
9847330f729Sjoerg }
9857330f729Sjoerg 
9867330f729Sjoerg std::pair<FileID, unsigned>
getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry * E,unsigned Offset) const9877330f729Sjoerg SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
9887330f729Sjoerg                                                 unsigned Offset) const {
9897330f729Sjoerg   // If this is an expansion record, walk through all the expansion points.
9907330f729Sjoerg   FileID FID;
9917330f729Sjoerg   SourceLocation Loc;
9927330f729Sjoerg   do {
9937330f729Sjoerg     Loc = E->getExpansion().getSpellingLoc();
9947330f729Sjoerg     Loc = Loc.getLocWithOffset(Offset);
9957330f729Sjoerg 
9967330f729Sjoerg     FID = getFileID(Loc);
9977330f729Sjoerg     E = &getSLocEntry(FID);
9987330f729Sjoerg     Offset = Loc.getOffset()-E->getOffset();
9997330f729Sjoerg   } while (!Loc.isFileID());
10007330f729Sjoerg 
10017330f729Sjoerg   return std::make_pair(FID, Offset);
10027330f729Sjoerg }
10037330f729Sjoerg 
10047330f729Sjoerg /// getImmediateSpellingLoc - Given a SourceLocation object, return the
10057330f729Sjoerg /// spelling location referenced by the ID.  This is the first level down
10067330f729Sjoerg /// towards the place where the characters that make up the lexed token can be
10077330f729Sjoerg /// found.  This should not generally be used by clients.
getImmediateSpellingLoc(SourceLocation Loc) const10087330f729Sjoerg SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
10097330f729Sjoerg   if (Loc.isFileID()) return Loc;
10107330f729Sjoerg   std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
10117330f729Sjoerg   Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
10127330f729Sjoerg   return Loc.getLocWithOffset(LocInfo.second);
10137330f729Sjoerg }
10147330f729Sjoerg 
1015*e038c9c4Sjoerg /// Return the filename of the file containing a SourceLocation.
getFilename(SourceLocation SpellingLoc) const1016*e038c9c4Sjoerg StringRef SourceManager::getFilename(SourceLocation SpellingLoc) const {
1017*e038c9c4Sjoerg   if (const FileEntry *F = getFileEntryForID(getFileID(SpellingLoc)))
1018*e038c9c4Sjoerg     return F->getName();
1019*e038c9c4Sjoerg   return StringRef();
1020*e038c9c4Sjoerg }
1021*e038c9c4Sjoerg 
10227330f729Sjoerg /// getImmediateExpansionRange - Loc is required to be an expansion location.
10237330f729Sjoerg /// Return the start/end of the expansion information.
10247330f729Sjoerg CharSourceRange
getImmediateExpansionRange(SourceLocation Loc) const10257330f729Sjoerg SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
10267330f729Sjoerg   assert(Loc.isMacroID() && "Not a macro expansion loc!");
10277330f729Sjoerg   const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
10287330f729Sjoerg   return Expansion.getExpansionLocRange();
10297330f729Sjoerg }
10307330f729Sjoerg 
getTopMacroCallerLoc(SourceLocation Loc) const10317330f729Sjoerg SourceLocation SourceManager::getTopMacroCallerLoc(SourceLocation Loc) const {
10327330f729Sjoerg   while (isMacroArgExpansion(Loc))
10337330f729Sjoerg     Loc = getImmediateSpellingLoc(Loc);
10347330f729Sjoerg   return Loc;
10357330f729Sjoerg }
10367330f729Sjoerg 
10377330f729Sjoerg /// getExpansionRange - Given a SourceLocation object, return the range of
10387330f729Sjoerg /// tokens covered by the expansion in the ultimate file.
getExpansionRange(SourceLocation Loc) const10397330f729Sjoerg CharSourceRange SourceManager::getExpansionRange(SourceLocation Loc) const {
10407330f729Sjoerg   if (Loc.isFileID())
10417330f729Sjoerg     return CharSourceRange(SourceRange(Loc, Loc), true);
10427330f729Sjoerg 
10437330f729Sjoerg   CharSourceRange Res = getImmediateExpansionRange(Loc);
10447330f729Sjoerg 
10457330f729Sjoerg   // Fully resolve the start and end locations to their ultimate expansion
10467330f729Sjoerg   // points.
10477330f729Sjoerg   while (!Res.getBegin().isFileID())
10487330f729Sjoerg     Res.setBegin(getImmediateExpansionRange(Res.getBegin()).getBegin());
10497330f729Sjoerg   while (!Res.getEnd().isFileID()) {
10507330f729Sjoerg     CharSourceRange EndRange = getImmediateExpansionRange(Res.getEnd());
10517330f729Sjoerg     Res.setEnd(EndRange.getEnd());
10527330f729Sjoerg     Res.setTokenRange(EndRange.isTokenRange());
10537330f729Sjoerg   }
10547330f729Sjoerg   return Res;
10557330f729Sjoerg }
10567330f729Sjoerg 
isMacroArgExpansion(SourceLocation Loc,SourceLocation * StartLoc) const10577330f729Sjoerg bool SourceManager::isMacroArgExpansion(SourceLocation Loc,
10587330f729Sjoerg                                         SourceLocation *StartLoc) const {
10597330f729Sjoerg   if (!Loc.isMacroID()) return false;
10607330f729Sjoerg 
10617330f729Sjoerg   FileID FID = getFileID(Loc);
10627330f729Sjoerg   const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
10637330f729Sjoerg   if (!Expansion.isMacroArgExpansion()) return false;
10647330f729Sjoerg 
10657330f729Sjoerg   if (StartLoc)
10667330f729Sjoerg     *StartLoc = Expansion.getExpansionLocStart();
10677330f729Sjoerg   return true;
10687330f729Sjoerg }
10697330f729Sjoerg 
isMacroBodyExpansion(SourceLocation Loc) const10707330f729Sjoerg bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const {
10717330f729Sjoerg   if (!Loc.isMacroID()) return false;
10727330f729Sjoerg 
10737330f729Sjoerg   FileID FID = getFileID(Loc);
10747330f729Sjoerg   const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
10757330f729Sjoerg   return Expansion.isMacroBodyExpansion();
10767330f729Sjoerg }
10777330f729Sjoerg 
isAtStartOfImmediateMacroExpansion(SourceLocation Loc,SourceLocation * MacroBegin) const10787330f729Sjoerg bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
10797330f729Sjoerg                                              SourceLocation *MacroBegin) const {
10807330f729Sjoerg   assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
10817330f729Sjoerg 
10827330f729Sjoerg   std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);
10837330f729Sjoerg   if (DecompLoc.second > 0)
10847330f729Sjoerg     return false; // Does not point at the start of expansion range.
10857330f729Sjoerg 
10867330f729Sjoerg   bool Invalid = false;
10877330f729Sjoerg   const SrcMgr::ExpansionInfo &ExpInfo =
10887330f729Sjoerg       getSLocEntry(DecompLoc.first, &Invalid).getExpansion();
10897330f729Sjoerg   if (Invalid)
10907330f729Sjoerg     return false;
10917330f729Sjoerg   SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();
10927330f729Sjoerg 
10937330f729Sjoerg   if (ExpInfo.isMacroArgExpansion()) {
10947330f729Sjoerg     // For macro argument expansions, check if the previous FileID is part of
10957330f729Sjoerg     // the same argument expansion, in which case this Loc is not at the
10967330f729Sjoerg     // beginning of the expansion.
10977330f729Sjoerg     FileID PrevFID = getPreviousFileID(DecompLoc.first);
10987330f729Sjoerg     if (!PrevFID.isInvalid()) {
10997330f729Sjoerg       const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);
11007330f729Sjoerg       if (Invalid)
11017330f729Sjoerg         return false;
11027330f729Sjoerg       if (PrevEntry.isExpansion() &&
11037330f729Sjoerg           PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)
11047330f729Sjoerg         return false;
11057330f729Sjoerg     }
11067330f729Sjoerg   }
11077330f729Sjoerg 
11087330f729Sjoerg   if (MacroBegin)
11097330f729Sjoerg     *MacroBegin = ExpLoc;
11107330f729Sjoerg   return true;
11117330f729Sjoerg }
11127330f729Sjoerg 
isAtEndOfImmediateMacroExpansion(SourceLocation Loc,SourceLocation * MacroEnd) const11137330f729Sjoerg bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
11147330f729Sjoerg                                                SourceLocation *MacroEnd) const {
11157330f729Sjoerg   assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
11167330f729Sjoerg 
11177330f729Sjoerg   FileID FID = getFileID(Loc);
11187330f729Sjoerg   SourceLocation NextLoc = Loc.getLocWithOffset(1);
11197330f729Sjoerg   if (isInFileID(NextLoc, FID))
11207330f729Sjoerg     return false; // Does not point at the end of expansion range.
11217330f729Sjoerg 
11227330f729Sjoerg   bool Invalid = false;
11237330f729Sjoerg   const SrcMgr::ExpansionInfo &ExpInfo =
11247330f729Sjoerg       getSLocEntry(FID, &Invalid).getExpansion();
11257330f729Sjoerg   if (Invalid)
11267330f729Sjoerg     return false;
11277330f729Sjoerg 
11287330f729Sjoerg   if (ExpInfo.isMacroArgExpansion()) {
11297330f729Sjoerg     // For macro argument expansions, check if the next FileID is part of the
11307330f729Sjoerg     // same argument expansion, in which case this Loc is not at the end of the
11317330f729Sjoerg     // expansion.
11327330f729Sjoerg     FileID NextFID = getNextFileID(FID);
11337330f729Sjoerg     if (!NextFID.isInvalid()) {
11347330f729Sjoerg       const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);
11357330f729Sjoerg       if (Invalid)
11367330f729Sjoerg         return false;
11377330f729Sjoerg       if (NextEntry.isExpansion() &&
11387330f729Sjoerg           NextEntry.getExpansion().getExpansionLocStart() ==
11397330f729Sjoerg               ExpInfo.getExpansionLocStart())
11407330f729Sjoerg         return false;
11417330f729Sjoerg     }
11427330f729Sjoerg   }
11437330f729Sjoerg 
11447330f729Sjoerg   if (MacroEnd)
11457330f729Sjoerg     *MacroEnd = ExpInfo.getExpansionLocEnd();
11467330f729Sjoerg   return true;
11477330f729Sjoerg }
11487330f729Sjoerg 
11497330f729Sjoerg //===----------------------------------------------------------------------===//
11507330f729Sjoerg // Queries about the code at a SourceLocation.
11517330f729Sjoerg //===----------------------------------------------------------------------===//
11527330f729Sjoerg 
11537330f729Sjoerg /// getCharacterData - Return a pointer to the start of the specified location
11547330f729Sjoerg /// in the appropriate MemoryBuffer.
getCharacterData(SourceLocation SL,bool * Invalid) const11557330f729Sjoerg const char *SourceManager::getCharacterData(SourceLocation SL,
11567330f729Sjoerg                                             bool *Invalid) const {
11577330f729Sjoerg   // Note that this is a hot function in the getSpelling() path, which is
11587330f729Sjoerg   // heavily used by -E mode.
11597330f729Sjoerg   std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
11607330f729Sjoerg 
11617330f729Sjoerg   // Note that calling 'getBuffer()' may lazily page in a source file.
11627330f729Sjoerg   bool CharDataInvalid = false;
11637330f729Sjoerg   const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
11647330f729Sjoerg   if (CharDataInvalid || !Entry.isFile()) {
11657330f729Sjoerg     if (Invalid)
11667330f729Sjoerg       *Invalid = true;
11677330f729Sjoerg 
11687330f729Sjoerg     return "<<<<INVALID BUFFER>>>>";
11697330f729Sjoerg   }
1170*e038c9c4Sjoerg   llvm::Optional<llvm::MemoryBufferRef> Buffer =
1171*e038c9c4Sjoerg       Entry.getFile().getContentCache().getBufferOrNone(Diag, getFileManager(),
1172*e038c9c4Sjoerg                                                         SourceLocation());
11737330f729Sjoerg   if (Invalid)
1174*e038c9c4Sjoerg     *Invalid = !Buffer;
1175*e038c9c4Sjoerg   return Buffer ? Buffer->getBufferStart() + LocInfo.second
1176*e038c9c4Sjoerg                 : "<<<<INVALID BUFFER>>>>";
11777330f729Sjoerg }
11787330f729Sjoerg 
11797330f729Sjoerg /// getColumnNumber - Return the column # for the specified file position.
11807330f729Sjoerg /// this is significantly cheaper to compute than the line number.
getColumnNumber(FileID FID,unsigned FilePos,bool * Invalid) const11817330f729Sjoerg unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
11827330f729Sjoerg                                         bool *Invalid) const {
1183*e038c9c4Sjoerg   llvm::Optional<llvm::MemoryBufferRef> MemBuf = getBufferOrNone(FID);
11847330f729Sjoerg   if (Invalid)
1185*e038c9c4Sjoerg     *Invalid = !MemBuf;
11867330f729Sjoerg 
1187*e038c9c4Sjoerg   if (!MemBuf)
11887330f729Sjoerg     return 1;
11897330f729Sjoerg 
11907330f729Sjoerg   // It is okay to request a position just past the end of the buffer.
11917330f729Sjoerg   if (FilePos > MemBuf->getBufferSize()) {
11927330f729Sjoerg     if (Invalid)
11937330f729Sjoerg       *Invalid = true;
11947330f729Sjoerg     return 1;
11957330f729Sjoerg   }
11967330f729Sjoerg 
11977330f729Sjoerg   const char *Buf = MemBuf->getBufferStart();
11987330f729Sjoerg   // See if we just calculated the line number for this FilePos and can use
11997330f729Sjoerg   // that to lookup the start of the line instead of searching for it.
1200*e038c9c4Sjoerg   if (LastLineNoFileIDQuery == FID && LastLineNoContentCache->SourceLineCache &&
1201*e038c9c4Sjoerg       LastLineNoResult < LastLineNoContentCache->SourceLineCache.size()) {
1202*e038c9c4Sjoerg     const unsigned *SourceLineCache =
1203*e038c9c4Sjoerg         LastLineNoContentCache->SourceLineCache.begin();
12047330f729Sjoerg     unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
12057330f729Sjoerg     unsigned LineEnd = SourceLineCache[LastLineNoResult];
12067330f729Sjoerg     if (FilePos >= LineStart && FilePos < LineEnd) {
12077330f729Sjoerg       // LineEnd is the LineStart of the next line.
12087330f729Sjoerg       // A line ends with separator LF or CR+LF on Windows.
12097330f729Sjoerg       // FilePos might point to the last separator,
12107330f729Sjoerg       // but we need a column number at most 1 + the last column.
12117330f729Sjoerg       if (FilePos + 1 == LineEnd && FilePos > LineStart) {
12127330f729Sjoerg         if (Buf[FilePos - 1] == '\r' || Buf[FilePos - 1] == '\n')
12137330f729Sjoerg           --FilePos;
12147330f729Sjoerg       }
12157330f729Sjoerg       return FilePos - LineStart + 1;
12167330f729Sjoerg     }
12177330f729Sjoerg   }
12187330f729Sjoerg 
12197330f729Sjoerg   unsigned LineStart = FilePos;
12207330f729Sjoerg   while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
12217330f729Sjoerg     --LineStart;
12227330f729Sjoerg   return FilePos-LineStart+1;
12237330f729Sjoerg }
12247330f729Sjoerg 
12257330f729Sjoerg // isInvalid - Return the result of calling loc.isInvalid(), and
12267330f729Sjoerg // if Invalid is not null, set its value to same.
12277330f729Sjoerg template<typename LocType>
isInvalid(LocType Loc,bool * Invalid)12287330f729Sjoerg static bool isInvalid(LocType Loc, bool *Invalid) {
12297330f729Sjoerg   bool MyInvalid = Loc.isInvalid();
12307330f729Sjoerg   if (Invalid)
12317330f729Sjoerg     *Invalid = MyInvalid;
12327330f729Sjoerg   return MyInvalid;
12337330f729Sjoerg }
12347330f729Sjoerg 
getSpellingColumnNumber(SourceLocation Loc,bool * Invalid) const12357330f729Sjoerg unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
12367330f729Sjoerg                                                 bool *Invalid) const {
12377330f729Sjoerg   if (isInvalid(Loc, Invalid)) return 0;
12387330f729Sjoerg   std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
12397330f729Sjoerg   return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
12407330f729Sjoerg }
12417330f729Sjoerg 
getExpansionColumnNumber(SourceLocation Loc,bool * Invalid) const12427330f729Sjoerg unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
12437330f729Sjoerg                                                  bool *Invalid) const {
12447330f729Sjoerg   if (isInvalid(Loc, Invalid)) return 0;
12457330f729Sjoerg   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
12467330f729Sjoerg   return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
12477330f729Sjoerg }
12487330f729Sjoerg 
getPresumedColumnNumber(SourceLocation Loc,bool * Invalid) const12497330f729Sjoerg unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
12507330f729Sjoerg                                                 bool *Invalid) const {
12517330f729Sjoerg   PresumedLoc PLoc = getPresumedLoc(Loc);
12527330f729Sjoerg   if (isInvalid(PLoc, Invalid)) return 0;
12537330f729Sjoerg   return PLoc.getColumn();
12547330f729Sjoerg }
12557330f729Sjoerg 
1256*e038c9c4Sjoerg // Check if mutli-byte word x has bytes between m and n, included. This may also
1257*e038c9c4Sjoerg // catch bytes equal to n + 1.
1258*e038c9c4Sjoerg // The returned value holds a 0x80 at each byte position that holds a match.
1259*e038c9c4Sjoerg // see http://graphics.stanford.edu/~seander/bithacks.html#HasBetweenInWord
1260*e038c9c4Sjoerg template <class T>
likelyhasbetween(T x,unsigned char m,unsigned char n)1261*e038c9c4Sjoerg static constexpr inline T likelyhasbetween(T x, unsigned char m,
1262*e038c9c4Sjoerg                                            unsigned char n) {
1263*e038c9c4Sjoerg   return ((x - ~static_cast<T>(0) / 255 * (n + 1)) & ~x &
1264*e038c9c4Sjoerg           ((x & ~static_cast<T>(0) / 255 * 127) +
1265*e038c9c4Sjoerg            (~static_cast<T>(0) / 255 * (127 - (m - 1))))) &
1266*e038c9c4Sjoerg          ~static_cast<T>(0) / 255 * 128;
1267*e038c9c4Sjoerg }
12687330f729Sjoerg 
get(llvm::MemoryBufferRef Buffer,llvm::BumpPtrAllocator & Alloc)1269*e038c9c4Sjoerg LineOffsetMapping LineOffsetMapping::get(llvm::MemoryBufferRef Buffer,
1270*e038c9c4Sjoerg                                          llvm::BumpPtrAllocator &Alloc) {
12717330f729Sjoerg 
12727330f729Sjoerg   // Find the file offsets of all of the *physical* source lines.  This does
12737330f729Sjoerg   // not look at trigraphs, escaped newlines, or anything else tricky.
12747330f729Sjoerg   SmallVector<unsigned, 256> LineOffsets;
12757330f729Sjoerg 
12767330f729Sjoerg   // Line #1 starts at char 0.
12777330f729Sjoerg   LineOffsets.push_back(0);
12787330f729Sjoerg 
1279*e038c9c4Sjoerg   const unsigned char *Buf = (const unsigned char *)Buffer.getBufferStart();
1280*e038c9c4Sjoerg   const unsigned char *End = (const unsigned char *)Buffer.getBufferEnd();
1281*e038c9c4Sjoerg   const std::size_t BufLen = End - Buf;
12827330f729Sjoerg 
1283*e038c9c4Sjoerg   unsigned I = 0;
1284*e038c9c4Sjoerg   uint64_t Word;
1285*e038c9c4Sjoerg 
1286*e038c9c4Sjoerg   // scan sizeof(Word) bytes at a time for new lines.
1287*e038c9c4Sjoerg   // This is much faster than scanning each byte independently.
1288*e038c9c4Sjoerg   if (BufLen > sizeof(Word)) {
1289*e038c9c4Sjoerg     do {
1290*e038c9c4Sjoerg       Word = llvm::support::endian::read64(Buf + I, llvm::support::little);
1291*e038c9c4Sjoerg       // no new line => jump over sizeof(Word) bytes.
1292*e038c9c4Sjoerg       auto Mask = likelyhasbetween(Word, '\n', '\r');
1293*e038c9c4Sjoerg       if (!Mask) {
1294*e038c9c4Sjoerg         I += sizeof(Word);
1295*e038c9c4Sjoerg         continue;
1296*e038c9c4Sjoerg       }
1297*e038c9c4Sjoerg 
1298*e038c9c4Sjoerg       // At that point, Mask contains 0x80 set at each byte that holds a value
1299*e038c9c4Sjoerg       // in [\n, \r + 1 [
1300*e038c9c4Sjoerg 
1301*e038c9c4Sjoerg       // Scan for the next newline - it's very likely there's one.
1302*e038c9c4Sjoerg       unsigned N =
1303*e038c9c4Sjoerg           llvm::countTrailingZeros(Mask) - 7; // -7 because 0x80 is the marker
1304*e038c9c4Sjoerg       Word >>= N;
1305*e038c9c4Sjoerg       I += N / 8 + 1;
1306*e038c9c4Sjoerg       unsigned char Byte = Word;
1307*e038c9c4Sjoerg       if (Byte == '\n') {
1308*e038c9c4Sjoerg         LineOffsets.push_back(I);
1309*e038c9c4Sjoerg       } else if (Byte == '\r') {
13107330f729Sjoerg         // If this is \r\n, skip both characters.
1311*e038c9c4Sjoerg         if (Buf[I] == '\n')
13127330f729Sjoerg           ++I;
13137330f729Sjoerg         LineOffsets.push_back(I);
13147330f729Sjoerg       }
1315*e038c9c4Sjoerg     } while (I < BufLen - sizeof(Word) - 1);
13167330f729Sjoerg   }
13177330f729Sjoerg 
1318*e038c9c4Sjoerg   // Handle tail using a regular check.
1319*e038c9c4Sjoerg   while (I < BufLen) {
1320*e038c9c4Sjoerg     if (Buf[I] == '\n') {
1321*e038c9c4Sjoerg       LineOffsets.push_back(I + 1);
1322*e038c9c4Sjoerg     } else if (Buf[I] == '\r') {
1323*e038c9c4Sjoerg       // If this is \r\n, skip both characters.
1324*e038c9c4Sjoerg       if (I + 1 < BufLen && Buf[I + 1] == '\n')
1325*e038c9c4Sjoerg         ++I;
1326*e038c9c4Sjoerg       LineOffsets.push_back(I + 1);
1327*e038c9c4Sjoerg     }
1328*e038c9c4Sjoerg     ++I;
1329*e038c9c4Sjoerg   }
1330*e038c9c4Sjoerg 
1331*e038c9c4Sjoerg   return LineOffsetMapping(LineOffsets, Alloc);
1332*e038c9c4Sjoerg }
1333*e038c9c4Sjoerg 
LineOffsetMapping(ArrayRef<unsigned> LineOffsets,llvm::BumpPtrAllocator & Alloc)1334*e038c9c4Sjoerg LineOffsetMapping::LineOffsetMapping(ArrayRef<unsigned> LineOffsets,
1335*e038c9c4Sjoerg                                      llvm::BumpPtrAllocator &Alloc)
1336*e038c9c4Sjoerg     : Storage(Alloc.Allocate<unsigned>(LineOffsets.size() + 1)) {
1337*e038c9c4Sjoerg   Storage[0] = LineOffsets.size();
1338*e038c9c4Sjoerg   std::copy(LineOffsets.begin(), LineOffsets.end(), Storage + 1);
13397330f729Sjoerg }
13407330f729Sjoerg 
13417330f729Sjoerg /// getLineNumber - Given a SourceLocation, return the spelling line number
13427330f729Sjoerg /// for the position indicated.  This requires building and caching a table of
13437330f729Sjoerg /// line offsets for the MemoryBuffer, so this is not cheap: use only when
13447330f729Sjoerg /// about to emit a diagnostic.
getLineNumber(FileID FID,unsigned FilePos,bool * Invalid) const13457330f729Sjoerg unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
13467330f729Sjoerg                                       bool *Invalid) const {
13477330f729Sjoerg   if (FID.isInvalid()) {
13487330f729Sjoerg     if (Invalid)
13497330f729Sjoerg       *Invalid = true;
13507330f729Sjoerg     return 1;
13517330f729Sjoerg   }
13527330f729Sjoerg 
1353*e038c9c4Sjoerg   const ContentCache *Content;
13547330f729Sjoerg   if (LastLineNoFileIDQuery == FID)
13557330f729Sjoerg     Content = LastLineNoContentCache;
13567330f729Sjoerg   else {
13577330f729Sjoerg     bool MyInvalid = false;
13587330f729Sjoerg     const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
13597330f729Sjoerg     if (MyInvalid || !Entry.isFile()) {
13607330f729Sjoerg       if (Invalid)
13617330f729Sjoerg         *Invalid = true;
13627330f729Sjoerg       return 1;
13637330f729Sjoerg     }
13647330f729Sjoerg 
1365*e038c9c4Sjoerg     Content = &Entry.getFile().getContentCache();
13667330f729Sjoerg   }
13677330f729Sjoerg 
13687330f729Sjoerg   // If this is the first use of line information for this buffer, compute the
13697330f729Sjoerg   /// SourceLineCache for it on demand.
13707330f729Sjoerg   if (!Content->SourceLineCache) {
1371*e038c9c4Sjoerg     llvm::Optional<llvm::MemoryBufferRef> Buffer =
1372*e038c9c4Sjoerg         Content->getBufferOrNone(Diag, getFileManager(), SourceLocation());
13737330f729Sjoerg     if (Invalid)
1374*e038c9c4Sjoerg       *Invalid = !Buffer;
1375*e038c9c4Sjoerg     if (!Buffer)
13767330f729Sjoerg       return 1;
1377*e038c9c4Sjoerg 
1378*e038c9c4Sjoerg     Content->SourceLineCache =
1379*e038c9c4Sjoerg         LineOffsetMapping::get(*Buffer, ContentCacheAlloc);
13807330f729Sjoerg   } else if (Invalid)
13817330f729Sjoerg     *Invalid = false;
13827330f729Sjoerg 
13837330f729Sjoerg   // Okay, we know we have a line number table.  Do a binary search to find the
13847330f729Sjoerg   // line number that this character position lands on.
1385*e038c9c4Sjoerg   const unsigned *SourceLineCache = Content->SourceLineCache.begin();
1386*e038c9c4Sjoerg   const unsigned *SourceLineCacheStart = SourceLineCache;
1387*e038c9c4Sjoerg   const unsigned *SourceLineCacheEnd = Content->SourceLineCache.end();
13887330f729Sjoerg 
13897330f729Sjoerg   unsigned QueriedFilePos = FilePos+1;
13907330f729Sjoerg 
13917330f729Sjoerg   // FIXME: I would like to be convinced that this code is worth being as
13927330f729Sjoerg   // complicated as it is, binary search isn't that slow.
13937330f729Sjoerg   //
13947330f729Sjoerg   // If it is worth being optimized, then in my opinion it could be more
13957330f729Sjoerg   // performant, simpler, and more obviously correct by just "galloping" outward
13967330f729Sjoerg   // from the queried file position. In fact, this could be incorporated into a
13977330f729Sjoerg   // generic algorithm such as lower_bound_with_hint.
13987330f729Sjoerg   //
13997330f729Sjoerg   // If someone gives me a test case where this matters, and I will do it! - DWD
14007330f729Sjoerg 
14017330f729Sjoerg   // If the previous query was to the same file, we know both the file pos from
14027330f729Sjoerg   // that query and the line number returned.  This allows us to narrow the
14037330f729Sjoerg   // search space from the entire file to something near the match.
14047330f729Sjoerg   if (LastLineNoFileIDQuery == FID) {
14057330f729Sjoerg     if (QueriedFilePos >= LastLineNoFilePos) {
14067330f729Sjoerg       // FIXME: Potential overflow?
14077330f729Sjoerg       SourceLineCache = SourceLineCache+LastLineNoResult-1;
14087330f729Sjoerg 
14097330f729Sjoerg       // The query is likely to be nearby the previous one.  Here we check to
14107330f729Sjoerg       // see if it is within 5, 10 or 20 lines.  It can be far away in cases
14117330f729Sjoerg       // where big comment blocks and vertical whitespace eat up lines but
14127330f729Sjoerg       // contribute no tokens.
14137330f729Sjoerg       if (SourceLineCache+5 < SourceLineCacheEnd) {
14147330f729Sjoerg         if (SourceLineCache[5] > QueriedFilePos)
14157330f729Sjoerg           SourceLineCacheEnd = SourceLineCache+5;
14167330f729Sjoerg         else if (SourceLineCache+10 < SourceLineCacheEnd) {
14177330f729Sjoerg           if (SourceLineCache[10] > QueriedFilePos)
14187330f729Sjoerg             SourceLineCacheEnd = SourceLineCache+10;
14197330f729Sjoerg           else if (SourceLineCache+20 < SourceLineCacheEnd) {
14207330f729Sjoerg             if (SourceLineCache[20] > QueriedFilePos)
14217330f729Sjoerg               SourceLineCacheEnd = SourceLineCache+20;
14227330f729Sjoerg           }
14237330f729Sjoerg         }
14247330f729Sjoerg       }
14257330f729Sjoerg     } else {
1426*e038c9c4Sjoerg       if (LastLineNoResult < Content->SourceLineCache.size())
14277330f729Sjoerg         SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
14287330f729Sjoerg     }
14297330f729Sjoerg   }
14307330f729Sjoerg 
1431*e038c9c4Sjoerg   const unsigned *Pos =
1432*e038c9c4Sjoerg       std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
14337330f729Sjoerg   unsigned LineNo = Pos-SourceLineCacheStart;
14347330f729Sjoerg 
14357330f729Sjoerg   LastLineNoFileIDQuery = FID;
14367330f729Sjoerg   LastLineNoContentCache = Content;
14377330f729Sjoerg   LastLineNoFilePos = QueriedFilePos;
14387330f729Sjoerg   LastLineNoResult = LineNo;
14397330f729Sjoerg   return LineNo;
14407330f729Sjoerg }
14417330f729Sjoerg 
getSpellingLineNumber(SourceLocation Loc,bool * Invalid) const14427330f729Sjoerg unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
14437330f729Sjoerg                                               bool *Invalid) const {
14447330f729Sjoerg   if (isInvalid(Loc, Invalid)) return 0;
14457330f729Sjoerg   std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
14467330f729Sjoerg   return getLineNumber(LocInfo.first, LocInfo.second);
14477330f729Sjoerg }
getExpansionLineNumber(SourceLocation Loc,bool * Invalid) const14487330f729Sjoerg unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
14497330f729Sjoerg                                                bool *Invalid) const {
14507330f729Sjoerg   if (isInvalid(Loc, Invalid)) return 0;
14517330f729Sjoerg   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
14527330f729Sjoerg   return getLineNumber(LocInfo.first, LocInfo.second);
14537330f729Sjoerg }
getPresumedLineNumber(SourceLocation Loc,bool * Invalid) const14547330f729Sjoerg unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
14557330f729Sjoerg                                               bool *Invalid) const {
14567330f729Sjoerg   PresumedLoc PLoc = getPresumedLoc(Loc);
14577330f729Sjoerg   if (isInvalid(PLoc, Invalid)) return 0;
14587330f729Sjoerg   return PLoc.getLine();
14597330f729Sjoerg }
14607330f729Sjoerg 
14617330f729Sjoerg /// getFileCharacteristic - return the file characteristic of the specified
14627330f729Sjoerg /// source location, indicating whether this is a normal file, a system
14637330f729Sjoerg /// header, or an "implicit extern C" system header.
14647330f729Sjoerg ///
14657330f729Sjoerg /// This state can be modified with flags on GNU linemarker directives like:
14667330f729Sjoerg ///   # 4 "foo.h" 3
14677330f729Sjoerg /// which changes all source locations in the current file after that to be
14687330f729Sjoerg /// considered to be from a system header.
14697330f729Sjoerg SrcMgr::CharacteristicKind
getFileCharacteristic(SourceLocation Loc) const14707330f729Sjoerg SourceManager::getFileCharacteristic(SourceLocation Loc) const {
14717330f729Sjoerg   assert(Loc.isValid() && "Can't get file characteristic of invalid loc!");
14727330f729Sjoerg   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1473*e038c9c4Sjoerg   const SLocEntry *SEntry = getSLocEntryForFile(LocInfo.first);
1474*e038c9c4Sjoerg   if (!SEntry)
14757330f729Sjoerg     return C_User;
14767330f729Sjoerg 
1477*e038c9c4Sjoerg   const SrcMgr::FileInfo &FI = SEntry->getFile();
14787330f729Sjoerg 
14797330f729Sjoerg   // If there are no #line directives in this file, just return the whole-file
14807330f729Sjoerg   // state.
14817330f729Sjoerg   if (!FI.hasLineDirectives())
14827330f729Sjoerg     return FI.getFileCharacteristic();
14837330f729Sjoerg 
14847330f729Sjoerg   assert(LineTable && "Can't have linetable entries without a LineTable!");
14857330f729Sjoerg   // See if there is a #line directive before the location.
14867330f729Sjoerg   const LineEntry *Entry =
14877330f729Sjoerg     LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
14887330f729Sjoerg 
14897330f729Sjoerg   // If this is before the first line marker, use the file characteristic.
14907330f729Sjoerg   if (!Entry)
14917330f729Sjoerg     return FI.getFileCharacteristic();
14927330f729Sjoerg 
14937330f729Sjoerg   return Entry->FileKind;
14947330f729Sjoerg }
14957330f729Sjoerg 
14967330f729Sjoerg /// Return the filename or buffer identifier of the buffer the location is in.
14977330f729Sjoerg /// Note that this name does not respect \#line directives.  Use getPresumedLoc
14987330f729Sjoerg /// for normal clients.
getBufferName(SourceLocation Loc,bool * Invalid) const14997330f729Sjoerg StringRef SourceManager::getBufferName(SourceLocation Loc,
15007330f729Sjoerg                                        bool *Invalid) const {
15017330f729Sjoerg   if (isInvalid(Loc, Invalid)) return "<invalid loc>";
15027330f729Sjoerg 
1503*e038c9c4Sjoerg   auto B = getBufferOrNone(getFileID(Loc));
1504*e038c9c4Sjoerg   if (Invalid)
1505*e038c9c4Sjoerg     *Invalid = !B;
1506*e038c9c4Sjoerg   return B ? B->getBufferIdentifier() : "<invalid buffer>";
15077330f729Sjoerg }
15087330f729Sjoerg 
15097330f729Sjoerg /// getPresumedLoc - This method returns the "presumed" location of a
15107330f729Sjoerg /// SourceLocation specifies.  A "presumed location" can be modified by \#line
15117330f729Sjoerg /// or GNU line marker directives.  This provides a view on the data that a
15127330f729Sjoerg /// user should see in diagnostics, for example.
15137330f729Sjoerg ///
15147330f729Sjoerg /// Note that a presumed location is always given as the expansion point of an
15157330f729Sjoerg /// expansion location, not at the spelling location.
getPresumedLoc(SourceLocation Loc,bool UseLineDirectives) const15167330f729Sjoerg PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc,
15177330f729Sjoerg                                           bool UseLineDirectives) const {
15187330f729Sjoerg   if (Loc.isInvalid()) return PresumedLoc();
15197330f729Sjoerg 
15207330f729Sjoerg   // Presumed locations are always for expansion points.
15217330f729Sjoerg   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
15227330f729Sjoerg 
15237330f729Sjoerg   bool Invalid = false;
15247330f729Sjoerg   const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
15257330f729Sjoerg   if (Invalid || !Entry.isFile())
15267330f729Sjoerg     return PresumedLoc();
15277330f729Sjoerg 
15287330f729Sjoerg   const SrcMgr::FileInfo &FI = Entry.getFile();
1529*e038c9c4Sjoerg   const SrcMgr::ContentCache *C = &FI.getContentCache();
15307330f729Sjoerg 
15317330f729Sjoerg   // To get the source name, first consult the FileEntry (if one exists)
15327330f729Sjoerg   // before the MemBuffer as this will avoid unnecessarily paging in the
15337330f729Sjoerg   // MemBuffer.
15347330f729Sjoerg   FileID FID = LocInfo.first;
15357330f729Sjoerg   StringRef Filename;
15367330f729Sjoerg   if (C->OrigEntry)
15377330f729Sjoerg     Filename = C->OrigEntry->getName();
1538*e038c9c4Sjoerg   else if (auto Buffer = C->getBufferOrNone(Diag, getFileManager()))
1539*e038c9c4Sjoerg     Filename = Buffer->getBufferIdentifier();
15407330f729Sjoerg 
15417330f729Sjoerg   unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
15427330f729Sjoerg   if (Invalid)
15437330f729Sjoerg     return PresumedLoc();
15447330f729Sjoerg   unsigned ColNo  = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
15457330f729Sjoerg   if (Invalid)
15467330f729Sjoerg     return PresumedLoc();
15477330f729Sjoerg 
15487330f729Sjoerg   SourceLocation IncludeLoc = FI.getIncludeLoc();
15497330f729Sjoerg 
15507330f729Sjoerg   // If we have #line directives in this file, update and overwrite the physical
15517330f729Sjoerg   // location info if appropriate.
15527330f729Sjoerg   if (UseLineDirectives && FI.hasLineDirectives()) {
15537330f729Sjoerg     assert(LineTable && "Can't have linetable entries without a LineTable!");
15547330f729Sjoerg     // See if there is a #line directive before this.  If so, get it.
15557330f729Sjoerg     if (const LineEntry *Entry =
15567330f729Sjoerg           LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
15577330f729Sjoerg       // If the LineEntry indicates a filename, use it.
15587330f729Sjoerg       if (Entry->FilenameID != -1) {
15597330f729Sjoerg         Filename = LineTable->getFilename(Entry->FilenameID);
15607330f729Sjoerg         // The contents of files referenced by #line are not in the
15617330f729Sjoerg         // SourceManager
15627330f729Sjoerg         FID = FileID::get(0);
15637330f729Sjoerg       }
15647330f729Sjoerg 
15657330f729Sjoerg       // Use the line number specified by the LineEntry.  This line number may
15667330f729Sjoerg       // be multiple lines down from the line entry.  Add the difference in
15677330f729Sjoerg       // physical line numbers from the query point and the line marker to the
15687330f729Sjoerg       // total.
15697330f729Sjoerg       unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
15707330f729Sjoerg       LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
15717330f729Sjoerg 
15727330f729Sjoerg       // Note that column numbers are not molested by line markers.
15737330f729Sjoerg 
15747330f729Sjoerg       // Handle virtual #include manipulation.
15757330f729Sjoerg       if (Entry->IncludeOffset) {
15767330f729Sjoerg         IncludeLoc = getLocForStartOfFile(LocInfo.first);
15777330f729Sjoerg         IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
15787330f729Sjoerg       }
15797330f729Sjoerg     }
15807330f729Sjoerg   }
15817330f729Sjoerg 
15827330f729Sjoerg   return PresumedLoc(Filename.data(), FID, LineNo, ColNo, IncludeLoc);
15837330f729Sjoerg }
15847330f729Sjoerg 
15857330f729Sjoerg /// Returns whether the PresumedLoc for a given SourceLocation is
15867330f729Sjoerg /// in the main file.
15877330f729Sjoerg ///
15887330f729Sjoerg /// This computes the "presumed" location for a SourceLocation, then checks
15897330f729Sjoerg /// whether it came from a file other than the main file. This is different
15907330f729Sjoerg /// from isWrittenInMainFile() because it takes line marker directives into
15917330f729Sjoerg /// account.
isInMainFile(SourceLocation Loc) const15927330f729Sjoerg bool SourceManager::isInMainFile(SourceLocation Loc) const {
15937330f729Sjoerg   if (Loc.isInvalid()) return false;
15947330f729Sjoerg 
15957330f729Sjoerg   // Presumed locations are always for expansion points.
15967330f729Sjoerg   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
15977330f729Sjoerg 
1598*e038c9c4Sjoerg   const SLocEntry *Entry = getSLocEntryForFile(LocInfo.first);
1599*e038c9c4Sjoerg   if (!Entry)
16007330f729Sjoerg     return false;
16017330f729Sjoerg 
1602*e038c9c4Sjoerg   const SrcMgr::FileInfo &FI = Entry->getFile();
16037330f729Sjoerg 
16047330f729Sjoerg   // Check if there is a line directive for this location.
16057330f729Sjoerg   if (FI.hasLineDirectives())
16067330f729Sjoerg     if (const LineEntry *Entry =
16077330f729Sjoerg             LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
16087330f729Sjoerg       if (Entry->IncludeOffset)
16097330f729Sjoerg         return false;
16107330f729Sjoerg 
16117330f729Sjoerg   return FI.getIncludeLoc().isInvalid();
16127330f729Sjoerg }
16137330f729Sjoerg 
16147330f729Sjoerg /// The size of the SLocEntry that \p FID represents.
getFileIDSize(FileID FID) const16157330f729Sjoerg unsigned SourceManager::getFileIDSize(FileID FID) const {
16167330f729Sjoerg   bool Invalid = false;
16177330f729Sjoerg   const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
16187330f729Sjoerg   if (Invalid)
16197330f729Sjoerg     return 0;
16207330f729Sjoerg 
16217330f729Sjoerg   int ID = FID.ID;
16227330f729Sjoerg   unsigned NextOffset;
16237330f729Sjoerg   if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
16247330f729Sjoerg     NextOffset = getNextLocalOffset();
16257330f729Sjoerg   else if (ID+1 == -1)
16267330f729Sjoerg     NextOffset = MaxLoadedOffset;
16277330f729Sjoerg   else
16287330f729Sjoerg     NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
16297330f729Sjoerg 
16307330f729Sjoerg   return NextOffset - Entry.getOffset() - 1;
16317330f729Sjoerg }
16327330f729Sjoerg 
16337330f729Sjoerg //===----------------------------------------------------------------------===//
16347330f729Sjoerg // Other miscellaneous methods.
16357330f729Sjoerg //===----------------------------------------------------------------------===//
16367330f729Sjoerg 
16377330f729Sjoerg /// Get the source location for the given file:line:col triplet.
16387330f729Sjoerg ///
16397330f729Sjoerg /// If the source file is included multiple times, the source location will
16407330f729Sjoerg /// be based upon an arbitrary inclusion.
translateFileLineCol(const FileEntry * SourceFile,unsigned Line,unsigned Col) const16417330f729Sjoerg SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
16427330f729Sjoerg                                                   unsigned Line,
16437330f729Sjoerg                                                   unsigned Col) const {
16447330f729Sjoerg   assert(SourceFile && "Null source file!");
16457330f729Sjoerg   assert(Line && Col && "Line and column should start from 1!");
16467330f729Sjoerg 
16477330f729Sjoerg   FileID FirstFID = translateFile(SourceFile);
16487330f729Sjoerg   return translateLineCol(FirstFID, Line, Col);
16497330f729Sjoerg }
16507330f729Sjoerg 
16517330f729Sjoerg /// Get the FileID for the given file.
16527330f729Sjoerg ///
16537330f729Sjoerg /// If the source file is included multiple times, the FileID will be the
16547330f729Sjoerg /// first inclusion.
translateFile(const FileEntry * SourceFile) const16557330f729Sjoerg FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
16567330f729Sjoerg   assert(SourceFile && "Null source file!");
16577330f729Sjoerg 
16587330f729Sjoerg   // First, check the main file ID, since it is common to look for a
16597330f729Sjoerg   // location in the main file.
16607330f729Sjoerg   if (MainFileID.isValid()) {
16617330f729Sjoerg     bool Invalid = false;
16627330f729Sjoerg     const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
16637330f729Sjoerg     if (Invalid)
16647330f729Sjoerg       return FileID();
16657330f729Sjoerg 
16667330f729Sjoerg     if (MainSLoc.isFile()) {
1667*e038c9c4Sjoerg       if (MainSLoc.getFile().getContentCache().OrigEntry == SourceFile)
16687330f729Sjoerg         return MainFileID;
16697330f729Sjoerg     }
16707330f729Sjoerg   }
16717330f729Sjoerg 
16727330f729Sjoerg   // The location we're looking for isn't in the main file; look
16737330f729Sjoerg   // through all of the local source locations.
16747330f729Sjoerg   for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1675*e038c9c4Sjoerg     const SLocEntry &SLoc = getLocalSLocEntry(I);
1676*e038c9c4Sjoerg     if (SLoc.isFile() &&
1677*e038c9c4Sjoerg         SLoc.getFile().getContentCache().OrigEntry == SourceFile)
16787330f729Sjoerg       return FileID::get(I);
16797330f729Sjoerg   }
16807330f729Sjoerg 
16817330f729Sjoerg   // If that still didn't help, try the modules.
16827330f729Sjoerg   for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
16837330f729Sjoerg     const SLocEntry &SLoc = getLoadedSLocEntry(I);
1684*e038c9c4Sjoerg     if (SLoc.isFile() &&
1685*e038c9c4Sjoerg         SLoc.getFile().getContentCache().OrigEntry == SourceFile)
16867330f729Sjoerg       return FileID::get(-int(I) - 2);
16877330f729Sjoerg   }
16887330f729Sjoerg 
16897330f729Sjoerg   return FileID();
16907330f729Sjoerg }
16917330f729Sjoerg 
16927330f729Sjoerg /// Get the source location in \arg FID for the given line:col.
16937330f729Sjoerg /// Returns null location if \arg FID is not a file SLocEntry.
translateLineCol(FileID FID,unsigned Line,unsigned Col) const16947330f729Sjoerg SourceLocation SourceManager::translateLineCol(FileID FID,
16957330f729Sjoerg                                                unsigned Line,
16967330f729Sjoerg                                                unsigned Col) const {
16977330f729Sjoerg   // Lines are used as a one-based index into a zero-based array. This assert
16987330f729Sjoerg   // checks for possible buffer underruns.
16997330f729Sjoerg   assert(Line && Col && "Line and column should start from 1!");
17007330f729Sjoerg 
17017330f729Sjoerg   if (FID.isInvalid())
17027330f729Sjoerg     return SourceLocation();
17037330f729Sjoerg 
17047330f729Sjoerg   bool Invalid = false;
17057330f729Sjoerg   const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
17067330f729Sjoerg   if (Invalid)
17077330f729Sjoerg     return SourceLocation();
17087330f729Sjoerg 
17097330f729Sjoerg   if (!Entry.isFile())
17107330f729Sjoerg     return SourceLocation();
17117330f729Sjoerg 
17127330f729Sjoerg   SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
17137330f729Sjoerg 
17147330f729Sjoerg   if (Line == 1 && Col == 1)
17157330f729Sjoerg     return FileLoc;
17167330f729Sjoerg 
1717*e038c9c4Sjoerg   const ContentCache *Content = &Entry.getFile().getContentCache();
17187330f729Sjoerg 
17197330f729Sjoerg   // If this is the first use of line information for this buffer, compute the
17207330f729Sjoerg   // SourceLineCache for it on demand.
1721*e038c9c4Sjoerg   llvm::Optional<llvm::MemoryBufferRef> Buffer =
1722*e038c9c4Sjoerg       Content->getBufferOrNone(Diag, getFileManager());
1723*e038c9c4Sjoerg   if (!Buffer)
17247330f729Sjoerg     return SourceLocation();
1725*e038c9c4Sjoerg   if (!Content->SourceLineCache)
1726*e038c9c4Sjoerg     Content->SourceLineCache =
1727*e038c9c4Sjoerg         LineOffsetMapping::get(*Buffer, ContentCacheAlloc);
17287330f729Sjoerg 
1729*e038c9c4Sjoerg   if (Line > Content->SourceLineCache.size()) {
1730*e038c9c4Sjoerg     unsigned Size = Buffer->getBufferSize();
17317330f729Sjoerg     if (Size > 0)
17327330f729Sjoerg       --Size;
17337330f729Sjoerg     return FileLoc.getLocWithOffset(Size);
17347330f729Sjoerg   }
17357330f729Sjoerg 
17367330f729Sjoerg   unsigned FilePos = Content->SourceLineCache[Line - 1];
17377330f729Sjoerg   const char *Buf = Buffer->getBufferStart() + FilePos;
17387330f729Sjoerg   unsigned BufLength = Buffer->getBufferSize() - FilePos;
17397330f729Sjoerg   if (BufLength == 0)
17407330f729Sjoerg     return FileLoc.getLocWithOffset(FilePos);
17417330f729Sjoerg 
17427330f729Sjoerg   unsigned i = 0;
17437330f729Sjoerg 
17447330f729Sjoerg   // Check that the given column is valid.
17457330f729Sjoerg   while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
17467330f729Sjoerg     ++i;
17477330f729Sjoerg   return FileLoc.getLocWithOffset(FilePos + i);
17487330f729Sjoerg }
17497330f729Sjoerg 
17507330f729Sjoerg /// Compute a map of macro argument chunks to their expanded source
17517330f729Sjoerg /// location. Chunks that are not part of a macro argument will map to an
17527330f729Sjoerg /// invalid source location. e.g. if a file contains one macro argument at
17537330f729Sjoerg /// offset 100 with length 10, this is how the map will be formed:
17547330f729Sjoerg ///     0   -> SourceLocation()
17557330f729Sjoerg ///     100 -> Expanded macro arg location
17567330f729Sjoerg ///     110 -> SourceLocation()
computeMacroArgsCache(MacroArgsMap & MacroArgsCache,FileID FID) const17577330f729Sjoerg void SourceManager::computeMacroArgsCache(MacroArgsMap &MacroArgsCache,
17587330f729Sjoerg                                           FileID FID) const {
17597330f729Sjoerg   assert(FID.isValid());
17607330f729Sjoerg 
17617330f729Sjoerg   // Initially no macro argument chunk is present.
17627330f729Sjoerg   MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
17637330f729Sjoerg 
17647330f729Sjoerg   int ID = FID.ID;
17657330f729Sjoerg   while (true) {
17667330f729Sjoerg     ++ID;
17677330f729Sjoerg     // Stop if there are no more FileIDs to check.
17687330f729Sjoerg     if (ID > 0) {
17697330f729Sjoerg       if (unsigned(ID) >= local_sloc_entry_size())
17707330f729Sjoerg         return;
17717330f729Sjoerg     } else if (ID == -1) {
17727330f729Sjoerg       return;
17737330f729Sjoerg     }
17747330f729Sjoerg 
17757330f729Sjoerg     bool Invalid = false;
17767330f729Sjoerg     const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);
17777330f729Sjoerg     if (Invalid)
17787330f729Sjoerg       return;
17797330f729Sjoerg     if (Entry.isFile()) {
1780*e038c9c4Sjoerg       auto& File = Entry.getFile();
1781*e038c9c4Sjoerg       if (File.getFileCharacteristic() == C_User_ModuleMap ||
1782*e038c9c4Sjoerg           File.getFileCharacteristic() == C_System_ModuleMap)
17837330f729Sjoerg         continue;
17847330f729Sjoerg 
1785*e038c9c4Sjoerg       SourceLocation IncludeLoc = File.getIncludeLoc();
1786*e038c9c4Sjoerg       bool IncludedInFID =
1787*e038c9c4Sjoerg           (IncludeLoc.isValid() && isInFileID(IncludeLoc, FID)) ||
1788*e038c9c4Sjoerg           // Predefined header doesn't have a valid include location in main
1789*e038c9c4Sjoerg           // file, but any files created by it should still be skipped when
1790*e038c9c4Sjoerg           // computing macro args expanded in the main file.
1791*e038c9c4Sjoerg           (FID == MainFileID && Entry.getFile().getName() == "<built-in>");
1792*e038c9c4Sjoerg       if (IncludedInFID) {
1793*e038c9c4Sjoerg         // Skip the files/macros of the #include'd file, we only care about
1794*e038c9c4Sjoerg         // macros that lexed macro arguments from our file.
17957330f729Sjoerg         if (Entry.getFile().NumCreatedFIDs)
17967330f729Sjoerg           ID += Entry.getFile().NumCreatedFIDs - 1 /*because of next ++ID*/;
17977330f729Sjoerg         continue;
1798*e038c9c4Sjoerg       } else if (IncludeLoc.isValid()) {
1799*e038c9c4Sjoerg         // If file was included but not from FID, there is no more files/macros
1800*e038c9c4Sjoerg         // that may be "contained" in this file.
1801*e038c9c4Sjoerg         return;
1802*e038c9c4Sjoerg       }
1803*e038c9c4Sjoerg       continue;
18047330f729Sjoerg     }
18057330f729Sjoerg 
18067330f729Sjoerg     const ExpansionInfo &ExpInfo = Entry.getExpansion();
18077330f729Sjoerg 
18087330f729Sjoerg     if (ExpInfo.getExpansionLocStart().isFileID()) {
18097330f729Sjoerg       if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
18107330f729Sjoerg         return; // No more files/macros that may be "contained" in this file.
18117330f729Sjoerg     }
18127330f729Sjoerg 
18137330f729Sjoerg     if (!ExpInfo.isMacroArgExpansion())
18147330f729Sjoerg       continue;
18157330f729Sjoerg 
18167330f729Sjoerg     associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
18177330f729Sjoerg                                  ExpInfo.getSpellingLoc(),
18187330f729Sjoerg                                  SourceLocation::getMacroLoc(Entry.getOffset()),
18197330f729Sjoerg                                  getFileIDSize(FileID::get(ID)));
18207330f729Sjoerg   }
18217330f729Sjoerg }
18227330f729Sjoerg 
associateFileChunkWithMacroArgExp(MacroArgsMap & MacroArgsCache,FileID FID,SourceLocation SpellLoc,SourceLocation ExpansionLoc,unsigned ExpansionLength) const18237330f729Sjoerg void SourceManager::associateFileChunkWithMacroArgExp(
18247330f729Sjoerg                                          MacroArgsMap &MacroArgsCache,
18257330f729Sjoerg                                          FileID FID,
18267330f729Sjoerg                                          SourceLocation SpellLoc,
18277330f729Sjoerg                                          SourceLocation ExpansionLoc,
18287330f729Sjoerg                                          unsigned ExpansionLength) const {
18297330f729Sjoerg   if (!SpellLoc.isFileID()) {
18307330f729Sjoerg     unsigned SpellBeginOffs = SpellLoc.getOffset();
18317330f729Sjoerg     unsigned SpellEndOffs = SpellBeginOffs + ExpansionLength;
18327330f729Sjoerg 
18337330f729Sjoerg     // The spelling range for this macro argument expansion can span multiple
18347330f729Sjoerg     // consecutive FileID entries. Go through each entry contained in the
18357330f729Sjoerg     // spelling range and if one is itself a macro argument expansion, recurse
18367330f729Sjoerg     // and associate the file chunk that it represents.
18377330f729Sjoerg 
18387330f729Sjoerg     FileID SpellFID; // Current FileID in the spelling range.
18397330f729Sjoerg     unsigned SpellRelativeOffs;
18407330f729Sjoerg     std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);
18417330f729Sjoerg     while (true) {
18427330f729Sjoerg       const SLocEntry &Entry = getSLocEntry(SpellFID);
18437330f729Sjoerg       unsigned SpellFIDBeginOffs = Entry.getOffset();
18447330f729Sjoerg       unsigned SpellFIDSize = getFileIDSize(SpellFID);
18457330f729Sjoerg       unsigned SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;
18467330f729Sjoerg       const ExpansionInfo &Info = Entry.getExpansion();
18477330f729Sjoerg       if (Info.isMacroArgExpansion()) {
18487330f729Sjoerg         unsigned CurrSpellLength;
18497330f729Sjoerg         if (SpellFIDEndOffs < SpellEndOffs)
18507330f729Sjoerg           CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
18517330f729Sjoerg         else
18527330f729Sjoerg           CurrSpellLength = ExpansionLength;
18537330f729Sjoerg         associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
18547330f729Sjoerg                       Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),
18557330f729Sjoerg                       ExpansionLoc, CurrSpellLength);
18567330f729Sjoerg       }
18577330f729Sjoerg 
18587330f729Sjoerg       if (SpellFIDEndOffs >= SpellEndOffs)
18597330f729Sjoerg         return; // we covered all FileID entries in the spelling range.
18607330f729Sjoerg 
18617330f729Sjoerg       // Move to the next FileID entry in the spelling range.
18627330f729Sjoerg       unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
18637330f729Sjoerg       ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);
18647330f729Sjoerg       ExpansionLength -= advance;
18657330f729Sjoerg       ++SpellFID.ID;
18667330f729Sjoerg       SpellRelativeOffs = 0;
18677330f729Sjoerg     }
18687330f729Sjoerg   }
18697330f729Sjoerg 
18707330f729Sjoerg   assert(SpellLoc.isFileID());
18717330f729Sjoerg 
18727330f729Sjoerg   unsigned BeginOffs;
18737330f729Sjoerg   if (!isInFileID(SpellLoc, FID, &BeginOffs))
18747330f729Sjoerg     return;
18757330f729Sjoerg 
18767330f729Sjoerg   unsigned EndOffs = BeginOffs + ExpansionLength;
18777330f729Sjoerg 
18787330f729Sjoerg   // Add a new chunk for this macro argument. A previous macro argument chunk
18797330f729Sjoerg   // may have been lexed again, so e.g. if the map is
18807330f729Sjoerg   //     0   -> SourceLocation()
18817330f729Sjoerg   //     100 -> Expanded loc #1
18827330f729Sjoerg   //     110 -> SourceLocation()
18837330f729Sjoerg   // and we found a new macro FileID that lexed from offset 105 with length 3,
18847330f729Sjoerg   // the new map will be:
18857330f729Sjoerg   //     0   -> SourceLocation()
18867330f729Sjoerg   //     100 -> Expanded loc #1
18877330f729Sjoerg   //     105 -> Expanded loc #2
18887330f729Sjoerg   //     108 -> Expanded loc #1
18897330f729Sjoerg   //     110 -> SourceLocation()
18907330f729Sjoerg   //
18917330f729Sjoerg   // Since re-lexed macro chunks will always be the same size or less of
18927330f729Sjoerg   // previous chunks, we only need to find where the ending of the new macro
18937330f729Sjoerg   // chunk is mapped to and update the map with new begin/end mappings.
18947330f729Sjoerg 
18957330f729Sjoerg   MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
18967330f729Sjoerg   --I;
18977330f729Sjoerg   SourceLocation EndOffsMappedLoc = I->second;
18987330f729Sjoerg   MacroArgsCache[BeginOffs] = ExpansionLoc;
18997330f729Sjoerg   MacroArgsCache[EndOffs] = EndOffsMappedLoc;
19007330f729Sjoerg }
19017330f729Sjoerg 
19027330f729Sjoerg /// If \arg Loc points inside a function macro argument, the returned
19037330f729Sjoerg /// location will be the macro location in which the argument was expanded.
19047330f729Sjoerg /// If a macro argument is used multiple times, the expanded location will
19057330f729Sjoerg /// be at the first expansion of the argument.
19067330f729Sjoerg /// e.g.
19077330f729Sjoerg ///   MY_MACRO(foo);
19087330f729Sjoerg ///             ^
19097330f729Sjoerg /// Passing a file location pointing at 'foo', will yield a macro location
19107330f729Sjoerg /// where 'foo' was expanded into.
19117330f729Sjoerg SourceLocation
getMacroArgExpandedLocation(SourceLocation Loc) const19127330f729Sjoerg SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
19137330f729Sjoerg   if (Loc.isInvalid() || !Loc.isFileID())
19147330f729Sjoerg     return Loc;
19157330f729Sjoerg 
19167330f729Sjoerg   FileID FID;
19177330f729Sjoerg   unsigned Offset;
19187330f729Sjoerg   std::tie(FID, Offset) = getDecomposedLoc(Loc);
19197330f729Sjoerg   if (FID.isInvalid())
19207330f729Sjoerg     return Loc;
19217330f729Sjoerg 
19227330f729Sjoerg   std::unique_ptr<MacroArgsMap> &MacroArgsCache = MacroArgsCacheMap[FID];
19237330f729Sjoerg   if (!MacroArgsCache) {
19247330f729Sjoerg     MacroArgsCache = std::make_unique<MacroArgsMap>();
19257330f729Sjoerg     computeMacroArgsCache(*MacroArgsCache, FID);
19267330f729Sjoerg   }
19277330f729Sjoerg 
19287330f729Sjoerg   assert(!MacroArgsCache->empty());
19297330f729Sjoerg   MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
1930*e038c9c4Sjoerg   // In case every element in MacroArgsCache is greater than Offset we can't
1931*e038c9c4Sjoerg   // decrement the iterator.
1932*e038c9c4Sjoerg   if (I == MacroArgsCache->begin())
1933*e038c9c4Sjoerg     return Loc;
1934*e038c9c4Sjoerg 
19357330f729Sjoerg   --I;
19367330f729Sjoerg 
19377330f729Sjoerg   unsigned MacroArgBeginOffs = I->first;
19387330f729Sjoerg   SourceLocation MacroArgExpandedLoc = I->second;
19397330f729Sjoerg   if (MacroArgExpandedLoc.isValid())
19407330f729Sjoerg     return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
19417330f729Sjoerg 
19427330f729Sjoerg   return Loc;
19437330f729Sjoerg }
19447330f729Sjoerg 
19457330f729Sjoerg std::pair<FileID, unsigned>
getDecomposedIncludedLoc(FileID FID) const19467330f729Sjoerg SourceManager::getDecomposedIncludedLoc(FileID FID) const {
19477330f729Sjoerg   if (FID.isInvalid())
19487330f729Sjoerg     return std::make_pair(FileID(), 0);
19497330f729Sjoerg 
19507330f729Sjoerg   // Uses IncludedLocMap to retrieve/cache the decomposed loc.
19517330f729Sjoerg 
19527330f729Sjoerg   using DecompTy = std::pair<FileID, unsigned>;
19537330f729Sjoerg   auto InsertOp = IncludedLocMap.try_emplace(FID);
19547330f729Sjoerg   DecompTy &DecompLoc = InsertOp.first->second;
19557330f729Sjoerg   if (!InsertOp.second)
19567330f729Sjoerg     return DecompLoc; // already in map.
19577330f729Sjoerg 
19587330f729Sjoerg   SourceLocation UpperLoc;
19597330f729Sjoerg   bool Invalid = false;
19607330f729Sjoerg   const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
19617330f729Sjoerg   if (!Invalid) {
19627330f729Sjoerg     if (Entry.isExpansion())
19637330f729Sjoerg       UpperLoc = Entry.getExpansion().getExpansionLocStart();
19647330f729Sjoerg     else
19657330f729Sjoerg       UpperLoc = Entry.getFile().getIncludeLoc();
19667330f729Sjoerg   }
19677330f729Sjoerg 
19687330f729Sjoerg   if (UpperLoc.isValid())
19697330f729Sjoerg     DecompLoc = getDecomposedLoc(UpperLoc);
19707330f729Sjoerg 
19717330f729Sjoerg   return DecompLoc;
19727330f729Sjoerg }
19737330f729Sjoerg 
19747330f729Sjoerg /// Given a decomposed source location, move it up the include/expansion stack
19757330f729Sjoerg /// to the parent source location.  If this is possible, return the decomposed
19767330f729Sjoerg /// version of the parent in Loc and return false.  If Loc is the top-level
19777330f729Sjoerg /// entry, return true and don't modify it.
MoveUpIncludeHierarchy(std::pair<FileID,unsigned> & Loc,const SourceManager & SM)19787330f729Sjoerg static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
19797330f729Sjoerg                                    const SourceManager &SM) {
19807330f729Sjoerg   std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
19817330f729Sjoerg   if (UpperLoc.first.isInvalid())
19827330f729Sjoerg     return true; // We reached the top.
19837330f729Sjoerg 
19847330f729Sjoerg   Loc = UpperLoc;
19857330f729Sjoerg   return false;
19867330f729Sjoerg }
19877330f729Sjoerg 
19887330f729Sjoerg /// Return the cache entry for comparing the given file IDs
19897330f729Sjoerg /// for isBeforeInTranslationUnit.
getInBeforeInTUCache(FileID LFID,FileID RFID) const19907330f729Sjoerg InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
19917330f729Sjoerg                                                             FileID RFID) const {
19927330f729Sjoerg   // This is a magic number for limiting the cache size.  It was experimentally
19937330f729Sjoerg   // derived from a small Objective-C project (where the cache filled
19947330f729Sjoerg   // out to ~250 items).  We can make it larger if necessary.
19957330f729Sjoerg   enum { MagicCacheSize = 300 };
19967330f729Sjoerg   IsBeforeInTUCacheKey Key(LFID, RFID);
19977330f729Sjoerg 
19987330f729Sjoerg   // If the cache size isn't too large, do a lookup and if necessary default
19997330f729Sjoerg   // construct an entry.  We can then return it to the caller for direct
20007330f729Sjoerg   // use.  When they update the value, the cache will get automatically
20017330f729Sjoerg   // updated as well.
20027330f729Sjoerg   if (IBTUCache.size() < MagicCacheSize)
20037330f729Sjoerg     return IBTUCache[Key];
20047330f729Sjoerg 
20057330f729Sjoerg   // Otherwise, do a lookup that will not construct a new value.
20067330f729Sjoerg   InBeforeInTUCache::iterator I = IBTUCache.find(Key);
20077330f729Sjoerg   if (I != IBTUCache.end())
20087330f729Sjoerg     return I->second;
20097330f729Sjoerg 
20107330f729Sjoerg   // Fall back to the overflow value.
20117330f729Sjoerg   return IBTUCacheOverflow;
20127330f729Sjoerg }
20137330f729Sjoerg 
20147330f729Sjoerg /// Determines the order of 2 source locations in the translation unit.
20157330f729Sjoerg ///
20167330f729Sjoerg /// \returns true if LHS source location comes before RHS, false otherwise.
isBeforeInTranslationUnit(SourceLocation LHS,SourceLocation RHS) const20177330f729Sjoerg bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
20187330f729Sjoerg                                               SourceLocation RHS) const {
20197330f729Sjoerg   assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
20207330f729Sjoerg   if (LHS == RHS)
20217330f729Sjoerg     return false;
20227330f729Sjoerg 
20237330f729Sjoerg   std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
20247330f729Sjoerg   std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
20257330f729Sjoerg 
20267330f729Sjoerg   // getDecomposedLoc may have failed to return a valid FileID because, e.g. it
20277330f729Sjoerg   // is a serialized one referring to a file that was removed after we loaded
20287330f729Sjoerg   // the PCH.
20297330f729Sjoerg   if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
20307330f729Sjoerg     return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
20317330f729Sjoerg 
20327330f729Sjoerg   std::pair<bool, bool> InSameTU = isInTheSameTranslationUnit(LOffs, ROffs);
20337330f729Sjoerg   if (InSameTU.first)
20347330f729Sjoerg     return InSameTU.second;
20357330f729Sjoerg 
20367330f729Sjoerg   // If we arrived here, the location is either in a built-ins buffer or
20377330f729Sjoerg   // associated with global inline asm. PR5662 and PR22576 are examples.
20387330f729Sjoerg 
2039*e038c9c4Sjoerg   StringRef LB = getBufferOrFake(LOffs.first).getBufferIdentifier();
2040*e038c9c4Sjoerg   StringRef RB = getBufferOrFake(ROffs.first).getBufferIdentifier();
20417330f729Sjoerg   bool LIsBuiltins = LB == "<built-in>";
20427330f729Sjoerg   bool RIsBuiltins = RB == "<built-in>";
20437330f729Sjoerg   // Sort built-in before non-built-in.
20447330f729Sjoerg   if (LIsBuiltins || RIsBuiltins) {
20457330f729Sjoerg     if (LIsBuiltins != RIsBuiltins)
20467330f729Sjoerg       return LIsBuiltins;
20477330f729Sjoerg     // Both are in built-in buffers, but from different files. We just claim that
20487330f729Sjoerg     // lower IDs come first.
20497330f729Sjoerg     return LOffs.first < ROffs.first;
20507330f729Sjoerg   }
20517330f729Sjoerg   bool LIsAsm = LB == "<inline asm>";
20527330f729Sjoerg   bool RIsAsm = RB == "<inline asm>";
20537330f729Sjoerg   // Sort assembler after built-ins, but before the rest.
20547330f729Sjoerg   if (LIsAsm || RIsAsm) {
20557330f729Sjoerg     if (LIsAsm != RIsAsm)
20567330f729Sjoerg       return RIsAsm;
20577330f729Sjoerg     assert(LOffs.first == ROffs.first);
20587330f729Sjoerg     return false;
20597330f729Sjoerg   }
20607330f729Sjoerg   bool LIsScratch = LB == "<scratch space>";
20617330f729Sjoerg   bool RIsScratch = RB == "<scratch space>";
20627330f729Sjoerg   // Sort scratch after inline asm, but before the rest.
20637330f729Sjoerg   if (LIsScratch || RIsScratch) {
20647330f729Sjoerg     if (LIsScratch != RIsScratch)
20657330f729Sjoerg       return LIsScratch;
20667330f729Sjoerg     return LOffs.second < ROffs.second;
20677330f729Sjoerg   }
20687330f729Sjoerg   llvm_unreachable("Unsortable locations found");
20697330f729Sjoerg }
20707330f729Sjoerg 
isInTheSameTranslationUnit(std::pair<FileID,unsigned> & LOffs,std::pair<FileID,unsigned> & ROffs) const20717330f729Sjoerg std::pair<bool, bool> SourceManager::isInTheSameTranslationUnit(
20727330f729Sjoerg     std::pair<FileID, unsigned> &LOffs,
20737330f729Sjoerg     std::pair<FileID, unsigned> &ROffs) const {
20747330f729Sjoerg   // If the source locations are in the same file, just compare offsets.
20757330f729Sjoerg   if (LOffs.first == ROffs.first)
20767330f729Sjoerg     return std::make_pair(true, LOffs.second < ROffs.second);
20777330f729Sjoerg 
20787330f729Sjoerg   // If we are comparing a source location with multiple locations in the same
20797330f729Sjoerg   // file, we get a big win by caching the result.
20807330f729Sjoerg   InBeforeInTUCacheEntry &IsBeforeInTUCache =
20817330f729Sjoerg     getInBeforeInTUCache(LOffs.first, ROffs.first);
20827330f729Sjoerg 
20837330f729Sjoerg   // If we are comparing a source location with multiple locations in the same
20847330f729Sjoerg   // file, we get a big win by caching the result.
20857330f729Sjoerg   if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
20867330f729Sjoerg     return std::make_pair(
20877330f729Sjoerg         true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
20887330f729Sjoerg 
20897330f729Sjoerg   // Okay, we missed in the cache, start updating the cache for this query.
20907330f729Sjoerg   IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
20917330f729Sjoerg                           /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID);
20927330f729Sjoerg 
20937330f729Sjoerg   // We need to find the common ancestor. The only way of doing this is to
20947330f729Sjoerg   // build the complete include chain for one and then walking up the chain
20957330f729Sjoerg   // of the other looking for a match.
20967330f729Sjoerg   // We use a map from FileID to Offset to store the chain. Easier than writing
20977330f729Sjoerg   // a custom set hash info that only depends on the first part of a pair.
20987330f729Sjoerg   using LocSet = llvm::SmallDenseMap<FileID, unsigned, 16>;
20997330f729Sjoerg   LocSet LChain;
21007330f729Sjoerg   do {
21017330f729Sjoerg     LChain.insert(LOffs);
21027330f729Sjoerg     // We catch the case where LOffs is in a file included by ROffs and
21037330f729Sjoerg     // quit early. The other way round unfortunately remains suboptimal.
21047330f729Sjoerg   } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
21057330f729Sjoerg   LocSet::iterator I;
21067330f729Sjoerg   while((I = LChain.find(ROffs.first)) == LChain.end()) {
21077330f729Sjoerg     if (MoveUpIncludeHierarchy(ROffs, *this))
21087330f729Sjoerg       break; // Met at topmost file.
21097330f729Sjoerg   }
21107330f729Sjoerg   if (I != LChain.end())
21117330f729Sjoerg     LOffs = *I;
21127330f729Sjoerg 
21137330f729Sjoerg   // If we exited because we found a nearest common ancestor, compare the
21147330f729Sjoerg   // locations within the common file and cache them.
21157330f729Sjoerg   if (LOffs.first == ROffs.first) {
21167330f729Sjoerg     IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
21177330f729Sjoerg     return std::make_pair(
21187330f729Sjoerg         true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
21197330f729Sjoerg   }
21207330f729Sjoerg   // Clear the lookup cache, it depends on a common location.
21217330f729Sjoerg   IsBeforeInTUCache.clear();
21227330f729Sjoerg   return std::make_pair(false, false);
21237330f729Sjoerg }
21247330f729Sjoerg 
PrintStats() const21257330f729Sjoerg void SourceManager::PrintStats() const {
21267330f729Sjoerg   llvm::errs() << "\n*** Source Manager Stats:\n";
21277330f729Sjoerg   llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
21287330f729Sjoerg                << " mem buffers mapped.\n";
21297330f729Sjoerg   llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
21307330f729Sjoerg                << llvm::capacity_in_bytes(LocalSLocEntryTable)
21317330f729Sjoerg                << " bytes of capacity), "
21327330f729Sjoerg                << NextLocalOffset << "B of Sloc address space used.\n";
21337330f729Sjoerg   llvm::errs() << LoadedSLocEntryTable.size()
21347330f729Sjoerg                << " loaded SLocEntries allocated, "
21357330f729Sjoerg                << MaxLoadedOffset - CurrentLoadedOffset
21367330f729Sjoerg                << "B of Sloc address space used.\n";
21377330f729Sjoerg 
21387330f729Sjoerg   unsigned NumLineNumsComputed = 0;
21397330f729Sjoerg   unsigned NumFileBytesMapped = 0;
21407330f729Sjoerg   for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
2141*e038c9c4Sjoerg     NumLineNumsComputed += bool(I->second->SourceLineCache);
21427330f729Sjoerg     NumFileBytesMapped  += I->second->getSizeBytesMapped();
21437330f729Sjoerg   }
21447330f729Sjoerg   unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
21457330f729Sjoerg 
21467330f729Sjoerg   llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
21477330f729Sjoerg                << NumLineNumsComputed << " files with line #'s computed, "
21487330f729Sjoerg                << NumMacroArgsComputed << " files with macro args computed.\n";
21497330f729Sjoerg   llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
21507330f729Sjoerg                << NumBinaryProbes << " binary.\n";
21517330f729Sjoerg }
21527330f729Sjoerg 
dump() const21537330f729Sjoerg LLVM_DUMP_METHOD void SourceManager::dump() const {
21547330f729Sjoerg   llvm::raw_ostream &out = llvm::errs();
21557330f729Sjoerg 
21567330f729Sjoerg   auto DumpSLocEntry = [&](int ID, const SrcMgr::SLocEntry &Entry,
21577330f729Sjoerg                            llvm::Optional<unsigned> NextStart) {
21587330f729Sjoerg     out << "SLocEntry <FileID " << ID << "> " << (Entry.isFile() ? "file" : "expansion")
21597330f729Sjoerg         << " <SourceLocation " << Entry.getOffset() << ":";
21607330f729Sjoerg     if (NextStart)
21617330f729Sjoerg       out << *NextStart << ">\n";
21627330f729Sjoerg     else
21637330f729Sjoerg       out << "???\?>\n";
21647330f729Sjoerg     if (Entry.isFile()) {
21657330f729Sjoerg       auto &FI = Entry.getFile();
21667330f729Sjoerg       if (FI.NumCreatedFIDs)
21677330f729Sjoerg         out << "  covers <FileID " << ID << ":" << int(ID + FI.NumCreatedFIDs)
21687330f729Sjoerg             << ">\n";
21697330f729Sjoerg       if (FI.getIncludeLoc().isValid())
21707330f729Sjoerg         out << "  included from " << FI.getIncludeLoc().getOffset() << "\n";
2171*e038c9c4Sjoerg       auto &CC = FI.getContentCache();
2172*e038c9c4Sjoerg       out << "  for " << (CC.OrigEntry ? CC.OrigEntry->getName() : "<none>")
21737330f729Sjoerg           << "\n";
2174*e038c9c4Sjoerg       if (CC.BufferOverridden)
21757330f729Sjoerg         out << "  contents overridden\n";
2176*e038c9c4Sjoerg       if (CC.ContentsEntry != CC.OrigEntry) {
21777330f729Sjoerg         out << "  contents from "
2178*e038c9c4Sjoerg             << (CC.ContentsEntry ? CC.ContentsEntry->getName() : "<none>")
21797330f729Sjoerg             << "\n";
21807330f729Sjoerg       }
21817330f729Sjoerg     } else {
21827330f729Sjoerg       auto &EI = Entry.getExpansion();
21837330f729Sjoerg       out << "  spelling from " << EI.getSpellingLoc().getOffset() << "\n";
21847330f729Sjoerg       out << "  macro " << (EI.isMacroArgExpansion() ? "arg" : "body")
21857330f729Sjoerg           << " range <" << EI.getExpansionLocStart().getOffset() << ":"
21867330f729Sjoerg           << EI.getExpansionLocEnd().getOffset() << ">\n";
21877330f729Sjoerg     }
21887330f729Sjoerg   };
21897330f729Sjoerg 
21907330f729Sjoerg   // Dump local SLocEntries.
21917330f729Sjoerg   for (unsigned ID = 0, NumIDs = LocalSLocEntryTable.size(); ID != NumIDs; ++ID) {
21927330f729Sjoerg     DumpSLocEntry(ID, LocalSLocEntryTable[ID],
21937330f729Sjoerg                   ID == NumIDs - 1 ? NextLocalOffset
21947330f729Sjoerg                                    : LocalSLocEntryTable[ID + 1].getOffset());
21957330f729Sjoerg   }
21967330f729Sjoerg   // Dump loaded SLocEntries.
21977330f729Sjoerg   llvm::Optional<unsigned> NextStart;
21987330f729Sjoerg   for (unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
21997330f729Sjoerg     int ID = -(int)Index - 2;
22007330f729Sjoerg     if (SLocEntryLoaded[Index]) {
22017330f729Sjoerg       DumpSLocEntry(ID, LoadedSLocEntryTable[Index], NextStart);
22027330f729Sjoerg       NextStart = LoadedSLocEntryTable[Index].getOffset();
22037330f729Sjoerg     } else {
22047330f729Sjoerg       NextStart = None;
22057330f729Sjoerg     }
22067330f729Sjoerg   }
22077330f729Sjoerg }
22087330f729Sjoerg 
22097330f729Sjoerg ExternalSLocEntrySource::~ExternalSLocEntrySource() = default;
22107330f729Sjoerg 
22117330f729Sjoerg /// Return the amount of memory used by memory buffers, breaking down
22127330f729Sjoerg /// by heap-backed versus mmap'ed memory.
getMemoryBufferSizes() const22137330f729Sjoerg SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
22147330f729Sjoerg   size_t malloc_bytes = 0;
22157330f729Sjoerg   size_t mmap_bytes = 0;
22167330f729Sjoerg 
22177330f729Sjoerg   for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
22187330f729Sjoerg     if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
22197330f729Sjoerg       switch (MemBufferInfos[i]->getMemoryBufferKind()) {
22207330f729Sjoerg         case llvm::MemoryBuffer::MemoryBuffer_MMap:
22217330f729Sjoerg           mmap_bytes += sized_mapped;
22227330f729Sjoerg           break;
22237330f729Sjoerg         case llvm::MemoryBuffer::MemoryBuffer_Malloc:
22247330f729Sjoerg           malloc_bytes += sized_mapped;
22257330f729Sjoerg           break;
22267330f729Sjoerg       }
22277330f729Sjoerg 
22287330f729Sjoerg   return MemoryBufferSizes(malloc_bytes, mmap_bytes);
22297330f729Sjoerg }
22307330f729Sjoerg 
getDataStructureSizes() const22317330f729Sjoerg size_t SourceManager::getDataStructureSizes() const {
22327330f729Sjoerg   size_t size = llvm::capacity_in_bytes(MemBufferInfos)
22337330f729Sjoerg     + llvm::capacity_in_bytes(LocalSLocEntryTable)
22347330f729Sjoerg     + llvm::capacity_in_bytes(LoadedSLocEntryTable)
22357330f729Sjoerg     + llvm::capacity_in_bytes(SLocEntryLoaded)
22367330f729Sjoerg     + llvm::capacity_in_bytes(FileInfos);
22377330f729Sjoerg 
22387330f729Sjoerg   if (OverriddenFilesInfo)
22397330f729Sjoerg     size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);
22407330f729Sjoerg 
22417330f729Sjoerg   return size;
22427330f729Sjoerg }
22437330f729Sjoerg 
SourceManagerForFile(StringRef FileName,StringRef Content)22447330f729Sjoerg SourceManagerForFile::SourceManagerForFile(StringRef FileName,
22457330f729Sjoerg                                            StringRef Content) {
22467330f729Sjoerg   // This is referenced by `FileMgr` and will be released by `FileMgr` when it
22477330f729Sjoerg   // is deleted.
22487330f729Sjoerg   IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
22497330f729Sjoerg       new llvm::vfs::InMemoryFileSystem);
22507330f729Sjoerg   InMemoryFileSystem->addFile(
22517330f729Sjoerg       FileName, 0,
22527330f729Sjoerg       llvm::MemoryBuffer::getMemBuffer(Content, FileName,
22537330f729Sjoerg                                        /*RequiresNullTerminator=*/false));
22547330f729Sjoerg   // This is passed to `SM` as reference, so the pointer has to be referenced
22557330f729Sjoerg   // in `Environment` so that `FileMgr` can out-live this function scope.
22567330f729Sjoerg   FileMgr =
22577330f729Sjoerg       std::make_unique<FileManager>(FileSystemOptions(), InMemoryFileSystem);
22587330f729Sjoerg   // This is passed to `SM` as reference, so the pointer has to be referenced
22597330f729Sjoerg   // by `Environment` due to the same reason above.
22607330f729Sjoerg   Diagnostics = std::make_unique<DiagnosticsEngine>(
22617330f729Sjoerg       IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
22627330f729Sjoerg       new DiagnosticOptions);
22637330f729Sjoerg   SourceMgr = std::make_unique<SourceManager>(*Diagnostics, *FileMgr);
22647330f729Sjoerg   FileID ID = SourceMgr->createFileID(*FileMgr->getFile(FileName),
22657330f729Sjoerg                                       SourceLocation(), clang::SrcMgr::C_User);
22667330f729Sjoerg   assert(ID.isValid());
22677330f729Sjoerg   SourceMgr->setMainFileID(ID);
22687330f729Sjoerg }
2269