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