blob: 275d520e04473f96928cec811d65f3c7f9eda6b8 [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"
15#include "clang/Basic/FileManager.h"
Chris Lattner5e36a7a2007-07-24 05:57:19 +000016#include "llvm/Support/Compiler.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "llvm/Support/MemoryBuffer.h"
18#include "llvm/System/Path.h"
Ted Kremenek78d85f52007-10-30 21:08:08 +000019#include "llvm/Bitcode/Serialize.h"
20#include "llvm/Bitcode/Deserialize.h"
Ted Kremenek665dd4a2007-12-05 22:21:13 +000021#include "llvm/Support/Streams.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include <algorithm>
Reid Spencer5f016e22007-07-11 17:01:13 +000023using namespace clang;
24using namespace SrcMgr;
25using llvm::MemoryBuffer;
26
Chris Lattner23b5dc62009-02-04 00:40:31 +000027//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +000028// SourceManager Helper Classes
Chris Lattner23b5dc62009-02-04 00:40:31 +000029//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +000030
Ted Kremenek78d85f52007-10-30 21:08:08 +000031ContentCache::~ContentCache() {
32 delete Buffer;
Reid Spencer5f016e22007-07-11 17:01:13 +000033}
34
Ted Kremenekc16c2082009-01-06 01:55:26 +000035/// getSizeBytesMapped - Returns the number of bytes actually mapped for
36/// this ContentCache. This can be 0 if the MemBuffer was not actually
37/// instantiated.
38unsigned ContentCache::getSizeBytesMapped() const {
39 return Buffer ? Buffer->getBufferSize() : 0;
40}
41
42/// getSize - Returns the size of the content encapsulated by this ContentCache.
43/// This can be the size of the source file or the size of an arbitrary
44/// scratch buffer. If the ContentCache encapsulates a source file, that
45/// file is not lazily brought in from disk to satisfy this query.
46unsigned ContentCache::getSize() const {
47 return Entry ? Entry->getSize() : Buffer->getBufferSize();
48}
49
Chris Lattner987cd3d2009-01-26 07:37:49 +000050const llvm::MemoryBuffer *ContentCache::getBuffer() const {
Ted Kremenek5b034ad2009-01-06 22:43:04 +000051 // Lazily create the Buffer for ContentCaches that wrap files.
52 if (!Buffer && Entry) {
53 // FIXME: Should we support a way to not have to do this check over
54 // and over if we cannot open the file?
Chris Lattner05816592009-01-17 03:54:16 +000055 Buffer = MemoryBuffer::getFile(Entry->getName(), 0, Entry->getSize());
Ted Kremenek5b034ad2009-01-06 22:43:04 +000056 }
Ted Kremenekc16c2082009-01-06 01:55:26 +000057 return Buffer;
58}
59
Chris Lattner23b5dc62009-02-04 00:40:31 +000060//===----------------------------------------------------------------------===//
Chris Lattner5b9a5042009-01-26 07:57:50 +000061// Line Table Implementation
Chris Lattner23b5dc62009-02-04 00:40:31 +000062//===----------------------------------------------------------------------===//
Chris Lattner5b9a5042009-01-26 07:57:50 +000063
64namespace clang {
Chris Lattner23b5dc62009-02-04 00:40:31 +000065struct LineEntry {
66 /// FileOffset - The offset in this file that the line entry occurs at.
67 unsigned FileOffset;
Chris Lattner9d79eba2009-02-04 05:21:58 +000068
Chris Lattner23b5dc62009-02-04 00:40:31 +000069 /// LineNo - The presumed line number of this line entry: #line 4.
70 unsigned LineNo;
Chris Lattner9d79eba2009-02-04 05:21:58 +000071
Chris Lattner23b5dc62009-02-04 00:40:31 +000072 /// FilenameID - The ID of the filename identified by this line entry:
73 /// #line 4 "foo.c". This is -1 if not specified.
74 int FilenameID;
75
Chris Lattner9d79eba2009-02-04 05:21:58 +000076 /// Flags - Set the 0 if no flags, 1 if a system header,
77 SrcMgr::CharacteristicKind FileKind;
78
79 static LineEntry get(unsigned Offs, unsigned Line, int Filename,
80 SrcMgr::CharacteristicKind FileKind) {
Chris Lattner23b5dc62009-02-04 00:40:31 +000081 LineEntry E;
82 E.FileOffset = Offs;
83 E.LineNo = Line;
84 E.FilenameID = Filename;
85 return E;
86 }
87};
Chris Lattner6c1fbe02009-02-04 04:46:59 +000088
89inline bool operator<(const LineEntry &E, unsigned Offset) {
90 return E.FileOffset < Offset;
91}
92
93inline bool operator<(unsigned Offset, const LineEntry &E) {
94 return Offset < E.FileOffset;
95}
Chris Lattner23b5dc62009-02-04 00:40:31 +000096
Chris Lattner5b9a5042009-01-26 07:57:50 +000097/// LineTableInfo - This class is used to hold and unique data used to
98/// represent #line information.
99class LineTableInfo {
100 /// FilenameIDs - This map is used to assign unique IDs to filenames in
101 /// #line directives. This allows us to unique the filenames that
102 /// frequently reoccur and reference them with indices. FilenameIDs holds
103 /// the mapping from string -> ID, and FilenamesByID holds the mapping of ID
104 /// to string.
105 llvm::StringMap<unsigned, llvm::BumpPtrAllocator> FilenameIDs;
106 std::vector<llvm::StringMapEntry<unsigned>*> FilenamesByID;
Chris Lattner23b5dc62009-02-04 00:40:31 +0000107
108 /// LineEntries - This is a map from FileIDs to a list of line entries (sorted
109 /// by the offset they occur in the file.
110 std::map<unsigned, std::vector<LineEntry> > LineEntries;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000111public:
112 LineTableInfo() {
113 }
114
115 void clear() {
116 FilenameIDs.clear();
117 FilenamesByID.clear();
118 }
119
120 ~LineTableInfo() {}
121
122 unsigned getLineTableFilenameID(const char *Ptr, unsigned Len);
Chris Lattner3cd949c2009-02-04 01:55:42 +0000123 const char *getFilename(unsigned ID) const {
124 assert(ID < FilenamesByID.size() && "Invalid FilenameID");
125 return FilenamesByID[ID]->getKeyData();
126 }
127
Chris Lattner23b5dc62009-02-04 00:40:31 +0000128 void AddLineNote(unsigned FID, unsigned Offset,
Chris Lattnerac50e342009-02-03 22:13:05 +0000129 unsigned LineNo, int FilenameID);
Chris Lattner9d79eba2009-02-04 05:21:58 +0000130 void AddLineNote(unsigned FID, unsigned Offset,
131 unsigned LineNo, int FilenameID,
132 unsigned EntryExit, SrcMgr::CharacteristicKind FileKind);
133
Chris Lattner3cd949c2009-02-04 01:55:42 +0000134
135 /// FindNearestLineEntry - Find the line entry nearest to FID that is before
136 /// it. If there is no line entry before Offset in FID, return null.
137 const LineEntry *FindNearestLineEntry(unsigned FID, unsigned Offset);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000138};
139} // namespace clang
140
Chris Lattner5b9a5042009-01-26 07:57:50 +0000141unsigned LineTableInfo::getLineTableFilenameID(const char *Ptr, unsigned Len) {
142 // Look up the filename in the string table, returning the pre-existing value
143 // if it exists.
144 llvm::StringMapEntry<unsigned> &Entry =
145 FilenameIDs.GetOrCreateValue(Ptr, Ptr+Len, ~0U);
146 if (Entry.getValue() != ~0U)
147 return Entry.getValue();
148
149 // Otherwise, assign this the next available ID.
150 Entry.setValue(FilenamesByID.size());
151 FilenamesByID.push_back(&Entry);
152 return FilenamesByID.size()-1;
153}
154
Chris Lattnerac50e342009-02-03 22:13:05 +0000155/// AddLineNote - Add a line note to the line table that indicates that there
156/// is a #line at the specified FID/Offset location which changes the presumed
157/// location to LineNo/FilenameID.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000158void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
Chris Lattnerac50e342009-02-03 22:13:05 +0000159 unsigned LineNo, int FilenameID) {
Chris Lattner23b5dc62009-02-04 00:40:31 +0000160 std::vector<LineEntry> &Entries = LineEntries[FID];
Chris Lattnerac50e342009-02-03 22:13:05 +0000161
Chris Lattner23b5dc62009-02-04 00:40:31 +0000162 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
163 "Adding line entries out of order!");
Chris Lattner3cd949c2009-02-04 01:55:42 +0000164
Chris Lattner9d79eba2009-02-04 05:21:58 +0000165 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
Chris Lattner3cd949c2009-02-04 01:55:42 +0000166
Chris Lattner9d79eba2009-02-04 05:21:58 +0000167 if (!Entries.empty()) {
168 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
169 // that we are still in "foo.h".
170 if (FilenameID == -1)
171 FilenameID = Entries.back().FilenameID;
172
173 // If we are after a line marker that switched us to system header mode,
174 // preserve it.
175 Kind = Entries.back().FileKind;
176 }
177
178 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind));
Chris Lattnerac50e342009-02-03 22:13:05 +0000179}
180
Chris Lattner9d79eba2009-02-04 05:21:58 +0000181/// AddLineNote This is the same as the previous version of AddLineNote, but is
182/// used for GNU line markers. If EntryExit is 0, then this doesn't change the
183/// presumed #include stack. If it is 1, this is a file entry, if it is 2 then
184/// this is a file exit. FileKind specifies whether this is a system header or
185/// extern C system header.
186void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
187 unsigned LineNo, int FilenameID,
188 unsigned EntryExit,
189 SrcMgr::CharacteristicKind FileKind) {
190 assert(FilenameID != -1 && "Unspecified filename should use other accessor");
191
192 std::vector<LineEntry> &Entries = LineEntries[FID];
193
194 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
195 "Adding line entries out of order!");
196
197
198 // TODO: Handle EntryExit.
199
200 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind));
201}
202
203
Chris Lattner3cd949c2009-02-04 01:55:42 +0000204/// FindNearestLineEntry - Find the line entry nearest to FID that is before
205/// it. If there is no line entry before Offset in FID, return null.
206const LineEntry *LineTableInfo::FindNearestLineEntry(unsigned FID,
207 unsigned Offset) {
208 const std::vector<LineEntry> &Entries = LineEntries[FID];
209 assert(!Entries.empty() && "No #line entries for this FID after all!");
210
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000211 // It is very common for the query to be after the last #line, check this
212 // first.
213 if (Entries.back().FileOffset <= Offset)
214 return &Entries.back();
Chris Lattner3cd949c2009-02-04 01:55:42 +0000215
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000216 // Do a binary search to find the maximal element that is still before Offset.
217 std::vector<LineEntry>::const_iterator I =
218 std::upper_bound(Entries.begin(), Entries.end(), Offset);
219 if (I == Entries.begin()) return 0;
220 return &*--I;
Chris Lattner3cd949c2009-02-04 01:55:42 +0000221}
Chris Lattnerac50e342009-02-03 22:13:05 +0000222
223
Chris Lattner5b9a5042009-01-26 07:57:50 +0000224/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
225///
226unsigned SourceManager::getLineTableFilenameID(const char *Ptr, unsigned Len) {
227 if (LineTable == 0)
228 LineTable = new LineTableInfo();
229 return LineTable->getLineTableFilenameID(Ptr, Len);
230}
231
232
Chris Lattner4c4ea172009-02-03 21:52:55 +0000233/// AddLineNote - Add a line note to the line table for the FileID and offset
234/// specified by Loc. If FilenameID is -1, it is considered to be
235/// unspecified.
236void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
237 int FilenameID) {
Chris Lattnerac50e342009-02-03 22:13:05 +0000238 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Chris Lattner4c4ea172009-02-03 21:52:55 +0000239
Chris Lattnerac50e342009-02-03 22:13:05 +0000240 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
241
242 // Remember that this file has #line directives now if it doesn't already.
243 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
244
245 if (LineTable == 0)
246 LineTable = new LineTableInfo();
Chris Lattner23b5dc62009-02-04 00:40:31 +0000247 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID);
Chris Lattner4c4ea172009-02-03 21:52:55 +0000248}
249
Chris Lattner9d79eba2009-02-04 05:21:58 +0000250/// AddLineNote - Add a GNU line marker to the line table.
251void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
252 int FilenameID, bool IsFileEntry,
253 bool IsFileExit, bool IsSystemHeader,
254 bool IsExternCHeader) {
255 // If there is no filename and no flags, this is treated just like a #line,
256 // which does not change the flags of the previous line marker.
257 if (FilenameID == -1) {
258 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
259 "Can't set flags without setting the filename!");
260 return AddLineNote(Loc, LineNo, FilenameID);
261 }
262
263 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
264 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
265
266 // Remember that this file has #line directives now if it doesn't already.
267 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
268
269 if (LineTable == 0)
270 LineTable = new LineTableInfo();
271
272 SrcMgr::CharacteristicKind FileKind;
273 if (IsExternCHeader)
274 FileKind = SrcMgr::C_ExternCSystem;
275 else if (IsSystemHeader)
276 FileKind = SrcMgr::C_System;
277 else
278 FileKind = SrcMgr::C_User;
279
280 unsigned EntryExit = 0;
281 if (IsFileEntry)
282 EntryExit = 1;
283 else if (IsFileExit)
284 EntryExit = 2;
285
286 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID,
287 EntryExit, FileKind);
288}
289
Chris Lattner4c4ea172009-02-03 21:52:55 +0000290
Chris Lattner23b5dc62009-02-04 00:40:31 +0000291//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000292// Private 'Create' methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000293//===----------------------------------------------------------------------===//
Ted Kremenekc16c2082009-01-06 01:55:26 +0000294
Chris Lattner5b9a5042009-01-26 07:57:50 +0000295SourceManager::~SourceManager() {
296 delete LineTable;
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000297
298 // Delete FileEntry objects corresponding to content caches. Since the actual
299 // content cache objects are bump pointer allocated, we just have to run the
300 // dtors, but we call the deallocate method for completeness.
301 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
302 MemBufferInfos[i]->~ContentCache();
303 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
304 }
305 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
306 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
307 I->second->~ContentCache();
308 ContentCacheAlloc.Deallocate(I->second);
309 }
Chris Lattner5b9a5042009-01-26 07:57:50 +0000310}
311
312void SourceManager::clearIDTables() {
313 MainFileID = FileID();
314 SLocEntryTable.clear();
315 LastLineNoFileIDQuery = FileID();
316 LastLineNoContentCache = 0;
317 LastFileIDLookup = FileID();
318
319 if (LineTable)
320 LineTable->clear();
321
322 // Use up FileID #0 as an invalid instantiation.
323 NextOffset = 0;
324 createInstantiationLoc(SourceLocation(), SourceLocation(), 1);
325}
326
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000327/// getOrCreateContentCache - Create or return a cached ContentCache for the
328/// specified file.
329const ContentCache *
330SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000331 assert(FileEnt && "Didn't specify a file entry to use?");
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000332
Reid Spencer5f016e22007-07-11 17:01:13 +0000333 // Do we already have information about this file?
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000334 ContentCache *&Entry = FileInfos[FileEnt];
335 if (Entry) return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000336
Chris Lattner00282d62009-02-03 07:41:46 +0000337 // Nope, create a new Cache entry. Make sure it is at least 8-byte aligned
338 // so that FileInfo can use the low 3 bits of the pointer for its own
339 // nefarious purposes.
340 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
341 EntryAlign = std::max(8U, EntryAlign);
342 Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000343 new (Entry) ContentCache(FileEnt);
344 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000345}
346
347
Ted Kremenekd1c0eee2007-10-31 17:53:38 +0000348/// createMemBufferContentCache - Create a new ContentCache for the specified
349/// memory buffer. This does no caching.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000350const ContentCache*
351SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
Chris Lattner00282d62009-02-03 07:41:46 +0000352 // Add a new ContentCache to the MemBufferInfos list and return it. Make sure
353 // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of
354 // the pointer for its own nefarious purposes.
355 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
356 EntryAlign = std::max(8U, EntryAlign);
357 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000358 new (Entry) ContentCache();
359 MemBufferInfos.push_back(Entry);
360 Entry->setBuffer(Buffer);
361 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000362}
363
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000364//===----------------------------------------------------------------------===//
365// Methods to create new FileID's and instantiations.
366//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000367
Nico Weber48002c82008-09-29 00:25:48 +0000368/// createFileID - Create a new fileID for the specified ContentCache and
Ted Kremenek0d892d82007-10-30 22:57:35 +0000369/// include position. This works regardless of whether the ContentCache
370/// corresponds to a file or some other input source.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000371FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000372 SourceLocation IncludePos,
373 SrcMgr::CharacteristicKind FileCharacter) {
374 SLocEntryTable.push_back(SLocEntry::get(NextOffset,
375 FileInfo::get(IncludePos, File,
376 FileCharacter)));
Ted Kremenekc16c2082009-01-06 01:55:26 +0000377 unsigned FileSize = File->getSize();
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000378 assert(NextOffset+FileSize+1 > NextOffset && "Ran out of source locations!");
379 NextOffset += FileSize+1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000380
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000381 // Set LastFileIDLookup to the newly created file. The next getFileID call is
382 // almost guaranteed to be from that file.
383 return LastFileIDLookup = FileID::get(SLocEntryTable.size()-1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000384}
385
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000386/// createInstantiationLoc - Return a new SourceLocation that encodes the fact
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000387/// that a token from SpellingLoc should actually be referenced from
Reid Spencer5f016e22007-07-11 17:01:13 +0000388/// InstantiationLoc.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000389SourceLocation SourceManager::createInstantiationLoc(SourceLocation SpellingLoc,
390 SourceLocation InstantLoc,
391 unsigned TokLength) {
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000392 SLocEntryTable.push_back(SLocEntry::get(NextOffset,
393 InstantiationInfo::get(InstantLoc,
394 SpellingLoc)));
395 assert(NextOffset+TokLength+1 > NextOffset && "Ran out of source locations!");
396 NextOffset += TokLength+1;
397 return SourceLocation::getMacroLoc(NextOffset-(TokLength+1));
Reid Spencer5f016e22007-07-11 17:01:13 +0000398}
399
Chris Lattner31530ba2009-01-19 07:32:13 +0000400/// getBufferData - Return a pointer to the start and end of the source buffer
401/// data for the specified FileID.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000402std::pair<const char*, const char*>
403SourceManager::getBufferData(FileID FID) const {
404 const llvm::MemoryBuffer *Buf = getBuffer(FID);
405 return std::make_pair(Buf->getBufferStart(), Buf->getBufferEnd());
406}
407
408
Chris Lattner23b5dc62009-02-04 00:40:31 +0000409//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000410// SourceLocation manipulation methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000411//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000412
413/// getFileIDSlow - Return the FileID for a SourceLocation. This is a very hot
414/// method that is used for all SourceManager queries that start with a
415/// SourceLocation object. It is responsible for finding the entry in
416/// SLocEntryTable which contains the specified location.
417///
418FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
419 assert(SLocOffset && "Invalid FileID");
420
421 // After the first and second level caches, I see two common sorts of
422 // behavior: 1) a lot of searched FileID's are "near" the cached file location
423 // or are "near" the cached instantiation location. 2) others are just
424 // completely random and may be a very long way away.
425 //
426 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
427 // then we fall back to a less cache efficient, but more scalable, binary
428 // search to find the location.
429
430 // See if this is near the file point - worst case we start scanning from the
431 // most newly created FileID.
432 std::vector<SrcMgr::SLocEntry>::const_iterator I;
433
434 if (SLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
435 // Neither loc prunes our search.
436 I = SLocEntryTable.end();
437 } else {
438 // Perhaps it is near the file point.
439 I = SLocEntryTable.begin()+LastFileIDLookup.ID;
440 }
441
442 // Find the FileID that contains this. "I" is an iterator that points to a
443 // FileID whose offset is known to be larger than SLocOffset.
444 unsigned NumProbes = 0;
445 while (1) {
446 --I;
447 if (I->getOffset() <= SLocOffset) {
448#if 0
449 printf("lin %d -> %d [%s] %d %d\n", SLocOffset,
450 I-SLocEntryTable.begin(),
451 I->isInstantiation() ? "inst" : "file",
452 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
453#endif
454 FileID Res = FileID::get(I-SLocEntryTable.begin());
455
456 // If this isn't an instantiation, remember it. We have good locality
457 // across FileID lookups.
458 if (!I->isInstantiation())
459 LastFileIDLookup = Res;
460 NumLinearScans += NumProbes+1;
461 return Res;
462 }
463 if (++NumProbes == 8)
464 break;
465 }
466
467 // Convert "I" back into an index. We know that it is an entry whose index is
468 // larger than the offset we are looking for.
469 unsigned GreaterIndex = I-SLocEntryTable.begin();
470 // LessIndex - This is the lower bound of the range that we're searching.
471 // We know that the offset corresponding to the FileID is is less than
472 // SLocOffset.
473 unsigned LessIndex = 0;
474 NumProbes = 0;
475 while (1) {
476 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
477 unsigned MidOffset = SLocEntryTable[MiddleIndex].getOffset();
478
479 ++NumProbes;
480
481 // If the offset of the midpoint is too large, chop the high side of the
482 // range to the midpoint.
483 if (MidOffset > SLocOffset) {
484 GreaterIndex = MiddleIndex;
485 continue;
486 }
487
488 // If the middle index contains the value, succeed and return.
489 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
490#if 0
491 printf("bin %d -> %d [%s] %d %d\n", SLocOffset,
492 I-SLocEntryTable.begin(),
493 I->isInstantiation() ? "inst" : "file",
494 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
495#endif
496 FileID Res = FileID::get(MiddleIndex);
497
498 // If this isn't an instantiation, remember it. We have good locality
499 // across FileID lookups.
500 if (!I->isInstantiation())
501 LastFileIDLookup = Res;
502 NumBinaryProbes += NumProbes;
503 return Res;
504 }
505
506 // Otherwise, move the low-side up to the middle index.
507 LessIndex = MiddleIndex;
508 }
509}
510
Chris Lattneraddb7972009-01-26 20:04:19 +0000511SourceLocation SourceManager::
512getInstantiationLocSlowCase(SourceLocation Loc) const {
513 do {
514 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
515 Loc =getSLocEntry(LocInfo.first).getInstantiation().getInstantiationLoc();
516 Loc = Loc.getFileLocWithOffset(LocInfo.second);
517 } while (!Loc.isFileID());
518
519 return Loc;
520}
521
522SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
523 do {
524 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
525 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
526 Loc = Loc.getFileLocWithOffset(LocInfo.second);
527 } while (!Loc.isFileID());
528 return Loc;
529}
530
531
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000532std::pair<FileID, unsigned>
533SourceManager::getDecomposedInstantiationLocSlowCase(const SrcMgr::SLocEntry *E,
534 unsigned Offset) const {
535 // If this is an instantiation record, walk through all the instantiation
536 // points.
537 FileID FID;
538 SourceLocation Loc;
539 do {
540 Loc = E->getInstantiation().getInstantiationLoc();
541
542 FID = getFileID(Loc);
543 E = &getSLocEntry(FID);
544 Offset += Loc.getOffset()-E->getOffset();
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000545 } while (!Loc.isFileID());
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000546
547 return std::make_pair(FID, Offset);
548}
549
550std::pair<FileID, unsigned>
551SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
552 unsigned Offset) const {
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000553 // If this is an instantiation record, walk through all the instantiation
554 // points.
555 FileID FID;
556 SourceLocation Loc;
557 do {
558 Loc = E->getInstantiation().getSpellingLoc();
559
560 FID = getFileID(Loc);
561 E = &getSLocEntry(FID);
562 Offset += Loc.getOffset()-E->getOffset();
563 } while (!Loc.isFileID());
564
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000565 return std::make_pair(FID, Offset);
566}
567
568
569//===----------------------------------------------------------------------===//
570// Queries about the code at a SourceLocation.
571//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000572
573/// getCharacterData - Return a pointer to the start of the specified location
574/// in the appropriate MemoryBuffer.
575const char *SourceManager::getCharacterData(SourceLocation SL) const {
576 // Note that this is a hot function in the getSpelling() path, which is
577 // heavily used by -E mode.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000578 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Chris Lattner2b2453a2009-01-17 06:22:33 +0000579
Ted Kremenekc16c2082009-01-06 01:55:26 +0000580 // Note that calling 'getBuffer()' may lazily page in a source file.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000581 return getSLocEntry(LocInfo.first).getFile().getContentCache()
582 ->getBuffer()->getBufferStart() + LocInfo.second;
Reid Spencer5f016e22007-07-11 17:01:13 +0000583}
584
Reid Spencer5f016e22007-07-11 17:01:13 +0000585
Chris Lattner9dc1f532007-07-20 16:37:10 +0000586/// getColumnNumber - Return the column # for the specified file position.
Chris Lattner7da5aea2009-02-04 00:55:58 +0000587/// this is significantly cheaper to compute than the line number.
588unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos) const {
589 const char *Buf = getBuffer(FID)->getBufferStart();
Reid Spencer5f016e22007-07-11 17:01:13 +0000590
Reid Spencer5f016e22007-07-11 17:01:13 +0000591 unsigned LineStart = FilePos;
592 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
593 --LineStart;
594 return FilePos-LineStart+1;
595}
596
Chris Lattner7da5aea2009-02-04 00:55:58 +0000597unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000598 if (Loc.isInvalid()) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000599 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
600 return getColumnNumber(LocInfo.first, LocInfo.second);
601}
602
603unsigned SourceManager::getInstantiationColumnNumber(SourceLocation Loc) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000604 if (Loc.isInvalid()) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000605 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
606 return getColumnNumber(LocInfo.first, LocInfo.second);
607}
608
609
610
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000611static void ComputeLineNumbers(ContentCache* FI,
612 llvm::BumpPtrAllocator &Alloc) DISABLE_INLINE;
613static void ComputeLineNumbers(ContentCache* FI, llvm::BumpPtrAllocator &Alloc){
Ted Kremenekc16c2082009-01-06 01:55:26 +0000614 // Note that calling 'getBuffer()' may lazily page in the file.
615 const MemoryBuffer *Buffer = FI->getBuffer();
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000616
617 // Find the file offsets of all of the *physical* source lines. This does
618 // not look at trigraphs, escaped newlines, or anything else tricky.
619 std::vector<unsigned> LineOffsets;
620
621 // Line #1 starts at char 0.
622 LineOffsets.push_back(0);
623
624 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
625 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
626 unsigned Offs = 0;
627 while (1) {
628 // Skip over the contents of the line.
629 // TODO: Vectorize this? This is very performance sensitive for programs
630 // with lots of diagnostics and in -E mode.
631 const unsigned char *NextBuf = (const unsigned char *)Buf;
632 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
633 ++NextBuf;
634 Offs += NextBuf-Buf;
635 Buf = NextBuf;
636
637 if (Buf[0] == '\n' || Buf[0] == '\r') {
638 // If this is \n\r or \r\n, skip both characters.
639 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
640 ++Offs, ++Buf;
641 ++Offs, ++Buf;
642 LineOffsets.push_back(Offs);
643 } else {
644 // Otherwise, this is a null. If end of file, exit.
645 if (Buf == End) break;
646 // Otherwise, skip the null.
647 ++Offs, ++Buf;
648 }
649 }
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000650
651 // Copy the offsets into the FileInfo structure.
652 FI->NumLines = LineOffsets.size();
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000653 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000654 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
655}
Reid Spencer5f016e22007-07-11 17:01:13 +0000656
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000657/// getLineNumber - Given a SourceLocation, return the spelling line number
Reid Spencer5f016e22007-07-11 17:01:13 +0000658/// for the position indicated. This requires building and caching a table of
659/// line offsets for the MemoryBuffer, so this is not cheap: use only when
660/// about to emit a diagnostic.
Chris Lattner30fc9332009-02-04 01:06:56 +0000661unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos) const {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000662 ContentCache *Content;
Chris Lattner30fc9332009-02-04 01:06:56 +0000663 if (LastLineNoFileIDQuery == FID)
Ted Kremenek78d85f52007-10-30 21:08:08 +0000664 Content = LastLineNoContentCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000665 else
Chris Lattner30fc9332009-02-04 01:06:56 +0000666 Content = const_cast<ContentCache*>(getSLocEntry(FID)
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000667 .getFile().getContentCache());
Reid Spencer5f016e22007-07-11 17:01:13 +0000668
669 // If this is the first use of line information for this buffer, compute the
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000670 /// SourceLineCache for it on demand.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000671 if (Content->SourceLineCache == 0)
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000672 ComputeLineNumbers(Content, ContentCacheAlloc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000673
674 // Okay, we know we have a line number table. Do a binary search to find the
675 // line number that this character position lands on.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000676 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000677 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenek78d85f52007-10-30 21:08:08 +0000678 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000679
Chris Lattner30fc9332009-02-04 01:06:56 +0000680 unsigned QueriedFilePos = FilePos+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000681
682 // If the previous query was to the same file, we know both the file pos from
683 // that query and the line number returned. This allows us to narrow the
684 // search space from the entire file to something near the match.
Chris Lattner30fc9332009-02-04 01:06:56 +0000685 if (LastLineNoFileIDQuery == FID) {
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000686 if (QueriedFilePos >= LastLineNoFilePos) {
687 SourceLineCache = SourceLineCache+LastLineNoResult-1;
688
689 // The query is likely to be nearby the previous one. Here we check to
690 // see if it is within 5, 10 or 20 lines. It can be far away in cases
691 // where big comment blocks and vertical whitespace eat up lines but
692 // contribute no tokens.
693 if (SourceLineCache+5 < SourceLineCacheEnd) {
694 if (SourceLineCache[5] > QueriedFilePos)
695 SourceLineCacheEnd = SourceLineCache+5;
696 else if (SourceLineCache+10 < SourceLineCacheEnd) {
697 if (SourceLineCache[10] > QueriedFilePos)
698 SourceLineCacheEnd = SourceLineCache+10;
699 else if (SourceLineCache+20 < SourceLineCacheEnd) {
700 if (SourceLineCache[20] > QueriedFilePos)
701 SourceLineCacheEnd = SourceLineCache+20;
702 }
703 }
704 }
705 } else {
706 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
707 }
708 }
709
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000710 // If the spread is large, do a "radix" test as our initial guess, based on
711 // the assumption that lines average to approximately the same length.
712 // NOTE: This is currently disabled, as it does not appear to be profitable in
713 // initial measurements.
714 if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
Ted Kremenek78d85f52007-10-30 21:08:08 +0000715 unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000716
717 // Take a stab at guessing where it is.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000718 unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000719
720 // Check for -10 and +10 lines.
721 unsigned LowerBound = std::max(int(ApproxPos-10), 0);
722 unsigned UpperBound = std::min(ApproxPos+10, FileLen);
723
724 // If the computed lower bound is less than the query location, move it in.
725 if (SourceLineCache < SourceLineCacheStart+LowerBound &&
726 SourceLineCacheStart[LowerBound] < QueriedFilePos)
727 SourceLineCache = SourceLineCacheStart+LowerBound;
728
729 // If the computed upper bound is greater than the query location, move it.
730 if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
731 SourceLineCacheStart[UpperBound] >= QueriedFilePos)
732 SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
733 }
734
735 unsigned *Pos
736 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000737 unsigned LineNo = Pos-SourceLineCacheStart;
738
Chris Lattner30fc9332009-02-04 01:06:56 +0000739 LastLineNoFileIDQuery = FID;
Ted Kremenek78d85f52007-10-30 21:08:08 +0000740 LastLineNoContentCache = Content;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000741 LastLineNoFilePos = QueriedFilePos;
742 LastLineNoResult = LineNo;
743 return LineNo;
Reid Spencer5f016e22007-07-11 17:01:13 +0000744}
745
Chris Lattner30fc9332009-02-04 01:06:56 +0000746unsigned SourceManager::getInstantiationLineNumber(SourceLocation Loc) const {
747 if (Loc.isInvalid()) return 0;
748 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
749 return getLineNumber(LocInfo.first, LocInfo.second);
750}
751unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc) const {
752 if (Loc.isInvalid()) return 0;
753 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
754 return getLineNumber(LocInfo.first, LocInfo.second);
755}
756
757
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000758/// getPresumedLoc - This method returns the "presumed" location of a
759/// SourceLocation specifies. A "presumed location" can be modified by #line
760/// or GNU line marker directives. This provides a view on the data that a
761/// user should see in diagnostics, for example.
762///
763/// Note that a presumed location is always given as the instantiation point
764/// of an instantiation location, not at the spelling location.
765PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
766 if (Loc.isInvalid()) return PresumedLoc();
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000767
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000768 // Presumed locations are always for instantiation points.
Chris Lattner7da5aea2009-02-04 00:55:58 +0000769 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000770
Chris Lattner30fc9332009-02-04 01:06:56 +0000771 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000772 const SrcMgr::ContentCache *C = FI.getContentCache();
Chris Lattner3cd949c2009-02-04 01:55:42 +0000773
774 // To get the source name, first consult the FileEntry (if one exists)
775 // before the MemBuffer as this will avoid unnecessarily paging in the
776 // MemBuffer.
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000777 const char *Filename =
778 C->Entry ? C->Entry->getName() : C->getBuffer()->getBufferIdentifier();
Chris Lattner3cd949c2009-02-04 01:55:42 +0000779 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second);
780 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second);
781 SourceLocation IncludeLoc = FI.getIncludeLoc();
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000782
Chris Lattner3cd949c2009-02-04 01:55:42 +0000783 // If we have #line directives in this file, update and overwrite the physical
784 // location info if appropriate.
785 if (FI.hasLineDirectives()) {
786 assert(LineTable && "Can't have linetable entries without a LineTable!");
787 // See if there is a #line directive before this. If so, get it.
788 if (const LineEntry *Entry =
789 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) {
Chris Lattnerfc391332009-02-04 02:00:59 +0000790 // If the LineEntry indicates a filename, use it.
Chris Lattner3cd949c2009-02-04 01:55:42 +0000791 if (Entry->FilenameID != -1)
792 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerfc391332009-02-04 02:00:59 +0000793
794 // Use the line number specified by the LineEntry. This line number may
795 // be multiple lines down from the line entry. Add the difference in
796 // physical line numbers from the query point and the line marker to the
797 // total.
798 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
799 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
800
Chris Lattner0e0e5da2009-02-04 02:15:40 +0000801 // Note that column numbers are not molested by line markers.
Chris Lattner3cd949c2009-02-04 01:55:42 +0000802 }
803 }
804
805 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000806}
807
808//===----------------------------------------------------------------------===//
809// Other miscellaneous methods.
810//===----------------------------------------------------------------------===//
811
812
Reid Spencer5f016e22007-07-11 17:01:13 +0000813/// PrintStats - Print statistics to stderr.
814///
815void SourceManager::PrintStats() const {
Ted Kremenek665dd4a2007-12-05 22:21:13 +0000816 llvm::cerr << "\n*** Source Manager Stats:\n";
817 llvm::cerr << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
Chris Lattner08c375c2009-01-27 05:22:43 +0000818 << " mem buffers mapped.\n";
819 llvm::cerr << SLocEntryTable.size() << " SLocEntry's allocated, "
820 << NextOffset << "B of Sloc address space used.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000821
Reid Spencer5f016e22007-07-11 17:01:13 +0000822 unsigned NumLineNumsComputed = 0;
823 unsigned NumFileBytesMapped = 0;
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000824 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
825 NumLineNumsComputed += I->second->SourceLineCache != 0;
826 NumFileBytesMapped += I->second->getSizeBytesMapped();
Reid Spencer5f016e22007-07-11 17:01:13 +0000827 }
Ted Kremenek78d85f52007-10-30 21:08:08 +0000828
Ted Kremenek665dd4a2007-12-05 22:21:13 +0000829 llvm::cerr << NumFileBytesMapped << " bytes of files mapped, "
830 << NumLineNumsComputed << " files with line #'s computed.\n";
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000831 llvm::cerr << "FileID scans: " << NumLinearScans << " linear, "
832 << NumBinaryProbes << " binary.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000833}
Ted Kremeneke21272f2007-12-04 19:39:02 +0000834
835//===----------------------------------------------------------------------===//
836// Serialization.
837//===----------------------------------------------------------------------===//
Ted Kremenek099b4742007-12-05 00:14:18 +0000838
839void ContentCache::Emit(llvm::Serializer& S) const {
Ted Kremeneke21272f2007-12-04 19:39:02 +0000840 S.FlushRecord();
841 S.EmitPtr(this);
Ted Kremeneke21272f2007-12-04 19:39:02 +0000842
Ted Kremenek82dfaf72007-12-18 22:12:19 +0000843 if (Entry) {
844 llvm::sys::Path Fname(Buffer->getBufferIdentifier());
845
846 if (Fname.isAbsolute())
847 S.EmitCStr(Fname.c_str());
848 else {
849 // Create an absolute path.
850 // FIXME: This will potentially contain ".." and "." in the path.
851 llvm::sys::Path path = llvm::sys::Path::GetCurrentDirectory();
852 path.appendComponent(Fname.c_str());
853 S.EmitCStr(path.c_str());
854 }
855 }
Ted Kremenek099b4742007-12-05 00:14:18 +0000856 else {
Ted Kremeneke21272f2007-12-04 19:39:02 +0000857 const char* p = Buffer->getBufferStart();
858 const char* e = Buffer->getBufferEnd();
859
Ted Kremenek099b4742007-12-05 00:14:18 +0000860 S.EmitInt(e-p);
861
Ted Kremeneke21272f2007-12-04 19:39:02 +0000862 for ( ; p != e; ++p)
Ted Kremenek099b4742007-12-05 00:14:18 +0000863 S.EmitInt(*p);
Ted Kremeneke21272f2007-12-04 19:39:02 +0000864 }
865
Ted Kremenek099b4742007-12-05 00:14:18 +0000866 S.FlushRecord();
Ted Kremeneke21272f2007-12-04 19:39:02 +0000867}
Ted Kremenek099b4742007-12-05 00:14:18 +0000868
869void ContentCache::ReadToSourceManager(llvm::Deserializer& D,
870 SourceManager& SMgr,
871 FileManager* FMgr,
872 std::vector<char>& Buf) {
873 if (FMgr) {
874 llvm::SerializedPtrID PtrID = D.ReadPtrID();
875 D.ReadCStr(Buf,false);
876
877 // Create/fetch the FileEntry.
878 const char* start = &Buf[0];
879 const FileEntry* E = FMgr->getFile(start,start+Buf.size());
880
Ted Kremenekdb9c2292007-12-13 18:12:10 +0000881 // FIXME: Ideally we want a lazy materialization of the ContentCache
882 // anyway, because we don't want to read in source files unless this
883 // is absolutely needed.
884 if (!E)
885 D.RegisterPtr(PtrID,NULL);
Nico Weber48002c82008-09-29 00:25:48 +0000886 else
Ted Kremenekdb9c2292007-12-13 18:12:10 +0000887 // Get the ContextCache object and register it with the deserializer.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000888 D.RegisterPtr(PtrID, SMgr.getOrCreateContentCache(E));
889 return;
Ted Kremenek099b4742007-12-05 00:14:18 +0000890 }
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000891
892 // Register the ContextCache object with the deserializer.
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000893 /* FIXME:
894 ContentCache *Entry
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000895 SMgr.MemBufferInfos.push_back(ContentCache());
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000896 = const_cast<ContentCache&>(SMgr.MemBufferInfos.back());
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000897 D.RegisterPtr(&Entry);
898
899 // Create the buffer.
900 unsigned Size = D.ReadInt();
901 Entry.Buffer = MemoryBuffer::getNewUninitMemBuffer(Size);
902
903 // Read the contents of the buffer.
904 char* p = const_cast<char*>(Entry.Buffer->getBufferStart());
905 for (unsigned i = 0; i < Size ; ++i)
906 p[i] = D.ReadInt();
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000907 */
Ted Kremenek099b4742007-12-05 00:14:18 +0000908}
909
910void SourceManager::Emit(llvm::Serializer& S) const {
Ted Kremenek1f941002007-12-05 00:19:51 +0000911 S.EnterBlock();
912 S.EmitPtr(this);
Chris Lattner2b2453a2009-01-17 06:22:33 +0000913 S.EmitInt(MainFileID.getOpaqueValue());
Ted Kremenek1f941002007-12-05 00:19:51 +0000914
Ted Kremenek099b4742007-12-05 00:14:18 +0000915 // Emit: FileInfos. Just emit the file name.
916 S.EnterBlock();
917
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000918 // FIXME: Emit FileInfos.
919 //std::for_each(FileInfos.begin(), FileInfos.end(),
920 // S.MakeEmitter<ContentCache>());
Ted Kremenek099b4742007-12-05 00:14:18 +0000921
922 S.ExitBlock();
923
924 // Emit: MemBufferInfos
925 S.EnterBlock();
926
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000927 /* FIXME: EMIT.
Ted Kremenek099b4742007-12-05 00:14:18 +0000928 std::for_each(MemBufferInfos.begin(), MemBufferInfos.end(),
929 S.MakeEmitter<ContentCache>());
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000930 */
Ted Kremenek099b4742007-12-05 00:14:18 +0000931
932 S.ExitBlock();
933
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000934 // FIXME: Emit SLocEntryTable.
Ted Kremenek1f941002007-12-05 00:19:51 +0000935
936 S.ExitBlock();
Ted Kremenek099b4742007-12-05 00:14:18 +0000937}
938
Ted Kremenek1f941002007-12-05 00:19:51 +0000939SourceManager*
Chris Lattner23b5dc62009-02-04 00:40:31 +0000940SourceManager::CreateAndRegister(llvm::Deserializer &D, FileManager &FMgr) {
Ted Kremenek1f941002007-12-05 00:19:51 +0000941 SourceManager *M = new SourceManager();
942 D.RegisterPtr(M);
943
Ted Kremenek76edd0e2007-12-19 22:29:55 +0000944 // Read: the FileID of the main source file of the translation unit.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000945 M->MainFileID = FileID::get(D.ReadInt());
Ted Kremenek76edd0e2007-12-19 22:29:55 +0000946
Ted Kremenek099b4742007-12-05 00:14:18 +0000947 std::vector<char> Buf;
948
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000949 /*{ // FIXME Read: FileInfos.
Ted Kremenek099b4742007-12-05 00:14:18 +0000950 llvm::Deserializer::Location BLoc = D.getCurrentBlockLocation();
951 while (!D.FinishedBlock(BLoc))
Ted Kremenek1f941002007-12-05 00:19:51 +0000952 ContentCache::ReadToSourceManager(D,*M,&FMgr,Buf);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000953 }*/
Ted Kremenek099b4742007-12-05 00:14:18 +0000954
955 { // Read: MemBufferInfos.
956 llvm::Deserializer::Location BLoc = D.getCurrentBlockLocation();
957 while (!D.FinishedBlock(BLoc))
Ted Kremenek1f941002007-12-05 00:19:51 +0000958 ContentCache::ReadToSourceManager(D,*M,NULL,Buf);
Ted Kremenek099b4742007-12-05 00:14:18 +0000959 }
960
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000961 // FIXME: Read SLocEntryTable.
Ted Kremenek1f941002007-12-05 00:19:51 +0000962
963 return M;
Ted Kremenek1f2c7d12007-12-10 18:01:25 +0000964}