1 //===--- SourceManager.cpp - Track and cache source files -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the SourceManager interface.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Basic/SourceManager.h"
15 #include "clang/Basic/Diagnostic.h"
16 #include "clang/Basic/FileManager.h"
17 #include "clang/Basic/SourceManagerInternals.h"
18 #include "llvm/ADT/Optional.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include "llvm/Support/Capacity.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/Path.h"
25 #include "llvm/Support/raw_ostream.h"
29 using namespace clang;
30 using namespace SrcMgr;
31 using llvm::MemoryBuffer;
33 //===----------------------------------------------------------------------===//
34 // SourceManager Helper Classes
35 //===----------------------------------------------------------------------===//
37 ContentCache::~ContentCache() {
38 if (shouldFreeBuffer())
39 delete Buffer.getPointer();
42 /// getSizeBytesMapped - Returns the number of bytes actually mapped for this
43 /// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
44 unsigned ContentCache::getSizeBytesMapped() const {
45 return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
48 /// Returns the kind of memory used to back the memory buffer for
49 /// this content cache. This is used for performance analysis.
50 llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
51 assert(Buffer.getPointer());
53 // Should be unreachable, but keep for sanity.
54 if (!Buffer.getPointer())
55 return llvm::MemoryBuffer::MemoryBuffer_Malloc;
57 llvm::MemoryBuffer *buf = Buffer.getPointer();
58 return buf->getBufferKind();
61 /// getSize - Returns the size of the content encapsulated by this ContentCache.
62 /// This can be the size of the source file or the size of an arbitrary
63 /// scratch buffer. If the ContentCache encapsulates a source file, that
64 /// file is not lazily brought in from disk to satisfy this query.
65 unsigned ContentCache::getSize() const {
66 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
67 : (unsigned) ContentsEntry->getSize();
70 void ContentCache::replaceBuffer(llvm::MemoryBuffer *B, bool DoNotFree) {
71 if (B && B == Buffer.getPointer()) {
72 assert(0 && "Replacing with the same buffer");
73 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
77 if (shouldFreeBuffer())
78 delete Buffer.getPointer();
80 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
83 llvm::MemoryBuffer *ContentCache::getBuffer(DiagnosticsEngine &Diag,
84 const SourceManager &SM,
86 bool *Invalid) const {
87 // Lazily create the Buffer for ContentCaches that wrap files. If we already
88 // computed it, just return what we have.
89 if (Buffer.getPointer() || !ContentsEntry) {
91 *Invalid = isBufferInvalid();
93 return Buffer.getPointer();
96 bool isVolatile = SM.userFilesAreVolatile() && !IsSystemFile;
98 SM.getFileManager().getBufferForFile(ContentsEntry, isVolatile);
100 // If we were unable to open the file, then we are in an inconsistent
101 // situation where the content cache referenced a file which no longer
102 // exists. Most likely, we were using a stat cache with an invalid entry but
103 // the file could also have been removed during processing. Since we can't
104 // really deal with this situation, just create an empty buffer.
106 // FIXME: This is definitely not ideal, but our immediate clients can't
107 // currently handle returning a null entry here. Ideally we should detect
108 // that we are in an inconsistent situation and error out as quickly as
110 if (!BufferOrError) {
111 StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
112 Buffer.setPointer(MemoryBuffer::getNewUninitMemBuffer(
113 ContentsEntry->getSize(), "<invalid>").release());
114 char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart());
115 for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
116 Ptr[i] = FillStr[i % FillStr.size()];
118 if (Diag.isDiagnosticInFlight())
119 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
120 ContentsEntry->getName(),
121 BufferOrError.getError().message());
123 Diag.Report(Loc, diag::err_cannot_open_file)
124 << ContentsEntry->getName() << BufferOrError.getError().message();
126 Buffer.setInt(Buffer.getInt() | InvalidFlag);
128 if (Invalid) *Invalid = true;
129 return Buffer.getPointer();
132 Buffer.setPointer(BufferOrError->release());
134 // Check that the file's size is the same as in the file entry (which may
135 // have come from a stat cache).
136 if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) {
137 if (Diag.isDiagnosticInFlight())
138 Diag.SetDelayedDiagnostic(diag::err_file_modified,
139 ContentsEntry->getName());
141 Diag.Report(Loc, diag::err_file_modified)
142 << ContentsEntry->getName();
144 Buffer.setInt(Buffer.getInt() | InvalidFlag);
145 if (Invalid) *Invalid = true;
146 return Buffer.getPointer();
149 // If the buffer is valid, check to see if it has a UTF Byte Order Mark
150 // (BOM). We only support UTF-8 with and without a BOM right now. See
151 // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
152 StringRef BufStr = Buffer.getPointer()->getBuffer();
153 const char *InvalidBOM = llvm::StringSwitch<const char *>(BufStr)
154 .StartsWith("\xFE\xFF", "UTF-16 (BE)")
155 .StartsWith("\xFF\xFE", "UTF-16 (LE)")
156 .StartsWith("\x00\x00\xFE\xFF", "UTF-32 (BE)")
157 .StartsWith("\xFF\xFE\x00\x00", "UTF-32 (LE)")
158 .StartsWith("\x2B\x2F\x76", "UTF-7")
159 .StartsWith("\xF7\x64\x4C", "UTF-1")
160 .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
161 .StartsWith("\x0E\xFE\xFF", "SDSU")
162 .StartsWith("\xFB\xEE\x28", "BOCU-1")
163 .StartsWith("\x84\x31\x95\x33", "GB-18030")
167 Diag.Report(Loc, diag::err_unsupported_bom)
168 << InvalidBOM << ContentsEntry->getName();
169 Buffer.setInt(Buffer.getInt() | InvalidFlag);
173 *Invalid = isBufferInvalid();
175 return Buffer.getPointer();
178 unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
180 FilenameIDs.insert(std::make_pair(Name, FilenamesByID.size()));
182 FilenamesByID.push_back(&*IterBool.first);
183 return IterBool.first->second;
186 /// Add a line note to the line table that indicates that there is a \#line or
187 /// GNU line marker at the specified FID/Offset location which changes the
188 /// presumed location to LineNo/FilenameID. If EntryExit is 0, then this doesn't
189 /// change the presumed \#include stack. If it is 1, this is a file entry, if
190 /// it is 2 then this is a file exit. FileKind specifies whether this is a
191 /// system header or extern C system header.
192 void LineTableInfo::AddLineNote(FileID FID, unsigned Offset, unsigned LineNo,
193 int FilenameID, unsigned EntryExit,
194 SrcMgr::CharacteristicKind FileKind) {
195 std::vector<LineEntry> &Entries = LineEntries[FID];
197 // An unspecified FilenameID means use the last filename if available, or the
198 // main source file otherwise.
199 if (FilenameID == -1 && !Entries.empty())
200 FilenameID = Entries.back().FilenameID;
202 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
203 "Adding line entries out of order!");
205 unsigned IncludeOffset = 0;
206 if (EntryExit == 0) { // No #include stack change.
207 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
208 } else if (EntryExit == 1) {
209 IncludeOffset = Offset-1;
210 } else if (EntryExit == 2) {
211 assert(!Entries.empty() && Entries.back().IncludeOffset &&
212 "PPDirectives should have caught case when popping empty include stack");
214 // Get the include loc of the last entries' include loc as our include loc.
216 if (const LineEntry *PrevEntry =
217 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
218 IncludeOffset = PrevEntry->IncludeOffset;
221 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
226 /// FindNearestLineEntry - Find the line entry nearest to FID that is before
227 /// it. If there is no line entry before Offset in FID, return null.
228 const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID,
230 const std::vector<LineEntry> &Entries = LineEntries[FID];
231 assert(!Entries.empty() && "No #line entries for this FID after all!");
233 // It is very common for the query to be after the last #line, check this
235 if (Entries.back().FileOffset <= Offset)
236 return &Entries.back();
238 // Do a binary search to find the maximal element that is still before Offset.
239 std::vector<LineEntry>::const_iterator I =
240 std::upper_bound(Entries.begin(), Entries.end(), Offset);
241 if (I == Entries.begin()) return nullptr;
245 /// \brief Add a new line entry that has already been encoded into
246 /// the internal representation of the line table.
247 void LineTableInfo::AddEntry(FileID FID,
248 const std::vector<LineEntry> &Entries) {
249 LineEntries[FID] = Entries;
252 /// getLineTableFilenameID - Return the uniqued ID for the specified filename.
254 unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
255 return getLineTable().getLineTableFilenameID(Name);
258 /// AddLineNote - Add a line note to the line table for the FileID and offset
259 /// specified by Loc. If FilenameID is -1, it is considered to be
261 void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
262 int FilenameID, bool IsFileEntry,
264 SrcMgr::CharacteristicKind FileKind) {
265 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
267 bool Invalid = false;
268 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
269 if (!Entry.isFile() || Invalid)
272 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
274 // Remember that this file has #line directives now if it doesn't already.
275 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
277 (void) getLineTable();
279 unsigned EntryExit = 0;
285 LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,
286 EntryExit, FileKind);
289 LineTableInfo &SourceManager::getLineTable() {
291 LineTable = new LineTableInfo();
295 //===----------------------------------------------------------------------===//
296 // Private 'Create' methods.
297 //===----------------------------------------------------------------------===//
299 SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
300 bool UserFilesAreVolatile)
301 : Diag(Diag), FileMgr(FileMgr), OverridenFilesKeepOriginalName(true),
302 UserFilesAreVolatile(UserFilesAreVolatile), FilesAreTransient(false),
303 ExternalSLocEntries(nullptr), LineTable(nullptr), NumLinearScans(0),
306 Diag.setSourceManager(this);
309 SourceManager::~SourceManager() {
312 // Delete FileEntry objects corresponding to content caches. Since the actual
313 // content cache objects are bump pointer allocated, we just have to run the
314 // dtors, but we call the deallocate method for completeness.
315 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
316 if (MemBufferInfos[i]) {
317 MemBufferInfos[i]->~ContentCache();
318 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
321 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
322 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
324 I->second->~ContentCache();
325 ContentCacheAlloc.Deallocate(I->second);
330 void SourceManager::clearIDTables() {
331 MainFileID = FileID();
332 LocalSLocEntryTable.clear();
333 LoadedSLocEntryTable.clear();
334 SLocEntryLoaded.clear();
335 LastLineNoFileIDQuery = FileID();
336 LastLineNoContentCache = nullptr;
337 LastFileIDLookup = FileID();
342 // Use up FileID #0 as an invalid expansion.
344 CurrentLoadedOffset = MaxLoadedOffset;
345 createExpansionLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
348 /// getOrCreateContentCache - Create or return a cached ContentCache for the
351 SourceManager::getOrCreateContentCache(const FileEntry *FileEnt,
353 assert(FileEnt && "Didn't specify a file entry to use?");
355 // Do we already have information about this file?
356 ContentCache *&Entry = FileInfos[FileEnt];
357 if (Entry) return Entry;
359 // Nope, create a new Cache entry.
360 Entry = ContentCacheAlloc.Allocate<ContentCache>();
362 if (OverriddenFilesInfo) {
363 // If the file contents are overridden with contents from another file,
364 // pass that file to ContentCache.
365 llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
366 overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
367 if (overI == OverriddenFilesInfo->OverriddenFiles.end())
368 new (Entry) ContentCache(FileEnt);
370 new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
374 new (Entry) ContentCache(FileEnt);
377 Entry->IsSystemFile = isSystemFile;
378 Entry->IsTransient = FilesAreTransient;
384 /// createMemBufferContentCache - Create a new ContentCache for the specified
385 /// memory buffer. This does no caching.
386 const ContentCache *SourceManager::createMemBufferContentCache(
387 std::unique_ptr<llvm::MemoryBuffer> Buffer) {
388 // Add a new ContentCache to the MemBufferInfos list and return it.
389 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
390 new (Entry) ContentCache();
391 MemBufferInfos.push_back(Entry);
392 Entry->setBuffer(std::move(Buffer));
396 const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
397 bool *Invalid) const {
398 assert(!SLocEntryLoaded[Index]);
399 if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
402 // If the file of the SLocEntry changed we could still have loaded it.
403 if (!SLocEntryLoaded[Index]) {
404 // Try to recover; create a SLocEntry so the rest of clang can handle it.
405 LoadedSLocEntryTable[Index] = SLocEntry::get(0,
406 FileInfo::get(SourceLocation(),
407 getFakeContentCacheForRecovery(),
412 return LoadedSLocEntryTable[Index];
415 std::pair<int, unsigned>
416 SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
417 unsigned TotalSize) {
418 assert(ExternalSLocEntries && "Don't have an external sloc source");
419 // Make sure we're not about to run out of source locations.
420 if (CurrentLoadedOffset - TotalSize < NextLocalOffset)
421 return std::make_pair(0, 0);
422 LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
423 SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
424 CurrentLoadedOffset -= TotalSize;
425 int ID = LoadedSLocEntryTable.size();
426 return std::make_pair(-ID - 1, CurrentLoadedOffset);
429 /// \brief As part of recovering from missing or changed content, produce a
430 /// fake, non-empty buffer.
431 llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const {
432 if (!FakeBufferForRecovery)
433 FakeBufferForRecovery =
434 llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
436 return FakeBufferForRecovery.get();
439 /// \brief As part of recovering from missing or changed content, produce a
440 /// fake content cache.
441 const SrcMgr::ContentCache *
442 SourceManager::getFakeContentCacheForRecovery() const {
443 if (!FakeContentCacheForRecovery) {
444 FakeContentCacheForRecovery = llvm::make_unique<SrcMgr::ContentCache>();
445 FakeContentCacheForRecovery->replaceBuffer(getFakeBufferForRecovery(),
448 return FakeContentCacheForRecovery.get();
451 /// \brief Returns the previous in-order FileID or an invalid FileID if there
452 /// is no previous one.
453 FileID SourceManager::getPreviousFileID(FileID FID) const {
464 } else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {
468 return FileID::get(ID-1);
471 /// \brief Returns the next in-order FileID or an invalid FileID if there is
473 FileID SourceManager::getNextFileID(FileID FID) const {
479 if (unsigned(ID+1) >= local_sloc_entry_size())
481 } else if (ID+1 >= -1) {
485 return FileID::get(ID+1);
488 //===----------------------------------------------------------------------===//
489 // Methods to create new FileID's and macro expansions.
490 //===----------------------------------------------------------------------===//
492 /// createFileID - Create a new FileID for the specified ContentCache and
493 /// include position. This works regardless of whether the ContentCache
494 /// corresponds to a file or some other input source.
495 FileID SourceManager::createFileID(const ContentCache *File,
496 SourceLocation IncludePos,
497 SrcMgr::CharacteristicKind FileCharacter,
498 int LoadedID, unsigned LoadedOffset) {
500 assert(LoadedID != -1 && "Loading sentinel FileID");
501 unsigned Index = unsigned(-LoadedID) - 2;
502 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
503 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
504 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset,
505 FileInfo::get(IncludePos, File, FileCharacter));
506 SLocEntryLoaded[Index] = true;
507 return FileID::get(LoadedID);
509 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset,
510 FileInfo::get(IncludePos, File,
512 unsigned FileSize = File->getSize();
513 assert(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
514 NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset &&
515 "Ran out of source locations!");
516 // We do a +1 here because we want a SourceLocation that means "the end of the
517 // file", e.g. for the "no newline at the end of the file" diagnostic.
518 NextLocalOffset += FileSize + 1;
520 // Set LastFileIDLookup to the newly created file. The next getFileID call is
521 // almost guaranteed to be from that file.
522 FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
523 return LastFileIDLookup = FID;
527 SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc,
528 SourceLocation ExpansionLoc,
529 unsigned TokLength) {
530 ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
532 return createExpansionLocImpl(Info, TokLength);
536 SourceManager::createExpansionLoc(SourceLocation SpellingLoc,
537 SourceLocation ExpansionLocStart,
538 SourceLocation ExpansionLocEnd,
541 unsigned LoadedOffset) {
542 ExpansionInfo Info = ExpansionInfo::create(SpellingLoc, ExpansionLocStart,
544 return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset);
548 SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
551 unsigned LoadedOffset) {
553 assert(LoadedID != -1 && "Loading sentinel FileID");
554 unsigned Index = unsigned(-LoadedID) - 2;
555 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
556 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
557 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
558 SLocEntryLoaded[Index] = true;
559 return SourceLocation::getMacroLoc(LoadedOffset);
561 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
562 assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&
563 NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&
564 "Ran out of source locations!");
565 // See createFileID for that +1.
566 NextLocalOffset += TokLength + 1;
567 return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
570 llvm::MemoryBuffer *SourceManager::getMemoryBufferForFile(const FileEntry *File,
572 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
573 assert(IR && "getOrCreateContentCache() cannot return NULL");
574 return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
577 void SourceManager::overrideFileContents(const FileEntry *SourceFile,
578 llvm::MemoryBuffer *Buffer,
580 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
581 assert(IR && "getOrCreateContentCache() cannot return NULL");
583 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
584 const_cast<SrcMgr::ContentCache *>(IR)->BufferOverridden = true;
586 getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
589 void SourceManager::overrideFileContents(const FileEntry *SourceFile,
590 const FileEntry *NewFile) {
591 assert(SourceFile->getSize() == NewFile->getSize() &&
592 "Different sizes, use the FileManager to create a virtual file with "
594 assert(FileInfos.count(SourceFile) == 0 &&
595 "This function should be called at the initialization stage, before "
596 "any parsing occurs.");
597 getOverriddenFilesInfo().OverriddenFiles[SourceFile] = NewFile;
600 void SourceManager::disableFileContentsOverride(const FileEntry *File) {
601 if (!isFileOverridden(File))
604 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
605 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(nullptr);
606 const_cast<SrcMgr::ContentCache *>(IR)->ContentsEntry = IR->OrigEntry;
608 assert(OverriddenFilesInfo);
609 OverriddenFilesInfo->OverriddenFiles.erase(File);
610 OverriddenFilesInfo->OverriddenFilesWithBuffer.erase(File);
613 void SourceManager::setFileIsTransient(const FileEntry *File) {
614 const SrcMgr::ContentCache *CC = getOrCreateContentCache(File);
615 const_cast<SrcMgr::ContentCache *>(CC)->IsTransient = true;
618 StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
619 bool MyInvalid = false;
620 const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid);
621 if (!SLoc.isFile() || MyInvalid) {
624 return "<<<<<INVALID SOURCE LOCATION>>>>>";
627 llvm::MemoryBuffer *Buf = SLoc.getFile().getContentCache()->getBuffer(
628 Diag, *this, SourceLocation(), &MyInvalid);
630 *Invalid = MyInvalid;
633 return "<<<<<INVALID SOURCE LOCATION>>>>>";
635 return Buf->getBuffer();
638 //===----------------------------------------------------------------------===//
639 // SourceLocation manipulation methods.
640 //===----------------------------------------------------------------------===//
642 /// \brief Return the FileID for a SourceLocation.
644 /// This is the cache-miss path of getFileID. Not as hot as that function, but
645 /// still very important. It is responsible for finding the entry in the
646 /// SLocEntry tables that contains the specified location.
647 FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
649 return FileID::get(0);
651 // Now it is time to search for the correct file. See where the SLocOffset
652 // sits in the global view and consult local or loaded buffers for it.
653 if (SLocOffset < NextLocalOffset)
654 return getFileIDLocal(SLocOffset);
655 return getFileIDLoaded(SLocOffset);
658 /// \brief Return the FileID for a SourceLocation with a low offset.
660 /// This function knows that the SourceLocation is in a local buffer, not a
662 FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const {
663 assert(SLocOffset < NextLocalOffset && "Bad function choice");
665 // After the first and second level caches, I see two common sorts of
666 // behavior: 1) a lot of searched FileID's are "near" the cached file
667 // location or are "near" the cached expansion location. 2) others are just
668 // completely random and may be a very long way away.
670 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
671 // then we fall back to a less cache efficient, but more scalable, binary
672 // search to find the location.
674 // See if this is near the file point - worst case we start scanning from the
675 // most newly created FileID.
676 const SrcMgr::SLocEntry *I;
678 if (LastFileIDLookup.ID < 0 ||
679 LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
680 // Neither loc prunes our search.
681 I = LocalSLocEntryTable.end();
683 // Perhaps it is near the file point.
684 I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
687 // Find the FileID that contains this. "I" is an iterator that points to a
688 // FileID whose offset is known to be larger than SLocOffset.
689 unsigned NumProbes = 0;
692 if (I->getOffset() <= SLocOffset) {
693 FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
695 // If this isn't an expansion, remember it. We have good locality across
697 if (!I->isExpansion())
698 LastFileIDLookup = Res;
699 NumLinearScans += NumProbes+1;
702 if (++NumProbes == 8)
706 // Convert "I" back into an index. We know that it is an entry whose index is
707 // larger than the offset we are looking for.
708 unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
709 // LessIndex - This is the lower bound of the range that we're searching.
710 // We know that the offset corresponding to the FileID is is less than
712 unsigned LessIndex = 0;
715 bool Invalid = false;
716 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
717 unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
719 return FileID::get(0);
723 // If the offset of the midpoint is too large, chop the high side of the
724 // range to the midpoint.
725 if (MidOffset > SLocOffset) {
726 GreaterIndex = MiddleIndex;
730 // If the middle index contains the value, succeed and return.
731 // FIXME: This could be made faster by using a function that's aware of
732 // being in the local area.
733 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
734 FileID Res = FileID::get(MiddleIndex);
736 // If this isn't a macro expansion, remember it. We have good locality
737 // across FileID lookups.
738 if (!LocalSLocEntryTable[MiddleIndex].isExpansion())
739 LastFileIDLookup = Res;
740 NumBinaryProbes += NumProbes;
744 // Otherwise, move the low-side up to the middle index.
745 LessIndex = MiddleIndex;
749 /// \brief Return the FileID for a SourceLocation with a high offset.
751 /// This function knows that the SourceLocation is in a loaded buffer, not a
753 FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
754 // Sanity checking, otherwise a bug may lead to hanging in release build.
755 if (SLocOffset < CurrentLoadedOffset) {
756 assert(0 && "Invalid SLocOffset or bad function choice");
760 // Essentially the same as the local case, but the loaded array is sorted
761 // in the other direction.
763 // First do a linear scan from the last lookup position, if possible.
765 int LastID = LastFileIDLookup.ID;
766 if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
769 I = (-LastID - 2) + 1;
772 for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
773 // Make sure the entry is loaded!
774 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
775 if (E.getOffset() <= SLocOffset) {
776 FileID Res = FileID::get(-int(I) - 2);
778 if (!E.isExpansion())
779 LastFileIDLookup = Res;
780 NumLinearScans += NumProbes + 1;
785 // Linear scan failed. Do the binary search. Note the reverse sorting of the
786 // table: GreaterIndex is the one where the offset is greater, which is
787 // actually a lower index!
788 unsigned GreaterIndex = I;
789 unsigned LessIndex = LoadedSLocEntryTable.size();
793 unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
794 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
795 if (E.getOffset() == 0)
796 return FileID(); // invalid entry.
800 if (E.getOffset() > SLocOffset) {
801 // Sanity checking, otherwise a bug may lead to hanging in release build.
802 if (GreaterIndex == MiddleIndex) {
803 assert(0 && "binary search missed the entry");
806 GreaterIndex = MiddleIndex;
810 if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
811 FileID Res = FileID::get(-int(MiddleIndex) - 2);
812 if (!E.isExpansion())
813 LastFileIDLookup = Res;
814 NumBinaryProbes += NumProbes;
818 // Sanity checking, otherwise a bug may lead to hanging in release build.
819 if (LessIndex == MiddleIndex) {
820 assert(0 && "binary search missed the entry");
823 LessIndex = MiddleIndex;
827 SourceLocation SourceManager::
828 getExpansionLocSlowCase(SourceLocation Loc) const {
830 // Note: If Loc indicates an offset into a token that came from a macro
831 // expansion (e.g. the 5th character of the token) we do not want to add
832 // this offset when going to the expansion location. The expansion
833 // location is the macro invocation, which the offset has nothing to do
834 // with. This is unlike when we get the spelling loc, because the offset
835 // directly correspond to the token whose spelling we're inspecting.
836 Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
837 } while (!Loc.isFileID());
842 SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
844 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
845 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
846 Loc = Loc.getLocWithOffset(LocInfo.second);
847 } while (!Loc.isFileID());
851 SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
853 if (isMacroArgExpansion(Loc))
854 Loc = getImmediateSpellingLoc(Loc);
856 Loc = getImmediateExpansionRange(Loc).first;
857 } while (!Loc.isFileID());
862 std::pair<FileID, unsigned>
863 SourceManager::getDecomposedExpansionLocSlowCase(
864 const SrcMgr::SLocEntry *E) const {
865 // If this is an expansion record, walk through all the expansion points.
870 Loc = E->getExpansion().getExpansionLocStart();
872 FID = getFileID(Loc);
873 E = &getSLocEntry(FID);
874 Offset = Loc.getOffset()-E->getOffset();
875 } while (!Loc.isFileID());
877 return std::make_pair(FID, Offset);
880 std::pair<FileID, unsigned>
881 SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
882 unsigned Offset) const {
883 // If this is an expansion record, walk through all the expansion points.
887 Loc = E->getExpansion().getSpellingLoc();
888 Loc = Loc.getLocWithOffset(Offset);
890 FID = getFileID(Loc);
891 E = &getSLocEntry(FID);
892 Offset = Loc.getOffset()-E->getOffset();
893 } while (!Loc.isFileID());
895 return std::make_pair(FID, Offset);
898 /// getImmediateSpellingLoc - Given a SourceLocation object, return the
899 /// spelling location referenced by the ID. This is the first level down
900 /// towards the place where the characters that make up the lexed token can be
901 /// found. This should not generally be used by clients.
902 SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
903 if (Loc.isFileID()) return Loc;
904 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
905 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
906 return Loc.getLocWithOffset(LocInfo.second);
910 /// getImmediateExpansionRange - Loc is required to be an expansion location.
911 /// Return the start/end of the expansion information.
912 std::pair<SourceLocation,SourceLocation>
913 SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
914 assert(Loc.isMacroID() && "Not a macro expansion loc!");
915 const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
916 return Expansion.getExpansionLocRange();
919 /// getExpansionRange - Given a SourceLocation object, return the range of
920 /// tokens covered by the expansion in the ultimate file.
921 std::pair<SourceLocation,SourceLocation>
922 SourceManager::getExpansionRange(SourceLocation Loc) const {
923 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
925 std::pair<SourceLocation,SourceLocation> Res =
926 getImmediateExpansionRange(Loc);
928 // Fully resolve the start and end locations to their ultimate expansion
930 while (!Res.first.isFileID())
931 Res.first = getImmediateExpansionRange(Res.first).first;
932 while (!Res.second.isFileID())
933 Res.second = getImmediateExpansionRange(Res.second).second;
937 bool SourceManager::isMacroArgExpansion(SourceLocation Loc,
938 SourceLocation *StartLoc) const {
939 if (!Loc.isMacroID()) return false;
941 FileID FID = getFileID(Loc);
942 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
943 if (!Expansion.isMacroArgExpansion()) return false;
946 *StartLoc = Expansion.getExpansionLocStart();
950 bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const {
951 if (!Loc.isMacroID()) return false;
953 FileID FID = getFileID(Loc);
954 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
955 return Expansion.isMacroBodyExpansion();
958 bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
959 SourceLocation *MacroBegin) const {
960 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
962 std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);
963 if (DecompLoc.second > 0)
964 return false; // Does not point at the start of expansion range.
966 bool Invalid = false;
967 const SrcMgr::ExpansionInfo &ExpInfo =
968 getSLocEntry(DecompLoc.first, &Invalid).getExpansion();
971 SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();
973 if (ExpInfo.isMacroArgExpansion()) {
974 // For macro argument expansions, check if the previous FileID is part of
975 // the same argument expansion, in which case this Loc is not at the
976 // beginning of the expansion.
977 FileID PrevFID = getPreviousFileID(DecompLoc.first);
978 if (!PrevFID.isInvalid()) {
979 const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);
982 if (PrevEntry.isExpansion() &&
983 PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)
989 *MacroBegin = ExpLoc;
993 bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
994 SourceLocation *MacroEnd) const {
995 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
997 FileID FID = getFileID(Loc);
998 SourceLocation NextLoc = Loc.getLocWithOffset(1);
999 if (isInFileID(NextLoc, FID))
1000 return false; // Does not point at the end of expansion range.
1002 bool Invalid = false;
1003 const SrcMgr::ExpansionInfo &ExpInfo =
1004 getSLocEntry(FID, &Invalid).getExpansion();
1008 if (ExpInfo.isMacroArgExpansion()) {
1009 // For macro argument expansions, check if the next FileID is part of the
1010 // same argument expansion, in which case this Loc is not at the end of the
1012 FileID NextFID = getNextFileID(FID);
1013 if (!NextFID.isInvalid()) {
1014 const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);
1017 if (NextEntry.isExpansion() &&
1018 NextEntry.getExpansion().getExpansionLocStart() ==
1019 ExpInfo.getExpansionLocStart())
1025 *MacroEnd = ExpInfo.getExpansionLocEnd();
1030 //===----------------------------------------------------------------------===//
1031 // Queries about the code at a SourceLocation.
1032 //===----------------------------------------------------------------------===//
1034 /// getCharacterData - Return a pointer to the start of the specified location
1035 /// in the appropriate MemoryBuffer.
1036 const char *SourceManager::getCharacterData(SourceLocation SL,
1037 bool *Invalid) const {
1038 // Note that this is a hot function in the getSpelling() path, which is
1039 // heavily used by -E mode.
1040 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
1042 // Note that calling 'getBuffer()' may lazily page in a source file.
1043 bool CharDataInvalid = false;
1044 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
1045 if (CharDataInvalid || !Entry.isFile()) {
1049 return "<<<<INVALID BUFFER>>>>";
1051 llvm::MemoryBuffer *Buffer = Entry.getFile().getContentCache()->getBuffer(
1052 Diag, *this, SourceLocation(), &CharDataInvalid);
1054 *Invalid = CharDataInvalid;
1055 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
1059 /// getColumnNumber - Return the column # for the specified file position.
1060 /// this is significantly cheaper to compute than the line number.
1061 unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
1062 bool *Invalid) const {
1063 bool MyInvalid = false;
1064 llvm::MemoryBuffer *MemBuf = getBuffer(FID, &MyInvalid);
1066 *Invalid = MyInvalid;
1071 // It is okay to request a position just past the end of the buffer.
1072 if (FilePos > MemBuf->getBufferSize()) {
1078 const char *Buf = MemBuf->getBufferStart();
1079 // See if we just calculated the line number for this FilePos and can use
1080 // that to lookup the start of the line instead of searching for it.
1081 if (LastLineNoFileIDQuery == FID &&
1082 LastLineNoContentCache->SourceLineCache != nullptr &&
1083 LastLineNoResult < LastLineNoContentCache->NumLines) {
1084 unsigned *SourceLineCache = LastLineNoContentCache->SourceLineCache;
1085 unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
1086 unsigned LineEnd = SourceLineCache[LastLineNoResult];
1087 if (FilePos >= LineStart && FilePos < LineEnd) {
1088 // LineEnd is the LineStart of the next line.
1089 // A line ends with separator LF or CR+LF on Windows.
1090 // FilePos might point to the last separator,
1091 // but we need a column number at most 1 + the last column.
1092 if (FilePos + 1 == LineEnd && FilePos > LineStart) {
1093 if (Buf[FilePos - 1] == '\r' || Buf[FilePos - 1] == '\n')
1096 return FilePos - LineStart + 1;
1100 unsigned LineStart = FilePos;
1101 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
1103 return FilePos-LineStart+1;
1106 // isInvalid - Return the result of calling loc.isInvalid(), and
1107 // if Invalid is not null, set its value to same.
1108 template<typename LocType>
1109 static bool isInvalid(LocType Loc, bool *Invalid) {
1110 bool MyInvalid = Loc.isInvalid();
1112 *Invalid = MyInvalid;
1116 unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
1117 bool *Invalid) const {
1118 if (isInvalid(Loc, Invalid)) return 0;
1119 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1120 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1123 unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
1124 bool *Invalid) const {
1125 if (isInvalid(Loc, Invalid)) return 0;
1126 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1127 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1130 unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
1131 bool *Invalid) const {
1132 PresumedLoc PLoc = getPresumedLoc(Loc);
1133 if (isInvalid(PLoc, Invalid)) return 0;
1134 return PLoc.getColumn();
1138 #include <emmintrin.h>
1141 static LLVM_ATTRIBUTE_NOINLINE void
1142 ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
1143 llvm::BumpPtrAllocator &Alloc,
1144 const SourceManager &SM, bool &Invalid);
1145 static void ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
1146 llvm::BumpPtrAllocator &Alloc,
1147 const SourceManager &SM, bool &Invalid) {
1148 // Note that calling 'getBuffer()' may lazily page in the file.
1149 MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(), &Invalid);
1153 // Find the file offsets of all of the *physical* source lines. This does
1154 // not look at trigraphs, escaped newlines, or anything else tricky.
1155 SmallVector<unsigned, 256> LineOffsets;
1157 // Line #1 starts at char 0.
1158 LineOffsets.push_back(0);
1160 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
1161 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
1164 // Skip over the contents of the line.
1165 const unsigned char *NextBuf = (const unsigned char *)Buf;
1168 // Try to skip to the next newline using SSE instructions. This is very
1169 // performance sensitive for programs with lots of diagnostics and in -E
1171 __m128i CRs = _mm_set1_epi8('\r');
1172 __m128i LFs = _mm_set1_epi8('\n');
1174 // First fix up the alignment to 16 bytes.
1175 while (((uintptr_t)NextBuf & 0xF) != 0) {
1176 if (*NextBuf == '\n' || *NextBuf == '\r' || *NextBuf == '\0')
1177 goto FoundSpecialChar;
1181 // Scan 16 byte chunks for '\r' and '\n'. Ignore '\0'.
1182 while (NextBuf+16 <= End) {
1183 const __m128i Chunk = *(const __m128i*)NextBuf;
1184 __m128i Cmp = _mm_or_si128(_mm_cmpeq_epi8(Chunk, CRs),
1185 _mm_cmpeq_epi8(Chunk, LFs));
1186 unsigned Mask = _mm_movemask_epi8(Cmp);
1188 // If we found a newline, adjust the pointer and jump to the handling code.
1190 NextBuf += llvm::countTrailingZeros(Mask);
1191 goto FoundSpecialChar;
1197 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
1203 Offs += NextBuf-Buf;
1206 if (Buf[0] == '\n' || Buf[0] == '\r') {
1207 // If this is \n\r or \r\n, skip both characters.
1208 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1]) {
1214 LineOffsets.push_back(Offs);
1216 // Otherwise, this is a null. If end of file, exit.
1217 if (Buf == End) break;
1218 // Otherwise, skip the null.
1224 // Copy the offsets into the FileInfo structure.
1225 FI->NumLines = LineOffsets.size();
1226 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
1227 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
1230 /// getLineNumber - Given a SourceLocation, return the spelling line number
1231 /// for the position indicated. This requires building and caching a table of
1232 /// line offsets for the MemoryBuffer, so this is not cheap: use only when
1233 /// about to emit a diagnostic.
1234 unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1235 bool *Invalid) const {
1236 if (FID.isInvalid()) {
1242 ContentCache *Content;
1243 if (LastLineNoFileIDQuery == FID)
1244 Content = LastLineNoContentCache;
1246 bool MyInvalid = false;
1247 const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1248 if (MyInvalid || !Entry.isFile()) {
1254 Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
1257 // If this is the first use of line information for this buffer, compute the
1258 /// SourceLineCache for it on demand.
1259 if (!Content->SourceLineCache) {
1260 bool MyInvalid = false;
1261 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
1263 *Invalid = MyInvalid;
1269 // Okay, we know we have a line number table. Do a binary search to find the
1270 // line number that this character position lands on.
1271 unsigned *SourceLineCache = Content->SourceLineCache;
1272 unsigned *SourceLineCacheStart = SourceLineCache;
1273 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
1275 unsigned QueriedFilePos = FilePos+1;
1277 // FIXME: I would like to be convinced that this code is worth being as
1278 // complicated as it is, binary search isn't that slow.
1280 // If it is worth being optimized, then in my opinion it could be more
1281 // performant, simpler, and more obviously correct by just "galloping" outward
1282 // from the queried file position. In fact, this could be incorporated into a
1283 // generic algorithm such as lower_bound_with_hint.
1285 // If someone gives me a test case where this matters, and I will do it! - DWD
1287 // If the previous query was to the same file, we know both the file pos from
1288 // that query and the line number returned. This allows us to narrow the
1289 // search space from the entire file to something near the match.
1290 if (LastLineNoFileIDQuery == FID) {
1291 if (QueriedFilePos >= LastLineNoFilePos) {
1292 // FIXME: Potential overflow?
1293 SourceLineCache = SourceLineCache+LastLineNoResult-1;
1295 // The query is likely to be nearby the previous one. Here we check to
1296 // see if it is within 5, 10 or 20 lines. It can be far away in cases
1297 // where big comment blocks and vertical whitespace eat up lines but
1298 // contribute no tokens.
1299 if (SourceLineCache+5 < SourceLineCacheEnd) {
1300 if (SourceLineCache[5] > QueriedFilePos)
1301 SourceLineCacheEnd = SourceLineCache+5;
1302 else if (SourceLineCache+10 < SourceLineCacheEnd) {
1303 if (SourceLineCache[10] > QueriedFilePos)
1304 SourceLineCacheEnd = SourceLineCache+10;
1305 else if (SourceLineCache+20 < SourceLineCacheEnd) {
1306 if (SourceLineCache[20] > QueriedFilePos)
1307 SourceLineCacheEnd = SourceLineCache+20;
1312 if (LastLineNoResult < Content->NumLines)
1313 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
1318 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
1319 unsigned LineNo = Pos-SourceLineCacheStart;
1321 LastLineNoFileIDQuery = FID;
1322 LastLineNoContentCache = Content;
1323 LastLineNoFilePos = QueriedFilePos;
1324 LastLineNoResult = LineNo;
1328 unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1329 bool *Invalid) const {
1330 if (isInvalid(Loc, Invalid)) return 0;
1331 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1332 return getLineNumber(LocInfo.first, LocInfo.second);
1334 unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
1335 bool *Invalid) const {
1336 if (isInvalid(Loc, Invalid)) return 0;
1337 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1338 return getLineNumber(LocInfo.first, LocInfo.second);
1340 unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
1341 bool *Invalid) const {
1342 PresumedLoc PLoc = getPresumedLoc(Loc);
1343 if (isInvalid(PLoc, Invalid)) return 0;
1344 return PLoc.getLine();
1347 /// getFileCharacteristic - return the file characteristic of the specified
1348 /// source location, indicating whether this is a normal file, a system
1349 /// header, or an "implicit extern C" system header.
1351 /// This state can be modified with flags on GNU linemarker directives like:
1353 /// which changes all source locations in the current file after that to be
1354 /// considered to be from a system header.
1355 SrcMgr::CharacteristicKind
1356 SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1357 assert(Loc.isValid() && "Can't get file characteristic of invalid loc!");
1358 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1359 bool Invalid = false;
1360 const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
1361 if (Invalid || !SEntry.isFile())
1364 const SrcMgr::FileInfo &FI = SEntry.getFile();
1366 // If there are no #line directives in this file, just return the whole-file
1368 if (!FI.hasLineDirectives())
1369 return FI.getFileCharacteristic();
1371 assert(LineTable && "Can't have linetable entries without a LineTable!");
1372 // See if there is a #line directive before the location.
1373 const LineEntry *Entry =
1374 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
1376 // If this is before the first line marker, use the file characteristic.
1378 return FI.getFileCharacteristic();
1380 return Entry->FileKind;
1383 /// Return the filename or buffer identifier of the buffer the location is in.
1384 /// Note that this name does not respect \#line directives. Use getPresumedLoc
1385 /// for normal clients.
1386 StringRef SourceManager::getBufferName(SourceLocation Loc,
1387 bool *Invalid) const {
1388 if (isInvalid(Loc, Invalid)) return "<invalid loc>";
1390 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
1394 /// getPresumedLoc - This method returns the "presumed" location of a
1395 /// SourceLocation specifies. A "presumed location" can be modified by \#line
1396 /// or GNU line marker directives. This provides a view on the data that a
1397 /// user should see in diagnostics, for example.
1399 /// Note that a presumed location is always given as the expansion point of an
1400 /// expansion location, not at the spelling location.
1401 PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc,
1402 bool UseLineDirectives) const {
1403 if (Loc.isInvalid()) return PresumedLoc();
1405 // Presumed locations are always for expansion points.
1406 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1408 bool Invalid = false;
1409 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1410 if (Invalid || !Entry.isFile())
1411 return PresumedLoc();
1413 const SrcMgr::FileInfo &FI = Entry.getFile();
1414 const SrcMgr::ContentCache *C = FI.getContentCache();
1416 // To get the source name, first consult the FileEntry (if one exists)
1417 // before the MemBuffer as this will avoid unnecessarily paging in the
1421 Filename = C->OrigEntry->getName();
1423 Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
1425 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1427 return PresumedLoc();
1428 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1430 return PresumedLoc();
1432 SourceLocation IncludeLoc = FI.getIncludeLoc();
1434 // If we have #line directives in this file, update and overwrite the physical
1435 // location info if appropriate.
1436 if (UseLineDirectives && FI.hasLineDirectives()) {
1437 assert(LineTable && "Can't have linetable entries without a LineTable!");
1438 // See if there is a #line directive before this. If so, get it.
1439 if (const LineEntry *Entry =
1440 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
1441 // If the LineEntry indicates a filename, use it.
1442 if (Entry->FilenameID != -1)
1443 Filename = LineTable->getFilename(Entry->FilenameID);
1445 // Use the line number specified by the LineEntry. This line number may
1446 // be multiple lines down from the line entry. Add the difference in
1447 // physical line numbers from the query point and the line marker to the
1449 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1450 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
1452 // Note that column numbers are not molested by line markers.
1454 // Handle virtual #include manipulation.
1455 if (Entry->IncludeOffset) {
1456 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1457 IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
1462 return PresumedLoc(Filename.data(), LineNo, ColNo, IncludeLoc);
1465 /// \brief Returns whether the PresumedLoc for a given SourceLocation is
1466 /// in the main file.
1468 /// This computes the "presumed" location for a SourceLocation, then checks
1469 /// whether it came from a file other than the main file. This is different
1470 /// from isWrittenInMainFile() because it takes line marker directives into
1472 bool SourceManager::isInMainFile(SourceLocation Loc) const {
1473 if (Loc.isInvalid()) return false;
1475 // Presumed locations are always for expansion points.
1476 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1478 bool Invalid = false;
1479 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1480 if (Invalid || !Entry.isFile())
1483 const SrcMgr::FileInfo &FI = Entry.getFile();
1485 // Check if there is a line directive for this location.
1486 if (FI.hasLineDirectives())
1487 if (const LineEntry *Entry =
1488 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
1489 if (Entry->IncludeOffset)
1492 return FI.getIncludeLoc().isInvalid();
1495 /// \brief The size of the SLocEntry that \p FID represents.
1496 unsigned SourceManager::getFileIDSize(FileID FID) const {
1497 bool Invalid = false;
1498 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1503 unsigned NextOffset;
1504 if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
1505 NextOffset = getNextLocalOffset();
1506 else if (ID+1 == -1)
1507 NextOffset = MaxLoadedOffset;
1509 NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
1511 return NextOffset - Entry.getOffset() - 1;
1514 //===----------------------------------------------------------------------===//
1515 // Other miscellaneous methods.
1516 //===----------------------------------------------------------------------===//
1518 /// \brief Retrieve the inode for the given file entry, if possible.
1520 /// This routine involves a system call, and therefore should only be used
1521 /// in non-performance-critical code.
1522 static Optional<llvm::sys::fs::UniqueID>
1523 getActualFileUID(const FileEntry *File) {
1527 llvm::sys::fs::UniqueID ID;
1528 if (llvm::sys::fs::getUniqueID(File->getName(), ID))
1534 /// \brief Get the source location for the given file:line:col triplet.
1536 /// If the source file is included multiple times, the source location will
1537 /// be based upon an arbitrary inclusion.
1538 SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
1540 unsigned Col) const {
1541 assert(SourceFile && "Null source file!");
1542 assert(Line && Col && "Line and column should start from 1!");
1544 FileID FirstFID = translateFile(SourceFile);
1545 return translateLineCol(FirstFID, Line, Col);
1548 /// \brief Get the FileID for the given file.
1550 /// If the source file is included multiple times, the FileID will be the
1551 /// first inclusion.
1552 FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
1553 assert(SourceFile && "Null source file!");
1555 // Find the first file ID that corresponds to the given file.
1558 // First, check the main file ID, since it is common to look for a
1559 // location in the main file.
1560 Optional<llvm::sys::fs::UniqueID> SourceFileUID;
1561 Optional<StringRef> SourceFileName;
1562 if (MainFileID.isValid()) {
1563 bool Invalid = false;
1564 const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1568 if (MainSLoc.isFile()) {
1569 const ContentCache *MainContentCache
1570 = MainSLoc.getFile().getContentCache();
1571 if (!MainContentCache) {
1572 // Can't do anything
1573 } else if (MainContentCache->OrigEntry == SourceFile) {
1574 FirstFID = MainFileID;
1576 // Fall back: check whether we have the same base name and inode
1577 // as the main file.
1578 const FileEntry *MainFile = MainContentCache->OrigEntry;
1579 SourceFileName = llvm::sys::path::filename(SourceFile->getName());
1580 if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) {
1581 SourceFileUID = getActualFileUID(SourceFile);
1582 if (SourceFileUID) {
1583 if (Optional<llvm::sys::fs::UniqueID> MainFileUID =
1584 getActualFileUID(MainFile)) {
1585 if (*SourceFileUID == *MainFileUID) {
1586 FirstFID = MainFileID;
1587 SourceFile = MainFile;
1596 if (FirstFID.isInvalid()) {
1597 // The location we're looking for isn't in the main file; look
1598 // through all of the local source locations.
1599 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1600 bool Invalid = false;
1601 const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid);
1605 if (SLoc.isFile() &&
1606 SLoc.getFile().getContentCache() &&
1607 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1608 FirstFID = FileID::get(I);
1612 // If that still didn't help, try the modules.
1613 if (FirstFID.isInvalid()) {
1614 for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
1615 const SLocEntry &SLoc = getLoadedSLocEntry(I);
1616 if (SLoc.isFile() &&
1617 SLoc.getFile().getContentCache() &&
1618 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1619 FirstFID = FileID::get(-int(I) - 2);
1626 // If we haven't found what we want yet, try again, but this time stat()
1627 // each of the files in case the files have changed since we originally
1629 if (FirstFID.isInvalid() &&
1631 (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) &&
1632 (SourceFileUID || (SourceFileUID = getActualFileUID(SourceFile)))) {
1633 bool Invalid = false;
1634 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1637 const SLocEntry &SLoc = getSLocEntry(IFileID, &Invalid);
1641 if (SLoc.isFile()) {
1642 const ContentCache *FileContentCache
1643 = SLoc.getFile().getContentCache();
1644 const FileEntry *Entry = FileContentCache ? FileContentCache->OrigEntry
1647 *SourceFileName == llvm::sys::path::filename(Entry->getName())) {
1648 if (Optional<llvm::sys::fs::UniqueID> EntryUID =
1649 getActualFileUID(Entry)) {
1650 if (*SourceFileUID == *EntryUID) {
1651 FirstFID = FileID::get(I);
1665 /// \brief Get the source location in \arg FID for the given line:col.
1666 /// Returns null location if \arg FID is not a file SLocEntry.
1667 SourceLocation SourceManager::translateLineCol(FileID FID,
1669 unsigned Col) const {
1670 // Lines are used as a one-based index into a zero-based array. This assert
1671 // checks for possible buffer underruns.
1672 assert(Line && Col && "Line and column should start from 1!");
1674 if (FID.isInvalid())
1675 return SourceLocation();
1677 bool Invalid = false;
1678 const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1680 return SourceLocation();
1682 if (!Entry.isFile())
1683 return SourceLocation();
1685 SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
1687 if (Line == 1 && Col == 1)
1690 ContentCache *Content
1691 = const_cast<ContentCache *>(Entry.getFile().getContentCache());
1693 return SourceLocation();
1695 // If this is the first use of line information for this buffer, compute the
1696 // SourceLineCache for it on demand.
1697 if (!Content->SourceLineCache) {
1698 bool MyInvalid = false;
1699 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
1701 return SourceLocation();
1704 if (Line > Content->NumLines) {
1705 unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
1708 return FileLoc.getLocWithOffset(Size);
1711 llvm::MemoryBuffer *Buffer = Content->getBuffer(Diag, *this);
1712 unsigned FilePos = Content->SourceLineCache[Line - 1];
1713 const char *Buf = Buffer->getBufferStart() + FilePos;
1714 unsigned BufLength = Buffer->getBufferSize() - FilePos;
1716 return FileLoc.getLocWithOffset(FilePos);
1720 // Check that the given column is valid.
1721 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1723 return FileLoc.getLocWithOffset(FilePos + i);
1726 /// \brief Compute a map of macro argument chunks to their expanded source
1727 /// location. Chunks that are not part of a macro argument will map to an
1728 /// invalid source location. e.g. if a file contains one macro argument at
1729 /// offset 100 with length 10, this is how the map will be formed:
1730 /// 0 -> SourceLocation()
1731 /// 100 -> Expanded macro arg location
1732 /// 110 -> SourceLocation()
1733 void SourceManager::computeMacroArgsCache(MacroArgsMap &MacroArgsCache,
1735 assert(FID.isValid());
1737 // Initially no macro argument chunk is present.
1738 MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
1743 // Stop if there are no more FileIDs to check.
1745 if (unsigned(ID) >= local_sloc_entry_size())
1747 } else if (ID == -1) {
1751 bool Invalid = false;
1752 const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);
1755 if (Entry.isFile()) {
1756 SourceLocation IncludeLoc = Entry.getFile().getIncludeLoc();
1757 if (IncludeLoc.isInvalid())
1759 if (!isInFileID(IncludeLoc, FID))
1760 return; // No more files/macros that may be "contained" in this file.
1762 // Skip the files/macros of the #include'd file, we only care about macros
1763 // that lexed macro arguments from our file.
1764 if (Entry.getFile().NumCreatedFIDs)
1765 ID += Entry.getFile().NumCreatedFIDs - 1/*because of next ++ID*/;
1769 const ExpansionInfo &ExpInfo = Entry.getExpansion();
1771 if (ExpInfo.getExpansionLocStart().isFileID()) {
1772 if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
1773 return; // No more files/macros that may be "contained" in this file.
1776 if (!ExpInfo.isMacroArgExpansion())
1779 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1780 ExpInfo.getSpellingLoc(),
1781 SourceLocation::getMacroLoc(Entry.getOffset()),
1782 getFileIDSize(FileID::get(ID)));
1786 void SourceManager::associateFileChunkWithMacroArgExp(
1787 MacroArgsMap &MacroArgsCache,
1789 SourceLocation SpellLoc,
1790 SourceLocation ExpansionLoc,
1791 unsigned ExpansionLength) const {
1792 if (!SpellLoc.isFileID()) {
1793 unsigned SpellBeginOffs = SpellLoc.getOffset();
1794 unsigned SpellEndOffs = SpellBeginOffs + ExpansionLength;
1796 // The spelling range for this macro argument expansion can span multiple
1797 // consecutive FileID entries. Go through each entry contained in the
1798 // spelling range and if one is itself a macro argument expansion, recurse
1799 // and associate the file chunk that it represents.
1801 FileID SpellFID; // Current FileID in the spelling range.
1802 unsigned SpellRelativeOffs;
1803 std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);
1805 const SLocEntry &Entry = getSLocEntry(SpellFID);
1806 unsigned SpellFIDBeginOffs = Entry.getOffset();
1807 unsigned SpellFIDSize = getFileIDSize(SpellFID);
1808 unsigned SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;
1809 const ExpansionInfo &Info = Entry.getExpansion();
1810 if (Info.isMacroArgExpansion()) {
1811 unsigned CurrSpellLength;
1812 if (SpellFIDEndOffs < SpellEndOffs)
1813 CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
1815 CurrSpellLength = ExpansionLength;
1816 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1817 Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),
1818 ExpansionLoc, CurrSpellLength);
1821 if (SpellFIDEndOffs >= SpellEndOffs)
1822 return; // we covered all FileID entries in the spelling range.
1824 // Move to the next FileID entry in the spelling range.
1825 unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
1826 ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);
1827 ExpansionLength -= advance;
1829 SpellRelativeOffs = 0;
1834 assert(SpellLoc.isFileID());
1837 if (!isInFileID(SpellLoc, FID, &BeginOffs))
1840 unsigned EndOffs = BeginOffs + ExpansionLength;
1842 // Add a new chunk for this macro argument. A previous macro argument chunk
1843 // may have been lexed again, so e.g. if the map is
1844 // 0 -> SourceLocation()
1845 // 100 -> Expanded loc #1
1846 // 110 -> SourceLocation()
1847 // and we found a new macro FileID that lexed from offet 105 with length 3,
1848 // the new map will be:
1849 // 0 -> SourceLocation()
1850 // 100 -> Expanded loc #1
1851 // 105 -> Expanded loc #2
1852 // 108 -> Expanded loc #1
1853 // 110 -> SourceLocation()
1855 // Since re-lexed macro chunks will always be the same size or less of
1856 // previous chunks, we only need to find where the ending of the new macro
1857 // chunk is mapped to and update the map with new begin/end mappings.
1859 MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
1861 SourceLocation EndOffsMappedLoc = I->second;
1862 MacroArgsCache[BeginOffs] = ExpansionLoc;
1863 MacroArgsCache[EndOffs] = EndOffsMappedLoc;
1866 /// \brief If \arg Loc points inside a function macro argument, the returned
1867 /// location will be the macro location in which the argument was expanded.
1868 /// If a macro argument is used multiple times, the expanded location will
1869 /// be at the first expansion of the argument.
1873 /// Passing a file location pointing at 'foo', will yield a macro location
1874 /// where 'foo' was expanded into.
1876 SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
1877 if (Loc.isInvalid() || !Loc.isFileID())
1882 std::tie(FID, Offset) = getDecomposedLoc(Loc);
1883 if (FID.isInvalid())
1886 std::unique_ptr<MacroArgsMap> &MacroArgsCache = MacroArgsCacheMap[FID];
1887 if (!MacroArgsCache) {
1888 MacroArgsCache = llvm::make_unique<MacroArgsMap>();
1889 computeMacroArgsCache(*MacroArgsCache, FID);
1892 assert(!MacroArgsCache->empty());
1893 MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
1896 unsigned MacroArgBeginOffs = I->first;
1897 SourceLocation MacroArgExpandedLoc = I->second;
1898 if (MacroArgExpandedLoc.isValid())
1899 return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
1904 std::pair<FileID, unsigned>
1905 SourceManager::getDecomposedIncludedLoc(FileID FID) const {
1906 if (FID.isInvalid())
1907 return std::make_pair(FileID(), 0);
1909 // Uses IncludedLocMap to retrieve/cache the decomposed loc.
1911 typedef std::pair<FileID, unsigned> DecompTy;
1912 typedef llvm::DenseMap<FileID, DecompTy> MapTy;
1913 std::pair<MapTy::iterator, bool>
1914 InsertOp = IncludedLocMap.insert(std::make_pair(FID, DecompTy()));
1915 DecompTy &DecompLoc = InsertOp.first->second;
1916 if (!InsertOp.second)
1917 return DecompLoc; // already in map.
1919 SourceLocation UpperLoc;
1920 bool Invalid = false;
1921 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1923 if (Entry.isExpansion())
1924 UpperLoc = Entry.getExpansion().getExpansionLocStart();
1926 UpperLoc = Entry.getFile().getIncludeLoc();
1929 if (UpperLoc.isValid())
1930 DecompLoc = getDecomposedLoc(UpperLoc);
1935 /// Given a decomposed source location, move it up the include/expansion stack
1936 /// to the parent source location. If this is possible, return the decomposed
1937 /// version of the parent in Loc and return false. If Loc is the top-level
1938 /// entry, return true and don't modify it.
1939 static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1940 const SourceManager &SM) {
1941 std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
1942 if (UpperLoc.first.isInvalid())
1943 return true; // We reached the top.
1949 /// Return the cache entry for comparing the given file IDs
1950 /// for isBeforeInTranslationUnit.
1951 InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
1952 FileID RFID) const {
1953 // This is a magic number for limiting the cache size. It was experimentally
1954 // derived from a small Objective-C project (where the cache filled
1955 // out to ~250 items). We can make it larger if necessary.
1956 enum { MagicCacheSize = 300 };
1957 IsBeforeInTUCacheKey Key(LFID, RFID);
1959 // If the cache size isn't too large, do a lookup and if necessary default
1960 // construct an entry. We can then return it to the caller for direct
1961 // use. When they update the value, the cache will get automatically
1963 if (IBTUCache.size() < MagicCacheSize)
1964 return IBTUCache[Key];
1966 // Otherwise, do a lookup that will not construct a new value.
1967 InBeforeInTUCache::iterator I = IBTUCache.find(Key);
1968 if (I != IBTUCache.end())
1971 // Fall back to the overflow value.
1972 return IBTUCacheOverflow;
1975 /// \brief Determines the order of 2 source locations in the translation unit.
1977 /// \returns true if LHS source location comes before RHS, false otherwise.
1978 bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1979 SourceLocation RHS) const {
1980 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1984 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1985 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
1987 // getDecomposedLoc may have failed to return a valid FileID because, e.g. it
1988 // is a serialized one referring to a file that was removed after we loaded
1990 if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
1991 return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
1993 // If the source locations are in the same file, just compare offsets.
1994 if (LOffs.first == ROffs.first)
1995 return LOffs.second < ROffs.second;
1997 // If we are comparing a source location with multiple locations in the same
1998 // file, we get a big win by caching the result.
1999 InBeforeInTUCacheEntry &IsBeforeInTUCache =
2000 getInBeforeInTUCache(LOffs.first, ROffs.first);
2002 // If we are comparing a source location with multiple locations in the same
2003 // file, we get a big win by caching the result.
2004 if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
2005 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
2007 // Okay, we missed in the cache, start updating the cache for this query.
2008 IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
2009 /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID);
2011 // We need to find the common ancestor. The only way of doing this is to
2012 // build the complete include chain for one and then walking up the chain
2013 // of the other looking for a match.
2014 // We use a map from FileID to Offset to store the chain. Easier than writing
2015 // a custom set hash info that only depends on the first part of a pair.
2016 typedef llvm::SmallDenseMap<FileID, unsigned, 16> LocSet;
2019 LChain.insert(LOffs);
2020 // We catch the case where LOffs is in a file included by ROffs and
2021 // quit early. The other way round unfortunately remains suboptimal.
2022 } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
2024 while((I = LChain.find(ROffs.first)) == LChain.end()) {
2025 if (MoveUpIncludeHierarchy(ROffs, *this))
2026 break; // Met at topmost file.
2028 if (I != LChain.end())
2031 // If we exited because we found a nearest common ancestor, compare the
2032 // locations within the common file and cache them.
2033 if (LOffs.first == ROffs.first) {
2034 IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
2035 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
2038 // If we arrived here, the location is either in a built-ins buffer or
2039 // associated with global inline asm. PR5662 and PR22576 are examples.
2041 // Clear the lookup cache, it depends on a common location.
2042 IsBeforeInTUCache.clear();
2043 StringRef LB = getBuffer(LOffs.first)->getBufferIdentifier();
2044 StringRef RB = getBuffer(ROffs.first)->getBufferIdentifier();
2045 bool LIsBuiltins = LB == "<built-in>";
2046 bool RIsBuiltins = RB == "<built-in>";
2047 // Sort built-in before non-built-in.
2048 if (LIsBuiltins || RIsBuiltins) {
2049 if (LIsBuiltins != RIsBuiltins)
2051 // Both are in built-in buffers, but from different files. We just claim that
2052 // lower IDs come first.
2053 return LOffs.first < ROffs.first;
2055 bool LIsAsm = LB == "<inline asm>";
2056 bool RIsAsm = RB == "<inline asm>";
2057 // Sort assembler after built-ins, but before the rest.
2058 if (LIsAsm || RIsAsm) {
2059 if (LIsAsm != RIsAsm)
2061 assert(LOffs.first == ROffs.first);
2064 bool LIsScratch = LB == "<scratch space>";
2065 bool RIsScratch = RB == "<scratch space>";
2066 // Sort scratch after inline asm, but before the rest.
2067 if (LIsScratch || RIsScratch) {
2068 if (LIsScratch != RIsScratch)
2070 return LOffs.second < ROffs.second;
2072 llvm_unreachable("Unsortable locations found");
2075 void SourceManager::PrintStats() const {
2076 llvm::errs() << "\n*** Source Manager Stats:\n";
2077 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
2078 << " mem buffers mapped.\n";
2079 llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
2080 << llvm::capacity_in_bytes(LocalSLocEntryTable)
2081 << " bytes of capacity), "
2082 << NextLocalOffset << "B of Sloc address space used.\n";
2083 llvm::errs() << LoadedSLocEntryTable.size()
2084 << " loaded SLocEntries allocated, "
2085 << MaxLoadedOffset - CurrentLoadedOffset
2086 << "B of Sloc address space used.\n";
2088 unsigned NumLineNumsComputed = 0;
2089 unsigned NumFileBytesMapped = 0;
2090 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
2091 NumLineNumsComputed += I->second->SourceLineCache != nullptr;
2092 NumFileBytesMapped += I->second->getSizeBytesMapped();
2094 unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
2096 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
2097 << NumLineNumsComputed << " files with line #'s computed, "
2098 << NumMacroArgsComputed << " files with macro args computed.\n";
2099 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
2100 << NumBinaryProbes << " binary.\n";
2103 LLVM_DUMP_METHOD void SourceManager::dump() const {
2104 llvm::raw_ostream &out = llvm::errs();
2106 auto DumpSLocEntry = [&](int ID, const SrcMgr::SLocEntry &Entry,
2107 llvm::Optional<unsigned> NextStart) {
2108 out << "SLocEntry <FileID " << ID << "> " << (Entry.isFile() ? "file" : "expansion")
2109 << " <SourceLocation " << Entry.getOffset() << ":";
2111 out << *NextStart << ">\n";
2114 if (Entry.isFile()) {
2115 auto &FI = Entry.getFile();
2116 if (FI.NumCreatedFIDs)
2117 out << " covers <FileID " << ID << ":" << int(ID + FI.NumCreatedFIDs)
2119 if (FI.getIncludeLoc().isValid())
2120 out << " included from " << FI.getIncludeLoc().getOffset() << "\n";
2121 if (auto *CC = FI.getContentCache()) {
2122 out << " for " << (CC->OrigEntry ? CC->OrigEntry->getName() : "<none>")
2124 if (CC->BufferOverridden)
2125 out << " contents overridden\n";
2126 if (CC->ContentsEntry != CC->OrigEntry) {
2127 out << " contents from "
2128 << (CC->ContentsEntry ? CC->ContentsEntry->getName() : "<none>")
2133 auto &EI = Entry.getExpansion();
2134 out << " spelling from " << EI.getSpellingLoc().getOffset() << "\n";
2135 out << " macro " << (EI.isMacroArgExpansion() ? "arg" : "body")
2136 << " range <" << EI.getExpansionLocStart().getOffset() << ":"
2137 << EI.getExpansionLocEnd().getOffset() << ">\n";
2141 // Dump local SLocEntries.
2142 for (unsigned ID = 0, NumIDs = LocalSLocEntryTable.size(); ID != NumIDs; ++ID) {
2143 DumpSLocEntry(ID, LocalSLocEntryTable[ID],
2144 ID == NumIDs - 1 ? NextLocalOffset
2145 : LocalSLocEntryTable[ID + 1].getOffset());
2147 // Dump loaded SLocEntries.
2148 llvm::Optional<unsigned> NextStart;
2149 for (unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
2150 int ID = -(int)Index - 2;
2151 if (SLocEntryLoaded[Index]) {
2152 DumpSLocEntry(ID, LoadedSLocEntryTable[Index], NextStart);
2153 NextStart = LoadedSLocEntryTable[Index].getOffset();
2160 ExternalSLocEntrySource::~ExternalSLocEntrySource() { }
2162 /// Return the amount of memory used by memory buffers, breaking down
2163 /// by heap-backed versus mmap'ed memory.
2164 SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
2165 size_t malloc_bytes = 0;
2166 size_t mmap_bytes = 0;
2168 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
2169 if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
2170 switch (MemBufferInfos[i]->getMemoryBufferKind()) {
2171 case llvm::MemoryBuffer::MemoryBuffer_MMap:
2172 mmap_bytes += sized_mapped;
2174 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
2175 malloc_bytes += sized_mapped;
2179 return MemoryBufferSizes(malloc_bytes, mmap_bytes);
2182 size_t SourceManager::getDataStructureSizes() const {
2183 size_t size = llvm::capacity_in_bytes(MemBufferInfos)
2184 + llvm::capacity_in_bytes(LocalSLocEntryTable)
2185 + llvm::capacity_in_bytes(LoadedSLocEntryTable)
2186 + llvm::capacity_in_bytes(SLocEntryLoaded)
2187 + llvm::capacity_in_bytes(FileInfos);
2189 if (OverriddenFilesInfo)
2190 size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);