blob: ac2fe3d69e3866daf9838699bf05042aea362b77 [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 Gregorf9b0a582010-03-15 23:33:37 +000025#include <cstdio>
Douglas Gregoraea67db2010-03-15 22:54:52 +000026
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28using namespace SrcMgr;
29using llvm::MemoryBuffer;
30
Chris Lattner23b5dc62009-02-04 00:40:31 +000031//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +000032// SourceManager Helper Classes
Chris Lattner23b5dc62009-02-04 00:40:31 +000033//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +000034
Douglas Gregoraea67db2010-03-15 22:54:52 +000035struct BufferResult::FailureData {
36 const llvm::MemoryBuffer *Buffer;
37 const char *FileName;
38 std::string ErrorStr;
39};
40
41BufferResult::BufferResult(const BufferResult &Other) {
42 if (const llvm::MemoryBuffer *Buffer
43 = Other.Data.dyn_cast<const llvm::MemoryBuffer *>()) {
44 Data = Buffer;
45 return;
46 }
47
48 Data = new FailureData(*Other.Data.get<FailureData *>());
49}
50
51BufferResult::BufferResult(const char *FileName, llvm::StringRef ErrorStr,
52 const llvm::MemoryBuffer *Buffer) {
53 FailureData *FD = new FailureData;
54 FD->FileName = FileName;
55 FD->ErrorStr = ErrorStr;
56 FD->Buffer = Buffer;
57 Data = FD;
58}
59
60BufferResult::~BufferResult() {
61 if (FailureData *FD = Data.dyn_cast<FailureData *>())
62 delete FD;
63}
64
65bool BufferResult::isInvalid() const {
66 return Data.is<FailureData *>();
67}
68
69const llvm::MemoryBuffer *BufferResult::getBuffer(Diagnostic &Diags) const {
70 llvm::StringRef FileName;
71 std::string ErrorMsg;
72 const llvm::MemoryBuffer *Result = getBuffer(FileName, ErrorMsg);
73 if (!ErrorMsg.empty()) {
74 Diags.Report(diag::err_cannot_open_file)
75 << FileName << ErrorMsg;
76 }
77 return Result;
78}
79
80const llvm::MemoryBuffer *BufferResult::getBuffer(llvm::StringRef &FileName,
81 std::string &Error) const {
82 if (const llvm::MemoryBuffer *Buffer
83 = Data.dyn_cast<const llvm::MemoryBuffer *>())
84 return Buffer;
85
86 FailureData *Fail = Data.get<FailureData *>();
87 FileName = Fail->FileName;
88 Error = Fail->ErrorStr;
89 return Fail->Buffer;
90}
91
92BufferResult::operator const llvm::MemoryBuffer *() const {
93 llvm::StringRef FileName;
94 std::string ErrorMsg;
95 const llvm::MemoryBuffer *Result = getBuffer(FileName, ErrorMsg);
96 if (!ErrorMsg.empty()) {
97 fprintf(stderr, "error: cannot open file '%s': %s\n",
98 FileName.str().c_str(), ErrorMsg.c_str());
99 }
100
101 return Result;
102}
103
Ted Kremenek78d85f52007-10-30 21:08:08 +0000104ContentCache::~ContentCache() {
105 delete Buffer;
Reid Spencer5f016e22007-07-11 17:01:13 +0000106}
107
Ted Kremenekc16c2082009-01-06 01:55:26 +0000108/// getSizeBytesMapped - Returns the number of bytes actually mapped for
109/// this ContentCache. This can be 0 if the MemBuffer was not actually
110/// instantiated.
111unsigned ContentCache::getSizeBytesMapped() const {
112 return Buffer ? Buffer->getBufferSize() : 0;
113}
114
115/// getSize - Returns the size of the content encapsulated by this ContentCache.
116/// This can be the size of the source file or the size of an arbitrary
117/// scratch buffer. If the ContentCache encapsulates a source file, that
Douglas Gregor29684422009-12-02 06:49:09 +0000118/// file is not lazily brought in from disk to satisfy this query.
Ted Kremenekc16c2082009-01-06 01:55:26 +0000119unsigned ContentCache::getSize() const {
Ted Kremenek8515fbf2010-03-10 18:22:38 +0000120 return Buffer ? (unsigned) Buffer->getBufferSize()
121 : (unsigned) Entry->getSize();
Ted Kremenekc16c2082009-01-06 01:55:26 +0000122}
123
Douglas Gregor29684422009-12-02 06:49:09 +0000124void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B) {
Douglas Gregor109ae732009-12-03 17:05:59 +0000125 assert(B != Buffer);
Douglas Gregor29684422009-12-02 06:49:09 +0000126
127 delete Buffer;
128 Buffer = B;
129}
130
Douglas Gregoraea67db2010-03-15 22:54:52 +0000131BufferResult ContentCache::getBuffer() const {
Ted Kremenek5b034ad2009-01-06 22:43:04 +0000132 // Lazily create the Buffer for ContentCaches that wrap files.
133 if (!Buffer && Entry) {
Douglas Gregoraea67db2010-03-15 22:54:52 +0000134 std::string ErrorStr;
135 struct stat FileInfo;
136 Buffer = MemoryBuffer::getFile(Entry->getName(), &ErrorStr,
137 Entry->getSize(), &FileInfo);
Daniel Dunbar21a8bed2009-12-06 05:43:36 +0000138
139 // If we were unable to open the file, then we are in an inconsistent
140 // situation where the content cache referenced a file which no longer
141 // exists. Most likely, we were using a stat cache with an invalid entry but
142 // the file could also have been removed during processing. Since we can't
143 // really deal with this situation, just create an empty buffer.
144 //
145 // FIXME: This is definitely not ideal, but our immediate clients can't
146 // currently handle returning a null entry here. Ideally we should detect
147 // that we are in an inconsistent situation and error out as quickly as
148 // possible.
149 if (!Buffer) {
150 const llvm::StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
151 Buffer = MemoryBuffer::getNewMemBuffer(Entry->getSize(), "<invalid>");
152 char *Ptr = const_cast<char*>(Buffer->getBufferStart());
153 for (unsigned i = 0, e = Entry->getSize(); i != e; ++i)
154 Ptr[i] = FillStr[i % FillStr.size()];
Douglas Gregoraea67db2010-03-15 22:54:52 +0000155 return BufferResult(Entry->getName(), ErrorStr, Buffer);
156 } else {
157 // Check that the file's size and modification time is the same as
158 // in the file entry (which may have come from a stat cache).
159 // FIXME: Make these strings localizable.
160 if (FileInfo.st_size != Entry->getSize()) {
161 ErrorStr = "file has changed size since it was originally read";
162 return BufferResult(Entry->getName(), ErrorStr, Buffer);
163 } else if (FileInfo.st_mtime != Entry->getModificationTime()) {
164 ErrorStr = "file has been modified since it was originally read";
165 return BufferResult(Entry->getName(), ErrorStr, Buffer);
166 }
Daniel Dunbar21a8bed2009-12-06 05:43:36 +0000167 }
Ted Kremenek5b034ad2009-01-06 22:43:04 +0000168 }
Douglas Gregoraea67db2010-03-15 22:54:52 +0000169
Ted Kremenekc16c2082009-01-06 01:55:26 +0000170 return Buffer;
171}
172
Chris Lattner5b9a5042009-01-26 07:57:50 +0000173unsigned LineTableInfo::getLineTableFilenameID(const char *Ptr, unsigned Len) {
174 // Look up the filename in the string table, returning the pre-existing value
175 // if it exists.
Mike Stump1eb44332009-09-09 15:08:12 +0000176 llvm::StringMapEntry<unsigned> &Entry =
Chris Lattner5b9a5042009-01-26 07:57:50 +0000177 FilenameIDs.GetOrCreateValue(Ptr, Ptr+Len, ~0U);
178 if (Entry.getValue() != ~0U)
179 return Entry.getValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000180
Chris Lattner5b9a5042009-01-26 07:57:50 +0000181 // Otherwise, assign this the next available ID.
182 Entry.setValue(FilenamesByID.size());
183 FilenamesByID.push_back(&Entry);
184 return FilenamesByID.size()-1;
185}
186
Chris Lattnerac50e342009-02-03 22:13:05 +0000187/// AddLineNote - Add a line note to the line table that indicates that there
188/// is a #line at the specified FID/Offset location which changes the presumed
189/// location to LineNo/FilenameID.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000190void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
Chris Lattnerac50e342009-02-03 22:13:05 +0000191 unsigned LineNo, int FilenameID) {
Chris Lattner23b5dc62009-02-04 00:40:31 +0000192 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000193
Chris Lattner23b5dc62009-02-04 00:40:31 +0000194 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
195 "Adding line entries out of order!");
Mike Stump1eb44332009-09-09 15:08:12 +0000196
Chris Lattner9d79eba2009-02-04 05:21:58 +0000197 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
Chris Lattner137b6a62009-02-04 06:25:26 +0000198 unsigned IncludeOffset = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000199
Chris Lattner9d79eba2009-02-04 05:21:58 +0000200 if (!Entries.empty()) {
201 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
202 // that we are still in "foo.h".
203 if (FilenameID == -1)
204 FilenameID = Entries.back().FilenameID;
Mike Stump1eb44332009-09-09 15:08:12 +0000205
Chris Lattner137b6a62009-02-04 06:25:26 +0000206 // If we are after a line marker that switched us to system header mode, or
207 // that set #include information, preserve it.
Chris Lattner9d79eba2009-02-04 05:21:58 +0000208 Kind = Entries.back().FileKind;
Chris Lattner137b6a62009-02-04 06:25:26 +0000209 IncludeOffset = Entries.back().IncludeOffset;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000210 }
Mike Stump1eb44332009-09-09 15:08:12 +0000211
Chris Lattner137b6a62009-02-04 06:25:26 +0000212 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
213 IncludeOffset));
Chris Lattnerac50e342009-02-03 22:13:05 +0000214}
215
Chris Lattner9d79eba2009-02-04 05:21:58 +0000216/// AddLineNote This is the same as the previous version of AddLineNote, but is
217/// used for GNU line markers. If EntryExit is 0, then this doesn't change the
218/// presumed #include stack. If it is 1, this is a file entry, if it is 2 then
219/// this is a file exit. FileKind specifies whether this is a system header or
220/// extern C system header.
221void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
222 unsigned LineNo, int FilenameID,
223 unsigned EntryExit,
224 SrcMgr::CharacteristicKind FileKind) {
225 assert(FilenameID != -1 && "Unspecified filename should use other accessor");
Mike Stump1eb44332009-09-09 15:08:12 +0000226
Chris Lattner9d79eba2009-02-04 05:21:58 +0000227 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000228
Chris Lattner9d79eba2009-02-04 05:21:58 +0000229 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
230 "Adding line entries out of order!");
231
Chris Lattner137b6a62009-02-04 06:25:26 +0000232 unsigned IncludeOffset = 0;
233 if (EntryExit == 0) { // No #include stack change.
234 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
235 } else if (EntryExit == 1) {
236 IncludeOffset = Offset-1;
237 } else if (EntryExit == 2) {
238 assert(!Entries.empty() && Entries.back().IncludeOffset &&
239 "PPDirectives should have caught case when popping empty include stack");
Mike Stump1eb44332009-09-09 15:08:12 +0000240
Chris Lattner137b6a62009-02-04 06:25:26 +0000241 // Get the include loc of the last entries' include loc as our include loc.
242 IncludeOffset = 0;
243 if (const LineEntry *PrevEntry =
244 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
245 IncludeOffset = PrevEntry->IncludeOffset;
246 }
Mike Stump1eb44332009-09-09 15:08:12 +0000247
Chris Lattner137b6a62009-02-04 06:25:26 +0000248 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
249 IncludeOffset));
Chris Lattner9d79eba2009-02-04 05:21:58 +0000250}
251
252
Chris Lattner3cd949c2009-02-04 01:55:42 +0000253/// FindNearestLineEntry - Find the line entry nearest to FID that is before
254/// it. If there is no line entry before Offset in FID, return null.
Mike Stump1eb44332009-09-09 15:08:12 +0000255const LineEntry *LineTableInfo::FindNearestLineEntry(unsigned FID,
Chris Lattner3cd949c2009-02-04 01:55:42 +0000256 unsigned Offset) {
257 const std::vector<LineEntry> &Entries = LineEntries[FID];
258 assert(!Entries.empty() && "No #line entries for this FID after all!");
259
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000260 // It is very common for the query to be after the last #line, check this
261 // first.
262 if (Entries.back().FileOffset <= Offset)
263 return &Entries.back();
Chris Lattner3cd949c2009-02-04 01:55:42 +0000264
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000265 // Do a binary search to find the maximal element that is still before Offset.
266 std::vector<LineEntry>::const_iterator I =
267 std::upper_bound(Entries.begin(), Entries.end(), Offset);
268 if (I == Entries.begin()) return 0;
269 return &*--I;
Chris Lattner3cd949c2009-02-04 01:55:42 +0000270}
Chris Lattnerac50e342009-02-03 22:13:05 +0000271
Douglas Gregorbd945002009-04-13 16:31:14 +0000272/// \brief Add a new line entry that has already been encoded into
273/// the internal representation of the line table.
Mike Stump1eb44332009-09-09 15:08:12 +0000274void LineTableInfo::AddEntry(unsigned FID,
Douglas Gregorbd945002009-04-13 16:31:14 +0000275 const std::vector<LineEntry> &Entries) {
276 LineEntries[FID] = Entries;
277}
Chris Lattnerac50e342009-02-03 22:13:05 +0000278
Chris Lattner5b9a5042009-01-26 07:57:50 +0000279/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
Mike Stump1eb44332009-09-09 15:08:12 +0000280///
Chris Lattner5b9a5042009-01-26 07:57:50 +0000281unsigned SourceManager::getLineTableFilenameID(const char *Ptr, unsigned Len) {
282 if (LineTable == 0)
283 LineTable = new LineTableInfo();
284 return LineTable->getLineTableFilenameID(Ptr, Len);
285}
286
287
Chris Lattner4c4ea172009-02-03 21:52:55 +0000288/// AddLineNote - Add a line note to the line table for the FileID and offset
289/// specified by Loc. If FilenameID is -1, it is considered to be
290/// unspecified.
291void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
292 int FilenameID) {
Chris Lattnerac50e342009-02-03 22:13:05 +0000293 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000294
Chris Lattnerac50e342009-02-03 22:13:05 +0000295 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
296
297 // Remember that this file has #line directives now if it doesn't already.
298 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000299
Chris Lattnerac50e342009-02-03 22:13:05 +0000300 if (LineTable == 0)
301 LineTable = new LineTableInfo();
Chris Lattner23b5dc62009-02-04 00:40:31 +0000302 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID);
Chris Lattner4c4ea172009-02-03 21:52:55 +0000303}
304
Chris Lattner9d79eba2009-02-04 05:21:58 +0000305/// AddLineNote - Add a GNU line marker to the line table.
306void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
307 int FilenameID, bool IsFileEntry,
308 bool IsFileExit, bool IsSystemHeader,
309 bool IsExternCHeader) {
310 // If there is no filename and no flags, this is treated just like a #line,
311 // which does not change the flags of the previous line marker.
312 if (FilenameID == -1) {
313 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
314 "Can't set flags without setting the filename!");
315 return AddLineNote(Loc, LineNo, FilenameID);
316 }
Mike Stump1eb44332009-09-09 15:08:12 +0000317
Chris Lattner9d79eba2009-02-04 05:21:58 +0000318 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
319 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Chris Lattner9d79eba2009-02-04 05:21:58 +0000321 // Remember that this file has #line directives now if it doesn't already.
322 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000323
Chris Lattner9d79eba2009-02-04 05:21:58 +0000324 if (LineTable == 0)
325 LineTable = new LineTableInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000326
Chris Lattner9d79eba2009-02-04 05:21:58 +0000327 SrcMgr::CharacteristicKind FileKind;
328 if (IsExternCHeader)
329 FileKind = SrcMgr::C_ExternCSystem;
330 else if (IsSystemHeader)
331 FileKind = SrcMgr::C_System;
332 else
333 FileKind = SrcMgr::C_User;
Mike Stump1eb44332009-09-09 15:08:12 +0000334
Chris Lattner9d79eba2009-02-04 05:21:58 +0000335 unsigned EntryExit = 0;
336 if (IsFileEntry)
337 EntryExit = 1;
338 else if (IsFileExit)
339 EntryExit = 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000340
Chris Lattner9d79eba2009-02-04 05:21:58 +0000341 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID,
342 EntryExit, FileKind);
343}
344
Douglas Gregorbd945002009-04-13 16:31:14 +0000345LineTableInfo &SourceManager::getLineTable() {
346 if (LineTable == 0)
347 LineTable = new LineTableInfo();
348 return *LineTable;
349}
Chris Lattner4c4ea172009-02-03 21:52:55 +0000350
Chris Lattner23b5dc62009-02-04 00:40:31 +0000351//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000352// Private 'Create' methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000353//===----------------------------------------------------------------------===//
Ted Kremenekc16c2082009-01-06 01:55:26 +0000354
Chris Lattner5b9a5042009-01-26 07:57:50 +0000355SourceManager::~SourceManager() {
356 delete LineTable;
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000358 // Delete FileEntry objects corresponding to content caches. Since the actual
359 // content cache objects are bump pointer allocated, we just have to run the
360 // dtors, but we call the deallocate method for completeness.
361 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
362 MemBufferInfos[i]->~ContentCache();
363 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
364 }
365 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
366 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
367 I->second->~ContentCache();
368 ContentCacheAlloc.Deallocate(I->second);
369 }
Chris Lattner5b9a5042009-01-26 07:57:50 +0000370}
371
372void SourceManager::clearIDTables() {
373 MainFileID = FileID();
374 SLocEntryTable.clear();
375 LastLineNoFileIDQuery = FileID();
376 LastLineNoContentCache = 0;
377 LastFileIDLookup = FileID();
Mike Stump1eb44332009-09-09 15:08:12 +0000378
Chris Lattner5b9a5042009-01-26 07:57:50 +0000379 if (LineTable)
380 LineTable->clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Chris Lattner5b9a5042009-01-26 07:57:50 +0000382 // Use up FileID #0 as an invalid instantiation.
383 NextOffset = 0;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000384 createInstantiationLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000385}
386
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000387/// getOrCreateContentCache - Create or return a cached ContentCache for the
388/// specified file.
389const ContentCache *
390SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000391 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Reid Spencer5f016e22007-07-11 17:01:13 +0000393 // Do we already have information about this file?
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000394 ContentCache *&Entry = FileInfos[FileEnt];
395 if (Entry) return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Chris Lattner00282d62009-02-03 07:41:46 +0000397 // Nope, create a new Cache entry. Make sure it is at least 8-byte aligned
398 // so that FileInfo can use the low 3 bits of the pointer for its own
399 // nefarious purposes.
400 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
401 EntryAlign = std::max(8U, EntryAlign);
402 Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000403 new (Entry) ContentCache(FileEnt);
404 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000405}
406
407
Ted Kremenekd1c0eee2007-10-31 17:53:38 +0000408/// createMemBufferContentCache - Create a new ContentCache for the specified
409/// memory buffer. This does no caching.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000410const ContentCache*
411SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
Chris Lattner00282d62009-02-03 07:41:46 +0000412 // Add a new ContentCache to the MemBufferInfos list and return it. Make sure
413 // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of
414 // the pointer for its own nefarious purposes.
415 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
416 EntryAlign = std::max(8U, EntryAlign);
417 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000418 new (Entry) ContentCache();
419 MemBufferInfos.push_back(Entry);
420 Entry->setBuffer(Buffer);
421 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000422}
423
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000424void SourceManager::PreallocateSLocEntries(ExternalSLocEntrySource *Source,
425 unsigned NumSLocEntries,
426 unsigned NextOffset) {
427 ExternalSLocEntries = Source;
428 this->NextOffset = NextOffset;
429 SLocEntryLoaded.resize(NumSLocEntries + 1);
430 SLocEntryLoaded[0] = true;
431 SLocEntryTable.resize(SLocEntryTable.size() + NumSLocEntries);
432}
433
Douglas Gregor2bf1eb02009-04-27 21:28:04 +0000434void SourceManager::ClearPreallocatedSLocEntries() {
435 unsigned I = 0;
436 for (unsigned N = SLocEntryLoaded.size(); I != N; ++I)
437 if (!SLocEntryLoaded[I])
438 break;
439
440 // We've already loaded all preallocated source location entries.
441 if (I == SLocEntryLoaded.size())
442 return;
443
444 // Remove everything from location I onward.
445 SLocEntryTable.resize(I);
446 SLocEntryLoaded.clear();
447 ExternalSLocEntries = 0;
448}
449
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000450
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000451//===----------------------------------------------------------------------===//
452// Methods to create new FileID's and instantiations.
453//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000454
Nico Weber48002c82008-09-29 00:25:48 +0000455/// createFileID - Create a new fileID for the specified ContentCache and
Ted Kremenek0d892d82007-10-30 22:57:35 +0000456/// include position. This works regardless of whether the ContentCache
457/// corresponds to a file or some other input source.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000458FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000459 SourceLocation IncludePos,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000460 SrcMgr::CharacteristicKind FileCharacter,
461 unsigned PreallocatedID,
462 unsigned Offset) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000463 if (PreallocatedID) {
464 // If we're filling in a preallocated ID, just load in the file
465 // entry and return.
Mike Stump1eb44332009-09-09 15:08:12 +0000466 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000467 "Preallocate ID out-of-range");
Mike Stump1eb44332009-09-09 15:08:12 +0000468 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000469 "Source location entry already loaded");
470 assert(Offset && "Preallocate source location cannot have zero offset");
Mike Stump1eb44332009-09-09 15:08:12 +0000471 SLocEntryTable[PreallocatedID]
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000472 = SLocEntry::get(Offset, FileInfo::get(IncludePos, File, FileCharacter));
473 SLocEntryLoaded[PreallocatedID] = true;
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +0000474 FileID FID = FileID::get(PreallocatedID);
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +0000475 return LastFileIDLookup = FID;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000476 }
477
Mike Stump1eb44332009-09-09 15:08:12 +0000478 SLocEntryTable.push_back(SLocEntry::get(NextOffset,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000479 FileInfo::get(IncludePos, File,
480 FileCharacter)));
Ted Kremenekc16c2082009-01-06 01:55:26 +0000481 unsigned FileSize = File->getSize();
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000482 assert(NextOffset+FileSize+1 > NextOffset && "Ran out of source locations!");
483 NextOffset += FileSize+1;
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000485 // Set LastFileIDLookup to the newly created file. The next getFileID call is
486 // almost guaranteed to be from that file.
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000487 FileID FID = FileID::get(SLocEntryTable.size()-1);
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000488 return LastFileIDLookup = FID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000489}
490
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000491/// createInstantiationLoc - Return a new SourceLocation that encodes the fact
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000492/// that a token from SpellingLoc should actually be referenced from
Reid Spencer5f016e22007-07-11 17:01:13 +0000493/// InstantiationLoc.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000494SourceLocation SourceManager::createInstantiationLoc(SourceLocation SpellingLoc,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000495 SourceLocation ILocStart,
496 SourceLocation ILocEnd,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000497 unsigned TokLength,
498 unsigned PreallocatedID,
499 unsigned Offset) {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000500 InstantiationInfo II = InstantiationInfo::get(ILocStart,ILocEnd, SpellingLoc);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000501 if (PreallocatedID) {
502 // If we're filling in a preallocated ID, just load in the
503 // instantiation entry and return.
Mike Stump1eb44332009-09-09 15:08:12 +0000504 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000505 "Preallocate ID out-of-range");
Mike Stump1eb44332009-09-09 15:08:12 +0000506 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000507 "Source location entry already loaded");
508 assert(Offset && "Preallocate source location cannot have zero offset");
509 SLocEntryTable[PreallocatedID] = SLocEntry::get(Offset, II);
510 SLocEntryLoaded[PreallocatedID] = true;
511 return SourceLocation::getMacroLoc(Offset);
512 }
Chris Lattnere7fb4842009-02-15 20:52:18 +0000513 SLocEntryTable.push_back(SLocEntry::get(NextOffset, II));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000514 assert(NextOffset+TokLength+1 > NextOffset && "Ran out of source locations!");
515 NextOffset += TokLength+1;
516 return SourceLocation::getMacroLoc(NextOffset-(TokLength+1));
Reid Spencer5f016e22007-07-11 17:01:13 +0000517}
518
Douglas Gregoraea67db2010-03-15 22:54:52 +0000519BufferResult SourceManager::getMemoryBufferForFile(const FileEntry *File) {
Douglas Gregor29684422009-12-02 06:49:09 +0000520 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregoraea67db2010-03-15 22:54:52 +0000521 assert(IR && "getOrCreateContentCache() cannot return NULL");
Douglas Gregor29684422009-12-02 06:49:09 +0000522 return IR->getBuffer();
523}
524
525bool SourceManager::overrideFileContents(const FileEntry *SourceFile,
526 const llvm::MemoryBuffer *Buffer) {
527 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
528 if (IR == 0)
529 return true;
530
531 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer);
532 return false;
533}
534
Chris Lattner2b2453a2009-01-17 06:22:33 +0000535std::pair<const char*, const char*>
Douglas Gregorf715ca12010-03-16 00:06:06 +0000536SourceManager::getBufferData(FileID FID, bool *Invalid) const {
537 if (Invalid)
538 *Invalid = false;
539
540 const llvm::MemoryBuffer *Buf = getBuffer(FID).getBuffer(Diag);
541 if (!Buf) {
542 if (*Invalid)
543 *Invalid = true;
544 const char *FakeText = "";
545 return std::make_pair(FakeText, FakeText + strlen(FakeText));
546 }
Douglas Gregoraea67db2010-03-15 22:54:52 +0000547 return std::make_pair(Buf->getBufferStart(), Buf->getBufferEnd());
548}
Chris Lattner2b2453a2009-01-17 06:22:33 +0000549
Chris Lattner23b5dc62009-02-04 00:40:31 +0000550//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000551// SourceLocation manipulation methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000552//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000553
554/// getFileIDSlow - Return the FileID for a SourceLocation. This is a very hot
555/// method that is used for all SourceManager queries that start with a
556/// SourceLocation object. It is responsible for finding the entry in
557/// SLocEntryTable which contains the specified location.
558///
559FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
560 assert(SLocOffset && "Invalid FileID");
Mike Stump1eb44332009-09-09 15:08:12 +0000561
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000562 // After the first and second level caches, I see two common sorts of
563 // behavior: 1) a lot of searched FileID's are "near" the cached file location
564 // or are "near" the cached instantiation location. 2) others are just
565 // completely random and may be a very long way away.
566 //
567 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
568 // then we fall back to a less cache efficient, but more scalable, binary
569 // search to find the location.
Mike Stump1eb44332009-09-09 15:08:12 +0000570
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000571 // See if this is near the file point - worst case we start scanning from the
572 // most newly created FileID.
573 std::vector<SrcMgr::SLocEntry>::const_iterator I;
Mike Stump1eb44332009-09-09 15:08:12 +0000574
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000575 if (SLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
576 // Neither loc prunes our search.
577 I = SLocEntryTable.end();
578 } else {
579 // Perhaps it is near the file point.
580 I = SLocEntryTable.begin()+LastFileIDLookup.ID;
581 }
582
583 // Find the FileID that contains this. "I" is an iterator that points to a
584 // FileID whose offset is known to be larger than SLocOffset.
585 unsigned NumProbes = 0;
586 while (1) {
587 --I;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000588 if (ExternalSLocEntries)
589 getSLocEntry(FileID::get(I - SLocEntryTable.begin()));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000590 if (I->getOffset() <= SLocOffset) {
591#if 0
592 printf("lin %d -> %d [%s] %d %d\n", SLocOffset,
593 I-SLocEntryTable.begin(),
594 I->isInstantiation() ? "inst" : "file",
595 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
596#endif
597 FileID Res = FileID::get(I-SLocEntryTable.begin());
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000598
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000599 // If this isn't an instantiation, remember it. We have good locality
600 // across FileID lookups.
601 if (!I->isInstantiation())
602 LastFileIDLookup = Res;
603 NumLinearScans += NumProbes+1;
604 return Res;
605 }
606 if (++NumProbes == 8)
607 break;
608 }
Mike Stump1eb44332009-09-09 15:08:12 +0000609
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000610 // Convert "I" back into an index. We know that it is an entry whose index is
611 // larger than the offset we are looking for.
612 unsigned GreaterIndex = I-SLocEntryTable.begin();
613 // LessIndex - This is the lower bound of the range that we're searching.
614 // We know that the offset corresponding to the FileID is is less than
615 // SLocOffset.
616 unsigned LessIndex = 0;
617 NumProbes = 0;
618 while (1) {
619 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000620 unsigned MidOffset = getSLocEntry(FileID::get(MiddleIndex)).getOffset();
Mike Stump1eb44332009-09-09 15:08:12 +0000621
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000622 ++NumProbes;
Mike Stump1eb44332009-09-09 15:08:12 +0000623
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000624 // If the offset of the midpoint is too large, chop the high side of the
625 // range to the midpoint.
626 if (MidOffset > SLocOffset) {
627 GreaterIndex = MiddleIndex;
628 continue;
629 }
Mike Stump1eb44332009-09-09 15:08:12 +0000630
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000631 // If the middle index contains the value, succeed and return.
632 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
633#if 0
634 printf("bin %d -> %d [%s] %d %d\n", SLocOffset,
635 I-SLocEntryTable.begin(),
636 I->isInstantiation() ? "inst" : "file",
637 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
638#endif
639 FileID Res = FileID::get(MiddleIndex);
640
641 // If this isn't an instantiation, remember it. We have good locality
642 // across FileID lookups.
643 if (!I->isInstantiation())
644 LastFileIDLookup = Res;
645 NumBinaryProbes += NumProbes;
646 return Res;
647 }
Mike Stump1eb44332009-09-09 15:08:12 +0000648
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000649 // Otherwise, move the low-side up to the middle index.
650 LessIndex = MiddleIndex;
651 }
652}
653
Chris Lattneraddb7972009-01-26 20:04:19 +0000654SourceLocation SourceManager::
655getInstantiationLocSlowCase(SourceLocation Loc) const {
656 do {
Chris Lattnera5c6c582010-02-12 19:31:35 +0000657 // Note: If Loc indicates an offset into a token that came from a macro
658 // expansion (e.g. the 5th character of the token) we do not want to add
659 // this offset when going to the instantiation location. The instatiation
660 // location is the macro invocation, which the offset has nothing to do
661 // with. This is unlike when we get the spelling loc, because the offset
662 // directly correspond to the token whose spelling we're inspecting.
663 Loc = getSLocEntry(getFileID(Loc)).getInstantiation()
Chris Lattnere7fb4842009-02-15 20:52:18 +0000664 .getInstantiationLocStart();
Chris Lattneraddb7972009-01-26 20:04:19 +0000665 } while (!Loc.isFileID());
666
667 return Loc;
668}
669
670SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
671 do {
672 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
673 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
674 Loc = Loc.getFileLocWithOffset(LocInfo.second);
675 } while (!Loc.isFileID());
676 return Loc;
677}
678
679
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000680std::pair<FileID, unsigned>
681SourceManager::getDecomposedInstantiationLocSlowCase(const SrcMgr::SLocEntry *E,
682 unsigned Offset) const {
683 // If this is an instantiation record, walk through all the instantiation
684 // points.
685 FileID FID;
686 SourceLocation Loc;
687 do {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000688 Loc = E->getInstantiation().getInstantiationLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000689
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000690 FID = getFileID(Loc);
691 E = &getSLocEntry(FID);
692 Offset += Loc.getOffset()-E->getOffset();
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000693 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000694
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000695 return std::make_pair(FID, Offset);
696}
697
698std::pair<FileID, unsigned>
699SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
700 unsigned Offset) const {
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000701 // If this is an instantiation record, walk through all the instantiation
702 // points.
703 FileID FID;
704 SourceLocation Loc;
705 do {
706 Loc = E->getInstantiation().getSpellingLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000707
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000708 FID = getFileID(Loc);
709 E = &getSLocEntry(FID);
710 Offset += Loc.getOffset()-E->getOffset();
711 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000712
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000713 return std::make_pair(FID, Offset);
714}
715
Chris Lattner387616e2009-02-17 08:04:48 +0000716/// getImmediateSpellingLoc - Given a SourceLocation object, return the
717/// spelling location referenced by the ID. This is the first level down
718/// towards the place where the characters that make up the lexed token can be
719/// found. This should not generally be used by clients.
720SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
721 if (Loc.isFileID()) return Loc;
722 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
723 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
724 return Loc.getFileLocWithOffset(LocInfo.second);
725}
726
727
Chris Lattnere7fb4842009-02-15 20:52:18 +0000728/// getImmediateInstantiationRange - Loc is required to be an instantiation
729/// location. Return the start/end of the instantiation information.
730std::pair<SourceLocation,SourceLocation>
731SourceManager::getImmediateInstantiationRange(SourceLocation Loc) const {
732 assert(Loc.isMacroID() && "Not an instantiation loc!");
733 const InstantiationInfo &II = getSLocEntry(getFileID(Loc)).getInstantiation();
734 return II.getInstantiationLocRange();
735}
736
Chris Lattner66781332009-02-15 21:26:50 +0000737/// getInstantiationRange - Given a SourceLocation object, return the
738/// range of tokens covered by the instantiation in the ultimate file.
739std::pair<SourceLocation,SourceLocation>
740SourceManager::getInstantiationRange(SourceLocation Loc) const {
741 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000742
Chris Lattner66781332009-02-15 21:26:50 +0000743 std::pair<SourceLocation,SourceLocation> Res =
744 getImmediateInstantiationRange(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000745
Chris Lattner66781332009-02-15 21:26:50 +0000746 // Fully resolve the start and end locations to their ultimate instantiation
747 // points.
748 while (!Res.first.isFileID())
749 Res.first = getImmediateInstantiationRange(Res.first).first;
750 while (!Res.second.isFileID())
751 Res.second = getImmediateInstantiationRange(Res.second).second;
752 return Res;
753}
754
Chris Lattnere7fb4842009-02-15 20:52:18 +0000755
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000756
757//===----------------------------------------------------------------------===//
758// Queries about the code at a SourceLocation.
759//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000760
761/// getCharacterData - Return a pointer to the start of the specified location
762/// in the appropriate MemoryBuffer.
763const char *SourceManager::getCharacterData(SourceLocation SL) const {
764 // Note that this is a hot function in the getSpelling() path, which is
765 // heavily used by -E mode.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000766 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump1eb44332009-09-09 15:08:12 +0000767
Ted Kremenekc16c2082009-01-06 01:55:26 +0000768 // Note that calling 'getBuffer()' may lazily page in a source file.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000769 return getSLocEntry(LocInfo.first).getFile().getContentCache()
770 ->getBuffer()->getBufferStart() + LocInfo.second;
Reid Spencer5f016e22007-07-11 17:01:13 +0000771}
772
Reid Spencer5f016e22007-07-11 17:01:13 +0000773
Chris Lattner9dc1f532007-07-20 16:37:10 +0000774/// getColumnNumber - Return the column # for the specified file position.
Chris Lattner7da5aea2009-02-04 00:55:58 +0000775/// this is significantly cheaper to compute than the line number.
776unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos) const {
777 const char *Buf = getBuffer(FID)->getBufferStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000778
Reid Spencer5f016e22007-07-11 17:01:13 +0000779 unsigned LineStart = FilePos;
780 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
781 --LineStart;
782 return FilePos-LineStart+1;
783}
784
Chris Lattner7da5aea2009-02-04 00:55:58 +0000785unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000786 if (Loc.isInvalid()) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000787 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
788 return getColumnNumber(LocInfo.first, LocInfo.second);
789}
790
791unsigned SourceManager::getInstantiationColumnNumber(SourceLocation Loc) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000792 if (Loc.isInvalid()) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000793 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
794 return getColumnNumber(LocInfo.first, LocInfo.second);
795}
796
797
798
Benjamin Kramerc997eb42009-11-14 16:36:57 +0000799static DISABLE_INLINE void ComputeLineNumbers(ContentCache* FI,
800 llvm::BumpPtrAllocator &Alloc);
Mike Stump1eb44332009-09-09 15:08:12 +0000801static void ComputeLineNumbers(ContentCache* FI, llvm::BumpPtrAllocator &Alloc){
Ted Kremenekc16c2082009-01-06 01:55:26 +0000802 // Note that calling 'getBuffer()' may lazily page in the file.
803 const MemoryBuffer *Buffer = FI->getBuffer();
Mike Stump1eb44332009-09-09 15:08:12 +0000804
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000805 // Find the file offsets of all of the *physical* source lines. This does
806 // not look at trigraphs, escaped newlines, or anything else tricky.
807 std::vector<unsigned> LineOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +0000808
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000809 // Line #1 starts at char 0.
810 LineOffsets.push_back(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000811
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000812 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
813 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
814 unsigned Offs = 0;
815 while (1) {
816 // Skip over the contents of the line.
817 // TODO: Vectorize this? This is very performance sensitive for programs
818 // with lots of diagnostics and in -E mode.
819 const unsigned char *NextBuf = (const unsigned char *)Buf;
820 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
821 ++NextBuf;
822 Offs += NextBuf-Buf;
823 Buf = NextBuf;
Mike Stump1eb44332009-09-09 15:08:12 +0000824
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000825 if (Buf[0] == '\n' || Buf[0] == '\r') {
826 // If this is \n\r or \r\n, skip both characters.
827 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
828 ++Offs, ++Buf;
829 ++Offs, ++Buf;
830 LineOffsets.push_back(Offs);
831 } else {
832 // Otherwise, this is a null. If end of file, exit.
833 if (Buf == End) break;
834 // Otherwise, skip the null.
835 ++Offs, ++Buf;
836 }
837 }
Mike Stump1eb44332009-09-09 15:08:12 +0000838
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000839 // Copy the offsets into the FileInfo structure.
840 FI->NumLines = LineOffsets.size();
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000841 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000842 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
843}
Reid Spencer5f016e22007-07-11 17:01:13 +0000844
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000845/// getLineNumber - Given a SourceLocation, return the spelling line number
Reid Spencer5f016e22007-07-11 17:01:13 +0000846/// for the position indicated. This requires building and caching a table of
847/// line offsets for the MemoryBuffer, so this is not cheap: use only when
848/// about to emit a diagnostic.
Chris Lattner30fc9332009-02-04 01:06:56 +0000849unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos) const {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000850 ContentCache *Content;
Chris Lattner30fc9332009-02-04 01:06:56 +0000851 if (LastLineNoFileIDQuery == FID)
Ted Kremenek78d85f52007-10-30 21:08:08 +0000852 Content = LastLineNoContentCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000853 else
Chris Lattner30fc9332009-02-04 01:06:56 +0000854 Content = const_cast<ContentCache*>(getSLocEntry(FID)
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000855 .getFile().getContentCache());
Mike Stump1eb44332009-09-09 15:08:12 +0000856
Reid Spencer5f016e22007-07-11 17:01:13 +0000857 // If this is the first use of line information for this buffer, compute the
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000858 /// SourceLineCache for it on demand.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000859 if (Content->SourceLineCache == 0)
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000860 ComputeLineNumbers(Content, ContentCacheAlloc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000861
862 // Okay, we know we have a line number table. Do a binary search to find the
863 // line number that this character position lands on.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000864 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000865 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenek78d85f52007-10-30 21:08:08 +0000866 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump1eb44332009-09-09 15:08:12 +0000867
Chris Lattner30fc9332009-02-04 01:06:56 +0000868 unsigned QueriedFilePos = FilePos+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000869
Daniel Dunbar4106d692009-05-18 17:30:52 +0000870 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump1eb44332009-09-09 15:08:12 +0000871 // complicated as it is, binary search isn't that slow.
Daniel Dunbar4106d692009-05-18 17:30:52 +0000872 //
873 // If it is worth being optimized, then in my opinion it could be more
874 // performant, simpler, and more obviously correct by just "galloping" outward
875 // from the queried file position. In fact, this could be incorporated into a
876 // generic algorithm such as lower_bound_with_hint.
877 //
878 // If someone gives me a test case where this matters, and I will do it! - DWD
879
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000880 // If the previous query was to the same file, we know both the file pos from
881 // that query and the line number returned. This allows us to narrow the
882 // search space from the entire file to something near the match.
Chris Lattner30fc9332009-02-04 01:06:56 +0000883 if (LastLineNoFileIDQuery == FID) {
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000884 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar4106d692009-05-18 17:30:52 +0000885 // FIXME: Potential overflow?
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000886 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump1eb44332009-09-09 15:08:12 +0000887
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000888 // The query is likely to be nearby the previous one. Here we check to
889 // see if it is within 5, 10 or 20 lines. It can be far away in cases
890 // where big comment blocks and vertical whitespace eat up lines but
891 // contribute no tokens.
892 if (SourceLineCache+5 < SourceLineCacheEnd) {
893 if (SourceLineCache[5] > QueriedFilePos)
894 SourceLineCacheEnd = SourceLineCache+5;
895 else if (SourceLineCache+10 < SourceLineCacheEnd) {
896 if (SourceLineCache[10] > QueriedFilePos)
897 SourceLineCacheEnd = SourceLineCache+10;
898 else if (SourceLineCache+20 < SourceLineCacheEnd) {
899 if (SourceLineCache[20] > QueriedFilePos)
900 SourceLineCacheEnd = SourceLineCache+20;
901 }
902 }
903 }
904 } else {
Daniel Dunbar4106d692009-05-18 17:30:52 +0000905 if (LastLineNoResult < Content->NumLines)
906 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000907 }
908 }
Mike Stump1eb44332009-09-09 15:08:12 +0000909
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000910 // If the spread is large, do a "radix" test as our initial guess, based on
911 // the assumption that lines average to approximately the same length.
912 // NOTE: This is currently disabled, as it does not appear to be profitable in
913 // initial measurements.
914 if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
Ted Kremenek78d85f52007-10-30 21:08:08 +0000915 unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
Mike Stump1eb44332009-09-09 15:08:12 +0000916
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000917 // Take a stab at guessing where it is.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000918 unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
Mike Stump1eb44332009-09-09 15:08:12 +0000919
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000920 // Check for -10 and +10 lines.
921 unsigned LowerBound = std::max(int(ApproxPos-10), 0);
922 unsigned UpperBound = std::min(ApproxPos+10, FileLen);
923
924 // If the computed lower bound is less than the query location, move it in.
925 if (SourceLineCache < SourceLineCacheStart+LowerBound &&
926 SourceLineCacheStart[LowerBound] < QueriedFilePos)
927 SourceLineCache = SourceLineCacheStart+LowerBound;
Mike Stump1eb44332009-09-09 15:08:12 +0000928
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000929 // If the computed upper bound is greater than the query location, move it.
930 if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
931 SourceLineCacheStart[UpperBound] >= QueriedFilePos)
932 SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
933 }
Mike Stump1eb44332009-09-09 15:08:12 +0000934
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000935 unsigned *Pos
936 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000937 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump1eb44332009-09-09 15:08:12 +0000938
Chris Lattner30fc9332009-02-04 01:06:56 +0000939 LastLineNoFileIDQuery = FID;
Ted Kremenek78d85f52007-10-30 21:08:08 +0000940 LastLineNoContentCache = Content;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000941 LastLineNoFilePos = QueriedFilePos;
942 LastLineNoResult = LineNo;
943 return LineNo;
Reid Spencer5f016e22007-07-11 17:01:13 +0000944}
945
Chris Lattner30fc9332009-02-04 01:06:56 +0000946unsigned SourceManager::getInstantiationLineNumber(SourceLocation Loc) const {
947 if (Loc.isInvalid()) return 0;
948 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
949 return getLineNumber(LocInfo.first, LocInfo.second);
950}
951unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc) const {
952 if (Loc.isInvalid()) return 0;
953 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
954 return getLineNumber(LocInfo.first, LocInfo.second);
955}
956
Chris Lattner6b306672009-02-04 05:33:01 +0000957/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump1eb44332009-09-09 15:08:12 +0000958/// source location, indicating whether this is a normal file, a system
Chris Lattner6b306672009-02-04 05:33:01 +0000959/// header, or an "implicit extern C" system header.
960///
961/// This state can be modified with flags on GNU linemarker directives like:
962/// # 4 "foo.h" 3
963/// which changes all source locations in the current file after that to be
964/// considered to be from a system header.
Mike Stump1eb44332009-09-09 15:08:12 +0000965SrcMgr::CharacteristicKind
Chris Lattner6b306672009-02-04 05:33:01 +0000966SourceManager::getFileCharacteristic(SourceLocation Loc) const {
967 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
968 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
969 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
970
971 // If there are no #line directives in this file, just return the whole-file
972 // state.
973 if (!FI.hasLineDirectives())
974 return FI.getFileCharacteristic();
Mike Stump1eb44332009-09-09 15:08:12 +0000975
Chris Lattner6b306672009-02-04 05:33:01 +0000976 assert(LineTable && "Can't have linetable entries without a LineTable!");
977 // See if there is a #line directive before the location.
978 const LineEntry *Entry =
979 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second);
Mike Stump1eb44332009-09-09 15:08:12 +0000980
Chris Lattner6b306672009-02-04 05:33:01 +0000981 // If this is before the first line marker, use the file characteristic.
982 if (!Entry)
983 return FI.getFileCharacteristic();
984
985 return Entry->FileKind;
986}
987
Chris Lattnerbff5c512009-02-17 08:39:06 +0000988/// Return the filename or buffer identifier of the buffer the location is in.
989/// Note that this name does not respect #line directives. Use getPresumedLoc
990/// for normal clients.
991const char *SourceManager::getBufferName(SourceLocation Loc) const {
992 if (Loc.isInvalid()) return "<invalid loc>";
Mike Stump1eb44332009-09-09 15:08:12 +0000993
Chris Lattnerbff5c512009-02-17 08:39:06 +0000994 return getBuffer(getFileID(Loc))->getBufferIdentifier();
995}
996
Chris Lattner30fc9332009-02-04 01:06:56 +0000997
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000998/// getPresumedLoc - This method returns the "presumed" location of a
999/// SourceLocation specifies. A "presumed location" can be modified by #line
1000/// or GNU line marker directives. This provides a view on the data that a
1001/// user should see in diagnostics, for example.
1002///
1003/// Note that a presumed location is always given as the instantiation point
1004/// of an instantiation location, not at the spelling location.
1005PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
1006 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001007
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001008 // Presumed locations are always for instantiation points.
Chris Lattner7da5aea2009-02-04 00:55:58 +00001009 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +00001010
Chris Lattner30fc9332009-02-04 01:06:56 +00001011 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001012 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump1eb44332009-09-09 15:08:12 +00001013
Chris Lattner3cd949c2009-02-04 01:55:42 +00001014 // To get the source name, first consult the FileEntry (if one exists)
1015 // before the MemBuffer as this will avoid unnecessarily paging in the
1016 // MemBuffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001017 const char *Filename =
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001018 C->Entry ? C->Entry->getName() : C->getBuffer()->getBufferIdentifier();
Chris Lattner3cd949c2009-02-04 01:55:42 +00001019 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second);
1020 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second);
1021 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001022
Chris Lattner3cd949c2009-02-04 01:55:42 +00001023 // If we have #line directives in this file, update and overwrite the physical
1024 // location info if appropriate.
1025 if (FI.hasLineDirectives()) {
1026 assert(LineTable && "Can't have linetable entries without a LineTable!");
1027 // See if there is a #line directive before this. If so, get it.
1028 if (const LineEntry *Entry =
1029 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) {
Chris Lattnerfc391332009-02-04 02:00:59 +00001030 // If the LineEntry indicates a filename, use it.
Chris Lattner3cd949c2009-02-04 01:55:42 +00001031 if (Entry->FilenameID != -1)
1032 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerfc391332009-02-04 02:00:59 +00001033
1034 // Use the line number specified by the LineEntry. This line number may
1035 // be multiple lines down from the line entry. Add the difference in
1036 // physical line numbers from the query point and the line marker to the
1037 // total.
1038 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1039 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001040
Chris Lattner0e0e5da2009-02-04 02:15:40 +00001041 // Note that column numbers are not molested by line markers.
Mike Stump1eb44332009-09-09 15:08:12 +00001042
Chris Lattner137b6a62009-02-04 06:25:26 +00001043 // Handle virtual #include manipulation.
1044 if (Entry->IncludeOffset) {
1045 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1046 IncludeLoc = IncludeLoc.getFileLocWithOffset(Entry->IncludeOffset);
1047 }
Chris Lattner3cd949c2009-02-04 01:55:42 +00001048 }
1049 }
1050
1051 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001052}
1053
1054//===----------------------------------------------------------------------===//
1055// Other miscellaneous methods.
1056//===----------------------------------------------------------------------===//
1057
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001058/// \brief Get the source location for the given file:line:col triplet.
1059///
1060/// If the source file is included multiple times, the source location will
1061/// be based upon the first inclusion.
1062SourceLocation SourceManager::getLocation(const FileEntry *SourceFile,
1063 unsigned Line, unsigned Col) const {
1064 assert(SourceFile && "Null source file!");
1065 assert(Line && Col && "Line and column should start from 1!");
1066
1067 fileinfo_iterator FI = FileInfos.find(SourceFile);
1068 if (FI == FileInfos.end())
1069 return SourceLocation();
1070 ContentCache *Content = FI->second;
Mike Stump1eb44332009-09-09 15:08:12 +00001071
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001072 // If this is the first use of line information for this buffer, compute the
1073 /// SourceLineCache for it on demand.
1074 if (Content->SourceLineCache == 0)
1075 ComputeLineNumbers(Content, ContentCacheAlloc);
1076
Douglas Gregor4a160e12009-12-02 05:34:39 +00001077 // Find the first file ID that corresponds to the given file.
1078 FileID FirstFID;
1079
1080 // First, check the main file ID, since it is common to look for a
1081 // location in the main file.
1082 if (!MainFileID.isInvalid()) {
1083 const SLocEntry &MainSLoc = getSLocEntry(MainFileID);
1084 if (MainSLoc.isFile() && MainSLoc.getFile().getContentCache() == Content)
1085 FirstFID = MainFileID;
1086 }
1087
1088 if (FirstFID.isInvalid()) {
1089 // The location we're looking for isn't in the main file; look
1090 // through all of the source locations.
1091 for (unsigned I = 0, N = sloc_entry_size(); I != N; ++I) {
1092 const SLocEntry &SLoc = getSLocEntry(I);
1093 if (SLoc.isFile() && SLoc.getFile().getContentCache() == Content) {
1094 FirstFID = FileID::get(I);
1095 break;
1096 }
1097 }
1098 }
1099
1100 if (FirstFID.isInvalid())
1101 return SourceLocation();
1102
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001103 if (Line > Content->NumLines) {
1104 unsigned Size = Content->getBuffer()->getBufferSize();
1105 if (Size > 0)
1106 --Size;
1107 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(Size);
1108 }
1109
1110 unsigned FilePos = Content->SourceLineCache[Line - 1];
1111 const char *Buf = Content->getBuffer()->getBufferStart() + FilePos;
1112 unsigned BufLength = Content->getBuffer()->getBufferEnd() - Buf;
1113 unsigned i = 0;
1114
1115 // Check that the given column is valid.
1116 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1117 ++i;
1118 if (i < Col-1)
1119 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + i);
1120
Douglas Gregor4a160e12009-12-02 05:34:39 +00001121 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + Col - 1);
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001122}
1123
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001124/// \brief Determines the order of 2 source locations in the translation unit.
1125///
1126/// \returns true if LHS source location comes before RHS, false otherwise.
1127bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1128 SourceLocation RHS) const {
1129 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1130 if (LHS == RHS)
1131 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001132
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001133 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1134 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00001135
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001136 // If the source locations are in the same file, just compare offsets.
1137 if (LOffs.first == ROffs.first)
1138 return LOffs.second < ROffs.second;
1139
1140 // If we are comparing a source location with multiple locations in the same
1141 // file, we get a big win by caching the result.
Mike Stump1eb44332009-09-09 15:08:12 +00001142
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001143 if (LastLFIDForBeforeTUCheck == LOffs.first &&
1144 LastRFIDForBeforeTUCheck == ROffs.first)
1145 return LastResForBeforeTUCheck;
Mike Stump1eb44332009-09-09 15:08:12 +00001146
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001147 LastLFIDForBeforeTUCheck = LOffs.first;
1148 LastRFIDForBeforeTUCheck = ROffs.first;
Mike Stump1eb44332009-09-09 15:08:12 +00001149
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001150 // "Traverse" the include/instantiation stacks of both locations and try to
1151 // find a common "ancestor".
1152 //
1153 // First we traverse the stack of the right location and check each level
1154 // against the level of the left location, while collecting all levels in a
1155 // "stack map".
1156
1157 std::map<FileID, unsigned> ROffsMap;
1158 ROffsMap[ROffs.first] = ROffs.second;
1159
1160 while (1) {
1161 SourceLocation UpperLoc;
1162 const SrcMgr::SLocEntry &Entry = getSLocEntry(ROffs.first);
1163 if (Entry.isInstantiation())
1164 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1165 else
1166 UpperLoc = Entry.getFile().getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001167
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001168 if (UpperLoc.isInvalid())
1169 break; // We reached the top.
Mike Stump1eb44332009-09-09 15:08:12 +00001170
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001171 ROffs = getDecomposedLoc(UpperLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001172
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001173 if (LOffs.first == ROffs.first)
1174 return LastResForBeforeTUCheck = LOffs.second < ROffs.second;
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001176 ROffsMap[ROffs.first] = ROffs.second;
1177 }
1178
1179 // We didn't find a common ancestor. Now traverse the stack of the left
1180 // location, checking against the stack map of the right location.
1181
1182 while (1) {
1183 SourceLocation UpperLoc;
1184 const SrcMgr::SLocEntry &Entry = getSLocEntry(LOffs.first);
1185 if (Entry.isInstantiation())
1186 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1187 else
1188 UpperLoc = Entry.getFile().getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001189
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001190 if (UpperLoc.isInvalid())
1191 break; // We reached the top.
Mike Stump1eb44332009-09-09 15:08:12 +00001192
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001193 LOffs = getDecomposedLoc(UpperLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001194
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001195 std::map<FileID, unsigned>::iterator I = ROffsMap.find(LOffs.first);
1196 if (I != ROffsMap.end())
1197 return LastResForBeforeTUCheck = LOffs.second < I->second;
1198 }
Mike Stump1eb44332009-09-09 15:08:12 +00001199
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001200 // There is no common ancestor, most probably because one location is in the
1201 // predefines buffer.
1202 //
1203 // FIXME: We should rearrange the external interface so this simply never
1204 // happens; it can't conceptually happen. Also see PR5662.
Mike Stump1eb44332009-09-09 15:08:12 +00001205
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001206 // If exactly one location is a memory buffer, assume it preceeds the other.
1207 bool LIsMB = !getSLocEntry(LOffs.first).getFile().getContentCache()->Entry;
1208 bool RIsMB = !getSLocEntry(ROffs.first).getFile().getContentCache()->Entry;
1209 if (LIsMB != RIsMB)
1210 return LastResForBeforeTUCheck = LIsMB;
Mike Stump1eb44332009-09-09 15:08:12 +00001211
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001212 // Otherwise, just assume FileIDs were created in order.
1213 return LastResForBeforeTUCheck = (LOffs.first < ROffs.first);
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001214}
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001215
Reid Spencer5f016e22007-07-11 17:01:13 +00001216/// PrintStats - Print statistics to stderr.
1217///
1218void SourceManager::PrintStats() const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001219 llvm::errs() << "\n*** Source Manager Stats:\n";
1220 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
1221 << " mem buffers mapped.\n";
1222 llvm::errs() << SLocEntryTable.size() << " SLocEntry's allocated, "
1223 << NextOffset << "B of Sloc address space used.\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001224
Reid Spencer5f016e22007-07-11 17:01:13 +00001225 unsigned NumLineNumsComputed = 0;
1226 unsigned NumFileBytesMapped = 0;
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00001227 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
1228 NumLineNumsComputed += I->second->SourceLineCache != 0;
1229 NumFileBytesMapped += I->second->getSizeBytesMapped();
Reid Spencer5f016e22007-07-11 17:01:13 +00001230 }
Mike Stump1eb44332009-09-09 15:08:12 +00001231
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001232 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
1233 << NumLineNumsComputed << " files with line #'s computed.\n";
1234 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
1235 << NumBinaryProbes << " binary.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +00001236}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001237
1238ExternalSLocEntrySource::~ExternalSLocEntrySource() { }