xref: /llvm-project/clang/lib/Basic/SourceManager.cpp (revision 120992ad81034687bc9fe76f6a76b60d6c4539b0)
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/SourceManagerInternals.h"
16 #include "clang/Basic/Diagnostic.h"
17 #include "clang/Basic/FileManager.h"
18 #include "llvm/ADT/StringSwitch.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/Support/Compiler.h"
21 #include "llvm/Support/MemoryBuffer.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/Support/Path.h"
24 #include <algorithm>
25 #include <string>
26 #include <cstring>
27 #include <sys/stat.h>
28 
29 using namespace clang;
30 using namespace SrcMgr;
31 using llvm::MemoryBuffer;
32 
33 //===----------------------------------------------------------------------===//
34 // SourceManager Helper Classes
35 //===----------------------------------------------------------------------===//
36 
37 ContentCache::~ContentCache() {
38   if (shouldFreeBuffer())
39     delete Buffer.getPointer();
40 }
41 
42 /// getSizeBytesMapped - Returns the number of bytes actually mapped for this
43 /// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
44 unsigned ContentCache::getSizeBytesMapped() const {
45   return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
46 }
47 
48 /// Returns the kind of memory used to back the memory buffer for
49 /// this content cache.  This is used for performance analysis.
50 llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
51   assert(Buffer.getPointer());
52 
53   // Should be unreachable, but keep for sanity.
54   if (!Buffer.getPointer())
55     return llvm::MemoryBuffer::MemoryBuffer_Malloc;
56 
57   const llvm::MemoryBuffer *buf = Buffer.getPointer();
58   return buf->getBufferKind();
59 }
60 
61 /// getSize - Returns the size of the content encapsulated by this ContentCache.
62 ///  This can be the size of the source file or the size of an arbitrary
63 ///  scratch buffer.  If the ContentCache encapsulates a source file, that
64 ///  file is not lazily brought in from disk to satisfy this query.
65 unsigned ContentCache::getSize() const {
66   return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
67                              : (unsigned) ContentsEntry->getSize();
68 }
69 
70 void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B,
71                                  bool DoNotFree) {
72   assert(B != Buffer.getPointer());
73 
74   if (shouldFreeBuffer())
75     delete Buffer.getPointer();
76   Buffer.setPointer(B);
77   Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
78 }
79 
80 const llvm::MemoryBuffer *ContentCache::getBuffer(Diagnostic &Diag,
81                                                   const SourceManager &SM,
82                                                   SourceLocation Loc,
83                                                   bool *Invalid) const {
84   // Lazily create the Buffer for ContentCaches that wrap files.  If we already
85   // computed it, just return what we have.
86   if (Buffer.getPointer() || ContentsEntry == 0) {
87     if (Invalid)
88       *Invalid = isBufferInvalid();
89 
90     return Buffer.getPointer();
91   }
92 
93   std::string ErrorStr;
94   Buffer.setPointer(SM.getFileManager().getBufferForFile(ContentsEntry, &ErrorStr));
95 
96   // If we were unable to open the file, then we are in an inconsistent
97   // situation where the content cache referenced a file which no longer
98   // exists. Most likely, we were using a stat cache with an invalid entry but
99   // the file could also have been removed during processing. Since we can't
100   // really deal with this situation, just create an empty buffer.
101   //
102   // FIXME: This is definitely not ideal, but our immediate clients can't
103   // currently handle returning a null entry here. Ideally we should detect
104   // that we are in an inconsistent situation and error out as quickly as
105   // possible.
106   if (!Buffer.getPointer()) {
107     const StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
108     Buffer.setPointer(MemoryBuffer::getNewMemBuffer(ContentsEntry->getSize(),
109                                                     "<invalid>"));
110     char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart());
111     for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
112       Ptr[i] = FillStr[i % FillStr.size()];
113 
114     if (Diag.isDiagnosticInFlight())
115       Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
116                                 ContentsEntry->getName(), ErrorStr);
117     else
118       Diag.Report(Loc, diag::err_cannot_open_file)
119         << ContentsEntry->getName() << ErrorStr;
120 
121     Buffer.setInt(Buffer.getInt() | InvalidFlag);
122 
123     if (Invalid) *Invalid = true;
124     return Buffer.getPointer();
125   }
126 
127   // Check that the file's size is the same as in the file entry (which may
128   // have come from a stat cache).
129   if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) {
130     if (Diag.isDiagnosticInFlight())
131       Diag.SetDelayedDiagnostic(diag::err_file_modified,
132                                 ContentsEntry->getName());
133     else
134       Diag.Report(Loc, diag::err_file_modified)
135         << ContentsEntry->getName();
136 
137     Buffer.setInt(Buffer.getInt() | InvalidFlag);
138     if (Invalid) *Invalid = true;
139     return Buffer.getPointer();
140   }
141 
142   // If the buffer is valid, check to see if it has a UTF Byte Order Mark
143   // (BOM).  We only support UTF-8 with and without a BOM right now.  See
144   // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
145   StringRef BufStr = Buffer.getPointer()->getBuffer();
146   const char *InvalidBOM = llvm::StringSwitch<const char *>(BufStr)
147     .StartsWith("\xFE\xFF", "UTF-16 (BE)")
148     .StartsWith("\xFF\xFE", "UTF-16 (LE)")
149     .StartsWith("\x00\x00\xFE\xFF", "UTF-32 (BE)")
150     .StartsWith("\xFF\xFE\x00\x00", "UTF-32 (LE)")
151     .StartsWith("\x2B\x2F\x76", "UTF-7")
152     .StartsWith("\xF7\x64\x4C", "UTF-1")
153     .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
154     .StartsWith("\x0E\xFE\xFF", "SDSU")
155     .StartsWith("\xFB\xEE\x28", "BOCU-1")
156     .StartsWith("\x84\x31\x95\x33", "GB-18030")
157     .Default(0);
158 
159   if (InvalidBOM) {
160     Diag.Report(Loc, diag::err_unsupported_bom)
161       << InvalidBOM << ContentsEntry->getName();
162     Buffer.setInt(Buffer.getInt() | InvalidFlag);
163   }
164 
165   if (Invalid)
166     *Invalid = isBufferInvalid();
167 
168   return Buffer.getPointer();
169 }
170 
171 unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
172   // Look up the filename in the string table, returning the pre-existing value
173   // if it exists.
174   llvm::StringMapEntry<unsigned> &Entry =
175     FilenameIDs.GetOrCreateValue(Name, ~0U);
176   if (Entry.getValue() != ~0U)
177     return Entry.getValue();
178 
179   // Otherwise, assign this the next available ID.
180   Entry.setValue(FilenamesByID.size());
181   FilenamesByID.push_back(&Entry);
182   return FilenamesByID.size()-1;
183 }
184 
185 /// AddLineNote - Add a line note to the line table that indicates that there
186 /// is a #line at the specified FID/Offset location which changes the presumed
187 /// location to LineNo/FilenameID.
188 void LineTableInfo::AddLineNote(int FID, unsigned Offset,
189                                 unsigned LineNo, int FilenameID) {
190   std::vector<LineEntry> &Entries = LineEntries[FID];
191 
192   assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
193          "Adding line entries out of order!");
194 
195   SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
196   unsigned IncludeOffset = 0;
197 
198   if (!Entries.empty()) {
199     // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
200     // that we are still in "foo.h".
201     if (FilenameID == -1)
202       FilenameID = Entries.back().FilenameID;
203 
204     // If we are after a line marker that switched us to system header mode, or
205     // that set #include information, preserve it.
206     Kind = Entries.back().FileKind;
207     IncludeOffset = Entries.back().IncludeOffset;
208   }
209 
210   Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
211                                    IncludeOffset));
212 }
213 
214 /// AddLineNote This is the same as the previous version of AddLineNote, but is
215 /// used for GNU line markers.  If EntryExit is 0, then this doesn't change the
216 /// presumed #include stack.  If it is 1, this is a file entry, if it is 2 then
217 /// this is a file exit.  FileKind specifies whether this is a system header or
218 /// extern C system header.
219 void LineTableInfo::AddLineNote(int FID, unsigned Offset,
220                                 unsigned LineNo, int FilenameID,
221                                 unsigned EntryExit,
222                                 SrcMgr::CharacteristicKind FileKind) {
223   assert(FilenameID != -1 && "Unspecified filename should use other accessor");
224 
225   std::vector<LineEntry> &Entries = LineEntries[FID];
226 
227   assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
228          "Adding line entries out of order!");
229 
230   unsigned IncludeOffset = 0;
231   if (EntryExit == 0) {  // No #include stack change.
232     IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
233   } else if (EntryExit == 1) {
234     IncludeOffset = Offset-1;
235   } else if (EntryExit == 2) {
236     assert(!Entries.empty() && Entries.back().IncludeOffset &&
237        "PPDirectives should have caught case when popping empty include stack");
238 
239     // Get the include loc of the last entries' include loc as our include loc.
240     IncludeOffset = 0;
241     if (const LineEntry *PrevEntry =
242           FindNearestLineEntry(FID, Entries.back().IncludeOffset))
243       IncludeOffset = PrevEntry->IncludeOffset;
244   }
245 
246   Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
247                                    IncludeOffset));
248 }
249 
250 
251 /// FindNearestLineEntry - Find the line entry nearest to FID that is before
252 /// it.  If there is no line entry before Offset in FID, return null.
253 const LineEntry *LineTableInfo::FindNearestLineEntry(int FID,
254                                                      unsigned Offset) {
255   const std::vector<LineEntry> &Entries = LineEntries[FID];
256   assert(!Entries.empty() && "No #line entries for this FID after all!");
257 
258   // It is very common for the query to be after the last #line, check this
259   // first.
260   if (Entries.back().FileOffset <= Offset)
261     return &Entries.back();
262 
263   // Do a binary search to find the maximal element that is still before Offset.
264   std::vector<LineEntry>::const_iterator I =
265     std::upper_bound(Entries.begin(), Entries.end(), Offset);
266   if (I == Entries.begin()) return 0;
267   return &*--I;
268 }
269 
270 /// \brief Add a new line entry that has already been encoded into
271 /// the internal representation of the line table.
272 void LineTableInfo::AddEntry(int FID,
273                              const std::vector<LineEntry> &Entries) {
274   LineEntries[FID] = Entries;
275 }
276 
277 /// getLineTableFilenameID - Return the uniqued ID for the specified filename.
278 ///
279 unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
280   if (LineTable == 0)
281     LineTable = new LineTableInfo();
282   return LineTable->getLineTableFilenameID(Name);
283 }
284 
285 
286 /// AddLineNote - Add a line note to the line table for the FileID and offset
287 /// specified by Loc.  If FilenameID is -1, it is considered to be
288 /// unspecified.
289 void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
290                                 int FilenameID) {
291   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
292 
293   bool Invalid = false;
294   const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
295   if (!Entry.isFile() || Invalid)
296     return;
297 
298   const SrcMgr::FileInfo &FileInfo = Entry.getFile();
299 
300   // Remember that this file has #line directives now if it doesn't already.
301   const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
302 
303   if (LineTable == 0)
304     LineTable = new LineTableInfo();
305   LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID);
306 }
307 
308 /// AddLineNote - Add a GNU line marker to the line table.
309 void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
310                                 int FilenameID, bool IsFileEntry,
311                                 bool IsFileExit, bool IsSystemHeader,
312                                 bool IsExternCHeader) {
313   // If there is no filename and no flags, this is treated just like a #line,
314   // which does not change the flags of the previous line marker.
315   if (FilenameID == -1) {
316     assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
317            "Can't set flags without setting the filename!");
318     return AddLineNote(Loc, LineNo, FilenameID);
319   }
320 
321   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
322 
323   bool Invalid = false;
324   const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
325   if (!Entry.isFile() || Invalid)
326     return;
327 
328   const SrcMgr::FileInfo &FileInfo = Entry.getFile();
329 
330   // Remember that this file has #line directives now if it doesn't already.
331   const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
332 
333   if (LineTable == 0)
334     LineTable = new LineTableInfo();
335 
336   SrcMgr::CharacteristicKind FileKind;
337   if (IsExternCHeader)
338     FileKind = SrcMgr::C_ExternCSystem;
339   else if (IsSystemHeader)
340     FileKind = SrcMgr::C_System;
341   else
342     FileKind = SrcMgr::C_User;
343 
344   unsigned EntryExit = 0;
345   if (IsFileEntry)
346     EntryExit = 1;
347   else if (IsFileExit)
348     EntryExit = 2;
349 
350   LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID,
351                          EntryExit, FileKind);
352 }
353 
354 LineTableInfo &SourceManager::getLineTable() {
355   if (LineTable == 0)
356     LineTable = new LineTableInfo();
357   return *LineTable;
358 }
359 
360 //===----------------------------------------------------------------------===//
361 // Private 'Create' methods.
362 //===----------------------------------------------------------------------===//
363 
364 SourceManager::SourceManager(Diagnostic &Diag, FileManager &FileMgr)
365   : Diag(Diag), FileMgr(FileMgr), OverridenFilesKeepOriginalName(true),
366     ExternalSLocEntries(0), LineTable(0), NumLinearScans(0),
367     NumBinaryProbes(0), FakeBufferForRecovery(0) {
368   clearIDTables();
369   Diag.setSourceManager(this);
370 }
371 
372 SourceManager::~SourceManager() {
373   delete LineTable;
374 
375   // Delete FileEntry objects corresponding to content caches.  Since the actual
376   // content cache objects are bump pointer allocated, we just have to run the
377   // dtors, but we call the deallocate method for completeness.
378   for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
379     MemBufferInfos[i]->~ContentCache();
380     ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
381   }
382   for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
383        I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
384     I->second->~ContentCache();
385     ContentCacheAlloc.Deallocate(I->second);
386   }
387 
388   delete FakeBufferForRecovery;
389 }
390 
391 void SourceManager::clearIDTables() {
392   MainFileID = FileID();
393   LocalSLocEntryTable.clear();
394   LoadedSLocEntryTable.clear();
395   SLocEntryLoaded.clear();
396   LastLineNoFileIDQuery = FileID();
397   LastLineNoContentCache = 0;
398   LastFileIDLookup = FileID();
399 
400   if (LineTable)
401     LineTable->clear();
402 
403   // Use up FileID #0 as an invalid expansion.
404   NextLocalOffset = 0;
405   // The highest possible offset is 2^31-1, so CurrentLoadedOffset starts at
406   // 2^31.
407   CurrentLoadedOffset = 1U << 31U;
408   createExpansionLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
409 }
410 
411 /// getOrCreateContentCache - Create or return a cached ContentCache for the
412 /// specified file.
413 const ContentCache *
414 SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) {
415   assert(FileEnt && "Didn't specify a file entry to use?");
416 
417   // Do we already have information about this file?
418   ContentCache *&Entry = FileInfos[FileEnt];
419   if (Entry) return Entry;
420 
421   // Nope, create a new Cache entry.  Make sure it is at least 8-byte aligned
422   // so that FileInfo can use the low 3 bits of the pointer for its own
423   // nefarious purposes.
424   unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
425   EntryAlign = std::max(8U, EntryAlign);
426   Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
427 
428   // If the file contents are overridden with contents from another file,
429   // pass that file to ContentCache.
430   llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
431       overI = OverriddenFiles.find(FileEnt);
432   if (overI == OverriddenFiles.end())
433     new (Entry) ContentCache(FileEnt);
434   else
435     new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
436                                                             : overI->second,
437                              overI->second);
438 
439   return Entry;
440 }
441 
442 
443 /// createMemBufferContentCache - Create a new ContentCache for the specified
444 ///  memory buffer.  This does no caching.
445 const ContentCache*
446 SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
447   // Add a new ContentCache to the MemBufferInfos list and return it.  Make sure
448   // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of
449   // the pointer for its own nefarious purposes.
450   unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
451   EntryAlign = std::max(8U, EntryAlign);
452   ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
453   new (Entry) ContentCache();
454   MemBufferInfos.push_back(Entry);
455   Entry->setBuffer(Buffer);
456   return Entry;
457 }
458 
459 std::pair<int, unsigned>
460 SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
461                                          unsigned TotalSize) {
462   assert(ExternalSLocEntries && "Don't have an external sloc source");
463   LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
464   SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
465   CurrentLoadedOffset -= TotalSize;
466   assert(CurrentLoadedOffset >= NextLocalOffset && "Out of source locations");
467   int ID = LoadedSLocEntryTable.size();
468   return std::make_pair(-ID - 1, CurrentLoadedOffset);
469 }
470 
471 /// \brief As part of recovering from missing or changed content, produce a
472 /// fake, non-empty buffer.
473 const llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const {
474   if (!FakeBufferForRecovery)
475     FakeBufferForRecovery
476       = llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
477 
478   return FakeBufferForRecovery;
479 }
480 
481 //===----------------------------------------------------------------------===//
482 // Methods to create new FileID's and macro expansions.
483 //===----------------------------------------------------------------------===//
484 
485 /// createFileID - Create a new FileID for the specified ContentCache and
486 /// include position.  This works regardless of whether the ContentCache
487 /// corresponds to a file or some other input source.
488 FileID SourceManager::createFileID(const ContentCache *File,
489                                    SourceLocation IncludePos,
490                                    SrcMgr::CharacteristicKind FileCharacter,
491                                    int LoadedID, unsigned LoadedOffset) {
492   if (LoadedID < 0) {
493     assert(LoadedID != -1 && "Loading sentinel FileID");
494     unsigned Index = unsigned(-LoadedID) - 2;
495     assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
496     assert(!SLocEntryLoaded[Index] && "FileID already loaded");
497     LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset,
498         FileInfo::get(IncludePos, File, FileCharacter));
499     SLocEntryLoaded[Index] = true;
500     return FileID::get(LoadedID);
501   }
502   LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset,
503                                                FileInfo::get(IncludePos, File,
504                                                              FileCharacter)));
505   unsigned FileSize = File->getSize();
506   assert(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
507          NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset &&
508          "Ran out of source locations!");
509   // We do a +1 here because we want a SourceLocation that means "the end of the
510   // file", e.g. for the "no newline at the end of the file" diagnostic.
511   NextLocalOffset += FileSize + 1;
512 
513   // Set LastFileIDLookup to the newly created file.  The next getFileID call is
514   // almost guaranteed to be from that file.
515   FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
516   return LastFileIDLookup = FID;
517 }
518 
519 SourceLocation
520 SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc,
521                                           SourceLocation ExpansionLoc,
522                                           unsigned TokLength) {
523   ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
524                                                         ExpansionLoc);
525   return createExpansionLocImpl(Info, TokLength);
526 }
527 
528 SourceLocation
529 SourceManager::createExpansionLoc(SourceLocation SpellingLoc,
530                                   SourceLocation ExpansionLocStart,
531                                   SourceLocation ExpansionLocEnd,
532                                   unsigned TokLength,
533                                   int LoadedID,
534                                   unsigned LoadedOffset) {
535   ExpansionInfo Info = ExpansionInfo::create(SpellingLoc, ExpansionLocStart,
536                                              ExpansionLocEnd);
537   return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset);
538 }
539 
540 SourceLocation
541 SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
542                                       unsigned TokLength,
543                                       int LoadedID,
544                                       unsigned LoadedOffset) {
545   if (LoadedID < 0) {
546     assert(LoadedID != -1 && "Loading sentinel FileID");
547     unsigned Index = unsigned(-LoadedID) - 2;
548     assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
549     assert(!SLocEntryLoaded[Index] && "FileID already loaded");
550     LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
551     SLocEntryLoaded[Index] = true;
552     return SourceLocation::getMacroLoc(LoadedOffset);
553   }
554   LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
555   assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&
556          NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&
557          "Ran out of source locations!");
558   // See createFileID for that +1.
559   NextLocalOffset += TokLength + 1;
560   return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
561 }
562 
563 const llvm::MemoryBuffer *
564 SourceManager::getMemoryBufferForFile(const FileEntry *File,
565                                       bool *Invalid) {
566   const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
567   assert(IR && "getOrCreateContentCache() cannot return NULL");
568   return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
569 }
570 
571 void SourceManager::overrideFileContents(const FileEntry *SourceFile,
572                                          const llvm::MemoryBuffer *Buffer,
573                                          bool DoNotFree) {
574   const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
575   assert(IR && "getOrCreateContentCache() cannot return NULL");
576 
577   const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
578 }
579 
580 void SourceManager::overrideFileContents(const FileEntry *SourceFile,
581                                          const FileEntry *NewFile) {
582   assert(SourceFile->getSize() == NewFile->getSize() &&
583          "Different sizes, use the FileManager to create a virtual file with "
584          "the correct size");
585   assert(FileInfos.count(SourceFile) == 0 &&
586          "This function should be called at the initialization stage, before "
587          "any parsing occurs.");
588   OverriddenFiles[SourceFile] = NewFile;
589 }
590 
591 StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
592   bool MyInvalid = false;
593   const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid);
594   if (!SLoc.isFile() || MyInvalid) {
595     if (Invalid)
596       *Invalid = true;
597     return "<<<<<INVALID SOURCE LOCATION>>>>>";
598   }
599 
600   const llvm::MemoryBuffer *Buf
601     = SLoc.getFile().getContentCache()->getBuffer(Diag, *this, SourceLocation(),
602                                                   &MyInvalid);
603   if (Invalid)
604     *Invalid = MyInvalid;
605 
606   if (MyInvalid)
607     return "<<<<<INVALID SOURCE LOCATION>>>>>";
608 
609   return Buf->getBuffer();
610 }
611 
612 //===----------------------------------------------------------------------===//
613 // SourceLocation manipulation methods.
614 //===----------------------------------------------------------------------===//
615 
616 /// \brief Return the FileID for a SourceLocation.
617 ///
618 /// This is the cache-miss path of getFileID. Not as hot as that function, but
619 /// still very important. It is responsible for finding the entry in the
620 /// SLocEntry tables that contains the specified location.
621 FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
622   if (!SLocOffset)
623     return FileID::get(0);
624 
625   // Now it is time to search for the correct file. See where the SLocOffset
626   // sits in the global view and consult local or loaded buffers for it.
627   if (SLocOffset < NextLocalOffset)
628     return getFileIDLocal(SLocOffset);
629   return getFileIDLoaded(SLocOffset);
630 }
631 
632 /// \brief Return the FileID for a SourceLocation with a low offset.
633 ///
634 /// This function knows that the SourceLocation is in a local buffer, not a
635 /// loaded one.
636 FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const {
637   assert(SLocOffset < NextLocalOffset && "Bad function choice");
638 
639   // After the first and second level caches, I see two common sorts of
640   // behavior: 1) a lot of searched FileID's are "near" the cached file
641   // location or are "near" the cached expansion location. 2) others are just
642   // completely random and may be a very long way away.
643   //
644   // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
645   // then we fall back to a less cache efficient, but more scalable, binary
646   // search to find the location.
647 
648   // See if this is near the file point - worst case we start scanning from the
649   // most newly created FileID.
650   std::vector<SrcMgr::SLocEntry>::const_iterator I;
651 
652   if (LastFileIDLookup.ID < 0 ||
653       LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
654     // Neither loc prunes our search.
655     I = LocalSLocEntryTable.end();
656   } else {
657     // Perhaps it is near the file point.
658     I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
659   }
660 
661   // Find the FileID that contains this.  "I" is an iterator that points to a
662   // FileID whose offset is known to be larger than SLocOffset.
663   unsigned NumProbes = 0;
664   while (1) {
665     --I;
666     if (I->getOffset() <= SLocOffset) {
667       FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
668 
669       // If this isn't an expansion, remember it.  We have good locality across
670       // FileID lookups.
671       if (!I->isExpansion())
672         LastFileIDLookup = Res;
673       NumLinearScans += NumProbes+1;
674       return Res;
675     }
676     if (++NumProbes == 8)
677       break;
678   }
679 
680   // Convert "I" back into an index.  We know that it is an entry whose index is
681   // larger than the offset we are looking for.
682   unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
683   // LessIndex - This is the lower bound of the range that we're searching.
684   // We know that the offset corresponding to the FileID is is less than
685   // SLocOffset.
686   unsigned LessIndex = 0;
687   NumProbes = 0;
688   while (1) {
689     bool Invalid = false;
690     unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
691     unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
692     if (Invalid)
693       return FileID::get(0);
694 
695     ++NumProbes;
696 
697     // If the offset of the midpoint is too large, chop the high side of the
698     // range to the midpoint.
699     if (MidOffset > SLocOffset) {
700       GreaterIndex = MiddleIndex;
701       continue;
702     }
703 
704     // If the middle index contains the value, succeed and return.
705     // FIXME: This could be made faster by using a function that's aware of
706     // being in the local area.
707     if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
708       FileID Res = FileID::get(MiddleIndex);
709 
710       // If this isn't a macro expansion, remember it.  We have good locality
711       // across FileID lookups.
712       if (!LocalSLocEntryTable[MiddleIndex].isExpansion())
713         LastFileIDLookup = Res;
714       NumBinaryProbes += NumProbes;
715       return Res;
716     }
717 
718     // Otherwise, move the low-side up to the middle index.
719     LessIndex = MiddleIndex;
720   }
721 }
722 
723 /// \brief Return the FileID for a SourceLocation with a high offset.
724 ///
725 /// This function knows that the SourceLocation is in a loaded buffer, not a
726 /// local one.
727 FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
728   assert(SLocOffset >= CurrentLoadedOffset && "Bad function choice");
729 
730   // Essentially the same as the local case, but the loaded array is sorted
731   // in the other direction.
732 
733   // First do a linear scan from the last lookup position, if possible.
734   unsigned I;
735   int LastID = LastFileIDLookup.ID;
736   if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
737     I = 0;
738   else
739     I = (-LastID - 2) + 1;
740 
741   unsigned NumProbes;
742   for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
743     // Make sure the entry is loaded!
744     const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
745     if (E.getOffset() <= SLocOffset) {
746       FileID Res = FileID::get(-int(I) - 2);
747 
748       if (!E.isExpansion())
749         LastFileIDLookup = Res;
750       NumLinearScans += NumProbes + 1;
751       return Res;
752     }
753   }
754 
755   // Linear scan failed. Do the binary search. Note the reverse sorting of the
756   // table: GreaterIndex is the one where the offset is greater, which is
757   // actually a lower index!
758   unsigned GreaterIndex = I;
759   unsigned LessIndex = LoadedSLocEntryTable.size();
760   NumProbes = 0;
761   while (1) {
762     ++NumProbes;
763     unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
764     const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
765 
766     ++NumProbes;
767 
768     if (E.getOffset() > SLocOffset) {
769       GreaterIndex = MiddleIndex;
770       continue;
771     }
772 
773     if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
774       FileID Res = FileID::get(-int(MiddleIndex) - 2);
775       if (!E.isExpansion())
776         LastFileIDLookup = Res;
777       NumBinaryProbes += NumProbes;
778       return Res;
779     }
780 
781     LessIndex = MiddleIndex;
782   }
783 }
784 
785 SourceLocation SourceManager::
786 getExpansionLocSlowCase(SourceLocation Loc) const {
787   do {
788     // Note: If Loc indicates an offset into a token that came from a macro
789     // expansion (e.g. the 5th character of the token) we do not want to add
790     // this offset when going to the expansion location.  The expansion
791     // location is the macro invocation, which the offset has nothing to do
792     // with.  This is unlike when we get the spelling loc, because the offset
793     // directly correspond to the token whose spelling we're inspecting.
794     Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
795   } while (!Loc.isFileID());
796 
797   return Loc;
798 }
799 
800 SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
801   do {
802     std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
803     Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
804     Loc = Loc.getFileLocWithOffset(LocInfo.second);
805   } while (!Loc.isFileID());
806   return Loc;
807 }
808 
809 
810 std::pair<FileID, unsigned>
811 SourceManager::getDecomposedExpansionLocSlowCase(
812                                              const SrcMgr::SLocEntry *E) const {
813   // If this is an expansion record, walk through all the expansion points.
814   FileID FID;
815   SourceLocation Loc;
816   unsigned Offset;
817   do {
818     Loc = E->getExpansion().getExpansionLocStart();
819 
820     FID = getFileID(Loc);
821     E = &getSLocEntry(FID);
822     Offset = Loc.getOffset()-E->getOffset();
823   } while (!Loc.isFileID());
824 
825   return std::make_pair(FID, Offset);
826 }
827 
828 std::pair<FileID, unsigned>
829 SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
830                                                 unsigned Offset) const {
831   // If this is an expansion record, walk through all the expansion points.
832   FileID FID;
833   SourceLocation Loc;
834   do {
835     Loc = E->getExpansion().getSpellingLoc();
836 
837     FID = getFileID(Loc);
838     E = &getSLocEntry(FID);
839     Offset += Loc.getOffset()-E->getOffset();
840   } while (!Loc.isFileID());
841 
842   return std::make_pair(FID, Offset);
843 }
844 
845 /// getImmediateSpellingLoc - Given a SourceLocation object, return the
846 /// spelling location referenced by the ID.  This is the first level down
847 /// towards the place where the characters that make up the lexed token can be
848 /// found.  This should not generally be used by clients.
849 SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
850   if (Loc.isFileID()) return Loc;
851   std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
852   Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
853   return Loc.getFileLocWithOffset(LocInfo.second);
854 }
855 
856 
857 /// getImmediateExpansionRange - Loc is required to be an expansion location.
858 /// Return the start/end of the expansion information.
859 std::pair<SourceLocation,SourceLocation>
860 SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
861   assert(Loc.isMacroID() && "Not a macro expansion loc!");
862   const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
863   return Expansion.getExpansionLocRange();
864 }
865 
866 /// getExpansionRange - Given a SourceLocation object, return the range of
867 /// tokens covered by the expansion in the ultimate file.
868 std::pair<SourceLocation,SourceLocation>
869 SourceManager::getExpansionRange(SourceLocation Loc) const {
870   if (Loc.isFileID()) return std::make_pair(Loc, Loc);
871 
872   std::pair<SourceLocation,SourceLocation> Res =
873     getImmediateExpansionRange(Loc);
874 
875   // Fully resolve the start and end locations to their ultimate expansion
876   // points.
877   while (!Res.first.isFileID())
878     Res.first = getImmediateExpansionRange(Res.first).first;
879   while (!Res.second.isFileID())
880     Res.second = getImmediateExpansionRange(Res.second).second;
881   return Res;
882 }
883 
884 bool SourceManager::isMacroArgExpansion(SourceLocation Loc) const {
885   if (!Loc.isMacroID()) return false;
886 
887   FileID FID = getFileID(Loc);
888   const SrcMgr::SLocEntry *E = &getSLocEntry(FID);
889   const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
890   return Expansion.isMacroArgExpansion();
891 }
892 
893 
894 //===----------------------------------------------------------------------===//
895 // Queries about the code at a SourceLocation.
896 //===----------------------------------------------------------------------===//
897 
898 /// getCharacterData - Return a pointer to the start of the specified location
899 /// in the appropriate MemoryBuffer.
900 const char *SourceManager::getCharacterData(SourceLocation SL,
901                                             bool *Invalid) const {
902   // Note that this is a hot function in the getSpelling() path, which is
903   // heavily used by -E mode.
904   std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
905 
906   // Note that calling 'getBuffer()' may lazily page in a source file.
907   bool CharDataInvalid = false;
908   const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
909   if (CharDataInvalid || !Entry.isFile()) {
910     if (Invalid)
911       *Invalid = true;
912 
913     return "<<<<INVALID BUFFER>>>>";
914   }
915   const llvm::MemoryBuffer *Buffer
916     = Entry.getFile().getContentCache()
917                   ->getBuffer(Diag, *this, SourceLocation(), &CharDataInvalid);
918   if (Invalid)
919     *Invalid = CharDataInvalid;
920   return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
921 }
922 
923 
924 /// getColumnNumber - Return the column # for the specified file position.
925 /// this is significantly cheaper to compute than the line number.
926 unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
927                                         bool *Invalid) const {
928   bool MyInvalid = false;
929   const char *Buf = getBuffer(FID, &MyInvalid)->getBufferStart();
930   if (Invalid)
931     *Invalid = MyInvalid;
932 
933   if (MyInvalid)
934     return 1;
935 
936   unsigned LineStart = FilePos;
937   while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
938     --LineStart;
939   return FilePos-LineStart+1;
940 }
941 
942 // isInvalid - Return the result of calling loc.isInvalid(), and
943 // if Invalid is not null, set its value to same.
944 static bool isInvalid(SourceLocation Loc, bool *Invalid) {
945   bool MyInvalid = Loc.isInvalid();
946   if (Invalid)
947     *Invalid = MyInvalid;
948   return MyInvalid;
949 }
950 
951 unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
952                                                 bool *Invalid) const {
953   if (isInvalid(Loc, Invalid)) return 0;
954   std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
955   return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
956 }
957 
958 unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
959                                                  bool *Invalid) const {
960   if (isInvalid(Loc, Invalid)) return 0;
961   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
962   return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
963 }
964 
965 unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
966                                                 bool *Invalid) const {
967   if (isInvalid(Loc, Invalid)) return 0;
968   return getPresumedLoc(Loc).getColumn();
969 }
970 
971 static LLVM_ATTRIBUTE_NOINLINE void
972 ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
973                    llvm::BumpPtrAllocator &Alloc,
974                    const SourceManager &SM, bool &Invalid);
975 static void ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
976                                llvm::BumpPtrAllocator &Alloc,
977                                const SourceManager &SM, bool &Invalid) {
978   // Note that calling 'getBuffer()' may lazily page in the file.
979   const MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(),
980                                              &Invalid);
981   if (Invalid)
982     return;
983 
984   // Find the file offsets of all of the *physical* source lines.  This does
985   // not look at trigraphs, escaped newlines, or anything else tricky.
986   SmallVector<unsigned, 256> LineOffsets;
987 
988   // Line #1 starts at char 0.
989   LineOffsets.push_back(0);
990 
991   const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
992   const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
993   unsigned Offs = 0;
994   while (1) {
995     // Skip over the contents of the line.
996     // TODO: Vectorize this?  This is very performance sensitive for programs
997     // with lots of diagnostics and in -E mode.
998     const unsigned char *NextBuf = (const unsigned char *)Buf;
999     while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
1000       ++NextBuf;
1001     Offs += NextBuf-Buf;
1002     Buf = NextBuf;
1003 
1004     if (Buf[0] == '\n' || Buf[0] == '\r') {
1005       // If this is \n\r or \r\n, skip both characters.
1006       if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
1007         ++Offs, ++Buf;
1008       ++Offs, ++Buf;
1009       LineOffsets.push_back(Offs);
1010     } else {
1011       // Otherwise, this is a null.  If end of file, exit.
1012       if (Buf == End) break;
1013       // Otherwise, skip the null.
1014       ++Offs, ++Buf;
1015     }
1016   }
1017 
1018   // Copy the offsets into the FileInfo structure.
1019   FI->NumLines = LineOffsets.size();
1020   FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
1021   std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
1022 }
1023 
1024 /// getLineNumber - Given a SourceLocation, return the spelling line number
1025 /// for the position indicated.  This requires building and caching a table of
1026 /// line offsets for the MemoryBuffer, so this is not cheap: use only when
1027 /// about to emit a diagnostic.
1028 unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1029                                       bool *Invalid) const {
1030   if (FID.isInvalid()) {
1031     if (Invalid)
1032       *Invalid = true;
1033     return 1;
1034   }
1035 
1036   ContentCache *Content;
1037   if (LastLineNoFileIDQuery == FID)
1038     Content = LastLineNoContentCache;
1039   else {
1040     bool MyInvalid = false;
1041     const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1042     if (MyInvalid || !Entry.isFile()) {
1043       if (Invalid)
1044         *Invalid = true;
1045       return 1;
1046     }
1047 
1048     Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
1049   }
1050 
1051   // If this is the first use of line information for this buffer, compute the
1052   /// SourceLineCache for it on demand.
1053   if (Content->SourceLineCache == 0) {
1054     bool MyInvalid = false;
1055     ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
1056     if (Invalid)
1057       *Invalid = MyInvalid;
1058     if (MyInvalid)
1059       return 1;
1060   } else if (Invalid)
1061     *Invalid = false;
1062 
1063   // Okay, we know we have a line number table.  Do a binary search to find the
1064   // line number that this character position lands on.
1065   unsigned *SourceLineCache = Content->SourceLineCache;
1066   unsigned *SourceLineCacheStart = SourceLineCache;
1067   unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
1068 
1069   unsigned QueriedFilePos = FilePos+1;
1070 
1071   // FIXME: I would like to be convinced that this code is worth being as
1072   // complicated as it is, binary search isn't that slow.
1073   //
1074   // If it is worth being optimized, then in my opinion it could be more
1075   // performant, simpler, and more obviously correct by just "galloping" outward
1076   // from the queried file position. In fact, this could be incorporated into a
1077   // generic algorithm such as lower_bound_with_hint.
1078   //
1079   // If someone gives me a test case where this matters, and I will do it! - DWD
1080 
1081   // If the previous query was to the same file, we know both the file pos from
1082   // that query and the line number returned.  This allows us to narrow the
1083   // search space from the entire file to something near the match.
1084   if (LastLineNoFileIDQuery == FID) {
1085     if (QueriedFilePos >= LastLineNoFilePos) {
1086       // FIXME: Potential overflow?
1087       SourceLineCache = SourceLineCache+LastLineNoResult-1;
1088 
1089       // The query is likely to be nearby the previous one.  Here we check to
1090       // see if it is within 5, 10 or 20 lines.  It can be far away in cases
1091       // where big comment blocks and vertical whitespace eat up lines but
1092       // contribute no tokens.
1093       if (SourceLineCache+5 < SourceLineCacheEnd) {
1094         if (SourceLineCache[5] > QueriedFilePos)
1095           SourceLineCacheEnd = SourceLineCache+5;
1096         else if (SourceLineCache+10 < SourceLineCacheEnd) {
1097           if (SourceLineCache[10] > QueriedFilePos)
1098             SourceLineCacheEnd = SourceLineCache+10;
1099           else if (SourceLineCache+20 < SourceLineCacheEnd) {
1100             if (SourceLineCache[20] > QueriedFilePos)
1101               SourceLineCacheEnd = SourceLineCache+20;
1102           }
1103         }
1104       }
1105     } else {
1106       if (LastLineNoResult < Content->NumLines)
1107         SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
1108     }
1109   }
1110 
1111   // If the spread is large, do a "radix" test as our initial guess, based on
1112   // the assumption that lines average to approximately the same length.
1113   // NOTE: This is currently disabled, as it does not appear to be profitable in
1114   // initial measurements.
1115   if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
1116     unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
1117 
1118     // Take a stab at guessing where it is.
1119     unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
1120 
1121     // Check for -10 and +10 lines.
1122     unsigned LowerBound = std::max(int(ApproxPos-10), 0);
1123     unsigned UpperBound = std::min(ApproxPos+10, FileLen);
1124 
1125     // If the computed lower bound is less than the query location, move it in.
1126     if (SourceLineCache < SourceLineCacheStart+LowerBound &&
1127         SourceLineCacheStart[LowerBound] < QueriedFilePos)
1128       SourceLineCache = SourceLineCacheStart+LowerBound;
1129 
1130     // If the computed upper bound is greater than the query location, move it.
1131     if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
1132         SourceLineCacheStart[UpperBound] >= QueriedFilePos)
1133       SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
1134   }
1135 
1136   unsigned *Pos
1137     = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
1138   unsigned LineNo = Pos-SourceLineCacheStart;
1139 
1140   LastLineNoFileIDQuery = FID;
1141   LastLineNoContentCache = Content;
1142   LastLineNoFilePos = QueriedFilePos;
1143   LastLineNoResult = LineNo;
1144   return LineNo;
1145 }
1146 
1147 unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1148                                               bool *Invalid) const {
1149   if (isInvalid(Loc, Invalid)) return 0;
1150   std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1151   return getLineNumber(LocInfo.first, LocInfo.second);
1152 }
1153 unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
1154                                                bool *Invalid) const {
1155   if (isInvalid(Loc, Invalid)) return 0;
1156   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1157   return getLineNumber(LocInfo.first, LocInfo.second);
1158 }
1159 unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
1160                                               bool *Invalid) const {
1161   if (isInvalid(Loc, Invalid)) return 0;
1162   return getPresumedLoc(Loc).getLine();
1163 }
1164 
1165 /// getFileCharacteristic - return the file characteristic of the specified
1166 /// source location, indicating whether this is a normal file, a system
1167 /// header, or an "implicit extern C" system header.
1168 ///
1169 /// This state can be modified with flags on GNU linemarker directives like:
1170 ///   # 4 "foo.h" 3
1171 /// which changes all source locations in the current file after that to be
1172 /// considered to be from a system header.
1173 SrcMgr::CharacteristicKind
1174 SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1175   assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
1176   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1177   bool Invalid = false;
1178   const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
1179   if (Invalid || !SEntry.isFile())
1180     return C_User;
1181 
1182   const SrcMgr::FileInfo &FI = SEntry.getFile();
1183 
1184   // If there are no #line directives in this file, just return the whole-file
1185   // state.
1186   if (!FI.hasLineDirectives())
1187     return FI.getFileCharacteristic();
1188 
1189   assert(LineTable && "Can't have linetable entries without a LineTable!");
1190   // See if there is a #line directive before the location.
1191   const LineEntry *Entry =
1192     LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second);
1193 
1194   // If this is before the first line marker, use the file characteristic.
1195   if (!Entry)
1196     return FI.getFileCharacteristic();
1197 
1198   return Entry->FileKind;
1199 }
1200 
1201 /// Return the filename or buffer identifier of the buffer the location is in.
1202 /// Note that this name does not respect #line directives.  Use getPresumedLoc
1203 /// for normal clients.
1204 const char *SourceManager::getBufferName(SourceLocation Loc,
1205                                          bool *Invalid) const {
1206   if (isInvalid(Loc, Invalid)) return "<invalid loc>";
1207 
1208   return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
1209 }
1210 
1211 
1212 /// getPresumedLoc - This method returns the "presumed" location of a
1213 /// SourceLocation specifies.  A "presumed location" can be modified by #line
1214 /// or GNU line marker directives.  This provides a view on the data that a
1215 /// user should see in diagnostics, for example.
1216 ///
1217 /// Note that a presumed location is always given as the expansion point of an
1218 /// expansion location, not at the spelling location.
1219 PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
1220   if (Loc.isInvalid()) return PresumedLoc();
1221 
1222   // Presumed locations are always for expansion points.
1223   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1224 
1225   bool Invalid = false;
1226   const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1227   if (Invalid || !Entry.isFile())
1228     return PresumedLoc();
1229 
1230   const SrcMgr::FileInfo &FI = Entry.getFile();
1231   const SrcMgr::ContentCache *C = FI.getContentCache();
1232 
1233   // To get the source name, first consult the FileEntry (if one exists)
1234   // before the MemBuffer as this will avoid unnecessarily paging in the
1235   // MemBuffer.
1236   const char *Filename;
1237   if (C->OrigEntry)
1238     Filename = C->OrigEntry->getName();
1239   else
1240     Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
1241 
1242   unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1243   if (Invalid)
1244     return PresumedLoc();
1245   unsigned ColNo  = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1246   if (Invalid)
1247     return PresumedLoc();
1248 
1249   SourceLocation IncludeLoc = FI.getIncludeLoc();
1250 
1251   // If we have #line directives in this file, update and overwrite the physical
1252   // location info if appropriate.
1253   if (FI.hasLineDirectives()) {
1254     assert(LineTable && "Can't have linetable entries without a LineTable!");
1255     // See if there is a #line directive before this.  If so, get it.
1256     if (const LineEntry *Entry =
1257           LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) {
1258       // If the LineEntry indicates a filename, use it.
1259       if (Entry->FilenameID != -1)
1260         Filename = LineTable->getFilename(Entry->FilenameID);
1261 
1262       // Use the line number specified by the LineEntry.  This line number may
1263       // be multiple lines down from the line entry.  Add the difference in
1264       // physical line numbers from the query point and the line marker to the
1265       // total.
1266       unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1267       LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
1268 
1269       // Note that column numbers are not molested by line markers.
1270 
1271       // Handle virtual #include manipulation.
1272       if (Entry->IncludeOffset) {
1273         IncludeLoc = getLocForStartOfFile(LocInfo.first);
1274         IncludeLoc = IncludeLoc.getFileLocWithOffset(Entry->IncludeOffset);
1275       }
1276     }
1277   }
1278 
1279   return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
1280 }
1281 
1282 //===----------------------------------------------------------------------===//
1283 // Other miscellaneous methods.
1284 //===----------------------------------------------------------------------===//
1285 
1286 /// \brief Retrieve the inode for the given file entry, if possible.
1287 ///
1288 /// This routine involves a system call, and therefore should only be used
1289 /// in non-performance-critical code.
1290 static llvm::Optional<ino_t> getActualFileInode(const FileEntry *File) {
1291   if (!File)
1292     return llvm::Optional<ino_t>();
1293 
1294   struct stat StatBuf;
1295   if (::stat(File->getName(), &StatBuf))
1296     return llvm::Optional<ino_t>();
1297 
1298   return StatBuf.st_ino;
1299 }
1300 
1301 /// \brief Get the source location for the given file:line:col triplet.
1302 ///
1303 /// If the source file is included multiple times, the source location will
1304 /// be based upon an arbitrary inclusion.
1305 SourceLocation SourceManager::getLocation(const FileEntry *SourceFile,
1306                                           unsigned Line, unsigned Col) {
1307   assert(SourceFile && "Null source file!");
1308   assert(Line && Col && "Line and column should start from 1!");
1309 
1310   // Find the first file ID that corresponds to the given file.
1311   FileID FirstFID;
1312 
1313   // First, check the main file ID, since it is common to look for a
1314   // location in the main file.
1315   llvm::Optional<ino_t> SourceFileInode;
1316   llvm::Optional<StringRef> SourceFileName;
1317   if (!MainFileID.isInvalid()) {
1318     bool Invalid = false;
1319     const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1320     if (Invalid)
1321       return SourceLocation();
1322 
1323     if (MainSLoc.isFile()) {
1324       const ContentCache *MainContentCache
1325         = MainSLoc.getFile().getContentCache();
1326       if (!MainContentCache) {
1327         // Can't do anything
1328       } else if (MainContentCache->OrigEntry == SourceFile) {
1329         FirstFID = MainFileID;
1330       } else {
1331         // Fall back: check whether we have the same base name and inode
1332         // as the main file.
1333         const FileEntry *MainFile = MainContentCache->OrigEntry;
1334         SourceFileName = llvm::sys::path::filename(SourceFile->getName());
1335         if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) {
1336           SourceFileInode = getActualFileInode(SourceFile);
1337           if (SourceFileInode) {
1338             if (llvm::Optional<ino_t> MainFileInode
1339                                                = getActualFileInode(MainFile)) {
1340               if (*SourceFileInode == *MainFileInode) {
1341                 FirstFID = MainFileID;
1342                 SourceFile = MainFile;
1343               }
1344             }
1345           }
1346         }
1347       }
1348     }
1349   }
1350 
1351   if (FirstFID.isInvalid()) {
1352     // The location we're looking for isn't in the main file; look
1353     // through all of the local source locations.
1354     for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1355       bool Invalid = false;
1356       const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid);
1357       if (Invalid)
1358         return SourceLocation();
1359 
1360       if (SLoc.isFile() &&
1361           SLoc.getFile().getContentCache() &&
1362           SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1363         FirstFID = FileID::get(I);
1364         break;
1365       }
1366     }
1367     // If that still didn't help, try the modules.
1368     if (FirstFID.isInvalid()) {
1369       for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
1370         const SLocEntry &SLoc = getLoadedSLocEntry(I);
1371         if (SLoc.isFile() &&
1372             SLoc.getFile().getContentCache() &&
1373             SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1374           FirstFID = FileID::get(-int(I) - 2);
1375           break;
1376         }
1377       }
1378     }
1379   }
1380 
1381   // If we haven't found what we want yet, try again, but this time stat()
1382   // each of the files in case the files have changed since we originally
1383   // parsed the file.
1384   if (FirstFID.isInvalid() &&
1385       (SourceFileName ||
1386        (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) &&
1387       (SourceFileInode ||
1388        (SourceFileInode = getActualFileInode(SourceFile)))) {
1389     bool Invalid = false;
1390     for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1391       FileID IFileID;
1392       IFileID.ID = I;
1393       const SLocEntry &SLoc = getSLocEntry(IFileID, &Invalid);
1394       if (Invalid)
1395         return SourceLocation();
1396 
1397       if (SLoc.isFile()) {
1398         const ContentCache *FileContentCache
1399           = SLoc.getFile().getContentCache();
1400       const FileEntry *Entry =FileContentCache? FileContentCache->OrigEntry : 0;
1401         if (Entry &&
1402             *SourceFileName == llvm::sys::path::filename(Entry->getName())) {
1403           if (llvm::Optional<ino_t> EntryInode = getActualFileInode(Entry)) {
1404             if (*SourceFileInode == *EntryInode) {
1405               FirstFID = FileID::get(I);
1406               SourceFile = Entry;
1407               break;
1408             }
1409           }
1410         }
1411       }
1412     }
1413   }
1414 
1415   if (FirstFID.isInvalid())
1416     return SourceLocation();
1417 
1418   if (Line == 1 && Col == 1)
1419     return getLocForStartOfFile(FirstFID);
1420 
1421   ContentCache *Content
1422     = const_cast<ContentCache *>(getOrCreateContentCache(SourceFile));
1423   if (!Content)
1424     return SourceLocation();
1425 
1426   // If this is the first use of line information for this buffer, compute the
1427   // SourceLineCache for it on demand.
1428   if (Content->SourceLineCache == 0) {
1429     bool MyInvalid = false;
1430     ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
1431     if (MyInvalid)
1432       return SourceLocation();
1433   }
1434 
1435   if (Line > Content->NumLines) {
1436     unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
1437     if (Size > 0)
1438       --Size;
1439     return getLocForStartOfFile(FirstFID).getFileLocWithOffset(Size);
1440   }
1441 
1442   unsigned FilePos = Content->SourceLineCache[Line - 1];
1443   const char *Buf = Content->getBuffer(Diag, *this)->getBufferStart() + FilePos;
1444   unsigned BufLength = Content->getBuffer(Diag, *this)->getBufferEnd() - Buf;
1445   unsigned i = 0;
1446 
1447   // Check that the given column is valid.
1448   while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1449     ++i;
1450   if (i < Col-1)
1451     return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + i);
1452 
1453   return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + Col - 1);
1454 }
1455 
1456 /// Given a decomposed source location, move it up the include/expansion stack
1457 /// to the parent source location.  If this is possible, return the decomposed
1458 /// version of the parent in Loc and return false.  If Loc is the top-level
1459 /// entry, return true and don't modify it.
1460 static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1461                                    const SourceManager &SM) {
1462   SourceLocation UpperLoc;
1463   const SrcMgr::SLocEntry &Entry = SM.getSLocEntry(Loc.first);
1464   if (Entry.isExpansion())
1465     UpperLoc = Entry.getExpansion().getExpansionLocStart();
1466   else
1467     UpperLoc = Entry.getFile().getIncludeLoc();
1468 
1469   if (UpperLoc.isInvalid())
1470     return true; // We reached the top.
1471 
1472   Loc = SM.getDecomposedLoc(UpperLoc);
1473   return false;
1474 }
1475 
1476 
1477 /// \brief Determines the order of 2 source locations in the translation unit.
1478 ///
1479 /// \returns true if LHS source location comes before RHS, false otherwise.
1480 bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1481                                               SourceLocation RHS) const {
1482   assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1483   if (LHS == RHS)
1484     return false;
1485 
1486   // If both locations are macro expansions, the order of their offsets reflect
1487   // the order that the tokens, pointed to by these locations, were expanded
1488   // (during parsing each token that is expanded by a macro, expands the
1489   // SLocEntries).
1490 
1491   std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1492   std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
1493 
1494   // If the source locations are in the same file, just compare offsets.
1495   if (LOffs.first == ROffs.first)
1496     return LOffs.second < ROffs.second;
1497 
1498   // If we are comparing a source location with multiple locations in the same
1499   // file, we get a big win by caching the result.
1500   if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
1501     return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
1502 
1503   // Okay, we missed in the cache, start updating the cache for this query.
1504   IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first);
1505 
1506   // We need to find the common ancestor. The only way of doing this is to
1507   // build the complete include chain for one and then walking up the chain
1508   // of the other looking for a match.
1509   // We use a map from FileID to Offset to store the chain. Easier than writing
1510   // a custom set hash info that only depends on the first part of a pair.
1511   typedef llvm::DenseMap<FileID, unsigned> LocSet;
1512   LocSet LChain;
1513   do {
1514     LChain.insert(LOffs);
1515     // We catch the case where LOffs is in a file included by ROffs and
1516     // quit early. The other way round unfortunately remains suboptimal.
1517   } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
1518   LocSet::iterator I;
1519   while((I = LChain.find(ROffs.first)) == LChain.end()) {
1520     if (MoveUpIncludeHierarchy(ROffs, *this))
1521       break; // Met at topmost file.
1522   }
1523   if (I != LChain.end())
1524     LOffs = *I;
1525 
1526   // If we exited because we found a nearest common ancestor, compare the
1527   // locations within the common file and cache them.
1528   if (LOffs.first == ROffs.first) {
1529     IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
1530     return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
1531   }
1532 
1533   // This can happen if a location is in a built-ins buffer.
1534   // But see PR5662.
1535   // Clear the lookup cache, it depends on a common location.
1536   IsBeforeInTUCache.setQueryFIDs(FileID(), FileID());
1537   bool LIsBuiltins = strcmp("<built-in>",
1538                             getBuffer(LOffs.first)->getBufferIdentifier()) == 0;
1539   bool RIsBuiltins = strcmp("<built-in>",
1540                             getBuffer(ROffs.first)->getBufferIdentifier()) == 0;
1541   // built-in is before non-built-in
1542   if (LIsBuiltins != RIsBuiltins)
1543     return LIsBuiltins;
1544   assert(LIsBuiltins && RIsBuiltins &&
1545          "Non-built-in locations must be rooted in the main file");
1546   // Both are in built-in buffers, but from different files. We just claim that
1547   // lower IDs come first.
1548   return LOffs.first < ROffs.first;
1549 }
1550 
1551 /// PrintStats - Print statistics to stderr.
1552 ///
1553 void SourceManager::PrintStats() const {
1554   llvm::errs() << "\n*** Source Manager Stats:\n";
1555   llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
1556                << " mem buffers mapped.\n";
1557   llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
1558                << LocalSLocEntryTable.capacity()*sizeof(SrcMgr::SLocEntry)
1559                << " bytes of capacity), "
1560                << NextLocalOffset << "B of Sloc address space used.\n";
1561   llvm::errs() << LoadedSLocEntryTable.size()
1562                << " loaded SLocEntries allocated, "
1563                << (1U << 31U) - CurrentLoadedOffset
1564                << "B of Sloc address space used.\n";
1565 
1566   unsigned NumLineNumsComputed = 0;
1567   unsigned NumFileBytesMapped = 0;
1568   for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
1569     NumLineNumsComputed += I->second->SourceLineCache != 0;
1570     NumFileBytesMapped  += I->second->getSizeBytesMapped();
1571   }
1572 
1573   llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
1574                << NumLineNumsComputed << " files with line #'s computed.\n";
1575   llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
1576                << NumBinaryProbes << " binary.\n";
1577 }
1578 
1579 ExternalSLocEntrySource::~ExternalSLocEntrySource() { }
1580 
1581 /// Return the amount of memory used by memory buffers, breaking down
1582 /// by heap-backed versus mmap'ed memory.
1583 SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
1584   size_t malloc_bytes = 0;
1585   size_t mmap_bytes = 0;
1586 
1587   for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
1588     if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
1589       switch (MemBufferInfos[i]->getMemoryBufferKind()) {
1590         case llvm::MemoryBuffer::MemoryBuffer_MMap:
1591           mmap_bytes += sized_mapped;
1592           break;
1593         case llvm::MemoryBuffer::MemoryBuffer_Malloc:
1594           malloc_bytes += sized_mapped;
1595           break;
1596       }
1597 
1598   return MemoryBufferSizes(malloc_bytes, mmap_bytes);
1599 }
1600 
1601 size_t SourceManager::getDataStructureSizes() const {
1602   return MemBufferInfos.capacity()
1603     + LocalSLocEntryTable.capacity()
1604     + LoadedSLocEntryTable.capacity()
1605     + SLocEntryLoaded.capacity()
1606     + FileInfos.getMemorySize()
1607     + OverriddenFiles.getMemorySize();
1608 }
1609