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