blob: 1182af7a0aa90f7f589054db69bf39109df0a9f4 [file] [log] [blame]
Chris Lattner22eb9722006-06-18 05:43:12 +00001//===--- SourceManager.cpp - Track and cache source files -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the SourceManager interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Basic/SourceManager.h"
15#include "clang/Basic/FileManager.h"
16#include "clang/Basic/SourceBuffer.h"
17#include "llvm/System/Path.h"
18#include <algorithm>
19#include <iostream>
20using namespace llvm;
21using namespace clang;
Chris Lattner5f4b1ff2006-06-20 05:02:40 +000022using namespace SrcMgr;
Chris Lattner22eb9722006-06-18 05:43:12 +000023
24SourceManager::~SourceManager() {
25 for (std::map<const FileEntry *, FileInfo>::iterator I = FileInfos.begin(),
26 E = FileInfos.end(); I != E; ++I) {
27 delete I->second.Buffer;
28 delete[] I->second.SourceLineCache;
29 }
30
31 for (std::list<InfoRec>::iterator I = MemBufferInfos.begin(),
32 E = MemBufferInfos.end(); I != E; ++I) {
33 delete I->second.Buffer;
34 delete[] I->second.SourceLineCache;
35 }
36}
37
38/// getFileInfo - Create or return a cached FileInfo for the specified file.
39///
Chris Lattner5f4b1ff2006-06-20 05:02:40 +000040const InfoRec *
Chris Lattner22eb9722006-06-18 05:43:12 +000041SourceManager::getInfoRec(const FileEntry *FileEnt) {
42 assert(FileEnt && "Didn't specify a file entry to use?");
43 // Do we already have information about this file?
44 std::map<const FileEntry *, FileInfo>::iterator I =
45 FileInfos.lower_bound(FileEnt);
46 if (I != FileInfos.end() && I->first == FileEnt)
47 return &*I;
48
49 // Nope, get information.
50 const SourceBuffer *File;
51 try {
52 File = clang::SourceBuffer::getFile(FileEnt);
53 if (File == 0)
54 return 0;
55 } catch (...) {
56 return 0;
57 }
58
59 const InfoRec &Entry =
60 *FileInfos.insert(I, std::make_pair(FileEnt, FileInfo()));
61 FileInfo &Info = const_cast<FileInfo &>(Entry.second);
62
63 Info.Buffer = File;
64 Info.SourceLineCache = 0;
65 Info.NumLines = 0;
66 return &Entry;
67}
68
69
70/// createMemBufferInfoRec - Create a new info record for the specified memory
71/// buffer. This does no caching.
Chris Lattner5f4b1ff2006-06-20 05:02:40 +000072const InfoRec *
Chris Lattner22eb9722006-06-18 05:43:12 +000073SourceManager::createMemBufferInfoRec(const SourceBuffer *Buffer) {
74 // Add a new info record to the MemBufferInfos list and return it.
75 FileInfo FI;
76 FI.Buffer = Buffer;
77 FI.SourceLineCache = 0;
78 FI.NumLines = 0;
79 MemBufferInfos.push_back(InfoRec(0, FI));
80 return &MemBufferInfos.back();
81}
82
83
84/// createFileID - Create a new fileID for the specified InfoRec and include
85/// position. This works regardless of whether the InfoRec corresponds to a
86/// file or some other input source.
87unsigned SourceManager::createFileID(const InfoRec *File,
88 SourceLocation IncludePos) {
89 // If FileEnt is really large (e.g. it's a large .i file), we may not be able
90 // to fit an arbitrary position in the file in the FilePos field. To handle
91 // this, we create one FileID for each chunk of the file that fits in a
92 // FilePos field.
93 unsigned FileSize = File->second.Buffer->getBufferSize();
94 if (FileSize+1 < (1 << SourceLocation::FilePosBits)) {
Chris Lattner5f4b1ff2006-06-20 05:02:40 +000095 FileIDs.push_back(FileIDInfo::getNormalBuffer(IncludePos, 0, File));
Chris Lattner22eb9722006-06-18 05:43:12 +000096 return FileIDs.size();
97 }
98
99 // Create one FileID for each chunk of the file.
100 unsigned Result = FileIDs.size()+1;
101
102 unsigned ChunkNo = 0;
103 while (1) {
Chris Lattner5f4b1ff2006-06-20 05:02:40 +0000104 FileIDs.push_back(FileIDInfo::getNormalBuffer(IncludePos, ChunkNo++, File));
Chris Lattner22eb9722006-06-18 05:43:12 +0000105
106 if (FileSize+1 < (1 << SourceLocation::FilePosBits)) break;
107 FileSize -= (1 << SourceLocation::FilePosBits);
108 }
109
110 return Result;
111}
112
Chris Lattner7d6a4f62006-06-30 06:10:08 +0000113/// getInstantiationLoc - Return a new SourceLocation that encodes the fact
114/// that a token from physloc PhysLoc should actually be referenced from
115/// InstantiationLoc.
116SourceLocation SourceManager::getInstantiationLoc(SourceLocation PhysLoc,
117 SourceLocation InstantLoc) {
Chris Lattner351050b2006-07-16 18:05:08 +0000118 assert(getFIDInfo(PhysLoc.getFileID())->IDType !=
119 SrcMgr::FileIDInfo::MacroExpansion &&
120 "Location instantiated in a macro?");
121
Chris Lattner4c37a8c2006-06-30 06:15:08 +0000122 // Resolve InstantLoc down to a real logical location.
123 InstantLoc = getLogicalLoc(InstantLoc);
Chris Lattner7fa8c882006-07-20 06:48:52 +0000124
125 unsigned InstantiationFileID;
126 // If this is the same instantiation as was requested last time, return this
127 // immediately.
128 if (PhysLoc.getFileID() == LastInstantiationLoc_MacroFID &&
129 InstantLoc == LastInstantiationLoc_InstantLoc) {
130 InstantiationFileID = LastInstantiationLoc_Result;
131 } else {
132 // Add a FileID for this. FIXME: should cache these!
133 FileIDs.push_back(FileIDInfo::getMacroExpansion(InstantLoc,
134 PhysLoc.getFileID()));
135 InstantiationFileID = FileIDs.size();
136
137 // Remember this in the single-entry cache for next time.
138 LastInstantiationLoc_MacroFID = PhysLoc.getFileID();
139 LastInstantiationLoc_InstantLoc = InstantLoc;
140 LastInstantiationLoc_Result = InstantiationFileID;
141 }
Chris Lattner4c37a8c2006-06-30 06:15:08 +0000142 return SourceLocation(InstantiationFileID, PhysLoc.getRawFilePos());
Chris Lattner7d6a4f62006-06-30 06:10:08 +0000143}
144
145
Chris Lattner30709b032006-06-21 03:01:55 +0000146
Chris Lattnerd01e2912006-06-18 16:22:51 +0000147/// getCharacterData - Return a pointer to the start of the specified location
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000148/// in the appropriate SourceBuffer.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000149const char *SourceManager::getCharacterData(SourceLocation SL) const {
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000150 // Note that this is a hot function in the getSpelling() path, which is
151 // heavily used by -E mode.
152 unsigned FileID = SL.getFileID();
153 assert(FileID && "Invalid source location!");
154
155 return getFileInfo(FileID)->Buffer->getBufferStart() + getFilePos(SL);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000156}
157
Chris Lattner685730f2006-06-26 01:36:22 +0000158/// getIncludeLoc - Return the location of the #include for the specified
159/// FileID.
160SourceLocation SourceManager::getIncludeLoc(unsigned FileID) const {
161 const SrcMgr::FileIDInfo *FIDInfo = getFIDInfo(FileID);
162
163 // For Macros, the physical loc is specified by the MacroTokenFileID.
Chris Lattner2dffd2b2006-06-29 16:44:08 +0000164 if (FIDInfo->IDType == SrcMgr::FileIDInfo::MacroExpansion)
Chris Lattner685730f2006-06-26 01:36:22 +0000165 FIDInfo = &FileIDs[FIDInfo->u.MacroTokenFileID-1];
166
167 return FIDInfo->IncludeLoc;
168}
169
Chris Lattnerd01e2912006-06-18 16:22:51 +0000170
Chris Lattner22eb9722006-06-18 05:43:12 +0000171/// getColumnNumber - Return the column # for the specified include position.
172/// this is significantly cheaper to compute than the line number. This returns
173/// zero if the column number isn't known.
Chris Lattner9a13bde2006-06-21 04:57:09 +0000174unsigned SourceManager::getColumnNumber(SourceLocation Loc) const {
Chris Lattner2dffd2b2006-06-29 16:44:08 +0000175 Loc = getLogicalLoc(Loc);
Chris Lattner9a13bde2006-06-21 04:57:09 +0000176 unsigned FileID = Loc.getFileID();
Chris Lattner22eb9722006-06-18 05:43:12 +0000177 if (FileID == 0) return 0;
Chris Lattner30709b032006-06-21 03:01:55 +0000178
Chris Lattner9a13bde2006-06-21 04:57:09 +0000179 unsigned FilePos = getFilePos(Loc);
Chris Lattner30709b032006-06-21 03:01:55 +0000180 const SourceBuffer *Buffer = getBuffer(FileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000181 const char *Buf = Buffer->getBufferStart();
182
183 unsigned LineStart = FilePos;
184 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
185 --LineStart;
186 return FilePos-LineStart+1;
187}
188
Chris Lattner9a13bde2006-06-21 04:57:09 +0000189/// getSourceName - This method returns the name of the file or buffer that
190/// the SourceLocation specifies. This can be modified with #line directives,
191/// etc.
192std::string SourceManager::getSourceName(SourceLocation Loc) {
Chris Lattner2dffd2b2006-06-29 16:44:08 +0000193 Loc = getLogicalLoc(Loc);
Chris Lattner9a13bde2006-06-21 04:57:09 +0000194 unsigned FileID = Loc.getFileID();
195 if (FileID == 0) return "";
Chris Lattner2dffd2b2006-06-29 16:44:08 +0000196 return getFileInfo(FileID)->Buffer->getBufferIdentifier();
Chris Lattner9a13bde2006-06-21 04:57:09 +0000197}
198
199
Chris Lattner22eb9722006-06-18 05:43:12 +0000200/// getLineNumber - Given a SourceLocation, return the physical line number
201/// for the position indicated. This requires building and caching a table of
202/// line offsets for the SourceBuffer, so this is not cheap: use only when
203/// about to emit a diagnostic.
Chris Lattner9a13bde2006-06-21 04:57:09 +0000204unsigned SourceManager::getLineNumber(SourceLocation Loc) {
Chris Lattner2dffd2b2006-06-29 16:44:08 +0000205 Loc = getLogicalLoc(Loc);
Chris Lattnera85a9d22006-07-02 20:07:52 +0000206 unsigned FileID = Loc.getFileID();
207 if (FileID == 0) return 0;
208 FileInfo *FileInfo = getFileInfo(FileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000209
210 // If this is the first use of line information for this buffer, compute the
211 /// SourceLineCache for it on demand.
212 if (FileInfo->SourceLineCache == 0) {
213 const SourceBuffer *Buffer = FileInfo->Buffer;
214
215 // Find the file offsets of all of the *physical* source lines. This does
216 // not look at trigraphs, escaped newlines, or anything else tricky.
217 std::vector<unsigned> LineOffsets;
218
219 // Line #1 starts at char 0.
220 LineOffsets.push_back(0);
221
222 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
223 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
224 unsigned Offs = 0;
225 while (1) {
226 // Skip over the contents of the line.
227 // TODO: Vectorize this? This is very performance sensitive for programs
Chris Lattnerd5da3ea2006-07-04 21:11:41 +0000228 // with lots of diagnostics and in -E mode.
Chris Lattner22eb9722006-06-18 05:43:12 +0000229 const unsigned char *NextBuf = (const unsigned char *)Buf;
230 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
231 ++NextBuf;
232 Offs += NextBuf-Buf;
233 Buf = NextBuf;
234
235 if (Buf[0] == '\n' || Buf[0] == '\r') {
236 // If this is \n\r or \r\n, skip both characters.
237 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
238 ++Offs, ++Buf;
239 ++Offs, ++Buf;
240 LineOffsets.push_back(Offs);
241 } else {
242 // Otherwise, this is a null. If end of file, exit.
243 if (Buf == End) break;
244 // Otherwise, skip the null.
245 ++Offs, ++Buf;
246 }
247 }
248 LineOffsets.push_back(Offs);
249
250 // Copy the offsets into the FileInfo structure.
251 FileInfo->NumLines = LineOffsets.size();
252 FileInfo->SourceLineCache = new unsigned[LineOffsets.size()];
253 std::copy(LineOffsets.begin(), LineOffsets.end(),
254 FileInfo->SourceLineCache);
255 }
256
257 // Okay, we know we have a line number table. Do a binary search to find the
258 // line number that this character position lands on.
259 unsigned NumLines = FileInfo->NumLines;
260 unsigned *SourceLineCache = FileInfo->SourceLineCache;
261
262 // TODO: If this is performance sensitive, we could try doing simple radix
263 // type approaches to make good (tight?) initial guesses based on the
264 // assumption that all lines are the same average size.
265 unsigned *Pos = std::lower_bound(SourceLineCache, SourceLineCache+NumLines,
Chris Lattner9a13bde2006-06-21 04:57:09 +0000266 getFilePos(Loc)+1);
Chris Lattner22eb9722006-06-18 05:43:12 +0000267 return Pos-SourceLineCache;
268}
269
Chris Lattnerf6fd68a2006-06-26 01:48:23 +0000270/// getSourceFilePos - This method returns the *logical* offset from the start
271/// of the file that the specified SourceLocation represents. This returns
272/// the location of the *logical* character data, not the physical file
273/// position. In the case of macros, for example, this returns where the
274/// macro was instantiated, not where the characters for the macro can be
275/// found.
276unsigned SourceManager::getSourceFilePos(SourceLocation Loc) const {
277
278 // If this is a macro, we need to get the instantiation location.
279 const SrcMgr::FileIDInfo *FIDInfo = getFIDInfo(Loc.getFileID());
Chris Lattnerdc9f9bf2006-06-29 06:33:42 +0000280 while (FIDInfo->IDType == SrcMgr::FileIDInfo::MacroExpansion) {
281 Loc = FIDInfo->IncludeLoc;
282 FIDInfo = getFIDInfo(Loc.getFileID());
283 }
Chris Lattnerf6fd68a2006-06-26 01:48:23 +0000284
285 return getFilePos(Loc);
286}
287
288
Chris Lattner22eb9722006-06-18 05:43:12 +0000289/// PrintStats - Print statistics to stderr.
290///
291void SourceManager::PrintStats() const {
292 std::cerr << "\n*** Source Manager Stats:\n";
293 std::cerr << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
294 << " mem buffers mapped, " << FileIDs.size()
295 << " file ID's allocated.\n";
Chris Lattner30709b032006-06-21 03:01:55 +0000296 unsigned NumBuffers = 0, NumMacros = 0;
297 for (unsigned i = 0, e = FileIDs.size(); i != e; ++i) {
298 if (FileIDs[i].IDType == FileIDInfo::NormalBuffer)
299 ++NumBuffers;
300 else if (FileIDs[i].IDType == FileIDInfo::MacroExpansion)
301 ++NumMacros;
302 else
303 assert(0 && "Unknown FileID!");
304 }
305 std::cerr << " " << NumBuffers << " normal buffer FileID's, "
306 << NumMacros << " macro expansion FileID's.\n";
307
308
Chris Lattner22eb9722006-06-18 05:43:12 +0000309
310 unsigned NumLineNumsComputed = 0;
311 unsigned NumFileBytesMapped = 0;
312 for (std::map<const FileEntry *, FileInfo>::const_iterator I =
313 FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
314 NumLineNumsComputed += I->second.SourceLineCache != 0;
315 NumFileBytesMapped += I->second.Buffer->getBufferSize();
316 }
317 std::cerr << NumFileBytesMapped << " bytes of files mapped, "
318 << NumLineNumsComputed << " files with line #'s computed.\n";
319}