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