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