blob: 8564a76feb1b30779866384366c6321f0262a500 [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"
Douglas Gregord4f77aa2009-04-13 15:31:25 +000015#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregoraea67db2010-03-15 22:54:52 +000016#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/Basic/FileManager.h"
Chris Lattner5e36a7a2007-07-24 05:57:19 +000018#include "llvm/Support/Compiler.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "llvm/Support/MemoryBuffer.h"
Chris Lattnerd57a7ef2009-08-23 22:45:33 +000020#include "llvm/Support/raw_ostream.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021#include "llvm/System/Path.h"
22#include <algorithm>
Douglas Gregoraea67db2010-03-15 22:54:52 +000023#include <string>
Douglas Gregorf715ca12010-03-16 00:06:06 +000024#include <cstring>
Douglas Gregoraea67db2010-03-15 22:54:52 +000025
Reid Spencer5f016e22007-07-11 17:01:13 +000026using namespace clang;
27using namespace SrcMgr;
28using llvm::MemoryBuffer;
29
Chris Lattner23b5dc62009-02-04 00:40:31 +000030//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +000031// SourceManager Helper Classes
Chris Lattner23b5dc62009-02-04 00:40:31 +000032//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +000033
Ted Kremenek78d85f52007-10-30 21:08:08 +000034ContentCache::~ContentCache() {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000035 if (shouldFreeBuffer())
36 delete Buffer.getPointer();
Reid Spencer5f016e22007-07-11 17:01:13 +000037}
38
Ted Kremenekc16c2082009-01-06 01:55:26 +000039/// getSizeBytesMapped - Returns the number of bytes actually mapped for
40/// this ContentCache. This can be 0 if the MemBuffer was not actually
41/// instantiated.
42unsigned ContentCache::getSizeBytesMapped() const {
Douglas Gregorc8151082010-03-16 22:53:51 +000043 return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
Ted Kremenekc16c2082009-01-06 01:55:26 +000044}
45
46/// getSize - Returns the size of the content encapsulated by this ContentCache.
47/// This can be the size of the source file or the size of an arbitrary
48/// scratch buffer. If the ContentCache encapsulates a source file, that
Douglas Gregor29684422009-12-02 06:49:09 +000049/// file is not lazily brought in from disk to satisfy this query.
Ted Kremenekc16c2082009-01-06 01:55:26 +000050unsigned ContentCache::getSize() const {
Douglas Gregorc8151082010-03-16 22:53:51 +000051 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
52 : (unsigned) Entry->getSize();
Ted Kremenekc16c2082009-01-06 01:55:26 +000053}
54
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000055void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B,
56 bool DoNotFree) {
Douglas Gregorc8151082010-03-16 22:53:51 +000057 assert(B != Buffer.getPointer());
Douglas Gregor29684422009-12-02 06:49:09 +000058
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000059 if (shouldFreeBuffer())
60 delete Buffer.getPointer();
Douglas Gregorc8151082010-03-16 22:53:51 +000061 Buffer.setPointer(B);
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000062 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
Douglas Gregor29684422009-12-02 06:49:09 +000063}
64
Douglas Gregor36c35ba2010-03-16 00:35:39 +000065const llvm::MemoryBuffer *ContentCache::getBuffer(Diagnostic &Diag,
Chris Lattner5c5db4e2010-04-20 20:49:23 +000066 const SourceManager &SM,
Chris Lattnere127a0d2010-04-20 20:35:58 +000067 SourceLocation Loc,
Douglas Gregor36c35ba2010-03-16 00:35:39 +000068 bool *Invalid) const {
69 if (Invalid)
70 *Invalid = false;
71
Ted Kremenek5b034ad2009-01-06 22:43:04 +000072 // Lazily create the Buffer for ContentCaches that wrap files.
Douglas Gregorc8151082010-03-16 22:53:51 +000073 if (!Buffer.getPointer() && Entry) {
Douglas Gregoraea67db2010-03-15 22:54:52 +000074 std::string ErrorStr;
75 struct stat FileInfo;
Douglas Gregorc8151082010-03-16 22:53:51 +000076 Buffer.setPointer(MemoryBuffer::getFile(Entry->getName(), &ErrorStr,
77 Entry->getSize(), &FileInfo));
Douglas Gregorc8151082010-03-16 22:53:51 +000078
Daniel Dunbar21a8bed2009-12-06 05:43:36 +000079 // If we were unable to open the file, then we are in an inconsistent
80 // situation where the content cache referenced a file which no longer
81 // exists. Most likely, we were using a stat cache with an invalid entry but
82 // the file could also have been removed during processing. Since we can't
83 // really deal with this situation, just create an empty buffer.
84 //
85 // FIXME: This is definitely not ideal, but our immediate clients can't
86 // currently handle returning a null entry here. Ideally we should detect
87 // that we are in an inconsistent situation and error out as quickly as
88 // possible.
Douglas Gregorc8151082010-03-16 22:53:51 +000089 if (!Buffer.getPointer()) {
Daniel Dunbar21a8bed2009-12-06 05:43:36 +000090 const llvm::StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
Douglas Gregorc8151082010-03-16 22:53:51 +000091 Buffer.setPointer(MemoryBuffer::getNewMemBuffer(Entry->getSize(),
92 "<invalid>"));
93 char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart());
Daniel Dunbar21a8bed2009-12-06 05:43:36 +000094 for (unsigned i = 0, e = Entry->getSize(); i != e; ++i)
95 Ptr[i] = FillStr[i % FillStr.size()];
Douglas Gregor93ea5cb2010-03-22 15:10:57 +000096
97 if (Diag.isDiagnosticInFlight())
98 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
99 Entry->getName(), ErrorStr);
100 else
Chris Lattnere127a0d2010-04-20 20:35:58 +0000101 Diag.Report(FullSourceLoc(Loc, SM), diag::err_cannot_open_file)
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000102 << Entry->getName() << ErrorStr;
103
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000104 Buffer.setInt(Buffer.getInt() | InvalidFlag);
Daniel Dunbar0b3c7732010-04-10 01:17:16 +0000105
106 // FIXME: This conditionalization is horrible, but we see spurious failures
107 // in the test suite due to this warning and no one has had time to hunt it
108 // down. So for now, we just don't emit this diagnostic on Win32, and hope
109 // nothing bad happens.
110 //
111 // PR6812.
Douglas Gregor9f692a02010-04-09 15:54:22 +0000112#if !defined(LLVM_ON_WIN32)
Daniel Dunbar0b3c7732010-04-10 01:17:16 +0000113 } else if (FileInfo.st_size != Entry->getSize() ||
114 FileInfo.st_mtime != Entry->getModificationTime()) {
Douglas Gregor9f692a02010-04-09 15:54:22 +0000115 // Check that the file's size and modification time are the same
116 // as in the file entry (which may have come from a stat cache).
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000117 if (Diag.isDiagnosticInFlight())
Daniel Dunbar0b3c7732010-04-10 01:17:16 +0000118 Diag.SetDelayedDiagnostic(diag::err_file_modified,
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000119 Entry->getName());
Daniel Dunbar0b3c7732010-04-10 01:17:16 +0000120 else
Chris Lattnere127a0d2010-04-20 20:35:58 +0000121 Diag.Report(FullSourceLoc(Loc, SM), diag::err_file_modified)
122 << Entry->getName();
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000123
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000124 Buffer.setInt(Buffer.getInt() | InvalidFlag);
Daniel Dunbar0b3c7732010-04-10 01:17:16 +0000125#endif
Daniel Dunbar21a8bed2009-12-06 05:43:36 +0000126 }
Chris Lattner38caec42010-04-20 18:14:03 +0000127
128 // If the buffer is valid, check to see if it has a UTF Byte Order Mark
129 // (BOM). We only support UTF-8 without a BOM right now. See
130 // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000131 if (!isBufferInvalid()) {
Chris Lattner38caec42010-04-20 18:14:03 +0000132 llvm::StringRef BufStr = Buffer.getPointer()->getBuffer();
133 const char *BOM = 0;
134 if (BufStr.startswith("\xFE\xBB\xBF"))
135 BOM = "UTF-8";
136 else if (BufStr.startswith("\xFE\xFF"))
137 BOM = "UTF-16 (BE)";
138 else if (BufStr.startswith("\xFF\xFE"))
139 BOM = "UTF-16 (LE)";
140 else if (BufStr.startswith(llvm::StringRef("\x00\x00\xFE\xFF", 4)))
141 BOM = "UTF-32 (BE)";
142 else if (BufStr.startswith(llvm::StringRef("\xFF\xFE\x00\x00", 4)))
143 BOM = "UTF-32 (LE)";
144 else if (BufStr.startswith("\x2B\x2F\x76"))
145 BOM = "UTF-7";
146 else if (BufStr.startswith("\xF7\x64\x4C"))
147 BOM = "UTF-1";
148 else if (BufStr.startswith("\xDD\x73\x66\x73"))
149 BOM = "UTF-EBCDIC";
150 else if (BufStr.startswith("\x0E\xFE\xFF"))
151 BOM = "SDSU";
152 else if (BufStr.startswith("\xFB\xEE\x28"))
153 BOM = "BOCU-1";
154 else if (BufStr.startswith("\x84\x31\x95\x33"))
155 BOM = "BOCU-1";
156
157 if (BOM) {
Chris Lattnere127a0d2010-04-20 20:35:58 +0000158 Diag.Report(FullSourceLoc(Loc, SM), diag::err_unsupported_bom)
159 << BOM << Entry->getName();
Chris Lattner38caec42010-04-20 18:14:03 +0000160 Buffer.setInt(1);
161 }
162 }
Ted Kremenek5b034ad2009-01-06 22:43:04 +0000163 }
Douglas Gregoraea67db2010-03-15 22:54:52 +0000164
Douglas Gregorc8151082010-03-16 22:53:51 +0000165 if (Invalid)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000166 *Invalid = isBufferInvalid();
Douglas Gregorc8151082010-03-16 22:53:51 +0000167
168 return Buffer.getPointer();
Ted Kremenekc16c2082009-01-06 01:55:26 +0000169}
170
Chris Lattner5b9a5042009-01-26 07:57:50 +0000171unsigned LineTableInfo::getLineTableFilenameID(const char *Ptr, unsigned Len) {
172 // Look up the filename in the string table, returning the pre-existing value
173 // if it exists.
Mike Stump1eb44332009-09-09 15:08:12 +0000174 llvm::StringMapEntry<unsigned> &Entry =
Chris Lattner5b9a5042009-01-26 07:57:50 +0000175 FilenameIDs.GetOrCreateValue(Ptr, Ptr+Len, ~0U);
176 if (Entry.getValue() != ~0U)
177 return Entry.getValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000178
Chris Lattner5b9a5042009-01-26 07:57:50 +0000179 // Otherwise, assign this the next available ID.
180 Entry.setValue(FilenamesByID.size());
181 FilenamesByID.push_back(&Entry);
182 return FilenamesByID.size()-1;
183}
184
Chris Lattnerac50e342009-02-03 22:13:05 +0000185/// AddLineNote - Add a line note to the line table that indicates that there
186/// is a #line at the specified FID/Offset location which changes the presumed
187/// location to LineNo/FilenameID.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000188void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
Chris Lattnerac50e342009-02-03 22:13:05 +0000189 unsigned LineNo, int FilenameID) {
Chris Lattner23b5dc62009-02-04 00:40:31 +0000190 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000191
Chris Lattner23b5dc62009-02-04 00:40:31 +0000192 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
193 "Adding line entries out of order!");
Mike Stump1eb44332009-09-09 15:08:12 +0000194
Chris Lattner9d79eba2009-02-04 05:21:58 +0000195 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
Chris Lattner137b6a62009-02-04 06:25:26 +0000196 unsigned IncludeOffset = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000197
Chris Lattner9d79eba2009-02-04 05:21:58 +0000198 if (!Entries.empty()) {
199 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
200 // that we are still in "foo.h".
201 if (FilenameID == -1)
202 FilenameID = Entries.back().FilenameID;
Mike Stump1eb44332009-09-09 15:08:12 +0000203
Chris Lattner137b6a62009-02-04 06:25:26 +0000204 // If we are after a line marker that switched us to system header mode, or
205 // that set #include information, preserve it.
Chris Lattner9d79eba2009-02-04 05:21:58 +0000206 Kind = Entries.back().FileKind;
Chris Lattner137b6a62009-02-04 06:25:26 +0000207 IncludeOffset = Entries.back().IncludeOffset;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000208 }
Mike Stump1eb44332009-09-09 15:08:12 +0000209
Chris Lattner137b6a62009-02-04 06:25:26 +0000210 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
211 IncludeOffset));
Chris Lattnerac50e342009-02-03 22:13:05 +0000212}
213
Chris Lattner9d79eba2009-02-04 05:21:58 +0000214/// AddLineNote This is the same as the previous version of AddLineNote, but is
215/// used for GNU line markers. If EntryExit is 0, then this doesn't change the
216/// presumed #include stack. If it is 1, this is a file entry, if it is 2 then
217/// this is a file exit. FileKind specifies whether this is a system header or
218/// extern C system header.
219void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
220 unsigned LineNo, int FilenameID,
221 unsigned EntryExit,
222 SrcMgr::CharacteristicKind FileKind) {
223 assert(FilenameID != -1 && "Unspecified filename should use other accessor");
Mike Stump1eb44332009-09-09 15:08:12 +0000224
Chris Lattner9d79eba2009-02-04 05:21:58 +0000225 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000226
Chris Lattner9d79eba2009-02-04 05:21:58 +0000227 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
228 "Adding line entries out of order!");
229
Chris Lattner137b6a62009-02-04 06:25:26 +0000230 unsigned IncludeOffset = 0;
231 if (EntryExit == 0) { // No #include stack change.
232 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
233 } else if (EntryExit == 1) {
234 IncludeOffset = Offset-1;
235 } else if (EntryExit == 2) {
236 assert(!Entries.empty() && Entries.back().IncludeOffset &&
237 "PPDirectives should have caught case when popping empty include stack");
Mike Stump1eb44332009-09-09 15:08:12 +0000238
Chris Lattner137b6a62009-02-04 06:25:26 +0000239 // Get the include loc of the last entries' include loc as our include loc.
240 IncludeOffset = 0;
241 if (const LineEntry *PrevEntry =
242 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
243 IncludeOffset = PrevEntry->IncludeOffset;
244 }
Mike Stump1eb44332009-09-09 15:08:12 +0000245
Chris Lattner137b6a62009-02-04 06:25:26 +0000246 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
247 IncludeOffset));
Chris Lattner9d79eba2009-02-04 05:21:58 +0000248}
249
250
Chris Lattner3cd949c2009-02-04 01:55:42 +0000251/// FindNearestLineEntry - Find the line entry nearest to FID that is before
252/// it. If there is no line entry before Offset in FID, return null.
Mike Stump1eb44332009-09-09 15:08:12 +0000253const LineEntry *LineTableInfo::FindNearestLineEntry(unsigned FID,
Chris Lattner3cd949c2009-02-04 01:55:42 +0000254 unsigned Offset) {
255 const std::vector<LineEntry> &Entries = LineEntries[FID];
256 assert(!Entries.empty() && "No #line entries for this FID after all!");
257
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000258 // It is very common for the query to be after the last #line, check this
259 // first.
260 if (Entries.back().FileOffset <= Offset)
261 return &Entries.back();
Chris Lattner3cd949c2009-02-04 01:55:42 +0000262
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000263 // Do a binary search to find the maximal element that is still before Offset.
264 std::vector<LineEntry>::const_iterator I =
265 std::upper_bound(Entries.begin(), Entries.end(), Offset);
266 if (I == Entries.begin()) return 0;
267 return &*--I;
Chris Lattner3cd949c2009-02-04 01:55:42 +0000268}
Chris Lattnerac50e342009-02-03 22:13:05 +0000269
Douglas Gregorbd945002009-04-13 16:31:14 +0000270/// \brief Add a new line entry that has already been encoded into
271/// the internal representation of the line table.
Mike Stump1eb44332009-09-09 15:08:12 +0000272void LineTableInfo::AddEntry(unsigned FID,
Douglas Gregorbd945002009-04-13 16:31:14 +0000273 const std::vector<LineEntry> &Entries) {
274 LineEntries[FID] = Entries;
275}
Chris Lattnerac50e342009-02-03 22:13:05 +0000276
Chris Lattner5b9a5042009-01-26 07:57:50 +0000277/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
Mike Stump1eb44332009-09-09 15:08:12 +0000278///
Chris Lattner5b9a5042009-01-26 07:57:50 +0000279unsigned SourceManager::getLineTableFilenameID(const char *Ptr, unsigned Len) {
280 if (LineTable == 0)
281 LineTable = new LineTableInfo();
282 return LineTable->getLineTableFilenameID(Ptr, Len);
283}
284
285
Chris Lattner4c4ea172009-02-03 21:52:55 +0000286/// AddLineNote - Add a line note to the line table for the FileID and offset
287/// specified by Loc. If FilenameID is -1, it is considered to be
288/// unspecified.
289void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
290 int FilenameID) {
Chris Lattnerac50e342009-02-03 22:13:05 +0000291 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000292
Chris Lattnerac50e342009-02-03 22:13:05 +0000293 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
294
295 // Remember that this file has #line directives now if it doesn't already.
296 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000297
Chris Lattnerac50e342009-02-03 22:13:05 +0000298 if (LineTable == 0)
299 LineTable = new LineTableInfo();
Chris Lattner23b5dc62009-02-04 00:40:31 +0000300 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID);
Chris Lattner4c4ea172009-02-03 21:52:55 +0000301}
302
Chris Lattner9d79eba2009-02-04 05:21:58 +0000303/// AddLineNote - Add a GNU line marker to the line table.
304void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
305 int FilenameID, bool IsFileEntry,
306 bool IsFileExit, bool IsSystemHeader,
307 bool IsExternCHeader) {
308 // If there is no filename and no flags, this is treated just like a #line,
309 // which does not change the flags of the previous line marker.
310 if (FilenameID == -1) {
311 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
312 "Can't set flags without setting the filename!");
313 return AddLineNote(Loc, LineNo, FilenameID);
314 }
Mike Stump1eb44332009-09-09 15:08:12 +0000315
Chris Lattner9d79eba2009-02-04 05:21:58 +0000316 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
317 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000318
Chris Lattner9d79eba2009-02-04 05:21:58 +0000319 // Remember that this file has #line directives now if it doesn't already.
320 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000321
Chris Lattner9d79eba2009-02-04 05:21:58 +0000322 if (LineTable == 0)
323 LineTable = new LineTableInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000324
Chris Lattner9d79eba2009-02-04 05:21:58 +0000325 SrcMgr::CharacteristicKind FileKind;
326 if (IsExternCHeader)
327 FileKind = SrcMgr::C_ExternCSystem;
328 else if (IsSystemHeader)
329 FileKind = SrcMgr::C_System;
330 else
331 FileKind = SrcMgr::C_User;
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Chris Lattner9d79eba2009-02-04 05:21:58 +0000333 unsigned EntryExit = 0;
334 if (IsFileEntry)
335 EntryExit = 1;
336 else if (IsFileExit)
337 EntryExit = 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Chris Lattner9d79eba2009-02-04 05:21:58 +0000339 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID,
340 EntryExit, FileKind);
341}
342
Douglas Gregorbd945002009-04-13 16:31:14 +0000343LineTableInfo &SourceManager::getLineTable() {
344 if (LineTable == 0)
345 LineTable = new LineTableInfo();
346 return *LineTable;
347}
Chris Lattner4c4ea172009-02-03 21:52:55 +0000348
Chris Lattner23b5dc62009-02-04 00:40:31 +0000349//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000350// Private 'Create' methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000351//===----------------------------------------------------------------------===//
Ted Kremenekc16c2082009-01-06 01:55:26 +0000352
Chris Lattner5b9a5042009-01-26 07:57:50 +0000353SourceManager::~SourceManager() {
354 delete LineTable;
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000356 // Delete FileEntry objects corresponding to content caches. Since the actual
357 // content cache objects are bump pointer allocated, we just have to run the
358 // dtors, but we call the deallocate method for completeness.
359 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
360 MemBufferInfos[i]->~ContentCache();
361 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
362 }
363 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
364 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
365 I->second->~ContentCache();
366 ContentCacheAlloc.Deallocate(I->second);
367 }
Chris Lattner5b9a5042009-01-26 07:57:50 +0000368}
369
370void SourceManager::clearIDTables() {
371 MainFileID = FileID();
372 SLocEntryTable.clear();
373 LastLineNoFileIDQuery = FileID();
374 LastLineNoContentCache = 0;
375 LastFileIDLookup = FileID();
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Chris Lattner5b9a5042009-01-26 07:57:50 +0000377 if (LineTable)
378 LineTable->clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000379
Chris Lattner5b9a5042009-01-26 07:57:50 +0000380 // Use up FileID #0 as an invalid instantiation.
381 NextOffset = 0;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000382 createInstantiationLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000383}
384
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000385/// getOrCreateContentCache - Create or return a cached ContentCache for the
386/// specified file.
387const ContentCache *
388SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000389 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump1eb44332009-09-09 15:08:12 +0000390
Reid Spencer5f016e22007-07-11 17:01:13 +0000391 // Do we already have information about this file?
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000392 ContentCache *&Entry = FileInfos[FileEnt];
393 if (Entry) return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Chris Lattner00282d62009-02-03 07:41:46 +0000395 // Nope, create a new Cache entry. Make sure it is at least 8-byte aligned
396 // so that FileInfo can use the low 3 bits of the pointer for its own
397 // nefarious purposes.
398 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
399 EntryAlign = std::max(8U, EntryAlign);
400 Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000401 new (Entry) ContentCache(FileEnt);
402 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000403}
404
405
Ted Kremenekd1c0eee2007-10-31 17:53:38 +0000406/// createMemBufferContentCache - Create a new ContentCache for the specified
407/// memory buffer. This does no caching.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000408const ContentCache*
409SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
Chris Lattner00282d62009-02-03 07:41:46 +0000410 // Add a new ContentCache to the MemBufferInfos list and return it. Make sure
411 // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of
412 // the pointer for its own nefarious purposes.
413 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
414 EntryAlign = std::max(8U, EntryAlign);
415 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000416 new (Entry) ContentCache();
417 MemBufferInfos.push_back(Entry);
418 Entry->setBuffer(Buffer);
419 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000420}
421
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000422void SourceManager::PreallocateSLocEntries(ExternalSLocEntrySource *Source,
423 unsigned NumSLocEntries,
424 unsigned NextOffset) {
425 ExternalSLocEntries = Source;
426 this->NextOffset = NextOffset;
Sebastian Redlb86238d2010-07-28 21:07:02 +0000427 unsigned CurPrealloc = SLocEntryLoaded.size();
428 // If we've ever preallocated, we must not count the dummy entry.
429 if (CurPrealloc) --CurPrealloc;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000430 SLocEntryLoaded.resize(NumSLocEntries + 1);
431 SLocEntryLoaded[0] = true;
Sebastian Redlb86238d2010-07-28 21:07:02 +0000432 SLocEntryTable.resize(SLocEntryTable.size() + NumSLocEntries - CurPrealloc);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000433}
434
Douglas Gregor2bf1eb02009-04-27 21:28:04 +0000435void SourceManager::ClearPreallocatedSLocEntries() {
436 unsigned I = 0;
437 for (unsigned N = SLocEntryLoaded.size(); I != N; ++I)
438 if (!SLocEntryLoaded[I])
439 break;
440
441 // We've already loaded all preallocated source location entries.
442 if (I == SLocEntryLoaded.size())
443 return;
444
445 // Remove everything from location I onward.
446 SLocEntryTable.resize(I);
447 SLocEntryLoaded.clear();
448 ExternalSLocEntries = 0;
449}
450
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000451
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000452//===----------------------------------------------------------------------===//
453// Methods to create new FileID's and instantiations.
454//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000455
Dan Gohman3f86b782010-08-26 21:27:06 +0000456/// createFileID - Create a new FileID for the specified ContentCache and
Ted Kremenek0d892d82007-10-30 22:57:35 +0000457/// include position. This works regardless of whether the ContentCache
458/// corresponds to a file or some other input source.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000459FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000460 SourceLocation IncludePos,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000461 SrcMgr::CharacteristicKind FileCharacter,
462 unsigned PreallocatedID,
463 unsigned Offset) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000464 if (PreallocatedID) {
465 // If we're filling in a preallocated ID, just load in the file
466 // entry and return.
Mike Stump1eb44332009-09-09 15:08:12 +0000467 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000468 "Preallocate ID out-of-range");
Mike Stump1eb44332009-09-09 15:08:12 +0000469 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000470 "Source location entry already loaded");
471 assert(Offset && "Preallocate source location cannot have zero offset");
Mike Stump1eb44332009-09-09 15:08:12 +0000472 SLocEntryTable[PreallocatedID]
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000473 = SLocEntry::get(Offset, FileInfo::get(IncludePos, File, FileCharacter));
474 SLocEntryLoaded[PreallocatedID] = true;
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +0000475 FileID FID = FileID::get(PreallocatedID);
Douglas Gregor5de65722010-03-19 06:12:06 +0000476 return FID;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000477 }
478
Mike Stump1eb44332009-09-09 15:08:12 +0000479 SLocEntryTable.push_back(SLocEntry::get(NextOffset,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000480 FileInfo::get(IncludePos, File,
481 FileCharacter)));
Ted Kremenekc16c2082009-01-06 01:55:26 +0000482 unsigned FileSize = File->getSize();
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000483 assert(NextOffset+FileSize+1 > NextOffset && "Ran out of source locations!");
484 NextOffset += FileSize+1;
Mike Stump1eb44332009-09-09 15:08:12 +0000485
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000486 // Set LastFileIDLookup to the newly created file. The next getFileID call is
487 // almost guaranteed to be from that file.
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000488 FileID FID = FileID::get(SLocEntryTable.size()-1);
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000489 return LastFileIDLookup = FID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000490}
491
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000492/// createInstantiationLoc - Return a new SourceLocation that encodes the fact
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000493/// that a token from SpellingLoc should actually be referenced from
Reid Spencer5f016e22007-07-11 17:01:13 +0000494/// InstantiationLoc.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000495SourceLocation SourceManager::createInstantiationLoc(SourceLocation SpellingLoc,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000496 SourceLocation ILocStart,
497 SourceLocation ILocEnd,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000498 unsigned TokLength,
499 unsigned PreallocatedID,
500 unsigned Offset) {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000501 InstantiationInfo II = InstantiationInfo::get(ILocStart,ILocEnd, SpellingLoc);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000502 if (PreallocatedID) {
503 // If we're filling in a preallocated ID, just load in the
504 // instantiation entry and return.
Mike Stump1eb44332009-09-09 15:08:12 +0000505 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000506 "Preallocate ID out-of-range");
Mike Stump1eb44332009-09-09 15:08:12 +0000507 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000508 "Source location entry already loaded");
509 assert(Offset && "Preallocate source location cannot have zero offset");
510 SLocEntryTable[PreallocatedID] = SLocEntry::get(Offset, II);
511 SLocEntryLoaded[PreallocatedID] = true;
512 return SourceLocation::getMacroLoc(Offset);
513 }
Chris Lattnere7fb4842009-02-15 20:52:18 +0000514 SLocEntryTable.push_back(SLocEntry::get(NextOffset, II));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000515 assert(NextOffset+TokLength+1 > NextOffset && "Ran out of source locations!");
516 NextOffset += TokLength+1;
517 return SourceLocation::getMacroLoc(NextOffset-(TokLength+1));
Reid Spencer5f016e22007-07-11 17:01:13 +0000518}
519
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000520const llvm::MemoryBuffer *
Douglas Gregor50f6af72010-03-16 05:20:39 +0000521SourceManager::getMemoryBufferForFile(const FileEntry *File,
522 bool *Invalid) {
Douglas Gregor29684422009-12-02 06:49:09 +0000523 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregoraea67db2010-03-15 22:54:52 +0000524 assert(IR && "getOrCreateContentCache() cannot return NULL");
Chris Lattnere127a0d2010-04-20 20:35:58 +0000525 return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
Douglas Gregor29684422009-12-02 06:49:09 +0000526}
527
Dan Gohman0d06e992010-10-26 20:47:28 +0000528void SourceManager::overrideFileContents(const FileEntry *SourceFile,
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000529 const llvm::MemoryBuffer *Buffer,
530 bool DoNotFree) {
Douglas Gregor29684422009-12-02 06:49:09 +0000531 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
Dan Gohman0d06e992010-10-26 20:47:28 +0000532 assert(IR && "getOrCreateContentCache() cannot return NULL");
Douglas Gregor29684422009-12-02 06:49:09 +0000533
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000534 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
Douglas Gregor29684422009-12-02 06:49:09 +0000535}
536
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000537llvm::StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
Douglas Gregoraae58b02010-03-16 20:01:30 +0000538 bool MyInvalid = false;
539 const llvm::MemoryBuffer *Buf = getBuffer(FID, &MyInvalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000540 if (Invalid)
Douglas Gregoraae58b02010-03-16 20:01:30 +0000541 *Invalid = MyInvalid;
542
543 if (MyInvalid)
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000544 return "";
Douglas Gregoraae58b02010-03-16 20:01:30 +0000545
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000546 return Buf->getBuffer();
Douglas Gregoraea67db2010-03-15 22:54:52 +0000547}
Chris Lattner2b2453a2009-01-17 06:22:33 +0000548
Chris Lattner23b5dc62009-02-04 00:40:31 +0000549//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000550// SourceLocation manipulation methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000551//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000552
553/// getFileIDSlow - Return the FileID for a SourceLocation. This is a very hot
554/// method that is used for all SourceManager queries that start with a
555/// SourceLocation object. It is responsible for finding the entry in
556/// SLocEntryTable which contains the specified location.
557///
558FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
559 assert(SLocOffset && "Invalid FileID");
Mike Stump1eb44332009-09-09 15:08:12 +0000560
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000561 // After the first and second level caches, I see two common sorts of
562 // behavior: 1) a lot of searched FileID's are "near" the cached file location
563 // or are "near" the cached instantiation location. 2) others are just
564 // completely random and may be a very long way away.
565 //
566 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
567 // then we fall back to a less cache efficient, but more scalable, binary
568 // search to find the location.
Mike Stump1eb44332009-09-09 15:08:12 +0000569
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000570 // See if this is near the file point - worst case we start scanning from the
571 // most newly created FileID.
572 std::vector<SrcMgr::SLocEntry>::const_iterator I;
Mike Stump1eb44332009-09-09 15:08:12 +0000573
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000574 if (SLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
575 // Neither loc prunes our search.
576 I = SLocEntryTable.end();
577 } else {
578 // Perhaps it is near the file point.
579 I = SLocEntryTable.begin()+LastFileIDLookup.ID;
580 }
581
582 // Find the FileID that contains this. "I" is an iterator that points to a
583 // FileID whose offset is known to be larger than SLocOffset.
584 unsigned NumProbes = 0;
585 while (1) {
586 --I;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000587 if (ExternalSLocEntries)
588 getSLocEntry(FileID::get(I - SLocEntryTable.begin()));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000589 if (I->getOffset() <= SLocOffset) {
590#if 0
591 printf("lin %d -> %d [%s] %d %d\n", SLocOffset,
592 I-SLocEntryTable.begin(),
593 I->isInstantiation() ? "inst" : "file",
594 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
595#endif
596 FileID Res = FileID::get(I-SLocEntryTable.begin());
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000597
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000598 // If this isn't an instantiation, remember it. We have good locality
599 // across FileID lookups.
600 if (!I->isInstantiation())
601 LastFileIDLookup = Res;
602 NumLinearScans += NumProbes+1;
603 return Res;
604 }
605 if (++NumProbes == 8)
606 break;
607 }
Mike Stump1eb44332009-09-09 15:08:12 +0000608
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000609 // Convert "I" back into an index. We know that it is an entry whose index is
610 // larger than the offset we are looking for.
611 unsigned GreaterIndex = I-SLocEntryTable.begin();
612 // LessIndex - This is the lower bound of the range that we're searching.
613 // We know that the offset corresponding to the FileID is is less than
614 // SLocOffset.
615 unsigned LessIndex = 0;
616 NumProbes = 0;
617 while (1) {
618 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000619 unsigned MidOffset = getSLocEntry(FileID::get(MiddleIndex)).getOffset();
Mike Stump1eb44332009-09-09 15:08:12 +0000620
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000621 ++NumProbes;
Mike Stump1eb44332009-09-09 15:08:12 +0000622
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000623 // If the offset of the midpoint is too large, chop the high side of the
624 // range to the midpoint.
625 if (MidOffset > SLocOffset) {
626 GreaterIndex = MiddleIndex;
627 continue;
628 }
Mike Stump1eb44332009-09-09 15:08:12 +0000629
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000630 // If the middle index contains the value, succeed and return.
631 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
632#if 0
633 printf("bin %d -> %d [%s] %d %d\n", SLocOffset,
634 I-SLocEntryTable.begin(),
635 I->isInstantiation() ? "inst" : "file",
636 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
637#endif
638 FileID Res = FileID::get(MiddleIndex);
639
640 // If this isn't an instantiation, remember it. We have good locality
641 // across FileID lookups.
642 if (!I->isInstantiation())
643 LastFileIDLookup = Res;
644 NumBinaryProbes += NumProbes;
645 return Res;
646 }
Mike Stump1eb44332009-09-09 15:08:12 +0000647
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000648 // Otherwise, move the low-side up to the middle index.
649 LessIndex = MiddleIndex;
650 }
651}
652
Chris Lattneraddb7972009-01-26 20:04:19 +0000653SourceLocation SourceManager::
654getInstantiationLocSlowCase(SourceLocation Loc) const {
655 do {
Chris Lattnera5c6c582010-02-12 19:31:35 +0000656 // Note: If Loc indicates an offset into a token that came from a macro
657 // expansion (e.g. the 5th character of the token) we do not want to add
658 // this offset when going to the instantiation location. The instatiation
659 // location is the macro invocation, which the offset has nothing to do
660 // with. This is unlike when we get the spelling loc, because the offset
661 // directly correspond to the token whose spelling we're inspecting.
662 Loc = getSLocEntry(getFileID(Loc)).getInstantiation()
Chris Lattnere7fb4842009-02-15 20:52:18 +0000663 .getInstantiationLocStart();
Chris Lattneraddb7972009-01-26 20:04:19 +0000664 } while (!Loc.isFileID());
665
666 return Loc;
667}
668
669SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
670 do {
671 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
672 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
673 Loc = Loc.getFileLocWithOffset(LocInfo.second);
674 } while (!Loc.isFileID());
675 return Loc;
676}
677
678
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000679std::pair<FileID, unsigned>
680SourceManager::getDecomposedInstantiationLocSlowCase(const SrcMgr::SLocEntry *E,
681 unsigned Offset) const {
682 // If this is an instantiation record, walk through all the instantiation
683 // points.
684 FileID FID;
685 SourceLocation Loc;
686 do {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000687 Loc = E->getInstantiation().getInstantiationLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000688
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000689 FID = getFileID(Loc);
690 E = &getSLocEntry(FID);
691 Offset += Loc.getOffset()-E->getOffset();
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000692 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000693
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000694 return std::make_pair(FID, Offset);
695}
696
697std::pair<FileID, unsigned>
698SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
699 unsigned Offset) const {
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000700 // If this is an instantiation record, walk through all the instantiation
701 // points.
702 FileID FID;
703 SourceLocation Loc;
704 do {
705 Loc = E->getInstantiation().getSpellingLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000706
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000707 FID = getFileID(Loc);
708 E = &getSLocEntry(FID);
709 Offset += Loc.getOffset()-E->getOffset();
710 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000711
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000712 return std::make_pair(FID, Offset);
713}
714
Chris Lattner387616e2009-02-17 08:04:48 +0000715/// getImmediateSpellingLoc - Given a SourceLocation object, return the
716/// spelling location referenced by the ID. This is the first level down
717/// towards the place where the characters that make up the lexed token can be
718/// found. This should not generally be used by clients.
719SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
720 if (Loc.isFileID()) return Loc;
721 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
722 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
723 return Loc.getFileLocWithOffset(LocInfo.second);
724}
725
726
Chris Lattnere7fb4842009-02-15 20:52:18 +0000727/// getImmediateInstantiationRange - Loc is required to be an instantiation
728/// location. Return the start/end of the instantiation information.
729std::pair<SourceLocation,SourceLocation>
730SourceManager::getImmediateInstantiationRange(SourceLocation Loc) const {
731 assert(Loc.isMacroID() && "Not an instantiation loc!");
732 const InstantiationInfo &II = getSLocEntry(getFileID(Loc)).getInstantiation();
733 return II.getInstantiationLocRange();
734}
735
Chris Lattner66781332009-02-15 21:26:50 +0000736/// getInstantiationRange - Given a SourceLocation object, return the
737/// range of tokens covered by the instantiation in the ultimate file.
738std::pair<SourceLocation,SourceLocation>
739SourceManager::getInstantiationRange(SourceLocation Loc) const {
740 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000741
Chris Lattner66781332009-02-15 21:26:50 +0000742 std::pair<SourceLocation,SourceLocation> Res =
743 getImmediateInstantiationRange(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000744
Chris Lattner66781332009-02-15 21:26:50 +0000745 // Fully resolve the start and end locations to their ultimate instantiation
746 // points.
747 while (!Res.first.isFileID())
748 Res.first = getImmediateInstantiationRange(Res.first).first;
749 while (!Res.second.isFileID())
750 Res.second = getImmediateInstantiationRange(Res.second).second;
751 return Res;
752}
753
Chris Lattnere7fb4842009-02-15 20:52:18 +0000754
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000755
756//===----------------------------------------------------------------------===//
757// Queries about the code at a SourceLocation.
758//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000759
760/// getCharacterData - Return a pointer to the start of the specified location
761/// in the appropriate MemoryBuffer.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000762const char *SourceManager::getCharacterData(SourceLocation SL,
763 bool *Invalid) const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000764 // Note that this is a hot function in the getSpelling() path, which is
765 // heavily used by -E mode.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000766 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump1eb44332009-09-09 15:08:12 +0000767
Ted Kremenekc16c2082009-01-06 01:55:26 +0000768 // Note that calling 'getBuffer()' may lazily page in a source file.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000769 bool CharDataInvalid = false;
770 const llvm::MemoryBuffer *Buffer
Chris Lattnere127a0d2010-04-20 20:35:58 +0000771 = getSLocEntry(LocInfo.first).getFile().getContentCache()
772 ->getBuffer(Diag, *this, SourceLocation(), &CharDataInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000773 if (Invalid)
774 *Invalid = CharDataInvalid;
775 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
Reid Spencer5f016e22007-07-11 17:01:13 +0000776}
777
Reid Spencer5f016e22007-07-11 17:01:13 +0000778
Chris Lattner9dc1f532007-07-20 16:37:10 +0000779/// getColumnNumber - Return the column # for the specified file position.
Chris Lattner7da5aea2009-02-04 00:55:58 +0000780/// this is significantly cheaper to compute than the line number.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000781unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
782 bool *Invalid) const {
783 bool MyInvalid = false;
784 const char *Buf = getBuffer(FID, &MyInvalid)->getBufferStart();
785 if (Invalid)
786 *Invalid = MyInvalid;
787
788 if (MyInvalid)
789 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000790
Reid Spencer5f016e22007-07-11 17:01:13 +0000791 unsigned LineStart = FilePos;
792 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
793 --LineStart;
794 return FilePos-LineStart+1;
795}
796
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000797// isInvalid - Return the result of calling loc.isInvalid(), and
798// if Invalid is not null, set its value to same.
799static bool isInvalid(SourceLocation Loc, bool *Invalid) {
800 bool MyInvalid = Loc.isInvalid();
801 if (Invalid)
802 *Invalid = MyInvalid;
803 return MyInvalid;
804}
805
Douglas Gregor50f6af72010-03-16 05:20:39 +0000806unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
807 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000808 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000809 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000810 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000811}
812
Douglas Gregor50f6af72010-03-16 05:20:39 +0000813unsigned SourceManager::getInstantiationColumnNumber(SourceLocation Loc,
814 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000815 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000816 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000817 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000818}
819
Chandler Carruth14bd9652010-10-23 08:44:57 +0000820static LLVM_ATTRIBUTE_NOINLINE void
Chris Lattnere127a0d2010-04-20 20:35:58 +0000821ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
822 llvm::BumpPtrAllocator &Alloc,
823 const SourceManager &SM, bool &Invalid);
824static void ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
825 llvm::BumpPtrAllocator &Alloc,
826 const SourceManager &SM, bool &Invalid) {
Ted Kremenekc16c2082009-01-06 01:55:26 +0000827 // Note that calling 'getBuffer()' may lazily page in the file.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000828 const MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(),
829 &Invalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000830 if (Invalid)
831 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000832
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000833 // Find the file offsets of all of the *physical* source lines. This does
834 // not look at trigraphs, escaped newlines, or anything else tricky.
835 std::vector<unsigned> LineOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +0000836
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000837 // Line #1 starts at char 0.
838 LineOffsets.push_back(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000839
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000840 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
841 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
842 unsigned Offs = 0;
843 while (1) {
844 // Skip over the contents of the line.
845 // TODO: Vectorize this? This is very performance sensitive for programs
846 // with lots of diagnostics and in -E mode.
847 const unsigned char *NextBuf = (const unsigned char *)Buf;
848 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
849 ++NextBuf;
850 Offs += NextBuf-Buf;
851 Buf = NextBuf;
Mike Stump1eb44332009-09-09 15:08:12 +0000852
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000853 if (Buf[0] == '\n' || Buf[0] == '\r') {
854 // If this is \n\r or \r\n, skip both characters.
855 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
856 ++Offs, ++Buf;
857 ++Offs, ++Buf;
858 LineOffsets.push_back(Offs);
859 } else {
860 // Otherwise, this is a null. If end of file, exit.
861 if (Buf == End) break;
862 // Otherwise, skip the null.
863 ++Offs, ++Buf;
864 }
865 }
Mike Stump1eb44332009-09-09 15:08:12 +0000866
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000867 // Copy the offsets into the FileInfo structure.
868 FI->NumLines = LineOffsets.size();
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000869 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000870 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
871}
Reid Spencer5f016e22007-07-11 17:01:13 +0000872
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000873/// getLineNumber - Given a SourceLocation, return the spelling line number
Reid Spencer5f016e22007-07-11 17:01:13 +0000874/// for the position indicated. This requires building and caching a table of
875/// line offsets for the MemoryBuffer, so this is not cheap: use only when
876/// about to emit a diagnostic.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000877unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
878 bool *Invalid) const {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000879 ContentCache *Content;
Chris Lattner30fc9332009-02-04 01:06:56 +0000880 if (LastLineNoFileIDQuery == FID)
Ted Kremenek78d85f52007-10-30 21:08:08 +0000881 Content = LastLineNoContentCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000882 else
Chris Lattner30fc9332009-02-04 01:06:56 +0000883 Content = const_cast<ContentCache*>(getSLocEntry(FID)
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000884 .getFile().getContentCache());
Mike Stump1eb44332009-09-09 15:08:12 +0000885
Reid Spencer5f016e22007-07-11 17:01:13 +0000886 // If this is the first use of line information for this buffer, compute the
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000887 /// SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000888 if (Content->SourceLineCache == 0) {
889 bool MyInvalid = false;
Chris Lattnere127a0d2010-04-20 20:35:58 +0000890 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000891 if (Invalid)
892 *Invalid = MyInvalid;
893 if (MyInvalid)
894 return 1;
895 } else if (Invalid)
896 *Invalid = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000897
898 // Okay, we know we have a line number table. Do a binary search to find the
899 // line number that this character position lands on.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000900 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000901 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenek78d85f52007-10-30 21:08:08 +0000902 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump1eb44332009-09-09 15:08:12 +0000903
Chris Lattner30fc9332009-02-04 01:06:56 +0000904 unsigned QueriedFilePos = FilePos+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000905
Daniel Dunbar4106d692009-05-18 17:30:52 +0000906 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump1eb44332009-09-09 15:08:12 +0000907 // complicated as it is, binary search isn't that slow.
Daniel Dunbar4106d692009-05-18 17:30:52 +0000908 //
909 // If it is worth being optimized, then in my opinion it could be more
910 // performant, simpler, and more obviously correct by just "galloping" outward
911 // from the queried file position. In fact, this could be incorporated into a
912 // generic algorithm such as lower_bound_with_hint.
913 //
914 // If someone gives me a test case where this matters, and I will do it! - DWD
915
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000916 // If the previous query was to the same file, we know both the file pos from
917 // that query and the line number returned. This allows us to narrow the
918 // search space from the entire file to something near the match.
Chris Lattner30fc9332009-02-04 01:06:56 +0000919 if (LastLineNoFileIDQuery == FID) {
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000920 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar4106d692009-05-18 17:30:52 +0000921 // FIXME: Potential overflow?
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000922 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump1eb44332009-09-09 15:08:12 +0000923
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000924 // The query is likely to be nearby the previous one. Here we check to
925 // see if it is within 5, 10 or 20 lines. It can be far away in cases
926 // where big comment blocks and vertical whitespace eat up lines but
927 // contribute no tokens.
928 if (SourceLineCache+5 < SourceLineCacheEnd) {
929 if (SourceLineCache[5] > QueriedFilePos)
930 SourceLineCacheEnd = SourceLineCache+5;
931 else if (SourceLineCache+10 < SourceLineCacheEnd) {
932 if (SourceLineCache[10] > QueriedFilePos)
933 SourceLineCacheEnd = SourceLineCache+10;
934 else if (SourceLineCache+20 < SourceLineCacheEnd) {
935 if (SourceLineCache[20] > QueriedFilePos)
936 SourceLineCacheEnd = SourceLineCache+20;
937 }
938 }
939 }
940 } else {
Daniel Dunbar4106d692009-05-18 17:30:52 +0000941 if (LastLineNoResult < Content->NumLines)
942 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000943 }
944 }
Mike Stump1eb44332009-09-09 15:08:12 +0000945
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000946 // If the spread is large, do a "radix" test as our initial guess, based on
947 // the assumption that lines average to approximately the same length.
948 // NOTE: This is currently disabled, as it does not appear to be profitable in
949 // initial measurements.
950 if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
Ted Kremenek78d85f52007-10-30 21:08:08 +0000951 unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
Mike Stump1eb44332009-09-09 15:08:12 +0000952
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000953 // Take a stab at guessing where it is.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000954 unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
Mike Stump1eb44332009-09-09 15:08:12 +0000955
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000956 // Check for -10 and +10 lines.
957 unsigned LowerBound = std::max(int(ApproxPos-10), 0);
958 unsigned UpperBound = std::min(ApproxPos+10, FileLen);
959
960 // If the computed lower bound is less than the query location, move it in.
961 if (SourceLineCache < SourceLineCacheStart+LowerBound &&
962 SourceLineCacheStart[LowerBound] < QueriedFilePos)
963 SourceLineCache = SourceLineCacheStart+LowerBound;
Mike Stump1eb44332009-09-09 15:08:12 +0000964
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000965 // If the computed upper bound is greater than the query location, move it.
966 if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
967 SourceLineCacheStart[UpperBound] >= QueriedFilePos)
968 SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
969 }
Mike Stump1eb44332009-09-09 15:08:12 +0000970
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000971 unsigned *Pos
972 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000973 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump1eb44332009-09-09 15:08:12 +0000974
Chris Lattner30fc9332009-02-04 01:06:56 +0000975 LastLineNoFileIDQuery = FID;
Ted Kremenek78d85f52007-10-30 21:08:08 +0000976 LastLineNoContentCache = Content;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000977 LastLineNoFilePos = QueriedFilePos;
978 LastLineNoResult = LineNo;
979 return LineNo;
Reid Spencer5f016e22007-07-11 17:01:13 +0000980}
981
Douglas Gregor50f6af72010-03-16 05:20:39 +0000982unsigned SourceManager::getInstantiationLineNumber(SourceLocation Loc,
983 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000984 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner30fc9332009-02-04 01:06:56 +0000985 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
986 return getLineNumber(LocInfo.first, LocInfo.second);
987}
Douglas Gregor50f6af72010-03-16 05:20:39 +0000988unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
989 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000990 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner30fc9332009-02-04 01:06:56 +0000991 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
992 return getLineNumber(LocInfo.first, LocInfo.second);
993}
994
Chris Lattner6b306672009-02-04 05:33:01 +0000995/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump1eb44332009-09-09 15:08:12 +0000996/// source location, indicating whether this is a normal file, a system
Chris Lattner6b306672009-02-04 05:33:01 +0000997/// header, or an "implicit extern C" system header.
998///
999/// This state can be modified with flags on GNU linemarker directives like:
1000/// # 4 "foo.h" 3
1001/// which changes all source locations in the current file after that to be
1002/// considered to be from a system header.
Mike Stump1eb44332009-09-09 15:08:12 +00001003SrcMgr::CharacteristicKind
Chris Lattner6b306672009-02-04 05:33:01 +00001004SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1005 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
1006 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
1007 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
1008
1009 // If there are no #line directives in this file, just return the whole-file
1010 // state.
1011 if (!FI.hasLineDirectives())
1012 return FI.getFileCharacteristic();
Mike Stump1eb44332009-09-09 15:08:12 +00001013
Chris Lattner6b306672009-02-04 05:33:01 +00001014 assert(LineTable && "Can't have linetable entries without a LineTable!");
1015 // See if there is a #line directive before the location.
1016 const LineEntry *Entry =
1017 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001018
Chris Lattner6b306672009-02-04 05:33:01 +00001019 // If this is before the first line marker, use the file characteristic.
1020 if (!Entry)
1021 return FI.getFileCharacteristic();
1022
1023 return Entry->FileKind;
1024}
1025
Chris Lattnerbff5c512009-02-17 08:39:06 +00001026/// Return the filename or buffer identifier of the buffer the location is in.
1027/// Note that this name does not respect #line directives. Use getPresumedLoc
1028/// for normal clients.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001029const char *SourceManager::getBufferName(SourceLocation Loc,
1030 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001031 if (isInvalid(Loc, Invalid)) return "<invalid loc>";
Mike Stump1eb44332009-09-09 15:08:12 +00001032
Douglas Gregor50f6af72010-03-16 05:20:39 +00001033 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
Chris Lattnerbff5c512009-02-17 08:39:06 +00001034}
1035
Chris Lattner30fc9332009-02-04 01:06:56 +00001036
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001037/// getPresumedLoc - This method returns the "presumed" location of a
1038/// SourceLocation specifies. A "presumed location" can be modified by #line
1039/// or GNU line marker directives. This provides a view on the data that a
1040/// user should see in diagnostics, for example.
1041///
1042/// Note that a presumed location is always given as the instantiation point
1043/// of an instantiation location, not at the spelling location.
1044PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
1045 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001046
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001047 // Presumed locations are always for instantiation points.
Chris Lattner7da5aea2009-02-04 00:55:58 +00001048 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +00001049
Chris Lattner30fc9332009-02-04 01:06:56 +00001050 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001051 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump1eb44332009-09-09 15:08:12 +00001052
Chris Lattner3cd949c2009-02-04 01:55:42 +00001053 // To get the source name, first consult the FileEntry (if one exists)
1054 // before the MemBuffer as this will avoid unnecessarily paging in the
1055 // MemBuffer.
Chris Lattnere127a0d2010-04-20 20:35:58 +00001056 const char *Filename;
1057 if (C->Entry)
1058 Filename = C->Entry->getName();
1059 else
1060 Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
Chris Lattner3cd949c2009-02-04 01:55:42 +00001061 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second);
1062 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second);
1063 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001064
Chris Lattner3cd949c2009-02-04 01:55:42 +00001065 // If we have #line directives in this file, update and overwrite the physical
1066 // location info if appropriate.
1067 if (FI.hasLineDirectives()) {
1068 assert(LineTable && "Can't have linetable entries without a LineTable!");
1069 // See if there is a #line directive before this. If so, get it.
1070 if (const LineEntry *Entry =
1071 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) {
Chris Lattnerfc391332009-02-04 02:00:59 +00001072 // If the LineEntry indicates a filename, use it.
Chris Lattner3cd949c2009-02-04 01:55:42 +00001073 if (Entry->FilenameID != -1)
1074 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerfc391332009-02-04 02:00:59 +00001075
1076 // Use the line number specified by the LineEntry. This line number may
1077 // be multiple lines down from the line entry. Add the difference in
1078 // physical line numbers from the query point and the line marker to the
1079 // total.
1080 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1081 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001082
Chris Lattner0e0e5da2009-02-04 02:15:40 +00001083 // Note that column numbers are not molested by line markers.
Mike Stump1eb44332009-09-09 15:08:12 +00001084
Chris Lattner137b6a62009-02-04 06:25:26 +00001085 // Handle virtual #include manipulation.
1086 if (Entry->IncludeOffset) {
1087 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1088 IncludeLoc = IncludeLoc.getFileLocWithOffset(Entry->IncludeOffset);
1089 }
Chris Lattner3cd949c2009-02-04 01:55:42 +00001090 }
1091 }
1092
1093 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001094}
1095
1096//===----------------------------------------------------------------------===//
1097// Other miscellaneous methods.
1098//===----------------------------------------------------------------------===//
1099
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001100/// \brief Get the source location for the given file:line:col triplet.
1101///
1102/// If the source file is included multiple times, the source location will
1103/// be based upon the first inclusion.
1104SourceLocation SourceManager::getLocation(const FileEntry *SourceFile,
1105 unsigned Line, unsigned Col) const {
1106 assert(SourceFile && "Null source file!");
1107 assert(Line && Col && "Line and column should start from 1!");
1108
1109 fileinfo_iterator FI = FileInfos.find(SourceFile);
1110 if (FI == FileInfos.end())
1111 return SourceLocation();
1112 ContentCache *Content = FI->second;
Mike Stump1eb44332009-09-09 15:08:12 +00001113
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001114 // If this is the first use of line information for this buffer, compute the
1115 /// SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001116 if (Content->SourceLineCache == 0) {
1117 bool MyInvalid = false;
Chris Lattnere127a0d2010-04-20 20:35:58 +00001118 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001119 if (MyInvalid)
1120 return SourceLocation();
1121 }
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001122
Douglas Gregor4a160e12009-12-02 05:34:39 +00001123 // Find the first file ID that corresponds to the given file.
1124 FileID FirstFID;
1125
1126 // First, check the main file ID, since it is common to look for a
1127 // location in the main file.
1128 if (!MainFileID.isInvalid()) {
1129 const SLocEntry &MainSLoc = getSLocEntry(MainFileID);
1130 if (MainSLoc.isFile() && MainSLoc.getFile().getContentCache() == Content)
1131 FirstFID = MainFileID;
1132 }
1133
1134 if (FirstFID.isInvalid()) {
1135 // The location we're looking for isn't in the main file; look
1136 // through all of the source locations.
1137 for (unsigned I = 0, N = sloc_entry_size(); I != N; ++I) {
1138 const SLocEntry &SLoc = getSLocEntry(I);
1139 if (SLoc.isFile() && SLoc.getFile().getContentCache() == Content) {
1140 FirstFID = FileID::get(I);
1141 break;
1142 }
1143 }
1144 }
1145
1146 if (FirstFID.isInvalid())
1147 return SourceLocation();
1148
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001149 if (Line > Content->NumLines) {
Chris Lattnere127a0d2010-04-20 20:35:58 +00001150 unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001151 if (Size > 0)
1152 --Size;
1153 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(Size);
1154 }
1155
1156 unsigned FilePos = Content->SourceLineCache[Line - 1];
Chris Lattnere127a0d2010-04-20 20:35:58 +00001157 const char *Buf = Content->getBuffer(Diag, *this)->getBufferStart() + FilePos;
1158 unsigned BufLength = Content->getBuffer(Diag, *this)->getBufferEnd() - Buf;
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001159 unsigned i = 0;
1160
1161 // Check that the given column is valid.
1162 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1163 ++i;
1164 if (i < Col-1)
1165 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + i);
1166
Douglas Gregor4a160e12009-12-02 05:34:39 +00001167 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + Col - 1);
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001168}
1169
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001170/// Given a decomposed source location, move it up the include/instantiation
1171/// stack to the parent source location. If this is possible, return the
1172/// decomposed version of the parent in Loc and return false. If Loc is the
1173/// top-level entry, return true and don't modify it.
1174static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1175 const SourceManager &SM) {
1176 SourceLocation UpperLoc;
1177 const SrcMgr::SLocEntry &Entry = SM.getSLocEntry(Loc.first);
1178 if (Entry.isInstantiation())
1179 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1180 else
1181 UpperLoc = Entry.getFile().getIncludeLoc();
1182
1183 if (UpperLoc.isInvalid())
1184 return true; // We reached the top.
1185
1186 Loc = SM.getDecomposedLoc(UpperLoc);
1187 return false;
1188}
1189
1190
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001191/// \brief Determines the order of 2 source locations in the translation unit.
1192///
1193/// \returns true if LHS source location comes before RHS, false otherwise.
1194bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1195 SourceLocation RHS) const {
1196 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1197 if (LHS == RHS)
1198 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001199
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001200 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1201 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00001202
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001203 // If the source locations are in the same file, just compare offsets.
1204 if (LOffs.first == ROffs.first)
1205 return LOffs.second < ROffs.second;
1206
1207 // If we are comparing a source location with multiple locations in the same
1208 // file, we get a big win by caching the result.
Chris Lattner66a915f2010-05-07 05:10:46 +00001209 if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
1210 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001211
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001212 // Okay, we missed in the cache, start updating the cache for this query.
1213 IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first);
Mike Stump1eb44332009-09-09 15:08:12 +00001214
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001215 // "Traverse" the include/instantiation stacks of both locations and try to
Chris Lattner48296ba2010-05-07 05:51:13 +00001216 // find a common "ancestor". FileIDs build a tree-like structure that
1217 // reflects the #include hierarchy, and this algorithm needs to find the
1218 // nearest common ancestor between the two locations. For example, if you
1219 // have a.c that includes b.h and c.h, and are comparing a location in b.h to
1220 // a location in c.h, we need to find that their nearest common ancestor is
1221 // a.c, and compare the locations of the two #includes to find their relative
1222 // ordering.
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001223 //
Chris Lattner48296ba2010-05-07 05:51:13 +00001224 // SourceManager assigns FileIDs in order of parsing. This means that an
1225 // includee always has a larger FileID than an includer. While you might
1226 // think that we could just compare the FileID's here, that doesn't work to
1227 // compare a point at the end of a.c with a point within c.h. Though c.h has
1228 // a larger FileID, we have to compare the include point of c.h to the
1229 // location in a.c.
1230 //
1231 // Despite not being able to directly compare FileID's, we can tell that a
1232 // larger FileID is necessarily more deeply nested than a lower one and use
1233 // this information to walk up the tree to the nearest common ancestor.
1234 do {
1235 // If LOffs is larger than ROffs, then LOffs must be more deeply nested than
1236 // ROffs, walk up the #include chain.
1237 if (LOffs.first.ID > ROffs.first.ID) {
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001238 if (MoveUpIncludeHierarchy(LOffs, *this))
Chris Lattner48296ba2010-05-07 05:51:13 +00001239 break; // We reached the top.
1240
Chris Lattner48296ba2010-05-07 05:51:13 +00001241 } else {
1242 // Otherwise, ROffs is larger than LOffs, so ROffs must be more deeply
1243 // nested than LOffs, walk up the #include chain.
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001244 if (MoveUpIncludeHierarchy(ROffs, *this))
Chris Lattner48296ba2010-05-07 05:51:13 +00001245 break; // We reached the top.
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001246 }
Chris Lattner48296ba2010-05-07 05:51:13 +00001247 } while (LOffs.first != ROffs.first);
Mike Stump1eb44332009-09-09 15:08:12 +00001248
Chris Lattner48296ba2010-05-07 05:51:13 +00001249 // If we exited because we found a nearest common ancestor, compare the
1250 // locations within the common file and cache them.
1251 if (LOffs.first == ROffs.first) {
1252 IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
1253 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001254 }
Mike Stump1eb44332009-09-09 15:08:12 +00001255
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001256 // There is no common ancestor, most probably because one location is in the
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001257 // predefines buffer or an AST file.
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001258 // FIXME: We should rearrange the external interface so this simply never
1259 // happens; it can't conceptually happen. Also see PR5662.
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001260 IsBeforeInTUCache.setQueryFIDs(FileID(), FileID()); // Don't try caching.
1261
1262 // Zip both entries up to the top level record.
1263 while (!MoveUpIncludeHierarchy(LOffs, *this)) /*empty*/;
1264 while (!MoveUpIncludeHierarchy(ROffs, *this)) /*empty*/;
Chris Lattner48296ba2010-05-07 05:51:13 +00001265
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001266 // If exactly one location is a memory buffer, assume it preceeds the other.
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001267
1268 // Strip off macro instantation locations, going up to the top-level File
1269 // SLocEntry.
1270 bool LIsMB = getFileEntryForID(LOffs.first) == 0;
1271 bool RIsMB = getFileEntryForID(ROffs.first) == 0;
Chris Lattner48296ba2010-05-07 05:51:13 +00001272 if (LIsMB != RIsMB)
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001273 return LIsMB;
Mike Stump1eb44332009-09-09 15:08:12 +00001274
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001275 // Otherwise, just assume FileIDs were created in order.
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001276 return LOffs.first < ROffs.first;
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001277}
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001278
Reid Spencer5f016e22007-07-11 17:01:13 +00001279/// PrintStats - Print statistics to stderr.
1280///
1281void SourceManager::PrintStats() const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001282 llvm::errs() << "\n*** Source Manager Stats:\n";
1283 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
1284 << " mem buffers mapped.\n";
1285 llvm::errs() << SLocEntryTable.size() << " SLocEntry's allocated, "
1286 << NextOffset << "B of Sloc address space used.\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001287
Reid Spencer5f016e22007-07-11 17:01:13 +00001288 unsigned NumLineNumsComputed = 0;
1289 unsigned NumFileBytesMapped = 0;
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00001290 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
1291 NumLineNumsComputed += I->second->SourceLineCache != 0;
1292 NumFileBytesMapped += I->second->getSizeBytesMapped();
Reid Spencer5f016e22007-07-11 17:01:13 +00001293 }
Mike Stump1eb44332009-09-09 15:08:12 +00001294
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001295 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
1296 << NumLineNumsComputed << " files with line #'s computed.\n";
1297 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
1298 << NumBinaryProbes << " binary.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +00001299}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001300
1301ExternalSLocEntrySource::~ExternalSLocEntrySource() { }