blob: 440e688cd736f57bb84c118873978a99639e509e [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() ||
96 FileInfo.st_mtime != Entry->getModificationTime()) {
Douglas Gregoraea67db2010-03-15 22:54:52 +000097 // Check that the file's size and modification time is the same as
98 // in the file entry (which may have come from a stat cache).
Douglas Gregore39b6002010-03-17 15:30:15 +000099 Diag.Report(diag::err_file_modified) << Entry->getName();
100 Buffer.setInt(true);
Daniel Dunbar21a8bed2009-12-06 05:43:36 +0000101 }
Ted Kremenek5b034ad2009-01-06 22:43:04 +0000102 }
Douglas Gregoraea67db2010-03-15 22:54:52 +0000103
Douglas Gregorc8151082010-03-16 22:53:51 +0000104 if (Invalid)
105 *Invalid = Buffer.getInt();
106
107 return Buffer.getPointer();
Ted Kremenekc16c2082009-01-06 01:55:26 +0000108}
109
Chris Lattner5b9a5042009-01-26 07:57:50 +0000110unsigned LineTableInfo::getLineTableFilenameID(const char *Ptr, unsigned Len) {
111 // Look up the filename in the string table, returning the pre-existing value
112 // if it exists.
Mike Stump1eb44332009-09-09 15:08:12 +0000113 llvm::StringMapEntry<unsigned> &Entry =
Chris Lattner5b9a5042009-01-26 07:57:50 +0000114 FilenameIDs.GetOrCreateValue(Ptr, Ptr+Len, ~0U);
115 if (Entry.getValue() != ~0U)
116 return Entry.getValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000117
Chris Lattner5b9a5042009-01-26 07:57:50 +0000118 // Otherwise, assign this the next available ID.
119 Entry.setValue(FilenamesByID.size());
120 FilenamesByID.push_back(&Entry);
121 return FilenamesByID.size()-1;
122}
123
Chris Lattnerac50e342009-02-03 22:13:05 +0000124/// AddLineNote - Add a line note to the line table that indicates that there
125/// is a #line at the specified FID/Offset location which changes the presumed
126/// location to LineNo/FilenameID.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000127void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
Chris Lattnerac50e342009-02-03 22:13:05 +0000128 unsigned LineNo, int FilenameID) {
Chris Lattner23b5dc62009-02-04 00:40:31 +0000129 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000130
Chris Lattner23b5dc62009-02-04 00:40:31 +0000131 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
132 "Adding line entries out of order!");
Mike Stump1eb44332009-09-09 15:08:12 +0000133
Chris Lattner9d79eba2009-02-04 05:21:58 +0000134 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
Chris Lattner137b6a62009-02-04 06:25:26 +0000135 unsigned IncludeOffset = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000136
Chris Lattner9d79eba2009-02-04 05:21:58 +0000137 if (!Entries.empty()) {
138 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
139 // that we are still in "foo.h".
140 if (FilenameID == -1)
141 FilenameID = Entries.back().FilenameID;
Mike Stump1eb44332009-09-09 15:08:12 +0000142
Chris Lattner137b6a62009-02-04 06:25:26 +0000143 // If we are after a line marker that switched us to system header mode, or
144 // that set #include information, preserve it.
Chris Lattner9d79eba2009-02-04 05:21:58 +0000145 Kind = Entries.back().FileKind;
Chris Lattner137b6a62009-02-04 06:25:26 +0000146 IncludeOffset = Entries.back().IncludeOffset;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000147 }
Mike Stump1eb44332009-09-09 15:08:12 +0000148
Chris Lattner137b6a62009-02-04 06:25:26 +0000149 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
150 IncludeOffset));
Chris Lattnerac50e342009-02-03 22:13:05 +0000151}
152
Chris Lattner9d79eba2009-02-04 05:21:58 +0000153/// AddLineNote This is the same as the previous version of AddLineNote, but is
154/// used for GNU line markers. If EntryExit is 0, then this doesn't change the
155/// presumed #include stack. If it is 1, this is a file entry, if it is 2 then
156/// this is a file exit. FileKind specifies whether this is a system header or
157/// extern C system header.
158void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
159 unsigned LineNo, int FilenameID,
160 unsigned EntryExit,
161 SrcMgr::CharacteristicKind FileKind) {
162 assert(FilenameID != -1 && "Unspecified filename should use other accessor");
Mike Stump1eb44332009-09-09 15:08:12 +0000163
Chris Lattner9d79eba2009-02-04 05:21:58 +0000164 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000165
Chris Lattner9d79eba2009-02-04 05:21:58 +0000166 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
167 "Adding line entries out of order!");
168
Chris Lattner137b6a62009-02-04 06:25:26 +0000169 unsigned IncludeOffset = 0;
170 if (EntryExit == 0) { // No #include stack change.
171 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
172 } else if (EntryExit == 1) {
173 IncludeOffset = Offset-1;
174 } else if (EntryExit == 2) {
175 assert(!Entries.empty() && Entries.back().IncludeOffset &&
176 "PPDirectives should have caught case when popping empty include stack");
Mike Stump1eb44332009-09-09 15:08:12 +0000177
Chris Lattner137b6a62009-02-04 06:25:26 +0000178 // Get the include loc of the last entries' include loc as our include loc.
179 IncludeOffset = 0;
180 if (const LineEntry *PrevEntry =
181 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
182 IncludeOffset = PrevEntry->IncludeOffset;
183 }
Mike Stump1eb44332009-09-09 15:08:12 +0000184
Chris Lattner137b6a62009-02-04 06:25:26 +0000185 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
186 IncludeOffset));
Chris Lattner9d79eba2009-02-04 05:21:58 +0000187}
188
189
Chris Lattner3cd949c2009-02-04 01:55:42 +0000190/// FindNearestLineEntry - Find the line entry nearest to FID that is before
191/// it. If there is no line entry before Offset in FID, return null.
Mike Stump1eb44332009-09-09 15:08:12 +0000192const LineEntry *LineTableInfo::FindNearestLineEntry(unsigned FID,
Chris Lattner3cd949c2009-02-04 01:55:42 +0000193 unsigned Offset) {
194 const std::vector<LineEntry> &Entries = LineEntries[FID];
195 assert(!Entries.empty() && "No #line entries for this FID after all!");
196
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000197 // It is very common for the query to be after the last #line, check this
198 // first.
199 if (Entries.back().FileOffset <= Offset)
200 return &Entries.back();
Chris Lattner3cd949c2009-02-04 01:55:42 +0000201
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000202 // Do a binary search to find the maximal element that is still before Offset.
203 std::vector<LineEntry>::const_iterator I =
204 std::upper_bound(Entries.begin(), Entries.end(), Offset);
205 if (I == Entries.begin()) return 0;
206 return &*--I;
Chris Lattner3cd949c2009-02-04 01:55:42 +0000207}
Chris Lattnerac50e342009-02-03 22:13:05 +0000208
Douglas Gregorbd945002009-04-13 16:31:14 +0000209/// \brief Add a new line entry that has already been encoded into
210/// the internal representation of the line table.
Mike Stump1eb44332009-09-09 15:08:12 +0000211void LineTableInfo::AddEntry(unsigned FID,
Douglas Gregorbd945002009-04-13 16:31:14 +0000212 const std::vector<LineEntry> &Entries) {
213 LineEntries[FID] = Entries;
214}
Chris Lattnerac50e342009-02-03 22:13:05 +0000215
Chris Lattner5b9a5042009-01-26 07:57:50 +0000216/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
Mike Stump1eb44332009-09-09 15:08:12 +0000217///
Chris Lattner5b9a5042009-01-26 07:57:50 +0000218unsigned SourceManager::getLineTableFilenameID(const char *Ptr, unsigned Len) {
219 if (LineTable == 0)
220 LineTable = new LineTableInfo();
221 return LineTable->getLineTableFilenameID(Ptr, Len);
222}
223
224
Chris Lattner4c4ea172009-02-03 21:52:55 +0000225/// AddLineNote - Add a line note to the line table for the FileID and offset
226/// specified by Loc. If FilenameID is -1, it is considered to be
227/// unspecified.
228void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
229 int FilenameID) {
Chris Lattnerac50e342009-02-03 22:13:05 +0000230 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000231
Chris Lattnerac50e342009-02-03 22:13:05 +0000232 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
233
234 // Remember that this file has #line directives now if it doesn't already.
235 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000236
Chris Lattnerac50e342009-02-03 22:13:05 +0000237 if (LineTable == 0)
238 LineTable = new LineTableInfo();
Chris Lattner23b5dc62009-02-04 00:40:31 +0000239 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID);
Chris Lattner4c4ea172009-02-03 21:52:55 +0000240}
241
Chris Lattner9d79eba2009-02-04 05:21:58 +0000242/// AddLineNote - Add a GNU line marker to the line table.
243void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
244 int FilenameID, bool IsFileEntry,
245 bool IsFileExit, bool IsSystemHeader,
246 bool IsExternCHeader) {
247 // If there is no filename and no flags, this is treated just like a #line,
248 // which does not change the flags of the previous line marker.
249 if (FilenameID == -1) {
250 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
251 "Can't set flags without setting the filename!");
252 return AddLineNote(Loc, LineNo, FilenameID);
253 }
Mike Stump1eb44332009-09-09 15:08:12 +0000254
Chris Lattner9d79eba2009-02-04 05:21:58 +0000255 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
256 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000257
Chris Lattner9d79eba2009-02-04 05:21:58 +0000258 // Remember that this file has #line directives now if it doesn't already.
259 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000260
Chris Lattner9d79eba2009-02-04 05:21:58 +0000261 if (LineTable == 0)
262 LineTable = new LineTableInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000263
Chris Lattner9d79eba2009-02-04 05:21:58 +0000264 SrcMgr::CharacteristicKind FileKind;
265 if (IsExternCHeader)
266 FileKind = SrcMgr::C_ExternCSystem;
267 else if (IsSystemHeader)
268 FileKind = SrcMgr::C_System;
269 else
270 FileKind = SrcMgr::C_User;
Mike Stump1eb44332009-09-09 15:08:12 +0000271
Chris Lattner9d79eba2009-02-04 05:21:58 +0000272 unsigned EntryExit = 0;
273 if (IsFileEntry)
274 EntryExit = 1;
275 else if (IsFileExit)
276 EntryExit = 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000277
Chris Lattner9d79eba2009-02-04 05:21:58 +0000278 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID,
279 EntryExit, FileKind);
280}
281
Douglas Gregorbd945002009-04-13 16:31:14 +0000282LineTableInfo &SourceManager::getLineTable() {
283 if (LineTable == 0)
284 LineTable = new LineTableInfo();
285 return *LineTable;
286}
Chris Lattner4c4ea172009-02-03 21:52:55 +0000287
Chris Lattner23b5dc62009-02-04 00:40:31 +0000288//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000289// Private 'Create' methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000290//===----------------------------------------------------------------------===//
Ted Kremenekc16c2082009-01-06 01:55:26 +0000291
Chris Lattner5b9a5042009-01-26 07:57:50 +0000292SourceManager::~SourceManager() {
293 delete LineTable;
Mike Stump1eb44332009-09-09 15:08:12 +0000294
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000295 // Delete FileEntry objects corresponding to content caches. Since the actual
296 // content cache objects are bump pointer allocated, we just have to run the
297 // dtors, but we call the deallocate method for completeness.
298 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
299 MemBufferInfos[i]->~ContentCache();
300 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
301 }
302 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
303 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
304 I->second->~ContentCache();
305 ContentCacheAlloc.Deallocate(I->second);
306 }
Chris Lattner5b9a5042009-01-26 07:57:50 +0000307}
308
309void SourceManager::clearIDTables() {
310 MainFileID = FileID();
311 SLocEntryTable.clear();
312 LastLineNoFileIDQuery = FileID();
313 LastLineNoContentCache = 0;
314 LastFileIDLookup = FileID();
Mike Stump1eb44332009-09-09 15:08:12 +0000315
Chris Lattner5b9a5042009-01-26 07:57:50 +0000316 if (LineTable)
317 LineTable->clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000318
Chris Lattner5b9a5042009-01-26 07:57:50 +0000319 // Use up FileID #0 as an invalid instantiation.
320 NextOffset = 0;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000321 createInstantiationLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000322}
323
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000324/// getOrCreateContentCache - Create or return a cached ContentCache for the
325/// specified file.
326const ContentCache *
327SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000328 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump1eb44332009-09-09 15:08:12 +0000329
Reid Spencer5f016e22007-07-11 17:01:13 +0000330 // Do we already have information about this file?
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000331 ContentCache *&Entry = FileInfos[FileEnt];
332 if (Entry) return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Chris Lattner00282d62009-02-03 07:41:46 +0000334 // Nope, create a new Cache entry. Make sure it is at least 8-byte aligned
335 // so that FileInfo can use the low 3 bits of the pointer for its own
336 // nefarious purposes.
337 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
338 EntryAlign = std::max(8U, EntryAlign);
339 Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000340 new (Entry) ContentCache(FileEnt);
341 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000342}
343
344
Ted Kremenekd1c0eee2007-10-31 17:53:38 +0000345/// createMemBufferContentCache - Create a new ContentCache for the specified
346/// memory buffer. This does no caching.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000347const ContentCache*
348SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
Chris Lattner00282d62009-02-03 07:41:46 +0000349 // Add a new ContentCache to the MemBufferInfos list and return it. Make sure
350 // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of
351 // the pointer for its own nefarious purposes.
352 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
353 EntryAlign = std::max(8U, EntryAlign);
354 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000355 new (Entry) ContentCache();
356 MemBufferInfos.push_back(Entry);
357 Entry->setBuffer(Buffer);
358 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000359}
360
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000361void SourceManager::PreallocateSLocEntries(ExternalSLocEntrySource *Source,
362 unsigned NumSLocEntries,
363 unsigned NextOffset) {
364 ExternalSLocEntries = Source;
365 this->NextOffset = NextOffset;
366 SLocEntryLoaded.resize(NumSLocEntries + 1);
367 SLocEntryLoaded[0] = true;
368 SLocEntryTable.resize(SLocEntryTable.size() + NumSLocEntries);
369}
370
Douglas Gregor2bf1eb02009-04-27 21:28:04 +0000371void SourceManager::ClearPreallocatedSLocEntries() {
372 unsigned I = 0;
373 for (unsigned N = SLocEntryLoaded.size(); I != N; ++I)
374 if (!SLocEntryLoaded[I])
375 break;
376
377 // We've already loaded all preallocated source location entries.
378 if (I == SLocEntryLoaded.size())
379 return;
380
381 // Remove everything from location I onward.
382 SLocEntryTable.resize(I);
383 SLocEntryLoaded.clear();
384 ExternalSLocEntries = 0;
385}
386
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000387
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000388//===----------------------------------------------------------------------===//
389// Methods to create new FileID's and instantiations.
390//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000391
Nico Weber48002c82008-09-29 00:25:48 +0000392/// createFileID - Create a new fileID for the specified ContentCache and
Ted Kremenek0d892d82007-10-30 22:57:35 +0000393/// include position. This works regardless of whether the ContentCache
394/// corresponds to a file or some other input source.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000395FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000396 SourceLocation IncludePos,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000397 SrcMgr::CharacteristicKind FileCharacter,
398 unsigned PreallocatedID,
399 unsigned Offset) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000400 if (PreallocatedID) {
401 // If we're filling in a preallocated ID, just load in the file
402 // entry and return.
Mike Stump1eb44332009-09-09 15:08:12 +0000403 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000404 "Preallocate ID out-of-range");
Mike Stump1eb44332009-09-09 15:08:12 +0000405 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000406 "Source location entry already loaded");
407 assert(Offset && "Preallocate source location cannot have zero offset");
Mike Stump1eb44332009-09-09 15:08:12 +0000408 SLocEntryTable[PreallocatedID]
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000409 = SLocEntry::get(Offset, FileInfo::get(IncludePos, File, FileCharacter));
410 SLocEntryLoaded[PreallocatedID] = true;
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +0000411 FileID FID = FileID::get(PreallocatedID);
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +0000412 return LastFileIDLookup = FID;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000413 }
414
Mike Stump1eb44332009-09-09 15:08:12 +0000415 SLocEntryTable.push_back(SLocEntry::get(NextOffset,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000416 FileInfo::get(IncludePos, File,
417 FileCharacter)));
Ted Kremenekc16c2082009-01-06 01:55:26 +0000418 unsigned FileSize = File->getSize();
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000419 assert(NextOffset+FileSize+1 > NextOffset && "Ran out of source locations!");
420 NextOffset += FileSize+1;
Mike Stump1eb44332009-09-09 15:08:12 +0000421
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000422 // Set LastFileIDLookup to the newly created file. The next getFileID call is
423 // almost guaranteed to be from that file.
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000424 FileID FID = FileID::get(SLocEntryTable.size()-1);
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000425 return LastFileIDLookup = FID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000426}
427
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000428/// createInstantiationLoc - Return a new SourceLocation that encodes the fact
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000429/// that a token from SpellingLoc should actually be referenced from
Reid Spencer5f016e22007-07-11 17:01:13 +0000430/// InstantiationLoc.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000431SourceLocation SourceManager::createInstantiationLoc(SourceLocation SpellingLoc,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000432 SourceLocation ILocStart,
433 SourceLocation ILocEnd,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000434 unsigned TokLength,
435 unsigned PreallocatedID,
436 unsigned Offset) {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000437 InstantiationInfo II = InstantiationInfo::get(ILocStart,ILocEnd, SpellingLoc);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000438 if (PreallocatedID) {
439 // If we're filling in a preallocated ID, just load in the
440 // instantiation entry and return.
Mike Stump1eb44332009-09-09 15:08:12 +0000441 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000442 "Preallocate ID out-of-range");
Mike Stump1eb44332009-09-09 15:08:12 +0000443 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000444 "Source location entry already loaded");
445 assert(Offset && "Preallocate source location cannot have zero offset");
446 SLocEntryTable[PreallocatedID] = SLocEntry::get(Offset, II);
447 SLocEntryLoaded[PreallocatedID] = true;
448 return SourceLocation::getMacroLoc(Offset);
449 }
Chris Lattnere7fb4842009-02-15 20:52:18 +0000450 SLocEntryTable.push_back(SLocEntry::get(NextOffset, II));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000451 assert(NextOffset+TokLength+1 > NextOffset && "Ran out of source locations!");
452 NextOffset += TokLength+1;
453 return SourceLocation::getMacroLoc(NextOffset-(TokLength+1));
Reid Spencer5f016e22007-07-11 17:01:13 +0000454}
455
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000456const llvm::MemoryBuffer *
Douglas Gregor50f6af72010-03-16 05:20:39 +0000457SourceManager::getMemoryBufferForFile(const FileEntry *File,
458 bool *Invalid) {
Douglas Gregor29684422009-12-02 06:49:09 +0000459 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregoraea67db2010-03-15 22:54:52 +0000460 assert(IR && "getOrCreateContentCache() cannot return NULL");
Douglas Gregor50f6af72010-03-16 05:20:39 +0000461 return IR->getBuffer(Diag, Invalid);
Douglas Gregor29684422009-12-02 06:49:09 +0000462}
463
464bool SourceManager::overrideFileContents(const FileEntry *SourceFile,
465 const llvm::MemoryBuffer *Buffer) {
466 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
467 if (IR == 0)
468 return true;
469
470 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer);
471 return false;
472}
473
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000474llvm::StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
Douglas Gregoraae58b02010-03-16 20:01:30 +0000475 bool MyInvalid = false;
476 const llvm::MemoryBuffer *Buf = getBuffer(FID, &MyInvalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000477 if (Invalid)
Douglas Gregoraae58b02010-03-16 20:01:30 +0000478 *Invalid = MyInvalid;
479
480 if (MyInvalid)
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000481 return "";
Douglas Gregoraae58b02010-03-16 20:01:30 +0000482
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000483 return Buf->getBuffer();
Douglas Gregoraea67db2010-03-15 22:54:52 +0000484}
Chris Lattner2b2453a2009-01-17 06:22:33 +0000485
Chris Lattner23b5dc62009-02-04 00:40:31 +0000486//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000487// SourceLocation manipulation methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000488//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000489
490/// getFileIDSlow - Return the FileID for a SourceLocation. This is a very hot
491/// method that is used for all SourceManager queries that start with a
492/// SourceLocation object. It is responsible for finding the entry in
493/// SLocEntryTable which contains the specified location.
494///
495FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
496 assert(SLocOffset && "Invalid FileID");
Mike Stump1eb44332009-09-09 15:08:12 +0000497
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000498 // After the first and second level caches, I see two common sorts of
499 // behavior: 1) a lot of searched FileID's are "near" the cached file location
500 // or are "near" the cached instantiation location. 2) others are just
501 // completely random and may be a very long way away.
502 //
503 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
504 // then we fall back to a less cache efficient, but more scalable, binary
505 // search to find the location.
Mike Stump1eb44332009-09-09 15:08:12 +0000506
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000507 // See if this is near the file point - worst case we start scanning from the
508 // most newly created FileID.
509 std::vector<SrcMgr::SLocEntry>::const_iterator I;
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000511 if (SLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
512 // Neither loc prunes our search.
513 I = SLocEntryTable.end();
514 } else {
515 // Perhaps it is near the file point.
516 I = SLocEntryTable.begin()+LastFileIDLookup.ID;
517 }
518
519 // Find the FileID that contains this. "I" is an iterator that points to a
520 // FileID whose offset is known to be larger than SLocOffset.
521 unsigned NumProbes = 0;
522 while (1) {
523 --I;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000524 if (ExternalSLocEntries)
525 getSLocEntry(FileID::get(I - SLocEntryTable.begin()));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000526 if (I->getOffset() <= SLocOffset) {
527#if 0
528 printf("lin %d -> %d [%s] %d %d\n", SLocOffset,
529 I-SLocEntryTable.begin(),
530 I->isInstantiation() ? "inst" : "file",
531 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
532#endif
533 FileID Res = FileID::get(I-SLocEntryTable.begin());
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000534
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000535 // If this isn't an instantiation, remember it. We have good locality
536 // across FileID lookups.
537 if (!I->isInstantiation())
538 LastFileIDLookup = Res;
539 NumLinearScans += NumProbes+1;
540 return Res;
541 }
542 if (++NumProbes == 8)
543 break;
544 }
Mike Stump1eb44332009-09-09 15:08:12 +0000545
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000546 // Convert "I" back into an index. We know that it is an entry whose index is
547 // larger than the offset we are looking for.
548 unsigned GreaterIndex = I-SLocEntryTable.begin();
549 // LessIndex - This is the lower bound of the range that we're searching.
550 // We know that the offset corresponding to the FileID is is less than
551 // SLocOffset.
552 unsigned LessIndex = 0;
553 NumProbes = 0;
554 while (1) {
555 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000556 unsigned MidOffset = getSLocEntry(FileID::get(MiddleIndex)).getOffset();
Mike Stump1eb44332009-09-09 15:08:12 +0000557
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000558 ++NumProbes;
Mike Stump1eb44332009-09-09 15:08:12 +0000559
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000560 // If the offset of the midpoint is too large, chop the high side of the
561 // range to the midpoint.
562 if (MidOffset > SLocOffset) {
563 GreaterIndex = MiddleIndex;
564 continue;
565 }
Mike Stump1eb44332009-09-09 15:08:12 +0000566
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000567 // If the middle index contains the value, succeed and return.
568 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
569#if 0
570 printf("bin %d -> %d [%s] %d %d\n", SLocOffset,
571 I-SLocEntryTable.begin(),
572 I->isInstantiation() ? "inst" : "file",
573 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
574#endif
575 FileID Res = FileID::get(MiddleIndex);
576
577 // If this isn't an instantiation, remember it. We have good locality
578 // across FileID lookups.
579 if (!I->isInstantiation())
580 LastFileIDLookup = Res;
581 NumBinaryProbes += NumProbes;
582 return Res;
583 }
Mike Stump1eb44332009-09-09 15:08:12 +0000584
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000585 // Otherwise, move the low-side up to the middle index.
586 LessIndex = MiddleIndex;
587 }
588}
589
Chris Lattneraddb7972009-01-26 20:04:19 +0000590SourceLocation SourceManager::
591getInstantiationLocSlowCase(SourceLocation Loc) const {
592 do {
Chris Lattnera5c6c582010-02-12 19:31:35 +0000593 // Note: If Loc indicates an offset into a token that came from a macro
594 // expansion (e.g. the 5th character of the token) we do not want to add
595 // this offset when going to the instantiation location. The instatiation
596 // location is the macro invocation, which the offset has nothing to do
597 // with. This is unlike when we get the spelling loc, because the offset
598 // directly correspond to the token whose spelling we're inspecting.
599 Loc = getSLocEntry(getFileID(Loc)).getInstantiation()
Chris Lattnere7fb4842009-02-15 20:52:18 +0000600 .getInstantiationLocStart();
Chris Lattneraddb7972009-01-26 20:04:19 +0000601 } while (!Loc.isFileID());
602
603 return Loc;
604}
605
606SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
607 do {
608 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
609 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
610 Loc = Loc.getFileLocWithOffset(LocInfo.second);
611 } while (!Loc.isFileID());
612 return Loc;
613}
614
615
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000616std::pair<FileID, unsigned>
617SourceManager::getDecomposedInstantiationLocSlowCase(const SrcMgr::SLocEntry *E,
618 unsigned Offset) const {
619 // If this is an instantiation record, walk through all the instantiation
620 // points.
621 FileID FID;
622 SourceLocation Loc;
623 do {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000624 Loc = E->getInstantiation().getInstantiationLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000625
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000626 FID = getFileID(Loc);
627 E = &getSLocEntry(FID);
628 Offset += Loc.getOffset()-E->getOffset();
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000629 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000630
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000631 return std::make_pair(FID, Offset);
632}
633
634std::pair<FileID, unsigned>
635SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
636 unsigned Offset) const {
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000637 // If this is an instantiation record, walk through all the instantiation
638 // points.
639 FileID FID;
640 SourceLocation Loc;
641 do {
642 Loc = E->getInstantiation().getSpellingLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000643
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000644 FID = getFileID(Loc);
645 E = &getSLocEntry(FID);
646 Offset += Loc.getOffset()-E->getOffset();
647 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000648
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000649 return std::make_pair(FID, Offset);
650}
651
Chris Lattner387616e2009-02-17 08:04:48 +0000652/// getImmediateSpellingLoc - Given a SourceLocation object, return the
653/// spelling location referenced by the ID. This is the first level down
654/// towards the place where the characters that make up the lexed token can be
655/// found. This should not generally be used by clients.
656SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
657 if (Loc.isFileID()) return Loc;
658 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
659 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
660 return Loc.getFileLocWithOffset(LocInfo.second);
661}
662
663
Chris Lattnere7fb4842009-02-15 20:52:18 +0000664/// getImmediateInstantiationRange - Loc is required to be an instantiation
665/// location. Return the start/end of the instantiation information.
666std::pair<SourceLocation,SourceLocation>
667SourceManager::getImmediateInstantiationRange(SourceLocation Loc) const {
668 assert(Loc.isMacroID() && "Not an instantiation loc!");
669 const InstantiationInfo &II = getSLocEntry(getFileID(Loc)).getInstantiation();
670 return II.getInstantiationLocRange();
671}
672
Chris Lattner66781332009-02-15 21:26:50 +0000673/// getInstantiationRange - Given a SourceLocation object, return the
674/// range of tokens covered by the instantiation in the ultimate file.
675std::pair<SourceLocation,SourceLocation>
676SourceManager::getInstantiationRange(SourceLocation Loc) const {
677 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000678
Chris Lattner66781332009-02-15 21:26:50 +0000679 std::pair<SourceLocation,SourceLocation> Res =
680 getImmediateInstantiationRange(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000681
Chris Lattner66781332009-02-15 21:26:50 +0000682 // Fully resolve the start and end locations to their ultimate instantiation
683 // points.
684 while (!Res.first.isFileID())
685 Res.first = getImmediateInstantiationRange(Res.first).first;
686 while (!Res.second.isFileID())
687 Res.second = getImmediateInstantiationRange(Res.second).second;
688 return Res;
689}
690
Chris Lattnere7fb4842009-02-15 20:52:18 +0000691
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000692
693//===----------------------------------------------------------------------===//
694// Queries about the code at a SourceLocation.
695//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000696
697/// getCharacterData - Return a pointer to the start of the specified location
698/// in the appropriate MemoryBuffer.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000699const char *SourceManager::getCharacterData(SourceLocation SL,
700 bool *Invalid) const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000701 // Note that this is a hot function in the getSpelling() path, which is
702 // heavily used by -E mode.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000703 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump1eb44332009-09-09 15:08:12 +0000704
Ted Kremenekc16c2082009-01-06 01:55:26 +0000705 // Note that calling 'getBuffer()' may lazily page in a source file.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000706 bool CharDataInvalid = false;
707 const llvm::MemoryBuffer *Buffer
708 = getSLocEntry(LocInfo.first).getFile().getContentCache()->getBuffer(Diag,
709 &CharDataInvalid);
710 if (Invalid)
711 *Invalid = CharDataInvalid;
712 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
Reid Spencer5f016e22007-07-11 17:01:13 +0000713}
714
Reid Spencer5f016e22007-07-11 17:01:13 +0000715
Chris Lattner9dc1f532007-07-20 16:37:10 +0000716/// getColumnNumber - Return the column # for the specified file position.
Chris Lattner7da5aea2009-02-04 00:55:58 +0000717/// this is significantly cheaper to compute than the line number.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000718unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
719 bool *Invalid) const {
720 bool MyInvalid = false;
721 const char *Buf = getBuffer(FID, &MyInvalid)->getBufferStart();
722 if (Invalid)
723 *Invalid = MyInvalid;
724
725 if (MyInvalid)
726 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000727
Reid Spencer5f016e22007-07-11 17:01:13 +0000728 unsigned LineStart = FilePos;
729 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
730 --LineStart;
731 return FilePos-LineStart+1;
732}
733
Douglas Gregor50f6af72010-03-16 05:20:39 +0000734unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
735 bool *Invalid) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000736 if (Loc.isInvalid()) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000737 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000738 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000739}
740
Douglas Gregor50f6af72010-03-16 05:20:39 +0000741unsigned SourceManager::getInstantiationColumnNumber(SourceLocation Loc,
742 bool *Invalid) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000743 if (Loc.isInvalid()) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000744 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000745 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000746}
747
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000748static DISABLE_INLINE void ComputeLineNumbers(Diagnostic &Diag,
749 ContentCache* FI,
Douglas Gregor50f6af72010-03-16 05:20:39 +0000750 llvm::BumpPtrAllocator &Alloc,
751 bool &Invalid);
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000752static void ComputeLineNumbers(Diagnostic &Diag, ContentCache* FI,
Douglas Gregor50f6af72010-03-16 05:20:39 +0000753 llvm::BumpPtrAllocator &Alloc, bool &Invalid) {
Ted Kremenekc16c2082009-01-06 01:55:26 +0000754 // Note that calling 'getBuffer()' may lazily page in the file.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000755 const MemoryBuffer *Buffer = FI->getBuffer(Diag, &Invalid);
756 if (Invalid)
757 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000758
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000759 // Find the file offsets of all of the *physical* source lines. This does
760 // not look at trigraphs, escaped newlines, or anything else tricky.
761 std::vector<unsigned> LineOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +0000762
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000763 // Line #1 starts at char 0.
764 LineOffsets.push_back(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000765
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000766 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
767 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
768 unsigned Offs = 0;
769 while (1) {
770 // Skip over the contents of the line.
771 // TODO: Vectorize this? This is very performance sensitive for programs
772 // with lots of diagnostics and in -E mode.
773 const unsigned char *NextBuf = (const unsigned char *)Buf;
774 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
775 ++NextBuf;
776 Offs += NextBuf-Buf;
777 Buf = NextBuf;
Mike Stump1eb44332009-09-09 15:08:12 +0000778
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000779 if (Buf[0] == '\n' || Buf[0] == '\r') {
780 // If this is \n\r or \r\n, skip both characters.
781 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
782 ++Offs, ++Buf;
783 ++Offs, ++Buf;
784 LineOffsets.push_back(Offs);
785 } else {
786 // Otherwise, this is a null. If end of file, exit.
787 if (Buf == End) break;
788 // Otherwise, skip the null.
789 ++Offs, ++Buf;
790 }
791 }
Mike Stump1eb44332009-09-09 15:08:12 +0000792
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000793 // Copy the offsets into the FileInfo structure.
794 FI->NumLines = LineOffsets.size();
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000795 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000796 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
797}
Reid Spencer5f016e22007-07-11 17:01:13 +0000798
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000799/// getLineNumber - Given a SourceLocation, return the spelling line number
Reid Spencer5f016e22007-07-11 17:01:13 +0000800/// for the position indicated. This requires building and caching a table of
801/// line offsets for the MemoryBuffer, so this is not cheap: use only when
802/// about to emit a diagnostic.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000803unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
804 bool *Invalid) const {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000805 ContentCache *Content;
Chris Lattner30fc9332009-02-04 01:06:56 +0000806 if (LastLineNoFileIDQuery == FID)
Ted Kremenek78d85f52007-10-30 21:08:08 +0000807 Content = LastLineNoContentCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000808 else
Chris Lattner30fc9332009-02-04 01:06:56 +0000809 Content = const_cast<ContentCache*>(getSLocEntry(FID)
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000810 .getFile().getContentCache());
Mike Stump1eb44332009-09-09 15:08:12 +0000811
Reid Spencer5f016e22007-07-11 17:01:13 +0000812 // If this is the first use of line information for this buffer, compute the
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000813 /// SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000814 if (Content->SourceLineCache == 0) {
815 bool MyInvalid = false;
816 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, MyInvalid);
817 if (Invalid)
818 *Invalid = MyInvalid;
819 if (MyInvalid)
820 return 1;
821 } else if (Invalid)
822 *Invalid = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000823
824 // Okay, we know we have a line number table. Do a binary search to find the
825 // line number that this character position lands on.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000826 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000827 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenek78d85f52007-10-30 21:08:08 +0000828 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump1eb44332009-09-09 15:08:12 +0000829
Chris Lattner30fc9332009-02-04 01:06:56 +0000830 unsigned QueriedFilePos = FilePos+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000831
Daniel Dunbar4106d692009-05-18 17:30:52 +0000832 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump1eb44332009-09-09 15:08:12 +0000833 // complicated as it is, binary search isn't that slow.
Daniel Dunbar4106d692009-05-18 17:30:52 +0000834 //
835 // If it is worth being optimized, then in my opinion it could be more
836 // performant, simpler, and more obviously correct by just "galloping" outward
837 // from the queried file position. In fact, this could be incorporated into a
838 // generic algorithm such as lower_bound_with_hint.
839 //
840 // If someone gives me a test case where this matters, and I will do it! - DWD
841
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000842 // If the previous query was to the same file, we know both the file pos from
843 // that query and the line number returned. This allows us to narrow the
844 // search space from the entire file to something near the match.
Chris Lattner30fc9332009-02-04 01:06:56 +0000845 if (LastLineNoFileIDQuery == FID) {
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000846 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar4106d692009-05-18 17:30:52 +0000847 // FIXME: Potential overflow?
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000848 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump1eb44332009-09-09 15:08:12 +0000849
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000850 // The query is likely to be nearby the previous one. Here we check to
851 // see if it is within 5, 10 or 20 lines. It can be far away in cases
852 // where big comment blocks and vertical whitespace eat up lines but
853 // contribute no tokens.
854 if (SourceLineCache+5 < SourceLineCacheEnd) {
855 if (SourceLineCache[5] > QueriedFilePos)
856 SourceLineCacheEnd = SourceLineCache+5;
857 else if (SourceLineCache+10 < SourceLineCacheEnd) {
858 if (SourceLineCache[10] > QueriedFilePos)
859 SourceLineCacheEnd = SourceLineCache+10;
860 else if (SourceLineCache+20 < SourceLineCacheEnd) {
861 if (SourceLineCache[20] > QueriedFilePos)
862 SourceLineCacheEnd = SourceLineCache+20;
863 }
864 }
865 }
866 } else {
Daniel Dunbar4106d692009-05-18 17:30:52 +0000867 if (LastLineNoResult < Content->NumLines)
868 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000869 }
870 }
Mike Stump1eb44332009-09-09 15:08:12 +0000871
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000872 // If the spread is large, do a "radix" test as our initial guess, based on
873 // the assumption that lines average to approximately the same length.
874 // NOTE: This is currently disabled, as it does not appear to be profitable in
875 // initial measurements.
876 if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
Ted Kremenek78d85f52007-10-30 21:08:08 +0000877 unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
Mike Stump1eb44332009-09-09 15:08:12 +0000878
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000879 // Take a stab at guessing where it is.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000880 unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
Mike Stump1eb44332009-09-09 15:08:12 +0000881
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000882 // Check for -10 and +10 lines.
883 unsigned LowerBound = std::max(int(ApproxPos-10), 0);
884 unsigned UpperBound = std::min(ApproxPos+10, FileLen);
885
886 // If the computed lower bound is less than the query location, move it in.
887 if (SourceLineCache < SourceLineCacheStart+LowerBound &&
888 SourceLineCacheStart[LowerBound] < QueriedFilePos)
889 SourceLineCache = SourceLineCacheStart+LowerBound;
Mike Stump1eb44332009-09-09 15:08:12 +0000890
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000891 // If the computed upper bound is greater than the query location, move it.
892 if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
893 SourceLineCacheStart[UpperBound] >= QueriedFilePos)
894 SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
895 }
Mike Stump1eb44332009-09-09 15:08:12 +0000896
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000897 unsigned *Pos
898 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000899 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump1eb44332009-09-09 15:08:12 +0000900
Chris Lattner30fc9332009-02-04 01:06:56 +0000901 LastLineNoFileIDQuery = FID;
Ted Kremenek78d85f52007-10-30 21:08:08 +0000902 LastLineNoContentCache = Content;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000903 LastLineNoFilePos = QueriedFilePos;
904 LastLineNoResult = LineNo;
905 return LineNo;
Reid Spencer5f016e22007-07-11 17:01:13 +0000906}
907
Douglas Gregor50f6af72010-03-16 05:20:39 +0000908unsigned SourceManager::getInstantiationLineNumber(SourceLocation Loc,
909 bool *Invalid) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000910 if (Loc.isInvalid()) return 0;
911 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
912 return getLineNumber(LocInfo.first, LocInfo.second);
913}
Douglas Gregor50f6af72010-03-16 05:20:39 +0000914unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
915 bool *Invalid) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000916 if (Loc.isInvalid()) return 0;
917 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
918 return getLineNumber(LocInfo.first, LocInfo.second);
919}
920
Chris Lattner6b306672009-02-04 05:33:01 +0000921/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump1eb44332009-09-09 15:08:12 +0000922/// source location, indicating whether this is a normal file, a system
Chris Lattner6b306672009-02-04 05:33:01 +0000923/// header, or an "implicit extern C" system header.
924///
925/// This state can be modified with flags on GNU linemarker directives like:
926/// # 4 "foo.h" 3
927/// which changes all source locations in the current file after that to be
928/// considered to be from a system header.
Mike Stump1eb44332009-09-09 15:08:12 +0000929SrcMgr::CharacteristicKind
Chris Lattner6b306672009-02-04 05:33:01 +0000930SourceManager::getFileCharacteristic(SourceLocation Loc) const {
931 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
932 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
933 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
934
935 // If there are no #line directives in this file, just return the whole-file
936 // state.
937 if (!FI.hasLineDirectives())
938 return FI.getFileCharacteristic();
Mike Stump1eb44332009-09-09 15:08:12 +0000939
Chris Lattner6b306672009-02-04 05:33:01 +0000940 assert(LineTable && "Can't have linetable entries without a LineTable!");
941 // See if there is a #line directive before the location.
942 const LineEntry *Entry =
943 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second);
Mike Stump1eb44332009-09-09 15:08:12 +0000944
Chris Lattner6b306672009-02-04 05:33:01 +0000945 // If this is before the first line marker, use the file characteristic.
946 if (!Entry)
947 return FI.getFileCharacteristic();
948
949 return Entry->FileKind;
950}
951
Chris Lattnerbff5c512009-02-17 08:39:06 +0000952/// Return the filename or buffer identifier of the buffer the location is in.
953/// Note that this name does not respect #line directives. Use getPresumedLoc
954/// for normal clients.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000955const char *SourceManager::getBufferName(SourceLocation Loc,
956 bool *Invalid) const {
Chris Lattnerbff5c512009-02-17 08:39:06 +0000957 if (Loc.isInvalid()) return "<invalid loc>";
Mike Stump1eb44332009-09-09 15:08:12 +0000958
Douglas Gregor50f6af72010-03-16 05:20:39 +0000959 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
Chris Lattnerbff5c512009-02-17 08:39:06 +0000960}
961
Chris Lattner30fc9332009-02-04 01:06:56 +0000962
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000963/// getPresumedLoc - This method returns the "presumed" location of a
964/// SourceLocation specifies. A "presumed location" can be modified by #line
965/// or GNU line marker directives. This provides a view on the data that a
966/// user should see in diagnostics, for example.
967///
968/// Note that a presumed location is always given as the instantiation point
969/// of an instantiation location, not at the spelling location.
970PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
971 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000972
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000973 // Presumed locations are always for instantiation points.
Chris Lattner7da5aea2009-02-04 00:55:58 +0000974 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000975
Chris Lattner30fc9332009-02-04 01:06:56 +0000976 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000977 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump1eb44332009-09-09 15:08:12 +0000978
Chris Lattner3cd949c2009-02-04 01:55:42 +0000979 // To get the source name, first consult the FileEntry (if one exists)
980 // before the MemBuffer as this will avoid unnecessarily paging in the
981 // MemBuffer.
Mike Stump1eb44332009-09-09 15:08:12 +0000982 const char *Filename =
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000983 C->Entry ? C->Entry->getName() : C->getBuffer(Diag)->getBufferIdentifier();
Chris Lattner3cd949c2009-02-04 01:55:42 +0000984 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second);
985 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second);
986 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000987
Chris Lattner3cd949c2009-02-04 01:55:42 +0000988 // If we have #line directives in this file, update and overwrite the physical
989 // location info if appropriate.
990 if (FI.hasLineDirectives()) {
991 assert(LineTable && "Can't have linetable entries without a LineTable!");
992 // See if there is a #line directive before this. If so, get it.
993 if (const LineEntry *Entry =
994 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) {
Chris Lattnerfc391332009-02-04 02:00:59 +0000995 // If the LineEntry indicates a filename, use it.
Chris Lattner3cd949c2009-02-04 01:55:42 +0000996 if (Entry->FilenameID != -1)
997 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerfc391332009-02-04 02:00:59 +0000998
999 // Use the line number specified by the LineEntry. This line number may
1000 // be multiple lines down from the line entry. Add the difference in
1001 // physical line numbers from the query point and the line marker to the
1002 // total.
1003 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1004 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001005
Chris Lattner0e0e5da2009-02-04 02:15:40 +00001006 // Note that column numbers are not molested by line markers.
Mike Stump1eb44332009-09-09 15:08:12 +00001007
Chris Lattner137b6a62009-02-04 06:25:26 +00001008 // Handle virtual #include manipulation.
1009 if (Entry->IncludeOffset) {
1010 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1011 IncludeLoc = IncludeLoc.getFileLocWithOffset(Entry->IncludeOffset);
1012 }
Chris Lattner3cd949c2009-02-04 01:55:42 +00001013 }
1014 }
1015
1016 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001017}
1018
1019//===----------------------------------------------------------------------===//
1020// Other miscellaneous methods.
1021//===----------------------------------------------------------------------===//
1022
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001023/// \brief Get the source location for the given file:line:col triplet.
1024///
1025/// If the source file is included multiple times, the source location will
1026/// be based upon the first inclusion.
1027SourceLocation SourceManager::getLocation(const FileEntry *SourceFile,
1028 unsigned Line, unsigned Col) const {
1029 assert(SourceFile && "Null source file!");
1030 assert(Line && Col && "Line and column should start from 1!");
1031
1032 fileinfo_iterator FI = FileInfos.find(SourceFile);
1033 if (FI == FileInfos.end())
1034 return SourceLocation();
1035 ContentCache *Content = FI->second;
Mike Stump1eb44332009-09-09 15:08:12 +00001036
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001037 // If this is the first use of line information for this buffer, compute the
1038 /// SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001039 if (Content->SourceLineCache == 0) {
1040 bool MyInvalid = false;
1041 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, MyInvalid);
1042 if (MyInvalid)
1043 return SourceLocation();
1044 }
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001045
Douglas Gregor4a160e12009-12-02 05:34:39 +00001046 // Find the first file ID that corresponds to the given file.
1047 FileID FirstFID;
1048
1049 // First, check the main file ID, since it is common to look for a
1050 // location in the main file.
1051 if (!MainFileID.isInvalid()) {
1052 const SLocEntry &MainSLoc = getSLocEntry(MainFileID);
1053 if (MainSLoc.isFile() && MainSLoc.getFile().getContentCache() == Content)
1054 FirstFID = MainFileID;
1055 }
1056
1057 if (FirstFID.isInvalid()) {
1058 // The location we're looking for isn't in the main file; look
1059 // through all of the source locations.
1060 for (unsigned I = 0, N = sloc_entry_size(); I != N; ++I) {
1061 const SLocEntry &SLoc = getSLocEntry(I);
1062 if (SLoc.isFile() && SLoc.getFile().getContentCache() == Content) {
1063 FirstFID = FileID::get(I);
1064 break;
1065 }
1066 }
1067 }
1068
1069 if (FirstFID.isInvalid())
1070 return SourceLocation();
1071
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001072 if (Line > Content->NumLines) {
Douglas Gregor36c35ba2010-03-16 00:35:39 +00001073 unsigned Size = Content->getBuffer(Diag)->getBufferSize();
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001074 if (Size > 0)
1075 --Size;
1076 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(Size);
1077 }
1078
1079 unsigned FilePos = Content->SourceLineCache[Line - 1];
Douglas Gregor36c35ba2010-03-16 00:35:39 +00001080 const char *Buf = Content->getBuffer(Diag)->getBufferStart() + FilePos;
1081 unsigned BufLength = Content->getBuffer(Diag)->getBufferEnd() - Buf;
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001082 unsigned i = 0;
1083
1084 // Check that the given column is valid.
1085 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1086 ++i;
1087 if (i < Col-1)
1088 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + i);
1089
Douglas Gregor4a160e12009-12-02 05:34:39 +00001090 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + Col - 1);
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001091}
1092
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001093/// \brief Determines the order of 2 source locations in the translation unit.
1094///
1095/// \returns true if LHS source location comes before RHS, false otherwise.
1096bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1097 SourceLocation RHS) const {
1098 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1099 if (LHS == RHS)
1100 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001101
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001102 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1103 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00001104
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001105 // If the source locations are in the same file, just compare offsets.
1106 if (LOffs.first == ROffs.first)
1107 return LOffs.second < ROffs.second;
1108
1109 // If we are comparing a source location with multiple locations in the same
1110 // file, we get a big win by caching the result.
Mike Stump1eb44332009-09-09 15:08:12 +00001111
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001112 if (LastLFIDForBeforeTUCheck == LOffs.first &&
1113 LastRFIDForBeforeTUCheck == ROffs.first)
1114 return LastResForBeforeTUCheck;
Mike Stump1eb44332009-09-09 15:08:12 +00001115
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001116 LastLFIDForBeforeTUCheck = LOffs.first;
1117 LastRFIDForBeforeTUCheck = ROffs.first;
Mike Stump1eb44332009-09-09 15:08:12 +00001118
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001119 // "Traverse" the include/instantiation stacks of both locations and try to
1120 // find a common "ancestor".
1121 //
1122 // First we traverse the stack of the right location and check each level
1123 // against the level of the left location, while collecting all levels in a
1124 // "stack map".
1125
1126 std::map<FileID, unsigned> ROffsMap;
1127 ROffsMap[ROffs.first] = ROffs.second;
1128
1129 while (1) {
1130 SourceLocation UpperLoc;
1131 const SrcMgr::SLocEntry &Entry = getSLocEntry(ROffs.first);
1132 if (Entry.isInstantiation())
1133 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1134 else
1135 UpperLoc = Entry.getFile().getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001136
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001137 if (UpperLoc.isInvalid())
1138 break; // We reached the top.
Mike Stump1eb44332009-09-09 15:08:12 +00001139
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001140 ROffs = getDecomposedLoc(UpperLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001141
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001142 if (LOffs.first == ROffs.first)
1143 return LastResForBeforeTUCheck = LOffs.second < ROffs.second;
Mike Stump1eb44332009-09-09 15:08:12 +00001144
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001145 ROffsMap[ROffs.first] = ROffs.second;
1146 }
1147
1148 // We didn't find a common ancestor. Now traverse the stack of the left
1149 // location, checking against the stack map of the right location.
1150
1151 while (1) {
1152 SourceLocation UpperLoc;
1153 const SrcMgr::SLocEntry &Entry = getSLocEntry(LOffs.first);
1154 if (Entry.isInstantiation())
1155 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1156 else
1157 UpperLoc = Entry.getFile().getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001158
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001159 if (UpperLoc.isInvalid())
1160 break; // We reached the top.
Mike Stump1eb44332009-09-09 15:08:12 +00001161
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001162 LOffs = getDecomposedLoc(UpperLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001163
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001164 std::map<FileID, unsigned>::iterator I = ROffsMap.find(LOffs.first);
1165 if (I != ROffsMap.end())
1166 return LastResForBeforeTUCheck = LOffs.second < I->second;
1167 }
Mike Stump1eb44332009-09-09 15:08:12 +00001168
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001169 // There is no common ancestor, most probably because one location is in the
1170 // predefines buffer.
1171 //
1172 // FIXME: We should rearrange the external interface so this simply never
1173 // happens; it can't conceptually happen. Also see PR5662.
Mike Stump1eb44332009-09-09 15:08:12 +00001174
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001175 // If exactly one location is a memory buffer, assume it preceeds the other.
1176 bool LIsMB = !getSLocEntry(LOffs.first).getFile().getContentCache()->Entry;
1177 bool RIsMB = !getSLocEntry(ROffs.first).getFile().getContentCache()->Entry;
1178 if (LIsMB != RIsMB)
1179 return LastResForBeforeTUCheck = LIsMB;
Mike Stump1eb44332009-09-09 15:08:12 +00001180
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001181 // Otherwise, just assume FileIDs were created in order.
1182 return LastResForBeforeTUCheck = (LOffs.first < ROffs.first);
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001183}
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001184
Reid Spencer5f016e22007-07-11 17:01:13 +00001185/// PrintStats - Print statistics to stderr.
1186///
1187void SourceManager::PrintStats() const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001188 llvm::errs() << "\n*** Source Manager Stats:\n";
1189 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
1190 << " mem buffers mapped.\n";
1191 llvm::errs() << SLocEntryTable.size() << " SLocEntry's allocated, "
1192 << NextOffset << "B of Sloc address space used.\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001193
Reid Spencer5f016e22007-07-11 17:01:13 +00001194 unsigned NumLineNumsComputed = 0;
1195 unsigned NumFileBytesMapped = 0;
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00001196 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
1197 NumLineNumsComputed += I->second->SourceLineCache != 0;
1198 NumFileBytesMapped += I->second->getSizeBytesMapped();
Reid Spencer5f016e22007-07-11 17:01:13 +00001199 }
Mike Stump1eb44332009-09-09 15:08:12 +00001200
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001201 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
1202 << NumLineNumsComputed << " files with line #'s computed.\n";
1203 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
1204 << NumBinaryProbes << " binary.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +00001205}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001206
1207ExternalSLocEntrySource::~ExternalSLocEntrySource() { }