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"
30 using namespace clang;
31 using namespace SrcMgr;
32 using llvm::MemoryBuffer;
34 //===----------------------------------------------------------------------===//
35 // SourceManager Helper Classes
36 //===----------------------------------------------------------------------===//
38 ContentCache::~ContentCache() {
39 if (shouldFreeBuffer())
40 delete Buffer.getPointer();
43 /// getSizeBytesMapped - Returns the number of bytes actually mapped for this
44 /// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
45 unsigned ContentCache::getSizeBytesMapped() const {
46 return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
49 /// Returns the kind of memory used to back the memory buffer for
50 /// this content cache. This is used for performance analysis.
51 llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
52 assert(Buffer.getPointer());
54 // Should be unreachable, but keep for sanity.
55 if (!Buffer.getPointer())
56 return llvm::MemoryBuffer::MemoryBuffer_Malloc;
58 llvm::MemoryBuffer *buf = Buffer.getPointer();
59 return buf->getBufferKind();
62 /// getSize - Returns the size of the content encapsulated by this ContentCache.
63 /// This can be the size of the source file or the size of an arbitrary
64 /// scratch buffer. If the ContentCache encapsulates a source file, that
65 /// file is not lazily brought in from disk to satisfy this query.
66 unsigned ContentCache::getSize() const {
67 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
68 : (unsigned) ContentsEntry->getSize();
71 void ContentCache::replaceBuffer(llvm::MemoryBuffer *B, bool DoNotFree) {
72 if (B && B == Buffer.getPointer()) {
73 assert(0 && "Replacing with the same buffer");
74 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
78 if (shouldFreeBuffer())
79 delete Buffer.getPointer();
81 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
84 llvm::MemoryBuffer *ContentCache::getBuffer(DiagnosticsEngine &Diag,
85 const SourceManager &SM,
87 bool *Invalid) const {
88 // Lazily create the Buffer for ContentCaches that wrap files. If we already
89 // computed it, just return what we have.
90 if (Buffer.getPointer() || !ContentsEntry) {
92 *Invalid = isBufferInvalid();
94 return Buffer.getPointer();
97 bool isVolatile = SM.userFilesAreVolatile() && !IsSystemFile;
99 SM.getFileManager().getBufferForFile(ContentsEntry, isVolatile);
101 // If we were unable to open the file, then we are in an inconsistent
102 // situation where the content cache referenced a file which no longer
103 // exists. Most likely, we were using a stat cache with an invalid entry but
104 // the file could also have been removed during processing. Since we can't
105 // really deal with this situation, just create an empty buffer.
107 // FIXME: This is definitely not ideal, but our immediate clients can't
108 // currently handle returning a null entry here. Ideally we should detect
109 // that we are in an inconsistent situation and error out as quickly as
111 if (!BufferOrError) {
112 StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
113 Buffer.setPointer(MemoryBuffer::getNewUninitMemBuffer(
114 ContentsEntry->getSize(), "<invalid>").release());
115 char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart());
116 for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
117 Ptr[i] = FillStr[i % FillStr.size()];
119 if (Diag.isDiagnosticInFlight())
120 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
121 ContentsEntry->getName(),
122 BufferOrError.getError().message());
124 Diag.Report(Loc, diag::err_cannot_open_file)
125 << ContentsEntry->getName() << BufferOrError.getError().message();
127 Buffer.setInt(Buffer.getInt() | InvalidFlag);
129 if (Invalid) *Invalid = true;
130 return Buffer.getPointer();
133 Buffer.setPointer(BufferOrError->release());
135 // Check that the file's size is the same as in the file entry (which may
136 // have come from a stat cache).
137 if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) {
138 if (Diag.isDiagnosticInFlight())
139 Diag.SetDelayedDiagnostic(diag::err_file_modified,
140 ContentsEntry->getName());
142 Diag.Report(Loc, diag::err_file_modified)
143 << ContentsEntry->getName();
145 Buffer.setInt(Buffer.getInt() | InvalidFlag);
146 if (Invalid) *Invalid = true;
147 return Buffer.getPointer();
150 // If the buffer is valid, check to see if it has a UTF Byte Order Mark
151 // (BOM). We only support UTF-8 with and without a BOM right now. See
152 // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
153 StringRef BufStr = Buffer.getPointer()->getBuffer();
154 const char *InvalidBOM = llvm::StringSwitch<const char *>(BufStr)
155 .StartsWith("\xFE\xFF", "UTF-16 (BE)")
156 .StartsWith("\xFF\xFE", "UTF-16 (LE)")
157 .StartsWith("\x00\x00\xFE\xFF", "UTF-32 (BE)")
158 .StartsWith("\xFF\xFE\x00\x00", "UTF-32 (LE)")
159 .StartsWith("\x2B\x2F\x76", "UTF-7")
160 .StartsWith("\xF7\x64\x4C", "UTF-1")
161 .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
162 .StartsWith("\x0E\xFE\xFF", "SDSU")
163 .StartsWith("\xFB\xEE\x28", "BOCU-1")
164 .StartsWith("\x84\x31\x95\x33", "GB-18030")
168 Diag.Report(Loc, diag::err_unsupported_bom)
169 << InvalidBOM << ContentsEntry->getName();
170 Buffer.setInt(Buffer.getInt() | InvalidFlag);
174 *Invalid = isBufferInvalid();
176 return Buffer.getPointer();
179 unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
181 FilenameIDs.insert(std::make_pair(Name, FilenamesByID.size()));
183 FilenamesByID.push_back(&*IterBool.first);
184 return IterBool.first->second;
187 /// AddLineNote - Add a line note to the line table that indicates that there
188 /// is a \#line at the specified FID/Offset location which changes the presumed
189 /// location to LineNo/FilenameID.
190 void LineTableInfo::AddLineNote(FileID FID, unsigned Offset,
191 unsigned LineNo, int FilenameID) {
192 std::vector<LineEntry> &Entries = LineEntries[FID];
194 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
195 "Adding line entries out of order!");
197 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
198 unsigned IncludeOffset = 0;
200 if (!Entries.empty()) {
201 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
202 // that we are still in "foo.h".
203 if (FilenameID == -1)
204 FilenameID = Entries.back().FilenameID;
206 // If we are after a line marker that switched us to system header mode, or
207 // that set #include information, preserve it.
208 Kind = Entries.back().FileKind;
209 IncludeOffset = Entries.back().IncludeOffset;
212 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
216 /// AddLineNote This is the same as the previous version of AddLineNote, but is
217 /// used for GNU line markers. If EntryExit is 0, then this doesn't change the
218 /// presumed \#include stack. If it is 1, this is a file entry, if it is 2 then
219 /// this is a file exit. FileKind specifies whether this is a system header or
220 /// extern C system header.
221 void LineTableInfo::AddLineNote(FileID FID, unsigned Offset,
222 unsigned LineNo, int FilenameID,
224 SrcMgr::CharacteristicKind FileKind) {
225 assert(FilenameID != -1 && "Unspecified filename should use other accessor");
227 std::vector<LineEntry> &Entries = LineEntries[FID];
229 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
230 "Adding line entries out of order!");
232 unsigned IncludeOffset = 0;
233 if (EntryExit == 0) { // No #include stack change.
234 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
235 } else if (EntryExit == 1) {
236 IncludeOffset = Offset-1;
237 } else if (EntryExit == 2) {
238 assert(!Entries.empty() && Entries.back().IncludeOffset &&
239 "PPDirectives should have caught case when popping empty include stack");
241 // Get the include loc of the last entries' include loc as our include loc.
243 if (const LineEntry *PrevEntry =
244 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
245 IncludeOffset = PrevEntry->IncludeOffset;
248 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
253 /// FindNearestLineEntry - Find the line entry nearest to FID that is before
254 /// it. If there is no line entry before Offset in FID, return null.
255 const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID,
257 const std::vector<LineEntry> &Entries = LineEntries[FID];
258 assert(!Entries.empty() && "No #line entries for this FID after all!");
260 // It is very common for the query to be after the last #line, check this
262 if (Entries.back().FileOffset <= Offset)
263 return &Entries.back();
265 // Do a binary search to find the maximal element that is still before Offset.
266 std::vector<LineEntry>::const_iterator I =
267 std::upper_bound(Entries.begin(), Entries.end(), Offset);
268 if (I == Entries.begin()) return nullptr;
272 /// \brief Add a new line entry that has already been encoded into
273 /// the internal representation of the line table.
274 void LineTableInfo::AddEntry(FileID FID,
275 const std::vector<LineEntry> &Entries) {
276 LineEntries[FID] = Entries;
279 /// getLineTableFilenameID - Return the uniqued ID for the specified filename.
281 unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
282 return getLineTable().getLineTableFilenameID(Name);
286 /// AddLineNote - Add a line note to the line table for the FileID and offset
287 /// specified by Loc. If FilenameID is -1, it is considered to be
289 void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
291 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
293 bool Invalid = false;
294 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
295 if (!Entry.isFile() || Invalid)
298 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
300 // Remember that this file has #line directives now if it doesn't already.
301 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
303 getLineTable().AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID);
306 /// AddLineNote - Add a GNU line marker to the line table.
307 void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
308 int FilenameID, bool IsFileEntry,
309 bool IsFileExit, bool IsSystemHeader,
310 bool IsExternCHeader) {
311 // If there is no filename and no flags, this is treated just like a #line,
312 // which does not change the flags of the previous line marker.
313 if (FilenameID == -1) {
314 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
315 "Can't set flags without setting the filename!");
316 return AddLineNote(Loc, LineNo, FilenameID);
319 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
321 bool Invalid = false;
322 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
323 if (!Entry.isFile() || Invalid)
326 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
328 // Remember that this file has #line directives now if it doesn't already.
329 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
331 (void) getLineTable();
333 SrcMgr::CharacteristicKind FileKind;
335 FileKind = SrcMgr::C_ExternCSystem;
336 else if (IsSystemHeader)
337 FileKind = SrcMgr::C_System;
339 FileKind = SrcMgr::C_User;
341 unsigned EntryExit = 0;
347 LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,
348 EntryExit, FileKind);
351 LineTableInfo &SourceManager::getLineTable() {
353 LineTable = new LineTableInfo();
357 //===----------------------------------------------------------------------===//
358 // Private 'Create' methods.
359 //===----------------------------------------------------------------------===//
361 SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
362 bool UserFilesAreVolatile)
363 : Diag(Diag), FileMgr(FileMgr), OverridenFilesKeepOriginalName(true),
364 UserFilesAreVolatile(UserFilesAreVolatile), FilesAreTransient(false),
365 ExternalSLocEntries(nullptr), LineTable(nullptr), NumLinearScans(0),
368 Diag.setSourceManager(this);
371 SourceManager::~SourceManager() {
374 // Delete FileEntry objects corresponding to content caches. Since the actual
375 // content cache objects are bump pointer allocated, we just have to run the
376 // dtors, but we call the deallocate method for completeness.
377 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
378 if (MemBufferInfos[i]) {
379 MemBufferInfos[i]->~ContentCache();
380 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
383 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
384 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
386 I->second->~ContentCache();
387 ContentCacheAlloc.Deallocate(I->second);
391 llvm::DeleteContainerSeconds(MacroArgsCacheMap);
394 void SourceManager::clearIDTables() {
395 MainFileID = FileID();
396 LocalSLocEntryTable.clear();
397 LoadedSLocEntryTable.clear();
398 SLocEntryLoaded.clear();
399 LastLineNoFileIDQuery = FileID();
400 LastLineNoContentCache = nullptr;
401 LastFileIDLookup = FileID();
406 // Use up FileID #0 as an invalid expansion.
408 CurrentLoadedOffset = MaxLoadedOffset;
409 createExpansionLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
412 /// getOrCreateContentCache - Create or return a cached ContentCache for the
415 SourceManager::getOrCreateContentCache(const FileEntry *FileEnt,
417 assert(FileEnt && "Didn't specify a file entry to use?");
419 // Do we already have information about this file?
420 ContentCache *&Entry = FileInfos[FileEnt];
421 if (Entry) return Entry;
423 // Nope, create a new Cache entry.
424 Entry = ContentCacheAlloc.Allocate<ContentCache>();
426 if (OverriddenFilesInfo) {
427 // If the file contents are overridden with contents from another file,
428 // pass that file to ContentCache.
429 llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
430 overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
431 if (overI == OverriddenFilesInfo->OverriddenFiles.end())
432 new (Entry) ContentCache(FileEnt);
434 new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
438 new (Entry) ContentCache(FileEnt);
441 Entry->IsSystemFile = isSystemFile;
442 Entry->IsTransient = FilesAreTransient;
448 /// createMemBufferContentCache - Create a new ContentCache for the specified
449 /// memory buffer. This does no caching.
450 const ContentCache *SourceManager::createMemBufferContentCache(
451 std::unique_ptr<llvm::MemoryBuffer> Buffer) {
452 // Add a new ContentCache to the MemBufferInfos list and return it.
453 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
454 new (Entry) ContentCache();
455 MemBufferInfos.push_back(Entry);
456 Entry->setBuffer(std::move(Buffer));
460 const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
461 bool *Invalid) const {
462 assert(!SLocEntryLoaded[Index]);
463 if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
466 // If the file of the SLocEntry changed we could still have loaded it.
467 if (!SLocEntryLoaded[Index]) {
468 // Try to recover; create a SLocEntry so the rest of clang can handle it.
469 LoadedSLocEntryTable[Index] = SLocEntry::get(0,
470 FileInfo::get(SourceLocation(),
471 getFakeContentCacheForRecovery(),
476 return LoadedSLocEntryTable[Index];
479 std::pair<int, unsigned>
480 SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
481 unsigned TotalSize) {
482 assert(ExternalSLocEntries && "Don't have an external sloc source");
483 // Make sure we're not about to run out of source locations.
484 if (CurrentLoadedOffset - TotalSize < NextLocalOffset)
485 return std::make_pair(0, 0);
486 LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
487 SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
488 CurrentLoadedOffset -= TotalSize;
489 int ID = LoadedSLocEntryTable.size();
490 return std::make_pair(-ID - 1, CurrentLoadedOffset);
493 /// \brief As part of recovering from missing or changed content, produce a
494 /// fake, non-empty buffer.
495 llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const {
496 if (!FakeBufferForRecovery)
497 FakeBufferForRecovery =
498 llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
500 return FakeBufferForRecovery.get();
503 /// \brief As part of recovering from missing or changed content, produce a
504 /// fake content cache.
505 const SrcMgr::ContentCache *
506 SourceManager::getFakeContentCacheForRecovery() const {
507 if (!FakeContentCacheForRecovery) {
508 FakeContentCacheForRecovery = llvm::make_unique<SrcMgr::ContentCache>();
509 FakeContentCacheForRecovery->replaceBuffer(getFakeBufferForRecovery(),
512 return FakeContentCacheForRecovery.get();
515 /// \brief Returns the previous in-order FileID or an invalid FileID if there
516 /// is no previous one.
517 FileID SourceManager::getPreviousFileID(FileID FID) const {
528 } else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {
532 return FileID::get(ID-1);
535 /// \brief Returns the next in-order FileID or an invalid FileID if there is
537 FileID SourceManager::getNextFileID(FileID FID) const {
543 if (unsigned(ID+1) >= local_sloc_entry_size())
545 } else if (ID+1 >= -1) {
549 return FileID::get(ID+1);
552 //===----------------------------------------------------------------------===//
553 // Methods to create new FileID's and macro expansions.
554 //===----------------------------------------------------------------------===//
556 /// createFileID - Create a new FileID for the specified ContentCache and
557 /// include position. This works regardless of whether the ContentCache
558 /// corresponds to a file or some other input source.
559 FileID SourceManager::createFileID(const ContentCache *File,
560 SourceLocation IncludePos,
561 SrcMgr::CharacteristicKind FileCharacter,
562 int LoadedID, unsigned LoadedOffset) {
564 assert(LoadedID != -1 && "Loading sentinel FileID");
565 unsigned Index = unsigned(-LoadedID) - 2;
566 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
567 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
568 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset,
569 FileInfo::get(IncludePos, File, FileCharacter));
570 SLocEntryLoaded[Index] = true;
571 return FileID::get(LoadedID);
573 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset,
574 FileInfo::get(IncludePos, File,
576 unsigned FileSize = File->getSize();
577 assert(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
578 NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset &&
579 "Ran out of source locations!");
580 // We do a +1 here because we want a SourceLocation that means "the end of the
581 // file", e.g. for the "no newline at the end of the file" diagnostic.
582 NextLocalOffset += FileSize + 1;
584 // Set LastFileIDLookup to the newly created file. The next getFileID call is
585 // almost guaranteed to be from that file.
586 FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
587 return LastFileIDLookup = FID;
591 SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc,
592 SourceLocation ExpansionLoc,
593 unsigned TokLength) {
594 ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
596 return createExpansionLocImpl(Info, TokLength);
600 SourceManager::createExpansionLoc(SourceLocation SpellingLoc,
601 SourceLocation ExpansionLocStart,
602 SourceLocation ExpansionLocEnd,
605 unsigned LoadedOffset) {
606 ExpansionInfo Info = ExpansionInfo::create(SpellingLoc, ExpansionLocStart,
608 return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset);
612 SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
615 unsigned LoadedOffset) {
617 assert(LoadedID != -1 && "Loading sentinel FileID");
618 unsigned Index = unsigned(-LoadedID) - 2;
619 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
620 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
621 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
622 SLocEntryLoaded[Index] = true;
623 return SourceLocation::getMacroLoc(LoadedOffset);
625 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
626 assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&
627 NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&
628 "Ran out of source locations!");
629 // See createFileID for that +1.
630 NextLocalOffset += TokLength + 1;
631 return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
634 llvm::MemoryBuffer *SourceManager::getMemoryBufferForFile(const FileEntry *File,
636 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
637 assert(IR && "getOrCreateContentCache() cannot return NULL");
638 return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
641 void SourceManager::overrideFileContents(const FileEntry *SourceFile,
642 llvm::MemoryBuffer *Buffer,
644 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
645 assert(IR && "getOrCreateContentCache() cannot return NULL");
647 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
648 const_cast<SrcMgr::ContentCache *>(IR)->BufferOverridden = true;
650 getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
653 void SourceManager::overrideFileContents(const FileEntry *SourceFile,
654 const FileEntry *NewFile) {
655 assert(SourceFile->getSize() == NewFile->getSize() &&
656 "Different sizes, use the FileManager to create a virtual file with "
658 assert(FileInfos.count(SourceFile) == 0 &&
659 "This function should be called at the initialization stage, before "
660 "any parsing occurs.");
661 getOverriddenFilesInfo().OverriddenFiles[SourceFile] = NewFile;
664 void SourceManager::disableFileContentsOverride(const FileEntry *File) {
665 if (!isFileOverridden(File))
668 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
669 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(nullptr);
670 const_cast<SrcMgr::ContentCache *>(IR)->ContentsEntry = IR->OrigEntry;
672 assert(OverriddenFilesInfo);
673 OverriddenFilesInfo->OverriddenFiles.erase(File);
674 OverriddenFilesInfo->OverriddenFilesWithBuffer.erase(File);
677 void SourceManager::setFileIsTransient(const FileEntry *File) {
678 const SrcMgr::ContentCache *CC = getOrCreateContentCache(File);
679 const_cast<SrcMgr::ContentCache *>(CC)->IsTransient = true;
682 StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
683 bool MyInvalid = false;
684 const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid);
685 if (!SLoc.isFile() || MyInvalid) {
688 return "<<<<<INVALID SOURCE LOCATION>>>>>";
691 llvm::MemoryBuffer *Buf = SLoc.getFile().getContentCache()->getBuffer(
692 Diag, *this, SourceLocation(), &MyInvalid);
694 *Invalid = MyInvalid;
697 return "<<<<<INVALID SOURCE LOCATION>>>>>";
699 return Buf->getBuffer();
702 //===----------------------------------------------------------------------===//
703 // SourceLocation manipulation methods.
704 //===----------------------------------------------------------------------===//
706 /// \brief Return the FileID for a SourceLocation.
708 /// This is the cache-miss path of getFileID. Not as hot as that function, but
709 /// still very important. It is responsible for finding the entry in the
710 /// SLocEntry tables that contains the specified location.
711 FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
713 return FileID::get(0);
715 // Now it is time to search for the correct file. See where the SLocOffset
716 // sits in the global view and consult local or loaded buffers for it.
717 if (SLocOffset < NextLocalOffset)
718 return getFileIDLocal(SLocOffset);
719 return getFileIDLoaded(SLocOffset);
722 /// \brief Return the FileID for a SourceLocation with a low offset.
724 /// This function knows that the SourceLocation is in a local buffer, not a
726 FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const {
727 assert(SLocOffset < NextLocalOffset && "Bad function choice");
729 // After the first and second level caches, I see two common sorts of
730 // behavior: 1) a lot of searched FileID's are "near" the cached file
731 // location or are "near" the cached expansion location. 2) others are just
732 // completely random and may be a very long way away.
734 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
735 // then we fall back to a less cache efficient, but more scalable, binary
736 // search to find the location.
738 // See if this is near the file point - worst case we start scanning from the
739 // most newly created FileID.
740 const SrcMgr::SLocEntry *I;
742 if (LastFileIDLookup.ID < 0 ||
743 LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
744 // Neither loc prunes our search.
745 I = LocalSLocEntryTable.end();
747 // Perhaps it is near the file point.
748 I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
751 // Find the FileID that contains this. "I" is an iterator that points to a
752 // FileID whose offset is known to be larger than SLocOffset.
753 unsigned NumProbes = 0;
756 if (I->getOffset() <= SLocOffset) {
757 FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
759 // If this isn't an expansion, remember it. We have good locality across
761 if (!I->isExpansion())
762 LastFileIDLookup = Res;
763 NumLinearScans += NumProbes+1;
766 if (++NumProbes == 8)
770 // Convert "I" back into an index. We know that it is an entry whose index is
771 // larger than the offset we are looking for.
772 unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
773 // LessIndex - This is the lower bound of the range that we're searching.
774 // We know that the offset corresponding to the FileID is is less than
776 unsigned LessIndex = 0;
779 bool Invalid = false;
780 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
781 unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
783 return FileID::get(0);
787 // If the offset of the midpoint is too large, chop the high side of the
788 // range to the midpoint.
789 if (MidOffset > SLocOffset) {
790 GreaterIndex = MiddleIndex;
794 // If the middle index contains the value, succeed and return.
795 // FIXME: This could be made faster by using a function that's aware of
796 // being in the local area.
797 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
798 FileID Res = FileID::get(MiddleIndex);
800 // If this isn't a macro expansion, remember it. We have good locality
801 // across FileID lookups.
802 if (!LocalSLocEntryTable[MiddleIndex].isExpansion())
803 LastFileIDLookup = Res;
804 NumBinaryProbes += NumProbes;
808 // Otherwise, move the low-side up to the middle index.
809 LessIndex = MiddleIndex;
813 /// \brief Return the FileID for a SourceLocation with a high offset.
815 /// This function knows that the SourceLocation is in a loaded buffer, not a
817 FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
818 // Sanity checking, otherwise a bug may lead to hanging in release build.
819 if (SLocOffset < CurrentLoadedOffset) {
820 assert(0 && "Invalid SLocOffset or bad function choice");
824 // Essentially the same as the local case, but the loaded array is sorted
825 // in the other direction.
827 // First do a linear scan from the last lookup position, if possible.
829 int LastID = LastFileIDLookup.ID;
830 if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
833 I = (-LastID - 2) + 1;
836 for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
837 // Make sure the entry is loaded!
838 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
839 if (E.getOffset() <= SLocOffset) {
840 FileID Res = FileID::get(-int(I) - 2);
842 if (!E.isExpansion())
843 LastFileIDLookup = Res;
844 NumLinearScans += NumProbes + 1;
849 // Linear scan failed. Do the binary search. Note the reverse sorting of the
850 // table: GreaterIndex is the one where the offset is greater, which is
851 // actually a lower index!
852 unsigned GreaterIndex = I;
853 unsigned LessIndex = LoadedSLocEntryTable.size();
857 unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
858 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
859 if (E.getOffset() == 0)
860 return FileID(); // invalid entry.
864 if (E.getOffset() > SLocOffset) {
865 // Sanity checking, otherwise a bug may lead to hanging in release build.
866 if (GreaterIndex == MiddleIndex) {
867 assert(0 && "binary search missed the entry");
870 GreaterIndex = MiddleIndex;
874 if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
875 FileID Res = FileID::get(-int(MiddleIndex) - 2);
876 if (!E.isExpansion())
877 LastFileIDLookup = Res;
878 NumBinaryProbes += NumProbes;
882 // Sanity checking, otherwise a bug may lead to hanging in release build.
883 if (LessIndex == MiddleIndex) {
884 assert(0 && "binary search missed the entry");
887 LessIndex = MiddleIndex;
891 SourceLocation SourceManager::
892 getExpansionLocSlowCase(SourceLocation Loc) const {
894 // Note: If Loc indicates an offset into a token that came from a macro
895 // expansion (e.g. the 5th character of the token) we do not want to add
896 // this offset when going to the expansion location. The expansion
897 // location is the macro invocation, which the offset has nothing to do
898 // with. This is unlike when we get the spelling loc, because the offset
899 // directly correspond to the token whose spelling we're inspecting.
900 Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
901 } while (!Loc.isFileID());
906 SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
908 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
909 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
910 Loc = Loc.getLocWithOffset(LocInfo.second);
911 } while (!Loc.isFileID());
915 SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
917 if (isMacroArgExpansion(Loc))
918 Loc = getImmediateSpellingLoc(Loc);
920 Loc = getImmediateExpansionRange(Loc).first;
921 } while (!Loc.isFileID());
926 std::pair<FileID, unsigned>
927 SourceManager::getDecomposedExpansionLocSlowCase(
928 const SrcMgr::SLocEntry *E) const {
929 // If this is an expansion record, walk through all the expansion points.
934 Loc = E->getExpansion().getExpansionLocStart();
936 FID = getFileID(Loc);
937 E = &getSLocEntry(FID);
938 Offset = Loc.getOffset()-E->getOffset();
939 } while (!Loc.isFileID());
941 return std::make_pair(FID, Offset);
944 std::pair<FileID, unsigned>
945 SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
946 unsigned Offset) const {
947 // If this is an expansion record, walk through all the expansion points.
951 Loc = E->getExpansion().getSpellingLoc();
952 Loc = Loc.getLocWithOffset(Offset);
954 FID = getFileID(Loc);
955 E = &getSLocEntry(FID);
956 Offset = Loc.getOffset()-E->getOffset();
957 } while (!Loc.isFileID());
959 return std::make_pair(FID, Offset);
962 /// getImmediateSpellingLoc - Given a SourceLocation object, return the
963 /// spelling location referenced by the ID. This is the first level down
964 /// towards the place where the characters that make up the lexed token can be
965 /// found. This should not generally be used by clients.
966 SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
967 if (Loc.isFileID()) return Loc;
968 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
969 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
970 return Loc.getLocWithOffset(LocInfo.second);
974 /// getImmediateExpansionRange - Loc is required to be an expansion location.
975 /// Return the start/end of the expansion information.
976 std::pair<SourceLocation,SourceLocation>
977 SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
978 assert(Loc.isMacroID() && "Not a macro expansion loc!");
979 const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
980 return Expansion.getExpansionLocRange();
983 /// getExpansionRange - Given a SourceLocation object, return the range of
984 /// tokens covered by the expansion in the ultimate file.
985 std::pair<SourceLocation,SourceLocation>
986 SourceManager::getExpansionRange(SourceLocation Loc) const {
987 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
989 std::pair<SourceLocation,SourceLocation> Res =
990 getImmediateExpansionRange(Loc);
992 // Fully resolve the start and end locations to their ultimate expansion
994 while (!Res.first.isFileID())
995 Res.first = getImmediateExpansionRange(Res.first).first;
996 while (!Res.second.isFileID())
997 Res.second = getImmediateExpansionRange(Res.second).second;
1001 bool SourceManager::isMacroArgExpansion(SourceLocation Loc,
1002 SourceLocation *StartLoc) const {
1003 if (!Loc.isMacroID()) return false;
1005 FileID FID = getFileID(Loc);
1006 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1007 if (!Expansion.isMacroArgExpansion()) return false;
1010 *StartLoc = Expansion.getExpansionLocStart();
1014 bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const {
1015 if (!Loc.isMacroID()) return false;
1017 FileID FID = getFileID(Loc);
1018 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1019 return Expansion.isMacroBodyExpansion();
1022 bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
1023 SourceLocation *MacroBegin) const {
1024 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1026 std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);
1027 if (DecompLoc.second > 0)
1028 return false; // Does not point at the start of expansion range.
1030 bool Invalid = false;
1031 const SrcMgr::ExpansionInfo &ExpInfo =
1032 getSLocEntry(DecompLoc.first, &Invalid).getExpansion();
1035 SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();
1037 if (ExpInfo.isMacroArgExpansion()) {
1038 // For macro argument expansions, check if the previous FileID is part of
1039 // the same argument expansion, in which case this Loc is not at the
1040 // beginning of the expansion.
1041 FileID PrevFID = getPreviousFileID(DecompLoc.first);
1042 if (!PrevFID.isInvalid()) {
1043 const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);
1046 if (PrevEntry.isExpansion() &&
1047 PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)
1053 *MacroBegin = ExpLoc;
1057 bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
1058 SourceLocation *MacroEnd) const {
1059 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1061 FileID FID = getFileID(Loc);
1062 SourceLocation NextLoc = Loc.getLocWithOffset(1);
1063 if (isInFileID(NextLoc, FID))
1064 return false; // Does not point at the end of expansion range.
1066 bool Invalid = false;
1067 const SrcMgr::ExpansionInfo &ExpInfo =
1068 getSLocEntry(FID, &Invalid).getExpansion();
1072 if (ExpInfo.isMacroArgExpansion()) {
1073 // For macro argument expansions, check if the next FileID is part of the
1074 // same argument expansion, in which case this Loc is not at the end of the
1076 FileID NextFID = getNextFileID(FID);
1077 if (!NextFID.isInvalid()) {
1078 const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);
1081 if (NextEntry.isExpansion() &&
1082 NextEntry.getExpansion().getExpansionLocStart() ==
1083 ExpInfo.getExpansionLocStart())
1089 *MacroEnd = ExpInfo.getExpansionLocEnd();
1094 //===----------------------------------------------------------------------===//
1095 // Queries about the code at a SourceLocation.
1096 //===----------------------------------------------------------------------===//
1098 /// getCharacterData - Return a pointer to the start of the specified location
1099 /// in the appropriate MemoryBuffer.
1100 const char *SourceManager::getCharacterData(SourceLocation SL,
1101 bool *Invalid) const {
1102 // Note that this is a hot function in the getSpelling() path, which is
1103 // heavily used by -E mode.
1104 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
1106 // Note that calling 'getBuffer()' may lazily page in a source file.
1107 bool CharDataInvalid = false;
1108 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
1109 if (CharDataInvalid || !Entry.isFile()) {
1113 return "<<<<INVALID BUFFER>>>>";
1115 llvm::MemoryBuffer *Buffer = Entry.getFile().getContentCache()->getBuffer(
1116 Diag, *this, SourceLocation(), &CharDataInvalid);
1118 *Invalid = CharDataInvalid;
1119 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
1123 /// getColumnNumber - Return the column # for the specified file position.
1124 /// this is significantly cheaper to compute than the line number.
1125 unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
1126 bool *Invalid) const {
1127 bool MyInvalid = false;
1128 llvm::MemoryBuffer *MemBuf = getBuffer(FID, &MyInvalid);
1130 *Invalid = MyInvalid;
1135 // It is okay to request a position just past the end of the buffer.
1136 if (FilePos > MemBuf->getBufferSize()) {
1142 // See if we just calculated the line number for this FilePos and can use
1143 // that to lookup the start of the line instead of searching for it.
1144 if (LastLineNoFileIDQuery == FID &&
1145 LastLineNoContentCache->SourceLineCache != nullptr &&
1146 LastLineNoResult < LastLineNoContentCache->NumLines) {
1147 unsigned *SourceLineCache = LastLineNoContentCache->SourceLineCache;
1148 unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
1149 unsigned LineEnd = SourceLineCache[LastLineNoResult];
1150 if (FilePos >= LineStart && FilePos < LineEnd)
1151 return FilePos - LineStart + 1;
1154 const char *Buf = MemBuf->getBufferStart();
1155 unsigned LineStart = FilePos;
1156 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
1158 return FilePos-LineStart+1;
1161 // isInvalid - Return the result of calling loc.isInvalid(), and
1162 // if Invalid is not null, set its value to same.
1163 static bool isInvalid(SourceLocation Loc, bool *Invalid) {
1164 bool MyInvalid = Loc.isInvalid();
1166 *Invalid = MyInvalid;
1170 unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
1171 bool *Invalid) const {
1172 if (isInvalid(Loc, Invalid)) return 0;
1173 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1174 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1177 unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
1178 bool *Invalid) const {
1179 if (isInvalid(Loc, Invalid)) return 0;
1180 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1181 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1184 unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
1185 bool *Invalid) const {
1186 if (isInvalid(Loc, Invalid)) return 0;
1187 return getPresumedLoc(Loc).getColumn();
1191 #include <emmintrin.h>
1194 static LLVM_ATTRIBUTE_NOINLINE void
1195 ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
1196 llvm::BumpPtrAllocator &Alloc,
1197 const SourceManager &SM, bool &Invalid);
1198 static void ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
1199 llvm::BumpPtrAllocator &Alloc,
1200 const SourceManager &SM, bool &Invalid) {
1201 // Note that calling 'getBuffer()' may lazily page in the file.
1202 MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(), &Invalid);
1206 // Find the file offsets of all of the *physical* source lines. This does
1207 // not look at trigraphs, escaped newlines, or anything else tricky.
1208 SmallVector<unsigned, 256> LineOffsets;
1210 // Line #1 starts at char 0.
1211 LineOffsets.push_back(0);
1213 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
1214 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
1217 // Skip over the contents of the line.
1218 const unsigned char *NextBuf = (const unsigned char *)Buf;
1221 // Try to skip to the next newline using SSE instructions. This is very
1222 // performance sensitive for programs with lots of diagnostics and in -E
1224 __m128i CRs = _mm_set1_epi8('\r');
1225 __m128i LFs = _mm_set1_epi8('\n');
1227 // First fix up the alignment to 16 bytes.
1228 while (((uintptr_t)NextBuf & 0xF) != 0) {
1229 if (*NextBuf == '\n' || *NextBuf == '\r' || *NextBuf == '\0')
1230 goto FoundSpecialChar;
1234 // Scan 16 byte chunks for '\r' and '\n'. Ignore '\0'.
1235 while (NextBuf+16 <= End) {
1236 const __m128i Chunk = *(const __m128i*)NextBuf;
1237 __m128i Cmp = _mm_or_si128(_mm_cmpeq_epi8(Chunk, CRs),
1238 _mm_cmpeq_epi8(Chunk, LFs));
1239 unsigned Mask = _mm_movemask_epi8(Cmp);
1241 // If we found a newline, adjust the pointer and jump to the handling code.
1243 NextBuf += llvm::countTrailingZeros(Mask);
1244 goto FoundSpecialChar;
1250 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
1256 Offs += NextBuf-Buf;
1259 if (Buf[0] == '\n' || Buf[0] == '\r') {
1260 // If this is \n\r or \r\n, skip both characters.
1261 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
1264 LineOffsets.push_back(Offs);
1266 // Otherwise, this is a null. If end of file, exit.
1267 if (Buf == End) break;
1268 // Otherwise, skip the null.
1273 // Copy the offsets into the FileInfo structure.
1274 FI->NumLines = LineOffsets.size();
1275 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
1276 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
1279 /// getLineNumber - Given a SourceLocation, return the spelling line number
1280 /// for the position indicated. This requires building and caching a table of
1281 /// line offsets for the MemoryBuffer, so this is not cheap: use only when
1282 /// about to emit a diagnostic.
1283 unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1284 bool *Invalid) const {
1285 if (FID.isInvalid()) {
1291 ContentCache *Content;
1292 if (LastLineNoFileIDQuery == FID)
1293 Content = LastLineNoContentCache;
1295 bool MyInvalid = false;
1296 const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1297 if (MyInvalid || !Entry.isFile()) {
1303 Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
1306 // If this is the first use of line information for this buffer, compute the
1307 /// SourceLineCache for it on demand.
1308 if (!Content->SourceLineCache) {
1309 bool MyInvalid = false;
1310 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
1312 *Invalid = MyInvalid;
1318 // Okay, we know we have a line number table. Do a binary search to find the
1319 // line number that this character position lands on.
1320 unsigned *SourceLineCache = Content->SourceLineCache;
1321 unsigned *SourceLineCacheStart = SourceLineCache;
1322 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
1324 unsigned QueriedFilePos = FilePos+1;
1326 // FIXME: I would like to be convinced that this code is worth being as
1327 // complicated as it is, binary search isn't that slow.
1329 // If it is worth being optimized, then in my opinion it could be more
1330 // performant, simpler, and more obviously correct by just "galloping" outward
1331 // from the queried file position. In fact, this could be incorporated into a
1332 // generic algorithm such as lower_bound_with_hint.
1334 // If someone gives me a test case where this matters, and I will do it! - DWD
1336 // If the previous query was to the same file, we know both the file pos from
1337 // that query and the line number returned. This allows us to narrow the
1338 // search space from the entire file to something near the match.
1339 if (LastLineNoFileIDQuery == FID) {
1340 if (QueriedFilePos >= LastLineNoFilePos) {
1341 // FIXME: Potential overflow?
1342 SourceLineCache = SourceLineCache+LastLineNoResult-1;
1344 // The query is likely to be nearby the previous one. Here we check to
1345 // see if it is within 5, 10 or 20 lines. It can be far away in cases
1346 // where big comment blocks and vertical whitespace eat up lines but
1347 // contribute no tokens.
1348 if (SourceLineCache+5 < SourceLineCacheEnd) {
1349 if (SourceLineCache[5] > QueriedFilePos)
1350 SourceLineCacheEnd = SourceLineCache+5;
1351 else if (SourceLineCache+10 < SourceLineCacheEnd) {
1352 if (SourceLineCache[10] > QueriedFilePos)
1353 SourceLineCacheEnd = SourceLineCache+10;
1354 else if (SourceLineCache+20 < SourceLineCacheEnd) {
1355 if (SourceLineCache[20] > QueriedFilePos)
1356 SourceLineCacheEnd = SourceLineCache+20;
1361 if (LastLineNoResult < Content->NumLines)
1362 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
1367 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
1368 unsigned LineNo = Pos-SourceLineCacheStart;
1370 LastLineNoFileIDQuery = FID;
1371 LastLineNoContentCache = Content;
1372 LastLineNoFilePos = QueriedFilePos;
1373 LastLineNoResult = LineNo;
1377 unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1378 bool *Invalid) const {
1379 if (isInvalid(Loc, Invalid)) return 0;
1380 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1381 return getLineNumber(LocInfo.first, LocInfo.second);
1383 unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
1384 bool *Invalid) const {
1385 if (isInvalid(Loc, Invalid)) return 0;
1386 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1387 return getLineNumber(LocInfo.first, LocInfo.second);
1389 unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
1390 bool *Invalid) const {
1391 if (isInvalid(Loc, Invalid)) return 0;
1392 return getPresumedLoc(Loc).getLine();
1395 /// getFileCharacteristic - return the file characteristic of the specified
1396 /// source location, indicating whether this is a normal file, a system
1397 /// header, or an "implicit extern C" system header.
1399 /// This state can be modified with flags on GNU linemarker directives like:
1401 /// which changes all source locations in the current file after that to be
1402 /// considered to be from a system header.
1403 SrcMgr::CharacteristicKind
1404 SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1405 assert(Loc.isValid() && "Can't get file characteristic of invalid loc!");
1406 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1407 bool Invalid = false;
1408 const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
1409 if (Invalid || !SEntry.isFile())
1412 const SrcMgr::FileInfo &FI = SEntry.getFile();
1414 // If there are no #line directives in this file, just return the whole-file
1416 if (!FI.hasLineDirectives())
1417 return FI.getFileCharacteristic();
1419 assert(LineTable && "Can't have linetable entries without a LineTable!");
1420 // See if there is a #line directive before the location.
1421 const LineEntry *Entry =
1422 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
1424 // If this is before the first line marker, use the file characteristic.
1426 return FI.getFileCharacteristic();
1428 return Entry->FileKind;
1431 /// Return the filename or buffer identifier of the buffer the location is in.
1432 /// Note that this name does not respect \#line directives. Use getPresumedLoc
1433 /// for normal clients.
1434 const char *SourceManager::getBufferName(SourceLocation Loc,
1435 bool *Invalid) const {
1436 if (isInvalid(Loc, Invalid)) return "<invalid loc>";
1438 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
1442 /// getPresumedLoc - This method returns the "presumed" location of a
1443 /// SourceLocation specifies. A "presumed location" can be modified by \#line
1444 /// or GNU line marker directives. This provides a view on the data that a
1445 /// user should see in diagnostics, for example.
1447 /// Note that a presumed location is always given as the expansion point of an
1448 /// expansion location, not at the spelling location.
1449 PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc,
1450 bool UseLineDirectives) const {
1451 if (Loc.isInvalid()) return PresumedLoc();
1453 // Presumed locations are always for expansion points.
1454 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1456 bool Invalid = false;
1457 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1458 if (Invalid || !Entry.isFile())
1459 return PresumedLoc();
1461 const SrcMgr::FileInfo &FI = Entry.getFile();
1462 const SrcMgr::ContentCache *C = FI.getContentCache();
1464 // To get the source name, first consult the FileEntry (if one exists)
1465 // before the MemBuffer as this will avoid unnecessarily paging in the
1467 const char *Filename;
1469 Filename = C->OrigEntry->getName();
1471 Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
1473 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1475 return PresumedLoc();
1476 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1478 return PresumedLoc();
1480 SourceLocation IncludeLoc = FI.getIncludeLoc();
1482 // If we have #line directives in this file, update and overwrite the physical
1483 // location info if appropriate.
1484 if (UseLineDirectives && FI.hasLineDirectives()) {
1485 assert(LineTable && "Can't have linetable entries without a LineTable!");
1486 // See if there is a #line directive before this. If so, get it.
1487 if (const LineEntry *Entry =
1488 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
1489 // If the LineEntry indicates a filename, use it.
1490 if (Entry->FilenameID != -1)
1491 Filename = LineTable->getFilename(Entry->FilenameID);
1493 // Use the line number specified by the LineEntry. This line number may
1494 // be multiple lines down from the line entry. Add the difference in
1495 // physical line numbers from the query point and the line marker to the
1497 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1498 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
1500 // Note that column numbers are not molested by line markers.
1502 // Handle virtual #include manipulation.
1503 if (Entry->IncludeOffset) {
1504 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1505 IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
1510 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
1513 /// \brief Returns whether the PresumedLoc for a given SourceLocation is
1514 /// in the main file.
1516 /// This computes the "presumed" location for a SourceLocation, then checks
1517 /// whether it came from a file other than the main file. This is different
1518 /// from isWrittenInMainFile() because it takes line marker directives into
1520 bool SourceManager::isInMainFile(SourceLocation Loc) const {
1521 if (Loc.isInvalid()) return false;
1523 // Presumed locations are always for expansion points.
1524 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1526 bool Invalid = false;
1527 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1528 if (Invalid || !Entry.isFile())
1531 const SrcMgr::FileInfo &FI = Entry.getFile();
1533 // Check if there is a line directive for this location.
1534 if (FI.hasLineDirectives())
1535 if (const LineEntry *Entry =
1536 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
1537 if (Entry->IncludeOffset)
1540 return FI.getIncludeLoc().isInvalid();
1543 /// \brief The size of the SLocEntry that \p FID represents.
1544 unsigned SourceManager::getFileIDSize(FileID FID) const {
1545 bool Invalid = false;
1546 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1551 unsigned NextOffset;
1552 if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
1553 NextOffset = getNextLocalOffset();
1554 else if (ID+1 == -1)
1555 NextOffset = MaxLoadedOffset;
1557 NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
1559 return NextOffset - Entry.getOffset() - 1;
1562 //===----------------------------------------------------------------------===//
1563 // Other miscellaneous methods.
1564 //===----------------------------------------------------------------------===//
1566 /// \brief Retrieve the inode for the given file entry, if possible.
1568 /// This routine involves a system call, and therefore should only be used
1569 /// in non-performance-critical code.
1570 static Optional<llvm::sys::fs::UniqueID>
1571 getActualFileUID(const FileEntry *File) {
1575 llvm::sys::fs::UniqueID ID;
1576 if (llvm::sys::fs::getUniqueID(File->getName(), ID))
1582 /// \brief Get the source location for the given file:line:col triplet.
1584 /// If the source file is included multiple times, the source location will
1585 /// be based upon an arbitrary inclusion.
1586 SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
1588 unsigned Col) const {
1589 assert(SourceFile && "Null source file!");
1590 assert(Line && Col && "Line and column should start from 1!");
1592 FileID FirstFID = translateFile(SourceFile);
1593 return translateLineCol(FirstFID, Line, Col);
1596 /// \brief Get the FileID for the given file.
1598 /// If the source file is included multiple times, the FileID will be the
1599 /// first inclusion.
1600 FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
1601 assert(SourceFile && "Null source file!");
1603 // Find the first file ID that corresponds to the given file.
1606 // First, check the main file ID, since it is common to look for a
1607 // location in the main file.
1608 Optional<llvm::sys::fs::UniqueID> SourceFileUID;
1609 Optional<StringRef> SourceFileName;
1610 if (MainFileID.isValid()) {
1611 bool Invalid = false;
1612 const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1616 if (MainSLoc.isFile()) {
1617 const ContentCache *MainContentCache
1618 = MainSLoc.getFile().getContentCache();
1619 if (!MainContentCache) {
1620 // Can't do anything
1621 } else if (MainContentCache->OrigEntry == SourceFile) {
1622 FirstFID = MainFileID;
1624 // Fall back: check whether we have the same base name and inode
1625 // as the main file.
1626 const FileEntry *MainFile = MainContentCache->OrigEntry;
1627 SourceFileName = llvm::sys::path::filename(SourceFile->getName());
1628 if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) {
1629 SourceFileUID = getActualFileUID(SourceFile);
1630 if (SourceFileUID) {
1631 if (Optional<llvm::sys::fs::UniqueID> MainFileUID =
1632 getActualFileUID(MainFile)) {
1633 if (*SourceFileUID == *MainFileUID) {
1634 FirstFID = MainFileID;
1635 SourceFile = MainFile;
1644 if (FirstFID.isInvalid()) {
1645 // The location we're looking for isn't in the main file; look
1646 // through all of the local source locations.
1647 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1648 bool Invalid = false;
1649 const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid);
1653 if (SLoc.isFile() &&
1654 SLoc.getFile().getContentCache() &&
1655 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1656 FirstFID = FileID::get(I);
1660 // If that still didn't help, try the modules.
1661 if (FirstFID.isInvalid()) {
1662 for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
1663 const SLocEntry &SLoc = getLoadedSLocEntry(I);
1664 if (SLoc.isFile() &&
1665 SLoc.getFile().getContentCache() &&
1666 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1667 FirstFID = FileID::get(-int(I) - 2);
1674 // If we haven't found what we want yet, try again, but this time stat()
1675 // each of the files in case the files have changed since we originally
1677 if (FirstFID.isInvalid() &&
1679 (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) &&
1680 (SourceFileUID || (SourceFileUID = getActualFileUID(SourceFile)))) {
1681 bool Invalid = false;
1682 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1685 const SLocEntry &SLoc = getSLocEntry(IFileID, &Invalid);
1689 if (SLoc.isFile()) {
1690 const ContentCache *FileContentCache
1691 = SLoc.getFile().getContentCache();
1692 const FileEntry *Entry = FileContentCache ? FileContentCache->OrigEntry
1695 *SourceFileName == llvm::sys::path::filename(Entry->getName())) {
1696 if (Optional<llvm::sys::fs::UniqueID> EntryUID =
1697 getActualFileUID(Entry)) {
1698 if (*SourceFileUID == *EntryUID) {
1699 FirstFID = FileID::get(I);
1713 /// \brief Get the source location in \arg FID for the given line:col.
1714 /// Returns null location if \arg FID is not a file SLocEntry.
1715 SourceLocation SourceManager::translateLineCol(FileID FID,
1717 unsigned Col) const {
1718 // Lines are used as a one-based index into a zero-based array. This assert
1719 // checks for possible buffer underruns.
1720 assert(Line && Col && "Line and column should start from 1!");
1722 if (FID.isInvalid())
1723 return SourceLocation();
1725 bool Invalid = false;
1726 const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1728 return SourceLocation();
1730 if (!Entry.isFile())
1731 return SourceLocation();
1733 SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
1735 if (Line == 1 && Col == 1)
1738 ContentCache *Content
1739 = const_cast<ContentCache *>(Entry.getFile().getContentCache());
1741 return SourceLocation();
1743 // If this is the first use of line information for this buffer, compute the
1744 // SourceLineCache for it on demand.
1745 if (!Content->SourceLineCache) {
1746 bool MyInvalid = false;
1747 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
1749 return SourceLocation();
1752 if (Line > Content->NumLines) {
1753 unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
1756 return FileLoc.getLocWithOffset(Size);
1759 llvm::MemoryBuffer *Buffer = Content->getBuffer(Diag, *this);
1760 unsigned FilePos = Content->SourceLineCache[Line - 1];
1761 const char *Buf = Buffer->getBufferStart() + FilePos;
1762 unsigned BufLength = Buffer->getBufferSize() - FilePos;
1764 return FileLoc.getLocWithOffset(FilePos);
1768 // Check that the given column is valid.
1769 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1771 return FileLoc.getLocWithOffset(FilePos + i);
1774 /// \brief Compute a map of macro argument chunks to their expanded source
1775 /// location. Chunks that are not part of a macro argument will map to an
1776 /// invalid source location. e.g. if a file contains one macro argument at
1777 /// offset 100 with length 10, this is how the map will be formed:
1778 /// 0 -> SourceLocation()
1779 /// 100 -> Expanded macro arg location
1780 /// 110 -> SourceLocation()
1781 void SourceManager::computeMacroArgsCache(MacroArgsMap *&CachePtr,
1783 assert(FID.isValid());
1786 CachePtr = new MacroArgsMap();
1787 MacroArgsMap &MacroArgsCache = *CachePtr;
1788 // Initially no macro argument chunk is present.
1789 MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
1794 // Stop if there are no more FileIDs to check.
1796 if (unsigned(ID) >= local_sloc_entry_size())
1798 } else if (ID == -1) {
1802 bool Invalid = false;
1803 const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);
1806 if (Entry.isFile()) {
1807 SourceLocation IncludeLoc = Entry.getFile().getIncludeLoc();
1808 if (IncludeLoc.isInvalid())
1810 if (!isInFileID(IncludeLoc, FID))
1811 return; // No more files/macros that may be "contained" in this file.
1813 // Skip the files/macros of the #include'd file, we only care about macros
1814 // that lexed macro arguments from our file.
1815 if (Entry.getFile().NumCreatedFIDs)
1816 ID += Entry.getFile().NumCreatedFIDs - 1/*because of next ++ID*/;
1820 const ExpansionInfo &ExpInfo = Entry.getExpansion();
1822 if (ExpInfo.getExpansionLocStart().isFileID()) {
1823 if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
1824 return; // No more files/macros that may be "contained" in this file.
1827 if (!ExpInfo.isMacroArgExpansion())
1830 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1831 ExpInfo.getSpellingLoc(),
1832 SourceLocation::getMacroLoc(Entry.getOffset()),
1833 getFileIDSize(FileID::get(ID)));
1837 void SourceManager::associateFileChunkWithMacroArgExp(
1838 MacroArgsMap &MacroArgsCache,
1840 SourceLocation SpellLoc,
1841 SourceLocation ExpansionLoc,
1842 unsigned ExpansionLength) const {
1843 if (!SpellLoc.isFileID()) {
1844 unsigned SpellBeginOffs = SpellLoc.getOffset();
1845 unsigned SpellEndOffs = SpellBeginOffs + ExpansionLength;
1847 // The spelling range for this macro argument expansion can span multiple
1848 // consecutive FileID entries. Go through each entry contained in the
1849 // spelling range and if one is itself a macro argument expansion, recurse
1850 // and associate the file chunk that it represents.
1852 FileID SpellFID; // Current FileID in the spelling range.
1853 unsigned SpellRelativeOffs;
1854 std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);
1856 const SLocEntry &Entry = getSLocEntry(SpellFID);
1857 unsigned SpellFIDBeginOffs = Entry.getOffset();
1858 unsigned SpellFIDSize = getFileIDSize(SpellFID);
1859 unsigned SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;
1860 const ExpansionInfo &Info = Entry.getExpansion();
1861 if (Info.isMacroArgExpansion()) {
1862 unsigned CurrSpellLength;
1863 if (SpellFIDEndOffs < SpellEndOffs)
1864 CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
1866 CurrSpellLength = ExpansionLength;
1867 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1868 Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),
1869 ExpansionLoc, CurrSpellLength);
1872 if (SpellFIDEndOffs >= SpellEndOffs)
1873 return; // we covered all FileID entries in the spelling range.
1875 // Move to the next FileID entry in the spelling range.
1876 unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
1877 ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);
1878 ExpansionLength -= advance;
1880 SpellRelativeOffs = 0;
1885 assert(SpellLoc.isFileID());
1888 if (!isInFileID(SpellLoc, FID, &BeginOffs))
1891 unsigned EndOffs = BeginOffs + ExpansionLength;
1893 // Add a new chunk for this macro argument. A previous macro argument chunk
1894 // may have been lexed again, so e.g. if the map is
1895 // 0 -> SourceLocation()
1896 // 100 -> Expanded loc #1
1897 // 110 -> SourceLocation()
1898 // and we found a new macro FileID that lexed from offet 105 with length 3,
1899 // the new map will be:
1900 // 0 -> SourceLocation()
1901 // 100 -> Expanded loc #1
1902 // 105 -> Expanded loc #2
1903 // 108 -> Expanded loc #1
1904 // 110 -> SourceLocation()
1906 // Since re-lexed macro chunks will always be the same size or less of
1907 // previous chunks, we only need to find where the ending of the new macro
1908 // chunk is mapped to and update the map with new begin/end mappings.
1910 MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
1912 SourceLocation EndOffsMappedLoc = I->second;
1913 MacroArgsCache[BeginOffs] = ExpansionLoc;
1914 MacroArgsCache[EndOffs] = EndOffsMappedLoc;
1917 /// \brief If \arg Loc points inside a function macro argument, the returned
1918 /// location will be the macro location in which the argument was expanded.
1919 /// If a macro argument is used multiple times, the expanded location will
1920 /// be at the first expansion of the argument.
1924 /// Passing a file location pointing at 'foo', will yield a macro location
1925 /// where 'foo' was expanded into.
1927 SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
1928 if (Loc.isInvalid() || !Loc.isFileID())
1933 std::tie(FID, Offset) = getDecomposedLoc(Loc);
1934 if (FID.isInvalid())
1937 MacroArgsMap *&MacroArgsCache = MacroArgsCacheMap[FID];
1938 if (!MacroArgsCache)
1939 computeMacroArgsCache(MacroArgsCache, FID);
1941 assert(!MacroArgsCache->empty());
1942 MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
1945 unsigned MacroArgBeginOffs = I->first;
1946 SourceLocation MacroArgExpandedLoc = I->second;
1947 if (MacroArgExpandedLoc.isValid())
1948 return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
1953 std::pair<FileID, unsigned>
1954 SourceManager::getDecomposedIncludedLoc(FileID FID) const {
1955 if (FID.isInvalid())
1956 return std::make_pair(FileID(), 0);
1958 // Uses IncludedLocMap to retrieve/cache the decomposed loc.
1960 typedef std::pair<FileID, unsigned> DecompTy;
1961 typedef llvm::DenseMap<FileID, DecompTy> MapTy;
1962 std::pair<MapTy::iterator, bool>
1963 InsertOp = IncludedLocMap.insert(std::make_pair(FID, DecompTy()));
1964 DecompTy &DecompLoc = InsertOp.first->second;
1965 if (!InsertOp.second)
1966 return DecompLoc; // already in map.
1968 SourceLocation UpperLoc;
1969 bool Invalid = false;
1970 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1972 if (Entry.isExpansion())
1973 UpperLoc = Entry.getExpansion().getExpansionLocStart();
1975 UpperLoc = Entry.getFile().getIncludeLoc();
1978 if (UpperLoc.isValid())
1979 DecompLoc = getDecomposedLoc(UpperLoc);
1984 /// Given a decomposed source location, move it up the include/expansion stack
1985 /// to the parent source location. If this is possible, return the decomposed
1986 /// version of the parent in Loc and return false. If Loc is the top-level
1987 /// entry, return true and don't modify it.
1988 static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1989 const SourceManager &SM) {
1990 std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
1991 if (UpperLoc.first.isInvalid())
1992 return true; // We reached the top.
1998 /// Return the cache entry for comparing the given file IDs
1999 /// for isBeforeInTranslationUnit.
2000 InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
2001 FileID RFID) const {
2002 // This is a magic number for limiting the cache size. It was experimentally
2003 // derived from a small Objective-C project (where the cache filled
2004 // out to ~250 items). We can make it larger if necessary.
2005 enum { MagicCacheSize = 300 };
2006 IsBeforeInTUCacheKey Key(LFID, RFID);
2008 // If the cache size isn't too large, do a lookup and if necessary default
2009 // construct an entry. We can then return it to the caller for direct
2010 // use. When they update the value, the cache will get automatically
2012 if (IBTUCache.size() < MagicCacheSize)
2013 return IBTUCache[Key];
2015 // Otherwise, do a lookup that will not construct a new value.
2016 InBeforeInTUCache::iterator I = IBTUCache.find(Key);
2017 if (I != IBTUCache.end())
2020 // Fall back to the overflow value.
2021 return IBTUCacheOverflow;
2024 /// \brief Determines the order of 2 source locations in the translation unit.
2026 /// \returns true if LHS source location comes before RHS, false otherwise.
2027 bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
2028 SourceLocation RHS) const {
2029 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
2033 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
2034 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
2036 // getDecomposedLoc may have failed to return a valid FileID because, e.g. it
2037 // is a serialized one referring to a file that was removed after we loaded
2039 if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
2040 return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
2042 // If the source locations are in the same file, just compare offsets.
2043 if (LOffs.first == ROffs.first)
2044 return LOffs.second < ROffs.second;
2046 // If we are comparing a source location with multiple locations in the same
2047 // file, we get a big win by caching the result.
2048 InBeforeInTUCacheEntry &IsBeforeInTUCache =
2049 getInBeforeInTUCache(LOffs.first, ROffs.first);
2051 // If we are comparing a source location with multiple locations in the same
2052 // file, we get a big win by caching the result.
2053 if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
2054 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
2056 // Okay, we missed in the cache, start updating the cache for this query.
2057 IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
2058 /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID);
2060 // We need to find the common ancestor. The only way of doing this is to
2061 // build the complete include chain for one and then walking up the chain
2062 // of the other looking for a match.
2063 // We use a map from FileID to Offset to store the chain. Easier than writing
2064 // a custom set hash info that only depends on the first part of a pair.
2065 typedef llvm::SmallDenseMap<FileID, unsigned, 16> LocSet;
2068 LChain.insert(LOffs);
2069 // We catch the case where LOffs is in a file included by ROffs and
2070 // quit early. The other way round unfortunately remains suboptimal.
2071 } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
2073 while((I = LChain.find(ROffs.first)) == LChain.end()) {
2074 if (MoveUpIncludeHierarchy(ROffs, *this))
2075 break; // Met at topmost file.
2077 if (I != LChain.end())
2080 // If we exited because we found a nearest common ancestor, compare the
2081 // locations within the common file and cache them.
2082 if (LOffs.first == ROffs.first) {
2083 IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
2084 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
2087 // If we arrived here, the location is either in a built-ins buffer or
2088 // associated with global inline asm. PR5662 and PR22576 are examples.
2090 // Clear the lookup cache, it depends on a common location.
2091 IsBeforeInTUCache.clear();
2092 llvm::MemoryBuffer *LBuf = getBuffer(LOffs.first);
2093 llvm::MemoryBuffer *RBuf = getBuffer(ROffs.first);
2094 bool LIsBuiltins = strcmp("<built-in>", LBuf->getBufferIdentifier()) == 0;
2095 bool RIsBuiltins = strcmp("<built-in>", RBuf->getBufferIdentifier()) == 0;
2096 // Sort built-in before non-built-in.
2097 if (LIsBuiltins || RIsBuiltins) {
2098 if (LIsBuiltins != RIsBuiltins)
2100 // Both are in built-in buffers, but from different files. We just claim that
2101 // lower IDs come first.
2102 return LOffs.first < ROffs.first;
2104 bool LIsAsm = strcmp("<inline asm>", LBuf->getBufferIdentifier()) == 0;
2105 bool RIsAsm = strcmp("<inline asm>", RBuf->getBufferIdentifier()) == 0;
2106 // Sort assembler after built-ins, but before the rest.
2107 if (LIsAsm || RIsAsm) {
2108 if (LIsAsm != RIsAsm)
2110 assert(LOffs.first == ROffs.first);
2113 llvm_unreachable("Unsortable locations found");
2116 void SourceManager::PrintStats() const {
2117 llvm::errs() << "\n*** Source Manager Stats:\n";
2118 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
2119 << " mem buffers mapped.\n";
2120 llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
2121 << llvm::capacity_in_bytes(LocalSLocEntryTable)
2122 << " bytes of capacity), "
2123 << NextLocalOffset << "B of Sloc address space used.\n";
2124 llvm::errs() << LoadedSLocEntryTable.size()
2125 << " loaded SLocEntries allocated, "
2126 << MaxLoadedOffset - CurrentLoadedOffset
2127 << "B of Sloc address space used.\n";
2129 unsigned NumLineNumsComputed = 0;
2130 unsigned NumFileBytesMapped = 0;
2131 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
2132 NumLineNumsComputed += I->second->SourceLineCache != nullptr;
2133 NumFileBytesMapped += I->second->getSizeBytesMapped();
2135 unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
2137 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
2138 << NumLineNumsComputed << " files with line #'s computed, "
2139 << NumMacroArgsComputed << " files with macro args computed.\n";
2140 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
2141 << NumBinaryProbes << " binary.\n";
2144 LLVM_DUMP_METHOD void SourceManager::dump() const {
2145 llvm::raw_ostream &out = llvm::errs();
2147 auto DumpSLocEntry = [&](int ID, const SrcMgr::SLocEntry &Entry,
2148 llvm::Optional<unsigned> NextStart) {
2149 out << "SLocEntry <FileID " << ID << "> " << (Entry.isFile() ? "file" : "expansion")
2150 << " <SourceLocation " << Entry.getOffset() << ":";
2152 out << *NextStart << ">\n";
2155 if (Entry.isFile()) {
2156 auto &FI = Entry.getFile();
2157 if (FI.NumCreatedFIDs)
2158 out << " covers <FileID " << ID << ":" << int(ID + FI.NumCreatedFIDs)
2160 if (FI.getIncludeLoc().isValid())
2161 out << " included from " << FI.getIncludeLoc().getOffset() << "\n";
2162 if (auto *CC = FI.getContentCache()) {
2163 out << " for " << (CC->OrigEntry ? CC->OrigEntry->getName() : "<none>")
2165 if (CC->BufferOverridden)
2166 out << " contents overridden\n";
2167 if (CC->ContentsEntry != CC->OrigEntry) {
2168 out << " contents from "
2169 << (CC->ContentsEntry ? CC->ContentsEntry->getName() : "<none>")
2174 auto &EI = Entry.getExpansion();
2175 out << " spelling from " << EI.getSpellingLoc().getOffset() << "\n";
2176 out << " macro " << (EI.isMacroArgExpansion() ? "arg" : "body")
2177 << " range <" << EI.getExpansionLocStart().getOffset() << ":"
2178 << EI.getExpansionLocEnd().getOffset() << ">\n";
2182 // Dump local SLocEntries.
2183 for (unsigned ID = 0, NumIDs = LocalSLocEntryTable.size(); ID != NumIDs; ++ID) {
2184 DumpSLocEntry(ID, LocalSLocEntryTable[ID],
2185 ID == NumIDs - 1 ? NextLocalOffset
2186 : LocalSLocEntryTable[ID + 1].getOffset());
2188 // Dump loaded SLocEntries.
2189 llvm::Optional<unsigned> NextStart;
2190 for (unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
2191 int ID = -(int)Index - 2;
2192 if (SLocEntryLoaded[Index]) {
2193 DumpSLocEntry(ID, LoadedSLocEntryTable[Index], NextStart);
2194 NextStart = LoadedSLocEntryTable[Index].getOffset();
2201 ExternalSLocEntrySource::~ExternalSLocEntrySource() { }
2203 /// Return the amount of memory used by memory buffers, breaking down
2204 /// by heap-backed versus mmap'ed memory.
2205 SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
2206 size_t malloc_bytes = 0;
2207 size_t mmap_bytes = 0;
2209 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
2210 if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
2211 switch (MemBufferInfos[i]->getMemoryBufferKind()) {
2212 case llvm::MemoryBuffer::MemoryBuffer_MMap:
2213 mmap_bytes += sized_mapped;
2215 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
2216 malloc_bytes += sized_mapped;
2220 return MemoryBufferSizes(malloc_bytes, mmap_bytes);
2223 size_t SourceManager::getDataStructureSizes() const {
2224 size_t size = llvm::capacity_in_bytes(MemBufferInfos)
2225 + llvm::capacity_in_bytes(LocalSLocEntryTable)
2226 + llvm::capacity_in_bytes(LoadedSLocEntryTable)
2227 + llvm::capacity_in_bytes(SLocEntryLoaded)
2228 + llvm::capacity_in_bytes(FileInfos);
2230 if (OverriddenFilesInfo)
2231 size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);