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