blob: c37a2c36565dc37417d63ba67508a20ed476d08c [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);
124
125 // Add a FileID for this. FIXME: should cache these!
126 FileIDs.push_back(FileIDInfo::getMacroExpansion(InstantLoc,
127 PhysLoc.getFileID()));
128 unsigned InstantiationFileID = FileIDs.size();
129 return SourceLocation(InstantiationFileID, PhysLoc.getRawFilePos());
Chris Lattner7d6a4f62006-06-30 06:10:08 +0000130}
131
132
Chris Lattner30709b032006-06-21 03:01:55 +0000133
Chris Lattnerd01e2912006-06-18 16:22:51 +0000134/// getCharacterData - Return a pointer to the start of the specified location
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000135/// in the appropriate SourceBuffer.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000136const char *SourceManager::getCharacterData(SourceLocation SL) const {
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000137 // Note that this is a hot function in the getSpelling() path, which is
138 // heavily used by -E mode.
139 unsigned FileID = SL.getFileID();
140 assert(FileID && "Invalid source location!");
141
142 return getFileInfo(FileID)->Buffer->getBufferStart() + getFilePos(SL);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000143}
144
Chris Lattner685730f2006-06-26 01:36:22 +0000145/// getIncludeLoc - Return the location of the #include for the specified
146/// FileID.
147SourceLocation SourceManager::getIncludeLoc(unsigned FileID) const {
148 const SrcMgr::FileIDInfo *FIDInfo = getFIDInfo(FileID);
149
150 // For Macros, the physical loc is specified by the MacroTokenFileID.
Chris Lattner2dffd2b2006-06-29 16:44:08 +0000151 if (FIDInfo->IDType == SrcMgr::FileIDInfo::MacroExpansion)
Chris Lattner685730f2006-06-26 01:36:22 +0000152 FIDInfo = &FileIDs[FIDInfo->u.MacroTokenFileID-1];
153
154 return FIDInfo->IncludeLoc;
155}
156
Chris Lattnerd01e2912006-06-18 16:22:51 +0000157
Chris Lattner22eb9722006-06-18 05:43:12 +0000158/// getColumnNumber - Return the column # for the specified include position.
159/// this is significantly cheaper to compute than the line number. This returns
160/// zero if the column number isn't known.
Chris Lattner9a13bde2006-06-21 04:57:09 +0000161unsigned SourceManager::getColumnNumber(SourceLocation Loc) const {
Chris Lattner2dffd2b2006-06-29 16:44:08 +0000162 Loc = getLogicalLoc(Loc);
Chris Lattner9a13bde2006-06-21 04:57:09 +0000163 unsigned FileID = Loc.getFileID();
Chris Lattner22eb9722006-06-18 05:43:12 +0000164 if (FileID == 0) return 0;
Chris Lattner30709b032006-06-21 03:01:55 +0000165
Chris Lattner9a13bde2006-06-21 04:57:09 +0000166 unsigned FilePos = getFilePos(Loc);
Chris Lattner30709b032006-06-21 03:01:55 +0000167 const SourceBuffer *Buffer = getBuffer(FileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000168 const char *Buf = Buffer->getBufferStart();
169
170 unsigned LineStart = FilePos;
171 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
172 --LineStart;
173 return FilePos-LineStart+1;
174}
175
Chris Lattner9a13bde2006-06-21 04:57:09 +0000176/// getSourceName - This method returns the name of the file or buffer that
177/// the SourceLocation specifies. This can be modified with #line directives,
178/// etc.
179std::string SourceManager::getSourceName(SourceLocation Loc) {
Chris Lattner2dffd2b2006-06-29 16:44:08 +0000180 Loc = getLogicalLoc(Loc);
Chris Lattner9a13bde2006-06-21 04:57:09 +0000181 unsigned FileID = Loc.getFileID();
182 if (FileID == 0) return "";
Chris Lattner2dffd2b2006-06-29 16:44:08 +0000183 return getFileInfo(FileID)->Buffer->getBufferIdentifier();
Chris Lattner9a13bde2006-06-21 04:57:09 +0000184}
185
186
Chris Lattner22eb9722006-06-18 05:43:12 +0000187/// getLineNumber - Given a SourceLocation, return the physical line number
188/// for the position indicated. This requires building and caching a table of
189/// line offsets for the SourceBuffer, so this is not cheap: use only when
190/// about to emit a diagnostic.
Chris Lattner9a13bde2006-06-21 04:57:09 +0000191unsigned SourceManager::getLineNumber(SourceLocation Loc) {
Chris Lattner2dffd2b2006-06-29 16:44:08 +0000192 Loc = getLogicalLoc(Loc);
Chris Lattnera85a9d22006-07-02 20:07:52 +0000193 unsigned FileID = Loc.getFileID();
194 if (FileID == 0) return 0;
195 FileInfo *FileInfo = getFileInfo(FileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000196
197 // If this is the first use of line information for this buffer, compute the
198 /// SourceLineCache for it on demand.
199 if (FileInfo->SourceLineCache == 0) {
200 const SourceBuffer *Buffer = FileInfo->Buffer;
201
202 // Find the file offsets of all of the *physical* source lines. This does
203 // not look at trigraphs, escaped newlines, or anything else tricky.
204 std::vector<unsigned> LineOffsets;
205
206 // Line #1 starts at char 0.
207 LineOffsets.push_back(0);
208
209 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
210 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
211 unsigned Offs = 0;
212 while (1) {
213 // Skip over the contents of the line.
214 // TODO: Vectorize this? This is very performance sensitive for programs
Chris Lattnerd5da3ea2006-07-04 21:11:41 +0000215 // with lots of diagnostics and in -E mode.
Chris Lattner22eb9722006-06-18 05:43:12 +0000216 const unsigned char *NextBuf = (const unsigned char *)Buf;
217 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
218 ++NextBuf;
219 Offs += NextBuf-Buf;
220 Buf = NextBuf;
221
222 if (Buf[0] == '\n' || Buf[0] == '\r') {
223 // If this is \n\r or \r\n, skip both characters.
224 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
225 ++Offs, ++Buf;
226 ++Offs, ++Buf;
227 LineOffsets.push_back(Offs);
228 } else {
229 // Otherwise, this is a null. If end of file, exit.
230 if (Buf == End) break;
231 // Otherwise, skip the null.
232 ++Offs, ++Buf;
233 }
234 }
235 LineOffsets.push_back(Offs);
236
237 // Copy the offsets into the FileInfo structure.
238 FileInfo->NumLines = LineOffsets.size();
239 FileInfo->SourceLineCache = new unsigned[LineOffsets.size()];
240 std::copy(LineOffsets.begin(), LineOffsets.end(),
241 FileInfo->SourceLineCache);
242 }
243
244 // Okay, we know we have a line number table. Do a binary search to find the
245 // line number that this character position lands on.
246 unsigned NumLines = FileInfo->NumLines;
247 unsigned *SourceLineCache = FileInfo->SourceLineCache;
248
249 // TODO: If this is performance sensitive, we could try doing simple radix
250 // type approaches to make good (tight?) initial guesses based on the
251 // assumption that all lines are the same average size.
252 unsigned *Pos = std::lower_bound(SourceLineCache, SourceLineCache+NumLines,
Chris Lattner9a13bde2006-06-21 04:57:09 +0000253 getFilePos(Loc)+1);
Chris Lattner22eb9722006-06-18 05:43:12 +0000254 return Pos-SourceLineCache;
255}
256
Chris Lattnerf6fd68a2006-06-26 01:48:23 +0000257/// getSourceFilePos - This method returns the *logical* offset from the start
258/// of the file that the specified SourceLocation represents. This returns
259/// the location of the *logical* character data, not the physical file
260/// position. In the case of macros, for example, this returns where the
261/// macro was instantiated, not where the characters for the macro can be
262/// found.
263unsigned SourceManager::getSourceFilePos(SourceLocation Loc) const {
264
265 // If this is a macro, we need to get the instantiation location.
266 const SrcMgr::FileIDInfo *FIDInfo = getFIDInfo(Loc.getFileID());
Chris Lattnerdc9f9bf2006-06-29 06:33:42 +0000267 while (FIDInfo->IDType == SrcMgr::FileIDInfo::MacroExpansion) {
268 Loc = FIDInfo->IncludeLoc;
269 FIDInfo = getFIDInfo(Loc.getFileID());
270 }
Chris Lattnerf6fd68a2006-06-26 01:48:23 +0000271
272 return getFilePos(Loc);
273}
274
275
Chris Lattner22eb9722006-06-18 05:43:12 +0000276/// PrintStats - Print statistics to stderr.
277///
278void SourceManager::PrintStats() const {
279 std::cerr << "\n*** Source Manager Stats:\n";
280 std::cerr << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
281 << " mem buffers mapped, " << FileIDs.size()
282 << " file ID's allocated.\n";
Chris Lattner30709b032006-06-21 03:01:55 +0000283 unsigned NumBuffers = 0, NumMacros = 0;
284 for (unsigned i = 0, e = FileIDs.size(); i != e; ++i) {
285 if (FileIDs[i].IDType == FileIDInfo::NormalBuffer)
286 ++NumBuffers;
287 else if (FileIDs[i].IDType == FileIDInfo::MacroExpansion)
288 ++NumMacros;
289 else
290 assert(0 && "Unknown FileID!");
291 }
292 std::cerr << " " << NumBuffers << " normal buffer FileID's, "
293 << NumMacros << " macro expansion FileID's.\n";
294
295
Chris Lattner22eb9722006-06-18 05:43:12 +0000296
297 unsigned NumLineNumsComputed = 0;
298 unsigned NumFileBytesMapped = 0;
299 for (std::map<const FileEntry *, FileInfo>::const_iterator I =
300 FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
301 NumLineNumsComputed += I->second.SourceLineCache != 0;
302 NumFileBytesMapped += I->second.Buffer->getBufferSize();
303 }
304 std::cerr << NumFileBytesMapped << " bytes of files mapped, "
305 << NumLineNumsComputed << " files with line #'s computed.\n";
306}