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