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((B && 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 void SourceManager::initializeForReplay(const SourceManager &Old) {
349 assert(MainFileID.isInvalid() && "expected uninitialized SourceManager");
351 auto CloneContentCache = [&](const ContentCache *Cache) -> ContentCache * {
352 auto *Clone = new (ContentCacheAlloc.Allocate<ContentCache>()) ContentCache;
353 Clone->OrigEntry = Cache->OrigEntry;
354 Clone->ContentsEntry = Cache->ContentsEntry;
355 Clone->BufferOverridden = Cache->BufferOverridden;
356 Clone->IsSystemFile = Cache->IsSystemFile;
357 Clone->IsTransient = Cache->IsTransient;
358 Clone->replaceBuffer(Cache->getRawBuffer(), /*DoNotFree*/true);
362 // Set up our main file ID as a copy of the old source manager's main file.
363 const SLocEntry &OldMainFile = Old.getSLocEntry(Old.getMainFileID());
364 assert(OldMainFile.isFile() && "main file is macro expansion?");
365 auto *MainCC = CloneContentCache(OldMainFile.getFile().getContentCache());
366 MemBufferInfos.push_back(MainCC);
367 setMainFileID(createFileID(MainCC, SourceLocation(),
368 OldMainFile.getFile().getFileCharacteristic(),
371 // Ensure all SLocEntries are loaded from the external source.
372 for (unsigned I = 0, N = Old.LoadedSLocEntryTable.size(); I != N; ++I)
373 if (!Old.SLocEntryLoaded[I])
374 Old.loadSLocEntry(I, nullptr);
376 // Inherit any content cache data from the old source manager.
377 for (auto &FileInfo : Old.FileInfos) {
378 SrcMgr::ContentCache *&Slot = FileInfos[FileInfo.first];
381 Slot = CloneContentCache(FileInfo.second);
385 /// getOrCreateContentCache - Create or return a cached ContentCache for the
388 SourceManager::getOrCreateContentCache(const FileEntry *FileEnt,
390 assert(FileEnt && "Didn't specify a file entry to use?");
392 // Do we already have information about this file?
393 ContentCache *&Entry = FileInfos[FileEnt];
394 if (Entry) return Entry;
396 // Nope, create a new Cache entry.
397 Entry = ContentCacheAlloc.Allocate<ContentCache>();
399 if (OverriddenFilesInfo) {
400 // If the file contents are overridden with contents from another file,
401 // pass that file to ContentCache.
402 llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
403 overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
404 if (overI == OverriddenFilesInfo->OverriddenFiles.end())
405 new (Entry) ContentCache(FileEnt);
407 new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
411 new (Entry) ContentCache(FileEnt);
414 Entry->IsSystemFile = isSystemFile;
415 Entry->IsTransient = FilesAreTransient;
421 /// createMemBufferContentCache - Create a new ContentCache for the specified
422 /// memory buffer. This does no caching.
423 const ContentCache *SourceManager::createMemBufferContentCache(
424 std::unique_ptr<llvm::MemoryBuffer> Buffer) {
425 // Add a new ContentCache to the MemBufferInfos list and return it.
426 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
427 new (Entry) ContentCache();
428 MemBufferInfos.push_back(Entry);
429 Entry->setBuffer(std::move(Buffer));
433 const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
434 bool *Invalid) const {
435 assert(!SLocEntryLoaded[Index]);
436 if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
439 // If the file of the SLocEntry changed we could still have loaded it.
440 if (!SLocEntryLoaded[Index]) {
441 // Try to recover; create a SLocEntry so the rest of clang can handle it.
442 LoadedSLocEntryTable[Index] = SLocEntry::get(0,
443 FileInfo::get(SourceLocation(),
444 getFakeContentCacheForRecovery(),
449 return LoadedSLocEntryTable[Index];
452 std::pair<int, unsigned>
453 SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
454 unsigned TotalSize) {
455 assert(ExternalSLocEntries && "Don't have an external sloc source");
456 // Make sure we're not about to run out of source locations.
457 if (CurrentLoadedOffset - TotalSize < NextLocalOffset)
458 return std::make_pair(0, 0);
459 LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
460 SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
461 CurrentLoadedOffset -= TotalSize;
462 int ID = LoadedSLocEntryTable.size();
463 return std::make_pair(-ID - 1, CurrentLoadedOffset);
466 /// \brief As part of recovering from missing or changed content, produce a
467 /// fake, non-empty buffer.
468 llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const {
469 if (!FakeBufferForRecovery)
470 FakeBufferForRecovery =
471 llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
473 return FakeBufferForRecovery.get();
476 /// \brief As part of recovering from missing or changed content, produce a
477 /// fake content cache.
478 const SrcMgr::ContentCache *
479 SourceManager::getFakeContentCacheForRecovery() const {
480 if (!FakeContentCacheForRecovery) {
481 FakeContentCacheForRecovery = llvm::make_unique<SrcMgr::ContentCache>();
482 FakeContentCacheForRecovery->replaceBuffer(getFakeBufferForRecovery(),
485 return FakeContentCacheForRecovery.get();
488 /// \brief Returns the previous in-order FileID or an invalid FileID if there
489 /// is no previous one.
490 FileID SourceManager::getPreviousFileID(FileID FID) const {
501 } else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {
505 return FileID::get(ID-1);
508 /// \brief Returns the next in-order FileID or an invalid FileID if there is
510 FileID SourceManager::getNextFileID(FileID FID) const {
516 if (unsigned(ID+1) >= local_sloc_entry_size())
518 } else if (ID+1 >= -1) {
522 return FileID::get(ID+1);
525 //===----------------------------------------------------------------------===//
526 // Methods to create new FileID's and macro expansions.
527 //===----------------------------------------------------------------------===//
529 /// createFileID - Create a new FileID for the specified ContentCache and
530 /// include position. This works regardless of whether the ContentCache
531 /// corresponds to a file or some other input source.
532 FileID SourceManager::createFileID(const ContentCache *File,
533 SourceLocation IncludePos,
534 SrcMgr::CharacteristicKind FileCharacter,
535 int LoadedID, unsigned LoadedOffset) {
537 assert(LoadedID != -1 && "Loading sentinel FileID");
538 unsigned Index = unsigned(-LoadedID) - 2;
539 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
540 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
541 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset,
542 FileInfo::get(IncludePos, File, FileCharacter));
543 SLocEntryLoaded[Index] = true;
544 return FileID::get(LoadedID);
546 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset,
547 FileInfo::get(IncludePos, File,
549 unsigned FileSize = File->getSize();
550 assert(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
551 NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset &&
552 "Ran out of source locations!");
553 // We do a +1 here because we want a SourceLocation that means "the end of the
554 // file", e.g. for the "no newline at the end of the file" diagnostic.
555 NextLocalOffset += FileSize + 1;
557 // Set LastFileIDLookup to the newly created file. The next getFileID call is
558 // almost guaranteed to be from that file.
559 FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
560 return LastFileIDLookup = FID;
564 SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc,
565 SourceLocation ExpansionLoc,
566 unsigned TokLength) {
567 ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
569 return createExpansionLocImpl(Info, TokLength);
573 SourceManager::createExpansionLoc(SourceLocation SpellingLoc,
574 SourceLocation ExpansionLocStart,
575 SourceLocation ExpansionLocEnd,
578 unsigned LoadedOffset) {
579 ExpansionInfo Info = ExpansionInfo::create(SpellingLoc, ExpansionLocStart,
581 return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset);
585 SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
588 unsigned LoadedOffset) {
590 assert(LoadedID != -1 && "Loading sentinel FileID");
591 unsigned Index = unsigned(-LoadedID) - 2;
592 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
593 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
594 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
595 SLocEntryLoaded[Index] = true;
596 return SourceLocation::getMacroLoc(LoadedOffset);
598 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
599 assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&
600 NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&
601 "Ran out of source locations!");
602 // See createFileID for that +1.
603 NextLocalOffset += TokLength + 1;
604 return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
607 llvm::MemoryBuffer *SourceManager::getMemoryBufferForFile(const FileEntry *File,
609 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
610 assert(IR && "getOrCreateContentCache() cannot return NULL");
611 return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
614 void SourceManager::overrideFileContents(const FileEntry *SourceFile,
615 llvm::MemoryBuffer *Buffer,
617 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
618 assert(IR && "getOrCreateContentCache() cannot return NULL");
620 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
621 const_cast<SrcMgr::ContentCache *>(IR)->BufferOverridden = true;
623 getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
626 void SourceManager::overrideFileContents(const FileEntry *SourceFile,
627 const FileEntry *NewFile) {
628 assert(SourceFile->getSize() == NewFile->getSize() &&
629 "Different sizes, use the FileManager to create a virtual file with "
631 assert(FileInfos.count(SourceFile) == 0 &&
632 "This function should be called at the initialization stage, before "
633 "any parsing occurs.");
634 getOverriddenFilesInfo().OverriddenFiles[SourceFile] = NewFile;
637 void SourceManager::disableFileContentsOverride(const FileEntry *File) {
638 if (!isFileOverridden(File))
641 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
642 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(nullptr);
643 const_cast<SrcMgr::ContentCache *>(IR)->ContentsEntry = IR->OrigEntry;
645 assert(OverriddenFilesInfo);
646 OverriddenFilesInfo->OverriddenFiles.erase(File);
647 OverriddenFilesInfo->OverriddenFilesWithBuffer.erase(File);
650 void SourceManager::setFileIsTransient(const FileEntry *File) {
651 const SrcMgr::ContentCache *CC = getOrCreateContentCache(File);
652 const_cast<SrcMgr::ContentCache *>(CC)->IsTransient = true;
655 StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
656 bool MyInvalid = false;
657 const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid);
658 if (!SLoc.isFile() || MyInvalid) {
661 return "<<<<<INVALID SOURCE LOCATION>>>>>";
664 llvm::MemoryBuffer *Buf = SLoc.getFile().getContentCache()->getBuffer(
665 Diag, *this, SourceLocation(), &MyInvalid);
667 *Invalid = MyInvalid;
670 return "<<<<<INVALID SOURCE LOCATION>>>>>";
672 return Buf->getBuffer();
675 //===----------------------------------------------------------------------===//
676 // SourceLocation manipulation methods.
677 //===----------------------------------------------------------------------===//
679 /// \brief Return the FileID for a SourceLocation.
681 /// This is the cache-miss path of getFileID. Not as hot as that function, but
682 /// still very important. It is responsible for finding the entry in the
683 /// SLocEntry tables that contains the specified location.
684 FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
686 return FileID::get(0);
688 // Now it is time to search for the correct file. See where the SLocOffset
689 // sits in the global view and consult local or loaded buffers for it.
690 if (SLocOffset < NextLocalOffset)
691 return getFileIDLocal(SLocOffset);
692 return getFileIDLoaded(SLocOffset);
695 /// \brief Return the FileID for a SourceLocation with a low offset.
697 /// This function knows that the SourceLocation is in a local buffer, not a
699 FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const {
700 assert(SLocOffset < NextLocalOffset && "Bad function choice");
702 // After the first and second level caches, I see two common sorts of
703 // behavior: 1) a lot of searched FileID's are "near" the cached file
704 // location or are "near" the cached expansion location. 2) others are just
705 // completely random and may be a very long way away.
707 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
708 // then we fall back to a less cache efficient, but more scalable, binary
709 // search to find the location.
711 // See if this is near the file point - worst case we start scanning from the
712 // most newly created FileID.
713 const SrcMgr::SLocEntry *I;
715 if (LastFileIDLookup.ID < 0 ||
716 LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
717 // Neither loc prunes our search.
718 I = LocalSLocEntryTable.end();
720 // Perhaps it is near the file point.
721 I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
724 // Find the FileID that contains this. "I" is an iterator that points to a
725 // FileID whose offset is known to be larger than SLocOffset.
726 unsigned NumProbes = 0;
729 if (I->getOffset() <= SLocOffset) {
730 FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
732 // If this isn't an expansion, remember it. We have good locality across
734 if (!I->isExpansion())
735 LastFileIDLookup = Res;
736 NumLinearScans += NumProbes+1;
739 if (++NumProbes == 8)
743 // Convert "I" back into an index. We know that it is an entry whose index is
744 // larger than the offset we are looking for.
745 unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
746 // LessIndex - This is the lower bound of the range that we're searching.
747 // We know that the offset corresponding to the FileID is is less than
749 unsigned LessIndex = 0;
752 bool Invalid = false;
753 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
754 unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
756 return FileID::get(0);
760 // If the offset of the midpoint is too large, chop the high side of the
761 // range to the midpoint.
762 if (MidOffset > SLocOffset) {
763 GreaterIndex = MiddleIndex;
767 // If the middle index contains the value, succeed and return.
768 // FIXME: This could be made faster by using a function that's aware of
769 // being in the local area.
770 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
771 FileID Res = FileID::get(MiddleIndex);
773 // If this isn't a macro expansion, remember it. We have good locality
774 // across FileID lookups.
775 if (!LocalSLocEntryTable[MiddleIndex].isExpansion())
776 LastFileIDLookup = Res;
777 NumBinaryProbes += NumProbes;
781 // Otherwise, move the low-side up to the middle index.
782 LessIndex = MiddleIndex;
786 /// \brief Return the FileID for a SourceLocation with a high offset.
788 /// This function knows that the SourceLocation is in a loaded buffer, not a
790 FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
791 // Sanity checking, otherwise a bug may lead to hanging in release build.
792 if (SLocOffset < CurrentLoadedOffset) {
793 assert(0 && "Invalid SLocOffset or bad function choice");
797 // Essentially the same as the local case, but the loaded array is sorted
798 // in the other direction.
800 // First do a linear scan from the last lookup position, if possible.
802 int LastID = LastFileIDLookup.ID;
803 if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
806 I = (-LastID - 2) + 1;
809 for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
810 // Make sure the entry is loaded!
811 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
812 if (E.getOffset() <= SLocOffset) {
813 FileID Res = FileID::get(-int(I) - 2);
815 if (!E.isExpansion())
816 LastFileIDLookup = Res;
817 NumLinearScans += NumProbes + 1;
822 // Linear scan failed. Do the binary search. Note the reverse sorting of the
823 // table: GreaterIndex is the one where the offset is greater, which is
824 // actually a lower index!
825 unsigned GreaterIndex = I;
826 unsigned LessIndex = LoadedSLocEntryTable.size();
830 unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
831 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
832 if (E.getOffset() == 0)
833 return FileID(); // invalid entry.
837 if (E.getOffset() > SLocOffset) {
838 // Sanity checking, otherwise a bug may lead to hanging in release build.
839 if (GreaterIndex == MiddleIndex) {
840 assert(0 && "binary search missed the entry");
843 GreaterIndex = MiddleIndex;
847 if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
848 FileID Res = FileID::get(-int(MiddleIndex) - 2);
849 if (!E.isExpansion())
850 LastFileIDLookup = Res;
851 NumBinaryProbes += NumProbes;
855 // Sanity checking, otherwise a bug may lead to hanging in release build.
856 if (LessIndex == MiddleIndex) {
857 assert(0 && "binary search missed the entry");
860 LessIndex = MiddleIndex;
864 SourceLocation SourceManager::
865 getExpansionLocSlowCase(SourceLocation Loc) const {
867 // Note: If Loc indicates an offset into a token that came from a macro
868 // expansion (e.g. the 5th character of the token) we do not want to add
869 // this offset when going to the expansion location. The expansion
870 // location is the macro invocation, which the offset has nothing to do
871 // with. This is unlike when we get the spelling loc, because the offset
872 // directly correspond to the token whose spelling we're inspecting.
873 Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
874 } while (!Loc.isFileID());
879 SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
881 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
882 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
883 Loc = Loc.getLocWithOffset(LocInfo.second);
884 } while (!Loc.isFileID());
888 SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
890 if (isMacroArgExpansion(Loc))
891 Loc = getImmediateSpellingLoc(Loc);
893 Loc = getImmediateExpansionRange(Loc).first;
894 } while (!Loc.isFileID());
899 std::pair<FileID, unsigned>
900 SourceManager::getDecomposedExpansionLocSlowCase(
901 const SrcMgr::SLocEntry *E) const {
902 // If this is an expansion record, walk through all the expansion points.
907 Loc = E->getExpansion().getExpansionLocStart();
909 FID = getFileID(Loc);
910 E = &getSLocEntry(FID);
911 Offset = Loc.getOffset()-E->getOffset();
912 } while (!Loc.isFileID());
914 return std::make_pair(FID, Offset);
917 std::pair<FileID, unsigned>
918 SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
919 unsigned Offset) const {
920 // If this is an expansion record, walk through all the expansion points.
924 Loc = E->getExpansion().getSpellingLoc();
925 Loc = Loc.getLocWithOffset(Offset);
927 FID = getFileID(Loc);
928 E = &getSLocEntry(FID);
929 Offset = Loc.getOffset()-E->getOffset();
930 } while (!Loc.isFileID());
932 return std::make_pair(FID, Offset);
935 /// getImmediateSpellingLoc - Given a SourceLocation object, return the
936 /// spelling location referenced by the ID. This is the first level down
937 /// towards the place where the characters that make up the lexed token can be
938 /// found. This should not generally be used by clients.
939 SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
940 if (Loc.isFileID()) return Loc;
941 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
942 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
943 return Loc.getLocWithOffset(LocInfo.second);
947 /// getImmediateExpansionRange - Loc is required to be an expansion location.
948 /// Return the start/end of the expansion information.
949 std::pair<SourceLocation,SourceLocation>
950 SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
951 assert(Loc.isMacroID() && "Not a macro expansion loc!");
952 const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
953 return Expansion.getExpansionLocRange();
956 /// getExpansionRange - Given a SourceLocation object, return the range of
957 /// tokens covered by the expansion in the ultimate file.
958 std::pair<SourceLocation,SourceLocation>
959 SourceManager::getExpansionRange(SourceLocation Loc) const {
960 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
962 std::pair<SourceLocation,SourceLocation> Res =
963 getImmediateExpansionRange(Loc);
965 // Fully resolve the start and end locations to their ultimate expansion
967 while (!Res.first.isFileID())
968 Res.first = getImmediateExpansionRange(Res.first).first;
969 while (!Res.second.isFileID())
970 Res.second = getImmediateExpansionRange(Res.second).second;
974 bool SourceManager::isMacroArgExpansion(SourceLocation Loc,
975 SourceLocation *StartLoc) const {
976 if (!Loc.isMacroID()) return false;
978 FileID FID = getFileID(Loc);
979 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
980 if (!Expansion.isMacroArgExpansion()) return false;
983 *StartLoc = Expansion.getExpansionLocStart();
987 bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const {
988 if (!Loc.isMacroID()) return false;
990 FileID FID = getFileID(Loc);
991 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
992 return Expansion.isMacroBodyExpansion();
995 bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
996 SourceLocation *MacroBegin) const {
997 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
999 std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);
1000 if (DecompLoc.second > 0)
1001 return false; // Does not point at the start of expansion range.
1003 bool Invalid = false;
1004 const SrcMgr::ExpansionInfo &ExpInfo =
1005 getSLocEntry(DecompLoc.first, &Invalid).getExpansion();
1008 SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();
1010 if (ExpInfo.isMacroArgExpansion()) {
1011 // For macro argument expansions, check if the previous FileID is part of
1012 // the same argument expansion, in which case this Loc is not at the
1013 // beginning of the expansion.
1014 FileID PrevFID = getPreviousFileID(DecompLoc.first);
1015 if (!PrevFID.isInvalid()) {
1016 const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);
1019 if (PrevEntry.isExpansion() &&
1020 PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)
1026 *MacroBegin = ExpLoc;
1030 bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
1031 SourceLocation *MacroEnd) const {
1032 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1034 FileID FID = getFileID(Loc);
1035 SourceLocation NextLoc = Loc.getLocWithOffset(1);
1036 if (isInFileID(NextLoc, FID))
1037 return false; // Does not point at the end of expansion range.
1039 bool Invalid = false;
1040 const SrcMgr::ExpansionInfo &ExpInfo =
1041 getSLocEntry(FID, &Invalid).getExpansion();
1045 if (ExpInfo.isMacroArgExpansion()) {
1046 // For macro argument expansions, check if the next FileID is part of the
1047 // same argument expansion, in which case this Loc is not at the end of the
1049 FileID NextFID = getNextFileID(FID);
1050 if (!NextFID.isInvalid()) {
1051 const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);
1054 if (NextEntry.isExpansion() &&
1055 NextEntry.getExpansion().getExpansionLocStart() ==
1056 ExpInfo.getExpansionLocStart())
1062 *MacroEnd = ExpInfo.getExpansionLocEnd();
1067 //===----------------------------------------------------------------------===//
1068 // Queries about the code at a SourceLocation.
1069 //===----------------------------------------------------------------------===//
1071 /// getCharacterData - Return a pointer to the start of the specified location
1072 /// in the appropriate MemoryBuffer.
1073 const char *SourceManager::getCharacterData(SourceLocation SL,
1074 bool *Invalid) const {
1075 // Note that this is a hot function in the getSpelling() path, which is
1076 // heavily used by -E mode.
1077 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
1079 // Note that calling 'getBuffer()' may lazily page in a source file.
1080 bool CharDataInvalid = false;
1081 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
1082 if (CharDataInvalid || !Entry.isFile()) {
1086 return "<<<<INVALID BUFFER>>>>";
1088 llvm::MemoryBuffer *Buffer = Entry.getFile().getContentCache()->getBuffer(
1089 Diag, *this, SourceLocation(), &CharDataInvalid);
1091 *Invalid = CharDataInvalid;
1092 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
1096 /// getColumnNumber - Return the column # for the specified file position.
1097 /// this is significantly cheaper to compute than the line number.
1098 unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
1099 bool *Invalid) const {
1100 bool MyInvalid = false;
1101 llvm::MemoryBuffer *MemBuf = getBuffer(FID, &MyInvalid);
1103 *Invalid = MyInvalid;
1108 // It is okay to request a position just past the end of the buffer.
1109 if (FilePos > MemBuf->getBufferSize()) {
1115 const char *Buf = MemBuf->getBufferStart();
1116 // See if we just calculated the line number for this FilePos and can use
1117 // that to lookup the start of the line instead of searching for it.
1118 if (LastLineNoFileIDQuery == FID &&
1119 LastLineNoContentCache->SourceLineCache != nullptr &&
1120 LastLineNoResult < LastLineNoContentCache->NumLines) {
1121 unsigned *SourceLineCache = LastLineNoContentCache->SourceLineCache;
1122 unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
1123 unsigned LineEnd = SourceLineCache[LastLineNoResult];
1124 if (FilePos >= LineStart && FilePos < LineEnd) {
1125 // LineEnd is the LineStart of the next line.
1126 // A line ends with separator LF or CR+LF on Windows.
1127 // FilePos might point to the last separator,
1128 // but we need a column number at most 1 + the last column.
1129 if (FilePos + 1 == LineEnd && FilePos > LineStart) {
1130 if (Buf[FilePos - 1] == '\r' || Buf[FilePos - 1] == '\n')
1133 return FilePos - LineStart + 1;
1137 unsigned LineStart = FilePos;
1138 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
1140 return FilePos-LineStart+1;
1143 // isInvalid - Return the result of calling loc.isInvalid(), and
1144 // if Invalid is not null, set its value to same.
1145 template<typename LocType>
1146 static bool isInvalid(LocType Loc, bool *Invalid) {
1147 bool MyInvalid = Loc.isInvalid();
1149 *Invalid = MyInvalid;
1153 unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
1154 bool *Invalid) const {
1155 if (isInvalid(Loc, Invalid)) return 0;
1156 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1157 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1160 unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
1161 bool *Invalid) const {
1162 if (isInvalid(Loc, Invalid)) return 0;
1163 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1164 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1167 unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
1168 bool *Invalid) const {
1169 PresumedLoc PLoc = getPresumedLoc(Loc);
1170 if (isInvalid(PLoc, Invalid)) return 0;
1171 return PLoc.getColumn();
1175 #include <emmintrin.h>
1178 static LLVM_ATTRIBUTE_NOINLINE void
1179 ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
1180 llvm::BumpPtrAllocator &Alloc,
1181 const SourceManager &SM, bool &Invalid);
1182 static void ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
1183 llvm::BumpPtrAllocator &Alloc,
1184 const SourceManager &SM, bool &Invalid) {
1185 // Note that calling 'getBuffer()' may lazily page in the file.
1186 MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(), &Invalid);
1190 // Find the file offsets of all of the *physical* source lines. This does
1191 // not look at trigraphs, escaped newlines, or anything else tricky.
1192 SmallVector<unsigned, 256> LineOffsets;
1194 // Line #1 starts at char 0.
1195 LineOffsets.push_back(0);
1197 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
1198 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
1201 // Skip over the contents of the line.
1202 const unsigned char *NextBuf = (const unsigned char *)Buf;
1205 // Try to skip to the next newline using SSE instructions. This is very
1206 // performance sensitive for programs with lots of diagnostics and in -E
1208 __m128i CRs = _mm_set1_epi8('\r');
1209 __m128i LFs = _mm_set1_epi8('\n');
1211 // First fix up the alignment to 16 bytes.
1212 while (((uintptr_t)NextBuf & 0xF) != 0) {
1213 if (*NextBuf == '\n' || *NextBuf == '\r' || *NextBuf == '\0')
1214 goto FoundSpecialChar;
1218 // Scan 16 byte chunks for '\r' and '\n'. Ignore '\0'.
1219 while (NextBuf+16 <= End) {
1220 const __m128i Chunk = *(const __m128i*)NextBuf;
1221 __m128i Cmp = _mm_or_si128(_mm_cmpeq_epi8(Chunk, CRs),
1222 _mm_cmpeq_epi8(Chunk, LFs));
1223 unsigned Mask = _mm_movemask_epi8(Cmp);
1225 // If we found a newline, adjust the pointer and jump to the handling code.
1227 NextBuf += llvm::countTrailingZeros(Mask);
1228 goto FoundSpecialChar;
1234 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
1240 Offs += NextBuf-Buf;
1243 if (Buf[0] == '\n' || Buf[0] == '\r') {
1244 // If this is \n\r or \r\n, skip both characters.
1245 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1]) {
1251 LineOffsets.push_back(Offs);
1253 // Otherwise, this is a null. If end of file, exit.
1254 if (Buf == End) break;
1255 // Otherwise, skip the null.
1261 // Copy the offsets into the FileInfo structure.
1262 FI->NumLines = LineOffsets.size();
1263 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
1264 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
1267 /// getLineNumber - Given a SourceLocation, return the spelling line number
1268 /// for the position indicated. This requires building and caching a table of
1269 /// line offsets for the MemoryBuffer, so this is not cheap: use only when
1270 /// about to emit a diagnostic.
1271 unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1272 bool *Invalid) const {
1273 if (FID.isInvalid()) {
1279 ContentCache *Content;
1280 if (LastLineNoFileIDQuery == FID)
1281 Content = LastLineNoContentCache;
1283 bool MyInvalid = false;
1284 const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1285 if (MyInvalid || !Entry.isFile()) {
1291 Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
1294 // If this is the first use of line information for this buffer, compute the
1295 /// SourceLineCache for it on demand.
1296 if (!Content->SourceLineCache) {
1297 bool MyInvalid = false;
1298 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
1300 *Invalid = MyInvalid;
1306 // Okay, we know we have a line number table. Do a binary search to find the
1307 // line number that this character position lands on.
1308 unsigned *SourceLineCache = Content->SourceLineCache;
1309 unsigned *SourceLineCacheStart = SourceLineCache;
1310 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
1312 unsigned QueriedFilePos = FilePos+1;
1314 // FIXME: I would like to be convinced that this code is worth being as
1315 // complicated as it is, binary search isn't that slow.
1317 // If it is worth being optimized, then in my opinion it could be more
1318 // performant, simpler, and more obviously correct by just "galloping" outward
1319 // from the queried file position. In fact, this could be incorporated into a
1320 // generic algorithm such as lower_bound_with_hint.
1322 // If someone gives me a test case where this matters, and I will do it! - DWD
1324 // If the previous query was to the same file, we know both the file pos from
1325 // that query and the line number returned. This allows us to narrow the
1326 // search space from the entire file to something near the match.
1327 if (LastLineNoFileIDQuery == FID) {
1328 if (QueriedFilePos >= LastLineNoFilePos) {
1329 // FIXME: Potential overflow?
1330 SourceLineCache = SourceLineCache+LastLineNoResult-1;
1332 // The query is likely to be nearby the previous one. Here we check to
1333 // see if it is within 5, 10 or 20 lines. It can be far away in cases
1334 // where big comment blocks and vertical whitespace eat up lines but
1335 // contribute no tokens.
1336 if (SourceLineCache+5 < SourceLineCacheEnd) {
1337 if (SourceLineCache[5] > QueriedFilePos)
1338 SourceLineCacheEnd = SourceLineCache+5;
1339 else if (SourceLineCache+10 < SourceLineCacheEnd) {
1340 if (SourceLineCache[10] > QueriedFilePos)
1341 SourceLineCacheEnd = SourceLineCache+10;
1342 else if (SourceLineCache+20 < SourceLineCacheEnd) {
1343 if (SourceLineCache[20] > QueriedFilePos)
1344 SourceLineCacheEnd = SourceLineCache+20;
1349 if (LastLineNoResult < Content->NumLines)
1350 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
1355 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
1356 unsigned LineNo = Pos-SourceLineCacheStart;
1358 LastLineNoFileIDQuery = FID;
1359 LastLineNoContentCache = Content;
1360 LastLineNoFilePos = QueriedFilePos;
1361 LastLineNoResult = LineNo;
1365 unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1366 bool *Invalid) const {
1367 if (isInvalid(Loc, Invalid)) return 0;
1368 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1369 return getLineNumber(LocInfo.first, LocInfo.second);
1371 unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
1372 bool *Invalid) const {
1373 if (isInvalid(Loc, Invalid)) return 0;
1374 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1375 return getLineNumber(LocInfo.first, LocInfo.second);
1377 unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
1378 bool *Invalid) const {
1379 PresumedLoc PLoc = getPresumedLoc(Loc);
1380 if (isInvalid(PLoc, Invalid)) return 0;
1381 return PLoc.getLine();
1384 /// getFileCharacteristic - return the file characteristic of the specified
1385 /// source location, indicating whether this is a normal file, a system
1386 /// header, or an "implicit extern C" system header.
1388 /// This state can be modified with flags on GNU linemarker directives like:
1390 /// which changes all source locations in the current file after that to be
1391 /// considered to be from a system header.
1392 SrcMgr::CharacteristicKind
1393 SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1394 assert(Loc.isValid() && "Can't get file characteristic of invalid loc!");
1395 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1396 bool Invalid = false;
1397 const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
1398 if (Invalid || !SEntry.isFile())
1401 const SrcMgr::FileInfo &FI = SEntry.getFile();
1403 // If there are no #line directives in this file, just return the whole-file
1405 if (!FI.hasLineDirectives())
1406 return FI.getFileCharacteristic();
1408 assert(LineTable && "Can't have linetable entries without a LineTable!");
1409 // See if there is a #line directive before the location.
1410 const LineEntry *Entry =
1411 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
1413 // If this is before the first line marker, use the file characteristic.
1415 return FI.getFileCharacteristic();
1417 return Entry->FileKind;
1420 /// Return the filename or buffer identifier of the buffer the location is in.
1421 /// Note that this name does not respect \#line directives. Use getPresumedLoc
1422 /// for normal clients.
1423 StringRef SourceManager::getBufferName(SourceLocation Loc,
1424 bool *Invalid) const {
1425 if (isInvalid(Loc, Invalid)) return "<invalid loc>";
1427 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
1431 /// getPresumedLoc - This method returns the "presumed" location of a
1432 /// SourceLocation specifies. A "presumed location" can be modified by \#line
1433 /// or GNU line marker directives. This provides a view on the data that a
1434 /// user should see in diagnostics, for example.
1436 /// Note that a presumed location is always given as the expansion point of an
1437 /// expansion location, not at the spelling location.
1438 PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc,
1439 bool UseLineDirectives) const {
1440 if (Loc.isInvalid()) return PresumedLoc();
1442 // Presumed locations are always for expansion points.
1443 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1445 bool Invalid = false;
1446 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1447 if (Invalid || !Entry.isFile())
1448 return PresumedLoc();
1450 const SrcMgr::FileInfo &FI = Entry.getFile();
1451 const SrcMgr::ContentCache *C = FI.getContentCache();
1453 // To get the source name, first consult the FileEntry (if one exists)
1454 // before the MemBuffer as this will avoid unnecessarily paging in the
1458 Filename = C->OrigEntry->getName();
1460 Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
1462 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1464 return PresumedLoc();
1465 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1467 return PresumedLoc();
1469 SourceLocation IncludeLoc = FI.getIncludeLoc();
1471 // If we have #line directives in this file, update and overwrite the physical
1472 // location info if appropriate.
1473 if (UseLineDirectives && FI.hasLineDirectives()) {
1474 assert(LineTable && "Can't have linetable entries without a LineTable!");
1475 // See if there is a #line directive before this. If so, get it.
1476 if (const LineEntry *Entry =
1477 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
1478 // If the LineEntry indicates a filename, use it.
1479 if (Entry->FilenameID != -1)
1480 Filename = LineTable->getFilename(Entry->FilenameID);
1482 // Use the line number specified by the LineEntry. This line number may
1483 // be multiple lines down from the line entry. Add the difference in
1484 // physical line numbers from the query point and the line marker to the
1486 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1487 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
1489 // Note that column numbers are not molested by line markers.
1491 // Handle virtual #include manipulation.
1492 if (Entry->IncludeOffset) {
1493 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1494 IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
1499 return PresumedLoc(Filename.data(), LineNo, ColNo, IncludeLoc);
1502 /// \brief Returns whether the PresumedLoc for a given SourceLocation is
1503 /// in the main file.
1505 /// This computes the "presumed" location for a SourceLocation, then checks
1506 /// whether it came from a file other than the main file. This is different
1507 /// from isWrittenInMainFile() because it takes line marker directives into
1509 bool SourceManager::isInMainFile(SourceLocation Loc) const {
1510 if (Loc.isInvalid()) return false;
1512 // Presumed locations are always for expansion points.
1513 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1515 bool Invalid = false;
1516 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1517 if (Invalid || !Entry.isFile())
1520 const SrcMgr::FileInfo &FI = Entry.getFile();
1522 // Check if there is a line directive for this location.
1523 if (FI.hasLineDirectives())
1524 if (const LineEntry *Entry =
1525 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
1526 if (Entry->IncludeOffset)
1529 return FI.getIncludeLoc().isInvalid();
1532 /// \brief The size of the SLocEntry that \p FID represents.
1533 unsigned SourceManager::getFileIDSize(FileID FID) const {
1534 bool Invalid = false;
1535 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1540 unsigned NextOffset;
1541 if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
1542 NextOffset = getNextLocalOffset();
1543 else if (ID+1 == -1)
1544 NextOffset = MaxLoadedOffset;
1546 NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
1548 return NextOffset - Entry.getOffset() - 1;
1551 //===----------------------------------------------------------------------===//
1552 // Other miscellaneous methods.
1553 //===----------------------------------------------------------------------===//
1555 /// \brief Retrieve the inode for the given file entry, if possible.
1557 /// This routine involves a system call, and therefore should only be used
1558 /// in non-performance-critical code.
1559 static Optional<llvm::sys::fs::UniqueID>
1560 getActualFileUID(const FileEntry *File) {
1564 llvm::sys::fs::UniqueID ID;
1565 if (llvm::sys::fs::getUniqueID(File->getName(), ID))
1571 /// \brief Get the source location for the given file:line:col triplet.
1573 /// If the source file is included multiple times, the source location will
1574 /// be based upon an arbitrary inclusion.
1575 SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
1577 unsigned Col) const {
1578 assert(SourceFile && "Null source file!");
1579 assert(Line && Col && "Line and column should start from 1!");
1581 FileID FirstFID = translateFile(SourceFile);
1582 return translateLineCol(FirstFID, Line, Col);
1585 /// \brief Get the FileID for the given file.
1587 /// If the source file is included multiple times, the FileID will be the
1588 /// first inclusion.
1589 FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
1590 assert(SourceFile && "Null source file!");
1592 // Find the first file ID that corresponds to the given file.
1595 // First, check the main file ID, since it is common to look for a
1596 // location in the main file.
1597 Optional<llvm::sys::fs::UniqueID> SourceFileUID;
1598 Optional<StringRef> SourceFileName;
1599 if (MainFileID.isValid()) {
1600 bool Invalid = false;
1601 const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1605 if (MainSLoc.isFile()) {
1606 const ContentCache *MainContentCache
1607 = MainSLoc.getFile().getContentCache();
1608 if (!MainContentCache) {
1609 // Can't do anything
1610 } else if (MainContentCache->OrigEntry == SourceFile) {
1611 FirstFID = MainFileID;
1613 // Fall back: check whether we have the same base name and inode
1614 // as the main file.
1615 const FileEntry *MainFile = MainContentCache->OrigEntry;
1616 SourceFileName = llvm::sys::path::filename(SourceFile->getName());
1617 if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) {
1618 SourceFileUID = getActualFileUID(SourceFile);
1619 if (SourceFileUID) {
1620 if (Optional<llvm::sys::fs::UniqueID> MainFileUID =
1621 getActualFileUID(MainFile)) {
1622 if (*SourceFileUID == *MainFileUID) {
1623 FirstFID = MainFileID;
1624 SourceFile = MainFile;
1633 if (FirstFID.isInvalid()) {
1634 // The location we're looking for isn't in the main file; look
1635 // through all of the local source locations.
1636 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1637 bool Invalid = false;
1638 const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid);
1642 if (SLoc.isFile() &&
1643 SLoc.getFile().getContentCache() &&
1644 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1645 FirstFID = FileID::get(I);
1649 // If that still didn't help, try the modules.
1650 if (FirstFID.isInvalid()) {
1651 for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
1652 const SLocEntry &SLoc = getLoadedSLocEntry(I);
1653 if (SLoc.isFile() &&
1654 SLoc.getFile().getContentCache() &&
1655 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1656 FirstFID = FileID::get(-int(I) - 2);
1663 // If we haven't found what we want yet, try again, but this time stat()
1664 // each of the files in case the files have changed since we originally
1666 if (FirstFID.isInvalid() &&
1668 (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) &&
1669 (SourceFileUID || (SourceFileUID = getActualFileUID(SourceFile)))) {
1670 bool Invalid = false;
1671 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1674 const SLocEntry &SLoc = getSLocEntry(IFileID, &Invalid);
1678 if (SLoc.isFile()) {
1679 const ContentCache *FileContentCache
1680 = SLoc.getFile().getContentCache();
1681 const FileEntry *Entry = FileContentCache ? FileContentCache->OrigEntry
1684 *SourceFileName == llvm::sys::path::filename(Entry->getName())) {
1685 if (Optional<llvm::sys::fs::UniqueID> EntryUID =
1686 getActualFileUID(Entry)) {
1687 if (*SourceFileUID == *EntryUID) {
1688 FirstFID = FileID::get(I);
1702 /// \brief Get the source location in \arg FID for the given line:col.
1703 /// Returns null location if \arg FID is not a file SLocEntry.
1704 SourceLocation SourceManager::translateLineCol(FileID FID,
1706 unsigned Col) const {
1707 // Lines are used as a one-based index into a zero-based array. This assert
1708 // checks for possible buffer underruns.
1709 assert(Line && Col && "Line and column should start from 1!");
1711 if (FID.isInvalid())
1712 return SourceLocation();
1714 bool Invalid = false;
1715 const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1717 return SourceLocation();
1719 if (!Entry.isFile())
1720 return SourceLocation();
1722 SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
1724 if (Line == 1 && Col == 1)
1727 ContentCache *Content
1728 = const_cast<ContentCache *>(Entry.getFile().getContentCache());
1730 return SourceLocation();
1732 // If this is the first use of line information for this buffer, compute the
1733 // SourceLineCache for it on demand.
1734 if (!Content->SourceLineCache) {
1735 bool MyInvalid = false;
1736 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
1738 return SourceLocation();
1741 if (Line > Content->NumLines) {
1742 unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
1745 return FileLoc.getLocWithOffset(Size);
1748 llvm::MemoryBuffer *Buffer = Content->getBuffer(Diag, *this);
1749 unsigned FilePos = Content->SourceLineCache[Line - 1];
1750 const char *Buf = Buffer->getBufferStart() + FilePos;
1751 unsigned BufLength = Buffer->getBufferSize() - FilePos;
1753 return FileLoc.getLocWithOffset(FilePos);
1757 // Check that the given column is valid.
1758 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1760 return FileLoc.getLocWithOffset(FilePos + i);
1763 /// \brief Compute a map of macro argument chunks to their expanded source
1764 /// location. Chunks that are not part of a macro argument will map to an
1765 /// invalid source location. e.g. if a file contains one macro argument at
1766 /// offset 100 with length 10, this is how the map will be formed:
1767 /// 0 -> SourceLocation()
1768 /// 100 -> Expanded macro arg location
1769 /// 110 -> SourceLocation()
1770 void SourceManager::computeMacroArgsCache(MacroArgsMap &MacroArgsCache,
1772 assert(FID.isValid());
1774 // Initially no macro argument chunk is present.
1775 MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
1780 // Stop if there are no more FileIDs to check.
1782 if (unsigned(ID) >= local_sloc_entry_size())
1784 } else if (ID == -1) {
1788 bool Invalid = false;
1789 const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);
1792 if (Entry.isFile()) {
1793 SourceLocation IncludeLoc = Entry.getFile().getIncludeLoc();
1794 if (IncludeLoc.isInvalid())
1796 if (!isInFileID(IncludeLoc, FID))
1797 return; // No more files/macros that may be "contained" in this file.
1799 // Skip the files/macros of the #include'd file, we only care about macros
1800 // that lexed macro arguments from our file.
1801 if (Entry.getFile().NumCreatedFIDs)
1802 ID += Entry.getFile().NumCreatedFIDs - 1/*because of next ++ID*/;
1806 const ExpansionInfo &ExpInfo = Entry.getExpansion();
1808 if (ExpInfo.getExpansionLocStart().isFileID()) {
1809 if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
1810 return; // No more files/macros that may be "contained" in this file.
1813 if (!ExpInfo.isMacroArgExpansion())
1816 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1817 ExpInfo.getSpellingLoc(),
1818 SourceLocation::getMacroLoc(Entry.getOffset()),
1819 getFileIDSize(FileID::get(ID)));
1823 void SourceManager::associateFileChunkWithMacroArgExp(
1824 MacroArgsMap &MacroArgsCache,
1826 SourceLocation SpellLoc,
1827 SourceLocation ExpansionLoc,
1828 unsigned ExpansionLength) const {
1829 if (!SpellLoc.isFileID()) {
1830 unsigned SpellBeginOffs = SpellLoc.getOffset();
1831 unsigned SpellEndOffs = SpellBeginOffs + ExpansionLength;
1833 // The spelling range for this macro argument expansion can span multiple
1834 // consecutive FileID entries. Go through each entry contained in the
1835 // spelling range and if one is itself a macro argument expansion, recurse
1836 // and associate the file chunk that it represents.
1838 FileID SpellFID; // Current FileID in the spelling range.
1839 unsigned SpellRelativeOffs;
1840 std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);
1842 const SLocEntry &Entry = getSLocEntry(SpellFID);
1843 unsigned SpellFIDBeginOffs = Entry.getOffset();
1844 unsigned SpellFIDSize = getFileIDSize(SpellFID);
1845 unsigned SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;
1846 const ExpansionInfo &Info = Entry.getExpansion();
1847 if (Info.isMacroArgExpansion()) {
1848 unsigned CurrSpellLength;
1849 if (SpellFIDEndOffs < SpellEndOffs)
1850 CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
1852 CurrSpellLength = ExpansionLength;
1853 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1854 Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),
1855 ExpansionLoc, CurrSpellLength);
1858 if (SpellFIDEndOffs >= SpellEndOffs)
1859 return; // we covered all FileID entries in the spelling range.
1861 // Move to the next FileID entry in the spelling range.
1862 unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
1863 ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);
1864 ExpansionLength -= advance;
1866 SpellRelativeOffs = 0;
1871 assert(SpellLoc.isFileID());
1874 if (!isInFileID(SpellLoc, FID, &BeginOffs))
1877 unsigned EndOffs = BeginOffs + ExpansionLength;
1879 // Add a new chunk for this macro argument. A previous macro argument chunk
1880 // may have been lexed again, so e.g. if the map is
1881 // 0 -> SourceLocation()
1882 // 100 -> Expanded loc #1
1883 // 110 -> SourceLocation()
1884 // and we found a new macro FileID that lexed from offet 105 with length 3,
1885 // the new map will be:
1886 // 0 -> SourceLocation()
1887 // 100 -> Expanded loc #1
1888 // 105 -> Expanded loc #2
1889 // 108 -> Expanded loc #1
1890 // 110 -> SourceLocation()
1892 // Since re-lexed macro chunks will always be the same size or less of
1893 // previous chunks, we only need to find where the ending of the new macro
1894 // chunk is mapped to and update the map with new begin/end mappings.
1896 MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
1898 SourceLocation EndOffsMappedLoc = I->second;
1899 MacroArgsCache[BeginOffs] = ExpansionLoc;
1900 MacroArgsCache[EndOffs] = EndOffsMappedLoc;
1903 /// \brief If \arg Loc points inside a function macro argument, the returned
1904 /// location will be the macro location in which the argument was expanded.
1905 /// If a macro argument is used multiple times, the expanded location will
1906 /// be at the first expansion of the argument.
1910 /// Passing a file location pointing at 'foo', will yield a macro location
1911 /// where 'foo' was expanded into.
1913 SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
1914 if (Loc.isInvalid() || !Loc.isFileID())
1919 std::tie(FID, Offset) = getDecomposedLoc(Loc);
1920 if (FID.isInvalid())
1923 std::unique_ptr<MacroArgsMap> &MacroArgsCache = MacroArgsCacheMap[FID];
1924 if (!MacroArgsCache) {
1925 MacroArgsCache = llvm::make_unique<MacroArgsMap>();
1926 computeMacroArgsCache(*MacroArgsCache, FID);
1929 assert(!MacroArgsCache->empty());
1930 MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
1933 unsigned MacroArgBeginOffs = I->first;
1934 SourceLocation MacroArgExpandedLoc = I->second;
1935 if (MacroArgExpandedLoc.isValid())
1936 return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
1941 std::pair<FileID, unsigned>
1942 SourceManager::getDecomposedIncludedLoc(FileID FID) const {
1943 if (FID.isInvalid())
1944 return std::make_pair(FileID(), 0);
1946 // Uses IncludedLocMap to retrieve/cache the decomposed loc.
1948 typedef std::pair<FileID, unsigned> DecompTy;
1949 typedef llvm::DenseMap<FileID, DecompTy> MapTy;
1950 std::pair<MapTy::iterator, bool>
1951 InsertOp = IncludedLocMap.insert(std::make_pair(FID, DecompTy()));
1952 DecompTy &DecompLoc = InsertOp.first->second;
1953 if (!InsertOp.second)
1954 return DecompLoc; // already in map.
1956 SourceLocation UpperLoc;
1957 bool Invalid = false;
1958 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1960 if (Entry.isExpansion())
1961 UpperLoc = Entry.getExpansion().getExpansionLocStart();
1963 UpperLoc = Entry.getFile().getIncludeLoc();
1966 if (UpperLoc.isValid())
1967 DecompLoc = getDecomposedLoc(UpperLoc);
1972 /// Given a decomposed source location, move it up the include/expansion stack
1973 /// to the parent source location. If this is possible, return the decomposed
1974 /// version of the parent in Loc and return false. If Loc is the top-level
1975 /// entry, return true and don't modify it.
1976 static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1977 const SourceManager &SM) {
1978 std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
1979 if (UpperLoc.first.isInvalid())
1980 return true; // We reached the top.
1986 /// Return the cache entry for comparing the given file IDs
1987 /// for isBeforeInTranslationUnit.
1988 InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
1989 FileID RFID) const {
1990 // This is a magic number for limiting the cache size. It was experimentally
1991 // derived from a small Objective-C project (where the cache filled
1992 // out to ~250 items). We can make it larger if necessary.
1993 enum { MagicCacheSize = 300 };
1994 IsBeforeInTUCacheKey Key(LFID, RFID);
1996 // If the cache size isn't too large, do a lookup and if necessary default
1997 // construct an entry. We can then return it to the caller for direct
1998 // use. When they update the value, the cache will get automatically
2000 if (IBTUCache.size() < MagicCacheSize)
2001 return IBTUCache[Key];
2003 // Otherwise, do a lookup that will not construct a new value.
2004 InBeforeInTUCache::iterator I = IBTUCache.find(Key);
2005 if (I != IBTUCache.end())
2008 // Fall back to the overflow value.
2009 return IBTUCacheOverflow;
2012 /// \brief Determines the order of 2 source locations in the translation unit.
2014 /// \returns true if LHS source location comes before RHS, false otherwise.
2015 bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
2016 SourceLocation RHS) const {
2017 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
2021 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
2022 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
2024 // getDecomposedLoc may have failed to return a valid FileID because, e.g. it
2025 // is a serialized one referring to a file that was removed after we loaded
2027 if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
2028 return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
2030 // If the source locations are in the same file, just compare offsets.
2031 if (LOffs.first == ROffs.first)
2032 return LOffs.second < ROffs.second;
2034 // If we are comparing a source location with multiple locations in the same
2035 // file, we get a big win by caching the result.
2036 InBeforeInTUCacheEntry &IsBeforeInTUCache =
2037 getInBeforeInTUCache(LOffs.first, ROffs.first);
2039 // If we are comparing a source location with multiple locations in the same
2040 // file, we get a big win by caching the result.
2041 if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
2042 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
2044 // Okay, we missed in the cache, start updating the cache for this query.
2045 IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
2046 /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID);
2048 // We need to find the common ancestor. The only way of doing this is to
2049 // build the complete include chain for one and then walking up the chain
2050 // of the other looking for a match.
2051 // We use a map from FileID to Offset to store the chain. Easier than writing
2052 // a custom set hash info that only depends on the first part of a pair.
2053 typedef llvm::SmallDenseMap<FileID, unsigned, 16> LocSet;
2056 LChain.insert(LOffs);
2057 // We catch the case where LOffs is in a file included by ROffs and
2058 // quit early. The other way round unfortunately remains suboptimal.
2059 } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
2061 while((I = LChain.find(ROffs.first)) == LChain.end()) {
2062 if (MoveUpIncludeHierarchy(ROffs, *this))
2063 break; // Met at topmost file.
2065 if (I != LChain.end())
2068 // If we exited because we found a nearest common ancestor, compare the
2069 // locations within the common file and cache them.
2070 if (LOffs.first == ROffs.first) {
2071 IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
2072 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
2075 // If we arrived here, the location is either in a built-ins buffer or
2076 // associated with global inline asm. PR5662 and PR22576 are examples.
2078 // Clear the lookup cache, it depends on a common location.
2079 IsBeforeInTUCache.clear();
2080 StringRef LB = getBuffer(LOffs.first)->getBufferIdentifier();
2081 StringRef RB = getBuffer(ROffs.first)->getBufferIdentifier();
2082 bool LIsBuiltins = LB == "<built-in>";
2083 bool RIsBuiltins = RB == "<built-in>";
2084 // Sort built-in before non-built-in.
2085 if (LIsBuiltins || RIsBuiltins) {
2086 if (LIsBuiltins != RIsBuiltins)
2088 // Both are in built-in buffers, but from different files. We just claim that
2089 // lower IDs come first.
2090 return LOffs.first < ROffs.first;
2092 bool LIsAsm = LB == "<inline asm>";
2093 bool RIsAsm = RB == "<inline asm>";
2094 // Sort assembler after built-ins, but before the rest.
2095 if (LIsAsm || RIsAsm) {
2096 if (LIsAsm != RIsAsm)
2098 assert(LOffs.first == ROffs.first);
2101 bool LIsScratch = LB == "<scratch space>";
2102 bool RIsScratch = RB == "<scratch space>";
2103 // Sort scratch after inline asm, but before the rest.
2104 if (LIsScratch || RIsScratch) {
2105 if (LIsScratch != RIsScratch)
2107 return LOffs.second < ROffs.second;
2109 llvm_unreachable("Unsortable locations found");
2112 void SourceManager::PrintStats() const {
2113 llvm::errs() << "\n*** Source Manager Stats:\n";
2114 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
2115 << " mem buffers mapped.\n";
2116 llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
2117 << llvm::capacity_in_bytes(LocalSLocEntryTable)
2118 << " bytes of capacity), "
2119 << NextLocalOffset << "B of Sloc address space used.\n";
2120 llvm::errs() << LoadedSLocEntryTable.size()
2121 << " loaded SLocEntries allocated, "
2122 << MaxLoadedOffset - CurrentLoadedOffset
2123 << "B of Sloc address space used.\n";
2125 unsigned NumLineNumsComputed = 0;
2126 unsigned NumFileBytesMapped = 0;
2127 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
2128 NumLineNumsComputed += I->second->SourceLineCache != nullptr;
2129 NumFileBytesMapped += I->second->getSizeBytesMapped();
2131 unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
2133 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
2134 << NumLineNumsComputed << " files with line #'s computed, "
2135 << NumMacroArgsComputed << " files with macro args computed.\n";
2136 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
2137 << NumBinaryProbes << " binary.\n";
2140 LLVM_DUMP_METHOD void SourceManager::dump() const {
2141 llvm::raw_ostream &out = llvm::errs();
2143 auto DumpSLocEntry = [&](int ID, const SrcMgr::SLocEntry &Entry,
2144 llvm::Optional<unsigned> NextStart) {
2145 out << "SLocEntry <FileID " << ID << "> " << (Entry.isFile() ? "file" : "expansion")
2146 << " <SourceLocation " << Entry.getOffset() << ":";
2148 out << *NextStart << ">\n";
2151 if (Entry.isFile()) {
2152 auto &FI = Entry.getFile();
2153 if (FI.NumCreatedFIDs)
2154 out << " covers <FileID " << ID << ":" << int(ID + FI.NumCreatedFIDs)
2156 if (FI.getIncludeLoc().isValid())
2157 out << " included from " << FI.getIncludeLoc().getOffset() << "\n";
2158 if (auto *CC = FI.getContentCache()) {
2159 out << " for " << (CC->OrigEntry ? CC->OrigEntry->getName() : "<none>")
2161 if (CC->BufferOverridden)
2162 out << " contents overridden\n";
2163 if (CC->ContentsEntry != CC->OrigEntry) {
2164 out << " contents from "
2165 << (CC->ContentsEntry ? CC->ContentsEntry->getName() : "<none>")
2170 auto &EI = Entry.getExpansion();
2171 out << " spelling from " << EI.getSpellingLoc().getOffset() << "\n";
2172 out << " macro " << (EI.isMacroArgExpansion() ? "arg" : "body")
2173 << " range <" << EI.getExpansionLocStart().getOffset() << ":"
2174 << EI.getExpansionLocEnd().getOffset() << ">\n";
2178 // Dump local SLocEntries.
2179 for (unsigned ID = 0, NumIDs = LocalSLocEntryTable.size(); ID != NumIDs; ++ID) {
2180 DumpSLocEntry(ID, LocalSLocEntryTable[ID],
2181 ID == NumIDs - 1 ? NextLocalOffset
2182 : LocalSLocEntryTable[ID + 1].getOffset());
2184 // Dump loaded SLocEntries.
2185 llvm::Optional<unsigned> NextStart;
2186 for (unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
2187 int ID = -(int)Index - 2;
2188 if (SLocEntryLoaded[Index]) {
2189 DumpSLocEntry(ID, LoadedSLocEntryTable[Index], NextStart);
2190 NextStart = LoadedSLocEntryTable[Index].getOffset();
2197 ExternalSLocEntrySource::~ExternalSLocEntrySource() { }
2199 /// Return the amount of memory used by memory buffers, breaking down
2200 /// by heap-backed versus mmap'ed memory.
2201 SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
2202 size_t malloc_bytes = 0;
2203 size_t mmap_bytes = 0;
2205 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
2206 if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
2207 switch (MemBufferInfos[i]->getMemoryBufferKind()) {
2208 case llvm::MemoryBuffer::MemoryBuffer_MMap:
2209 mmap_bytes += sized_mapped;
2211 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
2212 malloc_bytes += sized_mapped;
2216 return MemoryBufferSizes(malloc_bytes, mmap_bytes);
2219 size_t SourceManager::getDataStructureSizes() const {
2220 size_t size = llvm::capacity_in_bytes(MemBufferInfos)
2221 + llvm::capacity_in_bytes(LocalSLocEntryTable)
2222 + llvm::capacity_in_bytes(LoadedSLocEntryTable)
2223 + llvm::capacity_in_bytes(SLocEntryLoaded)
2224 + llvm::capacity_in_bytes(FileInfos);
2226 if (OverriddenFilesInfo)
2227 size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);