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