blob: d3fbeeb1bb86abb66fe116799b2d202051d5d005 [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"
Douglas Gregorcdad0ba2009-04-13 15:31:25 +000015#include "clang/Basic/SourceManagerInternals.h"
Chris Lattner4b009652007-07-25 00:24:17 +000016#include "clang/Basic/FileManager.h"
17#include "llvm/Support/Compiler.h"
18#include "llvm/Support/MemoryBuffer.h"
19#include "llvm/System/Path.h"
Ted Kremenekdd364ea2007-10-30 21:08:08 +000020#include "llvm/Bitcode/Serialize.h"
21#include "llvm/Bitcode/Deserialize.h"
Ted Kremenekda29d8c2007-12-05 22:21:13 +000022#include "llvm/Support/Streams.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include <algorithm>
Chris Lattner4b009652007-07-25 00:24:17 +000024using namespace clang;
25using namespace SrcMgr;
26using llvm::MemoryBuffer;
27
Chris Lattnerfa45efd2009-02-04 00:40:31 +000028//===----------------------------------------------------------------------===//
Chris Lattner27c0ced2009-01-26 00:43:02 +000029// SourceManager Helper Classes
Chris Lattnerfa45efd2009-02-04 00:40:31 +000030//===----------------------------------------------------------------------===//
Chris Lattner27c0ced2009-01-26 00:43:02 +000031
Ted Kremenekdd364ea2007-10-30 21:08:08 +000032ContentCache::~ContentCache() {
33 delete Buffer;
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 Lattnerd2051b42009-01-26 07:57:50 +000061unsigned LineTableInfo::getLineTableFilenameID(const char *Ptr, unsigned Len) {
62 // Look up the filename in the string table, returning the pre-existing value
63 // if it exists.
64 llvm::StringMapEntry<unsigned> &Entry =
65 FilenameIDs.GetOrCreateValue(Ptr, Ptr+Len, ~0U);
66 if (Entry.getValue() != ~0U)
67 return Entry.getValue();
68
69 // Otherwise, assign this the next available ID.
70 Entry.setValue(FilenamesByID.size());
71 FilenamesByID.push_back(&Entry);
72 return FilenamesByID.size()-1;
73}
74
Chris Lattner6256b2b2009-02-03 22:13:05 +000075/// AddLineNote - Add a line note to the line table that indicates that there
76/// is a #line at the specified FID/Offset location which changes the presumed
77/// location to LineNo/FilenameID.
Chris Lattnerfa45efd2009-02-04 00:40:31 +000078void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
Chris Lattner6256b2b2009-02-03 22:13:05 +000079 unsigned LineNo, int FilenameID) {
Chris Lattnerfa45efd2009-02-04 00:40:31 +000080 std::vector<LineEntry> &Entries = LineEntries[FID];
Chris Lattner6256b2b2009-02-03 22:13:05 +000081
Chris Lattnerfa45efd2009-02-04 00:40:31 +000082 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
83 "Adding line entries out of order!");
Chris Lattner6f9fa5a2009-02-04 01:55:42 +000084
Chris Lattner7bf78512009-02-04 05:21:58 +000085 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
Chris Lattner778ae212009-02-04 06:25:26 +000086 unsigned IncludeOffset = 0;
Chris Lattner6f9fa5a2009-02-04 01:55:42 +000087
Chris Lattner7bf78512009-02-04 05:21:58 +000088 if (!Entries.empty()) {
89 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
90 // that we are still in "foo.h".
91 if (FilenameID == -1)
92 FilenameID = Entries.back().FilenameID;
93
Chris Lattner778ae212009-02-04 06:25:26 +000094 // If we are after a line marker that switched us to system header mode, or
95 // that set #include information, preserve it.
Chris Lattner7bf78512009-02-04 05:21:58 +000096 Kind = Entries.back().FileKind;
Chris Lattner778ae212009-02-04 06:25:26 +000097 IncludeOffset = Entries.back().IncludeOffset;
Chris Lattner7bf78512009-02-04 05:21:58 +000098 }
99
Chris Lattner778ae212009-02-04 06:25:26 +0000100 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
101 IncludeOffset));
Chris Lattner6256b2b2009-02-03 22:13:05 +0000102}
103
Chris Lattner7bf78512009-02-04 05:21:58 +0000104/// AddLineNote This is the same as the previous version of AddLineNote, but is
105/// used for GNU line markers. If EntryExit is 0, then this doesn't change the
106/// presumed #include stack. If it is 1, this is a file entry, if it is 2 then
107/// this is a file exit. FileKind specifies whether this is a system header or
108/// extern C system header.
109void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
110 unsigned LineNo, int FilenameID,
111 unsigned EntryExit,
112 SrcMgr::CharacteristicKind FileKind) {
113 assert(FilenameID != -1 && "Unspecified filename should use other accessor");
114
115 std::vector<LineEntry> &Entries = LineEntries[FID];
116
117 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
118 "Adding line entries out of order!");
119
Chris Lattner778ae212009-02-04 06:25:26 +0000120 unsigned IncludeOffset = 0;
121 if (EntryExit == 0) { // No #include stack change.
122 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
123 } else if (EntryExit == 1) {
124 IncludeOffset = Offset-1;
125 } else if (EntryExit == 2) {
126 assert(!Entries.empty() && Entries.back().IncludeOffset &&
127 "PPDirectives should have caught case when popping empty include stack");
128
129 // Get the include loc of the last entries' include loc as our include loc.
130 IncludeOffset = 0;
131 if (const LineEntry *PrevEntry =
132 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
133 IncludeOffset = PrevEntry->IncludeOffset;
134 }
Chris Lattner7bf78512009-02-04 05:21:58 +0000135
Chris Lattner778ae212009-02-04 06:25:26 +0000136 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
137 IncludeOffset));
Chris Lattner7bf78512009-02-04 05:21:58 +0000138}
139
140
Chris Lattner6f9fa5a2009-02-04 01:55:42 +0000141/// FindNearestLineEntry - Find the line entry nearest to FID that is before
142/// it. If there is no line entry before Offset in FID, return null.
143const LineEntry *LineTableInfo::FindNearestLineEntry(unsigned FID,
144 unsigned Offset) {
145 const std::vector<LineEntry> &Entries = LineEntries[FID];
146 assert(!Entries.empty() && "No #line entries for this FID after all!");
147
Chris Lattner1a2fbe42009-02-04 04:46:59 +0000148 // It is very common for the query to be after the last #line, check this
149 // first.
150 if (Entries.back().FileOffset <= Offset)
151 return &Entries.back();
Chris Lattner6f9fa5a2009-02-04 01:55:42 +0000152
Chris Lattner1a2fbe42009-02-04 04:46:59 +0000153 // Do a binary search to find the maximal element that is still before Offset.
154 std::vector<LineEntry>::const_iterator I =
155 std::upper_bound(Entries.begin(), Entries.end(), Offset);
156 if (I == Entries.begin()) return 0;
157 return &*--I;
Chris Lattner6f9fa5a2009-02-04 01:55:42 +0000158}
Chris Lattner6256b2b2009-02-03 22:13:05 +0000159
160
Chris Lattnerd2051b42009-01-26 07:57:50 +0000161/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
162///
163unsigned SourceManager::getLineTableFilenameID(const char *Ptr, unsigned Len) {
164 if (LineTable == 0)
165 LineTable = new LineTableInfo();
166 return LineTable->getLineTableFilenameID(Ptr, Len);
167}
168
169
Chris Lattnerb06739c2009-02-03 21:52:55 +0000170/// AddLineNote - Add a line note to the line table for the FileID and offset
171/// specified by Loc. If FilenameID is -1, it is considered to be
172/// unspecified.
173void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
174 int FilenameID) {
Chris Lattner6256b2b2009-02-03 22:13:05 +0000175 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Chris Lattnerb06739c2009-02-03 21:52:55 +0000176
Chris Lattner6256b2b2009-02-03 22:13:05 +0000177 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
178
179 // Remember that this file has #line directives now if it doesn't already.
180 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
181
182 if (LineTable == 0)
183 LineTable = new LineTableInfo();
Chris Lattnerfa45efd2009-02-04 00:40:31 +0000184 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID);
Chris Lattnerb06739c2009-02-03 21:52:55 +0000185}
186
Chris Lattner7bf78512009-02-04 05:21:58 +0000187/// AddLineNote - Add a GNU line marker to the line table.
188void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
189 int FilenameID, bool IsFileEntry,
190 bool IsFileExit, bool IsSystemHeader,
191 bool IsExternCHeader) {
192 // If there is no filename and no flags, this is treated just like a #line,
193 // which does not change the flags of the previous line marker.
194 if (FilenameID == -1) {
195 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
196 "Can't set flags without setting the filename!");
197 return AddLineNote(Loc, LineNo, FilenameID);
198 }
199
200 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
201 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
202
203 // Remember that this file has #line directives now if it doesn't already.
204 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
205
206 if (LineTable == 0)
207 LineTable = new LineTableInfo();
208
209 SrcMgr::CharacteristicKind FileKind;
210 if (IsExternCHeader)
211 FileKind = SrcMgr::C_ExternCSystem;
212 else if (IsSystemHeader)
213 FileKind = SrcMgr::C_System;
214 else
215 FileKind = SrcMgr::C_User;
216
217 unsigned EntryExit = 0;
218 if (IsFileEntry)
219 EntryExit = 1;
220 else if (IsFileExit)
221 EntryExit = 2;
222
223 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID,
224 EntryExit, FileKind);
225}
226
Chris Lattnerb06739c2009-02-03 21:52:55 +0000227
Chris Lattnerfa45efd2009-02-04 00:40:31 +0000228//===----------------------------------------------------------------------===//
Chris Lattner27c0ced2009-01-26 00:43:02 +0000229// Private 'Create' methods.
Chris Lattnerfa45efd2009-02-04 00:40:31 +0000230//===----------------------------------------------------------------------===//
Ted Kremenekaa7dac12009-01-06 01:55:26 +0000231
Chris Lattnerd2051b42009-01-26 07:57:50 +0000232SourceManager::~SourceManager() {
233 delete LineTable;
Chris Lattner8dedb842009-02-03 07:30:45 +0000234
235 // Delete FileEntry objects corresponding to content caches. Since the actual
236 // content cache objects are bump pointer allocated, we just have to run the
237 // dtors, but we call the deallocate method for completeness.
238 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
239 MemBufferInfos[i]->~ContentCache();
240 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
241 }
242 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
243 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
244 I->second->~ContentCache();
245 ContentCacheAlloc.Deallocate(I->second);
246 }
Chris Lattnerd2051b42009-01-26 07:57:50 +0000247}
248
249void SourceManager::clearIDTables() {
250 MainFileID = FileID();
251 SLocEntryTable.clear();
252 LastLineNoFileIDQuery = FileID();
253 LastLineNoContentCache = 0;
254 LastFileIDLookup = FileID();
255
256 if (LineTable)
257 LineTable->clear();
258
259 // Use up FileID #0 as an invalid instantiation.
260 NextOffset = 0;
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000261 createInstantiationLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattnerd2051b42009-01-26 07:57:50 +0000262}
263
Chris Lattner27c0ced2009-01-26 00:43:02 +0000264/// getOrCreateContentCache - Create or return a cached ContentCache for the
265/// specified file.
266const ContentCache *
267SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) {
Chris Lattner4b009652007-07-25 00:24:17 +0000268 assert(FileEnt && "Didn't specify a file entry to use?");
Chris Lattner27c0ced2009-01-26 00:43:02 +0000269
Chris Lattner4b009652007-07-25 00:24:17 +0000270 // Do we already have information about this file?
Chris Lattner8dedb842009-02-03 07:30:45 +0000271 ContentCache *&Entry = FileInfos[FileEnt];
272 if (Entry) return Entry;
Chris Lattner4b009652007-07-25 00:24:17 +0000273
Chris Lattner917d7c62009-02-03 07:41:46 +0000274 // Nope, create a new Cache entry. Make sure it is at least 8-byte aligned
275 // so that FileInfo can use the low 3 bits of the pointer for its own
276 // nefarious purposes.
277 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
278 EntryAlign = std::max(8U, EntryAlign);
279 Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner8dedb842009-02-03 07:30:45 +0000280 new (Entry) ContentCache(FileEnt);
281 return Entry;
Chris Lattner4b009652007-07-25 00:24:17 +0000282}
283
284
Ted Kremenek27f9c9b2007-10-31 17:53:38 +0000285/// createMemBufferContentCache - Create a new ContentCache for the specified
286/// memory buffer. This does no caching.
Ted Kremenekdd364ea2007-10-30 21:08:08 +0000287const ContentCache*
288SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
Chris Lattner917d7c62009-02-03 07:41:46 +0000289 // Add a new ContentCache to the MemBufferInfos list and return it. Make sure
290 // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of
291 // the pointer for its own nefarious purposes.
292 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
293 EntryAlign = std::max(8U, EntryAlign);
294 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner8dedb842009-02-03 07:30:45 +0000295 new (Entry) ContentCache();
296 MemBufferInfos.push_back(Entry);
297 Entry->setBuffer(Buffer);
298 return Entry;
Chris Lattner4b009652007-07-25 00:24:17 +0000299}
300
Chris Lattner27c0ced2009-01-26 00:43:02 +0000301//===----------------------------------------------------------------------===//
302// Methods to create new FileID's and instantiations.
303//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000304
Nico Weber630347d2008-09-29 00:25:48 +0000305/// createFileID - Create a new fileID for the specified ContentCache and
Ted Kremenek7670cca2007-10-30 22:57:35 +0000306/// include position. This works regardless of whether the ContentCache
307/// corresponds to a file or some other input source.
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000308FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattner27c0ced2009-01-26 00:43:02 +0000309 SourceLocation IncludePos,
310 SrcMgr::CharacteristicKind FileCharacter) {
311 SLocEntryTable.push_back(SLocEntry::get(NextOffset,
312 FileInfo::get(IncludePos, File,
313 FileCharacter)));
Ted Kremenekaa7dac12009-01-06 01:55:26 +0000314 unsigned FileSize = File->getSize();
Chris Lattner27c0ced2009-01-26 00:43:02 +0000315 assert(NextOffset+FileSize+1 > NextOffset && "Ran out of source locations!");
316 NextOffset += FileSize+1;
Chris Lattner4b009652007-07-25 00:24:17 +0000317
Chris Lattner27c0ced2009-01-26 00:43:02 +0000318 // Set LastFileIDLookup to the newly created file. The next getFileID call is
319 // almost guaranteed to be from that file.
320 return LastFileIDLookup = FileID::get(SLocEntryTable.size()-1);
Chris Lattner4b009652007-07-25 00:24:17 +0000321}
322
Chris Lattner27c0ced2009-01-26 00:43:02 +0000323/// createInstantiationLoc - Return a new SourceLocation that encodes the fact
Chris Lattnercdf600e2009-01-16 07:00:02 +0000324/// that a token from SpellingLoc should actually be referenced from
Chris Lattner4b009652007-07-25 00:24:17 +0000325/// InstantiationLoc.
Chris Lattner27c0ced2009-01-26 00:43:02 +0000326SourceLocation SourceManager::createInstantiationLoc(SourceLocation SpellingLoc,
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000327 SourceLocation ILocStart,
328 SourceLocation ILocEnd,
Chris Lattner27c0ced2009-01-26 00:43:02 +0000329 unsigned TokLength) {
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000330 InstantiationInfo II = InstantiationInfo::get(ILocStart,ILocEnd, SpellingLoc);
331 SLocEntryTable.push_back(SLocEntry::get(NextOffset, II));
Chris Lattner27c0ced2009-01-26 00:43:02 +0000332 assert(NextOffset+TokLength+1 > NextOffset && "Ran out of source locations!");
333 NextOffset += TokLength+1;
334 return SourceLocation::getMacroLoc(NextOffset-(TokLength+1));
Chris Lattner4b009652007-07-25 00:24:17 +0000335}
336
Chris Lattner71e443a2009-01-19 07:32:13 +0000337/// getBufferData - Return a pointer to the start and end of the source buffer
338/// data for the specified FileID.
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000339std::pair<const char*, const char*>
340SourceManager::getBufferData(FileID FID) const {
341 const llvm::MemoryBuffer *Buf = getBuffer(FID);
342 return std::make_pair(Buf->getBufferStart(), Buf->getBufferEnd());
343}
344
345
Chris Lattnerfa45efd2009-02-04 00:40:31 +0000346//===----------------------------------------------------------------------===//
Chris Lattner27c0ced2009-01-26 00:43:02 +0000347// SourceLocation manipulation methods.
Chris Lattnerfa45efd2009-02-04 00:40:31 +0000348//===----------------------------------------------------------------------===//
Chris Lattner27c0ced2009-01-26 00:43:02 +0000349
350/// getFileIDSlow - Return the FileID for a SourceLocation. This is a very hot
351/// method that is used for all SourceManager queries that start with a
352/// SourceLocation object. It is responsible for finding the entry in
353/// SLocEntryTable which contains the specified location.
354///
355FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
356 assert(SLocOffset && "Invalid FileID");
357
358 // After the first and second level caches, I see two common sorts of
359 // behavior: 1) a lot of searched FileID's are "near" the cached file location
360 // or are "near" the cached instantiation location. 2) others are just
361 // completely random and may be a very long way away.
362 //
363 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
364 // then we fall back to a less cache efficient, but more scalable, binary
365 // search to find the location.
366
367 // See if this is near the file point - worst case we start scanning from the
368 // most newly created FileID.
369 std::vector<SrcMgr::SLocEntry>::const_iterator I;
370
371 if (SLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
372 // Neither loc prunes our search.
373 I = SLocEntryTable.end();
374 } else {
375 // Perhaps it is near the file point.
376 I = SLocEntryTable.begin()+LastFileIDLookup.ID;
377 }
378
379 // Find the FileID that contains this. "I" is an iterator that points to a
380 // FileID whose offset is known to be larger than SLocOffset.
381 unsigned NumProbes = 0;
382 while (1) {
383 --I;
384 if (I->getOffset() <= SLocOffset) {
385#if 0
386 printf("lin %d -> %d [%s] %d %d\n", SLocOffset,
387 I-SLocEntryTable.begin(),
388 I->isInstantiation() ? "inst" : "file",
389 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
390#endif
391 FileID Res = FileID::get(I-SLocEntryTable.begin());
392
393 // If this isn't an instantiation, remember it. We have good locality
394 // across FileID lookups.
395 if (!I->isInstantiation())
396 LastFileIDLookup = Res;
397 NumLinearScans += NumProbes+1;
398 return Res;
399 }
400 if (++NumProbes == 8)
401 break;
402 }
403
404 // Convert "I" back into an index. We know that it is an entry whose index is
405 // larger than the offset we are looking for.
406 unsigned GreaterIndex = I-SLocEntryTable.begin();
407 // LessIndex - This is the lower bound of the range that we're searching.
408 // We know that the offset corresponding to the FileID is is less than
409 // SLocOffset.
410 unsigned LessIndex = 0;
411 NumProbes = 0;
412 while (1) {
413 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
414 unsigned MidOffset = SLocEntryTable[MiddleIndex].getOffset();
415
416 ++NumProbes;
417
418 // If the offset of the midpoint is too large, chop the high side of the
419 // range to the midpoint.
420 if (MidOffset > SLocOffset) {
421 GreaterIndex = MiddleIndex;
422 continue;
423 }
424
425 // If the middle index contains the value, succeed and return.
426 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
427#if 0
428 printf("bin %d -> %d [%s] %d %d\n", SLocOffset,
429 I-SLocEntryTable.begin(),
430 I->isInstantiation() ? "inst" : "file",
431 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
432#endif
433 FileID Res = FileID::get(MiddleIndex);
434
435 // If this isn't an instantiation, remember it. We have good locality
436 // across FileID lookups.
437 if (!I->isInstantiation())
438 LastFileIDLookup = Res;
439 NumBinaryProbes += NumProbes;
440 return Res;
441 }
442
443 // Otherwise, move the low-side up to the middle index.
444 LessIndex = MiddleIndex;
445 }
446}
447
Chris Lattner8d92c1a2009-01-26 20:04:19 +0000448SourceLocation SourceManager::
449getInstantiationLocSlowCase(SourceLocation Loc) const {
450 do {
451 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000452 Loc = getSLocEntry(LocInfo.first).getInstantiation()
453 .getInstantiationLocStart();
Chris Lattner8d92c1a2009-01-26 20:04:19 +0000454 Loc = Loc.getFileLocWithOffset(LocInfo.second);
455 } while (!Loc.isFileID());
456
457 return Loc;
458}
459
460SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
461 do {
462 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
463 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
464 Loc = Loc.getFileLocWithOffset(LocInfo.second);
465 } while (!Loc.isFileID());
466 return Loc;
467}
468
469
Chris Lattner27c0ced2009-01-26 00:43:02 +0000470std::pair<FileID, unsigned>
471SourceManager::getDecomposedInstantiationLocSlowCase(const SrcMgr::SLocEntry *E,
472 unsigned Offset) const {
473 // If this is an instantiation record, walk through all the instantiation
474 // points.
475 FileID FID;
476 SourceLocation Loc;
477 do {
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000478 Loc = E->getInstantiation().getInstantiationLocStart();
Chris Lattner27c0ced2009-01-26 00:43:02 +0000479
480 FID = getFileID(Loc);
481 E = &getSLocEntry(FID);
482 Offset += Loc.getOffset()-E->getOffset();
Chris Lattner18ad5582009-01-26 19:41:58 +0000483 } while (!Loc.isFileID());
Chris Lattner27c0ced2009-01-26 00:43:02 +0000484
485 return std::make_pair(FID, Offset);
486}
487
488std::pair<FileID, unsigned>
489SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
490 unsigned Offset) const {
Chris Lattner18ad5582009-01-26 19:41:58 +0000491 // If this is an instantiation record, walk through all the instantiation
492 // points.
493 FileID FID;
494 SourceLocation Loc;
495 do {
496 Loc = E->getInstantiation().getSpellingLoc();
497
498 FID = getFileID(Loc);
499 E = &getSLocEntry(FID);
500 Offset += Loc.getOffset()-E->getOffset();
501 } while (!Loc.isFileID());
502
Chris Lattner27c0ced2009-01-26 00:43:02 +0000503 return std::make_pair(FID, Offset);
504}
505
Chris Lattnerbf9a0e32009-02-17 08:04:48 +0000506/// getImmediateSpellingLoc - Given a SourceLocation object, return the
507/// spelling location referenced by the ID. This is the first level down
508/// towards the place where the characters that make up the lexed token can be
509/// found. This should not generally be used by clients.
510SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
511 if (Loc.isFileID()) return Loc;
512 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
513 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
514 return Loc.getFileLocWithOffset(LocInfo.second);
515}
516
517
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000518/// getImmediateInstantiationRange - Loc is required to be an instantiation
519/// location. Return the start/end of the instantiation information.
520std::pair<SourceLocation,SourceLocation>
521SourceManager::getImmediateInstantiationRange(SourceLocation Loc) const {
522 assert(Loc.isMacroID() && "Not an instantiation loc!");
523 const InstantiationInfo &II = getSLocEntry(getFileID(Loc)).getInstantiation();
524 return II.getInstantiationLocRange();
525}
526
Chris Lattner46558bf2009-02-15 21:26:50 +0000527/// getInstantiationRange - Given a SourceLocation object, return the
528/// range of tokens covered by the instantiation in the ultimate file.
529std::pair<SourceLocation,SourceLocation>
530SourceManager::getInstantiationRange(SourceLocation Loc) const {
531 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
532
533 std::pair<SourceLocation,SourceLocation> Res =
534 getImmediateInstantiationRange(Loc);
535
536 // Fully resolve the start and end locations to their ultimate instantiation
537 // points.
538 while (!Res.first.isFileID())
539 Res.first = getImmediateInstantiationRange(Res.first).first;
540 while (!Res.second.isFileID())
541 Res.second = getImmediateInstantiationRange(Res.second).second;
542 return Res;
543}
544
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000545
Chris Lattner27c0ced2009-01-26 00:43:02 +0000546
547//===----------------------------------------------------------------------===//
548// Queries about the code at a SourceLocation.
549//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000550
551/// getCharacterData - Return a pointer to the start of the specified location
552/// in the appropriate MemoryBuffer.
553const char *SourceManager::getCharacterData(SourceLocation SL) const {
554 // Note that this is a hot function in the getSpelling() path, which is
555 // heavily used by -E mode.
Chris Lattner27c0ced2009-01-26 00:43:02 +0000556 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000557
Ted Kremenekaa7dac12009-01-06 01:55:26 +0000558 // Note that calling 'getBuffer()' may lazily page in a source file.
Chris Lattner27c0ced2009-01-26 00:43:02 +0000559 return getSLocEntry(LocInfo.first).getFile().getContentCache()
560 ->getBuffer()->getBufferStart() + LocInfo.second;
Chris Lattner4b009652007-07-25 00:24:17 +0000561}
562
563
564/// getColumnNumber - Return the column # for the specified file position.
Chris Lattnere79fc852009-02-04 00:55:58 +0000565/// this is significantly cheaper to compute than the line number.
566unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos) const {
567 const char *Buf = getBuffer(FID)->getBufferStart();
Chris Lattner4b009652007-07-25 00:24:17 +0000568
Chris Lattner4b009652007-07-25 00:24:17 +0000569 unsigned LineStart = FilePos;
570 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
571 --LineStart;
572 return FilePos-LineStart+1;
573}
574
Chris Lattnere79fc852009-02-04 00:55:58 +0000575unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc) const {
Chris Lattner2d89c562009-02-04 01:06:56 +0000576 if (Loc.isInvalid()) return 0;
Chris Lattnere79fc852009-02-04 00:55:58 +0000577 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
578 return getColumnNumber(LocInfo.first, LocInfo.second);
579}
580
581unsigned SourceManager::getInstantiationColumnNumber(SourceLocation Loc) const {
Chris Lattner2d89c562009-02-04 01:06:56 +0000582 if (Loc.isInvalid()) return 0;
Chris Lattnere79fc852009-02-04 00:55:58 +0000583 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
584 return getColumnNumber(LocInfo.first, LocInfo.second);
585}
586
587
588
Chris Lattner8dedb842009-02-03 07:30:45 +0000589static void ComputeLineNumbers(ContentCache* FI,
590 llvm::BumpPtrAllocator &Alloc) DISABLE_INLINE;
591static void ComputeLineNumbers(ContentCache* FI, llvm::BumpPtrAllocator &Alloc){
Ted Kremenekaa7dac12009-01-06 01:55:26 +0000592 // Note that calling 'getBuffer()' may lazily page in the file.
593 const MemoryBuffer *Buffer = FI->getBuffer();
Chris Lattner4b009652007-07-25 00:24:17 +0000594
595 // Find the file offsets of all of the *physical* source lines. This does
596 // not look at trigraphs, escaped newlines, or anything else tricky.
597 std::vector<unsigned> LineOffsets;
598
599 // Line #1 starts at char 0.
600 LineOffsets.push_back(0);
601
602 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
603 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
604 unsigned Offs = 0;
605 while (1) {
606 // Skip over the contents of the line.
607 // TODO: Vectorize this? This is very performance sensitive for programs
608 // with lots of diagnostics and in -E mode.
609 const unsigned char *NextBuf = (const unsigned char *)Buf;
610 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
611 ++NextBuf;
612 Offs += NextBuf-Buf;
613 Buf = NextBuf;
614
615 if (Buf[0] == '\n' || Buf[0] == '\r') {
616 // If this is \n\r or \r\n, skip both characters.
617 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
618 ++Offs, ++Buf;
619 ++Offs, ++Buf;
620 LineOffsets.push_back(Offs);
621 } else {
622 // Otherwise, this is a null. If end of file, exit.
623 if (Buf == End) break;
624 // Otherwise, skip the null.
625 ++Offs, ++Buf;
626 }
627 }
Chris Lattner4b009652007-07-25 00:24:17 +0000628
629 // Copy the offsets into the FileInfo structure.
630 FI->NumLines = LineOffsets.size();
Chris Lattner8dedb842009-02-03 07:30:45 +0000631 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner4b009652007-07-25 00:24:17 +0000632 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
633}
634
Chris Lattnercdf600e2009-01-16 07:00:02 +0000635/// getLineNumber - Given a SourceLocation, return the spelling line number
Chris Lattner4b009652007-07-25 00:24:17 +0000636/// for the position indicated. This requires building and caching a table of
637/// line offsets for the MemoryBuffer, so this is not cheap: use only when
638/// about to emit a diagnostic.
Chris Lattner2d89c562009-02-04 01:06:56 +0000639unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos) const {
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000640 ContentCache *Content;
Chris Lattner2d89c562009-02-04 01:06:56 +0000641 if (LastLineNoFileIDQuery == FID)
Ted Kremenekdd364ea2007-10-30 21:08:08 +0000642 Content = LastLineNoContentCache;
Chris Lattner4b009652007-07-25 00:24:17 +0000643 else
Chris Lattner2d89c562009-02-04 01:06:56 +0000644 Content = const_cast<ContentCache*>(getSLocEntry(FID)
Chris Lattner27c0ced2009-01-26 00:43:02 +0000645 .getFile().getContentCache());
Chris Lattner4b009652007-07-25 00:24:17 +0000646
647 // If this is the first use of line information for this buffer, compute the
648 /// SourceLineCache for it on demand.
Ted Kremenekdd364ea2007-10-30 21:08:08 +0000649 if (Content->SourceLineCache == 0)
Chris Lattner8dedb842009-02-03 07:30:45 +0000650 ComputeLineNumbers(Content, ContentCacheAlloc);
Chris Lattner4b009652007-07-25 00:24:17 +0000651
652 // Okay, we know we have a line number table. Do a binary search to find the
653 // line number that this character position lands on.
Ted Kremenekdd364ea2007-10-30 21:08:08 +0000654 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner4b009652007-07-25 00:24:17 +0000655 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenekdd364ea2007-10-30 21:08:08 +0000656 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Chris Lattner4b009652007-07-25 00:24:17 +0000657
Chris Lattner2d89c562009-02-04 01:06:56 +0000658 unsigned QueriedFilePos = FilePos+1;
Chris Lattner4b009652007-07-25 00:24:17 +0000659
660 // If the previous query was to the same file, we know both the file pos from
661 // that query and the line number returned. This allows us to narrow the
662 // search space from the entire file to something near the match.
Chris Lattner2d89c562009-02-04 01:06:56 +0000663 if (LastLineNoFileIDQuery == FID) {
Chris Lattner4b009652007-07-25 00:24:17 +0000664 if (QueriedFilePos >= LastLineNoFilePos) {
665 SourceLineCache = SourceLineCache+LastLineNoResult-1;
666
667 // The query is likely to be nearby the previous one. Here we check to
668 // see if it is within 5, 10 or 20 lines. It can be far away in cases
669 // where big comment blocks and vertical whitespace eat up lines but
670 // contribute no tokens.
671 if (SourceLineCache+5 < SourceLineCacheEnd) {
672 if (SourceLineCache[5] > QueriedFilePos)
673 SourceLineCacheEnd = SourceLineCache+5;
674 else if (SourceLineCache+10 < SourceLineCacheEnd) {
675 if (SourceLineCache[10] > QueriedFilePos)
676 SourceLineCacheEnd = SourceLineCache+10;
677 else if (SourceLineCache+20 < SourceLineCacheEnd) {
678 if (SourceLineCache[20] > QueriedFilePos)
679 SourceLineCacheEnd = SourceLineCache+20;
680 }
681 }
682 }
683 } else {
684 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
685 }
686 }
687
688 // If the spread is large, do a "radix" test as our initial guess, based on
689 // the assumption that lines average to approximately the same length.
690 // NOTE: This is currently disabled, as it does not appear to be profitable in
691 // initial measurements.
692 if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
Ted Kremenekdd364ea2007-10-30 21:08:08 +0000693 unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
Chris Lattner4b009652007-07-25 00:24:17 +0000694
695 // Take a stab at guessing where it is.
Ted Kremenekdd364ea2007-10-30 21:08:08 +0000696 unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
Chris Lattner4b009652007-07-25 00:24:17 +0000697
698 // Check for -10 and +10 lines.
699 unsigned LowerBound = std::max(int(ApproxPos-10), 0);
700 unsigned UpperBound = std::min(ApproxPos+10, FileLen);
701
702 // If the computed lower bound is less than the query location, move it in.
703 if (SourceLineCache < SourceLineCacheStart+LowerBound &&
704 SourceLineCacheStart[LowerBound] < QueriedFilePos)
705 SourceLineCache = SourceLineCacheStart+LowerBound;
706
707 // If the computed upper bound is greater than the query location, move it.
708 if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
709 SourceLineCacheStart[UpperBound] >= QueriedFilePos)
710 SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
711 }
712
713 unsigned *Pos
714 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
715 unsigned LineNo = Pos-SourceLineCacheStart;
716
Chris Lattner2d89c562009-02-04 01:06:56 +0000717 LastLineNoFileIDQuery = FID;
Ted Kremenekdd364ea2007-10-30 21:08:08 +0000718 LastLineNoContentCache = Content;
Chris Lattner4b009652007-07-25 00:24:17 +0000719 LastLineNoFilePos = QueriedFilePos;
720 LastLineNoResult = LineNo;
721 return LineNo;
722}
723
Chris Lattner2d89c562009-02-04 01:06:56 +0000724unsigned SourceManager::getInstantiationLineNumber(SourceLocation Loc) const {
725 if (Loc.isInvalid()) return 0;
726 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
727 return getLineNumber(LocInfo.first, LocInfo.second);
728}
729unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc) const {
730 if (Loc.isInvalid()) return 0;
731 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
732 return getLineNumber(LocInfo.first, LocInfo.second);
733}
734
Chris Lattnerd0ff6022009-02-04 05:33:01 +0000735/// getFileCharacteristic - return the file characteristic of the specified
736/// source location, indicating whether this is a normal file, a system
737/// header, or an "implicit extern C" system header.
738///
739/// This state can be modified with flags on GNU linemarker directives like:
740/// # 4 "foo.h" 3
741/// which changes all source locations in the current file after that to be
742/// considered to be from a system header.
743SrcMgr::CharacteristicKind
744SourceManager::getFileCharacteristic(SourceLocation Loc) const {
745 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
746 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
747 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
748
749 // If there are no #line directives in this file, just return the whole-file
750 // state.
751 if (!FI.hasLineDirectives())
752 return FI.getFileCharacteristic();
753
754 assert(LineTable && "Can't have linetable entries without a LineTable!");
755 // See if there is a #line directive before the location.
756 const LineEntry *Entry =
757 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second);
758
759 // If this is before the first line marker, use the file characteristic.
760 if (!Entry)
761 return FI.getFileCharacteristic();
762
763 return Entry->FileKind;
764}
765
Chris Lattnerf1790ca2009-02-17 08:39:06 +0000766/// Return the filename or buffer identifier of the buffer the location is in.
767/// Note that this name does not respect #line directives. Use getPresumedLoc
768/// for normal clients.
769const char *SourceManager::getBufferName(SourceLocation Loc) const {
770 if (Loc.isInvalid()) return "<invalid loc>";
771
772 return getBuffer(getFileID(Loc))->getBufferIdentifier();
773}
774
Chris Lattner2d89c562009-02-04 01:06:56 +0000775
Chris Lattner836774b2009-01-27 07:57:44 +0000776/// getPresumedLoc - This method returns the "presumed" location of a
777/// SourceLocation specifies. A "presumed location" can be modified by #line
778/// or GNU line marker directives. This provides a view on the data that a
779/// user should see in diagnostics, for example.
780///
781/// Note that a presumed location is always given as the instantiation point
782/// of an instantiation location, not at the spelling location.
783PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
784 if (Loc.isInvalid()) return PresumedLoc();
Chris Lattner27c0ced2009-01-26 00:43:02 +0000785
Chris Lattner836774b2009-01-27 07:57:44 +0000786 // Presumed locations are always for instantiation points.
Chris Lattnere79fc852009-02-04 00:55:58 +0000787 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Chris Lattner836774b2009-01-27 07:57:44 +0000788
Chris Lattner2d89c562009-02-04 01:06:56 +0000789 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
Chris Lattner836774b2009-01-27 07:57:44 +0000790 const SrcMgr::ContentCache *C = FI.getContentCache();
Chris Lattner6f9fa5a2009-02-04 01:55:42 +0000791
792 // To get the source name, first consult the FileEntry (if one exists)
793 // before the MemBuffer as this will avoid unnecessarily paging in the
794 // MemBuffer.
Chris Lattner836774b2009-01-27 07:57:44 +0000795 const char *Filename =
796 C->Entry ? C->Entry->getName() : C->getBuffer()->getBufferIdentifier();
Chris Lattner6f9fa5a2009-02-04 01:55:42 +0000797 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second);
798 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second);
799 SourceLocation IncludeLoc = FI.getIncludeLoc();
Chris Lattner836774b2009-01-27 07:57:44 +0000800
Chris Lattner6f9fa5a2009-02-04 01:55:42 +0000801 // If we have #line directives in this file, update and overwrite the physical
802 // location info if appropriate.
803 if (FI.hasLineDirectives()) {
804 assert(LineTable && "Can't have linetable entries without a LineTable!");
805 // See if there is a #line directive before this. If so, get it.
806 if (const LineEntry *Entry =
807 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) {
Chris Lattner74ae2d92009-02-04 02:00:59 +0000808 // If the LineEntry indicates a filename, use it.
Chris Lattner6f9fa5a2009-02-04 01:55:42 +0000809 if (Entry->FilenameID != -1)
810 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattner74ae2d92009-02-04 02:00:59 +0000811
812 // Use the line number specified by the LineEntry. This line number may
813 // be multiple lines down from the line entry. Add the difference in
814 // physical line numbers from the query point and the line marker to the
815 // total.
816 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
817 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
818
Chris Lattneraabd3222009-02-04 02:15:40 +0000819 // Note that column numbers are not molested by line markers.
Chris Lattner778ae212009-02-04 06:25:26 +0000820
821 // Handle virtual #include manipulation.
822 if (Entry->IncludeOffset) {
823 IncludeLoc = getLocForStartOfFile(LocInfo.first);
824 IncludeLoc = IncludeLoc.getFileLocWithOffset(Entry->IncludeOffset);
825 }
Chris Lattner6f9fa5a2009-02-04 01:55:42 +0000826 }
827 }
828
829 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattner27c0ced2009-01-26 00:43:02 +0000830}
831
832//===----------------------------------------------------------------------===//
833// Other miscellaneous methods.
834//===----------------------------------------------------------------------===//
835
836
Chris Lattner4b009652007-07-25 00:24:17 +0000837/// PrintStats - Print statistics to stderr.
838///
839void SourceManager::PrintStats() const {
Ted Kremenekda29d8c2007-12-05 22:21:13 +0000840 llvm::cerr << "\n*** Source Manager Stats:\n";
841 llvm::cerr << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
Chris Lattner66284fd2009-01-27 05:22:43 +0000842 << " mem buffers mapped.\n";
843 llvm::cerr << SLocEntryTable.size() << " SLocEntry's allocated, "
844 << NextOffset << "B of Sloc address space used.\n";
Chris Lattner4b009652007-07-25 00:24:17 +0000845
Chris Lattner4b009652007-07-25 00:24:17 +0000846 unsigned NumLineNumsComputed = 0;
847 unsigned NumFileBytesMapped = 0;
Chris Lattner8dedb842009-02-03 07:30:45 +0000848 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
849 NumLineNumsComputed += I->second->SourceLineCache != 0;
850 NumFileBytesMapped += I->second->getSizeBytesMapped();
Chris Lattner4b009652007-07-25 00:24:17 +0000851 }
Ted Kremenekdd364ea2007-10-30 21:08:08 +0000852
Ted Kremenekda29d8c2007-12-05 22:21:13 +0000853 llvm::cerr << NumFileBytesMapped << " bytes of files mapped, "
854 << NumLineNumsComputed << " files with line #'s computed.\n";
Chris Lattner27c0ced2009-01-26 00:43:02 +0000855 llvm::cerr << "FileID scans: " << NumLinearScans << " linear, "
856 << NumBinaryProbes << " binary.\n";
Chris Lattner4b009652007-07-25 00:24:17 +0000857}
Ted Kremenek0ad06d12007-12-04 19:39:02 +0000858
859//===----------------------------------------------------------------------===//
860// Serialization.
861//===----------------------------------------------------------------------===//
Ted Kremenek9c856e92007-12-05 00:14:18 +0000862
863void ContentCache::Emit(llvm::Serializer& S) const {
Ted Kremenek0ad06d12007-12-04 19:39:02 +0000864 S.FlushRecord();
865 S.EmitPtr(this);
Ted Kremenek0ad06d12007-12-04 19:39:02 +0000866
Ted Kremenek1b6dd6f2007-12-18 22:12:19 +0000867 if (Entry) {
868 llvm::sys::Path Fname(Buffer->getBufferIdentifier());
869
870 if (Fname.isAbsolute())
871 S.EmitCStr(Fname.c_str());
872 else {
873 // Create an absolute path.
874 // FIXME: This will potentially contain ".." and "." in the path.
875 llvm::sys::Path path = llvm::sys::Path::GetCurrentDirectory();
876 path.appendComponent(Fname.c_str());
877 S.EmitCStr(path.c_str());
878 }
879 }
Ted Kremenek9c856e92007-12-05 00:14:18 +0000880 else {
Ted Kremenek0ad06d12007-12-04 19:39:02 +0000881 const char* p = Buffer->getBufferStart();
882 const char* e = Buffer->getBufferEnd();
883
Ted Kremenek9c856e92007-12-05 00:14:18 +0000884 S.EmitInt(e-p);
885
Ted Kremenek0ad06d12007-12-04 19:39:02 +0000886 for ( ; p != e; ++p)
Ted Kremenek9c856e92007-12-05 00:14:18 +0000887 S.EmitInt(*p);
Ted Kremenek0ad06d12007-12-04 19:39:02 +0000888 }
889
Ted Kremenek9c856e92007-12-05 00:14:18 +0000890 S.FlushRecord();
Ted Kremenek0ad06d12007-12-04 19:39:02 +0000891}
Ted Kremenek9c856e92007-12-05 00:14:18 +0000892
893void ContentCache::ReadToSourceManager(llvm::Deserializer& D,
894 SourceManager& SMgr,
895 FileManager* FMgr,
896 std::vector<char>& Buf) {
897 if (FMgr) {
898 llvm::SerializedPtrID PtrID = D.ReadPtrID();
899 D.ReadCStr(Buf,false);
900
901 // Create/fetch the FileEntry.
902 const char* start = &Buf[0];
903 const FileEntry* E = FMgr->getFile(start,start+Buf.size());
904
Ted Kremenekb92cd872007-12-13 18:12:10 +0000905 // FIXME: Ideally we want a lazy materialization of the ContentCache
906 // anyway, because we don't want to read in source files unless this
907 // is absolutely needed.
908 if (!E)
909 D.RegisterPtr(PtrID,NULL);
Nico Weber630347d2008-09-29 00:25:48 +0000910 else
Ted Kremenekb92cd872007-12-13 18:12:10 +0000911 // Get the ContextCache object and register it with the deserializer.
Chris Lattner27c0ced2009-01-26 00:43:02 +0000912 D.RegisterPtr(PtrID, SMgr.getOrCreateContentCache(E));
913 return;
Ted Kremenek9c856e92007-12-05 00:14:18 +0000914 }
Chris Lattner27c0ced2009-01-26 00:43:02 +0000915
916 // Register the ContextCache object with the deserializer.
Chris Lattner8dedb842009-02-03 07:30:45 +0000917 /* FIXME:
918 ContentCache *Entry
Chris Lattner27c0ced2009-01-26 00:43:02 +0000919 SMgr.MemBufferInfos.push_back(ContentCache());
Chris Lattner8dedb842009-02-03 07:30:45 +0000920 = const_cast<ContentCache&>(SMgr.MemBufferInfos.back());
Chris Lattner27c0ced2009-01-26 00:43:02 +0000921 D.RegisterPtr(&Entry);
922
923 // Create the buffer.
924 unsigned Size = D.ReadInt();
925 Entry.Buffer = MemoryBuffer::getNewUninitMemBuffer(Size);
926
927 // Read the contents of the buffer.
928 char* p = const_cast<char*>(Entry.Buffer->getBufferStart());
929 for (unsigned i = 0; i < Size ; ++i)
930 p[i] = D.ReadInt();
Chris Lattner8dedb842009-02-03 07:30:45 +0000931 */
Ted Kremenek9c856e92007-12-05 00:14:18 +0000932}
933
934void SourceManager::Emit(llvm::Serializer& S) const {
Ted Kremenekbc54abf2007-12-05 00:19:51 +0000935 S.EnterBlock();
936 S.EmitPtr(this);
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000937 S.EmitInt(MainFileID.getOpaqueValue());
Ted Kremenekbc54abf2007-12-05 00:19:51 +0000938
Ted Kremenek9c856e92007-12-05 00:14:18 +0000939 // Emit: FileInfos. Just emit the file name.
940 S.EnterBlock();
941
Chris Lattner8dedb842009-02-03 07:30:45 +0000942 // FIXME: Emit FileInfos.
943 //std::for_each(FileInfos.begin(), FileInfos.end(),
944 // S.MakeEmitter<ContentCache>());
Ted Kremenek9c856e92007-12-05 00:14:18 +0000945
946 S.ExitBlock();
947
948 // Emit: MemBufferInfos
949 S.EnterBlock();
950
Chris Lattner8dedb842009-02-03 07:30:45 +0000951 /* FIXME: EMIT.
Ted Kremenek9c856e92007-12-05 00:14:18 +0000952 std::for_each(MemBufferInfos.begin(), MemBufferInfos.end(),
953 S.MakeEmitter<ContentCache>());
Chris Lattner8dedb842009-02-03 07:30:45 +0000954 */
Ted Kremenek9c856e92007-12-05 00:14:18 +0000955
956 S.ExitBlock();
957
Chris Lattner27c0ced2009-01-26 00:43:02 +0000958 // FIXME: Emit SLocEntryTable.
Ted Kremenekbc54abf2007-12-05 00:19:51 +0000959
960 S.ExitBlock();
Ted Kremenek9c856e92007-12-05 00:14:18 +0000961}
962
Ted Kremenekbc54abf2007-12-05 00:19:51 +0000963SourceManager*
Chris Lattnerfa45efd2009-02-04 00:40:31 +0000964SourceManager::CreateAndRegister(llvm::Deserializer &D, FileManager &FMgr) {
Ted Kremenekbc54abf2007-12-05 00:19:51 +0000965 SourceManager *M = new SourceManager();
966 D.RegisterPtr(M);
967
Ted Kremenek2578dd02007-12-19 22:29:55 +0000968 // Read: the FileID of the main source file of the translation unit.
Chris Lattner27c0ced2009-01-26 00:43:02 +0000969 M->MainFileID = FileID::get(D.ReadInt());
Ted Kremenek2578dd02007-12-19 22:29:55 +0000970
Ted Kremenek9c856e92007-12-05 00:14:18 +0000971 std::vector<char> Buf;
972
Chris Lattner8dedb842009-02-03 07:30:45 +0000973 /*{ // FIXME Read: FileInfos.
Ted Kremenek9c856e92007-12-05 00:14:18 +0000974 llvm::Deserializer::Location BLoc = D.getCurrentBlockLocation();
975 while (!D.FinishedBlock(BLoc))
Ted Kremenekbc54abf2007-12-05 00:19:51 +0000976 ContentCache::ReadToSourceManager(D,*M,&FMgr,Buf);
Chris Lattner8dedb842009-02-03 07:30:45 +0000977 }*/
Ted Kremenek9c856e92007-12-05 00:14:18 +0000978
Douglas Gregordf7b8912009-04-02 23:40:00 +0000979 /*{ // FIXME Read: MemBufferInfos.
Ted Kremenek9c856e92007-12-05 00:14:18 +0000980 llvm::Deserializer::Location BLoc = D.getCurrentBlockLocation();
981 while (!D.FinishedBlock(BLoc))
Ted Kremenekbc54abf2007-12-05 00:19:51 +0000982 ContentCache::ReadToSourceManager(D,*M,NULL,Buf);
Douglas Gregordf7b8912009-04-02 23:40:00 +0000983 }*/
Ted Kremenek9c856e92007-12-05 00:14:18 +0000984
Chris Lattner27c0ced2009-01-26 00:43:02 +0000985 // FIXME: Read SLocEntryTable.
Ted Kremenekbc54abf2007-12-05 00:19:51 +0000986
987 return M;
Ted Kremenek12206af2007-12-10 18:01:25 +0000988}