blob: 4007ccf2a61e7e919e32dc26b34e07e26dac2fd8 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SourceManager.cpp - Track and cache source files -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the SourceManager interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Basic/SourceManager.h"
Douglas Gregord4f77aa2009-04-13 15:31:25 +000015#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregoraea67db2010-03-15 22:54:52 +000016#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/Basic/FileManager.h"
Chris Lattner5e36a7a2007-07-24 05:57:19 +000018#include "llvm/Support/Compiler.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "llvm/Support/MemoryBuffer.h"
Chris Lattnerd57a7ef2009-08-23 22:45:33 +000020#include "llvm/Support/raw_ostream.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021#include "llvm/System/Path.h"
22#include <algorithm>
Douglas Gregoraea67db2010-03-15 22:54:52 +000023#include <string>
Douglas Gregorf715ca12010-03-16 00:06:06 +000024#include <cstring>
Douglas Gregoraea67db2010-03-15 22:54:52 +000025
Reid Spencer5f016e22007-07-11 17:01:13 +000026using namespace clang;
27using namespace SrcMgr;
28using llvm::MemoryBuffer;
29
Chris Lattner23b5dc62009-02-04 00:40:31 +000030//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +000031// SourceManager Helper Classes
Chris Lattner23b5dc62009-02-04 00:40:31 +000032//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +000033
Ted Kremenek78d85f52007-10-30 21:08:08 +000034ContentCache::~ContentCache() {
35 delete Buffer;
Reid Spencer5f016e22007-07-11 17:01:13 +000036}
37
Ted Kremenekc16c2082009-01-06 01:55:26 +000038/// getSizeBytesMapped - Returns the number of bytes actually mapped for
39/// this ContentCache. This can be 0 if the MemBuffer was not actually
40/// instantiated.
41unsigned ContentCache::getSizeBytesMapped() const {
42 return Buffer ? Buffer->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
Douglas Gregor29684422009-12-02 06:49:09 +000048/// file is not lazily brought in from disk to satisfy this query.
Ted Kremenekc16c2082009-01-06 01:55:26 +000049unsigned ContentCache::getSize() const {
Ted Kremenek8515fbf2010-03-10 18:22:38 +000050 return Buffer ? (unsigned) Buffer->getBufferSize()
51 : (unsigned) Entry->getSize();
Ted Kremenekc16c2082009-01-06 01:55:26 +000052}
53
Douglas Gregor29684422009-12-02 06:49:09 +000054void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B) {
Douglas Gregor109ae732009-12-03 17:05:59 +000055 assert(B != Buffer);
Douglas Gregor29684422009-12-02 06:49:09 +000056
57 delete Buffer;
58 Buffer = B;
59}
60
Douglas Gregor36c35ba2010-03-16 00:35:39 +000061const llvm::MemoryBuffer *ContentCache::getBuffer(Diagnostic &Diag,
62 bool *Invalid) const {
63 if (Invalid)
64 *Invalid = false;
65
Ted Kremenek5b034ad2009-01-06 22:43:04 +000066 // Lazily create the Buffer for ContentCaches that wrap files.
67 if (!Buffer && Entry) {
Douglas Gregoraea67db2010-03-15 22:54:52 +000068 std::string ErrorStr;
69 struct stat FileInfo;
70 Buffer = MemoryBuffer::getFile(Entry->getName(), &ErrorStr,
71 Entry->getSize(), &FileInfo);
Daniel Dunbar21a8bed2009-12-06 05:43:36 +000072
73 // If we were unable to open the file, then we are in an inconsistent
74 // situation where the content cache referenced a file which no longer
75 // exists. Most likely, we were using a stat cache with an invalid entry but
76 // the file could also have been removed during processing. Since we can't
77 // really deal with this situation, just create an empty buffer.
78 //
79 // FIXME: This is definitely not ideal, but our immediate clients can't
80 // currently handle returning a null entry here. Ideally we should detect
81 // that we are in an inconsistent situation and error out as quickly as
82 // possible.
83 if (!Buffer) {
84 const llvm::StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
85 Buffer = MemoryBuffer::getNewMemBuffer(Entry->getSize(), "<invalid>");
86 char *Ptr = const_cast<char*>(Buffer->getBufferStart());
87 for (unsigned i = 0, e = Entry->getSize(); i != e; ++i)
88 Ptr[i] = FillStr[i % FillStr.size()];
Douglas Gregor36c35ba2010-03-16 00:35:39 +000089 Diag.Report(diag::err_cannot_open_file)
90 << Entry->getName() << ErrorStr;
91 if (Invalid)
92 *Invalid = true;
Douglas Gregoraea67db2010-03-15 22:54:52 +000093 } else {
94 // Check that the file's size and modification time is the same as
95 // in the file entry (which may have come from a stat cache).
Douglas Gregoraea67db2010-03-15 22:54:52 +000096 if (FileInfo.st_size != Entry->getSize()) {
Douglas Gregor36c35ba2010-03-16 00:35:39 +000097 Diag.Report(diag::err_file_size_changed)
98 << Entry->getName() << (unsigned)Entry->getSize()
99 << (unsigned)FileInfo.st_size;
100 if (Invalid)
101 *Invalid = true;
Douglas Gregoraea67db2010-03-15 22:54:52 +0000102 } else if (FileInfo.st_mtime != Entry->getModificationTime()) {
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000103 Diag.Report(diag::err_file_modified) << Entry->getName();
104 if (Invalid)
105 *Invalid = true;
Douglas Gregoraea67db2010-03-15 22:54:52 +0000106 }
Daniel Dunbar21a8bed2009-12-06 05:43:36 +0000107 }
Ted Kremenek5b034ad2009-01-06 22:43:04 +0000108 }
Douglas Gregoraea67db2010-03-15 22:54:52 +0000109
Ted Kremenekc16c2082009-01-06 01:55:26 +0000110 return Buffer;
111}
112
Chris Lattner5b9a5042009-01-26 07:57:50 +0000113unsigned LineTableInfo::getLineTableFilenameID(const char *Ptr, unsigned Len) {
114 // Look up the filename in the string table, returning the pre-existing value
115 // if it exists.
Mike Stump1eb44332009-09-09 15:08:12 +0000116 llvm::StringMapEntry<unsigned> &Entry =
Chris Lattner5b9a5042009-01-26 07:57:50 +0000117 FilenameIDs.GetOrCreateValue(Ptr, Ptr+Len, ~0U);
118 if (Entry.getValue() != ~0U)
119 return Entry.getValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000120
Chris Lattner5b9a5042009-01-26 07:57:50 +0000121 // Otherwise, assign this the next available ID.
122 Entry.setValue(FilenamesByID.size());
123 FilenamesByID.push_back(&Entry);
124 return FilenamesByID.size()-1;
125}
126
Chris Lattnerac50e342009-02-03 22:13:05 +0000127/// AddLineNote - Add a line note to the line table that indicates that there
128/// is a #line at the specified FID/Offset location which changes the presumed
129/// location to LineNo/FilenameID.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000130void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
Chris Lattnerac50e342009-02-03 22:13:05 +0000131 unsigned LineNo, int FilenameID) {
Chris Lattner23b5dc62009-02-04 00:40:31 +0000132 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000133
Chris Lattner23b5dc62009-02-04 00:40:31 +0000134 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
135 "Adding line entries out of order!");
Mike Stump1eb44332009-09-09 15:08:12 +0000136
Chris Lattner9d79eba2009-02-04 05:21:58 +0000137 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
Chris Lattner137b6a62009-02-04 06:25:26 +0000138 unsigned IncludeOffset = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000139
Chris Lattner9d79eba2009-02-04 05:21:58 +0000140 if (!Entries.empty()) {
141 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
142 // that we are still in "foo.h".
143 if (FilenameID == -1)
144 FilenameID = Entries.back().FilenameID;
Mike Stump1eb44332009-09-09 15:08:12 +0000145
Chris Lattner137b6a62009-02-04 06:25:26 +0000146 // If we are after a line marker that switched us to system header mode, or
147 // that set #include information, preserve it.
Chris Lattner9d79eba2009-02-04 05:21:58 +0000148 Kind = Entries.back().FileKind;
Chris Lattner137b6a62009-02-04 06:25:26 +0000149 IncludeOffset = Entries.back().IncludeOffset;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000150 }
Mike Stump1eb44332009-09-09 15:08:12 +0000151
Chris Lattner137b6a62009-02-04 06:25:26 +0000152 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
153 IncludeOffset));
Chris Lattnerac50e342009-02-03 22:13:05 +0000154}
155
Chris Lattner9d79eba2009-02-04 05:21:58 +0000156/// AddLineNote This is the same as the previous version of AddLineNote, but is
157/// used for GNU line markers. If EntryExit is 0, then this doesn't change the
158/// presumed #include stack. If it is 1, this is a file entry, if it is 2 then
159/// this is a file exit. FileKind specifies whether this is a system header or
160/// extern C system header.
161void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
162 unsigned LineNo, int FilenameID,
163 unsigned EntryExit,
164 SrcMgr::CharacteristicKind FileKind) {
165 assert(FilenameID != -1 && "Unspecified filename should use other accessor");
Mike Stump1eb44332009-09-09 15:08:12 +0000166
Chris Lattner9d79eba2009-02-04 05:21:58 +0000167 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000168
Chris Lattner9d79eba2009-02-04 05:21:58 +0000169 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
170 "Adding line entries out of order!");
171
Chris Lattner137b6a62009-02-04 06:25:26 +0000172 unsigned IncludeOffset = 0;
173 if (EntryExit == 0) { // No #include stack change.
174 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
175 } else if (EntryExit == 1) {
176 IncludeOffset = Offset-1;
177 } else if (EntryExit == 2) {
178 assert(!Entries.empty() && Entries.back().IncludeOffset &&
179 "PPDirectives should have caught case when popping empty include stack");
Mike Stump1eb44332009-09-09 15:08:12 +0000180
Chris Lattner137b6a62009-02-04 06:25:26 +0000181 // Get the include loc of the last entries' include loc as our include loc.
182 IncludeOffset = 0;
183 if (const LineEntry *PrevEntry =
184 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
185 IncludeOffset = PrevEntry->IncludeOffset;
186 }
Mike Stump1eb44332009-09-09 15:08:12 +0000187
Chris Lattner137b6a62009-02-04 06:25:26 +0000188 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
189 IncludeOffset));
Chris Lattner9d79eba2009-02-04 05:21:58 +0000190}
191
192
Chris Lattner3cd949c2009-02-04 01:55:42 +0000193/// FindNearestLineEntry - Find the line entry nearest to FID that is before
194/// it. If there is no line entry before Offset in FID, return null.
Mike Stump1eb44332009-09-09 15:08:12 +0000195const LineEntry *LineTableInfo::FindNearestLineEntry(unsigned FID,
Chris Lattner3cd949c2009-02-04 01:55:42 +0000196 unsigned Offset) {
197 const std::vector<LineEntry> &Entries = LineEntries[FID];
198 assert(!Entries.empty() && "No #line entries for this FID after all!");
199
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000200 // It is very common for the query to be after the last #line, check this
201 // first.
202 if (Entries.back().FileOffset <= Offset)
203 return &Entries.back();
Chris Lattner3cd949c2009-02-04 01:55:42 +0000204
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000205 // Do a binary search to find the maximal element that is still before Offset.
206 std::vector<LineEntry>::const_iterator I =
207 std::upper_bound(Entries.begin(), Entries.end(), Offset);
208 if (I == Entries.begin()) return 0;
209 return &*--I;
Chris Lattner3cd949c2009-02-04 01:55:42 +0000210}
Chris Lattnerac50e342009-02-03 22:13:05 +0000211
Douglas Gregorbd945002009-04-13 16:31:14 +0000212/// \brief Add a new line entry that has already been encoded into
213/// the internal representation of the line table.
Mike Stump1eb44332009-09-09 15:08:12 +0000214void LineTableInfo::AddEntry(unsigned FID,
Douglas Gregorbd945002009-04-13 16:31:14 +0000215 const std::vector<LineEntry> &Entries) {
216 LineEntries[FID] = Entries;
217}
Chris Lattnerac50e342009-02-03 22:13:05 +0000218
Chris Lattner5b9a5042009-01-26 07:57:50 +0000219/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
Mike Stump1eb44332009-09-09 15:08:12 +0000220///
Chris Lattner5b9a5042009-01-26 07:57:50 +0000221unsigned SourceManager::getLineTableFilenameID(const char *Ptr, unsigned Len) {
222 if (LineTable == 0)
223 LineTable = new LineTableInfo();
224 return LineTable->getLineTableFilenameID(Ptr, Len);
225}
226
227
Chris Lattner4c4ea172009-02-03 21:52:55 +0000228/// AddLineNote - Add a line note to the line table for the FileID and offset
229/// specified by Loc. If FilenameID is -1, it is considered to be
230/// unspecified.
231void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
232 int FilenameID) {
Chris Lattnerac50e342009-02-03 22:13:05 +0000233 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000234
Chris Lattnerac50e342009-02-03 22:13:05 +0000235 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
236
237 // Remember that this file has #line directives now if it doesn't already.
238 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000239
Chris Lattnerac50e342009-02-03 22:13:05 +0000240 if (LineTable == 0)
241 LineTable = new LineTableInfo();
Chris Lattner23b5dc62009-02-04 00:40:31 +0000242 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID);
Chris Lattner4c4ea172009-02-03 21:52:55 +0000243}
244
Chris Lattner9d79eba2009-02-04 05:21:58 +0000245/// AddLineNote - Add a GNU line marker to the line table.
246void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
247 int FilenameID, bool IsFileEntry,
248 bool IsFileExit, bool IsSystemHeader,
249 bool IsExternCHeader) {
250 // If there is no filename and no flags, this is treated just like a #line,
251 // which does not change the flags of the previous line marker.
252 if (FilenameID == -1) {
253 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
254 "Can't set flags without setting the filename!");
255 return AddLineNote(Loc, LineNo, FilenameID);
256 }
Mike Stump1eb44332009-09-09 15:08:12 +0000257
Chris Lattner9d79eba2009-02-04 05:21:58 +0000258 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
259 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000260
Chris Lattner9d79eba2009-02-04 05:21:58 +0000261 // Remember that this file has #line directives now if it doesn't already.
262 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000263
Chris Lattner9d79eba2009-02-04 05:21:58 +0000264 if (LineTable == 0)
265 LineTable = new LineTableInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000266
Chris Lattner9d79eba2009-02-04 05:21:58 +0000267 SrcMgr::CharacteristicKind FileKind;
268 if (IsExternCHeader)
269 FileKind = SrcMgr::C_ExternCSystem;
270 else if (IsSystemHeader)
271 FileKind = SrcMgr::C_System;
272 else
273 FileKind = SrcMgr::C_User;
Mike Stump1eb44332009-09-09 15:08:12 +0000274
Chris Lattner9d79eba2009-02-04 05:21:58 +0000275 unsigned EntryExit = 0;
276 if (IsFileEntry)
277 EntryExit = 1;
278 else if (IsFileExit)
279 EntryExit = 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000280
Chris Lattner9d79eba2009-02-04 05:21:58 +0000281 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID,
282 EntryExit, FileKind);
283}
284
Douglas Gregorbd945002009-04-13 16:31:14 +0000285LineTableInfo &SourceManager::getLineTable() {
286 if (LineTable == 0)
287 LineTable = new LineTableInfo();
288 return *LineTable;
289}
Chris Lattner4c4ea172009-02-03 21:52:55 +0000290
Chris Lattner23b5dc62009-02-04 00:40:31 +0000291//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000292// Private 'Create' methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000293//===----------------------------------------------------------------------===//
Ted Kremenekc16c2082009-01-06 01:55:26 +0000294
Chris Lattner5b9a5042009-01-26 07:57:50 +0000295SourceManager::~SourceManager() {
296 delete LineTable;
Mike Stump1eb44332009-09-09 15:08:12 +0000297
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000298 // Delete FileEntry objects corresponding to content caches. Since the actual
299 // content cache objects are bump pointer allocated, we just have to run the
300 // dtors, but we call the deallocate method for completeness.
301 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
302 MemBufferInfos[i]->~ContentCache();
303 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
304 }
305 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
306 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
307 I->second->~ContentCache();
308 ContentCacheAlloc.Deallocate(I->second);
309 }
Chris Lattner5b9a5042009-01-26 07:57:50 +0000310}
311
312void SourceManager::clearIDTables() {
313 MainFileID = FileID();
314 SLocEntryTable.clear();
315 LastLineNoFileIDQuery = FileID();
316 LastLineNoContentCache = 0;
317 LastFileIDLookup = FileID();
Mike Stump1eb44332009-09-09 15:08:12 +0000318
Chris Lattner5b9a5042009-01-26 07:57:50 +0000319 if (LineTable)
320 LineTable->clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000321
Chris Lattner5b9a5042009-01-26 07:57:50 +0000322 // Use up FileID #0 as an invalid instantiation.
323 NextOffset = 0;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000324 createInstantiationLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000325}
326
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000327/// getOrCreateContentCache - Create or return a cached ContentCache for the
328/// specified file.
329const ContentCache *
330SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000331 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Reid Spencer5f016e22007-07-11 17:01:13 +0000333 // Do we already have information about this file?
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000334 ContentCache *&Entry = FileInfos[FileEnt];
335 if (Entry) return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Chris Lattner00282d62009-02-03 07:41:46 +0000337 // Nope, create a new Cache entry. Make sure it is at least 8-byte aligned
338 // so that FileInfo can use the low 3 bits of the pointer for its own
339 // nefarious purposes.
340 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
341 EntryAlign = std::max(8U, EntryAlign);
342 Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000343 new (Entry) ContentCache(FileEnt);
344 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000345}
346
347
Ted Kremenekd1c0eee2007-10-31 17:53:38 +0000348/// createMemBufferContentCache - Create a new ContentCache for the specified
349/// memory buffer. This does no caching.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000350const ContentCache*
351SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
Chris Lattner00282d62009-02-03 07:41:46 +0000352 // Add a new ContentCache to the MemBufferInfos list and return it. Make sure
353 // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of
354 // the pointer for its own nefarious purposes.
355 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
356 EntryAlign = std::max(8U, EntryAlign);
357 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000358 new (Entry) ContentCache();
359 MemBufferInfos.push_back(Entry);
360 Entry->setBuffer(Buffer);
361 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000362}
363
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000364void SourceManager::PreallocateSLocEntries(ExternalSLocEntrySource *Source,
365 unsigned NumSLocEntries,
366 unsigned NextOffset) {
367 ExternalSLocEntries = Source;
368 this->NextOffset = NextOffset;
369 SLocEntryLoaded.resize(NumSLocEntries + 1);
370 SLocEntryLoaded[0] = true;
371 SLocEntryTable.resize(SLocEntryTable.size() + NumSLocEntries);
372}
373
Douglas Gregor2bf1eb02009-04-27 21:28:04 +0000374void SourceManager::ClearPreallocatedSLocEntries() {
375 unsigned I = 0;
376 for (unsigned N = SLocEntryLoaded.size(); I != N; ++I)
377 if (!SLocEntryLoaded[I])
378 break;
379
380 // We've already loaded all preallocated source location entries.
381 if (I == SLocEntryLoaded.size())
382 return;
383
384 // Remove everything from location I onward.
385 SLocEntryTable.resize(I);
386 SLocEntryLoaded.clear();
387 ExternalSLocEntries = 0;
388}
389
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000390
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000391//===----------------------------------------------------------------------===//
392// Methods to create new FileID's and instantiations.
393//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000394
Nico Weber48002c82008-09-29 00:25:48 +0000395/// createFileID - Create a new fileID for the specified ContentCache and
Ted Kremenek0d892d82007-10-30 22:57:35 +0000396/// include position. This works regardless of whether the ContentCache
397/// corresponds to a file or some other input source.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000398FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000399 SourceLocation IncludePos,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000400 SrcMgr::CharacteristicKind FileCharacter,
401 unsigned PreallocatedID,
402 unsigned Offset) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000403 if (PreallocatedID) {
404 // If we're filling in a preallocated ID, just load in the file
405 // entry and return.
Mike Stump1eb44332009-09-09 15:08:12 +0000406 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000407 "Preallocate ID out-of-range");
Mike Stump1eb44332009-09-09 15:08:12 +0000408 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000409 "Source location entry already loaded");
410 assert(Offset && "Preallocate source location cannot have zero offset");
Mike Stump1eb44332009-09-09 15:08:12 +0000411 SLocEntryTable[PreallocatedID]
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000412 = SLocEntry::get(Offset, FileInfo::get(IncludePos, File, FileCharacter));
413 SLocEntryLoaded[PreallocatedID] = true;
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +0000414 FileID FID = FileID::get(PreallocatedID);
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +0000415 return LastFileIDLookup = FID;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000416 }
417
Mike Stump1eb44332009-09-09 15:08:12 +0000418 SLocEntryTable.push_back(SLocEntry::get(NextOffset,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000419 FileInfo::get(IncludePos, File,
420 FileCharacter)));
Ted Kremenekc16c2082009-01-06 01:55:26 +0000421 unsigned FileSize = File->getSize();
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000422 assert(NextOffset+FileSize+1 > NextOffset && "Ran out of source locations!");
423 NextOffset += FileSize+1;
Mike Stump1eb44332009-09-09 15:08:12 +0000424
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000425 // Set LastFileIDLookup to the newly created file. The next getFileID call is
426 // almost guaranteed to be from that file.
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000427 FileID FID = FileID::get(SLocEntryTable.size()-1);
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000428 return LastFileIDLookup = FID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000429}
430
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000431/// createInstantiationLoc - Return a new SourceLocation that encodes the fact
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000432/// that a token from SpellingLoc should actually be referenced from
Reid Spencer5f016e22007-07-11 17:01:13 +0000433/// InstantiationLoc.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000434SourceLocation SourceManager::createInstantiationLoc(SourceLocation SpellingLoc,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000435 SourceLocation ILocStart,
436 SourceLocation ILocEnd,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000437 unsigned TokLength,
438 unsigned PreallocatedID,
439 unsigned Offset) {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000440 InstantiationInfo II = InstantiationInfo::get(ILocStart,ILocEnd, SpellingLoc);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000441 if (PreallocatedID) {
442 // If we're filling in a preallocated ID, just load in the
443 // instantiation entry and return.
Mike Stump1eb44332009-09-09 15:08:12 +0000444 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000445 "Preallocate ID out-of-range");
Mike Stump1eb44332009-09-09 15:08:12 +0000446 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000447 "Source location entry already loaded");
448 assert(Offset && "Preallocate source location cannot have zero offset");
449 SLocEntryTable[PreallocatedID] = SLocEntry::get(Offset, II);
450 SLocEntryLoaded[PreallocatedID] = true;
451 return SourceLocation::getMacroLoc(Offset);
452 }
Chris Lattnere7fb4842009-02-15 20:52:18 +0000453 SLocEntryTable.push_back(SLocEntry::get(NextOffset, II));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000454 assert(NextOffset+TokLength+1 > NextOffset && "Ran out of source locations!");
455 NextOffset += TokLength+1;
456 return SourceLocation::getMacroLoc(NextOffset-(TokLength+1));
Reid Spencer5f016e22007-07-11 17:01:13 +0000457}
458
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000459const llvm::MemoryBuffer *
Douglas Gregor50f6af72010-03-16 05:20:39 +0000460SourceManager::getMemoryBufferForFile(const FileEntry *File,
461 bool *Invalid) {
Douglas Gregor29684422009-12-02 06:49:09 +0000462 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregoraea67db2010-03-15 22:54:52 +0000463 assert(IR && "getOrCreateContentCache() cannot return NULL");
Douglas Gregor50f6af72010-03-16 05:20:39 +0000464 return IR->getBuffer(Diag, Invalid);
Douglas Gregor29684422009-12-02 06:49:09 +0000465}
466
467bool SourceManager::overrideFileContents(const FileEntry *SourceFile,
468 const llvm::MemoryBuffer *Buffer) {
469 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
470 if (IR == 0)
471 return true;
472
473 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer);
474 return false;
475}
476
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000477llvm::StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
Douglas Gregorf715ca12010-03-16 00:06:06 +0000478 if (Invalid)
479 *Invalid = false;
480
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000481 const llvm::MemoryBuffer *Buf = getBuffer(FID);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000482 if (!Buf) {
483 if (*Invalid)
484 *Invalid = true;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000485 return "";
Douglas Gregorf715ca12010-03-16 00:06:06 +0000486 }
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000487 return Buf->getBuffer();
Douglas Gregoraea67db2010-03-15 22:54:52 +0000488}
Chris Lattner2b2453a2009-01-17 06:22:33 +0000489
Chris Lattner23b5dc62009-02-04 00:40:31 +0000490//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000491// SourceLocation manipulation methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000492//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000493
494/// getFileIDSlow - Return the FileID for a SourceLocation. This is a very hot
495/// method that is used for all SourceManager queries that start with a
496/// SourceLocation object. It is responsible for finding the entry in
497/// SLocEntryTable which contains the specified location.
498///
499FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
500 assert(SLocOffset && "Invalid FileID");
Mike Stump1eb44332009-09-09 15:08:12 +0000501
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000502 // After the first and second level caches, I see two common sorts of
503 // behavior: 1) a lot of searched FileID's are "near" the cached file location
504 // or are "near" the cached instantiation location. 2) others are just
505 // completely random and may be a very long way away.
506 //
507 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
508 // then we fall back to a less cache efficient, but more scalable, binary
509 // search to find the location.
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000511 // See if this is near the file point - worst case we start scanning from the
512 // most newly created FileID.
513 std::vector<SrcMgr::SLocEntry>::const_iterator I;
Mike Stump1eb44332009-09-09 15:08:12 +0000514
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000515 if (SLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
516 // Neither loc prunes our search.
517 I = SLocEntryTable.end();
518 } else {
519 // Perhaps it is near the file point.
520 I = SLocEntryTable.begin()+LastFileIDLookup.ID;
521 }
522
523 // Find the FileID that contains this. "I" is an iterator that points to a
524 // FileID whose offset is known to be larger than SLocOffset.
525 unsigned NumProbes = 0;
526 while (1) {
527 --I;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000528 if (ExternalSLocEntries)
529 getSLocEntry(FileID::get(I - SLocEntryTable.begin()));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000530 if (I->getOffset() <= SLocOffset) {
531#if 0
532 printf("lin %d -> %d [%s] %d %d\n", SLocOffset,
533 I-SLocEntryTable.begin(),
534 I->isInstantiation() ? "inst" : "file",
535 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
536#endif
537 FileID Res = FileID::get(I-SLocEntryTable.begin());
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000538
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000539 // If this isn't an instantiation, remember it. We have good locality
540 // across FileID lookups.
541 if (!I->isInstantiation())
542 LastFileIDLookup = Res;
543 NumLinearScans += NumProbes+1;
544 return Res;
545 }
546 if (++NumProbes == 8)
547 break;
548 }
Mike Stump1eb44332009-09-09 15:08:12 +0000549
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000550 // Convert "I" back into an index. We know that it is an entry whose index is
551 // larger than the offset we are looking for.
552 unsigned GreaterIndex = I-SLocEntryTable.begin();
553 // LessIndex - This is the lower bound of the range that we're searching.
554 // We know that the offset corresponding to the FileID is is less than
555 // SLocOffset.
556 unsigned LessIndex = 0;
557 NumProbes = 0;
558 while (1) {
559 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000560 unsigned MidOffset = getSLocEntry(FileID::get(MiddleIndex)).getOffset();
Mike Stump1eb44332009-09-09 15:08:12 +0000561
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000562 ++NumProbes;
Mike Stump1eb44332009-09-09 15:08:12 +0000563
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000564 // If the offset of the midpoint is too large, chop the high side of the
565 // range to the midpoint.
566 if (MidOffset > SLocOffset) {
567 GreaterIndex = MiddleIndex;
568 continue;
569 }
Mike Stump1eb44332009-09-09 15:08:12 +0000570
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000571 // If the middle index contains the value, succeed and return.
572 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
573#if 0
574 printf("bin %d -> %d [%s] %d %d\n", SLocOffset,
575 I-SLocEntryTable.begin(),
576 I->isInstantiation() ? "inst" : "file",
577 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
578#endif
579 FileID Res = FileID::get(MiddleIndex);
580
581 // If this isn't an instantiation, remember it. We have good locality
582 // across FileID lookups.
583 if (!I->isInstantiation())
584 LastFileIDLookup = Res;
585 NumBinaryProbes += NumProbes;
586 return Res;
587 }
Mike Stump1eb44332009-09-09 15:08:12 +0000588
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000589 // Otherwise, move the low-side up to the middle index.
590 LessIndex = MiddleIndex;
591 }
592}
593
Chris Lattneraddb7972009-01-26 20:04:19 +0000594SourceLocation SourceManager::
595getInstantiationLocSlowCase(SourceLocation Loc) const {
596 do {
Chris Lattnera5c6c582010-02-12 19:31:35 +0000597 // Note: If Loc indicates an offset into a token that came from a macro
598 // expansion (e.g. the 5th character of the token) we do not want to add
599 // this offset when going to the instantiation location. The instatiation
600 // location is the macro invocation, which the offset has nothing to do
601 // with. This is unlike when we get the spelling loc, because the offset
602 // directly correspond to the token whose spelling we're inspecting.
603 Loc = getSLocEntry(getFileID(Loc)).getInstantiation()
Chris Lattnere7fb4842009-02-15 20:52:18 +0000604 .getInstantiationLocStart();
Chris Lattneraddb7972009-01-26 20:04:19 +0000605 } while (!Loc.isFileID());
606
607 return Loc;
608}
609
610SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
611 do {
612 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
613 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
614 Loc = Loc.getFileLocWithOffset(LocInfo.second);
615 } while (!Loc.isFileID());
616 return Loc;
617}
618
619
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000620std::pair<FileID, unsigned>
621SourceManager::getDecomposedInstantiationLocSlowCase(const SrcMgr::SLocEntry *E,
622 unsigned Offset) const {
623 // If this is an instantiation record, walk through all the instantiation
624 // points.
625 FileID FID;
626 SourceLocation Loc;
627 do {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000628 Loc = E->getInstantiation().getInstantiationLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000629
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000630 FID = getFileID(Loc);
631 E = &getSLocEntry(FID);
632 Offset += Loc.getOffset()-E->getOffset();
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000633 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000634
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000635 return std::make_pair(FID, Offset);
636}
637
638std::pair<FileID, unsigned>
639SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
640 unsigned Offset) const {
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000641 // If this is an instantiation record, walk through all the instantiation
642 // points.
643 FileID FID;
644 SourceLocation Loc;
645 do {
646 Loc = E->getInstantiation().getSpellingLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000647
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000648 FID = getFileID(Loc);
649 E = &getSLocEntry(FID);
650 Offset += Loc.getOffset()-E->getOffset();
651 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000652
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000653 return std::make_pair(FID, Offset);
654}
655
Chris Lattner387616e2009-02-17 08:04:48 +0000656/// getImmediateSpellingLoc - Given a SourceLocation object, return the
657/// spelling location referenced by the ID. This is the first level down
658/// towards the place where the characters that make up the lexed token can be
659/// found. This should not generally be used by clients.
660SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
661 if (Loc.isFileID()) return Loc;
662 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
663 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
664 return Loc.getFileLocWithOffset(LocInfo.second);
665}
666
667
Chris Lattnere7fb4842009-02-15 20:52:18 +0000668/// getImmediateInstantiationRange - Loc is required to be an instantiation
669/// location. Return the start/end of the instantiation information.
670std::pair<SourceLocation,SourceLocation>
671SourceManager::getImmediateInstantiationRange(SourceLocation Loc) const {
672 assert(Loc.isMacroID() && "Not an instantiation loc!");
673 const InstantiationInfo &II = getSLocEntry(getFileID(Loc)).getInstantiation();
674 return II.getInstantiationLocRange();
675}
676
Chris Lattner66781332009-02-15 21:26:50 +0000677/// getInstantiationRange - Given a SourceLocation object, return the
678/// range of tokens covered by the instantiation in the ultimate file.
679std::pair<SourceLocation,SourceLocation>
680SourceManager::getInstantiationRange(SourceLocation Loc) const {
681 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000682
Chris Lattner66781332009-02-15 21:26:50 +0000683 std::pair<SourceLocation,SourceLocation> Res =
684 getImmediateInstantiationRange(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000685
Chris Lattner66781332009-02-15 21:26:50 +0000686 // Fully resolve the start and end locations to their ultimate instantiation
687 // points.
688 while (!Res.first.isFileID())
689 Res.first = getImmediateInstantiationRange(Res.first).first;
690 while (!Res.second.isFileID())
691 Res.second = getImmediateInstantiationRange(Res.second).second;
692 return Res;
693}
694
Chris Lattnere7fb4842009-02-15 20:52:18 +0000695
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000696
697//===----------------------------------------------------------------------===//
698// Queries about the code at a SourceLocation.
699//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000700
701/// getCharacterData - Return a pointer to the start of the specified location
702/// in the appropriate MemoryBuffer.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000703const char *SourceManager::getCharacterData(SourceLocation SL,
704 bool *Invalid) const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000705 // Note that this is a hot function in the getSpelling() path, which is
706 // heavily used by -E mode.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000707 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump1eb44332009-09-09 15:08:12 +0000708
Ted Kremenekc16c2082009-01-06 01:55:26 +0000709 // Note that calling 'getBuffer()' may lazily page in a source file.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000710 bool CharDataInvalid = false;
711 const llvm::MemoryBuffer *Buffer
712 = getSLocEntry(LocInfo.first).getFile().getContentCache()->getBuffer(Diag,
713 &CharDataInvalid);
714 if (Invalid)
715 *Invalid = CharDataInvalid;
716 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
Reid Spencer5f016e22007-07-11 17:01:13 +0000717}
718
Reid Spencer5f016e22007-07-11 17:01:13 +0000719
Chris Lattner9dc1f532007-07-20 16:37:10 +0000720/// getColumnNumber - Return the column # for the specified file position.
Chris Lattner7da5aea2009-02-04 00:55:58 +0000721/// this is significantly cheaper to compute than the line number.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000722unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
723 bool *Invalid) const {
724 bool MyInvalid = false;
725 const char *Buf = getBuffer(FID, &MyInvalid)->getBufferStart();
726 if (Invalid)
727 *Invalid = MyInvalid;
728
729 if (MyInvalid)
730 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Reid Spencer5f016e22007-07-11 17:01:13 +0000732 unsigned LineStart = FilePos;
733 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
734 --LineStart;
735 return FilePos-LineStart+1;
736}
737
Douglas Gregor50f6af72010-03-16 05:20:39 +0000738unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
739 bool *Invalid) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000740 if (Loc.isInvalid()) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000741 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000742 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000743}
744
Douglas Gregor50f6af72010-03-16 05:20:39 +0000745unsigned SourceManager::getInstantiationColumnNumber(SourceLocation Loc,
746 bool *Invalid) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000747 if (Loc.isInvalid()) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000748 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000749 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000750}
751
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000752static DISABLE_INLINE void ComputeLineNumbers(Diagnostic &Diag,
753 ContentCache* FI,
Douglas Gregor50f6af72010-03-16 05:20:39 +0000754 llvm::BumpPtrAllocator &Alloc,
755 bool &Invalid);
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000756static void ComputeLineNumbers(Diagnostic &Diag, ContentCache* FI,
Douglas Gregor50f6af72010-03-16 05:20:39 +0000757 llvm::BumpPtrAllocator &Alloc, bool &Invalid) {
Ted Kremenekc16c2082009-01-06 01:55:26 +0000758 // Note that calling 'getBuffer()' may lazily page in the file.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000759 const MemoryBuffer *Buffer = FI->getBuffer(Diag, &Invalid);
760 if (Invalid)
761 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000762
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000763 // Find the file offsets of all of the *physical* source lines. This does
764 // not look at trigraphs, escaped newlines, or anything else tricky.
765 std::vector<unsigned> LineOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +0000766
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000767 // Line #1 starts at char 0.
768 LineOffsets.push_back(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000769
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000770 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
771 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
772 unsigned Offs = 0;
773 while (1) {
774 // Skip over the contents of the line.
775 // TODO: Vectorize this? This is very performance sensitive for programs
776 // with lots of diagnostics and in -E mode.
777 const unsigned char *NextBuf = (const unsigned char *)Buf;
778 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
779 ++NextBuf;
780 Offs += NextBuf-Buf;
781 Buf = NextBuf;
Mike Stump1eb44332009-09-09 15:08:12 +0000782
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000783 if (Buf[0] == '\n' || Buf[0] == '\r') {
784 // If this is \n\r or \r\n, skip both characters.
785 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
786 ++Offs, ++Buf;
787 ++Offs, ++Buf;
788 LineOffsets.push_back(Offs);
789 } else {
790 // Otherwise, this is a null. If end of file, exit.
791 if (Buf == End) break;
792 // Otherwise, skip the null.
793 ++Offs, ++Buf;
794 }
795 }
Mike Stump1eb44332009-09-09 15:08:12 +0000796
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000797 // Copy the offsets into the FileInfo structure.
798 FI->NumLines = LineOffsets.size();
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000799 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000800 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
801}
Reid Spencer5f016e22007-07-11 17:01:13 +0000802
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000803/// getLineNumber - Given a SourceLocation, return the spelling line number
Reid Spencer5f016e22007-07-11 17:01:13 +0000804/// for the position indicated. This requires building and caching a table of
805/// line offsets for the MemoryBuffer, so this is not cheap: use only when
806/// about to emit a diagnostic.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000807unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
808 bool *Invalid) const {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000809 ContentCache *Content;
Chris Lattner30fc9332009-02-04 01:06:56 +0000810 if (LastLineNoFileIDQuery == FID)
Ted Kremenek78d85f52007-10-30 21:08:08 +0000811 Content = LastLineNoContentCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000812 else
Chris Lattner30fc9332009-02-04 01:06:56 +0000813 Content = const_cast<ContentCache*>(getSLocEntry(FID)
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000814 .getFile().getContentCache());
Mike Stump1eb44332009-09-09 15:08:12 +0000815
Reid Spencer5f016e22007-07-11 17:01:13 +0000816 // If this is the first use of line information for this buffer, compute the
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000817 /// SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000818 if (Content->SourceLineCache == 0) {
819 bool MyInvalid = false;
820 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, MyInvalid);
821 if (Invalid)
822 *Invalid = MyInvalid;
823 if (MyInvalid)
824 return 1;
825 } else if (Invalid)
826 *Invalid = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000827
828 // Okay, we know we have a line number table. Do a binary search to find the
829 // line number that this character position lands on.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000830 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000831 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenek78d85f52007-10-30 21:08:08 +0000832 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump1eb44332009-09-09 15:08:12 +0000833
Chris Lattner30fc9332009-02-04 01:06:56 +0000834 unsigned QueriedFilePos = FilePos+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000835
Daniel Dunbar4106d692009-05-18 17:30:52 +0000836 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump1eb44332009-09-09 15:08:12 +0000837 // complicated as it is, binary search isn't that slow.
Daniel Dunbar4106d692009-05-18 17:30:52 +0000838 //
839 // If it is worth being optimized, then in my opinion it could be more
840 // performant, simpler, and more obviously correct by just "galloping" outward
841 // from the queried file position. In fact, this could be incorporated into a
842 // generic algorithm such as lower_bound_with_hint.
843 //
844 // If someone gives me a test case where this matters, and I will do it! - DWD
845
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000846 // If the previous query was to the same file, we know both the file pos from
847 // that query and the line number returned. This allows us to narrow the
848 // search space from the entire file to something near the match.
Chris Lattner30fc9332009-02-04 01:06:56 +0000849 if (LastLineNoFileIDQuery == FID) {
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000850 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar4106d692009-05-18 17:30:52 +0000851 // FIXME: Potential overflow?
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000852 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump1eb44332009-09-09 15:08:12 +0000853
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000854 // The query is likely to be nearby the previous one. Here we check to
855 // see if it is within 5, 10 or 20 lines. It can be far away in cases
856 // where big comment blocks and vertical whitespace eat up lines but
857 // contribute no tokens.
858 if (SourceLineCache+5 < SourceLineCacheEnd) {
859 if (SourceLineCache[5] > QueriedFilePos)
860 SourceLineCacheEnd = SourceLineCache+5;
861 else if (SourceLineCache+10 < SourceLineCacheEnd) {
862 if (SourceLineCache[10] > QueriedFilePos)
863 SourceLineCacheEnd = SourceLineCache+10;
864 else if (SourceLineCache+20 < SourceLineCacheEnd) {
865 if (SourceLineCache[20] > QueriedFilePos)
866 SourceLineCacheEnd = SourceLineCache+20;
867 }
868 }
869 }
870 } else {
Daniel Dunbar4106d692009-05-18 17:30:52 +0000871 if (LastLineNoResult < Content->NumLines)
872 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000873 }
874 }
Mike Stump1eb44332009-09-09 15:08:12 +0000875
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000876 // If the spread is large, do a "radix" test as our initial guess, based on
877 // the assumption that lines average to approximately the same length.
878 // NOTE: This is currently disabled, as it does not appear to be profitable in
879 // initial measurements.
880 if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
Ted Kremenek78d85f52007-10-30 21:08:08 +0000881 unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
Mike Stump1eb44332009-09-09 15:08:12 +0000882
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000883 // Take a stab at guessing where it is.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000884 unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
Mike Stump1eb44332009-09-09 15:08:12 +0000885
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000886 // Check for -10 and +10 lines.
887 unsigned LowerBound = std::max(int(ApproxPos-10), 0);
888 unsigned UpperBound = std::min(ApproxPos+10, FileLen);
889
890 // If the computed lower bound is less than the query location, move it in.
891 if (SourceLineCache < SourceLineCacheStart+LowerBound &&
892 SourceLineCacheStart[LowerBound] < QueriedFilePos)
893 SourceLineCache = SourceLineCacheStart+LowerBound;
Mike Stump1eb44332009-09-09 15:08:12 +0000894
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000895 // If the computed upper bound is greater than the query location, move it.
896 if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
897 SourceLineCacheStart[UpperBound] >= QueriedFilePos)
898 SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
899 }
Mike Stump1eb44332009-09-09 15:08:12 +0000900
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000901 unsigned *Pos
902 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000903 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump1eb44332009-09-09 15:08:12 +0000904
Chris Lattner30fc9332009-02-04 01:06:56 +0000905 LastLineNoFileIDQuery = FID;
Ted Kremenek78d85f52007-10-30 21:08:08 +0000906 LastLineNoContentCache = Content;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000907 LastLineNoFilePos = QueriedFilePos;
908 LastLineNoResult = LineNo;
909 return LineNo;
Reid Spencer5f016e22007-07-11 17:01:13 +0000910}
911
Douglas Gregor50f6af72010-03-16 05:20:39 +0000912unsigned SourceManager::getInstantiationLineNumber(SourceLocation Loc,
913 bool *Invalid) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000914 if (Loc.isInvalid()) return 0;
915 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
916 return getLineNumber(LocInfo.first, LocInfo.second);
917}
Douglas Gregor50f6af72010-03-16 05:20:39 +0000918unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
919 bool *Invalid) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000920 if (Loc.isInvalid()) return 0;
921 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
922 return getLineNumber(LocInfo.first, LocInfo.second);
923}
924
Chris Lattner6b306672009-02-04 05:33:01 +0000925/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump1eb44332009-09-09 15:08:12 +0000926/// source location, indicating whether this is a normal file, a system
Chris Lattner6b306672009-02-04 05:33:01 +0000927/// header, or an "implicit extern C" system header.
928///
929/// This state can be modified with flags on GNU linemarker directives like:
930/// # 4 "foo.h" 3
931/// which changes all source locations in the current file after that to be
932/// considered to be from a system header.
Mike Stump1eb44332009-09-09 15:08:12 +0000933SrcMgr::CharacteristicKind
Chris Lattner6b306672009-02-04 05:33:01 +0000934SourceManager::getFileCharacteristic(SourceLocation Loc) const {
935 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
936 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
937 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
938
939 // If there are no #line directives in this file, just return the whole-file
940 // state.
941 if (!FI.hasLineDirectives())
942 return FI.getFileCharacteristic();
Mike Stump1eb44332009-09-09 15:08:12 +0000943
Chris Lattner6b306672009-02-04 05:33:01 +0000944 assert(LineTable && "Can't have linetable entries without a LineTable!");
945 // See if there is a #line directive before the location.
946 const LineEntry *Entry =
947 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second);
Mike Stump1eb44332009-09-09 15:08:12 +0000948
Chris Lattner6b306672009-02-04 05:33:01 +0000949 // If this is before the first line marker, use the file characteristic.
950 if (!Entry)
951 return FI.getFileCharacteristic();
952
953 return Entry->FileKind;
954}
955
Chris Lattnerbff5c512009-02-17 08:39:06 +0000956/// Return the filename or buffer identifier of the buffer the location is in.
957/// Note that this name does not respect #line directives. Use getPresumedLoc
958/// for normal clients.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000959const char *SourceManager::getBufferName(SourceLocation Loc,
960 bool *Invalid) const {
Chris Lattnerbff5c512009-02-17 08:39:06 +0000961 if (Loc.isInvalid()) return "<invalid loc>";
Mike Stump1eb44332009-09-09 15:08:12 +0000962
Douglas Gregor50f6af72010-03-16 05:20:39 +0000963 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
Chris Lattnerbff5c512009-02-17 08:39:06 +0000964}
965
Chris Lattner30fc9332009-02-04 01:06:56 +0000966
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000967/// getPresumedLoc - This method returns the "presumed" location of a
968/// SourceLocation specifies. A "presumed location" can be modified by #line
969/// or GNU line marker directives. This provides a view on the data that a
970/// user should see in diagnostics, for example.
971///
972/// Note that a presumed location is always given as the instantiation point
973/// of an instantiation location, not at the spelling location.
974PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
975 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000976
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000977 // Presumed locations are always for instantiation points.
Chris Lattner7da5aea2009-02-04 00:55:58 +0000978 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000979
Chris Lattner30fc9332009-02-04 01:06:56 +0000980 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000981 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump1eb44332009-09-09 15:08:12 +0000982
Chris Lattner3cd949c2009-02-04 01:55:42 +0000983 // To get the source name, first consult the FileEntry (if one exists)
984 // before the MemBuffer as this will avoid unnecessarily paging in the
985 // MemBuffer.
Mike Stump1eb44332009-09-09 15:08:12 +0000986 const char *Filename =
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000987 C->Entry ? C->Entry->getName() : C->getBuffer(Diag)->getBufferIdentifier();
Chris Lattner3cd949c2009-02-04 01:55:42 +0000988 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second);
989 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second);
990 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000991
Chris Lattner3cd949c2009-02-04 01:55:42 +0000992 // If we have #line directives in this file, update and overwrite the physical
993 // location info if appropriate.
994 if (FI.hasLineDirectives()) {
995 assert(LineTable && "Can't have linetable entries without a LineTable!");
996 // See if there is a #line directive before this. If so, get it.
997 if (const LineEntry *Entry =
998 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) {
Chris Lattnerfc391332009-02-04 02:00:59 +0000999 // If the LineEntry indicates a filename, use it.
Chris Lattner3cd949c2009-02-04 01:55:42 +00001000 if (Entry->FilenameID != -1)
1001 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerfc391332009-02-04 02:00:59 +00001002
1003 // Use the line number specified by the LineEntry. This line number may
1004 // be multiple lines down from the line entry. Add the difference in
1005 // physical line numbers from the query point and the line marker to the
1006 // total.
1007 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1008 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001009
Chris Lattner0e0e5da2009-02-04 02:15:40 +00001010 // Note that column numbers are not molested by line markers.
Mike Stump1eb44332009-09-09 15:08:12 +00001011
Chris Lattner137b6a62009-02-04 06:25:26 +00001012 // Handle virtual #include manipulation.
1013 if (Entry->IncludeOffset) {
1014 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1015 IncludeLoc = IncludeLoc.getFileLocWithOffset(Entry->IncludeOffset);
1016 }
Chris Lattner3cd949c2009-02-04 01:55:42 +00001017 }
1018 }
1019
1020 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001021}
1022
1023//===----------------------------------------------------------------------===//
1024// Other miscellaneous methods.
1025//===----------------------------------------------------------------------===//
1026
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001027/// \brief Get the source location for the given file:line:col triplet.
1028///
1029/// If the source file is included multiple times, the source location will
1030/// be based upon the first inclusion.
1031SourceLocation SourceManager::getLocation(const FileEntry *SourceFile,
1032 unsigned Line, unsigned Col) const {
1033 assert(SourceFile && "Null source file!");
1034 assert(Line && Col && "Line and column should start from 1!");
1035
1036 fileinfo_iterator FI = FileInfos.find(SourceFile);
1037 if (FI == FileInfos.end())
1038 return SourceLocation();
1039 ContentCache *Content = FI->second;
Mike Stump1eb44332009-09-09 15:08:12 +00001040
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001041 // If this is the first use of line information for this buffer, compute the
1042 /// SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001043 if (Content->SourceLineCache == 0) {
1044 bool MyInvalid = false;
1045 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, MyInvalid);
1046 if (MyInvalid)
1047 return SourceLocation();
1048 }
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001049
Douglas Gregor4a160e12009-12-02 05:34:39 +00001050 // Find the first file ID that corresponds to the given file.
1051 FileID FirstFID;
1052
1053 // First, check the main file ID, since it is common to look for a
1054 // location in the main file.
1055 if (!MainFileID.isInvalid()) {
1056 const SLocEntry &MainSLoc = getSLocEntry(MainFileID);
1057 if (MainSLoc.isFile() && MainSLoc.getFile().getContentCache() == Content)
1058 FirstFID = MainFileID;
1059 }
1060
1061 if (FirstFID.isInvalid()) {
1062 // The location we're looking for isn't in the main file; look
1063 // through all of the source locations.
1064 for (unsigned I = 0, N = sloc_entry_size(); I != N; ++I) {
1065 const SLocEntry &SLoc = getSLocEntry(I);
1066 if (SLoc.isFile() && SLoc.getFile().getContentCache() == Content) {
1067 FirstFID = FileID::get(I);
1068 break;
1069 }
1070 }
1071 }
1072
1073 if (FirstFID.isInvalid())
1074 return SourceLocation();
1075
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001076 if (Line > Content->NumLines) {
Douglas Gregor36c35ba2010-03-16 00:35:39 +00001077 unsigned Size = Content->getBuffer(Diag)->getBufferSize();
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001078 if (Size > 0)
1079 --Size;
1080 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(Size);
1081 }
1082
1083 unsigned FilePos = Content->SourceLineCache[Line - 1];
Douglas Gregor36c35ba2010-03-16 00:35:39 +00001084 const char *Buf = Content->getBuffer(Diag)->getBufferStart() + FilePos;
1085 unsigned BufLength = Content->getBuffer(Diag)->getBufferEnd() - Buf;
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001086 unsigned i = 0;
1087
1088 // Check that the given column is valid.
1089 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1090 ++i;
1091 if (i < Col-1)
1092 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + i);
1093
Douglas Gregor4a160e12009-12-02 05:34:39 +00001094 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + Col - 1);
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001095}
1096
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001097/// \brief Determines the order of 2 source locations in the translation unit.
1098///
1099/// \returns true if LHS source location comes before RHS, false otherwise.
1100bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1101 SourceLocation RHS) const {
1102 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1103 if (LHS == RHS)
1104 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001105
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001106 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1107 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00001108
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001109 // If the source locations are in the same file, just compare offsets.
1110 if (LOffs.first == ROffs.first)
1111 return LOffs.second < ROffs.second;
1112
1113 // If we are comparing a source location with multiple locations in the same
1114 // file, we get a big win by caching the result.
Mike Stump1eb44332009-09-09 15:08:12 +00001115
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001116 if (LastLFIDForBeforeTUCheck == LOffs.first &&
1117 LastRFIDForBeforeTUCheck == ROffs.first)
1118 return LastResForBeforeTUCheck;
Mike Stump1eb44332009-09-09 15:08:12 +00001119
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001120 LastLFIDForBeforeTUCheck = LOffs.first;
1121 LastRFIDForBeforeTUCheck = ROffs.first;
Mike Stump1eb44332009-09-09 15:08:12 +00001122
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001123 // "Traverse" the include/instantiation stacks of both locations and try to
1124 // find a common "ancestor".
1125 //
1126 // First we traverse the stack of the right location and check each level
1127 // against the level of the left location, while collecting all levels in a
1128 // "stack map".
1129
1130 std::map<FileID, unsigned> ROffsMap;
1131 ROffsMap[ROffs.first] = ROffs.second;
1132
1133 while (1) {
1134 SourceLocation UpperLoc;
1135 const SrcMgr::SLocEntry &Entry = getSLocEntry(ROffs.first);
1136 if (Entry.isInstantiation())
1137 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1138 else
1139 UpperLoc = Entry.getFile().getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001140
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001141 if (UpperLoc.isInvalid())
1142 break; // We reached the top.
Mike Stump1eb44332009-09-09 15:08:12 +00001143
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001144 ROffs = getDecomposedLoc(UpperLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001146 if (LOffs.first == ROffs.first)
1147 return LastResForBeforeTUCheck = LOffs.second < ROffs.second;
Mike Stump1eb44332009-09-09 15:08:12 +00001148
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001149 ROffsMap[ROffs.first] = ROffs.second;
1150 }
1151
1152 // We didn't find a common ancestor. Now traverse the stack of the left
1153 // location, checking against the stack map of the right location.
1154
1155 while (1) {
1156 SourceLocation UpperLoc;
1157 const SrcMgr::SLocEntry &Entry = getSLocEntry(LOffs.first);
1158 if (Entry.isInstantiation())
1159 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1160 else
1161 UpperLoc = Entry.getFile().getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001162
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001163 if (UpperLoc.isInvalid())
1164 break; // We reached the top.
Mike Stump1eb44332009-09-09 15:08:12 +00001165
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001166 LOffs = getDecomposedLoc(UpperLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001167
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001168 std::map<FileID, unsigned>::iterator I = ROffsMap.find(LOffs.first);
1169 if (I != ROffsMap.end())
1170 return LastResForBeforeTUCheck = LOffs.second < I->second;
1171 }
Mike Stump1eb44332009-09-09 15:08:12 +00001172
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001173 // There is no common ancestor, most probably because one location is in the
1174 // predefines buffer.
1175 //
1176 // FIXME: We should rearrange the external interface so this simply never
1177 // happens; it can't conceptually happen. Also see PR5662.
Mike Stump1eb44332009-09-09 15:08:12 +00001178
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001179 // If exactly one location is a memory buffer, assume it preceeds the other.
1180 bool LIsMB = !getSLocEntry(LOffs.first).getFile().getContentCache()->Entry;
1181 bool RIsMB = !getSLocEntry(ROffs.first).getFile().getContentCache()->Entry;
1182 if (LIsMB != RIsMB)
1183 return LastResForBeforeTUCheck = LIsMB;
Mike Stump1eb44332009-09-09 15:08:12 +00001184
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001185 // Otherwise, just assume FileIDs were created in order.
1186 return LastResForBeforeTUCheck = (LOffs.first < ROffs.first);
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001187}
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001188
Reid Spencer5f016e22007-07-11 17:01:13 +00001189/// PrintStats - Print statistics to stderr.
1190///
1191void SourceManager::PrintStats() const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001192 llvm::errs() << "\n*** Source Manager Stats:\n";
1193 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
1194 << " mem buffers mapped.\n";
1195 llvm::errs() << SLocEntryTable.size() << " SLocEntry's allocated, "
1196 << NextOffset << "B of Sloc address space used.\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001197
Reid Spencer5f016e22007-07-11 17:01:13 +00001198 unsigned NumLineNumsComputed = 0;
1199 unsigned NumFileBytesMapped = 0;
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00001200 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
1201 NumLineNumsComputed += I->second->SourceLineCache != 0;
1202 NumFileBytesMapped += I->second->getSizeBytesMapped();
Reid Spencer5f016e22007-07-11 17:01:13 +00001203 }
Mike Stump1eb44332009-09-09 15:08:12 +00001204
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001205 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
1206 << NumLineNumsComputed << " files with line #'s computed.\n";
1207 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
1208 << NumBinaryProbes << " binary.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +00001209}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001210
1211ExternalSLocEntrySource::~ExternalSLocEntrySource() { }