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