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/LLVM.h"
18 #include "clang/Basic/SourceLocation.h"
19 #include "clang/Basic/SourceManagerInternals.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/None.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/Support/Allocator.h"
28 #include "llvm/Support/Capacity.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/FileSystem.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/Path.h"
35 #include "llvm/Support/raw_ostream.h"
45 using namespace clang;
46 using namespace SrcMgr;
47 using llvm::MemoryBuffer;
49 //===----------------------------------------------------------------------===//
50 // SourceManager Helper Classes
51 //===----------------------------------------------------------------------===//
53 ContentCache::~ContentCache() {
54 if (shouldFreeBuffer())
55 delete Buffer.getPointer();
58 /// getSizeBytesMapped - Returns the number of bytes actually mapped for this
59 /// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
60 unsigned ContentCache::getSizeBytesMapped() const {
61 return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
64 /// Returns the kind of memory used to back the memory buffer for
65 /// this content cache. This is used for performance analysis.
66 llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
67 assert(Buffer.getPointer());
69 // Should be unreachable, but keep for sanity.
70 if (!Buffer.getPointer())
71 return llvm::MemoryBuffer::MemoryBuffer_Malloc;
73 llvm::MemoryBuffer *buf = Buffer.getPointer();
74 return buf->getBufferKind();
77 /// getSize - Returns the size of the content encapsulated by this ContentCache.
78 /// This can be the size of the source file or the size of an arbitrary
79 /// scratch buffer. If the ContentCache encapsulates a source file, that
80 /// file is not lazily brought in from disk to satisfy this query.
81 unsigned ContentCache::getSize() const {
82 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
83 : (unsigned) ContentsEntry->getSize();
86 void ContentCache::replaceBuffer(llvm::MemoryBuffer *B, bool DoNotFree) {
87 if (B && B == Buffer.getPointer()) {
88 assert(0 && "Replacing with the same buffer");
89 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
93 if (shouldFreeBuffer())
94 delete Buffer.getPointer();
96 Buffer.setInt((B && DoNotFree) ? DoNotFreeFlag : 0);
99 llvm::MemoryBuffer *ContentCache::getBuffer(DiagnosticsEngine &Diag,
100 const SourceManager &SM,
102 bool *Invalid) const {
103 // Lazily create the Buffer for ContentCaches that wrap files. If we already
104 // computed it, just return what we have.
105 if (Buffer.getPointer() || !ContentsEntry) {
107 *Invalid = isBufferInvalid();
109 return Buffer.getPointer();
112 bool isVolatile = SM.userFilesAreVolatile() && !IsSystemFile;
114 SM.getFileManager().getBufferForFile(ContentsEntry, isVolatile);
116 // If we were unable to open the file, then we are in an inconsistent
117 // situation where the content cache referenced a file which no longer
118 // exists. Most likely, we were using a stat cache with an invalid entry but
119 // the file could also have been removed during processing. Since we can't
120 // really deal with this situation, just create an empty buffer.
122 // FIXME: This is definitely not ideal, but our immediate clients can't
123 // currently handle returning a null entry here. Ideally we should detect
124 // that we are in an inconsistent situation and error out as quickly as
126 if (!BufferOrError) {
127 StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
128 auto BackupBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
129 ContentsEntry->getSize(), "<invalid>");
130 char *Ptr = BackupBuffer->getBufferStart();
131 for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
132 Ptr[i] = FillStr[i % FillStr.size()];
133 Buffer.setPointer(BackupBuffer.release());
135 if (Diag.isDiagnosticInFlight())
136 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
137 ContentsEntry->getName(),
138 BufferOrError.getError().message());
140 Diag.Report(Loc, diag::err_cannot_open_file)
141 << ContentsEntry->getName() << BufferOrError.getError().message();
143 Buffer.setInt(Buffer.getInt() | InvalidFlag);
145 if (Invalid) *Invalid = true;
146 return Buffer.getPointer();
149 Buffer.setPointer(BufferOrError->release());
151 // Check that the file's size is the same as in the file entry (which may
152 // have come from a stat cache).
153 if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) {
154 if (Diag.isDiagnosticInFlight())
155 Diag.SetDelayedDiagnostic(diag::err_file_modified,
156 ContentsEntry->getName());
158 Diag.Report(Loc, diag::err_file_modified)
159 << ContentsEntry->getName();
161 Buffer.setInt(Buffer.getInt() | InvalidFlag);
162 if (Invalid) *Invalid = true;
163 return Buffer.getPointer();
166 // If the buffer is valid, check to see if it has a UTF Byte Order Mark
167 // (BOM). We only support UTF-8 with and without a BOM right now. See
168 // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
169 StringRef BufStr = Buffer.getPointer()->getBuffer();
170 const char *InvalidBOM = llvm::StringSwitch<const char *>(BufStr)
171 .StartsWith("\xFE\xFF", "UTF-16 (BE)")
172 .StartsWith("\xFF\xFE", "UTF-16 (LE)")
173 .StartsWith(llvm::StringLiteral::withInnerNUL("\x00\x00\xFE\xFF"),
175 .StartsWith(llvm::StringLiteral::withInnerNUL("\xFF\xFE\x00\x00"),
177 .StartsWith("\x2B\x2F\x76", "UTF-7")
178 .StartsWith("\xF7\x64\x4C", "UTF-1")
179 .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
180 .StartsWith("\x0E\xFE\xFF", "SDSU")
181 .StartsWith("\xFB\xEE\x28", "BOCU-1")
182 .StartsWith("\x84\x31\x95\x33", "GB-18030")
186 Diag.Report(Loc, diag::err_unsupported_bom)
187 << InvalidBOM << ContentsEntry->getName();
188 Buffer.setInt(Buffer.getInt() | InvalidFlag);
192 *Invalid = isBufferInvalid();
194 return Buffer.getPointer();
197 unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
199 FilenameIDs.insert(std::make_pair(Name, FilenamesByID.size()));
201 FilenamesByID.push_back(&*IterBool.first);
202 return IterBool.first->second;
205 /// Add a line note to the line table that indicates that there is a \#line or
206 /// GNU line marker at the specified FID/Offset location which changes the
207 /// presumed location to LineNo/FilenameID. If EntryExit is 0, then this doesn't
208 /// change the presumed \#include stack. If it is 1, this is a file entry, if
209 /// it is 2 then this is a file exit. FileKind specifies whether this is a
210 /// system header or extern C system header.
211 void LineTableInfo::AddLineNote(FileID FID, unsigned Offset, unsigned LineNo,
212 int FilenameID, unsigned EntryExit,
213 SrcMgr::CharacteristicKind FileKind) {
214 std::vector<LineEntry> &Entries = LineEntries[FID];
216 // An unspecified FilenameID means use the last filename if available, or the
217 // main source file otherwise.
218 if (FilenameID == -1 && !Entries.empty())
219 FilenameID = Entries.back().FilenameID;
221 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
222 "Adding line entries out of order!");
224 unsigned IncludeOffset = 0;
225 if (EntryExit == 0) { // No #include stack change.
226 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
227 } else if (EntryExit == 1) {
228 IncludeOffset = Offset-1;
229 } else if (EntryExit == 2) {
230 assert(!Entries.empty() && Entries.back().IncludeOffset &&
231 "PPDirectives should have caught case when popping empty include stack");
233 // Get the include loc of the last entries' include loc as our include loc.
235 if (const LineEntry *PrevEntry =
236 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
237 IncludeOffset = PrevEntry->IncludeOffset;
240 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
244 /// FindNearestLineEntry - Find the line entry nearest to FID that is before
245 /// it. If there is no line entry before Offset in FID, return null.
246 const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID,
248 const std::vector<LineEntry> &Entries = LineEntries[FID];
249 assert(!Entries.empty() && "No #line entries for this FID after all!");
251 // It is very common for the query to be after the last #line, check this
253 if (Entries.back().FileOffset <= Offset)
254 return &Entries.back();
256 // Do a binary search to find the maximal element that is still before Offset.
257 std::vector<LineEntry>::const_iterator I =
258 std::upper_bound(Entries.begin(), Entries.end(), Offset);
259 if (I == Entries.begin()) return nullptr;
263 /// Add a new line entry that has already been encoded into
264 /// the internal representation of the line table.
265 void LineTableInfo::AddEntry(FileID FID,
266 const std::vector<LineEntry> &Entries) {
267 LineEntries[FID] = Entries;
270 /// getLineTableFilenameID - Return the uniqued ID for the specified filename.
271 unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
272 return getLineTable().getLineTableFilenameID(Name);
275 /// AddLineNote - Add a line note to the line table for the FileID and offset
276 /// specified by Loc. If FilenameID is -1, it is considered to be
278 void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
279 int FilenameID, bool IsFileEntry,
281 SrcMgr::CharacteristicKind FileKind) {
282 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
284 bool Invalid = false;
285 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
286 if (!Entry.isFile() || Invalid)
289 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
291 // Remember that this file has #line directives now if it doesn't already.
292 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
294 (void) getLineTable();
296 unsigned EntryExit = 0;
302 LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,
303 EntryExit, FileKind);
306 LineTableInfo &SourceManager::getLineTable() {
308 LineTable = new LineTableInfo();
312 //===----------------------------------------------------------------------===//
313 // Private 'Create' methods.
314 //===----------------------------------------------------------------------===//
316 SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
317 bool UserFilesAreVolatile)
318 : Diag(Diag), FileMgr(FileMgr), UserFilesAreVolatile(UserFilesAreVolatile) {
320 Diag.setSourceManager(this);
323 SourceManager::~SourceManager() {
326 // Delete FileEntry objects corresponding to content caches. Since the actual
327 // content cache objects are bump pointer allocated, we just have to run the
328 // dtors, but we call the deallocate method for completeness.
329 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
330 if (MemBufferInfos[i]) {
331 MemBufferInfos[i]->~ContentCache();
332 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
335 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
336 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
338 I->second->~ContentCache();
339 ContentCacheAlloc.Deallocate(I->second);
344 void SourceManager::clearIDTables() {
345 MainFileID = FileID();
346 LocalSLocEntryTable.clear();
347 LoadedSLocEntryTable.clear();
348 SLocEntryLoaded.clear();
349 LastLineNoFileIDQuery = FileID();
350 LastLineNoContentCache = nullptr;
351 LastFileIDLookup = FileID();
356 // Use up FileID #0 as an invalid expansion.
358 CurrentLoadedOffset = MaxLoadedOffset;
359 createExpansionLoc(SourceLocation(), SourceLocation(), SourceLocation(), 1);
362 void SourceManager::initializeForReplay(const SourceManager &Old) {
363 assert(MainFileID.isInvalid() && "expected uninitialized SourceManager");
365 auto CloneContentCache = [&](const ContentCache *Cache) -> ContentCache * {
366 auto *Clone = new (ContentCacheAlloc.Allocate<ContentCache>()) ContentCache;
367 Clone->OrigEntry = Cache->OrigEntry;
368 Clone->ContentsEntry = Cache->ContentsEntry;
369 Clone->BufferOverridden = Cache->BufferOverridden;
370 Clone->IsSystemFile = Cache->IsSystemFile;
371 Clone->IsTransient = Cache->IsTransient;
372 Clone->replaceBuffer(Cache->getRawBuffer(), /*DoNotFree*/true);
376 // Ensure all SLocEntries are loaded from the external source.
377 for (unsigned I = 0, N = Old.LoadedSLocEntryTable.size(); I != N; ++I)
378 if (!Old.SLocEntryLoaded[I])
379 Old.loadSLocEntry(I, nullptr);
381 // Inherit any content cache data from the old source manager.
382 for (auto &FileInfo : Old.FileInfos) {
383 SrcMgr::ContentCache *&Slot = FileInfos[FileInfo.first];
386 Slot = CloneContentCache(FileInfo.second);
390 /// getOrCreateContentCache - Create or return a cached ContentCache for the
393 SourceManager::getOrCreateContentCache(const FileEntry *FileEnt,
395 assert(FileEnt && "Didn't specify a file entry to use?");
397 // Do we already have information about this file?
398 ContentCache *&Entry = FileInfos[FileEnt];
399 if (Entry) return Entry;
401 // Nope, create a new Cache entry.
402 Entry = ContentCacheAlloc.Allocate<ContentCache>();
404 if (OverriddenFilesInfo) {
405 // If the file contents are overridden with contents from another file,
406 // pass that file to ContentCache.
407 llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
408 overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
409 if (overI == OverriddenFilesInfo->OverriddenFiles.end())
410 new (Entry) ContentCache(FileEnt);
412 new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
416 new (Entry) ContentCache(FileEnt);
419 Entry->IsSystemFile = isSystemFile;
420 Entry->IsTransient = FilesAreTransient;
425 /// Create a new ContentCache for the specified memory buffer.
426 /// This does no caching.
428 SourceManager::createMemBufferContentCache(llvm::MemoryBuffer *Buffer,
430 // Add a new ContentCache to the MemBufferInfos list and return it.
431 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
432 new (Entry) ContentCache();
433 MemBufferInfos.push_back(Entry);
434 Entry->replaceBuffer(Buffer, DoNotFree);
438 const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
439 bool *Invalid) const {
440 assert(!SLocEntryLoaded[Index]);
441 if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
444 // If the file of the SLocEntry changed we could still have loaded it.
445 if (!SLocEntryLoaded[Index]) {
446 // Try to recover; create a SLocEntry so the rest of clang can handle it.
447 LoadedSLocEntryTable[Index] = SLocEntry::get(0,
448 FileInfo::get(SourceLocation(),
449 getFakeContentCacheForRecovery(),
454 return LoadedSLocEntryTable[Index];
457 std::pair<int, unsigned>
458 SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
459 unsigned TotalSize) {
460 assert(ExternalSLocEntries && "Don't have an external sloc source");
461 // Make sure we're not about to run out of source locations.
462 if (CurrentLoadedOffset - TotalSize < NextLocalOffset)
463 return std::make_pair(0, 0);
464 LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
465 SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
466 CurrentLoadedOffset -= TotalSize;
467 int ID = LoadedSLocEntryTable.size();
468 return std::make_pair(-ID - 1, CurrentLoadedOffset);
471 /// As part of recovering from missing or changed content, produce a
472 /// fake, non-empty buffer.
473 llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const {
474 if (!FakeBufferForRecovery)
475 FakeBufferForRecovery =
476 llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
478 return FakeBufferForRecovery.get();
481 /// As part of recovering from missing or changed content, produce a
482 /// fake content cache.
483 const SrcMgr::ContentCache *
484 SourceManager::getFakeContentCacheForRecovery() const {
485 if (!FakeContentCacheForRecovery) {
486 FakeContentCacheForRecovery = llvm::make_unique<SrcMgr::ContentCache>();
487 FakeContentCacheForRecovery->replaceBuffer(getFakeBufferForRecovery(),
490 return FakeContentCacheForRecovery.get();
493 /// Returns the previous in-order FileID or an invalid FileID if there
494 /// is no previous one.
495 FileID SourceManager::getPreviousFileID(FileID FID) const {
506 } else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {
510 return FileID::get(ID-1);
513 /// Returns the next in-order FileID or an invalid FileID if there is
515 FileID SourceManager::getNextFileID(FileID FID) const {
521 if (unsigned(ID+1) >= local_sloc_entry_size())
523 } else if (ID+1 >= -1) {
527 return FileID::get(ID+1);
530 //===----------------------------------------------------------------------===//
531 // Methods to create new FileID's and macro expansions.
532 //===----------------------------------------------------------------------===//
534 /// createFileID - Create a new FileID for the specified ContentCache and
535 /// include position. This works regardless of whether the ContentCache
536 /// corresponds to a file or some other input source.
537 FileID SourceManager::createFileID(const ContentCache *File,
538 SourceLocation IncludePos,
539 SrcMgr::CharacteristicKind FileCharacter,
540 int LoadedID, unsigned LoadedOffset) {
542 assert(LoadedID != -1 && "Loading sentinel FileID");
543 unsigned Index = unsigned(-LoadedID) - 2;
544 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
545 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
546 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset,
547 FileInfo::get(IncludePos, File, FileCharacter));
548 SLocEntryLoaded[Index] = true;
549 return FileID::get(LoadedID);
551 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset,
552 FileInfo::get(IncludePos, File,
554 unsigned FileSize = File->getSize();
555 assert(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
556 NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset &&
557 "Ran out of source locations!");
558 // We do a +1 here because we want a SourceLocation that means "the end of the
559 // file", e.g. for the "no newline at the end of the file" diagnostic.
560 NextLocalOffset += FileSize + 1;
562 // Set LastFileIDLookup to the newly created file. The next getFileID call is
563 // almost guaranteed to be from that file.
564 FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
565 return LastFileIDLookup = FID;
569 SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc,
570 SourceLocation ExpansionLoc,
571 unsigned TokLength) {
572 ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
574 return createExpansionLocImpl(Info, TokLength);
578 SourceManager::createExpansionLoc(SourceLocation SpellingLoc,
579 SourceLocation ExpansionLocStart,
580 SourceLocation ExpansionLocEnd,
582 bool ExpansionIsTokenRange,
584 unsigned LoadedOffset) {
585 ExpansionInfo Info = ExpansionInfo::create(
586 SpellingLoc, ExpansionLocStart, ExpansionLocEnd, ExpansionIsTokenRange);
587 return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset);
590 SourceLocation SourceManager::createTokenSplitLoc(SourceLocation Spelling,
591 SourceLocation TokenStart,
592 SourceLocation TokenEnd) {
593 assert(getFileID(TokenStart) == getFileID(TokenEnd) &&
594 "token spans multiple files");
595 return createExpansionLocImpl(
596 ExpansionInfo::createForTokenSplit(Spelling, TokenStart, TokenEnd),
597 TokenEnd.getOffset() - TokenStart.getOffset());
601 SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
604 unsigned LoadedOffset) {
606 assert(LoadedID != -1 && "Loading sentinel FileID");
607 unsigned Index = unsigned(-LoadedID) - 2;
608 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
609 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
610 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
611 SLocEntryLoaded[Index] = true;
612 return SourceLocation::getMacroLoc(LoadedOffset);
614 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
615 assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&
616 NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&
617 "Ran out of source locations!");
618 // See createFileID for that +1.
619 NextLocalOffset += TokLength + 1;
620 return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
623 llvm::MemoryBuffer *SourceManager::getMemoryBufferForFile(const FileEntry *File,
625 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
626 assert(IR && "getOrCreateContentCache() cannot return NULL");
627 return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
630 void SourceManager::overrideFileContents(const FileEntry *SourceFile,
631 llvm::MemoryBuffer *Buffer,
633 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
634 assert(IR && "getOrCreateContentCache() cannot return NULL");
636 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
637 const_cast<SrcMgr::ContentCache *>(IR)->BufferOverridden = true;
639 getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
642 void SourceManager::overrideFileContents(const FileEntry *SourceFile,
643 const FileEntry *NewFile) {
644 assert(SourceFile->getSize() == NewFile->getSize() &&
645 "Different sizes, use the FileManager to create a virtual file with "
647 assert(FileInfos.count(SourceFile) == 0 &&
648 "This function should be called at the initialization stage, before "
649 "any parsing occurs.");
650 getOverriddenFilesInfo().OverriddenFiles[SourceFile] = NewFile;
653 void SourceManager::disableFileContentsOverride(const FileEntry *File) {
654 if (!isFileOverridden(File))
657 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
658 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(nullptr);
659 const_cast<SrcMgr::ContentCache *>(IR)->ContentsEntry = IR->OrigEntry;
661 assert(OverriddenFilesInfo);
662 OverriddenFilesInfo->OverriddenFiles.erase(File);
663 OverriddenFilesInfo->OverriddenFilesWithBuffer.erase(File);
666 void SourceManager::setFileIsTransient(const FileEntry *File) {
667 const SrcMgr::ContentCache *CC = getOrCreateContentCache(File);
668 const_cast<SrcMgr::ContentCache *>(CC)->IsTransient = true;
671 StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
672 bool MyInvalid = false;
673 const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid);
674 if (!SLoc.isFile() || MyInvalid) {
677 return "<<<<<INVALID SOURCE LOCATION>>>>>";
680 llvm::MemoryBuffer *Buf = SLoc.getFile().getContentCache()->getBuffer(
681 Diag, *this, SourceLocation(), &MyInvalid);
683 *Invalid = MyInvalid;
686 return "<<<<<INVALID SOURCE LOCATION>>>>>";
688 return Buf->getBuffer();
691 //===----------------------------------------------------------------------===//
692 // SourceLocation manipulation methods.
693 //===----------------------------------------------------------------------===//
695 /// Return the FileID for a SourceLocation.
697 /// This is the cache-miss path of getFileID. Not as hot as that function, but
698 /// still very important. It is responsible for finding the entry in the
699 /// SLocEntry tables that contains the specified location.
700 FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
702 return FileID::get(0);
704 // Now it is time to search for the correct file. See where the SLocOffset
705 // sits in the global view and consult local or loaded buffers for it.
706 if (SLocOffset < NextLocalOffset)
707 return getFileIDLocal(SLocOffset);
708 return getFileIDLoaded(SLocOffset);
711 /// Return the FileID for a SourceLocation with a low offset.
713 /// This function knows that the SourceLocation is in a local buffer, not a
715 FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const {
716 assert(SLocOffset < NextLocalOffset && "Bad function choice");
718 // After the first and second level caches, I see two common sorts of
719 // behavior: 1) a lot of searched FileID's are "near" the cached file
720 // location or are "near" the cached expansion location. 2) others are just
721 // completely random and may be a very long way away.
723 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
724 // then we fall back to a less cache efficient, but more scalable, binary
725 // search to find the location.
727 // See if this is near the file point - worst case we start scanning from the
728 // most newly created FileID.
729 const SrcMgr::SLocEntry *I;
731 if (LastFileIDLookup.ID < 0 ||
732 LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
733 // Neither loc prunes our search.
734 I = LocalSLocEntryTable.end();
736 // Perhaps it is near the file point.
737 I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
740 // Find the FileID that contains this. "I" is an iterator that points to a
741 // FileID whose offset is known to be larger than SLocOffset.
742 unsigned NumProbes = 0;
745 if (I->getOffset() <= SLocOffset) {
746 FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
748 // If this isn't an expansion, remember it. We have good locality across
750 if (!I->isExpansion())
751 LastFileIDLookup = Res;
752 NumLinearScans += NumProbes+1;
755 if (++NumProbes == 8)
759 // Convert "I" back into an index. We know that it is an entry whose index is
760 // larger than the offset we are looking for.
761 unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
762 // LessIndex - This is the lower bound of the range that we're searching.
763 // We know that the offset corresponding to the FileID is is less than
765 unsigned LessIndex = 0;
768 bool Invalid = false;
769 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
770 unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
772 return FileID::get(0);
776 // If the offset of the midpoint is too large, chop the high side of the
777 // range to the midpoint.
778 if (MidOffset > SLocOffset) {
779 GreaterIndex = MiddleIndex;
783 // If the middle index contains the value, succeed and return.
784 // FIXME: This could be made faster by using a function that's aware of
785 // being in the local area.
786 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
787 FileID Res = FileID::get(MiddleIndex);
789 // If this isn't a macro expansion, remember it. We have good locality
790 // across FileID lookups.
791 if (!LocalSLocEntryTable[MiddleIndex].isExpansion())
792 LastFileIDLookup = Res;
793 NumBinaryProbes += NumProbes;
797 // Otherwise, move the low-side up to the middle index.
798 LessIndex = MiddleIndex;
802 /// Return the FileID for a SourceLocation with a high offset.
804 /// This function knows that the SourceLocation is in a loaded buffer, not a
806 FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
807 // Sanity checking, otherwise a bug may lead to hanging in release build.
808 if (SLocOffset < CurrentLoadedOffset) {
809 assert(0 && "Invalid SLocOffset or bad function choice");
813 // Essentially the same as the local case, but the loaded array is sorted
814 // in the other direction.
816 // First do a linear scan from the last lookup position, if possible.
818 int LastID = LastFileIDLookup.ID;
819 if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
822 I = (-LastID - 2) + 1;
825 for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
826 // Make sure the entry is loaded!
827 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
828 if (E.getOffset() <= SLocOffset) {
829 FileID Res = FileID::get(-int(I) - 2);
831 if (!E.isExpansion())
832 LastFileIDLookup = Res;
833 NumLinearScans += NumProbes + 1;
838 // Linear scan failed. Do the binary search. Note the reverse sorting of the
839 // table: GreaterIndex is the one where the offset is greater, which is
840 // actually a lower index!
841 unsigned GreaterIndex = I;
842 unsigned LessIndex = LoadedSLocEntryTable.size();
846 unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
847 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
848 if (E.getOffset() == 0)
849 return FileID(); // invalid entry.
853 if (E.getOffset() > SLocOffset) {
854 // Sanity checking, otherwise a bug may lead to hanging in release build.
855 if (GreaterIndex == MiddleIndex) {
856 assert(0 && "binary search missed the entry");
859 GreaterIndex = MiddleIndex;
863 if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
864 FileID Res = FileID::get(-int(MiddleIndex) - 2);
865 if (!E.isExpansion())
866 LastFileIDLookup = Res;
867 NumBinaryProbes += NumProbes;
871 // Sanity checking, otherwise a bug may lead to hanging in release build.
872 if (LessIndex == MiddleIndex) {
873 assert(0 && "binary search missed the entry");
876 LessIndex = MiddleIndex;
880 SourceLocation SourceManager::
881 getExpansionLocSlowCase(SourceLocation Loc) const {
883 // Note: If Loc indicates an offset into a token that came from a macro
884 // expansion (e.g. the 5th character of the token) we do not want to add
885 // this offset when going to the expansion location. The expansion
886 // location is the macro invocation, which the offset has nothing to do
887 // with. This is unlike when we get the spelling loc, because the offset
888 // directly correspond to the token whose spelling we're inspecting.
889 Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
890 } while (!Loc.isFileID());
895 SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
897 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
898 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
899 Loc = Loc.getLocWithOffset(LocInfo.second);
900 } while (!Loc.isFileID());
904 SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
906 if (isMacroArgExpansion(Loc))
907 Loc = getImmediateSpellingLoc(Loc);
909 Loc = getImmediateExpansionRange(Loc).getBegin();
910 } while (!Loc.isFileID());
915 std::pair<FileID, unsigned>
916 SourceManager::getDecomposedExpansionLocSlowCase(
917 const SrcMgr::SLocEntry *E) const {
918 // If this is an expansion record, walk through all the expansion points.
923 Loc = E->getExpansion().getExpansionLocStart();
925 FID = getFileID(Loc);
926 E = &getSLocEntry(FID);
927 Offset = Loc.getOffset()-E->getOffset();
928 } while (!Loc.isFileID());
930 return std::make_pair(FID, Offset);
933 std::pair<FileID, unsigned>
934 SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
935 unsigned Offset) const {
936 // If this is an expansion record, walk through all the expansion points.
940 Loc = E->getExpansion().getSpellingLoc();
941 Loc = Loc.getLocWithOffset(Offset);
943 FID = getFileID(Loc);
944 E = &getSLocEntry(FID);
945 Offset = Loc.getOffset()-E->getOffset();
946 } while (!Loc.isFileID());
948 return std::make_pair(FID, Offset);
951 /// getImmediateSpellingLoc - Given a SourceLocation object, return the
952 /// spelling location referenced by the ID. This is the first level down
953 /// towards the place where the characters that make up the lexed token can be
954 /// found. This should not generally be used by clients.
955 SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
956 if (Loc.isFileID()) return Loc;
957 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
958 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
959 return Loc.getLocWithOffset(LocInfo.second);
962 /// getImmediateExpansionRange - Loc is required to be an expansion location.
963 /// Return the start/end of the expansion information.
965 SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
966 assert(Loc.isMacroID() && "Not a macro expansion loc!");
967 const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
968 return Expansion.getExpansionLocRange();
971 SourceLocation SourceManager::getTopMacroCallerLoc(SourceLocation Loc) const {
972 while (isMacroArgExpansion(Loc))
973 Loc = getImmediateSpellingLoc(Loc);
977 /// getExpansionRange - Given a SourceLocation object, return the range of
978 /// tokens covered by the expansion in the ultimate file.
979 CharSourceRange SourceManager::getExpansionRange(SourceLocation Loc) const {
981 return CharSourceRange(SourceRange(Loc, Loc), true);
983 CharSourceRange Res = getImmediateExpansionRange(Loc);
985 // Fully resolve the start and end locations to their ultimate expansion
987 while (!Res.getBegin().isFileID())
988 Res.setBegin(getImmediateExpansionRange(Res.getBegin()).getBegin());
989 while (!Res.getEnd().isFileID()) {
990 CharSourceRange EndRange = getImmediateExpansionRange(Res.getEnd());
991 Res.setEnd(EndRange.getEnd());
992 Res.setTokenRange(EndRange.isTokenRange());
997 bool SourceManager::isMacroArgExpansion(SourceLocation Loc,
998 SourceLocation *StartLoc) const {
999 if (!Loc.isMacroID()) return false;
1001 FileID FID = getFileID(Loc);
1002 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1003 if (!Expansion.isMacroArgExpansion()) return false;
1006 *StartLoc = Expansion.getExpansionLocStart();
1010 bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const {
1011 if (!Loc.isMacroID()) return false;
1013 FileID FID = getFileID(Loc);
1014 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1015 return Expansion.isMacroBodyExpansion();
1018 bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
1019 SourceLocation *MacroBegin) const {
1020 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1022 std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);
1023 if (DecompLoc.second > 0)
1024 return false; // Does not point at the start of expansion range.
1026 bool Invalid = false;
1027 const SrcMgr::ExpansionInfo &ExpInfo =
1028 getSLocEntry(DecompLoc.first, &Invalid).getExpansion();
1031 SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();
1033 if (ExpInfo.isMacroArgExpansion()) {
1034 // For macro argument expansions, check if the previous FileID is part of
1035 // the same argument expansion, in which case this Loc is not at the
1036 // beginning of the expansion.
1037 FileID PrevFID = getPreviousFileID(DecompLoc.first);
1038 if (!PrevFID.isInvalid()) {
1039 const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);
1042 if (PrevEntry.isExpansion() &&
1043 PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)
1049 *MacroBegin = ExpLoc;
1053 bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
1054 SourceLocation *MacroEnd) const {
1055 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1057 FileID FID = getFileID(Loc);
1058 SourceLocation NextLoc = Loc.getLocWithOffset(1);
1059 if (isInFileID(NextLoc, FID))
1060 return false; // Does not point at the end of expansion range.
1062 bool Invalid = false;
1063 const SrcMgr::ExpansionInfo &ExpInfo =
1064 getSLocEntry(FID, &Invalid).getExpansion();
1068 if (ExpInfo.isMacroArgExpansion()) {
1069 // For macro argument expansions, check if the next FileID is part of the
1070 // same argument expansion, in which case this Loc is not at the end of the
1072 FileID NextFID = getNextFileID(FID);
1073 if (!NextFID.isInvalid()) {
1074 const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);
1077 if (NextEntry.isExpansion() &&
1078 NextEntry.getExpansion().getExpansionLocStart() ==
1079 ExpInfo.getExpansionLocStart())
1085 *MacroEnd = ExpInfo.getExpansionLocEnd();
1089 //===----------------------------------------------------------------------===//
1090 // Queries about the code at a SourceLocation.
1091 //===----------------------------------------------------------------------===//
1093 /// getCharacterData - Return a pointer to the start of the specified location
1094 /// in the appropriate MemoryBuffer.
1095 const char *SourceManager::getCharacterData(SourceLocation SL,
1096 bool *Invalid) const {
1097 // Note that this is a hot function in the getSpelling() path, which is
1098 // heavily used by -E mode.
1099 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
1101 // Note that calling 'getBuffer()' may lazily page in a source file.
1102 bool CharDataInvalid = false;
1103 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
1104 if (CharDataInvalid || !Entry.isFile()) {
1108 return "<<<<INVALID BUFFER>>>>";
1110 llvm::MemoryBuffer *Buffer = Entry.getFile().getContentCache()->getBuffer(
1111 Diag, *this, SourceLocation(), &CharDataInvalid);
1113 *Invalid = CharDataInvalid;
1114 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
1117 /// getColumnNumber - Return the column # for the specified file position.
1118 /// this is significantly cheaper to compute than the line number.
1119 unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
1120 bool *Invalid) const {
1121 bool MyInvalid = false;
1122 llvm::MemoryBuffer *MemBuf = getBuffer(FID, &MyInvalid);
1124 *Invalid = MyInvalid;
1129 // It is okay to request a position just past the end of the buffer.
1130 if (FilePos > MemBuf->getBufferSize()) {
1136 const char *Buf = MemBuf->getBufferStart();
1137 // See if we just calculated the line number for this FilePos and can use
1138 // that to lookup the start of the line instead of searching for it.
1139 if (LastLineNoFileIDQuery == FID &&
1140 LastLineNoContentCache->SourceLineCache != nullptr &&
1141 LastLineNoResult < LastLineNoContentCache->NumLines) {
1142 unsigned *SourceLineCache = LastLineNoContentCache->SourceLineCache;
1143 unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
1144 unsigned LineEnd = SourceLineCache[LastLineNoResult];
1145 if (FilePos >= LineStart && FilePos < LineEnd) {
1146 // LineEnd is the LineStart of the next line.
1147 // A line ends with separator LF or CR+LF on Windows.
1148 // FilePos might point to the last separator,
1149 // but we need a column number at most 1 + the last column.
1150 if (FilePos + 1 == LineEnd && FilePos > LineStart) {
1151 if (Buf[FilePos - 1] == '\r' || Buf[FilePos - 1] == '\n')
1154 return FilePos - LineStart + 1;
1158 unsigned LineStart = FilePos;
1159 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
1161 return FilePos-LineStart+1;
1164 // isInvalid - Return the result of calling loc.isInvalid(), and
1165 // if Invalid is not null, set its value to same.
1166 template<typename LocType>
1167 static bool isInvalid(LocType Loc, bool *Invalid) {
1168 bool MyInvalid = Loc.isInvalid();
1170 *Invalid = MyInvalid;
1174 unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
1175 bool *Invalid) const {
1176 if (isInvalid(Loc, Invalid)) return 0;
1177 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1178 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1181 unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
1182 bool *Invalid) const {
1183 if (isInvalid(Loc, Invalid)) return 0;
1184 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1185 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1188 unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
1189 bool *Invalid) const {
1190 PresumedLoc PLoc = getPresumedLoc(Loc);
1191 if (isInvalid(PLoc, Invalid)) return 0;
1192 return PLoc.getColumn();
1196 #include <emmintrin.h>
1199 static LLVM_ATTRIBUTE_NOINLINE void
1200 ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
1201 llvm::BumpPtrAllocator &Alloc,
1202 const SourceManager &SM, bool &Invalid);
1203 static void ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
1204 llvm::BumpPtrAllocator &Alloc,
1205 const SourceManager &SM, bool &Invalid) {
1206 // Note that calling 'getBuffer()' may lazily page in the file.
1207 MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(), &Invalid);
1211 // Find the file offsets of all of the *physical* source lines. This does
1212 // not look at trigraphs, escaped newlines, or anything else tricky.
1213 SmallVector<unsigned, 256> LineOffsets;
1215 // Line #1 starts at char 0.
1216 LineOffsets.push_back(0);
1218 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
1219 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
1222 // Skip over the contents of the line.
1223 const unsigned char *NextBuf = (const unsigned char *)Buf;
1226 // Try to skip to the next newline using SSE instructions. This is very
1227 // performance sensitive for programs with lots of diagnostics and in -E
1229 __m128i CRs = _mm_set1_epi8('\r');
1230 __m128i LFs = _mm_set1_epi8('\n');
1232 // First fix up the alignment to 16 bytes.
1233 while (((uintptr_t)NextBuf & 0xF) != 0) {
1234 if (*NextBuf == '\n' || *NextBuf == '\r' || *NextBuf == '\0')
1235 goto FoundSpecialChar;
1239 // Scan 16 byte chunks for '\r' and '\n'. Ignore '\0'.
1240 while (NextBuf+16 <= End) {
1241 const __m128i Chunk = *(const __m128i*)NextBuf;
1242 __m128i Cmp = _mm_or_si128(_mm_cmpeq_epi8(Chunk, CRs),
1243 _mm_cmpeq_epi8(Chunk, LFs));
1244 unsigned Mask = _mm_movemask_epi8(Cmp);
1246 // If we found a newline, adjust the pointer and jump to the handling code.
1248 NextBuf += llvm::countTrailingZeros(Mask);
1249 goto FoundSpecialChar;
1255 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
1261 Offs += NextBuf-Buf;
1264 if (Buf[0] == '\n' || Buf[0] == '\r') {
1265 // If this is \n\r or \r\n, skip both characters.
1266 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1]) {
1272 LineOffsets.push_back(Offs);
1274 // Otherwise, this is a null. If end of file, exit.
1275 if (Buf == End) break;
1276 // Otherwise, skip the null.
1282 // Copy the offsets into the FileInfo structure.
1283 FI->NumLines = LineOffsets.size();
1284 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
1285 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
1288 /// getLineNumber - Given a SourceLocation, return the spelling line number
1289 /// for the position indicated. This requires building and caching a table of
1290 /// line offsets for the MemoryBuffer, so this is not cheap: use only when
1291 /// about to emit a diagnostic.
1292 unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1293 bool *Invalid) const {
1294 if (FID.isInvalid()) {
1300 ContentCache *Content;
1301 if (LastLineNoFileIDQuery == FID)
1302 Content = LastLineNoContentCache;
1304 bool MyInvalid = false;
1305 const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1306 if (MyInvalid || !Entry.isFile()) {
1312 Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
1315 // If this is the first use of line information for this buffer, compute the
1316 /// SourceLineCache for it on demand.
1317 if (!Content->SourceLineCache) {
1318 bool MyInvalid = false;
1319 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
1321 *Invalid = MyInvalid;
1327 // Okay, we know we have a line number table. Do a binary search to find the
1328 // line number that this character position lands on.
1329 unsigned *SourceLineCache = Content->SourceLineCache;
1330 unsigned *SourceLineCacheStart = SourceLineCache;
1331 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
1333 unsigned QueriedFilePos = FilePos+1;
1335 // FIXME: I would like to be convinced that this code is worth being as
1336 // complicated as it is, binary search isn't that slow.
1338 // If it is worth being optimized, then in my opinion it could be more
1339 // performant, simpler, and more obviously correct by just "galloping" outward
1340 // from the queried file position. In fact, this could be incorporated into a
1341 // generic algorithm such as lower_bound_with_hint.
1343 // If someone gives me a test case where this matters, and I will do it! - DWD
1345 // If the previous query was to the same file, we know both the file pos from
1346 // that query and the line number returned. This allows us to narrow the
1347 // search space from the entire file to something near the match.
1348 if (LastLineNoFileIDQuery == FID) {
1349 if (QueriedFilePos >= LastLineNoFilePos) {
1350 // FIXME: Potential overflow?
1351 SourceLineCache = SourceLineCache+LastLineNoResult-1;
1353 // The query is likely to be nearby the previous one. Here we check to
1354 // see if it is within 5, 10 or 20 lines. It can be far away in cases
1355 // where big comment blocks and vertical whitespace eat up lines but
1356 // contribute no tokens.
1357 if (SourceLineCache+5 < SourceLineCacheEnd) {
1358 if (SourceLineCache[5] > QueriedFilePos)
1359 SourceLineCacheEnd = SourceLineCache+5;
1360 else if (SourceLineCache+10 < SourceLineCacheEnd) {
1361 if (SourceLineCache[10] > QueriedFilePos)
1362 SourceLineCacheEnd = SourceLineCache+10;
1363 else if (SourceLineCache+20 < SourceLineCacheEnd) {
1364 if (SourceLineCache[20] > QueriedFilePos)
1365 SourceLineCacheEnd = SourceLineCache+20;
1370 if (LastLineNoResult < Content->NumLines)
1371 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
1376 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
1377 unsigned LineNo = Pos-SourceLineCacheStart;
1379 LastLineNoFileIDQuery = FID;
1380 LastLineNoContentCache = Content;
1381 LastLineNoFilePos = QueriedFilePos;
1382 LastLineNoResult = LineNo;
1386 unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1387 bool *Invalid) const {
1388 if (isInvalid(Loc, Invalid)) return 0;
1389 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1390 return getLineNumber(LocInfo.first, LocInfo.second);
1392 unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
1393 bool *Invalid) const {
1394 if (isInvalid(Loc, Invalid)) return 0;
1395 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1396 return getLineNumber(LocInfo.first, LocInfo.second);
1398 unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
1399 bool *Invalid) const {
1400 PresumedLoc PLoc = getPresumedLoc(Loc);
1401 if (isInvalid(PLoc, Invalid)) return 0;
1402 return PLoc.getLine();
1405 /// getFileCharacteristic - return the file characteristic of the specified
1406 /// source location, indicating whether this is a normal file, a system
1407 /// header, or an "implicit extern C" system header.
1409 /// This state can be modified with flags on GNU linemarker directives like:
1411 /// which changes all source locations in the current file after that to be
1412 /// considered to be from a system header.
1413 SrcMgr::CharacteristicKind
1414 SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1415 assert(Loc.isValid() && "Can't get file characteristic of invalid loc!");
1416 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1417 bool Invalid = false;
1418 const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
1419 if (Invalid || !SEntry.isFile())
1422 const SrcMgr::FileInfo &FI = SEntry.getFile();
1424 // If there are no #line directives in this file, just return the whole-file
1426 if (!FI.hasLineDirectives())
1427 return FI.getFileCharacteristic();
1429 assert(LineTable && "Can't have linetable entries without a LineTable!");
1430 // See if there is a #line directive before the location.
1431 const LineEntry *Entry =
1432 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
1434 // If this is before the first line marker, use the file characteristic.
1436 return FI.getFileCharacteristic();
1438 return Entry->FileKind;
1441 /// Return the filename or buffer identifier of the buffer the location is in.
1442 /// Note that this name does not respect \#line directives. Use getPresumedLoc
1443 /// for normal clients.
1444 StringRef SourceManager::getBufferName(SourceLocation Loc,
1445 bool *Invalid) const {
1446 if (isInvalid(Loc, Invalid)) return "<invalid loc>";
1448 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
1451 /// getPresumedLoc - This method returns the "presumed" location of a
1452 /// SourceLocation specifies. A "presumed location" can be modified by \#line
1453 /// or GNU line marker directives. This provides a view on the data that a
1454 /// user should see in diagnostics, for example.
1456 /// Note that a presumed location is always given as the expansion point of an
1457 /// expansion location, not at the spelling location.
1458 PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc,
1459 bool UseLineDirectives) const {
1460 if (Loc.isInvalid()) return PresumedLoc();
1462 // Presumed locations are always for expansion points.
1463 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1465 bool Invalid = false;
1466 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1467 if (Invalid || !Entry.isFile())
1468 return PresumedLoc();
1470 const SrcMgr::FileInfo &FI = Entry.getFile();
1471 const SrcMgr::ContentCache *C = FI.getContentCache();
1473 // To get the source name, first consult the FileEntry (if one exists)
1474 // before the MemBuffer as this will avoid unnecessarily paging in the
1478 Filename = C->OrigEntry->getName();
1480 Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
1482 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1484 return PresumedLoc();
1485 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1487 return PresumedLoc();
1489 SourceLocation IncludeLoc = FI.getIncludeLoc();
1491 // If we have #line directives in this file, update and overwrite the physical
1492 // location info if appropriate.
1493 if (UseLineDirectives && FI.hasLineDirectives()) {
1494 assert(LineTable && "Can't have linetable entries without a LineTable!");
1495 // See if there is a #line directive before this. If so, get it.
1496 if (const LineEntry *Entry =
1497 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
1498 // If the LineEntry indicates a filename, use it.
1499 if (Entry->FilenameID != -1)
1500 Filename = LineTable->getFilename(Entry->FilenameID);
1502 // Use the line number specified by the LineEntry. This line number may
1503 // be multiple lines down from the line entry. Add the difference in
1504 // physical line numbers from the query point and the line marker to the
1506 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1507 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
1509 // Note that column numbers are not molested by line markers.
1511 // Handle virtual #include manipulation.
1512 if (Entry->IncludeOffset) {
1513 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1514 IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
1519 return PresumedLoc(Filename.data(), LineNo, ColNo, IncludeLoc);
1522 /// Returns whether the PresumedLoc for a given SourceLocation is
1523 /// in the main file.
1525 /// This computes the "presumed" location for a SourceLocation, then checks
1526 /// whether it came from a file other than the main file. This is different
1527 /// from isWrittenInMainFile() because it takes line marker directives into
1529 bool SourceManager::isInMainFile(SourceLocation Loc) const {
1530 if (Loc.isInvalid()) return false;
1532 // Presumed locations are always for expansion points.
1533 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1535 bool Invalid = false;
1536 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1537 if (Invalid || !Entry.isFile())
1540 const SrcMgr::FileInfo &FI = Entry.getFile();
1542 // Check if there is a line directive for this location.
1543 if (FI.hasLineDirectives())
1544 if (const LineEntry *Entry =
1545 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
1546 if (Entry->IncludeOffset)
1549 return FI.getIncludeLoc().isInvalid();
1552 /// The size of the SLocEntry that \p FID represents.
1553 unsigned SourceManager::getFileIDSize(FileID FID) const {
1554 bool Invalid = false;
1555 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1560 unsigned NextOffset;
1561 if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
1562 NextOffset = getNextLocalOffset();
1563 else if (ID+1 == -1)
1564 NextOffset = MaxLoadedOffset;
1566 NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
1568 return NextOffset - Entry.getOffset() - 1;
1571 //===----------------------------------------------------------------------===//
1572 // Other miscellaneous methods.
1573 //===----------------------------------------------------------------------===//
1575 /// Retrieve the inode for the given file entry, if possible.
1577 /// This routine involves a system call, and therefore should only be used
1578 /// in non-performance-critical code.
1579 static Optional<llvm::sys::fs::UniqueID>
1580 getActualFileUID(const FileEntry *File) {
1584 llvm::sys::fs::UniqueID ID;
1585 if (llvm::sys::fs::getUniqueID(File->getName(), ID))
1591 /// Get the source location for the given file:line:col triplet.
1593 /// If the source file is included multiple times, the source location will
1594 /// be based upon an arbitrary inclusion.
1595 SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
1597 unsigned Col) const {
1598 assert(SourceFile && "Null source file!");
1599 assert(Line && Col && "Line and column should start from 1!");
1601 FileID FirstFID = translateFile(SourceFile);
1602 return translateLineCol(FirstFID, Line, Col);
1605 /// Get the FileID for the given file.
1607 /// If the source file is included multiple times, the FileID will be the
1608 /// first inclusion.
1609 FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
1610 assert(SourceFile && "Null source file!");
1612 // Find the first file ID that corresponds to the given file.
1615 // First, check the main file ID, since it is common to look for a
1616 // location in the main file.
1617 Optional<llvm::sys::fs::UniqueID> SourceFileUID;
1618 Optional<StringRef> SourceFileName;
1619 if (MainFileID.isValid()) {
1620 bool Invalid = false;
1621 const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1625 if (MainSLoc.isFile()) {
1626 const ContentCache *MainContentCache
1627 = MainSLoc.getFile().getContentCache();
1628 if (!MainContentCache) {
1629 // Can't do anything
1630 } else if (MainContentCache->OrigEntry == SourceFile) {
1631 FirstFID = MainFileID;
1633 // Fall back: check whether we have the same base name and inode
1634 // as the main file.
1635 const FileEntry *MainFile = MainContentCache->OrigEntry;
1636 SourceFileName = llvm::sys::path::filename(SourceFile->getName());
1637 if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) {
1638 SourceFileUID = getActualFileUID(SourceFile);
1639 if (SourceFileUID) {
1640 if (Optional<llvm::sys::fs::UniqueID> MainFileUID =
1641 getActualFileUID(MainFile)) {
1642 if (*SourceFileUID == *MainFileUID) {
1643 FirstFID = MainFileID;
1644 SourceFile = MainFile;
1653 if (FirstFID.isInvalid()) {
1654 // The location we're looking for isn't in the main file; look
1655 // through all of the local source locations.
1656 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1657 bool Invalid = false;
1658 const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid);
1662 if (SLoc.isFile() &&
1663 SLoc.getFile().getContentCache() &&
1664 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1665 FirstFID = FileID::get(I);
1669 // If that still didn't help, try the modules.
1670 if (FirstFID.isInvalid()) {
1671 for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
1672 const SLocEntry &SLoc = getLoadedSLocEntry(I);
1673 if (SLoc.isFile() &&
1674 SLoc.getFile().getContentCache() &&
1675 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1676 FirstFID = FileID::get(-int(I) - 2);
1683 // If we haven't found what we want yet, try again, but this time stat()
1684 // each of the files in case the files have changed since we originally
1686 if (FirstFID.isInvalid() &&
1688 (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) &&
1689 (SourceFileUID || (SourceFileUID = getActualFileUID(SourceFile)))) {
1690 bool Invalid = false;
1691 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1694 const SLocEntry &SLoc = getSLocEntry(IFileID, &Invalid);
1698 if (SLoc.isFile()) {
1699 const ContentCache *FileContentCache
1700 = SLoc.getFile().getContentCache();
1701 const FileEntry *Entry = FileContentCache ? FileContentCache->OrigEntry
1704 *SourceFileName == llvm::sys::path::filename(Entry->getName())) {
1705 if (Optional<llvm::sys::fs::UniqueID> EntryUID =
1706 getActualFileUID(Entry)) {
1707 if (*SourceFileUID == *EntryUID) {
1708 FirstFID = FileID::get(I);
1722 /// Get the source location in \arg FID for the given line:col.
1723 /// Returns null location if \arg FID is not a file SLocEntry.
1724 SourceLocation SourceManager::translateLineCol(FileID FID,
1726 unsigned Col) const {
1727 // Lines are used as a one-based index into a zero-based array. This assert
1728 // checks for possible buffer underruns.
1729 assert(Line && Col && "Line and column should start from 1!");
1731 if (FID.isInvalid())
1732 return SourceLocation();
1734 bool Invalid = false;
1735 const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1737 return SourceLocation();
1739 if (!Entry.isFile())
1740 return SourceLocation();
1742 SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
1744 if (Line == 1 && Col == 1)
1747 ContentCache *Content
1748 = const_cast<ContentCache *>(Entry.getFile().getContentCache());
1750 return SourceLocation();
1752 // If this is the first use of line information for this buffer, compute the
1753 // SourceLineCache for it on demand.
1754 if (!Content->SourceLineCache) {
1755 bool MyInvalid = false;
1756 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
1758 return SourceLocation();
1761 if (Line > Content->NumLines) {
1762 unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
1765 return FileLoc.getLocWithOffset(Size);
1768 llvm::MemoryBuffer *Buffer = Content->getBuffer(Diag, *this);
1769 unsigned FilePos = Content->SourceLineCache[Line - 1];
1770 const char *Buf = Buffer->getBufferStart() + FilePos;
1771 unsigned BufLength = Buffer->getBufferSize() - FilePos;
1773 return FileLoc.getLocWithOffset(FilePos);
1777 // Check that the given column is valid.
1778 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1780 return FileLoc.getLocWithOffset(FilePos + i);
1783 /// Compute a map of macro argument chunks to their expanded source
1784 /// location. Chunks that are not part of a macro argument will map to an
1785 /// invalid source location. e.g. if a file contains one macro argument at
1786 /// offset 100 with length 10, this is how the map will be formed:
1787 /// 0 -> SourceLocation()
1788 /// 100 -> Expanded macro arg location
1789 /// 110 -> SourceLocation()
1790 void SourceManager::computeMacroArgsCache(MacroArgsMap &MacroArgsCache,
1792 assert(FID.isValid());
1794 // Initially no macro argument chunk is present.
1795 MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
1800 // Stop if there are no more FileIDs to check.
1802 if (unsigned(ID) >= local_sloc_entry_size())
1804 } else if (ID == -1) {
1808 bool Invalid = false;
1809 const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);
1812 if (Entry.isFile()) {
1813 SourceLocation IncludeLoc = Entry.getFile().getIncludeLoc();
1814 if (IncludeLoc.isInvalid())
1816 if (!isInFileID(IncludeLoc, FID))
1817 return; // No more files/macros that may be "contained" in this file.
1819 // Skip the files/macros of the #include'd file, we only care about macros
1820 // that lexed macro arguments from our file.
1821 if (Entry.getFile().NumCreatedFIDs)
1822 ID += Entry.getFile().NumCreatedFIDs - 1/*because of next ++ID*/;
1826 const ExpansionInfo &ExpInfo = Entry.getExpansion();
1828 if (ExpInfo.getExpansionLocStart().isFileID()) {
1829 if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
1830 return; // No more files/macros that may be "contained" in this file.
1833 if (!ExpInfo.isMacroArgExpansion())
1836 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1837 ExpInfo.getSpellingLoc(),
1838 SourceLocation::getMacroLoc(Entry.getOffset()),
1839 getFileIDSize(FileID::get(ID)));
1843 void SourceManager::associateFileChunkWithMacroArgExp(
1844 MacroArgsMap &MacroArgsCache,
1846 SourceLocation SpellLoc,
1847 SourceLocation ExpansionLoc,
1848 unsigned ExpansionLength) const {
1849 if (!SpellLoc.isFileID()) {
1850 unsigned SpellBeginOffs = SpellLoc.getOffset();
1851 unsigned SpellEndOffs = SpellBeginOffs + ExpansionLength;
1853 // The spelling range for this macro argument expansion can span multiple
1854 // consecutive FileID entries. Go through each entry contained in the
1855 // spelling range and if one is itself a macro argument expansion, recurse
1856 // and associate the file chunk that it represents.
1858 FileID SpellFID; // Current FileID in the spelling range.
1859 unsigned SpellRelativeOffs;
1860 std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);
1862 const SLocEntry &Entry = getSLocEntry(SpellFID);
1863 unsigned SpellFIDBeginOffs = Entry.getOffset();
1864 unsigned SpellFIDSize = getFileIDSize(SpellFID);
1865 unsigned SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;
1866 const ExpansionInfo &Info = Entry.getExpansion();
1867 if (Info.isMacroArgExpansion()) {
1868 unsigned CurrSpellLength;
1869 if (SpellFIDEndOffs < SpellEndOffs)
1870 CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
1872 CurrSpellLength = ExpansionLength;
1873 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1874 Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),
1875 ExpansionLoc, CurrSpellLength);
1878 if (SpellFIDEndOffs >= SpellEndOffs)
1879 return; // we covered all FileID entries in the spelling range.
1881 // Move to the next FileID entry in the spelling range.
1882 unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
1883 ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);
1884 ExpansionLength -= advance;
1886 SpellRelativeOffs = 0;
1890 assert(SpellLoc.isFileID());
1893 if (!isInFileID(SpellLoc, FID, &BeginOffs))
1896 unsigned EndOffs = BeginOffs + ExpansionLength;
1898 // Add a new chunk for this macro argument. A previous macro argument chunk
1899 // may have been lexed again, so e.g. if the map is
1900 // 0 -> SourceLocation()
1901 // 100 -> Expanded loc #1
1902 // 110 -> SourceLocation()
1903 // and we found a new macro FileID that lexed from offset 105 with length 3,
1904 // the new map will be:
1905 // 0 -> SourceLocation()
1906 // 100 -> Expanded loc #1
1907 // 105 -> Expanded loc #2
1908 // 108 -> Expanded loc #1
1909 // 110 -> SourceLocation()
1911 // Since re-lexed macro chunks will always be the same size or less of
1912 // previous chunks, we only need to find where the ending of the new macro
1913 // chunk is mapped to and update the map with new begin/end mappings.
1915 MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
1917 SourceLocation EndOffsMappedLoc = I->second;
1918 MacroArgsCache[BeginOffs] = ExpansionLoc;
1919 MacroArgsCache[EndOffs] = EndOffsMappedLoc;
1922 /// If \arg Loc points inside a function macro argument, the returned
1923 /// location will be the macro location in which the argument was expanded.
1924 /// If a macro argument is used multiple times, the expanded location will
1925 /// be at the first expansion of the argument.
1929 /// Passing a file location pointing at 'foo', will yield a macro location
1930 /// where 'foo' was expanded into.
1932 SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
1933 if (Loc.isInvalid() || !Loc.isFileID())
1938 std::tie(FID, Offset) = getDecomposedLoc(Loc);
1939 if (FID.isInvalid())
1942 std::unique_ptr<MacroArgsMap> &MacroArgsCache = MacroArgsCacheMap[FID];
1943 if (!MacroArgsCache) {
1944 MacroArgsCache = llvm::make_unique<MacroArgsMap>();
1945 computeMacroArgsCache(*MacroArgsCache, FID);
1948 assert(!MacroArgsCache->empty());
1949 MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
1952 unsigned MacroArgBeginOffs = I->first;
1953 SourceLocation MacroArgExpandedLoc = I->second;
1954 if (MacroArgExpandedLoc.isValid())
1955 return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
1960 std::pair<FileID, unsigned>
1961 SourceManager::getDecomposedIncludedLoc(FileID FID) const {
1962 if (FID.isInvalid())
1963 return std::make_pair(FileID(), 0);
1965 // Uses IncludedLocMap to retrieve/cache the decomposed loc.
1967 using DecompTy = std::pair<FileID, unsigned>;
1968 using MapTy = llvm::DenseMap<FileID, DecompTy>;
1969 std::pair<MapTy::iterator, bool>
1970 InsertOp = IncludedLocMap.insert(std::make_pair(FID, DecompTy()));
1971 DecompTy &DecompLoc = InsertOp.first->second;
1972 if (!InsertOp.second)
1973 return DecompLoc; // already in map.
1975 SourceLocation UpperLoc;
1976 bool Invalid = false;
1977 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1979 if (Entry.isExpansion())
1980 UpperLoc = Entry.getExpansion().getExpansionLocStart();
1982 UpperLoc = Entry.getFile().getIncludeLoc();
1985 if (UpperLoc.isValid())
1986 DecompLoc = getDecomposedLoc(UpperLoc);
1991 /// Given a decomposed source location, move it up the include/expansion stack
1992 /// to the parent source location. If this is possible, return the decomposed
1993 /// version of the parent in Loc and return false. If Loc is the top-level
1994 /// entry, return true and don't modify it.
1995 static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1996 const SourceManager &SM) {
1997 std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
1998 if (UpperLoc.first.isInvalid())
1999 return true; // We reached the top.
2005 /// Return the cache entry for comparing the given file IDs
2006 /// for isBeforeInTranslationUnit.
2007 InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
2008 FileID RFID) const {
2009 // This is a magic number for limiting the cache size. It was experimentally
2010 // derived from a small Objective-C project (where the cache filled
2011 // out to ~250 items). We can make it larger if necessary.
2012 enum { MagicCacheSize = 300 };
2013 IsBeforeInTUCacheKey Key(LFID, RFID);
2015 // If the cache size isn't too large, do a lookup and if necessary default
2016 // construct an entry. We can then return it to the caller for direct
2017 // use. When they update the value, the cache will get automatically
2019 if (IBTUCache.size() < MagicCacheSize)
2020 return IBTUCache[Key];
2022 // Otherwise, do a lookup that will not construct a new value.
2023 InBeforeInTUCache::iterator I = IBTUCache.find(Key);
2024 if (I != IBTUCache.end())
2027 // Fall back to the overflow value.
2028 return IBTUCacheOverflow;
2031 /// Determines the order of 2 source locations in the translation unit.
2033 /// \returns true if LHS source location comes before RHS, false otherwise.
2034 bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
2035 SourceLocation RHS) const {
2036 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
2040 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
2041 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
2043 // getDecomposedLoc may have failed to return a valid FileID because, e.g. it
2044 // is a serialized one referring to a file that was removed after we loaded
2046 if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
2047 return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
2049 std::pair<bool, bool> InSameTU = isInTheSameTranslationUnit(LOffs, ROffs);
2051 return InSameTU.second;
2053 // If we arrived here, the location is either in a built-ins buffer or
2054 // associated with global inline asm. PR5662 and PR22576 are examples.
2056 StringRef LB = getBuffer(LOffs.first)->getBufferIdentifier();
2057 StringRef RB = getBuffer(ROffs.first)->getBufferIdentifier();
2058 bool LIsBuiltins = LB == "<built-in>";
2059 bool RIsBuiltins = RB == "<built-in>";
2060 // Sort built-in before non-built-in.
2061 if (LIsBuiltins || RIsBuiltins) {
2062 if (LIsBuiltins != RIsBuiltins)
2064 // Both are in built-in buffers, but from different files. We just claim that
2065 // lower IDs come first.
2066 return LOffs.first < ROffs.first;
2068 bool LIsAsm = LB == "<inline asm>";
2069 bool RIsAsm = RB == "<inline asm>";
2070 // Sort assembler after built-ins, but before the rest.
2071 if (LIsAsm || RIsAsm) {
2072 if (LIsAsm != RIsAsm)
2074 assert(LOffs.first == ROffs.first);
2077 bool LIsScratch = LB == "<scratch space>";
2078 bool RIsScratch = RB == "<scratch space>";
2079 // Sort scratch after inline asm, but before the rest.
2080 if (LIsScratch || RIsScratch) {
2081 if (LIsScratch != RIsScratch)
2083 return LOffs.second < ROffs.second;
2085 llvm_unreachable("Unsortable locations found");
2088 std::pair<bool, bool> SourceManager::isInTheSameTranslationUnit(
2089 std::pair<FileID, unsigned> &LOffs,
2090 std::pair<FileID, unsigned> &ROffs) const {
2091 // If the source locations are in the same file, just compare offsets.
2092 if (LOffs.first == ROffs.first)
2093 return std::make_pair(true, LOffs.second < ROffs.second);
2095 // If we are comparing a source location with multiple locations in the same
2096 // file, we get a big win by caching the result.
2097 InBeforeInTUCacheEntry &IsBeforeInTUCache =
2098 getInBeforeInTUCache(LOffs.first, ROffs.first);
2100 // If we are comparing a source location with multiple locations in the same
2101 // file, we get a big win by caching the result.
2102 if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
2103 return std::make_pair(
2104 true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2106 // Okay, we missed in the cache, start updating the cache for this query.
2107 IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
2108 /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID);
2110 // We need to find the common ancestor. The only way of doing this is to
2111 // build the complete include chain for one and then walking up the chain
2112 // of the other looking for a match.
2113 // We use a map from FileID to Offset to store the chain. Easier than writing
2114 // a custom set hash info that only depends on the first part of a pair.
2115 using LocSet = llvm::SmallDenseMap<FileID, unsigned, 16>;
2118 LChain.insert(LOffs);
2119 // We catch the case where LOffs is in a file included by ROffs and
2120 // quit early. The other way round unfortunately remains suboptimal.
2121 } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
2123 while((I = LChain.find(ROffs.first)) == LChain.end()) {
2124 if (MoveUpIncludeHierarchy(ROffs, *this))
2125 break; // Met at topmost file.
2127 if (I != LChain.end())
2130 // If we exited because we found a nearest common ancestor, compare the
2131 // locations within the common file and cache them.
2132 if (LOffs.first == ROffs.first) {
2133 IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
2134 return std::make_pair(
2135 true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2137 // Clear the lookup cache, it depends on a common location.
2138 IsBeforeInTUCache.clear();
2139 return std::make_pair(false, false);
2142 void SourceManager::PrintStats() const {
2143 llvm::errs() << "\n*** Source Manager Stats:\n";
2144 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
2145 << " mem buffers mapped.\n";
2146 llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
2147 << llvm::capacity_in_bytes(LocalSLocEntryTable)
2148 << " bytes of capacity), "
2149 << NextLocalOffset << "B of Sloc address space used.\n";
2150 llvm::errs() << LoadedSLocEntryTable.size()
2151 << " loaded SLocEntries allocated, "
2152 << MaxLoadedOffset - CurrentLoadedOffset
2153 << "B of Sloc address space used.\n";
2155 unsigned NumLineNumsComputed = 0;
2156 unsigned NumFileBytesMapped = 0;
2157 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
2158 NumLineNumsComputed += I->second->SourceLineCache != nullptr;
2159 NumFileBytesMapped += I->second->getSizeBytesMapped();
2161 unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
2163 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
2164 << NumLineNumsComputed << " files with line #'s computed, "
2165 << NumMacroArgsComputed << " files with macro args computed.\n";
2166 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
2167 << NumBinaryProbes << " binary.\n";
2170 LLVM_DUMP_METHOD void SourceManager::dump() const {
2171 llvm::raw_ostream &out = llvm::errs();
2173 auto DumpSLocEntry = [&](int ID, const SrcMgr::SLocEntry &Entry,
2174 llvm::Optional<unsigned> NextStart) {
2175 out << "SLocEntry <FileID " << ID << "> " << (Entry.isFile() ? "file" : "expansion")
2176 << " <SourceLocation " << Entry.getOffset() << ":";
2178 out << *NextStart << ">\n";
2181 if (Entry.isFile()) {
2182 auto &FI = Entry.getFile();
2183 if (FI.NumCreatedFIDs)
2184 out << " covers <FileID " << ID << ":" << int(ID + FI.NumCreatedFIDs)
2186 if (FI.getIncludeLoc().isValid())
2187 out << " included from " << FI.getIncludeLoc().getOffset() << "\n";
2188 if (auto *CC = FI.getContentCache()) {
2189 out << " for " << (CC->OrigEntry ? CC->OrigEntry->getName() : "<none>")
2191 if (CC->BufferOverridden)
2192 out << " contents overridden\n";
2193 if (CC->ContentsEntry != CC->OrigEntry) {
2194 out << " contents from "
2195 << (CC->ContentsEntry ? CC->ContentsEntry->getName() : "<none>")
2200 auto &EI = Entry.getExpansion();
2201 out << " spelling from " << EI.getSpellingLoc().getOffset() << "\n";
2202 out << " macro " << (EI.isMacroArgExpansion() ? "arg" : "body")
2203 << " range <" << EI.getExpansionLocStart().getOffset() << ":"
2204 << EI.getExpansionLocEnd().getOffset() << ">\n";
2208 // Dump local SLocEntries.
2209 for (unsigned ID = 0, NumIDs = LocalSLocEntryTable.size(); ID != NumIDs; ++ID) {
2210 DumpSLocEntry(ID, LocalSLocEntryTable[ID],
2211 ID == NumIDs - 1 ? NextLocalOffset
2212 : LocalSLocEntryTable[ID + 1].getOffset());
2214 // Dump loaded SLocEntries.
2215 llvm::Optional<unsigned> NextStart;
2216 for (unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
2217 int ID = -(int)Index - 2;
2218 if (SLocEntryLoaded[Index]) {
2219 DumpSLocEntry(ID, LoadedSLocEntryTable[Index], NextStart);
2220 NextStart = LoadedSLocEntryTable[Index].getOffset();
2227 ExternalSLocEntrySource::~ExternalSLocEntrySource() = default;
2229 /// Return the amount of memory used by memory buffers, breaking down
2230 /// by heap-backed versus mmap'ed memory.
2231 SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
2232 size_t malloc_bytes = 0;
2233 size_t mmap_bytes = 0;
2235 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
2236 if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
2237 switch (MemBufferInfos[i]->getMemoryBufferKind()) {
2238 case llvm::MemoryBuffer::MemoryBuffer_MMap:
2239 mmap_bytes += sized_mapped;
2241 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
2242 malloc_bytes += sized_mapped;
2246 return MemoryBufferSizes(malloc_bytes, mmap_bytes);
2249 size_t SourceManager::getDataStructureSizes() const {
2250 size_t size = llvm::capacity_in_bytes(MemBufferInfos)
2251 + llvm::capacity_in_bytes(LocalSLocEntryTable)
2252 + llvm::capacity_in_bytes(LoadedSLocEntryTable)
2253 + llvm::capacity_in_bytes(SLocEntryLoaded)
2254 + llvm::capacity_in_bytes(FileInfos);
2256 if (OverriddenFilesInfo)
2257 size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);
2262 SourceManagerForFile::SourceManagerForFile(StringRef FileName,
2263 StringRef Content) {
2264 // This is referenced by `FileMgr` and will be released by `FileMgr` when it
2266 IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
2267 new vfs::InMemoryFileSystem);
2268 InMemoryFileSystem->addFile(
2270 llvm::MemoryBuffer::getMemBuffer(Content, FileName,
2271 /*RequiresNullTerminator=*/false));
2272 // This is passed to `SM` as reference, so the pointer has to be referenced
2273 // in `Environment` so that `FileMgr` can out-live this function scope.
2275 llvm::make_unique<FileManager>(FileSystemOptions(), InMemoryFileSystem);
2276 // This is passed to `SM` as reference, so the pointer has to be referenced
2277 // by `Environment` due to the same reason above.
2278 Diagnostics = llvm::make_unique<DiagnosticsEngine>(
2279 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
2280 new DiagnosticOptions);
2281 SourceMgr = llvm::make_unique<SourceManager>(*Diagnostics, *FileMgr);
2282 FileID ID = SourceMgr->createFileID(FileMgr->getFile(FileName),
2283 SourceLocation(), clang::SrcMgr::C_User);
2284 assert(ID.isValid());
2285 SourceMgr->setMainFileID(ID);