blob: 6def967c4cfa279c4c601016202232fa38e08218 [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() {
Douglas Gregorc8151082010-03-16 22:53:51 +000035 delete Buffer.getPointer();
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 {
Douglas Gregorc8151082010-03-16 22:53:51 +000042 return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
Ted Kremenekc16c2082009-01-06 01:55:26 +000043}
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 {
Douglas Gregorc8151082010-03-16 22:53:51 +000050 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->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 Gregorc8151082010-03-16 22:53:51 +000055 assert(B != Buffer.getPointer());
Douglas Gregor29684422009-12-02 06:49:09 +000056
Douglas Gregorc8151082010-03-16 22:53:51 +000057 delete Buffer.getPointer();
58 Buffer.setPointer(B);
59 Buffer.setInt(false);
Douglas Gregor29684422009-12-02 06:49:09 +000060}
61
Douglas Gregor36c35ba2010-03-16 00:35:39 +000062const llvm::MemoryBuffer *ContentCache::getBuffer(Diagnostic &Diag,
63 bool *Invalid) const {
64 if (Invalid)
65 *Invalid = false;
66
Ted Kremenek5b034ad2009-01-06 22:43:04 +000067 // Lazily create the Buffer for ContentCaches that wrap files.
Douglas Gregorc8151082010-03-16 22:53:51 +000068 if (!Buffer.getPointer() && Entry) {
Douglas Gregoraea67db2010-03-15 22:54:52 +000069 std::string ErrorStr;
70 struct stat FileInfo;
Douglas Gregorc8151082010-03-16 22:53:51 +000071 Buffer.setPointer(MemoryBuffer::getFile(Entry->getName(), &ErrorStr,
72 Entry->getSize(), &FileInfo));
73 Buffer.setInt(false);
74
Daniel Dunbar21a8bed2009-12-06 05:43:36 +000075 // If we were unable to open the file, then we are in an inconsistent
76 // situation where the content cache referenced a file which no longer
77 // exists. Most likely, we were using a stat cache with an invalid entry but
78 // the file could also have been removed during processing. Since we can't
79 // really deal with this situation, just create an empty buffer.
80 //
81 // FIXME: This is definitely not ideal, but our immediate clients can't
82 // currently handle returning a null entry here. Ideally we should detect
83 // that we are in an inconsistent situation and error out as quickly as
84 // possible.
Douglas Gregorc8151082010-03-16 22:53:51 +000085 if (!Buffer.getPointer()) {
Daniel Dunbar21a8bed2009-12-06 05:43:36 +000086 const llvm::StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
Douglas Gregorc8151082010-03-16 22:53:51 +000087 Buffer.setPointer(MemoryBuffer::getNewMemBuffer(Entry->getSize(),
88 "<invalid>"));
89 char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart());
Daniel Dunbar21a8bed2009-12-06 05:43:36 +000090 for (unsigned i = 0, e = Entry->getSize(); i != e; ++i)
91 Ptr[i] = FillStr[i % FillStr.size()];
Douglas Gregor36c35ba2010-03-16 00:35:39 +000092 Diag.Report(diag::err_cannot_open_file)
93 << Entry->getName() << ErrorStr;
Douglas Gregorc8151082010-03-16 22:53:51 +000094 Buffer.setInt(true);
Douglas Gregore39b6002010-03-17 15:30:15 +000095 } else if (FileInfo.st_size != Entry->getSize() ||
Douglas Gregor0419a232010-03-17 15:33:06 +000096 FileInfo.st_mtime != Entry->getModificationTime() ||
97 FileInfo.st_ino != Entry->getInode()) {
98 // Check that the file's size, modification time, and inode are
99 // the same as in the file entry (which may have come from a
100 // stat cache).
Douglas Gregore39b6002010-03-17 15:30:15 +0000101 Diag.Report(diag::err_file_modified) << Entry->getName();
102 Buffer.setInt(true);
Daniel Dunbar21a8bed2009-12-06 05:43:36 +0000103 }
Ted Kremenek5b034ad2009-01-06 22:43:04 +0000104 }
Douglas Gregoraea67db2010-03-15 22:54:52 +0000105
Douglas Gregorc8151082010-03-16 22:53:51 +0000106 if (Invalid)
107 *Invalid = Buffer.getInt();
108
109 return Buffer.getPointer();
Ted Kremenekc16c2082009-01-06 01:55:26 +0000110}
111
Chris Lattner5b9a5042009-01-26 07:57:50 +0000112unsigned LineTableInfo::getLineTableFilenameID(const char *Ptr, unsigned Len) {
113 // Look up the filename in the string table, returning the pre-existing value
114 // if it exists.
Mike Stump1eb44332009-09-09 15:08:12 +0000115 llvm::StringMapEntry<unsigned> &Entry =
Chris Lattner5b9a5042009-01-26 07:57:50 +0000116 FilenameIDs.GetOrCreateValue(Ptr, Ptr+Len, ~0U);
117 if (Entry.getValue() != ~0U)
118 return Entry.getValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Chris Lattner5b9a5042009-01-26 07:57:50 +0000120 // Otherwise, assign this the next available ID.
121 Entry.setValue(FilenamesByID.size());
122 FilenamesByID.push_back(&Entry);
123 return FilenamesByID.size()-1;
124}
125
Chris Lattnerac50e342009-02-03 22:13:05 +0000126/// AddLineNote - Add a line note to the line table that indicates that there
127/// is a #line at the specified FID/Offset location which changes the presumed
128/// location to LineNo/FilenameID.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000129void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
Chris Lattnerac50e342009-02-03 22:13:05 +0000130 unsigned LineNo, int FilenameID) {
Chris Lattner23b5dc62009-02-04 00:40:31 +0000131 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000132
Chris Lattner23b5dc62009-02-04 00:40:31 +0000133 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
134 "Adding line entries out of order!");
Mike Stump1eb44332009-09-09 15:08:12 +0000135
Chris Lattner9d79eba2009-02-04 05:21:58 +0000136 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
Chris Lattner137b6a62009-02-04 06:25:26 +0000137 unsigned IncludeOffset = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000138
Chris Lattner9d79eba2009-02-04 05:21:58 +0000139 if (!Entries.empty()) {
140 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
141 // that we are still in "foo.h".
142 if (FilenameID == -1)
143 FilenameID = Entries.back().FilenameID;
Mike Stump1eb44332009-09-09 15:08:12 +0000144
Chris Lattner137b6a62009-02-04 06:25:26 +0000145 // If we are after a line marker that switched us to system header mode, or
146 // that set #include information, preserve it.
Chris Lattner9d79eba2009-02-04 05:21:58 +0000147 Kind = Entries.back().FileKind;
Chris Lattner137b6a62009-02-04 06:25:26 +0000148 IncludeOffset = Entries.back().IncludeOffset;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000149 }
Mike Stump1eb44332009-09-09 15:08:12 +0000150
Chris Lattner137b6a62009-02-04 06:25:26 +0000151 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
152 IncludeOffset));
Chris Lattnerac50e342009-02-03 22:13:05 +0000153}
154
Chris Lattner9d79eba2009-02-04 05:21:58 +0000155/// AddLineNote This is the same as the previous version of AddLineNote, but is
156/// used for GNU line markers. If EntryExit is 0, then this doesn't change the
157/// presumed #include stack. If it is 1, this is a file entry, if it is 2 then
158/// this is a file exit. FileKind specifies whether this is a system header or
159/// extern C system header.
160void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
161 unsigned LineNo, int FilenameID,
162 unsigned EntryExit,
163 SrcMgr::CharacteristicKind FileKind) {
164 assert(FilenameID != -1 && "Unspecified filename should use other accessor");
Mike Stump1eb44332009-09-09 15:08:12 +0000165
Chris Lattner9d79eba2009-02-04 05:21:58 +0000166 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000167
Chris Lattner9d79eba2009-02-04 05:21:58 +0000168 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
169 "Adding line entries out of order!");
170
Chris Lattner137b6a62009-02-04 06:25:26 +0000171 unsigned IncludeOffset = 0;
172 if (EntryExit == 0) { // No #include stack change.
173 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
174 } else if (EntryExit == 1) {
175 IncludeOffset = Offset-1;
176 } else if (EntryExit == 2) {
177 assert(!Entries.empty() && Entries.back().IncludeOffset &&
178 "PPDirectives should have caught case when popping empty include stack");
Mike Stump1eb44332009-09-09 15:08:12 +0000179
Chris Lattner137b6a62009-02-04 06:25:26 +0000180 // Get the include loc of the last entries' include loc as our include loc.
181 IncludeOffset = 0;
182 if (const LineEntry *PrevEntry =
183 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
184 IncludeOffset = PrevEntry->IncludeOffset;
185 }
Mike Stump1eb44332009-09-09 15:08:12 +0000186
Chris Lattner137b6a62009-02-04 06:25:26 +0000187 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
188 IncludeOffset));
Chris Lattner9d79eba2009-02-04 05:21:58 +0000189}
190
191
Chris Lattner3cd949c2009-02-04 01:55:42 +0000192/// FindNearestLineEntry - Find the line entry nearest to FID that is before
193/// it. If there is no line entry before Offset in FID, return null.
Mike Stump1eb44332009-09-09 15:08:12 +0000194const LineEntry *LineTableInfo::FindNearestLineEntry(unsigned FID,
Chris Lattner3cd949c2009-02-04 01:55:42 +0000195 unsigned Offset) {
196 const std::vector<LineEntry> &Entries = LineEntries[FID];
197 assert(!Entries.empty() && "No #line entries for this FID after all!");
198
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000199 // It is very common for the query to be after the last #line, check this
200 // first.
201 if (Entries.back().FileOffset <= Offset)
202 return &Entries.back();
Chris Lattner3cd949c2009-02-04 01:55:42 +0000203
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000204 // Do a binary search to find the maximal element that is still before Offset.
205 std::vector<LineEntry>::const_iterator I =
206 std::upper_bound(Entries.begin(), Entries.end(), Offset);
207 if (I == Entries.begin()) return 0;
208 return &*--I;
Chris Lattner3cd949c2009-02-04 01:55:42 +0000209}
Chris Lattnerac50e342009-02-03 22:13:05 +0000210
Douglas Gregorbd945002009-04-13 16:31:14 +0000211/// \brief Add a new line entry that has already been encoded into
212/// the internal representation of the line table.
Mike Stump1eb44332009-09-09 15:08:12 +0000213void LineTableInfo::AddEntry(unsigned FID,
Douglas Gregorbd945002009-04-13 16:31:14 +0000214 const std::vector<LineEntry> &Entries) {
215 LineEntries[FID] = Entries;
216}
Chris Lattnerac50e342009-02-03 22:13:05 +0000217
Chris Lattner5b9a5042009-01-26 07:57:50 +0000218/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
Mike Stump1eb44332009-09-09 15:08:12 +0000219///
Chris Lattner5b9a5042009-01-26 07:57:50 +0000220unsigned SourceManager::getLineTableFilenameID(const char *Ptr, unsigned Len) {
221 if (LineTable == 0)
222 LineTable = new LineTableInfo();
223 return LineTable->getLineTableFilenameID(Ptr, Len);
224}
225
226
Chris Lattner4c4ea172009-02-03 21:52:55 +0000227/// AddLineNote - Add a line note to the line table for the FileID and offset
228/// specified by Loc. If FilenameID is -1, it is considered to be
229/// unspecified.
230void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
231 int FilenameID) {
Chris Lattnerac50e342009-02-03 22:13:05 +0000232 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000233
Chris Lattnerac50e342009-02-03 22:13:05 +0000234 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
235
236 // Remember that this file has #line directives now if it doesn't already.
237 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000238
Chris Lattnerac50e342009-02-03 22:13:05 +0000239 if (LineTable == 0)
240 LineTable = new LineTableInfo();
Chris Lattner23b5dc62009-02-04 00:40:31 +0000241 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID);
Chris Lattner4c4ea172009-02-03 21:52:55 +0000242}
243
Chris Lattner9d79eba2009-02-04 05:21:58 +0000244/// AddLineNote - Add a GNU line marker to the line table.
245void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
246 int FilenameID, bool IsFileEntry,
247 bool IsFileExit, bool IsSystemHeader,
248 bool IsExternCHeader) {
249 // If there is no filename and no flags, this is treated just like a #line,
250 // which does not change the flags of the previous line marker.
251 if (FilenameID == -1) {
252 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
253 "Can't set flags without setting the filename!");
254 return AddLineNote(Loc, LineNo, FilenameID);
255 }
Mike Stump1eb44332009-09-09 15:08:12 +0000256
Chris Lattner9d79eba2009-02-04 05:21:58 +0000257 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
258 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000259
Chris Lattner9d79eba2009-02-04 05:21:58 +0000260 // Remember that this file has #line directives now if it doesn't already.
261 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000262
Chris Lattner9d79eba2009-02-04 05:21:58 +0000263 if (LineTable == 0)
264 LineTable = new LineTableInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000265
Chris Lattner9d79eba2009-02-04 05:21:58 +0000266 SrcMgr::CharacteristicKind FileKind;
267 if (IsExternCHeader)
268 FileKind = SrcMgr::C_ExternCSystem;
269 else if (IsSystemHeader)
270 FileKind = SrcMgr::C_System;
271 else
272 FileKind = SrcMgr::C_User;
Mike Stump1eb44332009-09-09 15:08:12 +0000273
Chris Lattner9d79eba2009-02-04 05:21:58 +0000274 unsigned EntryExit = 0;
275 if (IsFileEntry)
276 EntryExit = 1;
277 else if (IsFileExit)
278 EntryExit = 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Chris Lattner9d79eba2009-02-04 05:21:58 +0000280 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID,
281 EntryExit, FileKind);
282}
283
Douglas Gregorbd945002009-04-13 16:31:14 +0000284LineTableInfo &SourceManager::getLineTable() {
285 if (LineTable == 0)
286 LineTable = new LineTableInfo();
287 return *LineTable;
288}
Chris Lattner4c4ea172009-02-03 21:52:55 +0000289
Chris Lattner23b5dc62009-02-04 00:40:31 +0000290//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000291// Private 'Create' methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000292//===----------------------------------------------------------------------===//
Ted Kremenekc16c2082009-01-06 01:55:26 +0000293
Chris Lattner5b9a5042009-01-26 07:57:50 +0000294SourceManager::~SourceManager() {
295 delete LineTable;
Mike Stump1eb44332009-09-09 15:08:12 +0000296
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000297 // Delete FileEntry objects corresponding to content caches. Since the actual
298 // content cache objects are bump pointer allocated, we just have to run the
299 // dtors, but we call the deallocate method for completeness.
300 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
301 MemBufferInfos[i]->~ContentCache();
302 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
303 }
304 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
305 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
306 I->second->~ContentCache();
307 ContentCacheAlloc.Deallocate(I->second);
308 }
Chris Lattner5b9a5042009-01-26 07:57:50 +0000309}
310
311void SourceManager::clearIDTables() {
312 MainFileID = FileID();
313 SLocEntryTable.clear();
314 LastLineNoFileIDQuery = FileID();
315 LastLineNoContentCache = 0;
316 LastFileIDLookup = FileID();
Mike Stump1eb44332009-09-09 15:08:12 +0000317
Chris Lattner5b9a5042009-01-26 07:57:50 +0000318 if (LineTable)
319 LineTable->clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Chris Lattner5b9a5042009-01-26 07:57:50 +0000321 // Use up FileID #0 as an invalid instantiation.
322 NextOffset = 0;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000323 createInstantiationLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000324}
325
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000326/// getOrCreateContentCache - Create or return a cached ContentCache for the
327/// specified file.
328const ContentCache *
329SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000330 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump1eb44332009-09-09 15:08:12 +0000331
Reid Spencer5f016e22007-07-11 17:01:13 +0000332 // Do we already have information about this file?
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000333 ContentCache *&Entry = FileInfos[FileEnt];
334 if (Entry) return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000335
Chris Lattner00282d62009-02-03 07:41:46 +0000336 // Nope, create a new Cache entry. Make sure it is at least 8-byte aligned
337 // so that FileInfo can use the low 3 bits of the pointer for its own
338 // nefarious purposes.
339 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
340 EntryAlign = std::max(8U, EntryAlign);
341 Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000342 new (Entry) ContentCache(FileEnt);
343 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000344}
345
346
Ted Kremenekd1c0eee2007-10-31 17:53:38 +0000347/// createMemBufferContentCache - Create a new ContentCache for the specified
348/// memory buffer. This does no caching.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000349const ContentCache*
350SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
Chris Lattner00282d62009-02-03 07:41:46 +0000351 // Add a new ContentCache to the MemBufferInfos list and return it. Make sure
352 // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of
353 // the pointer for its own nefarious purposes.
354 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
355 EntryAlign = std::max(8U, EntryAlign);
356 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000357 new (Entry) ContentCache();
358 MemBufferInfos.push_back(Entry);
359 Entry->setBuffer(Buffer);
360 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000361}
362
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000363void SourceManager::PreallocateSLocEntries(ExternalSLocEntrySource *Source,
364 unsigned NumSLocEntries,
365 unsigned NextOffset) {
366 ExternalSLocEntries = Source;
367 this->NextOffset = NextOffset;
368 SLocEntryLoaded.resize(NumSLocEntries + 1);
369 SLocEntryLoaded[0] = true;
370 SLocEntryTable.resize(SLocEntryTable.size() + NumSLocEntries);
371}
372
Douglas Gregor2bf1eb02009-04-27 21:28:04 +0000373void SourceManager::ClearPreallocatedSLocEntries() {
374 unsigned I = 0;
375 for (unsigned N = SLocEntryLoaded.size(); I != N; ++I)
376 if (!SLocEntryLoaded[I])
377 break;
378
379 // We've already loaded all preallocated source location entries.
380 if (I == SLocEntryLoaded.size())
381 return;
382
383 // Remove everything from location I onward.
384 SLocEntryTable.resize(I);
385 SLocEntryLoaded.clear();
386 ExternalSLocEntries = 0;
387}
388
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000389
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000390//===----------------------------------------------------------------------===//
391// Methods to create new FileID's and instantiations.
392//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000393
Nico Weber48002c82008-09-29 00:25:48 +0000394/// createFileID - Create a new fileID for the specified ContentCache and
Ted Kremenek0d892d82007-10-30 22:57:35 +0000395/// include position. This works regardless of whether the ContentCache
396/// corresponds to a file or some other input source.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000397FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000398 SourceLocation IncludePos,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000399 SrcMgr::CharacteristicKind FileCharacter,
400 unsigned PreallocatedID,
401 unsigned Offset) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000402 if (PreallocatedID) {
403 // If we're filling in a preallocated ID, just load in the file
404 // entry and return.
Mike Stump1eb44332009-09-09 15:08:12 +0000405 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000406 "Preallocate ID out-of-range");
Mike Stump1eb44332009-09-09 15:08:12 +0000407 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000408 "Source location entry already loaded");
409 assert(Offset && "Preallocate source location cannot have zero offset");
Mike Stump1eb44332009-09-09 15:08:12 +0000410 SLocEntryTable[PreallocatedID]
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000411 = SLocEntry::get(Offset, FileInfo::get(IncludePos, File, FileCharacter));
412 SLocEntryLoaded[PreallocatedID] = true;
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +0000413 FileID FID = FileID::get(PreallocatedID);
Douglas Gregor5de65722010-03-19 06:12:06 +0000414 return FID;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000415 }
416
Mike Stump1eb44332009-09-09 15:08:12 +0000417 SLocEntryTable.push_back(SLocEntry::get(NextOffset,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000418 FileInfo::get(IncludePos, File,
419 FileCharacter)));
Ted Kremenekc16c2082009-01-06 01:55:26 +0000420 unsigned FileSize = File->getSize();
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000421 assert(NextOffset+FileSize+1 > NextOffset && "Ran out of source locations!");
422 NextOffset += FileSize+1;
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000424 // Set LastFileIDLookup to the newly created file. The next getFileID call is
425 // almost guaranteed to be from that file.
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000426 FileID FID = FileID::get(SLocEntryTable.size()-1);
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000427 return LastFileIDLookup = FID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000428}
429
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000430/// createInstantiationLoc - Return a new SourceLocation that encodes the fact
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000431/// that a token from SpellingLoc should actually be referenced from
Reid Spencer5f016e22007-07-11 17:01:13 +0000432/// InstantiationLoc.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000433SourceLocation SourceManager::createInstantiationLoc(SourceLocation SpellingLoc,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000434 SourceLocation ILocStart,
435 SourceLocation ILocEnd,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000436 unsigned TokLength,
437 unsigned PreallocatedID,
438 unsigned Offset) {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000439 InstantiationInfo II = InstantiationInfo::get(ILocStart,ILocEnd, SpellingLoc);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000440 if (PreallocatedID) {
441 // If we're filling in a preallocated ID, just load in the
442 // instantiation entry and return.
Mike Stump1eb44332009-09-09 15:08:12 +0000443 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000444 "Preallocate ID out-of-range");
Mike Stump1eb44332009-09-09 15:08:12 +0000445 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000446 "Source location entry already loaded");
447 assert(Offset && "Preallocate source location cannot have zero offset");
448 SLocEntryTable[PreallocatedID] = SLocEntry::get(Offset, II);
449 SLocEntryLoaded[PreallocatedID] = true;
450 return SourceLocation::getMacroLoc(Offset);
451 }
Chris Lattnere7fb4842009-02-15 20:52:18 +0000452 SLocEntryTable.push_back(SLocEntry::get(NextOffset, II));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000453 assert(NextOffset+TokLength+1 > NextOffset && "Ran out of source locations!");
454 NextOffset += TokLength+1;
455 return SourceLocation::getMacroLoc(NextOffset-(TokLength+1));
Reid Spencer5f016e22007-07-11 17:01:13 +0000456}
457
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000458const llvm::MemoryBuffer *
Douglas Gregor50f6af72010-03-16 05:20:39 +0000459SourceManager::getMemoryBufferForFile(const FileEntry *File,
460 bool *Invalid) {
Douglas Gregor29684422009-12-02 06:49:09 +0000461 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregoraea67db2010-03-15 22:54:52 +0000462 assert(IR && "getOrCreateContentCache() cannot return NULL");
Douglas Gregor50f6af72010-03-16 05:20:39 +0000463 return IR->getBuffer(Diag, Invalid);
Douglas Gregor29684422009-12-02 06:49:09 +0000464}
465
466bool SourceManager::overrideFileContents(const FileEntry *SourceFile,
467 const llvm::MemoryBuffer *Buffer) {
468 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
469 if (IR == 0)
470 return true;
471
472 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer);
473 return false;
474}
475
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000476llvm::StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
Douglas Gregoraae58b02010-03-16 20:01:30 +0000477 bool MyInvalid = false;
478 const llvm::MemoryBuffer *Buf = getBuffer(FID, &MyInvalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000479 if (Invalid)
Douglas Gregoraae58b02010-03-16 20:01:30 +0000480 *Invalid = MyInvalid;
481
482 if (MyInvalid)
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000483 return "";
Douglas Gregoraae58b02010-03-16 20:01:30 +0000484
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000485 return Buf->getBuffer();
Douglas Gregoraea67db2010-03-15 22:54:52 +0000486}
Chris Lattner2b2453a2009-01-17 06:22:33 +0000487
Chris Lattner23b5dc62009-02-04 00:40:31 +0000488//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000489// SourceLocation manipulation methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000490//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000491
492/// getFileIDSlow - Return the FileID for a SourceLocation. This is a very hot
493/// method that is used for all SourceManager queries that start with a
494/// SourceLocation object. It is responsible for finding the entry in
495/// SLocEntryTable which contains the specified location.
496///
497FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
498 assert(SLocOffset && "Invalid FileID");
Mike Stump1eb44332009-09-09 15:08:12 +0000499
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000500 // After the first and second level caches, I see two common sorts of
501 // behavior: 1) a lot of searched FileID's are "near" the cached file location
502 // or are "near" the cached instantiation location. 2) others are just
503 // completely random and may be a very long way away.
504 //
505 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
506 // then we fall back to a less cache efficient, but more scalable, binary
507 // search to find the location.
Mike Stump1eb44332009-09-09 15:08:12 +0000508
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000509 // See if this is near the file point - worst case we start scanning from the
510 // most newly created FileID.
511 std::vector<SrcMgr::SLocEntry>::const_iterator I;
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000513 if (SLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
514 // Neither loc prunes our search.
515 I = SLocEntryTable.end();
516 } else {
517 // Perhaps it is near the file point.
518 I = SLocEntryTable.begin()+LastFileIDLookup.ID;
519 }
520
521 // Find the FileID that contains this. "I" is an iterator that points to a
522 // FileID whose offset is known to be larger than SLocOffset.
523 unsigned NumProbes = 0;
524 while (1) {
525 --I;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000526 if (ExternalSLocEntries)
527 getSLocEntry(FileID::get(I - SLocEntryTable.begin()));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000528 if (I->getOffset() <= SLocOffset) {
529#if 0
530 printf("lin %d -> %d [%s] %d %d\n", SLocOffset,
531 I-SLocEntryTable.begin(),
532 I->isInstantiation() ? "inst" : "file",
533 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
534#endif
535 FileID Res = FileID::get(I-SLocEntryTable.begin());
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000536
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000537 // If this isn't an instantiation, remember it. We have good locality
538 // across FileID lookups.
539 if (!I->isInstantiation())
540 LastFileIDLookup = Res;
541 NumLinearScans += NumProbes+1;
542 return Res;
543 }
544 if (++NumProbes == 8)
545 break;
546 }
Mike Stump1eb44332009-09-09 15:08:12 +0000547
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000548 // Convert "I" back into an index. We know that it is an entry whose index is
549 // larger than the offset we are looking for.
550 unsigned GreaterIndex = I-SLocEntryTable.begin();
551 // LessIndex - This is the lower bound of the range that we're searching.
552 // We know that the offset corresponding to the FileID is is less than
553 // SLocOffset.
554 unsigned LessIndex = 0;
555 NumProbes = 0;
556 while (1) {
557 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000558 unsigned MidOffset = getSLocEntry(FileID::get(MiddleIndex)).getOffset();
Mike Stump1eb44332009-09-09 15:08:12 +0000559
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000560 ++NumProbes;
Mike Stump1eb44332009-09-09 15:08:12 +0000561
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000562 // If the offset of the midpoint is too large, chop the high side of the
563 // range to the midpoint.
564 if (MidOffset > SLocOffset) {
565 GreaterIndex = MiddleIndex;
566 continue;
567 }
Mike Stump1eb44332009-09-09 15:08:12 +0000568
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000569 // If the middle index contains the value, succeed and return.
570 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
571#if 0
572 printf("bin %d -> %d [%s] %d %d\n", SLocOffset,
573 I-SLocEntryTable.begin(),
574 I->isInstantiation() ? "inst" : "file",
575 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
576#endif
577 FileID Res = FileID::get(MiddleIndex);
578
579 // If this isn't an instantiation, remember it. We have good locality
580 // across FileID lookups.
581 if (!I->isInstantiation())
582 LastFileIDLookup = Res;
583 NumBinaryProbes += NumProbes;
584 return Res;
585 }
Mike Stump1eb44332009-09-09 15:08:12 +0000586
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000587 // Otherwise, move the low-side up to the middle index.
588 LessIndex = MiddleIndex;
589 }
590}
591
Chris Lattneraddb7972009-01-26 20:04:19 +0000592SourceLocation SourceManager::
593getInstantiationLocSlowCase(SourceLocation Loc) const {
594 do {
Chris Lattnera5c6c582010-02-12 19:31:35 +0000595 // Note: If Loc indicates an offset into a token that came from a macro
596 // expansion (e.g. the 5th character of the token) we do not want to add
597 // this offset when going to the instantiation location. The instatiation
598 // location is the macro invocation, which the offset has nothing to do
599 // with. This is unlike when we get the spelling loc, because the offset
600 // directly correspond to the token whose spelling we're inspecting.
601 Loc = getSLocEntry(getFileID(Loc)).getInstantiation()
Chris Lattnere7fb4842009-02-15 20:52:18 +0000602 .getInstantiationLocStart();
Chris Lattneraddb7972009-01-26 20:04:19 +0000603 } while (!Loc.isFileID());
604
605 return Loc;
606}
607
608SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
609 do {
610 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
611 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
612 Loc = Loc.getFileLocWithOffset(LocInfo.second);
613 } while (!Loc.isFileID());
614 return Loc;
615}
616
617
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000618std::pair<FileID, unsigned>
619SourceManager::getDecomposedInstantiationLocSlowCase(const SrcMgr::SLocEntry *E,
620 unsigned Offset) const {
621 // If this is an instantiation record, walk through all the instantiation
622 // points.
623 FileID FID;
624 SourceLocation Loc;
625 do {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000626 Loc = E->getInstantiation().getInstantiationLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000627
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000628 FID = getFileID(Loc);
629 E = &getSLocEntry(FID);
630 Offset += Loc.getOffset()-E->getOffset();
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000631 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000632
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000633 return std::make_pair(FID, Offset);
634}
635
636std::pair<FileID, unsigned>
637SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
638 unsigned Offset) const {
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000639 // If this is an instantiation record, walk through all the instantiation
640 // points.
641 FileID FID;
642 SourceLocation Loc;
643 do {
644 Loc = E->getInstantiation().getSpellingLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000645
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000646 FID = getFileID(Loc);
647 E = &getSLocEntry(FID);
648 Offset += Loc.getOffset()-E->getOffset();
649 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000650
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000651 return std::make_pair(FID, Offset);
652}
653
Chris Lattner387616e2009-02-17 08:04:48 +0000654/// getImmediateSpellingLoc - Given a SourceLocation object, return the
655/// spelling location referenced by the ID. This is the first level down
656/// towards the place where the characters that make up the lexed token can be
657/// found. This should not generally be used by clients.
658SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
659 if (Loc.isFileID()) return Loc;
660 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
661 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
662 return Loc.getFileLocWithOffset(LocInfo.second);
663}
664
665
Chris Lattnere7fb4842009-02-15 20:52:18 +0000666/// getImmediateInstantiationRange - Loc is required to be an instantiation
667/// location. Return the start/end of the instantiation information.
668std::pair<SourceLocation,SourceLocation>
669SourceManager::getImmediateInstantiationRange(SourceLocation Loc) const {
670 assert(Loc.isMacroID() && "Not an instantiation loc!");
671 const InstantiationInfo &II = getSLocEntry(getFileID(Loc)).getInstantiation();
672 return II.getInstantiationLocRange();
673}
674
Chris Lattner66781332009-02-15 21:26:50 +0000675/// getInstantiationRange - Given a SourceLocation object, return the
676/// range of tokens covered by the instantiation in the ultimate file.
677std::pair<SourceLocation,SourceLocation>
678SourceManager::getInstantiationRange(SourceLocation Loc) const {
679 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000680
Chris Lattner66781332009-02-15 21:26:50 +0000681 std::pair<SourceLocation,SourceLocation> Res =
682 getImmediateInstantiationRange(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000683
Chris Lattner66781332009-02-15 21:26:50 +0000684 // Fully resolve the start and end locations to their ultimate instantiation
685 // points.
686 while (!Res.first.isFileID())
687 Res.first = getImmediateInstantiationRange(Res.first).first;
688 while (!Res.second.isFileID())
689 Res.second = getImmediateInstantiationRange(Res.second).second;
690 return Res;
691}
692
Chris Lattnere7fb4842009-02-15 20:52:18 +0000693
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000694
695//===----------------------------------------------------------------------===//
696// Queries about the code at a SourceLocation.
697//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000698
699/// getCharacterData - Return a pointer to the start of the specified location
700/// in the appropriate MemoryBuffer.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000701const char *SourceManager::getCharacterData(SourceLocation SL,
702 bool *Invalid) const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000703 // Note that this is a hot function in the getSpelling() path, which is
704 // heavily used by -E mode.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000705 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump1eb44332009-09-09 15:08:12 +0000706
Ted Kremenekc16c2082009-01-06 01:55:26 +0000707 // Note that calling 'getBuffer()' may lazily page in a source file.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000708 bool CharDataInvalid = false;
709 const llvm::MemoryBuffer *Buffer
710 = getSLocEntry(LocInfo.first).getFile().getContentCache()->getBuffer(Diag,
711 &CharDataInvalid);
712 if (Invalid)
713 *Invalid = CharDataInvalid;
714 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
Reid Spencer5f016e22007-07-11 17:01:13 +0000715}
716
Reid Spencer5f016e22007-07-11 17:01:13 +0000717
Chris Lattner9dc1f532007-07-20 16:37:10 +0000718/// getColumnNumber - Return the column # for the specified file position.
Chris Lattner7da5aea2009-02-04 00:55:58 +0000719/// this is significantly cheaper to compute than the line number.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000720unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
721 bool *Invalid) const {
722 bool MyInvalid = false;
723 const char *Buf = getBuffer(FID, &MyInvalid)->getBufferStart();
724 if (Invalid)
725 *Invalid = MyInvalid;
726
727 if (MyInvalid)
728 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000729
Reid Spencer5f016e22007-07-11 17:01:13 +0000730 unsigned LineStart = FilePos;
731 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
732 --LineStart;
733 return FilePos-LineStart+1;
734}
735
Douglas Gregor50f6af72010-03-16 05:20:39 +0000736unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
737 bool *Invalid) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000738 if (Loc.isInvalid()) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000739 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000740 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000741}
742
Douglas Gregor50f6af72010-03-16 05:20:39 +0000743unsigned SourceManager::getInstantiationColumnNumber(SourceLocation Loc,
744 bool *Invalid) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000745 if (Loc.isInvalid()) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000746 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000747 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000748}
749
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000750static DISABLE_INLINE void ComputeLineNumbers(Diagnostic &Diag,
751 ContentCache* FI,
Douglas Gregor50f6af72010-03-16 05:20:39 +0000752 llvm::BumpPtrAllocator &Alloc,
753 bool &Invalid);
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000754static void ComputeLineNumbers(Diagnostic &Diag, ContentCache* FI,
Douglas Gregor50f6af72010-03-16 05:20:39 +0000755 llvm::BumpPtrAllocator &Alloc, bool &Invalid) {
Ted Kremenekc16c2082009-01-06 01:55:26 +0000756 // Note that calling 'getBuffer()' may lazily page in the file.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000757 const MemoryBuffer *Buffer = FI->getBuffer(Diag, &Invalid);
758 if (Invalid)
759 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000760
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000761 // Find the file offsets of all of the *physical* source lines. This does
762 // not look at trigraphs, escaped newlines, or anything else tricky.
763 std::vector<unsigned> LineOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +0000764
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000765 // Line #1 starts at char 0.
766 LineOffsets.push_back(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000767
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000768 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
769 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
770 unsigned Offs = 0;
771 while (1) {
772 // Skip over the contents of the line.
773 // TODO: Vectorize this? This is very performance sensitive for programs
774 // with lots of diagnostics and in -E mode.
775 const unsigned char *NextBuf = (const unsigned char *)Buf;
776 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
777 ++NextBuf;
778 Offs += NextBuf-Buf;
779 Buf = NextBuf;
Mike Stump1eb44332009-09-09 15:08:12 +0000780
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000781 if (Buf[0] == '\n' || Buf[0] == '\r') {
782 // If this is \n\r or \r\n, skip both characters.
783 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
784 ++Offs, ++Buf;
785 ++Offs, ++Buf;
786 LineOffsets.push_back(Offs);
787 } else {
788 // Otherwise, this is a null. If end of file, exit.
789 if (Buf == End) break;
790 // Otherwise, skip the null.
791 ++Offs, ++Buf;
792 }
793 }
Mike Stump1eb44332009-09-09 15:08:12 +0000794
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000795 // Copy the offsets into the FileInfo structure.
796 FI->NumLines = LineOffsets.size();
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000797 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000798 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
799}
Reid Spencer5f016e22007-07-11 17:01:13 +0000800
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000801/// getLineNumber - Given a SourceLocation, return the spelling line number
Reid Spencer5f016e22007-07-11 17:01:13 +0000802/// for the position indicated. This requires building and caching a table of
803/// line offsets for the MemoryBuffer, so this is not cheap: use only when
804/// about to emit a diagnostic.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000805unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
806 bool *Invalid) const {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000807 ContentCache *Content;
Chris Lattner30fc9332009-02-04 01:06:56 +0000808 if (LastLineNoFileIDQuery == FID)
Ted Kremenek78d85f52007-10-30 21:08:08 +0000809 Content = LastLineNoContentCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000810 else
Chris Lattner30fc9332009-02-04 01:06:56 +0000811 Content = const_cast<ContentCache*>(getSLocEntry(FID)
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000812 .getFile().getContentCache());
Mike Stump1eb44332009-09-09 15:08:12 +0000813
Reid Spencer5f016e22007-07-11 17:01:13 +0000814 // If this is the first use of line information for this buffer, compute the
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000815 /// SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000816 if (Content->SourceLineCache == 0) {
817 bool MyInvalid = false;
818 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, MyInvalid);
819 if (Invalid)
820 *Invalid = MyInvalid;
821 if (MyInvalid)
822 return 1;
823 } else if (Invalid)
824 *Invalid = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000825
826 // Okay, we know we have a line number table. Do a binary search to find the
827 // line number that this character position lands on.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000828 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000829 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenek78d85f52007-10-30 21:08:08 +0000830 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump1eb44332009-09-09 15:08:12 +0000831
Chris Lattner30fc9332009-02-04 01:06:56 +0000832 unsigned QueriedFilePos = FilePos+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000833
Daniel Dunbar4106d692009-05-18 17:30:52 +0000834 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump1eb44332009-09-09 15:08:12 +0000835 // complicated as it is, binary search isn't that slow.
Daniel Dunbar4106d692009-05-18 17:30:52 +0000836 //
837 // If it is worth being optimized, then in my opinion it could be more
838 // performant, simpler, and more obviously correct by just "galloping" outward
839 // from the queried file position. In fact, this could be incorporated into a
840 // generic algorithm such as lower_bound_with_hint.
841 //
842 // If someone gives me a test case where this matters, and I will do it! - DWD
843
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000844 // If the previous query was to the same file, we know both the file pos from
845 // that query and the line number returned. This allows us to narrow the
846 // search space from the entire file to something near the match.
Chris Lattner30fc9332009-02-04 01:06:56 +0000847 if (LastLineNoFileIDQuery == FID) {
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000848 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar4106d692009-05-18 17:30:52 +0000849 // FIXME: Potential overflow?
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000850 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump1eb44332009-09-09 15:08:12 +0000851
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000852 // The query is likely to be nearby the previous one. Here we check to
853 // see if it is within 5, 10 or 20 lines. It can be far away in cases
854 // where big comment blocks and vertical whitespace eat up lines but
855 // contribute no tokens.
856 if (SourceLineCache+5 < SourceLineCacheEnd) {
857 if (SourceLineCache[5] > QueriedFilePos)
858 SourceLineCacheEnd = SourceLineCache+5;
859 else if (SourceLineCache+10 < SourceLineCacheEnd) {
860 if (SourceLineCache[10] > QueriedFilePos)
861 SourceLineCacheEnd = SourceLineCache+10;
862 else if (SourceLineCache+20 < SourceLineCacheEnd) {
863 if (SourceLineCache[20] > QueriedFilePos)
864 SourceLineCacheEnd = SourceLineCache+20;
865 }
866 }
867 }
868 } else {
Daniel Dunbar4106d692009-05-18 17:30:52 +0000869 if (LastLineNoResult < Content->NumLines)
870 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000871 }
872 }
Mike Stump1eb44332009-09-09 15:08:12 +0000873
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000874 // If the spread is large, do a "radix" test as our initial guess, based on
875 // the assumption that lines average to approximately the same length.
876 // NOTE: This is currently disabled, as it does not appear to be profitable in
877 // initial measurements.
878 if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
Ted Kremenek78d85f52007-10-30 21:08:08 +0000879 unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
Mike Stump1eb44332009-09-09 15:08:12 +0000880
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000881 // Take a stab at guessing where it is.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000882 unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
Mike Stump1eb44332009-09-09 15:08:12 +0000883
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000884 // Check for -10 and +10 lines.
885 unsigned LowerBound = std::max(int(ApproxPos-10), 0);
886 unsigned UpperBound = std::min(ApproxPos+10, FileLen);
887
888 // If the computed lower bound is less than the query location, move it in.
889 if (SourceLineCache < SourceLineCacheStart+LowerBound &&
890 SourceLineCacheStart[LowerBound] < QueriedFilePos)
891 SourceLineCache = SourceLineCacheStart+LowerBound;
Mike Stump1eb44332009-09-09 15:08:12 +0000892
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000893 // If the computed upper bound is greater than the query location, move it.
894 if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
895 SourceLineCacheStart[UpperBound] >= QueriedFilePos)
896 SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
897 }
Mike Stump1eb44332009-09-09 15:08:12 +0000898
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000899 unsigned *Pos
900 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000901 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump1eb44332009-09-09 15:08:12 +0000902
Chris Lattner30fc9332009-02-04 01:06:56 +0000903 LastLineNoFileIDQuery = FID;
Ted Kremenek78d85f52007-10-30 21:08:08 +0000904 LastLineNoContentCache = Content;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000905 LastLineNoFilePos = QueriedFilePos;
906 LastLineNoResult = LineNo;
907 return LineNo;
Reid Spencer5f016e22007-07-11 17:01:13 +0000908}
909
Douglas Gregor50f6af72010-03-16 05:20:39 +0000910unsigned SourceManager::getInstantiationLineNumber(SourceLocation Loc,
911 bool *Invalid) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000912 if (Loc.isInvalid()) return 0;
913 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
914 return getLineNumber(LocInfo.first, LocInfo.second);
915}
Douglas Gregor50f6af72010-03-16 05:20:39 +0000916unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
917 bool *Invalid) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000918 if (Loc.isInvalid()) return 0;
919 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
920 return getLineNumber(LocInfo.first, LocInfo.second);
921}
922
Chris Lattner6b306672009-02-04 05:33:01 +0000923/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump1eb44332009-09-09 15:08:12 +0000924/// source location, indicating whether this is a normal file, a system
Chris Lattner6b306672009-02-04 05:33:01 +0000925/// header, or an "implicit extern C" system header.
926///
927/// This state can be modified with flags on GNU linemarker directives like:
928/// # 4 "foo.h" 3
929/// which changes all source locations in the current file after that to be
930/// considered to be from a system header.
Mike Stump1eb44332009-09-09 15:08:12 +0000931SrcMgr::CharacteristicKind
Chris Lattner6b306672009-02-04 05:33:01 +0000932SourceManager::getFileCharacteristic(SourceLocation Loc) const {
933 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
934 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
935 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
936
937 // If there are no #line directives in this file, just return the whole-file
938 // state.
939 if (!FI.hasLineDirectives())
940 return FI.getFileCharacteristic();
Mike Stump1eb44332009-09-09 15:08:12 +0000941
Chris Lattner6b306672009-02-04 05:33:01 +0000942 assert(LineTable && "Can't have linetable entries without a LineTable!");
943 // See if there is a #line directive before the location.
944 const LineEntry *Entry =
945 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second);
Mike Stump1eb44332009-09-09 15:08:12 +0000946
Chris Lattner6b306672009-02-04 05:33:01 +0000947 // If this is before the first line marker, use the file characteristic.
948 if (!Entry)
949 return FI.getFileCharacteristic();
950
951 return Entry->FileKind;
952}
953
Chris Lattnerbff5c512009-02-17 08:39:06 +0000954/// Return the filename or buffer identifier of the buffer the location is in.
955/// Note that this name does not respect #line directives. Use getPresumedLoc
956/// for normal clients.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000957const char *SourceManager::getBufferName(SourceLocation Loc,
958 bool *Invalid) const {
Chris Lattnerbff5c512009-02-17 08:39:06 +0000959 if (Loc.isInvalid()) return "<invalid loc>";
Mike Stump1eb44332009-09-09 15:08:12 +0000960
Douglas Gregor50f6af72010-03-16 05:20:39 +0000961 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
Chris Lattnerbff5c512009-02-17 08:39:06 +0000962}
963
Chris Lattner30fc9332009-02-04 01:06:56 +0000964
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000965/// getPresumedLoc - This method returns the "presumed" location of a
966/// SourceLocation specifies. A "presumed location" can be modified by #line
967/// or GNU line marker directives. This provides a view on the data that a
968/// user should see in diagnostics, for example.
969///
970/// Note that a presumed location is always given as the instantiation point
971/// of an instantiation location, not at the spelling location.
972PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
973 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000974
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000975 // Presumed locations are always for instantiation points.
Chris Lattner7da5aea2009-02-04 00:55:58 +0000976 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000977
Chris Lattner30fc9332009-02-04 01:06:56 +0000978 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000979 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump1eb44332009-09-09 15:08:12 +0000980
Chris Lattner3cd949c2009-02-04 01:55:42 +0000981 // To get the source name, first consult the FileEntry (if one exists)
982 // before the MemBuffer as this will avoid unnecessarily paging in the
983 // MemBuffer.
Mike Stump1eb44332009-09-09 15:08:12 +0000984 const char *Filename =
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000985 C->Entry ? C->Entry->getName() : C->getBuffer(Diag)->getBufferIdentifier();
Chris Lattner3cd949c2009-02-04 01:55:42 +0000986 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second);
987 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second);
988 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000989
Chris Lattner3cd949c2009-02-04 01:55:42 +0000990 // If we have #line directives in this file, update and overwrite the physical
991 // location info if appropriate.
992 if (FI.hasLineDirectives()) {
993 assert(LineTable && "Can't have linetable entries without a LineTable!");
994 // See if there is a #line directive before this. If so, get it.
995 if (const LineEntry *Entry =
996 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) {
Chris Lattnerfc391332009-02-04 02:00:59 +0000997 // If the LineEntry indicates a filename, use it.
Chris Lattner3cd949c2009-02-04 01:55:42 +0000998 if (Entry->FilenameID != -1)
999 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerfc391332009-02-04 02:00:59 +00001000
1001 // Use the line number specified by the LineEntry. This line number may
1002 // be multiple lines down from the line entry. Add the difference in
1003 // physical line numbers from the query point and the line marker to the
1004 // total.
1005 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1006 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001007
Chris Lattner0e0e5da2009-02-04 02:15:40 +00001008 // Note that column numbers are not molested by line markers.
Mike Stump1eb44332009-09-09 15:08:12 +00001009
Chris Lattner137b6a62009-02-04 06:25:26 +00001010 // Handle virtual #include manipulation.
1011 if (Entry->IncludeOffset) {
1012 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1013 IncludeLoc = IncludeLoc.getFileLocWithOffset(Entry->IncludeOffset);
1014 }
Chris Lattner3cd949c2009-02-04 01:55:42 +00001015 }
1016 }
1017
1018 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001019}
1020
1021//===----------------------------------------------------------------------===//
1022// Other miscellaneous methods.
1023//===----------------------------------------------------------------------===//
1024
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001025/// \brief Get the source location for the given file:line:col triplet.
1026///
1027/// If the source file is included multiple times, the source location will
1028/// be based upon the first inclusion.
1029SourceLocation SourceManager::getLocation(const FileEntry *SourceFile,
1030 unsigned Line, unsigned Col) const {
1031 assert(SourceFile && "Null source file!");
1032 assert(Line && Col && "Line and column should start from 1!");
1033
1034 fileinfo_iterator FI = FileInfos.find(SourceFile);
1035 if (FI == FileInfos.end())
1036 return SourceLocation();
1037 ContentCache *Content = FI->second;
Mike Stump1eb44332009-09-09 15:08:12 +00001038
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001039 // If this is the first use of line information for this buffer, compute the
1040 /// SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001041 if (Content->SourceLineCache == 0) {
1042 bool MyInvalid = false;
1043 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, MyInvalid);
1044 if (MyInvalid)
1045 return SourceLocation();
1046 }
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001047
Douglas Gregor4a160e12009-12-02 05:34:39 +00001048 // Find the first file ID that corresponds to the given file.
1049 FileID FirstFID;
1050
1051 // First, check the main file ID, since it is common to look for a
1052 // location in the main file.
1053 if (!MainFileID.isInvalid()) {
1054 const SLocEntry &MainSLoc = getSLocEntry(MainFileID);
1055 if (MainSLoc.isFile() && MainSLoc.getFile().getContentCache() == Content)
1056 FirstFID = MainFileID;
1057 }
1058
1059 if (FirstFID.isInvalid()) {
1060 // The location we're looking for isn't in the main file; look
1061 // through all of the source locations.
1062 for (unsigned I = 0, N = sloc_entry_size(); I != N; ++I) {
1063 const SLocEntry &SLoc = getSLocEntry(I);
1064 if (SLoc.isFile() && SLoc.getFile().getContentCache() == Content) {
1065 FirstFID = FileID::get(I);
1066 break;
1067 }
1068 }
1069 }
1070
1071 if (FirstFID.isInvalid())
1072 return SourceLocation();
1073
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001074 if (Line > Content->NumLines) {
Douglas Gregor36c35ba2010-03-16 00:35:39 +00001075 unsigned Size = Content->getBuffer(Diag)->getBufferSize();
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001076 if (Size > 0)
1077 --Size;
1078 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(Size);
1079 }
1080
1081 unsigned FilePos = Content->SourceLineCache[Line - 1];
Douglas Gregor36c35ba2010-03-16 00:35:39 +00001082 const char *Buf = Content->getBuffer(Diag)->getBufferStart() + FilePos;
1083 unsigned BufLength = Content->getBuffer(Diag)->getBufferEnd() - Buf;
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001084 unsigned i = 0;
1085
1086 // Check that the given column is valid.
1087 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1088 ++i;
1089 if (i < Col-1)
1090 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + i);
1091
Douglas Gregor4a160e12009-12-02 05:34:39 +00001092 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + Col - 1);
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001093}
1094
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001095/// \brief Determines the order of 2 source locations in the translation unit.
1096///
1097/// \returns true if LHS source location comes before RHS, false otherwise.
1098bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1099 SourceLocation RHS) const {
1100 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1101 if (LHS == RHS)
1102 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001103
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001104 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1105 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00001106
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001107 // If the source locations are in the same file, just compare offsets.
1108 if (LOffs.first == ROffs.first)
1109 return LOffs.second < ROffs.second;
1110
1111 // If we are comparing a source location with multiple locations in the same
1112 // file, we get a big win by caching the result.
Mike Stump1eb44332009-09-09 15:08:12 +00001113
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001114 if (LastLFIDForBeforeTUCheck == LOffs.first &&
1115 LastRFIDForBeforeTUCheck == ROffs.first)
1116 return LastResForBeforeTUCheck;
Mike Stump1eb44332009-09-09 15:08:12 +00001117
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001118 LastLFIDForBeforeTUCheck = LOffs.first;
1119 LastRFIDForBeforeTUCheck = ROffs.first;
Mike Stump1eb44332009-09-09 15:08:12 +00001120
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001121 // "Traverse" the include/instantiation stacks of both locations and try to
1122 // find a common "ancestor".
1123 //
1124 // First we traverse the stack of the right location and check each level
1125 // against the level of the left location, while collecting all levels in a
1126 // "stack map".
1127
1128 std::map<FileID, unsigned> ROffsMap;
1129 ROffsMap[ROffs.first] = ROffs.second;
1130
1131 while (1) {
1132 SourceLocation UpperLoc;
1133 const SrcMgr::SLocEntry &Entry = getSLocEntry(ROffs.first);
1134 if (Entry.isInstantiation())
1135 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1136 else
1137 UpperLoc = Entry.getFile().getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001138
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001139 if (UpperLoc.isInvalid())
1140 break; // We reached the top.
Mike Stump1eb44332009-09-09 15:08:12 +00001141
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001142 ROffs = getDecomposedLoc(UpperLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001143
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001144 if (LOffs.first == ROffs.first)
1145 return LastResForBeforeTUCheck = LOffs.second < ROffs.second;
Mike Stump1eb44332009-09-09 15:08:12 +00001146
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001147 ROffsMap[ROffs.first] = ROffs.second;
1148 }
1149
1150 // We didn't find a common ancestor. Now traverse the stack of the left
1151 // location, checking against the stack map of the right location.
1152
1153 while (1) {
1154 SourceLocation UpperLoc;
1155 const SrcMgr::SLocEntry &Entry = getSLocEntry(LOffs.first);
1156 if (Entry.isInstantiation())
1157 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1158 else
1159 UpperLoc = Entry.getFile().getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001160
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001161 if (UpperLoc.isInvalid())
1162 break; // We reached the top.
Mike Stump1eb44332009-09-09 15:08:12 +00001163
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001164 LOffs = getDecomposedLoc(UpperLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001165
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001166 std::map<FileID, unsigned>::iterator I = ROffsMap.find(LOffs.first);
1167 if (I != ROffsMap.end())
1168 return LastResForBeforeTUCheck = LOffs.second < I->second;
1169 }
Mike Stump1eb44332009-09-09 15:08:12 +00001170
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001171 // There is no common ancestor, most probably because one location is in the
1172 // predefines buffer.
1173 //
1174 // FIXME: We should rearrange the external interface so this simply never
1175 // happens; it can't conceptually happen. Also see PR5662.
Mike Stump1eb44332009-09-09 15:08:12 +00001176
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001177 // If exactly one location is a memory buffer, assume it preceeds the other.
1178 bool LIsMB = !getSLocEntry(LOffs.first).getFile().getContentCache()->Entry;
1179 bool RIsMB = !getSLocEntry(ROffs.first).getFile().getContentCache()->Entry;
1180 if (LIsMB != RIsMB)
1181 return LastResForBeforeTUCheck = LIsMB;
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001183 // Otherwise, just assume FileIDs were created in order.
1184 return LastResForBeforeTUCheck = (LOffs.first < ROffs.first);
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001185}
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001186
Reid Spencer5f016e22007-07-11 17:01:13 +00001187/// PrintStats - Print statistics to stderr.
1188///
1189void SourceManager::PrintStats() const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001190 llvm::errs() << "\n*** Source Manager Stats:\n";
1191 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
1192 << " mem buffers mapped.\n";
1193 llvm::errs() << SLocEntryTable.size() << " SLocEntry's allocated, "
1194 << NextOffset << "B of Sloc address space used.\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001195
Reid Spencer5f016e22007-07-11 17:01:13 +00001196 unsigned NumLineNumsComputed = 0;
1197 unsigned NumFileBytesMapped = 0;
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00001198 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
1199 NumLineNumsComputed += I->second->SourceLineCache != 0;
1200 NumFileBytesMapped += I->second->getSizeBytesMapped();
Reid Spencer5f016e22007-07-11 17:01:13 +00001201 }
Mike Stump1eb44332009-09-09 15:08:12 +00001202
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001203 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
1204 << NumLineNumsComputed << " files with line #'s computed.\n";
1205 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
1206 << NumBinaryProbes << " binary.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +00001207}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001208
1209ExternalSLocEntrySource::~ExternalSLocEntrySource() { }