blob: fcca97774df1dbc1bf36a117504018955de688cd [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SourceManager.cpp - Track and cache source files -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the SourceManager interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Basic/SourceManager.h"
15#include "clang/Basic/FileManager.h"
16#include "llvm/Support/Compiler.h"
17#include "llvm/Support/MemoryBuffer.h"
18#include "llvm/System/Path.h"
Ted Kremenekdd364ea2007-10-30 21:08:08 +000019#include "llvm/Bitcode/Serialize.h"
20#include "llvm/Bitcode/Deserialize.h"
Ted Kremenekda29d8c2007-12-05 22:21:13 +000021#include "llvm/Support/Streams.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include <algorithm>
Chris Lattner4b009652007-07-25 00:24:17 +000023using namespace clang;
24using namespace SrcMgr;
25using llvm::MemoryBuffer;
26
Chris Lattner27c0ced2009-01-26 00:43:02 +000027//===--------------------------------------------------------------------===//
28// SourceManager Helper Classes
29//===--------------------------------------------------------------------===//
30
Ted Kremenekdd364ea2007-10-30 21:08:08 +000031ContentCache::~ContentCache() {
32 delete Buffer;
33 delete [] SourceLineCache;
Chris Lattner4b009652007-07-25 00:24:17 +000034}
35
Ted Kremenekaa7dac12009-01-06 01:55:26 +000036/// getSizeBytesMapped - Returns the number of bytes actually mapped for
37/// this ContentCache. This can be 0 if the MemBuffer was not actually
38/// instantiated.
39unsigned ContentCache::getSizeBytesMapped() const {
40 return Buffer ? Buffer->getBufferSize() : 0;
41}
42
43/// getSize - Returns the size of the content encapsulated by this ContentCache.
44/// This can be the size of the source file or the size of an arbitrary
45/// scratch buffer. If the ContentCache encapsulates a source file, that
46/// file is not lazily brought in from disk to satisfy this query.
47unsigned ContentCache::getSize() const {
48 return Entry ? Entry->getSize() : Buffer->getBufferSize();
49}
50
Chris Lattner68b28ff2009-01-26 07:37:49 +000051const llvm::MemoryBuffer *ContentCache::getBuffer() const {
Ted Kremenek2bb9e6c2009-01-06 22:43:04 +000052 // Lazily create the Buffer for ContentCaches that wrap files.
53 if (!Buffer && Entry) {
54 // FIXME: Should we support a way to not have to do this check over
55 // and over if we cannot open the file?
Chris Lattnerac49bb42009-01-17 03:54:16 +000056 Buffer = MemoryBuffer::getFile(Entry->getName(), 0, Entry->getSize());
Ted Kremenek2bb9e6c2009-01-06 22:43:04 +000057 }
Ted Kremenekaa7dac12009-01-06 01:55:26 +000058 return Buffer;
59}
60
Chris Lattner27c0ced2009-01-26 00:43:02 +000061//===--------------------------------------------------------------------===//
62// Private 'Create' methods.
63//===--------------------------------------------------------------------===//
Ted Kremenekaa7dac12009-01-06 01:55:26 +000064
Chris Lattner27c0ced2009-01-26 00:43:02 +000065/// getOrCreateContentCache - Create or return a cached ContentCache for the
66/// specified file.
67const ContentCache *
68SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) {
Chris Lattner4b009652007-07-25 00:24:17 +000069 assert(FileEnt && "Didn't specify a file entry to use?");
Chris Lattner27c0ced2009-01-26 00:43:02 +000070
Chris Lattner4b009652007-07-25 00:24:17 +000071 // Do we already have information about this file?
Ted Kremenekdd364ea2007-10-30 21:08:08 +000072 std::set<ContentCache>::iterator I =
73 FileInfos.lower_bound(ContentCache(FileEnt));
74
75 if (I != FileInfos.end() && I->Entry == FileEnt)
Chris Lattner4b009652007-07-25 00:24:17 +000076 return &*I;
77
Chris Lattner68b28ff2009-01-26 07:37:49 +000078 // Nope, create a new Cache entry.
Ted Kremenekdd364ea2007-10-30 21:08:08 +000079 ContentCache& Entry = const_cast<ContentCache&>(*FileInfos.insert(I,FileEnt));
Ted Kremenekdd364ea2007-10-30 21:08:08 +000080 Entry.SourceLineCache = 0;
81 Entry.NumLines = 0;
Chris Lattner4b009652007-07-25 00:24:17 +000082 return &Entry;
83}
84
85
Ted Kremenek27f9c9b2007-10-31 17:53:38 +000086/// createMemBufferContentCache - Create a new ContentCache for the specified
87/// memory buffer. This does no caching.
Ted Kremenekdd364ea2007-10-30 21:08:08 +000088const ContentCache*
89SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
Ted Kremenek7670cca2007-10-30 22:57:35 +000090 // Add a new ContentCache to the MemBufferInfos list and return it. We
91 // must default construct the object first that the instance actually
92 // stored within MemBufferInfos actually owns the Buffer, and not any
93 // temporary we would use in the call to "push_back".
Ted Kremenekdd364ea2007-10-30 21:08:08 +000094 MemBufferInfos.push_back(ContentCache());
95 ContentCache& Entry = const_cast<ContentCache&>(MemBufferInfos.back());
Ted Kremenekaa7dac12009-01-06 01:55:26 +000096 Entry.setBuffer(Buffer);
Ted Kremenekdd364ea2007-10-30 21:08:08 +000097 return &Entry;
Chris Lattner4b009652007-07-25 00:24:17 +000098}
99
Chris Lattner27c0ced2009-01-26 00:43:02 +0000100//===----------------------------------------------------------------------===//
101// Methods to create new FileID's and instantiations.
102//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000103
Nico Weber630347d2008-09-29 00:25:48 +0000104/// createFileID - Create a new fileID for the specified ContentCache and
Ted Kremenek7670cca2007-10-30 22:57:35 +0000105/// include position. This works regardless of whether the ContentCache
106/// corresponds to a file or some other input source.
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000107FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattner27c0ced2009-01-26 00:43:02 +0000108 SourceLocation IncludePos,
109 SrcMgr::CharacteristicKind FileCharacter) {
110 SLocEntryTable.push_back(SLocEntry::get(NextOffset,
111 FileInfo::get(IncludePos, File,
112 FileCharacter)));
Ted Kremenekaa7dac12009-01-06 01:55:26 +0000113 unsigned FileSize = File->getSize();
Chris Lattner27c0ced2009-01-26 00:43:02 +0000114 assert(NextOffset+FileSize+1 > NextOffset && "Ran out of source locations!");
115 NextOffset += FileSize+1;
Chris Lattner4b009652007-07-25 00:24:17 +0000116
Chris Lattner27c0ced2009-01-26 00:43:02 +0000117 // Set LastFileIDLookup to the newly created file. The next getFileID call is
118 // almost guaranteed to be from that file.
119 return LastFileIDLookup = FileID::get(SLocEntryTable.size()-1);
Chris Lattner4b009652007-07-25 00:24:17 +0000120}
121
Chris Lattner27c0ced2009-01-26 00:43:02 +0000122/// createInstantiationLoc - Return a new SourceLocation that encodes the fact
Chris Lattnercdf600e2009-01-16 07:00:02 +0000123/// that a token from SpellingLoc should actually be referenced from
Chris Lattner4b009652007-07-25 00:24:17 +0000124/// InstantiationLoc.
Chris Lattner27c0ced2009-01-26 00:43:02 +0000125SourceLocation SourceManager::createInstantiationLoc(SourceLocation SpellingLoc,
126 SourceLocation InstantLoc,
127 unsigned TokLength) {
Chris Lattner4b009652007-07-25 00:24:17 +0000128 // The specified source location may be a mapped location, due to a macro
129 // instantiation or #line directive. Strip off this information to find out
130 // where the characters are actually located.
Chris Lattnercdf600e2009-01-16 07:00:02 +0000131 SpellingLoc = getSpellingLoc(SpellingLoc);
Chris Lattner4b009652007-07-25 00:24:17 +0000132
Chris Lattner18c8dc02009-01-16 07:36:28 +0000133 // Resolve InstantLoc down to a real instantiation location.
134 InstantLoc = getInstantiationLoc(InstantLoc);
Chris Lattner27c0ced2009-01-26 00:43:02 +0000135
136 SLocEntryTable.push_back(SLocEntry::get(NextOffset,
137 InstantiationInfo::get(InstantLoc,
138 SpellingLoc)));
139 assert(NextOffset+TokLength+1 > NextOffset && "Ran out of source locations!");
140 NextOffset += TokLength+1;
141 return SourceLocation::getMacroLoc(NextOffset-(TokLength+1));
Chris Lattner4b009652007-07-25 00:24:17 +0000142}
143
Chris Lattner71e443a2009-01-19 07:32:13 +0000144/// getBufferData - Return a pointer to the start and end of the source buffer
145/// data for the specified FileID.
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000146std::pair<const char*, const char*>
147SourceManager::getBufferData(FileID FID) const {
148 const llvm::MemoryBuffer *Buf = getBuffer(FID);
149 return std::make_pair(Buf->getBufferStart(), Buf->getBufferEnd());
150}
151
152
Chris Lattner27c0ced2009-01-26 00:43:02 +0000153//===--------------------------------------------------------------------===//
154// SourceLocation manipulation methods.
155//===--------------------------------------------------------------------===//
156
157/// getFileIDSlow - Return the FileID for a SourceLocation. This is a very hot
158/// method that is used for all SourceManager queries that start with a
159/// SourceLocation object. It is responsible for finding the entry in
160/// SLocEntryTable which contains the specified location.
161///
162FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
163 assert(SLocOffset && "Invalid FileID");
164
165 // After the first and second level caches, I see two common sorts of
166 // behavior: 1) a lot of searched FileID's are "near" the cached file location
167 // or are "near" the cached instantiation location. 2) others are just
168 // completely random and may be a very long way away.
169 //
170 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
171 // then we fall back to a less cache efficient, but more scalable, binary
172 // search to find the location.
173
174 // See if this is near the file point - worst case we start scanning from the
175 // most newly created FileID.
176 std::vector<SrcMgr::SLocEntry>::const_iterator I;
177
178 if (SLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
179 // Neither loc prunes our search.
180 I = SLocEntryTable.end();
181 } else {
182 // Perhaps it is near the file point.
183 I = SLocEntryTable.begin()+LastFileIDLookup.ID;
184 }
185
186 // Find the FileID that contains this. "I" is an iterator that points to a
187 // FileID whose offset is known to be larger than SLocOffset.
188 unsigned NumProbes = 0;
189 while (1) {
190 --I;
191 if (I->getOffset() <= SLocOffset) {
192#if 0
193 printf("lin %d -> %d [%s] %d %d\n", SLocOffset,
194 I-SLocEntryTable.begin(),
195 I->isInstantiation() ? "inst" : "file",
196 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
197#endif
198 FileID Res = FileID::get(I-SLocEntryTable.begin());
199
200 // If this isn't an instantiation, remember it. We have good locality
201 // across FileID lookups.
202 if (!I->isInstantiation())
203 LastFileIDLookup = Res;
204 NumLinearScans += NumProbes+1;
205 return Res;
206 }
207 if (++NumProbes == 8)
208 break;
209 }
210
211 // Convert "I" back into an index. We know that it is an entry whose index is
212 // larger than the offset we are looking for.
213 unsigned GreaterIndex = I-SLocEntryTable.begin();
214 // LessIndex - This is the lower bound of the range that we're searching.
215 // We know that the offset corresponding to the FileID is is less than
216 // SLocOffset.
217 unsigned LessIndex = 0;
218 NumProbes = 0;
219 while (1) {
220 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
221 unsigned MidOffset = SLocEntryTable[MiddleIndex].getOffset();
222
223 ++NumProbes;
224
225 // If the offset of the midpoint is too large, chop the high side of the
226 // range to the midpoint.
227 if (MidOffset > SLocOffset) {
228 GreaterIndex = MiddleIndex;
229 continue;
230 }
231
232 // If the middle index contains the value, succeed and return.
233 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
234#if 0
235 printf("bin %d -> %d [%s] %d %d\n", SLocOffset,
236 I-SLocEntryTable.begin(),
237 I->isInstantiation() ? "inst" : "file",
238 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
239#endif
240 FileID Res = FileID::get(MiddleIndex);
241
242 // If this isn't an instantiation, remember it. We have good locality
243 // across FileID lookups.
244 if (!I->isInstantiation())
245 LastFileIDLookup = Res;
246 NumBinaryProbes += NumProbes;
247 return Res;
248 }
249
250 // Otherwise, move the low-side up to the middle index.
251 LessIndex = MiddleIndex;
252 }
253}
254
255std::pair<FileID, unsigned>
256SourceManager::getDecomposedInstantiationLocSlowCase(const SrcMgr::SLocEntry *E,
257 unsigned Offset) const {
258 // If this is an instantiation record, walk through all the instantiation
259 // points.
260 FileID FID;
261 SourceLocation Loc;
262 do {
263 Loc = E->getInstantiation().getInstantiationLoc();
264
265 FID = getFileID(Loc);
266 E = &getSLocEntry(FID);
267 Offset += Loc.getOffset()-E->getOffset();
268 } while (Loc.isFileID());
269
270 return std::make_pair(FID, Offset);
271}
272
273std::pair<FileID, unsigned>
274SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
275 unsigned Offset) const {
276 // If this is an instantiation record, get and return the spelling.
277 SourceLocation Loc = E->getInstantiation().getSpellingLoc();
278 FileID FID = getFileID(Loc);
279 E = &getSLocEntry(FID);
280 Offset += Loc.getOffset()-E->getOffset();
281 assert(Loc.isFileID() && "Should only have one spelling link");
282 return std::make_pair(FID, Offset);
283}
284
285
286//===----------------------------------------------------------------------===//
287// Queries about the code at a SourceLocation.
288//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000289
290/// getCharacterData - Return a pointer to the start of the specified location
291/// in the appropriate MemoryBuffer.
292const char *SourceManager::getCharacterData(SourceLocation SL) const {
293 // Note that this is a hot function in the getSpelling() path, which is
294 // heavily used by -E mode.
Chris Lattner27c0ced2009-01-26 00:43:02 +0000295 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000296
Ted Kremenekaa7dac12009-01-06 01:55:26 +0000297 // Note that calling 'getBuffer()' may lazily page in a source file.
Chris Lattner27c0ced2009-01-26 00:43:02 +0000298 return getSLocEntry(LocInfo.first).getFile().getContentCache()
299 ->getBuffer()->getBufferStart() + LocInfo.second;
Chris Lattner4b009652007-07-25 00:24:17 +0000300}
301
302
303/// getColumnNumber - Return the column # for the specified file position.
304/// this is significantly cheaper to compute than the line number. This returns
305/// zero if the column number isn't known.
306unsigned SourceManager::getColumnNumber(SourceLocation Loc) const {
Chris Lattner27c0ced2009-01-26 00:43:02 +0000307 if (Loc.isInvalid()) return 0;
308 assert(Loc.isFileID() && "Don't know what part of instantiation loc to get");
Chris Lattner4b009652007-07-25 00:24:17 +0000309
Chris Lattner27c0ced2009-01-26 00:43:02 +0000310 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000311 unsigned FilePos = LocInfo.second;
312
313 const char *Buf = getBuffer(LocInfo.first)->getBufferStart();
Chris Lattner4b009652007-07-25 00:24:17 +0000314
315 unsigned LineStart = FilePos;
316 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
317 --LineStart;
318 return FilePos-LineStart+1;
319}
320
Ted Kremenekdd364ea2007-10-30 21:08:08 +0000321static void ComputeLineNumbers(ContentCache* FI) DISABLE_INLINE;
Ted Kremenekaa7dac12009-01-06 01:55:26 +0000322static void ComputeLineNumbers(ContentCache* FI) {
323 // Note that calling 'getBuffer()' may lazily page in the file.
324 const MemoryBuffer *Buffer = FI->getBuffer();
Chris Lattner4b009652007-07-25 00:24:17 +0000325
326 // Find the file offsets of all of the *physical* source lines. This does
327 // not look at trigraphs, escaped newlines, or anything else tricky.
328 std::vector<unsigned> LineOffsets;
329
330 // Line #1 starts at char 0.
331 LineOffsets.push_back(0);
332
333 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
334 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
335 unsigned Offs = 0;
336 while (1) {
337 // Skip over the contents of the line.
338 // TODO: Vectorize this? This is very performance sensitive for programs
339 // with lots of diagnostics and in -E mode.
340 const unsigned char *NextBuf = (const unsigned char *)Buf;
341 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
342 ++NextBuf;
343 Offs += NextBuf-Buf;
344 Buf = NextBuf;
345
346 if (Buf[0] == '\n' || Buf[0] == '\r') {
347 // If this is \n\r or \r\n, skip both characters.
348 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
349 ++Offs, ++Buf;
350 ++Offs, ++Buf;
351 LineOffsets.push_back(Offs);
352 } else {
353 // Otherwise, this is a null. If end of file, exit.
354 if (Buf == End) break;
355 // Otherwise, skip the null.
356 ++Offs, ++Buf;
357 }
358 }
Chris Lattner4b009652007-07-25 00:24:17 +0000359
360 // Copy the offsets into the FileInfo structure.
361 FI->NumLines = LineOffsets.size();
362 FI->SourceLineCache = new unsigned[LineOffsets.size()];
363 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
364}
365
Chris Lattnercdf600e2009-01-16 07:00:02 +0000366/// getLineNumber - Given a SourceLocation, return the spelling line number
Chris Lattner4b009652007-07-25 00:24:17 +0000367/// for the position indicated. This requires building and caching a table of
368/// line offsets for the MemoryBuffer, so this is not cheap: use only when
369/// about to emit a diagnostic.
Chris Lattnere9bf3e32008-11-18 06:51:15 +0000370unsigned SourceManager::getLineNumber(SourceLocation Loc) const {
Chris Lattner27c0ced2009-01-26 00:43:02 +0000371 if (Loc.isInvalid()) return 0;
372 assert(Loc.isFileID() && "Don't know what part of instantiation loc to get");
Ted Kremenekdd364ea2007-10-30 21:08:08 +0000373
Chris Lattner27c0ced2009-01-26 00:43:02 +0000374 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
375
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000376 ContentCache *Content;
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000377 if (LastLineNoFileIDQuery == LocInfo.first)
Ted Kremenekdd364ea2007-10-30 21:08:08 +0000378 Content = LastLineNoContentCache;
Chris Lattner4b009652007-07-25 00:24:17 +0000379 else
Chris Lattner27c0ced2009-01-26 00:43:02 +0000380 Content = const_cast<ContentCache*>(getSLocEntry(LocInfo.first)
381 .getFile().getContentCache());
Chris Lattner4b009652007-07-25 00:24:17 +0000382
383 // If this is the first use of line information for this buffer, compute the
384 /// SourceLineCache for it on demand.
Ted Kremenekdd364ea2007-10-30 21:08:08 +0000385 if (Content->SourceLineCache == 0)
386 ComputeLineNumbers(Content);
Chris Lattner4b009652007-07-25 00:24:17 +0000387
388 // Okay, we know we have a line number table. Do a binary search to find the
389 // line number that this character position lands on.
Ted Kremenekdd364ea2007-10-30 21:08:08 +0000390 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner4b009652007-07-25 00:24:17 +0000391 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenekdd364ea2007-10-30 21:08:08 +0000392 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Chris Lattner4b009652007-07-25 00:24:17 +0000393
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000394 unsigned QueriedFilePos = LocInfo.second+1;
Chris Lattner4b009652007-07-25 00:24:17 +0000395
396 // If the previous query was to the same file, we know both the file pos from
397 // that query and the line number returned. This allows us to narrow the
398 // search space from the entire file to something near the match.
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000399 if (LastLineNoFileIDQuery == LocInfo.first) {
Chris Lattner4b009652007-07-25 00:24:17 +0000400 if (QueriedFilePos >= LastLineNoFilePos) {
401 SourceLineCache = SourceLineCache+LastLineNoResult-1;
402
403 // The query is likely to be nearby the previous one. Here we check to
404 // see if it is within 5, 10 or 20 lines. It can be far away in cases
405 // where big comment blocks and vertical whitespace eat up lines but
406 // contribute no tokens.
407 if (SourceLineCache+5 < SourceLineCacheEnd) {
408 if (SourceLineCache[5] > QueriedFilePos)
409 SourceLineCacheEnd = SourceLineCache+5;
410 else if (SourceLineCache+10 < SourceLineCacheEnd) {
411 if (SourceLineCache[10] > QueriedFilePos)
412 SourceLineCacheEnd = SourceLineCache+10;
413 else if (SourceLineCache+20 < SourceLineCacheEnd) {
414 if (SourceLineCache[20] > QueriedFilePos)
415 SourceLineCacheEnd = SourceLineCache+20;
416 }
417 }
418 }
419 } else {
420 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
421 }
422 }
423
424 // If the spread is large, do a "radix" test as our initial guess, based on
425 // the assumption that lines average to approximately the same length.
426 // NOTE: This is currently disabled, as it does not appear to be profitable in
427 // initial measurements.
428 if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
Ted Kremenekdd364ea2007-10-30 21:08:08 +0000429 unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
Chris Lattner4b009652007-07-25 00:24:17 +0000430
431 // Take a stab at guessing where it is.
Ted Kremenekdd364ea2007-10-30 21:08:08 +0000432 unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
Chris Lattner4b009652007-07-25 00:24:17 +0000433
434 // Check for -10 and +10 lines.
435 unsigned LowerBound = std::max(int(ApproxPos-10), 0);
436 unsigned UpperBound = std::min(ApproxPos+10, FileLen);
437
438 // If the computed lower bound is less than the query location, move it in.
439 if (SourceLineCache < SourceLineCacheStart+LowerBound &&
440 SourceLineCacheStart[LowerBound] < QueriedFilePos)
441 SourceLineCache = SourceLineCacheStart+LowerBound;
442
443 // If the computed upper bound is greater than the query location, move it.
444 if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
445 SourceLineCacheStart[UpperBound] >= QueriedFilePos)
446 SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
447 }
448
449 unsigned *Pos
450 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
451 unsigned LineNo = Pos-SourceLineCacheStart;
452
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000453 LastLineNoFileIDQuery = LocInfo.first;
Ted Kremenekdd364ea2007-10-30 21:08:08 +0000454 LastLineNoContentCache = Content;
Chris Lattner4b009652007-07-25 00:24:17 +0000455 LastLineNoFilePos = QueriedFilePos;
456 LastLineNoResult = LineNo;
457 return LineNo;
458}
459
Chris Lattner27c0ced2009-01-26 00:43:02 +0000460/// getSourceName - This method returns the name of the file or buffer that
461/// the SourceLocation specifies. This can be modified with #line directives,
462/// etc.
463const char *SourceManager::getSourceName(SourceLocation Loc) const {
464 if (Loc.isInvalid()) return "";
465
466 const SrcMgr::ContentCache *C =
467 getSLocEntry(getFileID(getSpellingLoc(Loc))).getFile().getContentCache();
468
469 // To get the source name, first consult the FileEntry (if one exists) before
470 // the MemBuffer as this will avoid unnecessarily paging in the MemBuffer.
471 return C->Entry ? C->Entry->getName() : C->getBuffer()->getBufferIdentifier();
472}
473
474//===----------------------------------------------------------------------===//
475// Other miscellaneous methods.
476//===----------------------------------------------------------------------===//
477
478
Chris Lattner4b009652007-07-25 00:24:17 +0000479/// PrintStats - Print statistics to stderr.
480///
481void SourceManager::PrintStats() const {
Ted Kremenekda29d8c2007-12-05 22:21:13 +0000482 llvm::cerr << "\n*** Source Manager Stats:\n";
483 llvm::cerr << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
Chris Lattner27c0ced2009-01-26 00:43:02 +0000484 << " mem buffers mapped, " << SLocEntryTable.size()
485 << " SLocEntry's allocated.\n";
Chris Lattner4b009652007-07-25 00:24:17 +0000486
Chris Lattner4b009652007-07-25 00:24:17 +0000487 unsigned NumLineNumsComputed = 0;
488 unsigned NumFileBytesMapped = 0;
Ted Kremenekdd364ea2007-10-30 21:08:08 +0000489 for (std::set<ContentCache>::const_iterator I =
Chris Lattner4b009652007-07-25 00:24:17 +0000490 FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
Ted Kremenekdd364ea2007-10-30 21:08:08 +0000491 NumLineNumsComputed += I->SourceLineCache != 0;
Ted Kremenekaa7dac12009-01-06 01:55:26 +0000492 NumFileBytesMapped += I->getSizeBytesMapped();
Chris Lattner4b009652007-07-25 00:24:17 +0000493 }
Ted Kremenekdd364ea2007-10-30 21:08:08 +0000494
Ted Kremenekda29d8c2007-12-05 22:21:13 +0000495 llvm::cerr << NumFileBytesMapped << " bytes of files mapped, "
496 << NumLineNumsComputed << " files with line #'s computed.\n";
Chris Lattner27c0ced2009-01-26 00:43:02 +0000497 llvm::cerr << "FileID scans: " << NumLinearScans << " linear, "
498 << NumBinaryProbes << " binary.\n";
Chris Lattner4b009652007-07-25 00:24:17 +0000499}
Ted Kremenek0ad06d12007-12-04 19:39:02 +0000500
501//===----------------------------------------------------------------------===//
502// Serialization.
503//===----------------------------------------------------------------------===//
Ted Kremenek9c856e92007-12-05 00:14:18 +0000504
505void ContentCache::Emit(llvm::Serializer& S) const {
Ted Kremenek0ad06d12007-12-04 19:39:02 +0000506 S.FlushRecord();
507 S.EmitPtr(this);
Ted Kremenek0ad06d12007-12-04 19:39:02 +0000508
Ted Kremenek1b6dd6f2007-12-18 22:12:19 +0000509 if (Entry) {
510 llvm::sys::Path Fname(Buffer->getBufferIdentifier());
511
512 if (Fname.isAbsolute())
513 S.EmitCStr(Fname.c_str());
514 else {
515 // Create an absolute path.
516 // FIXME: This will potentially contain ".." and "." in the path.
517 llvm::sys::Path path = llvm::sys::Path::GetCurrentDirectory();
518 path.appendComponent(Fname.c_str());
519 S.EmitCStr(path.c_str());
520 }
521 }
Ted Kremenek9c856e92007-12-05 00:14:18 +0000522 else {
Ted Kremenek0ad06d12007-12-04 19:39:02 +0000523 const char* p = Buffer->getBufferStart();
524 const char* e = Buffer->getBufferEnd();
525
Ted Kremenek9c856e92007-12-05 00:14:18 +0000526 S.EmitInt(e-p);
527
Ted Kremenek0ad06d12007-12-04 19:39:02 +0000528 for ( ; p != e; ++p)
Ted Kremenek9c856e92007-12-05 00:14:18 +0000529 S.EmitInt(*p);
Ted Kremenek0ad06d12007-12-04 19:39:02 +0000530 }
531
Ted Kremenek9c856e92007-12-05 00:14:18 +0000532 S.FlushRecord();
Ted Kremenek0ad06d12007-12-04 19:39:02 +0000533}
Ted Kremenek9c856e92007-12-05 00:14:18 +0000534
535void ContentCache::ReadToSourceManager(llvm::Deserializer& D,
536 SourceManager& SMgr,
537 FileManager* FMgr,
538 std::vector<char>& Buf) {
539 if (FMgr) {
540 llvm::SerializedPtrID PtrID = D.ReadPtrID();
541 D.ReadCStr(Buf,false);
542
543 // Create/fetch the FileEntry.
544 const char* start = &Buf[0];
545 const FileEntry* E = FMgr->getFile(start,start+Buf.size());
546
Ted Kremenekb92cd872007-12-13 18:12:10 +0000547 // FIXME: Ideally we want a lazy materialization of the ContentCache
548 // anyway, because we don't want to read in source files unless this
549 // is absolutely needed.
550 if (!E)
551 D.RegisterPtr(PtrID,NULL);
Nico Weber630347d2008-09-29 00:25:48 +0000552 else
Ted Kremenekb92cd872007-12-13 18:12:10 +0000553 // Get the ContextCache object and register it with the deserializer.
Chris Lattner27c0ced2009-01-26 00:43:02 +0000554 D.RegisterPtr(PtrID, SMgr.getOrCreateContentCache(E));
555 return;
Ted Kremenek9c856e92007-12-05 00:14:18 +0000556 }
Chris Lattner27c0ced2009-01-26 00:43:02 +0000557
558 // Register the ContextCache object with the deserializer.
559 SMgr.MemBufferInfos.push_back(ContentCache());
560 ContentCache& Entry = const_cast<ContentCache&>(SMgr.MemBufferInfos.back());
561 D.RegisterPtr(&Entry);
562
563 // Create the buffer.
564 unsigned Size = D.ReadInt();
565 Entry.Buffer = MemoryBuffer::getNewUninitMemBuffer(Size);
566
567 // Read the contents of the buffer.
568 char* p = const_cast<char*>(Entry.Buffer->getBufferStart());
569 for (unsigned i = 0; i < Size ; ++i)
570 p[i] = D.ReadInt();
Ted Kremenek9c856e92007-12-05 00:14:18 +0000571}
572
573void SourceManager::Emit(llvm::Serializer& S) const {
Ted Kremenekbc54abf2007-12-05 00:19:51 +0000574 S.EnterBlock();
575 S.EmitPtr(this);
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000576 S.EmitInt(MainFileID.getOpaqueValue());
Ted Kremenekbc54abf2007-12-05 00:19:51 +0000577
Ted Kremenek9c856e92007-12-05 00:14:18 +0000578 // Emit: FileInfos. Just emit the file name.
579 S.EnterBlock();
580
581 std::for_each(FileInfos.begin(),FileInfos.end(),
582 S.MakeEmitter<ContentCache>());
583
584 S.ExitBlock();
585
586 // Emit: MemBufferInfos
587 S.EnterBlock();
588
589 std::for_each(MemBufferInfos.begin(), MemBufferInfos.end(),
590 S.MakeEmitter<ContentCache>());
591
592 S.ExitBlock();
593
Chris Lattner27c0ced2009-01-26 00:43:02 +0000594 // FIXME: Emit SLocEntryTable.
Ted Kremenekbc54abf2007-12-05 00:19:51 +0000595
596 S.ExitBlock();
Ted Kremenek9c856e92007-12-05 00:14:18 +0000597}
598
Ted Kremenekbc54abf2007-12-05 00:19:51 +0000599SourceManager*
600SourceManager::CreateAndRegister(llvm::Deserializer& D, FileManager& FMgr){
601 SourceManager *M = new SourceManager();
602 D.RegisterPtr(M);
603
Ted Kremenek2578dd02007-12-19 22:29:55 +0000604 // Read: the FileID of the main source file of the translation unit.
Chris Lattner27c0ced2009-01-26 00:43:02 +0000605 M->MainFileID = FileID::get(D.ReadInt());
Ted Kremenek2578dd02007-12-19 22:29:55 +0000606
Ted Kremenek9c856e92007-12-05 00:14:18 +0000607 std::vector<char> Buf;
608
609 { // Read: FileInfos.
610 llvm::Deserializer::Location BLoc = D.getCurrentBlockLocation();
611 while (!D.FinishedBlock(BLoc))
Ted Kremenekbc54abf2007-12-05 00:19:51 +0000612 ContentCache::ReadToSourceManager(D,*M,&FMgr,Buf);
Ted Kremenek9c856e92007-12-05 00:14:18 +0000613 }
614
615 { // Read: MemBufferInfos.
616 llvm::Deserializer::Location BLoc = D.getCurrentBlockLocation();
617 while (!D.FinishedBlock(BLoc))
Ted Kremenekbc54abf2007-12-05 00:19:51 +0000618 ContentCache::ReadToSourceManager(D,*M,NULL,Buf);
Ted Kremenek9c856e92007-12-05 00:14:18 +0000619 }
620
Chris Lattner27c0ced2009-01-26 00:43:02 +0000621 // FIXME: Read SLocEntryTable.
Ted Kremenekbc54abf2007-12-05 00:19:51 +0000622
623 return M;
Ted Kremenek12206af2007-12-10 18:01:25 +0000624}