• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===- SourceManager.cpp - Track and cache source files -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements the SourceManager interface.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/Basic/SourceManager.h"
14 #include "clang/Basic/Diagnostic.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/LLVM.h"
17 #include "clang/Basic/SourceLocation.h"
18 #include "clang/Basic/SourceManagerInternals.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/StringRef.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/Support/Allocator.h"
27 #include "llvm/Support/Capacity.h"
28 #include "llvm/Support/Compiler.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/FileSystem.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/Path.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include <algorithm>
36 #include <cassert>
37 #include <cstddef>
38 #include <cstdint>
39 #include <memory>
40 #include <tuple>
41 #include <utility>
42 #include <vector>
43 
44 using namespace clang;
45 using namespace SrcMgr;
46 using llvm::MemoryBuffer;
47 
48 //===----------------------------------------------------------------------===//
49 // SourceManager Helper Classes
50 //===----------------------------------------------------------------------===//
51 
52 /// getSizeBytesMapped - Returns the number of bytes actually mapped for this
53 /// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
getSizeBytesMapped() const54 unsigned ContentCache::getSizeBytesMapped() const {
55   return Buffer ? Buffer->getBufferSize() : 0;
56 }
57 
58 /// Returns the kind of memory used to back the memory buffer for
59 /// this content cache.  This is used for performance analysis.
getMemoryBufferKind() const60 llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
61   assert(Buffer);
62 
63   // Should be unreachable, but keep for sanity.
64   if (!Buffer)
65     return llvm::MemoryBuffer::MemoryBuffer_Malloc;
66 
67   return Buffer->getBufferKind();
68 }
69 
70 /// getSize - Returns the size of the content encapsulated by this ContentCache.
71 ///  This can be the size of the source file or the size of an arbitrary
72 ///  scratch buffer.  If the ContentCache encapsulates a source file, that
73 ///  file is not lazily brought in from disk to satisfy this query.
getSize() const74 unsigned ContentCache::getSize() const {
75   return Buffer ? (unsigned)Buffer->getBufferSize()
76                 : (unsigned)ContentsEntry->getSize();
77 }
78 
getInvalidBOM(StringRef BufStr)79 const char *ContentCache::getInvalidBOM(StringRef BufStr) {
80   // If the buffer is valid, check to see if it has a UTF Byte Order Mark
81   // (BOM).  We only support UTF-8 with and without a BOM right now.  See
82   // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
83   const char *InvalidBOM =
84       llvm::StringSwitch<const char *>(BufStr)
85           .StartsWith(llvm::StringLiteral::withInnerNUL("\x00\x00\xFE\xFF"),
86                       "UTF-32 (BE)")
87           .StartsWith(llvm::StringLiteral::withInnerNUL("\xFF\xFE\x00\x00"),
88                       "UTF-32 (LE)")
89           .StartsWith("\xFE\xFF", "UTF-16 (BE)")
90           .StartsWith("\xFF\xFE", "UTF-16 (LE)")
91           .StartsWith("\x2B\x2F\x76", "UTF-7")
92           .StartsWith("\xF7\x64\x4C", "UTF-1")
93           .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
94           .StartsWith("\x0E\xFE\xFF", "SCSU")
95           .StartsWith("\xFB\xEE\x28", "BOCU-1")
96           .StartsWith("\x84\x31\x95\x33", "GB-18030")
97           .Default(nullptr);
98 
99   return InvalidBOM;
100 }
101 
102 llvm::Optional<llvm::MemoryBufferRef>
getBufferOrNone(DiagnosticsEngine & Diag,FileManager & FM,SourceLocation Loc) const103 ContentCache::getBufferOrNone(DiagnosticsEngine &Diag, FileManager &FM,
104                               SourceLocation Loc) const {
105   // Lazily create the Buffer for ContentCaches that wrap files.  If we already
106   // computed it, just return what we have.
107   if (IsBufferInvalid)
108     return None;
109   if (Buffer)
110     return Buffer->getMemBufferRef();
111   if (!ContentsEntry)
112     return None;
113 
114   // Start with the assumption that the buffer is invalid to simplify early
115   // return paths.
116   IsBufferInvalid = true;
117 
118   // Check that the file's size fits in an 'unsigned' (with room for a
119   // past-the-end value). This is deeply regrettable, but various parts of
120   // Clang (including elsewhere in this file!) use 'unsigned' to represent file
121   // offsets, line numbers, string literal lengths, and so on, and fail
122   // miserably on large source files.
123   if ((uint64_t)ContentsEntry->getSize() >=
124       std::numeric_limits<unsigned>::max()) {
125     if (Diag.isDiagnosticInFlight())
126       Diag.SetDelayedDiagnostic(diag::err_file_too_large,
127                                 ContentsEntry->getName());
128     else
129       Diag.Report(Loc, diag::err_file_too_large)
130         << ContentsEntry->getName();
131 
132     return None;
133   }
134 
135   auto BufferOrError = FM.getBufferForFile(ContentsEntry, IsFileVolatile);
136 
137   // If we were unable to open the file, then we are in an inconsistent
138   // situation where the content cache referenced a file which no longer
139   // exists. Most likely, we were using a stat cache with an invalid entry but
140   // the file could also have been removed during processing. Since we can't
141   // really deal with this situation, just create an empty buffer.
142   if (!BufferOrError) {
143     if (Diag.isDiagnosticInFlight())
144       Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
145                                 ContentsEntry->getName(),
146                                 BufferOrError.getError().message());
147     else
148       Diag.Report(Loc, diag::err_cannot_open_file)
149           << ContentsEntry->getName() << BufferOrError.getError().message();
150 
151     return None;
152   }
153 
154   Buffer = std::move(*BufferOrError);
155 
156   // Check that the file's size is the same as in the file entry (which may
157   // have come from a stat cache).
158   if (Buffer->getBufferSize() != (size_t)ContentsEntry->getSize()) {
159     if (Diag.isDiagnosticInFlight())
160       Diag.SetDelayedDiagnostic(diag::err_file_modified,
161                                 ContentsEntry->getName());
162     else
163       Diag.Report(Loc, diag::err_file_modified)
164         << ContentsEntry->getName();
165 
166     return None;
167   }
168 
169   // If the buffer is valid, check to see if it has a UTF Byte Order Mark
170   // (BOM).  We only support UTF-8 with and without a BOM right now.  See
171   // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
172   StringRef BufStr = Buffer->getBuffer();
173   const char *InvalidBOM = getInvalidBOM(BufStr);
174 
175   if (InvalidBOM) {
176     Diag.Report(Loc, diag::err_unsupported_bom)
177       << InvalidBOM << ContentsEntry->getName();
178     return None;
179   }
180 
181   // Buffer has been validated.
182   IsBufferInvalid = false;
183   return Buffer->getMemBufferRef();
184 }
185 
getLineTableFilenameID(StringRef Name)186 unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
187   auto IterBool = FilenameIDs.try_emplace(Name, FilenamesByID.size());
188   if (IterBool.second)
189     FilenamesByID.push_back(&*IterBool.first);
190   return IterBool.first->second;
191 }
192 
193 /// Add a line note to the line table that indicates that there is a \#line or
194 /// GNU line marker at the specified FID/Offset location which changes the
195 /// presumed location to LineNo/FilenameID. If EntryExit is 0, then this doesn't
196 /// change the presumed \#include stack.  If it is 1, this is a file entry, if
197 /// it is 2 then this is a file exit. FileKind specifies whether this is a
198 /// system header or extern C system header.
AddLineNote(FileID FID,unsigned Offset,unsigned LineNo,int FilenameID,unsigned EntryExit,SrcMgr::CharacteristicKind FileKind)199 void LineTableInfo::AddLineNote(FileID FID, unsigned Offset, unsigned LineNo,
200                                 int FilenameID, unsigned EntryExit,
201                                 SrcMgr::CharacteristicKind FileKind) {
202   std::vector<LineEntry> &Entries = LineEntries[FID];
203 
204   // An unspecified FilenameID means use the last filename if available, or the
205   // main source file otherwise.
206   if (FilenameID == -1 && !Entries.empty())
207     FilenameID = Entries.back().FilenameID;
208 
209   assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
210          "Adding line entries out of order!");
211 
212   unsigned IncludeOffset = 0;
213   if (EntryExit == 0) {  // No #include stack change.
214     IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
215   } else if (EntryExit == 1) {
216     IncludeOffset = Offset-1;
217   } else if (EntryExit == 2) {
218     assert(!Entries.empty() && Entries.back().IncludeOffset &&
219        "PPDirectives should have caught case when popping empty include stack");
220 
221     // Get the include loc of the last entries' include loc as our include loc.
222     IncludeOffset = 0;
223     if (const LineEntry *PrevEntry =
224           FindNearestLineEntry(FID, Entries.back().IncludeOffset))
225       IncludeOffset = PrevEntry->IncludeOffset;
226   }
227 
228   Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
229                                    IncludeOffset));
230 }
231 
232 /// FindNearestLineEntry - Find the line entry nearest to FID that is before
233 /// it.  If there is no line entry before Offset in FID, return null.
FindNearestLineEntry(FileID FID,unsigned Offset)234 const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID,
235                                                      unsigned Offset) {
236   const std::vector<LineEntry> &Entries = LineEntries[FID];
237   assert(!Entries.empty() && "No #line entries for this FID after all!");
238 
239   // It is very common for the query to be after the last #line, check this
240   // first.
241   if (Entries.back().FileOffset <= Offset)
242     return &Entries.back();
243 
244   // Do a binary search to find the maximal element that is still before Offset.
245   std::vector<LineEntry>::const_iterator I = llvm::upper_bound(Entries, Offset);
246   if (I == Entries.begin())
247     return nullptr;
248   return &*--I;
249 }
250 
251 /// Add a new line entry that has already been encoded into
252 /// the internal representation of the line table.
AddEntry(FileID FID,const std::vector<LineEntry> & Entries)253 void LineTableInfo::AddEntry(FileID FID,
254                              const std::vector<LineEntry> &Entries) {
255   LineEntries[FID] = Entries;
256 }
257 
258 /// getLineTableFilenameID - Return the uniqued ID for the specified filename.
getLineTableFilenameID(StringRef Name)259 unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
260   return getLineTable().getLineTableFilenameID(Name);
261 }
262 
263 /// AddLineNote - Add a line note to the line table for the FileID and offset
264 /// specified by Loc.  If FilenameID is -1, it is considered to be
265 /// unspecified.
AddLineNote(SourceLocation Loc,unsigned LineNo,int FilenameID,bool IsFileEntry,bool IsFileExit,SrcMgr::CharacteristicKind FileKind)266 void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
267                                 int FilenameID, bool IsFileEntry,
268                                 bool IsFileExit,
269                                 SrcMgr::CharacteristicKind FileKind) {
270   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
271 
272   bool Invalid = false;
273   const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
274   if (!Entry.isFile() || Invalid)
275     return;
276 
277   const SrcMgr::FileInfo &FileInfo = Entry.getFile();
278 
279   // Remember that this file has #line directives now if it doesn't already.
280   const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
281 
282   (void) getLineTable();
283 
284   unsigned EntryExit = 0;
285   if (IsFileEntry)
286     EntryExit = 1;
287   else if (IsFileExit)
288     EntryExit = 2;
289 
290   LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,
291                          EntryExit, FileKind);
292 }
293 
getLineTable()294 LineTableInfo &SourceManager::getLineTable() {
295   if (!LineTable)
296     LineTable.reset(new LineTableInfo());
297   return *LineTable;
298 }
299 
300 //===----------------------------------------------------------------------===//
301 // Private 'Create' methods.
302 //===----------------------------------------------------------------------===//
303 
SourceManager(DiagnosticsEngine & Diag,FileManager & FileMgr,bool UserFilesAreVolatile)304 SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
305                              bool UserFilesAreVolatile)
306   : Diag(Diag), FileMgr(FileMgr), UserFilesAreVolatile(UserFilesAreVolatile) {
307   clearIDTables();
308   Diag.setSourceManager(this);
309 }
310 
~SourceManager()311 SourceManager::~SourceManager() {
312   // Delete FileEntry objects corresponding to content caches.  Since the actual
313   // content cache objects are bump pointer allocated, we just have to run the
314   // dtors, but we call the deallocate method for completeness.
315   for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
316     if (MemBufferInfos[i]) {
317       MemBufferInfos[i]->~ContentCache();
318       ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
319     }
320   }
321   for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
322        I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
323     if (I->second) {
324       I->second->~ContentCache();
325       ContentCacheAlloc.Deallocate(I->second);
326     }
327   }
328 }
329 
clearIDTables()330 void SourceManager::clearIDTables() {
331   MainFileID = FileID();
332   LocalSLocEntryTable.clear();
333   LoadedSLocEntryTable.clear();
334   SLocEntryLoaded.clear();
335   LastLineNoFileIDQuery = FileID();
336   LastLineNoContentCache = nullptr;
337   LastFileIDLookup = FileID();
338 
339   if (LineTable)
340     LineTable->clear();
341 
342   // Use up FileID #0 as an invalid expansion.
343   NextLocalOffset = 0;
344   CurrentLoadedOffset = MaxLoadedOffset;
345   createExpansionLoc(SourceLocation(), SourceLocation(), SourceLocation(), 1);
346 }
347 
isMainFile(const FileEntry & SourceFile)348 bool SourceManager::isMainFile(const FileEntry &SourceFile) {
349   assert(MainFileID.isValid() && "expected initialized SourceManager");
350   if (auto *FE = getFileEntryForID(MainFileID))
351     return FE->getUID() == SourceFile.getUID();
352   return false;
353 }
354 
initializeForReplay(const SourceManager & Old)355 void SourceManager::initializeForReplay(const SourceManager &Old) {
356   assert(MainFileID.isInvalid() && "expected uninitialized SourceManager");
357 
358   auto CloneContentCache = [&](const ContentCache *Cache) -> ContentCache * {
359     auto *Clone = new (ContentCacheAlloc.Allocate<ContentCache>()) ContentCache;
360     Clone->OrigEntry = Cache->OrigEntry;
361     Clone->ContentsEntry = Cache->ContentsEntry;
362     Clone->BufferOverridden = Cache->BufferOverridden;
363     Clone->IsFileVolatile = Cache->IsFileVolatile;
364     Clone->IsTransient = Cache->IsTransient;
365     Clone->setUnownedBuffer(Cache->getBufferIfLoaded());
366     return Clone;
367   };
368 
369   // Ensure all SLocEntries are loaded from the external source.
370   for (unsigned I = 0, N = Old.LoadedSLocEntryTable.size(); I != N; ++I)
371     if (!Old.SLocEntryLoaded[I])
372       Old.loadSLocEntry(I, nullptr);
373 
374   // Inherit any content cache data from the old source manager.
375   for (auto &FileInfo : Old.FileInfos) {
376     SrcMgr::ContentCache *&Slot = FileInfos[FileInfo.first];
377     if (Slot)
378       continue;
379     Slot = CloneContentCache(FileInfo.second);
380   }
381 }
382 
getOrCreateContentCache(const FileEntry * FileEnt,bool isSystemFile)383 ContentCache &SourceManager::getOrCreateContentCache(const FileEntry *FileEnt,
384                                                      bool isSystemFile) {
385   assert(FileEnt && "Didn't specify a file entry to use?");
386 
387   // Do we already have information about this file?
388   ContentCache *&Entry = FileInfos[FileEnt];
389   if (Entry)
390     return *Entry;
391 
392   // Nope, create a new Cache entry.
393   Entry = ContentCacheAlloc.Allocate<ContentCache>();
394 
395   if (OverriddenFilesInfo) {
396     // If the file contents are overridden with contents from another file,
397     // pass that file to ContentCache.
398     llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
399         overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
400     if (overI == OverriddenFilesInfo->OverriddenFiles.end())
401       new (Entry) ContentCache(FileEnt);
402     else
403       new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
404                                                               : overI->second,
405                                overI->second);
406   } else {
407     new (Entry) ContentCache(FileEnt);
408   }
409 
410   Entry->IsFileVolatile = UserFilesAreVolatile && !isSystemFile;
411   Entry->IsTransient = FilesAreTransient;
412 
413   return *Entry;
414 }
415 
416 /// Create a new ContentCache for the specified memory buffer.
417 /// This does no caching.
createMemBufferContentCache(std::unique_ptr<llvm::MemoryBuffer> Buffer)418 ContentCache &SourceManager::createMemBufferContentCache(
419     std::unique_ptr<llvm::MemoryBuffer> Buffer) {
420   // Add a new ContentCache to the MemBufferInfos list and return it.
421   ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
422   new (Entry) ContentCache();
423   MemBufferInfos.push_back(Entry);
424   Entry->setBuffer(std::move(Buffer));
425   return *Entry;
426 }
427 
loadSLocEntry(unsigned Index,bool * Invalid) const428 const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
429                                                       bool *Invalid) const {
430   assert(!SLocEntryLoaded[Index]);
431   if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
432     if (Invalid)
433       *Invalid = true;
434     // If the file of the SLocEntry changed we could still have loaded it.
435     if (!SLocEntryLoaded[Index]) {
436       // Try to recover; create a SLocEntry so the rest of clang can handle it.
437       if (!FakeSLocEntryForRecovery)
438         FakeSLocEntryForRecovery = std::make_unique<SLocEntry>(SLocEntry::get(
439             0, FileInfo::get(SourceLocation(), getFakeContentCacheForRecovery(),
440                              SrcMgr::C_User, "")));
441       return *FakeSLocEntryForRecovery;
442     }
443   }
444 
445   return LoadedSLocEntryTable[Index];
446 }
447 
448 std::pair<int, unsigned>
AllocateLoadedSLocEntries(unsigned NumSLocEntries,unsigned TotalSize)449 SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
450                                          unsigned TotalSize) {
451   assert(ExternalSLocEntries && "Don't have an external sloc source");
452   // Make sure we're not about to run out of source locations.
453   if (CurrentLoadedOffset - TotalSize < NextLocalOffset)
454     return std::make_pair(0, 0);
455   LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
456   SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
457   CurrentLoadedOffset -= TotalSize;
458   int ID = LoadedSLocEntryTable.size();
459   return std::make_pair(-ID - 1, CurrentLoadedOffset);
460 }
461 
462 /// As part of recovering from missing or changed content, produce a
463 /// fake, non-empty buffer.
getFakeBufferForRecovery() const464 llvm::MemoryBufferRef SourceManager::getFakeBufferForRecovery() const {
465   if (!FakeBufferForRecovery)
466     FakeBufferForRecovery =
467         llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
468 
469   return *FakeBufferForRecovery;
470 }
471 
472 /// As part of recovering from missing or changed content, produce a
473 /// fake content cache.
getFakeContentCacheForRecovery() const474 SrcMgr::ContentCache &SourceManager::getFakeContentCacheForRecovery() const {
475   if (!FakeContentCacheForRecovery) {
476     FakeContentCacheForRecovery = std::make_unique<SrcMgr::ContentCache>();
477     FakeContentCacheForRecovery->setUnownedBuffer(getFakeBufferForRecovery());
478   }
479   return *FakeContentCacheForRecovery;
480 }
481 
482 /// Returns the previous in-order FileID or an invalid FileID if there
483 /// is no previous one.
getPreviousFileID(FileID FID) const484 FileID SourceManager::getPreviousFileID(FileID FID) const {
485   if (FID.isInvalid())
486     return FileID();
487 
488   int ID = FID.ID;
489   if (ID == -1)
490     return FileID();
491 
492   if (ID > 0) {
493     if (ID-1 == 0)
494       return FileID();
495   } else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {
496     return FileID();
497   }
498 
499   return FileID::get(ID-1);
500 }
501 
502 /// Returns the next in-order FileID or an invalid FileID if there is
503 /// no next one.
getNextFileID(FileID FID) const504 FileID SourceManager::getNextFileID(FileID FID) const {
505   if (FID.isInvalid())
506     return FileID();
507 
508   int ID = FID.ID;
509   if (ID > 0) {
510     if (unsigned(ID+1) >= local_sloc_entry_size())
511       return FileID();
512   } else if (ID+1 >= -1) {
513     return FileID();
514   }
515 
516   return FileID::get(ID+1);
517 }
518 
519 //===----------------------------------------------------------------------===//
520 // Methods to create new FileID's and macro expansions.
521 //===----------------------------------------------------------------------===//
522 
523 /// Create a new FileID that represents the specified file
524 /// being \#included from the specified IncludePosition.
525 ///
526 /// This translates NULL into standard input.
createFileID(const FileEntry * SourceFile,SourceLocation IncludePos,SrcMgr::CharacteristicKind FileCharacter,int LoadedID,unsigned LoadedOffset)527 FileID SourceManager::createFileID(const FileEntry *SourceFile,
528                                    SourceLocation IncludePos,
529                                    SrcMgr::CharacteristicKind FileCharacter,
530                                    int LoadedID, unsigned LoadedOffset) {
531   assert(SourceFile && "Null source file!");
532   SrcMgr::ContentCache &IR =
533       getOrCreateContentCache(SourceFile, isSystem(FileCharacter));
534   return createFileIDImpl(IR, SourceFile->getName(), IncludePos, FileCharacter,
535                           LoadedID, LoadedOffset);
536 }
537 
createFileID(FileEntryRef SourceFile,SourceLocation IncludePos,SrcMgr::CharacteristicKind FileCharacter,int LoadedID,unsigned LoadedOffset)538 FileID SourceManager::createFileID(FileEntryRef SourceFile,
539                                    SourceLocation IncludePos,
540                                    SrcMgr::CharacteristicKind FileCharacter,
541                                    int LoadedID, unsigned LoadedOffset) {
542   SrcMgr::ContentCache &IR = getOrCreateContentCache(&SourceFile.getFileEntry(),
543                                                      isSystem(FileCharacter));
544   return createFileIDImpl(IR, SourceFile.getName(), IncludePos, FileCharacter,
545                           LoadedID, LoadedOffset);
546 }
547 
548 /// Create a new FileID that represents the specified memory buffer.
549 ///
550 /// This does no caching of the buffer and takes ownership of the
551 /// MemoryBuffer, so only pass a MemoryBuffer to this once.
createFileID(std::unique_ptr<llvm::MemoryBuffer> Buffer,SrcMgr::CharacteristicKind FileCharacter,int LoadedID,unsigned LoadedOffset,SourceLocation IncludeLoc)552 FileID SourceManager::createFileID(std::unique_ptr<llvm::MemoryBuffer> Buffer,
553                                    SrcMgr::CharacteristicKind FileCharacter,
554                                    int LoadedID, unsigned LoadedOffset,
555                                    SourceLocation IncludeLoc) {
556   StringRef Name = Buffer->getBufferIdentifier();
557   return createFileIDImpl(createMemBufferContentCache(std::move(Buffer)), Name,
558                           IncludeLoc, FileCharacter, LoadedID, LoadedOffset);
559 }
560 
561 /// Create a new FileID that represents the specified memory buffer.
562 ///
563 /// This does not take ownership of the MemoryBuffer. The memory buffer must
564 /// outlive the SourceManager.
createFileID(const llvm::MemoryBufferRef & Buffer,SrcMgr::CharacteristicKind FileCharacter,int LoadedID,unsigned LoadedOffset,SourceLocation IncludeLoc)565 FileID SourceManager::createFileID(const llvm::MemoryBufferRef &Buffer,
566                                    SrcMgr::CharacteristicKind FileCharacter,
567                                    int LoadedID, unsigned LoadedOffset,
568                                    SourceLocation IncludeLoc) {
569   return createFileID(llvm::MemoryBuffer::getMemBuffer(Buffer), FileCharacter,
570                       LoadedID, LoadedOffset, IncludeLoc);
571 }
572 
573 /// Get the FileID for \p SourceFile if it exists. Otherwise, create a
574 /// new FileID for the \p SourceFile.
575 FileID
getOrCreateFileID(const FileEntry * SourceFile,SrcMgr::CharacteristicKind FileCharacter)576 SourceManager::getOrCreateFileID(const FileEntry *SourceFile,
577                                  SrcMgr::CharacteristicKind FileCharacter) {
578   FileID ID = translateFile(SourceFile);
579   return ID.isValid() ? ID : createFileID(SourceFile, SourceLocation(),
580 					  FileCharacter);
581 }
582 
583 /// createFileID - Create a new FileID for the specified ContentCache and
584 /// include position.  This works regardless of whether the ContentCache
585 /// corresponds to a file or some other input source.
createFileIDImpl(ContentCache & File,StringRef Filename,SourceLocation IncludePos,SrcMgr::CharacteristicKind FileCharacter,int LoadedID,unsigned LoadedOffset)586 FileID SourceManager::createFileIDImpl(ContentCache &File, StringRef Filename,
587                                        SourceLocation IncludePos,
588                                        SrcMgr::CharacteristicKind FileCharacter,
589                                        int LoadedID, unsigned LoadedOffset) {
590   if (LoadedID < 0) {
591     assert(LoadedID != -1 && "Loading sentinel FileID");
592     unsigned Index = unsigned(-LoadedID) - 2;
593     assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
594     assert(!SLocEntryLoaded[Index] && "FileID already loaded");
595     LoadedSLocEntryTable[Index] = SLocEntry::get(
596         LoadedOffset, FileInfo::get(IncludePos, File, FileCharacter, Filename));
597     SLocEntryLoaded[Index] = true;
598     return FileID::get(LoadedID);
599   }
600   unsigned FileSize = File.getSize();
601   if (!(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
602         NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset)) {
603     Diag.Report(IncludePos, diag::err_include_too_large);
604     return FileID();
605   }
606   LocalSLocEntryTable.push_back(
607       SLocEntry::get(NextLocalOffset,
608                      FileInfo::get(IncludePos, File, FileCharacter, Filename)));
609   // We do a +1 here because we want a SourceLocation that means "the end of the
610   // file", e.g. for the "no newline at the end of the file" diagnostic.
611   NextLocalOffset += FileSize + 1;
612 
613   // Set LastFileIDLookup to the newly created file.  The next getFileID call is
614   // almost guaranteed to be from that file.
615   FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
616   return LastFileIDLookup = FID;
617 }
618 
619 SourceLocation
createMacroArgExpansionLoc(SourceLocation SpellingLoc,SourceLocation ExpansionLoc,unsigned TokLength)620 SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc,
621                                           SourceLocation ExpansionLoc,
622                                           unsigned TokLength) {
623   ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
624                                                         ExpansionLoc);
625   return createExpansionLocImpl(Info, TokLength);
626 }
627 
628 SourceLocation
createExpansionLoc(SourceLocation SpellingLoc,SourceLocation ExpansionLocStart,SourceLocation ExpansionLocEnd,unsigned TokLength,bool ExpansionIsTokenRange,int LoadedID,unsigned LoadedOffset)629 SourceManager::createExpansionLoc(SourceLocation SpellingLoc,
630                                   SourceLocation ExpansionLocStart,
631                                   SourceLocation ExpansionLocEnd,
632                                   unsigned TokLength,
633                                   bool ExpansionIsTokenRange,
634                                   int LoadedID,
635                                   unsigned LoadedOffset) {
636   ExpansionInfo Info = ExpansionInfo::create(
637       SpellingLoc, ExpansionLocStart, ExpansionLocEnd, ExpansionIsTokenRange);
638   return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset);
639 }
640 
createTokenSplitLoc(SourceLocation Spelling,SourceLocation TokenStart,SourceLocation TokenEnd)641 SourceLocation SourceManager::createTokenSplitLoc(SourceLocation Spelling,
642                                                   SourceLocation TokenStart,
643                                                   SourceLocation TokenEnd) {
644   assert(getFileID(TokenStart) == getFileID(TokenEnd) &&
645          "token spans multiple files");
646   return createExpansionLocImpl(
647       ExpansionInfo::createForTokenSplit(Spelling, TokenStart, TokenEnd),
648       TokenEnd.getOffset() - TokenStart.getOffset());
649 }
650 
651 SourceLocation
createExpansionLocImpl(const ExpansionInfo & Info,unsigned TokLength,int LoadedID,unsigned LoadedOffset)652 SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
653                                       unsigned TokLength,
654                                       int LoadedID,
655                                       unsigned LoadedOffset) {
656   if (LoadedID < 0) {
657     assert(LoadedID != -1 && "Loading sentinel FileID");
658     unsigned Index = unsigned(-LoadedID) - 2;
659     assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
660     assert(!SLocEntryLoaded[Index] && "FileID already loaded");
661     LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
662     SLocEntryLoaded[Index] = true;
663     return SourceLocation::getMacroLoc(LoadedOffset);
664   }
665   LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
666   assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&
667          NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&
668          "Ran out of source locations!");
669   // See createFileID for that +1.
670   NextLocalOffset += TokLength + 1;
671   return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
672 }
673 
674 llvm::Optional<llvm::MemoryBufferRef>
getMemoryBufferForFileOrNone(const FileEntry * File)675 SourceManager::getMemoryBufferForFileOrNone(const FileEntry *File) {
676   SrcMgr::ContentCache &IR = getOrCreateContentCache(File);
677   return IR.getBufferOrNone(Diag, getFileManager(), SourceLocation());
678 }
679 
overrideFileContents(const FileEntry * SourceFile,std::unique_ptr<llvm::MemoryBuffer> Buffer)680 void SourceManager::overrideFileContents(
681     const FileEntry *SourceFile, std::unique_ptr<llvm::MemoryBuffer> Buffer) {
682   SrcMgr::ContentCache &IR = getOrCreateContentCache(SourceFile);
683 
684   IR.setBuffer(std::move(Buffer));
685   IR.BufferOverridden = true;
686 
687   getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
688 }
689 
overrideFileContents(const FileEntry * SourceFile,const FileEntry * NewFile)690 void SourceManager::overrideFileContents(const FileEntry *SourceFile,
691                                          const FileEntry *NewFile) {
692   assert(SourceFile->getSize() == NewFile->getSize() &&
693          "Different sizes, use the FileManager to create a virtual file with "
694          "the correct size");
695   assert(FileInfos.count(SourceFile) == 0 &&
696          "This function should be called at the initialization stage, before "
697          "any parsing occurs.");
698   getOverriddenFilesInfo().OverriddenFiles[SourceFile] = NewFile;
699 }
700 
701 Optional<FileEntryRef>
bypassFileContentsOverride(FileEntryRef File)702 SourceManager::bypassFileContentsOverride(FileEntryRef File) {
703   assert(isFileOverridden(&File.getFileEntry()));
704   llvm::Optional<FileEntryRef> BypassFile = FileMgr.getBypassFile(File);
705 
706   // If the file can't be found in the FS, give up.
707   if (!BypassFile)
708     return None;
709 
710   (void)getOrCreateContentCache(&BypassFile->getFileEntry());
711   return BypassFile;
712 }
713 
setFileIsTransient(const FileEntry * File)714 void SourceManager::setFileIsTransient(const FileEntry *File) {
715   getOrCreateContentCache(File).IsTransient = true;
716 }
717 
718 Optional<StringRef>
getNonBuiltinFilenameForID(FileID FID) const719 SourceManager::getNonBuiltinFilenameForID(FileID FID) const {
720   if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID))
721     if (Entry->getFile().getContentCache().OrigEntry)
722       return Entry->getFile().getName();
723   return None;
724 }
725 
getBufferData(FileID FID,bool * Invalid) const726 StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
727   auto B = getBufferDataOrNone(FID);
728   if (Invalid)
729     *Invalid = !B;
730   return B ? *B : "<<<<<INVALID SOURCE LOCATION>>>>>";
731 }
732 
733 llvm::Optional<StringRef>
getBufferDataIfLoaded(FileID FID) const734 SourceManager::getBufferDataIfLoaded(FileID FID) const {
735   if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID))
736     return Entry->getFile().getContentCache().getBufferDataIfLoaded();
737   return None;
738 }
739 
getBufferDataOrNone(FileID FID) const740 llvm::Optional<StringRef> SourceManager::getBufferDataOrNone(FileID FID) const {
741   if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID))
742     if (auto B = Entry->getFile().getContentCache().getBufferOrNone(
743             Diag, getFileManager(), SourceLocation()))
744       return B->getBuffer();
745   return None;
746 }
747 
748 //===----------------------------------------------------------------------===//
749 // SourceLocation manipulation methods.
750 //===----------------------------------------------------------------------===//
751 
752 /// Return the FileID for a SourceLocation.
753 ///
754 /// This is the cache-miss path of getFileID. Not as hot as that function, but
755 /// still very important. It is responsible for finding the entry in the
756 /// SLocEntry tables that contains the specified location.
getFileIDSlow(unsigned SLocOffset) const757 FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
758   if (!SLocOffset)
759     return FileID::get(0);
760 
761   // Now it is time to search for the correct file. See where the SLocOffset
762   // sits in the global view and consult local or loaded buffers for it.
763   if (SLocOffset < NextLocalOffset)
764     return getFileIDLocal(SLocOffset);
765   return getFileIDLoaded(SLocOffset);
766 }
767 
768 /// Return the FileID for a SourceLocation with a low offset.
769 ///
770 /// This function knows that the SourceLocation is in a local buffer, not a
771 /// loaded one.
getFileIDLocal(unsigned SLocOffset) const772 FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const {
773   assert(SLocOffset < NextLocalOffset && "Bad function choice");
774 
775   // After the first and second level caches, I see two common sorts of
776   // behavior: 1) a lot of searched FileID's are "near" the cached file
777   // location or are "near" the cached expansion location. 2) others are just
778   // completely random and may be a very long way away.
779   //
780   // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
781   // then we fall back to a less cache efficient, but more scalable, binary
782   // search to find the location.
783 
784   // See if this is near the file point - worst case we start scanning from the
785   // most newly created FileID.
786   const SrcMgr::SLocEntry *I;
787 
788   if (LastFileIDLookup.ID < 0 ||
789       LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
790     // Neither loc prunes our search.
791     I = LocalSLocEntryTable.end();
792   } else {
793     // Perhaps it is near the file point.
794     I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
795   }
796 
797   // Find the FileID that contains this.  "I" is an iterator that points to a
798   // FileID whose offset is known to be larger than SLocOffset.
799   unsigned NumProbes = 0;
800   while (true) {
801     --I;
802     if (I->getOffset() <= SLocOffset) {
803       FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
804       // Remember it.  We have good locality across FileID lookups.
805       LastFileIDLookup = Res;
806       NumLinearScans += NumProbes+1;
807       return Res;
808     }
809     if (++NumProbes == 8)
810       break;
811   }
812 
813   // Convert "I" back into an index.  We know that it is an entry whose index is
814   // larger than the offset we are looking for.
815   unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
816   // LessIndex - This is the lower bound of the range that we're searching.
817   // We know that the offset corresponding to the FileID is is less than
818   // SLocOffset.
819   unsigned LessIndex = 0;
820   NumProbes = 0;
821   while (true) {
822     unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
823     unsigned MidOffset = getLocalSLocEntry(MiddleIndex).getOffset();
824 
825     ++NumProbes;
826 
827     // If the offset of the midpoint is too large, chop the high side of the
828     // range to the midpoint.
829     if (MidOffset > SLocOffset) {
830       GreaterIndex = MiddleIndex;
831       continue;
832     }
833 
834     // If the middle index contains the value, succeed and return.
835     if (MiddleIndex + 1 == LocalSLocEntryTable.size() ||
836         SLocOffset < getLocalSLocEntry(MiddleIndex + 1).getOffset()) {
837       FileID Res = FileID::get(MiddleIndex);
838 
839       // Remember it.  We have good locality across FileID lookups.
840       LastFileIDLookup = Res;
841       NumBinaryProbes += NumProbes;
842       return Res;
843     }
844 
845     // Otherwise, move the low-side up to the middle index.
846     LessIndex = MiddleIndex;
847   }
848 }
849 
850 /// Return the FileID for a SourceLocation with a high offset.
851 ///
852 /// This function knows that the SourceLocation is in a loaded buffer, not a
853 /// local one.
getFileIDLoaded(unsigned SLocOffset) const854 FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
855   // Sanity checking, otherwise a bug may lead to hanging in release build.
856   if (SLocOffset < CurrentLoadedOffset) {
857     assert(0 && "Invalid SLocOffset or bad function choice");
858     return FileID();
859   }
860 
861   // Essentially the same as the local case, but the loaded array is sorted
862   // in the other direction.
863 
864   // First do a linear scan from the last lookup position, if possible.
865   unsigned I;
866   int LastID = LastFileIDLookup.ID;
867   if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
868     I = 0;
869   else
870     I = (-LastID - 2) + 1;
871 
872   unsigned NumProbes;
873   for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
874     // Make sure the entry is loaded!
875     const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
876     if (E.getOffset() <= SLocOffset) {
877       FileID Res = FileID::get(-int(I) - 2);
878       LastFileIDLookup = Res;
879       NumLinearScans += NumProbes + 1;
880       return Res;
881     }
882   }
883 
884   // Linear scan failed. Do the binary search. Note the reverse sorting of the
885   // table: GreaterIndex is the one where the offset is greater, which is
886   // actually a lower index!
887   unsigned GreaterIndex = I;
888   unsigned LessIndex = LoadedSLocEntryTable.size();
889   NumProbes = 0;
890   while (true) {
891     ++NumProbes;
892     unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
893     const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
894     if (E.getOffset() == 0)
895       return FileID(); // invalid entry.
896 
897     ++NumProbes;
898 
899     if (E.getOffset() > SLocOffset) {
900       // Sanity checking, otherwise a bug may lead to hanging in release build.
901       if (GreaterIndex == MiddleIndex) {
902         assert(0 && "binary search missed the entry");
903         return FileID();
904       }
905       GreaterIndex = MiddleIndex;
906       continue;
907     }
908 
909     if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
910       FileID Res = FileID::get(-int(MiddleIndex) - 2);
911       LastFileIDLookup = Res;
912       NumBinaryProbes += NumProbes;
913       return Res;
914     }
915 
916     // Sanity checking, otherwise a bug may lead to hanging in release build.
917     if (LessIndex == MiddleIndex) {
918       assert(0 && "binary search missed the entry");
919       return FileID();
920     }
921     LessIndex = MiddleIndex;
922   }
923 }
924 
925 SourceLocation SourceManager::
getExpansionLocSlowCase(SourceLocation Loc) const926 getExpansionLocSlowCase(SourceLocation Loc) const {
927   do {
928     // Note: If Loc indicates an offset into a token that came from a macro
929     // expansion (e.g. the 5th character of the token) we do not want to add
930     // this offset when going to the expansion location.  The expansion
931     // location is the macro invocation, which the offset has nothing to do
932     // with.  This is unlike when we get the spelling loc, because the offset
933     // directly correspond to the token whose spelling we're inspecting.
934     Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
935   } while (!Loc.isFileID());
936 
937   return Loc;
938 }
939 
getSpellingLocSlowCase(SourceLocation Loc) const940 SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
941   do {
942     std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
943     Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
944     Loc = Loc.getLocWithOffset(LocInfo.second);
945   } while (!Loc.isFileID());
946   return Loc;
947 }
948 
getFileLocSlowCase(SourceLocation Loc) const949 SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
950   do {
951     if (isMacroArgExpansion(Loc))
952       Loc = getImmediateSpellingLoc(Loc);
953     else
954       Loc = getImmediateExpansionRange(Loc).getBegin();
955   } while (!Loc.isFileID());
956   return Loc;
957 }
958 
959 
960 std::pair<FileID, unsigned>
getDecomposedExpansionLocSlowCase(const SrcMgr::SLocEntry * E) const961 SourceManager::getDecomposedExpansionLocSlowCase(
962                                              const SrcMgr::SLocEntry *E) const {
963   // If this is an expansion record, walk through all the expansion points.
964   FileID FID;
965   SourceLocation Loc;
966   unsigned Offset;
967   do {
968     Loc = E->getExpansion().getExpansionLocStart();
969 
970     FID = getFileID(Loc);
971     E = &getSLocEntry(FID);
972     Offset = Loc.getOffset()-E->getOffset();
973   } while (!Loc.isFileID());
974 
975   return std::make_pair(FID, Offset);
976 }
977 
978 std::pair<FileID, unsigned>
getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry * E,unsigned Offset) const979 SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
980                                                 unsigned Offset) const {
981   // If this is an expansion record, walk through all the expansion points.
982   FileID FID;
983   SourceLocation Loc;
984   do {
985     Loc = E->getExpansion().getSpellingLoc();
986     Loc = Loc.getLocWithOffset(Offset);
987 
988     FID = getFileID(Loc);
989     E = &getSLocEntry(FID);
990     Offset = Loc.getOffset()-E->getOffset();
991   } while (!Loc.isFileID());
992 
993   return std::make_pair(FID, Offset);
994 }
995 
996 /// getImmediateSpellingLoc - Given a SourceLocation object, return the
997 /// spelling location referenced by the ID.  This is the first level down
998 /// towards the place where the characters that make up the lexed token can be
999 /// found.  This should not generally be used by clients.
getImmediateSpellingLoc(SourceLocation Loc) const1000 SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
1001   if (Loc.isFileID()) return Loc;
1002   std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
1003   Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
1004   return Loc.getLocWithOffset(LocInfo.second);
1005 }
1006 
1007 /// Return the filename of the file containing a SourceLocation.
getFilename(SourceLocation SpellingLoc) const1008 StringRef SourceManager::getFilename(SourceLocation SpellingLoc) const {
1009   if (const FileEntry *F = getFileEntryForID(getFileID(SpellingLoc)))
1010     return F->getName();
1011   return StringRef();
1012 }
1013 
1014 /// getImmediateExpansionRange - Loc is required to be an expansion location.
1015 /// Return the start/end of the expansion information.
1016 CharSourceRange
getImmediateExpansionRange(SourceLocation Loc) const1017 SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
1018   assert(Loc.isMacroID() && "Not a macro expansion loc!");
1019   const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
1020   return Expansion.getExpansionLocRange();
1021 }
1022 
getTopMacroCallerLoc(SourceLocation Loc) const1023 SourceLocation SourceManager::getTopMacroCallerLoc(SourceLocation Loc) const {
1024   while (isMacroArgExpansion(Loc))
1025     Loc = getImmediateSpellingLoc(Loc);
1026   return Loc;
1027 }
1028 
1029 /// getExpansionRange - Given a SourceLocation object, return the range of
1030 /// tokens covered by the expansion in the ultimate file.
getExpansionRange(SourceLocation Loc) const1031 CharSourceRange SourceManager::getExpansionRange(SourceLocation Loc) const {
1032   if (Loc.isFileID())
1033     return CharSourceRange(SourceRange(Loc, Loc), true);
1034 
1035   CharSourceRange Res = getImmediateExpansionRange(Loc);
1036 
1037   // Fully resolve the start and end locations to their ultimate expansion
1038   // points.
1039   while (!Res.getBegin().isFileID())
1040     Res.setBegin(getImmediateExpansionRange(Res.getBegin()).getBegin());
1041   while (!Res.getEnd().isFileID()) {
1042     CharSourceRange EndRange = getImmediateExpansionRange(Res.getEnd());
1043     Res.setEnd(EndRange.getEnd());
1044     Res.setTokenRange(EndRange.isTokenRange());
1045   }
1046   return Res;
1047 }
1048 
isMacroArgExpansion(SourceLocation Loc,SourceLocation * StartLoc) const1049 bool SourceManager::isMacroArgExpansion(SourceLocation Loc,
1050                                         SourceLocation *StartLoc) const {
1051   if (!Loc.isMacroID()) return false;
1052 
1053   FileID FID = getFileID(Loc);
1054   const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1055   if (!Expansion.isMacroArgExpansion()) return false;
1056 
1057   if (StartLoc)
1058     *StartLoc = Expansion.getExpansionLocStart();
1059   return true;
1060 }
1061 
isMacroBodyExpansion(SourceLocation Loc) const1062 bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const {
1063   if (!Loc.isMacroID()) return false;
1064 
1065   FileID FID = getFileID(Loc);
1066   const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1067   return Expansion.isMacroBodyExpansion();
1068 }
1069 
isAtStartOfImmediateMacroExpansion(SourceLocation Loc,SourceLocation * MacroBegin) const1070 bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
1071                                              SourceLocation *MacroBegin) const {
1072   assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1073 
1074   std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);
1075   if (DecompLoc.second > 0)
1076     return false; // Does not point at the start of expansion range.
1077 
1078   bool Invalid = false;
1079   const SrcMgr::ExpansionInfo &ExpInfo =
1080       getSLocEntry(DecompLoc.first, &Invalid).getExpansion();
1081   if (Invalid)
1082     return false;
1083   SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();
1084 
1085   if (ExpInfo.isMacroArgExpansion()) {
1086     // For macro argument expansions, check if the previous FileID is part of
1087     // the same argument expansion, in which case this Loc is not at the
1088     // beginning of the expansion.
1089     FileID PrevFID = getPreviousFileID(DecompLoc.first);
1090     if (!PrevFID.isInvalid()) {
1091       const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);
1092       if (Invalid)
1093         return false;
1094       if (PrevEntry.isExpansion() &&
1095           PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)
1096         return false;
1097     }
1098   }
1099 
1100   if (MacroBegin)
1101     *MacroBegin = ExpLoc;
1102   return true;
1103 }
1104 
isAtEndOfImmediateMacroExpansion(SourceLocation Loc,SourceLocation * MacroEnd) const1105 bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
1106                                                SourceLocation *MacroEnd) const {
1107   assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1108 
1109   FileID FID = getFileID(Loc);
1110   SourceLocation NextLoc = Loc.getLocWithOffset(1);
1111   if (isInFileID(NextLoc, FID))
1112     return false; // Does not point at the end of expansion range.
1113 
1114   bool Invalid = false;
1115   const SrcMgr::ExpansionInfo &ExpInfo =
1116       getSLocEntry(FID, &Invalid).getExpansion();
1117   if (Invalid)
1118     return false;
1119 
1120   if (ExpInfo.isMacroArgExpansion()) {
1121     // For macro argument expansions, check if the next FileID is part of the
1122     // same argument expansion, in which case this Loc is not at the end of the
1123     // expansion.
1124     FileID NextFID = getNextFileID(FID);
1125     if (!NextFID.isInvalid()) {
1126       const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);
1127       if (Invalid)
1128         return false;
1129       if (NextEntry.isExpansion() &&
1130           NextEntry.getExpansion().getExpansionLocStart() ==
1131               ExpInfo.getExpansionLocStart())
1132         return false;
1133     }
1134   }
1135 
1136   if (MacroEnd)
1137     *MacroEnd = ExpInfo.getExpansionLocEnd();
1138   return true;
1139 }
1140 
1141 //===----------------------------------------------------------------------===//
1142 // Queries about the code at a SourceLocation.
1143 //===----------------------------------------------------------------------===//
1144 
1145 /// getCharacterData - Return a pointer to the start of the specified location
1146 /// in the appropriate MemoryBuffer.
getCharacterData(SourceLocation SL,bool * Invalid) const1147 const char *SourceManager::getCharacterData(SourceLocation SL,
1148                                             bool *Invalid) const {
1149   // Note that this is a hot function in the getSpelling() path, which is
1150   // heavily used by -E mode.
1151   std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
1152 
1153   // Note that calling 'getBuffer()' may lazily page in a source file.
1154   bool CharDataInvalid = false;
1155   const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
1156   if (CharDataInvalid || !Entry.isFile()) {
1157     if (Invalid)
1158       *Invalid = true;
1159 
1160     return "<<<<INVALID BUFFER>>>>";
1161   }
1162   llvm::Optional<llvm::MemoryBufferRef> Buffer =
1163       Entry.getFile().getContentCache().getBufferOrNone(Diag, getFileManager(),
1164                                                         SourceLocation());
1165   if (Invalid)
1166     *Invalid = !Buffer;
1167   return Buffer ? Buffer->getBufferStart() + LocInfo.second
1168                 : "<<<<INVALID BUFFER>>>>";
1169 }
1170 
1171 /// getColumnNumber - Return the column # for the specified file position.
1172 /// this is significantly cheaper to compute than the line number.
getColumnNumber(FileID FID,unsigned FilePos,bool * Invalid) const1173 unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
1174                                         bool *Invalid) const {
1175   llvm::Optional<llvm::MemoryBufferRef> MemBuf = getBufferOrNone(FID);
1176   if (Invalid)
1177     *Invalid = !MemBuf;
1178 
1179   if (!MemBuf)
1180     return 1;
1181 
1182   // It is okay to request a position just past the end of the buffer.
1183   if (FilePos > MemBuf->getBufferSize()) {
1184     if (Invalid)
1185       *Invalid = true;
1186     return 1;
1187   }
1188 
1189   const char *Buf = MemBuf->getBufferStart();
1190   // See if we just calculated the line number for this FilePos and can use
1191   // that to lookup the start of the line instead of searching for it.
1192   if (LastLineNoFileIDQuery == FID && LastLineNoContentCache->SourceLineCache &&
1193       LastLineNoResult < LastLineNoContentCache->SourceLineCache.size()) {
1194     const unsigned *SourceLineCache =
1195         LastLineNoContentCache->SourceLineCache.begin();
1196     unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
1197     unsigned LineEnd = SourceLineCache[LastLineNoResult];
1198     if (FilePos >= LineStart && FilePos < LineEnd) {
1199       // LineEnd is the LineStart of the next line.
1200       // A line ends with separator LF or CR+LF on Windows.
1201       // FilePos might point to the last separator,
1202       // but we need a column number at most 1 + the last column.
1203       if (FilePos + 1 == LineEnd && FilePos > LineStart) {
1204         if (Buf[FilePos - 1] == '\r' || Buf[FilePos - 1] == '\n')
1205           --FilePos;
1206       }
1207       return FilePos - LineStart + 1;
1208     }
1209   }
1210 
1211   unsigned LineStart = FilePos;
1212   while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
1213     --LineStart;
1214   return FilePos-LineStart+1;
1215 }
1216 
1217 // isInvalid - Return the result of calling loc.isInvalid(), and
1218 // if Invalid is not null, set its value to same.
1219 template<typename LocType>
isInvalid(LocType Loc,bool * Invalid)1220 static bool isInvalid(LocType Loc, bool *Invalid) {
1221   bool MyInvalid = Loc.isInvalid();
1222   if (Invalid)
1223     *Invalid = MyInvalid;
1224   return MyInvalid;
1225 }
1226 
getSpellingColumnNumber(SourceLocation Loc,bool * Invalid) const1227 unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
1228                                                 bool *Invalid) const {
1229   if (isInvalid(Loc, Invalid)) return 0;
1230   std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1231   return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1232 }
1233 
getExpansionColumnNumber(SourceLocation Loc,bool * Invalid) const1234 unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
1235                                                  bool *Invalid) const {
1236   if (isInvalid(Loc, Invalid)) return 0;
1237   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1238   return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1239 }
1240 
getPresumedColumnNumber(SourceLocation Loc,bool * Invalid) const1241 unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
1242                                                 bool *Invalid) const {
1243   PresumedLoc PLoc = getPresumedLoc(Loc);
1244   if (isInvalid(PLoc, Invalid)) return 0;
1245   return PLoc.getColumn();
1246 }
1247 
1248 #ifdef __SSE2__
1249 #include <emmintrin.h>
1250 #endif
1251 
get(llvm::MemoryBufferRef Buffer,llvm::BumpPtrAllocator & Alloc)1252 LineOffsetMapping LineOffsetMapping::get(llvm::MemoryBufferRef Buffer,
1253                                          llvm::BumpPtrAllocator &Alloc) {
1254   // Find the file offsets of all of the *physical* source lines.  This does
1255   // not look at trigraphs, escaped newlines, or anything else tricky.
1256   SmallVector<unsigned, 256> LineOffsets;
1257 
1258   // Line #1 starts at char 0.
1259   LineOffsets.push_back(0);
1260 
1261   const unsigned char *Buf = (const unsigned char *)Buffer.getBufferStart();
1262   const unsigned char *End = (const unsigned char *)Buffer.getBufferEnd();
1263   const std::size_t BufLen = End - Buf;
1264   unsigned I = 0;
1265   while (I < BufLen) {
1266     if (Buf[I] == '\n') {
1267       LineOffsets.push_back(I + 1);
1268     } else if (Buf[I] == '\r') {
1269       // If this is \r\n, skip both characters.
1270       if (I + 1 < BufLen && Buf[I + 1] == '\n')
1271         ++I;
1272       LineOffsets.push_back(I + 1);
1273     }
1274     ++I;
1275   }
1276 
1277   return LineOffsetMapping(LineOffsets, Alloc);
1278 }
1279 
LineOffsetMapping(ArrayRef<unsigned> LineOffsets,llvm::BumpPtrAllocator & Alloc)1280 LineOffsetMapping::LineOffsetMapping(ArrayRef<unsigned> LineOffsets,
1281                                      llvm::BumpPtrAllocator &Alloc)
1282     : Storage(Alloc.Allocate<unsigned>(LineOffsets.size() + 1)) {
1283   Storage[0] = LineOffsets.size();
1284   std::copy(LineOffsets.begin(), LineOffsets.end(), Storage + 1);
1285 }
1286 
1287 /// getLineNumber - Given a SourceLocation, return the spelling line number
1288 /// for the position indicated.  This requires building and caching a table of
1289 /// line offsets for the MemoryBuffer, so this is not cheap: use only when
1290 /// about to emit a diagnostic.
getLineNumber(FileID FID,unsigned FilePos,bool * Invalid) const1291 unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1292                                       bool *Invalid) const {
1293   if (FID.isInvalid()) {
1294     if (Invalid)
1295       *Invalid = true;
1296     return 1;
1297   }
1298 
1299   const ContentCache *Content;
1300   if (LastLineNoFileIDQuery == FID)
1301     Content = LastLineNoContentCache;
1302   else {
1303     bool MyInvalid = false;
1304     const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1305     if (MyInvalid || !Entry.isFile()) {
1306       if (Invalid)
1307         *Invalid = true;
1308       return 1;
1309     }
1310 
1311     Content = &Entry.getFile().getContentCache();
1312   }
1313 
1314   // If this is the first use of line information for this buffer, compute the
1315   /// SourceLineCache for it on demand.
1316   if (!Content->SourceLineCache) {
1317     llvm::Optional<llvm::MemoryBufferRef> Buffer =
1318         Content->getBufferOrNone(Diag, getFileManager(), SourceLocation());
1319     if (Invalid)
1320       *Invalid = !Buffer;
1321     if (!Buffer)
1322       return 1;
1323 
1324     Content->SourceLineCache =
1325         LineOffsetMapping::get(*Buffer, ContentCacheAlloc);
1326   } else if (Invalid)
1327     *Invalid = false;
1328 
1329   // Okay, we know we have a line number table.  Do a binary search to find the
1330   // line number that this character position lands on.
1331   const unsigned *SourceLineCache = Content->SourceLineCache.begin();
1332   const unsigned *SourceLineCacheStart = SourceLineCache;
1333   const unsigned *SourceLineCacheEnd = Content->SourceLineCache.end();
1334 
1335   unsigned QueriedFilePos = FilePos+1;
1336 
1337   // FIXME: I would like to be convinced that this code is worth being as
1338   // complicated as it is, binary search isn't that slow.
1339   //
1340   // If it is worth being optimized, then in my opinion it could be more
1341   // performant, simpler, and more obviously correct by just "galloping" outward
1342   // from the queried file position. In fact, this could be incorporated into a
1343   // generic algorithm such as lower_bound_with_hint.
1344   //
1345   // If someone gives me a test case where this matters, and I will do it! - DWD
1346 
1347   // If the previous query was to the same file, we know both the file pos from
1348   // that query and the line number returned.  This allows us to narrow the
1349   // search space from the entire file to something near the match.
1350   if (LastLineNoFileIDQuery == FID) {
1351     if (QueriedFilePos >= LastLineNoFilePos) {
1352       // FIXME: Potential overflow?
1353       SourceLineCache = SourceLineCache+LastLineNoResult-1;
1354 
1355       // The query is likely to be nearby the previous one.  Here we check to
1356       // see if it is within 5, 10 or 20 lines.  It can be far away in cases
1357       // where big comment blocks and vertical whitespace eat up lines but
1358       // contribute no tokens.
1359       if (SourceLineCache+5 < SourceLineCacheEnd) {
1360         if (SourceLineCache[5] > QueriedFilePos)
1361           SourceLineCacheEnd = SourceLineCache+5;
1362         else if (SourceLineCache+10 < SourceLineCacheEnd) {
1363           if (SourceLineCache[10] > QueriedFilePos)
1364             SourceLineCacheEnd = SourceLineCache+10;
1365           else if (SourceLineCache+20 < SourceLineCacheEnd) {
1366             if (SourceLineCache[20] > QueriedFilePos)
1367               SourceLineCacheEnd = SourceLineCache+20;
1368           }
1369         }
1370       }
1371     } else {
1372       if (LastLineNoResult < Content->SourceLineCache.size())
1373         SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
1374     }
1375   }
1376 
1377   const unsigned *Pos =
1378       std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
1379   unsigned LineNo = Pos-SourceLineCacheStart;
1380 
1381   LastLineNoFileIDQuery = FID;
1382   LastLineNoContentCache = Content;
1383   LastLineNoFilePos = QueriedFilePos;
1384   LastLineNoResult = LineNo;
1385   return LineNo;
1386 }
1387 
getSpellingLineNumber(SourceLocation Loc,bool * Invalid) const1388 unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1389                                               bool *Invalid) const {
1390   if (isInvalid(Loc, Invalid)) return 0;
1391   std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1392   return getLineNumber(LocInfo.first, LocInfo.second);
1393 }
getExpansionLineNumber(SourceLocation Loc,bool * Invalid) const1394 unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
1395                                                bool *Invalid) const {
1396   if (isInvalid(Loc, Invalid)) return 0;
1397   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1398   return getLineNumber(LocInfo.first, LocInfo.second);
1399 }
getPresumedLineNumber(SourceLocation Loc,bool * Invalid) const1400 unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
1401                                               bool *Invalid) const {
1402   PresumedLoc PLoc = getPresumedLoc(Loc);
1403   if (isInvalid(PLoc, Invalid)) return 0;
1404   return PLoc.getLine();
1405 }
1406 
1407 /// getFileCharacteristic - return the file characteristic of the specified
1408 /// source location, indicating whether this is a normal file, a system
1409 /// header, or an "implicit extern C" system header.
1410 ///
1411 /// This state can be modified with flags on GNU linemarker directives like:
1412 ///   # 4 "foo.h" 3
1413 /// which changes all source locations in the current file after that to be
1414 /// considered to be from a system header.
1415 SrcMgr::CharacteristicKind
getFileCharacteristic(SourceLocation Loc) const1416 SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1417   assert(Loc.isValid() && "Can't get file characteristic of invalid loc!");
1418   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1419   const SLocEntry *SEntry = getSLocEntryForFile(LocInfo.first);
1420   if (!SEntry)
1421     return C_User;
1422 
1423   const SrcMgr::FileInfo &FI = SEntry->getFile();
1424 
1425   // If there are no #line directives in this file, just return the whole-file
1426   // state.
1427   if (!FI.hasLineDirectives())
1428     return FI.getFileCharacteristic();
1429 
1430   assert(LineTable && "Can't have linetable entries without a LineTable!");
1431   // See if there is a #line directive before the location.
1432   const LineEntry *Entry =
1433     LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
1434 
1435   // If this is before the first line marker, use the file characteristic.
1436   if (!Entry)
1437     return FI.getFileCharacteristic();
1438 
1439   return Entry->FileKind;
1440 }
1441 
1442 /// Return the filename or buffer identifier of the buffer the location is in.
1443 /// Note that this name does not respect \#line directives.  Use getPresumedLoc
1444 /// for normal clients.
getBufferName(SourceLocation Loc,bool * Invalid) const1445 StringRef SourceManager::getBufferName(SourceLocation Loc,
1446                                        bool *Invalid) const {
1447   if (isInvalid(Loc, Invalid)) return "<invalid loc>";
1448 
1449   auto B = getBufferOrNone(getFileID(Loc));
1450   if (Invalid)
1451     *Invalid = !B;
1452   return B ? B->getBufferIdentifier() : "<invalid buffer>";
1453 }
1454 
1455 /// getPresumedLoc - This method returns the "presumed" location of a
1456 /// SourceLocation specifies.  A "presumed location" can be modified by \#line
1457 /// or GNU line marker directives.  This provides a view on the data that a
1458 /// user should see in diagnostics, for example.
1459 ///
1460 /// Note that a presumed location is always given as the expansion point of an
1461 /// expansion location, not at the spelling location.
getPresumedLoc(SourceLocation Loc,bool UseLineDirectives) const1462 PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc,
1463                                           bool UseLineDirectives) const {
1464   if (Loc.isInvalid()) return PresumedLoc();
1465 
1466   // Presumed locations are always for expansion points.
1467   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1468 
1469   bool Invalid = false;
1470   const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1471   if (Invalid || !Entry.isFile())
1472     return PresumedLoc();
1473 
1474   const SrcMgr::FileInfo &FI = Entry.getFile();
1475   const SrcMgr::ContentCache *C = &FI.getContentCache();
1476 
1477   // To get the source name, first consult the FileEntry (if one exists)
1478   // before the MemBuffer as this will avoid unnecessarily paging in the
1479   // MemBuffer.
1480   FileID FID = LocInfo.first;
1481   StringRef Filename;
1482   if (C->OrigEntry)
1483     Filename = C->OrigEntry->getName();
1484   else if (auto Buffer = C->getBufferOrNone(Diag, getFileManager()))
1485     Filename = Buffer->getBufferIdentifier();
1486 
1487   unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1488   if (Invalid)
1489     return PresumedLoc();
1490   unsigned ColNo  = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1491   if (Invalid)
1492     return PresumedLoc();
1493 
1494   SourceLocation IncludeLoc = FI.getIncludeLoc();
1495 
1496   // If we have #line directives in this file, update and overwrite the physical
1497   // location info if appropriate.
1498   if (UseLineDirectives && FI.hasLineDirectives()) {
1499     assert(LineTable && "Can't have linetable entries without a LineTable!");
1500     // See if there is a #line directive before this.  If so, get it.
1501     if (const LineEntry *Entry =
1502           LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
1503       // If the LineEntry indicates a filename, use it.
1504       if (Entry->FilenameID != -1) {
1505         Filename = LineTable->getFilename(Entry->FilenameID);
1506         // The contents of files referenced by #line are not in the
1507         // SourceManager
1508         FID = FileID::get(0);
1509       }
1510 
1511       // Use the line number specified by the LineEntry.  This line number may
1512       // be multiple lines down from the line entry.  Add the difference in
1513       // physical line numbers from the query point and the line marker to the
1514       // total.
1515       unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1516       LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
1517 
1518       // Note that column numbers are not molested by line markers.
1519 
1520       // Handle virtual #include manipulation.
1521       if (Entry->IncludeOffset) {
1522         IncludeLoc = getLocForStartOfFile(LocInfo.first);
1523         IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
1524       }
1525     }
1526   }
1527 
1528   return PresumedLoc(Filename.data(), FID, LineNo, ColNo, IncludeLoc);
1529 }
1530 
1531 /// Returns whether the PresumedLoc for a given SourceLocation is
1532 /// in the main file.
1533 ///
1534 /// This computes the "presumed" location for a SourceLocation, then checks
1535 /// whether it came from a file other than the main file. This is different
1536 /// from isWrittenInMainFile() because it takes line marker directives into
1537 /// account.
isInMainFile(SourceLocation Loc) const1538 bool SourceManager::isInMainFile(SourceLocation Loc) const {
1539   if (Loc.isInvalid()) return false;
1540 
1541   // Presumed locations are always for expansion points.
1542   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1543 
1544   const SLocEntry *Entry = getSLocEntryForFile(LocInfo.first);
1545   if (!Entry)
1546     return false;
1547 
1548   const SrcMgr::FileInfo &FI = Entry->getFile();
1549 
1550   // Check if there is a line directive for this location.
1551   if (FI.hasLineDirectives())
1552     if (const LineEntry *Entry =
1553             LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
1554       if (Entry->IncludeOffset)
1555         return false;
1556 
1557   return FI.getIncludeLoc().isInvalid();
1558 }
1559 
1560 /// The size of the SLocEntry that \p FID represents.
getFileIDSize(FileID FID) const1561 unsigned SourceManager::getFileIDSize(FileID FID) const {
1562   bool Invalid = false;
1563   const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1564   if (Invalid)
1565     return 0;
1566 
1567   int ID = FID.ID;
1568   unsigned NextOffset;
1569   if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
1570     NextOffset = getNextLocalOffset();
1571   else if (ID+1 == -1)
1572     NextOffset = MaxLoadedOffset;
1573   else
1574     NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
1575 
1576   return NextOffset - Entry.getOffset() - 1;
1577 }
1578 
1579 //===----------------------------------------------------------------------===//
1580 // Other miscellaneous methods.
1581 //===----------------------------------------------------------------------===//
1582 
1583 /// Get the source location for the given file:line:col triplet.
1584 ///
1585 /// If the source file is included multiple times, the source location will
1586 /// be based upon an arbitrary inclusion.
translateFileLineCol(const FileEntry * SourceFile,unsigned Line,unsigned Col) const1587 SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
1588                                                   unsigned Line,
1589                                                   unsigned Col) const {
1590   assert(SourceFile && "Null source file!");
1591   assert(Line && Col && "Line and column should start from 1!");
1592 
1593   FileID FirstFID = translateFile(SourceFile);
1594   return translateLineCol(FirstFID, Line, Col);
1595 }
1596 
1597 /// Get the FileID for the given file.
1598 ///
1599 /// If the source file is included multiple times, the FileID will be the
1600 /// first inclusion.
translateFile(const FileEntry * SourceFile) const1601 FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
1602   assert(SourceFile && "Null source file!");
1603 
1604   // First, check the main file ID, since it is common to look for a
1605   // location in the main file.
1606   if (MainFileID.isValid()) {
1607     bool Invalid = false;
1608     const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1609     if (Invalid)
1610       return FileID();
1611 
1612     if (MainSLoc.isFile()) {
1613       if (MainSLoc.getFile().getContentCache().OrigEntry == SourceFile)
1614         return MainFileID;
1615     }
1616   }
1617 
1618   // The location we're looking for isn't in the main file; look
1619   // through all of the local source locations.
1620   for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1621     const SLocEntry &SLoc = getLocalSLocEntry(I);
1622     if (SLoc.isFile() &&
1623         SLoc.getFile().getContentCache().OrigEntry == SourceFile)
1624       return FileID::get(I);
1625   }
1626 
1627   // If that still didn't help, try the modules.
1628   for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
1629     const SLocEntry &SLoc = getLoadedSLocEntry(I);
1630     if (SLoc.isFile() &&
1631         SLoc.getFile().getContentCache().OrigEntry == SourceFile)
1632       return FileID::get(-int(I) - 2);
1633   }
1634 
1635   return FileID();
1636 }
1637 
1638 /// Get the source location in \arg FID for the given line:col.
1639 /// Returns null location if \arg FID is not a file SLocEntry.
translateLineCol(FileID FID,unsigned Line,unsigned Col) const1640 SourceLocation SourceManager::translateLineCol(FileID FID,
1641                                                unsigned Line,
1642                                                unsigned Col) const {
1643   // Lines are used as a one-based index into a zero-based array. This assert
1644   // checks for possible buffer underruns.
1645   assert(Line && Col && "Line and column should start from 1!");
1646 
1647   if (FID.isInvalid())
1648     return SourceLocation();
1649 
1650   bool Invalid = false;
1651   const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1652   if (Invalid)
1653     return SourceLocation();
1654 
1655   if (!Entry.isFile())
1656     return SourceLocation();
1657 
1658   SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
1659 
1660   if (Line == 1 && Col == 1)
1661     return FileLoc;
1662 
1663   const ContentCache *Content = &Entry.getFile().getContentCache();
1664 
1665   // If this is the first use of line information for this buffer, compute the
1666   // SourceLineCache for it on demand.
1667   llvm::Optional<llvm::MemoryBufferRef> Buffer =
1668       Content->getBufferOrNone(Diag, getFileManager());
1669   if (!Buffer)
1670     return SourceLocation();
1671   if (!Content->SourceLineCache)
1672     Content->SourceLineCache =
1673         LineOffsetMapping::get(*Buffer, ContentCacheAlloc);
1674 
1675   if (Line > Content->SourceLineCache.size()) {
1676     unsigned Size = Buffer->getBufferSize();
1677     if (Size > 0)
1678       --Size;
1679     return FileLoc.getLocWithOffset(Size);
1680   }
1681 
1682   unsigned FilePos = Content->SourceLineCache[Line - 1];
1683   const char *Buf = Buffer->getBufferStart() + FilePos;
1684   unsigned BufLength = Buffer->getBufferSize() - FilePos;
1685   if (BufLength == 0)
1686     return FileLoc.getLocWithOffset(FilePos);
1687 
1688   unsigned i = 0;
1689 
1690   // Check that the given column is valid.
1691   while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1692     ++i;
1693   return FileLoc.getLocWithOffset(FilePos + i);
1694 }
1695 
1696 /// Compute a map of macro argument chunks to their expanded source
1697 /// location. Chunks that are not part of a macro argument will map to an
1698 /// invalid source location. e.g. if a file contains one macro argument at
1699 /// offset 100 with length 10, this is how the map will be formed:
1700 ///     0   -> SourceLocation()
1701 ///     100 -> Expanded macro arg location
1702 ///     110 -> SourceLocation()
computeMacroArgsCache(MacroArgsMap & MacroArgsCache,FileID FID) const1703 void SourceManager::computeMacroArgsCache(MacroArgsMap &MacroArgsCache,
1704                                           FileID FID) const {
1705   assert(FID.isValid());
1706 
1707   // Initially no macro argument chunk is present.
1708   MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
1709 
1710   int ID = FID.ID;
1711   while (true) {
1712     ++ID;
1713     // Stop if there are no more FileIDs to check.
1714     if (ID > 0) {
1715       if (unsigned(ID) >= local_sloc_entry_size())
1716         return;
1717     } else if (ID == -1) {
1718       return;
1719     }
1720 
1721     bool Invalid = false;
1722     const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);
1723     if (Invalid)
1724       return;
1725     if (Entry.isFile()) {
1726       auto& File = Entry.getFile();
1727       if (File.getFileCharacteristic() == C_User_ModuleMap ||
1728           File.getFileCharacteristic() == C_System_ModuleMap)
1729         continue;
1730 
1731       SourceLocation IncludeLoc = File.getIncludeLoc();
1732       bool IncludedInFID =
1733           (IncludeLoc.isValid() && isInFileID(IncludeLoc, FID)) ||
1734           // Predefined header doesn't have a valid include location in main
1735           // file, but any files created by it should still be skipped when
1736           // computing macro args expanded in the main file.
1737           (FID == MainFileID && Entry.getFile().getName() == "<built-in>");
1738       if (IncludedInFID) {
1739         // Skip the files/macros of the #include'd file, we only care about
1740         // macros that lexed macro arguments from our file.
1741         if (Entry.getFile().NumCreatedFIDs)
1742           ID += Entry.getFile().NumCreatedFIDs - 1 /*because of next ++ID*/;
1743         continue;
1744       } else if (IncludeLoc.isValid()) {
1745         // If file was included but not from FID, there is no more files/macros
1746         // that may be "contained" in this file.
1747         return;
1748       }
1749       continue;
1750     }
1751 
1752     const ExpansionInfo &ExpInfo = Entry.getExpansion();
1753 
1754     if (ExpInfo.getExpansionLocStart().isFileID()) {
1755       if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
1756         return; // No more files/macros that may be "contained" in this file.
1757     }
1758 
1759     if (!ExpInfo.isMacroArgExpansion())
1760       continue;
1761 
1762     associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1763                                  ExpInfo.getSpellingLoc(),
1764                                  SourceLocation::getMacroLoc(Entry.getOffset()),
1765                                  getFileIDSize(FileID::get(ID)));
1766   }
1767 }
1768 
associateFileChunkWithMacroArgExp(MacroArgsMap & MacroArgsCache,FileID FID,SourceLocation SpellLoc,SourceLocation ExpansionLoc,unsigned ExpansionLength) const1769 void SourceManager::associateFileChunkWithMacroArgExp(
1770                                          MacroArgsMap &MacroArgsCache,
1771                                          FileID FID,
1772                                          SourceLocation SpellLoc,
1773                                          SourceLocation ExpansionLoc,
1774                                          unsigned ExpansionLength) const {
1775   if (!SpellLoc.isFileID()) {
1776     unsigned SpellBeginOffs = SpellLoc.getOffset();
1777     unsigned SpellEndOffs = SpellBeginOffs + ExpansionLength;
1778 
1779     // The spelling range for this macro argument expansion can span multiple
1780     // consecutive FileID entries. Go through each entry contained in the
1781     // spelling range and if one is itself a macro argument expansion, recurse
1782     // and associate the file chunk that it represents.
1783 
1784     FileID SpellFID; // Current FileID in the spelling range.
1785     unsigned SpellRelativeOffs;
1786     std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);
1787     while (true) {
1788       const SLocEntry &Entry = getSLocEntry(SpellFID);
1789       unsigned SpellFIDBeginOffs = Entry.getOffset();
1790       unsigned SpellFIDSize = getFileIDSize(SpellFID);
1791       unsigned SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;
1792       const ExpansionInfo &Info = Entry.getExpansion();
1793       if (Info.isMacroArgExpansion()) {
1794         unsigned CurrSpellLength;
1795         if (SpellFIDEndOffs < SpellEndOffs)
1796           CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
1797         else
1798           CurrSpellLength = ExpansionLength;
1799         associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1800                       Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),
1801                       ExpansionLoc, CurrSpellLength);
1802       }
1803 
1804       if (SpellFIDEndOffs >= SpellEndOffs)
1805         return; // we covered all FileID entries in the spelling range.
1806 
1807       // Move to the next FileID entry in the spelling range.
1808       unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
1809       ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);
1810       ExpansionLength -= advance;
1811       ++SpellFID.ID;
1812       SpellRelativeOffs = 0;
1813     }
1814   }
1815 
1816   assert(SpellLoc.isFileID());
1817 
1818   unsigned BeginOffs;
1819   if (!isInFileID(SpellLoc, FID, &BeginOffs))
1820     return;
1821 
1822   unsigned EndOffs = BeginOffs + ExpansionLength;
1823 
1824   // Add a new chunk for this macro argument. A previous macro argument chunk
1825   // may have been lexed again, so e.g. if the map is
1826   //     0   -> SourceLocation()
1827   //     100 -> Expanded loc #1
1828   //     110 -> SourceLocation()
1829   // and we found a new macro FileID that lexed from offset 105 with length 3,
1830   // the new map will be:
1831   //     0   -> SourceLocation()
1832   //     100 -> Expanded loc #1
1833   //     105 -> Expanded loc #2
1834   //     108 -> Expanded loc #1
1835   //     110 -> SourceLocation()
1836   //
1837   // Since re-lexed macro chunks will always be the same size or less of
1838   // previous chunks, we only need to find where the ending of the new macro
1839   // chunk is mapped to and update the map with new begin/end mappings.
1840 
1841   MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
1842   --I;
1843   SourceLocation EndOffsMappedLoc = I->second;
1844   MacroArgsCache[BeginOffs] = ExpansionLoc;
1845   MacroArgsCache[EndOffs] = EndOffsMappedLoc;
1846 }
1847 
1848 /// If \arg Loc points inside a function macro argument, the returned
1849 /// location will be the macro location in which the argument was expanded.
1850 /// If a macro argument is used multiple times, the expanded location will
1851 /// be at the first expansion of the argument.
1852 /// e.g.
1853 ///   MY_MACRO(foo);
1854 ///             ^
1855 /// Passing a file location pointing at 'foo', will yield a macro location
1856 /// where 'foo' was expanded into.
1857 SourceLocation
getMacroArgExpandedLocation(SourceLocation Loc) const1858 SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
1859   if (Loc.isInvalid() || !Loc.isFileID())
1860     return Loc;
1861 
1862   FileID FID;
1863   unsigned Offset;
1864   std::tie(FID, Offset) = getDecomposedLoc(Loc);
1865   if (FID.isInvalid())
1866     return Loc;
1867 
1868   std::unique_ptr<MacroArgsMap> &MacroArgsCache = MacroArgsCacheMap[FID];
1869   if (!MacroArgsCache) {
1870     MacroArgsCache = std::make_unique<MacroArgsMap>();
1871     computeMacroArgsCache(*MacroArgsCache, FID);
1872   }
1873 
1874   assert(!MacroArgsCache->empty());
1875   MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
1876   // In case every element in MacroArgsCache is greater than Offset we can't
1877   // decrement the iterator.
1878   if (I == MacroArgsCache->begin())
1879     return Loc;
1880 
1881   --I;
1882 
1883   unsigned MacroArgBeginOffs = I->first;
1884   SourceLocation MacroArgExpandedLoc = I->second;
1885   if (MacroArgExpandedLoc.isValid())
1886     return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
1887 
1888   return Loc;
1889 }
1890 
1891 std::pair<FileID, unsigned>
getDecomposedIncludedLoc(FileID FID) const1892 SourceManager::getDecomposedIncludedLoc(FileID FID) const {
1893   if (FID.isInvalid())
1894     return std::make_pair(FileID(), 0);
1895 
1896   // Uses IncludedLocMap to retrieve/cache the decomposed loc.
1897 
1898   using DecompTy = std::pair<FileID, unsigned>;
1899   auto InsertOp = IncludedLocMap.try_emplace(FID);
1900   DecompTy &DecompLoc = InsertOp.first->second;
1901   if (!InsertOp.second)
1902     return DecompLoc; // already in map.
1903 
1904   SourceLocation UpperLoc;
1905   bool Invalid = false;
1906   const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1907   if (!Invalid) {
1908     if (Entry.isExpansion())
1909       UpperLoc = Entry.getExpansion().getExpansionLocStart();
1910     else
1911       UpperLoc = Entry.getFile().getIncludeLoc();
1912   }
1913 
1914   if (UpperLoc.isValid())
1915     DecompLoc = getDecomposedLoc(UpperLoc);
1916 
1917   return DecompLoc;
1918 }
1919 
1920 /// Given a decomposed source location, move it up the include/expansion stack
1921 /// to the parent source location.  If this is possible, return the decomposed
1922 /// version of the parent in Loc and return false.  If Loc is the top-level
1923 /// entry, return true and don't modify it.
MoveUpIncludeHierarchy(std::pair<FileID,unsigned> & Loc,const SourceManager & SM)1924 static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1925                                    const SourceManager &SM) {
1926   std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
1927   if (UpperLoc.first.isInvalid())
1928     return true; // We reached the top.
1929 
1930   Loc = UpperLoc;
1931   return false;
1932 }
1933 
1934 /// Return the cache entry for comparing the given file IDs
1935 /// for isBeforeInTranslationUnit.
getInBeforeInTUCache(FileID LFID,FileID RFID) const1936 InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
1937                                                             FileID RFID) const {
1938   // This is a magic number for limiting the cache size.  It was experimentally
1939   // derived from a small Objective-C project (where the cache filled
1940   // out to ~250 items).  We can make it larger if necessary.
1941   enum { MagicCacheSize = 300 };
1942   IsBeforeInTUCacheKey Key(LFID, RFID);
1943 
1944   // If the cache size isn't too large, do a lookup and if necessary default
1945   // construct an entry.  We can then return it to the caller for direct
1946   // use.  When they update the value, the cache will get automatically
1947   // updated as well.
1948   if (IBTUCache.size() < MagicCacheSize)
1949     return IBTUCache[Key];
1950 
1951   // Otherwise, do a lookup that will not construct a new value.
1952   InBeforeInTUCache::iterator I = IBTUCache.find(Key);
1953   if (I != IBTUCache.end())
1954     return I->second;
1955 
1956   // Fall back to the overflow value.
1957   return IBTUCacheOverflow;
1958 }
1959 
1960 /// Determines the order of 2 source locations in the translation unit.
1961 ///
1962 /// \returns true if LHS source location comes before RHS, false otherwise.
isBeforeInTranslationUnit(SourceLocation LHS,SourceLocation RHS) const1963 bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1964                                               SourceLocation RHS) const {
1965   assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1966   if (LHS == RHS)
1967     return false;
1968 
1969   std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1970   std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
1971 
1972   // getDecomposedLoc may have failed to return a valid FileID because, e.g. it
1973   // is a serialized one referring to a file that was removed after we loaded
1974   // the PCH.
1975   if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
1976     return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
1977 
1978   std::pair<bool, bool> InSameTU = isInTheSameTranslationUnit(LOffs, ROffs);
1979   if (InSameTU.first)
1980     return InSameTU.second;
1981 
1982   // If we arrived here, the location is either in a built-ins buffer or
1983   // associated with global inline asm. PR5662 and PR22576 are examples.
1984 
1985   StringRef LB = getBufferOrFake(LOffs.first).getBufferIdentifier();
1986   StringRef RB = getBufferOrFake(ROffs.first).getBufferIdentifier();
1987   bool LIsBuiltins = LB == "<built-in>";
1988   bool RIsBuiltins = RB == "<built-in>";
1989   // Sort built-in before non-built-in.
1990   if (LIsBuiltins || RIsBuiltins) {
1991     if (LIsBuiltins != RIsBuiltins)
1992       return LIsBuiltins;
1993     // Both are in built-in buffers, but from different files. We just claim that
1994     // lower IDs come first.
1995     return LOffs.first < ROffs.first;
1996   }
1997   bool LIsAsm = LB == "<inline asm>";
1998   bool RIsAsm = RB == "<inline asm>";
1999   // Sort assembler after built-ins, but before the rest.
2000   if (LIsAsm || RIsAsm) {
2001     if (LIsAsm != RIsAsm)
2002       return RIsAsm;
2003     assert(LOffs.first == ROffs.first);
2004     return false;
2005   }
2006   bool LIsScratch = LB == "<scratch space>";
2007   bool RIsScratch = RB == "<scratch space>";
2008   // Sort scratch after inline asm, but before the rest.
2009   if (LIsScratch || RIsScratch) {
2010     if (LIsScratch != RIsScratch)
2011       return LIsScratch;
2012     return LOffs.second < ROffs.second;
2013   }
2014   llvm_unreachable("Unsortable locations found");
2015 }
2016 
isInTheSameTranslationUnit(std::pair<FileID,unsigned> & LOffs,std::pair<FileID,unsigned> & ROffs) const2017 std::pair<bool, bool> SourceManager::isInTheSameTranslationUnit(
2018     std::pair<FileID, unsigned> &LOffs,
2019     std::pair<FileID, unsigned> &ROffs) const {
2020   // If the source locations are in the same file, just compare offsets.
2021   if (LOffs.first == ROffs.first)
2022     return std::make_pair(true, LOffs.second < ROffs.second);
2023 
2024   // If we are comparing a source location with multiple locations in the same
2025   // file, we get a big win by caching the result.
2026   InBeforeInTUCacheEntry &IsBeforeInTUCache =
2027     getInBeforeInTUCache(LOffs.first, ROffs.first);
2028 
2029   // If we are comparing a source location with multiple locations in the same
2030   // file, we get a big win by caching the result.
2031   if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
2032     return std::make_pair(
2033         true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2034 
2035   // Okay, we missed in the cache, start updating the cache for this query.
2036   IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
2037                           /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID);
2038 
2039   // We need to find the common ancestor. The only way of doing this is to
2040   // build the complete include chain for one and then walking up the chain
2041   // of the other looking for a match.
2042   // We use a map from FileID to Offset to store the chain. Easier than writing
2043   // a custom set hash info that only depends on the first part of a pair.
2044   using LocSet = llvm::SmallDenseMap<FileID, unsigned, 16>;
2045   LocSet LChain;
2046   do {
2047     LChain.insert(LOffs);
2048     // We catch the case where LOffs is in a file included by ROffs and
2049     // quit early. The other way round unfortunately remains suboptimal.
2050   } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
2051   LocSet::iterator I;
2052   while((I = LChain.find(ROffs.first)) == LChain.end()) {
2053     if (MoveUpIncludeHierarchy(ROffs, *this))
2054       break; // Met at topmost file.
2055   }
2056   if (I != LChain.end())
2057     LOffs = *I;
2058 
2059   // If we exited because we found a nearest common ancestor, compare the
2060   // locations within the common file and cache them.
2061   if (LOffs.first == ROffs.first) {
2062     IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
2063     return std::make_pair(
2064         true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2065   }
2066   // Clear the lookup cache, it depends on a common location.
2067   IsBeforeInTUCache.clear();
2068   return std::make_pair(false, false);
2069 }
2070 
PrintStats() const2071 void SourceManager::PrintStats() const {
2072   llvm::errs() << "\n*** Source Manager Stats:\n";
2073   llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
2074                << " mem buffers mapped.\n";
2075   llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
2076                << llvm::capacity_in_bytes(LocalSLocEntryTable)
2077                << " bytes of capacity), "
2078                << NextLocalOffset << "B of Sloc address space used.\n";
2079   llvm::errs() << LoadedSLocEntryTable.size()
2080                << " loaded SLocEntries allocated, "
2081                << MaxLoadedOffset - CurrentLoadedOffset
2082                << "B of Sloc address space used.\n";
2083 
2084   unsigned NumLineNumsComputed = 0;
2085   unsigned NumFileBytesMapped = 0;
2086   for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
2087     NumLineNumsComputed += bool(I->second->SourceLineCache);
2088     NumFileBytesMapped  += I->second->getSizeBytesMapped();
2089   }
2090   unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
2091 
2092   llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
2093                << NumLineNumsComputed << " files with line #'s computed, "
2094                << NumMacroArgsComputed << " files with macro args computed.\n";
2095   llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
2096                << NumBinaryProbes << " binary.\n";
2097 }
2098 
dump() const2099 LLVM_DUMP_METHOD void SourceManager::dump() const {
2100   llvm::raw_ostream &out = llvm::errs();
2101 
2102   auto DumpSLocEntry = [&](int ID, const SrcMgr::SLocEntry &Entry,
2103                            llvm::Optional<unsigned> NextStart) {
2104     out << "SLocEntry <FileID " << ID << "> " << (Entry.isFile() ? "file" : "expansion")
2105         << " <SourceLocation " << Entry.getOffset() << ":";
2106     if (NextStart)
2107       out << *NextStart << ">\n";
2108     else
2109       out << "???\?>\n";
2110     if (Entry.isFile()) {
2111       auto &FI = Entry.getFile();
2112       if (FI.NumCreatedFIDs)
2113         out << "  covers <FileID " << ID << ":" << int(ID + FI.NumCreatedFIDs)
2114             << ">\n";
2115       if (FI.getIncludeLoc().isValid())
2116         out << "  included from " << FI.getIncludeLoc().getOffset() << "\n";
2117       auto &CC = FI.getContentCache();
2118       out << "  for " << (CC.OrigEntry ? CC.OrigEntry->getName() : "<none>")
2119           << "\n";
2120       if (CC.BufferOverridden)
2121         out << "  contents overridden\n";
2122       if (CC.ContentsEntry != CC.OrigEntry) {
2123         out << "  contents from "
2124             << (CC.ContentsEntry ? CC.ContentsEntry->getName() : "<none>")
2125             << "\n";
2126       }
2127     } else {
2128       auto &EI = Entry.getExpansion();
2129       out << "  spelling from " << EI.getSpellingLoc().getOffset() << "\n";
2130       out << "  macro " << (EI.isMacroArgExpansion() ? "arg" : "body")
2131           << " range <" << EI.getExpansionLocStart().getOffset() << ":"
2132           << EI.getExpansionLocEnd().getOffset() << ">\n";
2133     }
2134   };
2135 
2136   // Dump local SLocEntries.
2137   for (unsigned ID = 0, NumIDs = LocalSLocEntryTable.size(); ID != NumIDs; ++ID) {
2138     DumpSLocEntry(ID, LocalSLocEntryTable[ID],
2139                   ID == NumIDs - 1 ? NextLocalOffset
2140                                    : LocalSLocEntryTable[ID + 1].getOffset());
2141   }
2142   // Dump loaded SLocEntries.
2143   llvm::Optional<unsigned> NextStart;
2144   for (unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
2145     int ID = -(int)Index - 2;
2146     if (SLocEntryLoaded[Index]) {
2147       DumpSLocEntry(ID, LoadedSLocEntryTable[Index], NextStart);
2148       NextStart = LoadedSLocEntryTable[Index].getOffset();
2149     } else {
2150       NextStart = None;
2151     }
2152   }
2153 }
2154 
2155 ExternalSLocEntrySource::~ExternalSLocEntrySource() = default;
2156 
2157 /// Return the amount of memory used by memory buffers, breaking down
2158 /// by heap-backed versus mmap'ed memory.
getMemoryBufferSizes() const2159 SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
2160   size_t malloc_bytes = 0;
2161   size_t mmap_bytes = 0;
2162 
2163   for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
2164     if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
2165       switch (MemBufferInfos[i]->getMemoryBufferKind()) {
2166         case llvm::MemoryBuffer::MemoryBuffer_MMap:
2167           mmap_bytes += sized_mapped;
2168           break;
2169         case llvm::MemoryBuffer::MemoryBuffer_Malloc:
2170           malloc_bytes += sized_mapped;
2171           break;
2172       }
2173 
2174   return MemoryBufferSizes(malloc_bytes, mmap_bytes);
2175 }
2176 
getDataStructureSizes() const2177 size_t SourceManager::getDataStructureSizes() const {
2178   size_t size = llvm::capacity_in_bytes(MemBufferInfos)
2179     + llvm::capacity_in_bytes(LocalSLocEntryTable)
2180     + llvm::capacity_in_bytes(LoadedSLocEntryTable)
2181     + llvm::capacity_in_bytes(SLocEntryLoaded)
2182     + llvm::capacity_in_bytes(FileInfos);
2183 
2184   if (OverriddenFilesInfo)
2185     size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);
2186 
2187   return size;
2188 }
2189 
SourceManagerForFile(StringRef FileName,StringRef Content)2190 SourceManagerForFile::SourceManagerForFile(StringRef FileName,
2191                                            StringRef Content) {
2192   // This is referenced by `FileMgr` and will be released by `FileMgr` when it
2193   // is deleted.
2194   IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
2195       new llvm::vfs::InMemoryFileSystem);
2196   InMemoryFileSystem->addFile(
2197       FileName, 0,
2198       llvm::MemoryBuffer::getMemBuffer(Content, FileName,
2199                                        /*RequiresNullTerminator=*/false));
2200   // This is passed to `SM` as reference, so the pointer has to be referenced
2201   // in `Environment` so that `FileMgr` can out-live this function scope.
2202   FileMgr =
2203       std::make_unique<FileManager>(FileSystemOptions(), InMemoryFileSystem);
2204   // This is passed to `SM` as reference, so the pointer has to be referenced
2205   // by `Environment` due to the same reason above.
2206   Diagnostics = std::make_unique<DiagnosticsEngine>(
2207       IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
2208       new DiagnosticOptions);
2209   SourceMgr = std::make_unique<SourceManager>(*Diagnostics, *FileMgr);
2210   FileID ID = SourceMgr->createFileID(*FileMgr->getFile(FileName),
2211                                       SourceLocation(), clang::SrcMgr::C_User);
2212   assert(ID.isValid());
2213   SourceMgr->setMainFileID(ID);
2214 }
2215