blob: eaa911830f4d4a4c8dcdc38fa8f176fbf9e03d82 [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//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner22eb9722006-06-18 05:43:12 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the SourceManager interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Basic/SourceManager.h"
Douglas Gregora07ebc52009-04-13 15:31:25 +000015#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregor802b7762010-03-15 22:54:52 +000016#include "clang/Basic/Diagnostic.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000017#include "clang/Basic/FileManager.h"
Benjamin Kramer5a3f1cf2010-11-18 12:46:39 +000018#include "llvm/ADT/StringSwitch.h"
Chris Lattner8996fff2007-07-24 05:57:19 +000019#include "llvm/Support/Compiler.h"
Chris Lattner739e7392007-04-29 07:12:06 +000020#include "llvm/Support/MemoryBuffer.h"
Chris Lattner3441b4f2009-08-23 22:45:33 +000021#include "llvm/Support/raw_ostream.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000022#include "llvm/System/Path.h"
23#include <algorithm>
Douglas Gregor802b7762010-03-15 22:54:52 +000024#include <string>
Douglas Gregore0fbb832010-03-16 00:06:06 +000025#include <cstring>
Douglas Gregor802b7762010-03-15 22:54:52 +000026
Chris Lattner22eb9722006-06-18 05:43:12 +000027using namespace clang;
Chris Lattner5f4b1ff2006-06-20 05:02:40 +000028using namespace SrcMgr;
Chris Lattner23b7eb62007-06-15 23:05:46 +000029using llvm::MemoryBuffer;
Chris Lattner22eb9722006-06-18 05:43:12 +000030
Chris Lattner153a0f12009-02-04 00:40:31 +000031//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +000032// SourceManager Helper Classes
Chris Lattner153a0f12009-02-04 00:40:31 +000033//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +000034
Ted Kremenekc08bca62007-10-30 21:08:08 +000035ContentCache::~ContentCache() {
Douglas Gregor3f4bea02010-07-26 21:36:20 +000036 if (shouldFreeBuffer())
37 delete Buffer.getPointer();
Chris Lattner22eb9722006-06-18 05:43:12 +000038}
39
Ted Kremenek12c2af42009-01-06 01:55:26 +000040/// getSizeBytesMapped - Returns the number of bytes actually mapped for
41/// this ContentCache. This can be 0 if the MemBuffer was not actually
42/// instantiated.
43unsigned ContentCache::getSizeBytesMapped() const {
Douglas Gregor82752ec2010-03-16 22:53:51 +000044 return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
Ted Kremenek12c2af42009-01-06 01:55:26 +000045}
46
47/// getSize - Returns the size of the content encapsulated by this ContentCache.
48/// This can be the size of the source file or the size of an arbitrary
49/// scratch buffer. If the ContentCache encapsulates a source file, that
Douglas Gregor53ad6b92009-12-02 06:49:09 +000050/// file is not lazily brought in from disk to satisfy this query.
Ted Kremenek12c2af42009-01-06 01:55:26 +000051unsigned ContentCache::getSize() const {
Douglas Gregor82752ec2010-03-16 22:53:51 +000052 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
53 : (unsigned) Entry->getSize();
Ted Kremenek12c2af42009-01-06 01:55:26 +000054}
55
Douglas Gregor3f4bea02010-07-26 21:36:20 +000056void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B,
57 bool DoNotFree) {
Douglas Gregor82752ec2010-03-16 22:53:51 +000058 assert(B != Buffer.getPointer());
Douglas Gregor53ad6b92009-12-02 06:49:09 +000059
Douglas Gregor3f4bea02010-07-26 21:36:20 +000060 if (shouldFreeBuffer())
61 delete Buffer.getPointer();
Douglas Gregor82752ec2010-03-16 22:53:51 +000062 Buffer.setPointer(B);
Douglas Gregor3f4bea02010-07-26 21:36:20 +000063 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
Douglas Gregor53ad6b92009-12-02 06:49:09 +000064}
65
Douglas Gregor874cc622010-03-16 00:35:39 +000066const llvm::MemoryBuffer *ContentCache::getBuffer(Diagnostic &Diag,
Chris Lattner8f5bc9f2010-04-20 20:49:23 +000067 const SourceManager &SM,
Chris Lattnerfb24a3a2010-04-20 20:35:58 +000068 SourceLocation Loc,
Douglas Gregor874cc622010-03-16 00:35:39 +000069 bool *Invalid) const {
70 if (Invalid)
71 *Invalid = false;
72
Ted Kremenek763ea552009-01-06 22:43:04 +000073 // Lazily create the Buffer for ContentCaches that wrap files.
Douglas Gregor82752ec2010-03-16 22:53:51 +000074 if (!Buffer.getPointer() && Entry) {
Douglas Gregor802b7762010-03-15 22:54:52 +000075 std::string ErrorStr;
Chris Lattner5159f612010-11-23 08:35:12 +000076 Buffer.setPointer(SM.getFileManager().getBufferForFile(Entry, &ErrorStr));
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +000077
Daniel Dunbar7cea5f12009-12-06 05:43:36 +000078 // If we were unable to open the file, then we are in an inconsistent
79 // situation where the content cache referenced a file which no longer
80 // exists. Most likely, we were using a stat cache with an invalid entry but
81 // the file could also have been removed during processing. Since we can't
82 // really deal with this situation, just create an empty buffer.
83 //
84 // FIXME: This is definitely not ideal, but our immediate clients can't
85 // currently handle returning a null entry here. Ideally we should detect
86 // that we are in an inconsistent situation and error out as quickly as
87 // possible.
Douglas Gregor82752ec2010-03-16 22:53:51 +000088 if (!Buffer.getPointer()) {
Daniel Dunbar7cea5f12009-12-06 05:43:36 +000089 const llvm::StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
Douglas Gregor82752ec2010-03-16 22:53:51 +000090 Buffer.setPointer(MemoryBuffer::getNewMemBuffer(Entry->getSize(),
91 "<invalid>"));
92 char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart());
Daniel Dunbar7cea5f12009-12-06 05:43:36 +000093 for (unsigned i = 0, e = Entry->getSize(); i != e; ++i)
94 Ptr[i] = FillStr[i % FillStr.size()];
Douglas Gregor85795312010-03-22 15:10:57 +000095
96 if (Diag.isDiagnosticInFlight())
97 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
98 Entry->getName(), ErrorStr);
99 else
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000100 Diag.Report(Loc, diag::err_cannot_open_file)
Douglas Gregor85795312010-03-22 15:10:57 +0000101 << Entry->getName() << ErrorStr;
102
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000103 Buffer.setInt(Buffer.getInt() | InvalidFlag);
Daniel Dunbar584344f2010-04-10 01:17:16 +0000104
Chris Lattner4ac569b2010-11-23 06:09:11 +0000105 } else if (getRawBuffer()->getBufferSize() != (size_t)Entry->getSize()) {
106 // Check that the file's size is the same as in the file entry (which may
107 // have come from a stat cache).
Douglas Gregor85795312010-03-22 15:10:57 +0000108 if (Diag.isDiagnosticInFlight())
Daniel Dunbar584344f2010-04-10 01:17:16 +0000109 Diag.SetDelayedDiagnostic(diag::err_file_modified,
Douglas Gregor85795312010-03-22 15:10:57 +0000110 Entry->getName());
Daniel Dunbar584344f2010-04-10 01:17:16 +0000111 else
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000112 Diag.Report(Loc, diag::err_file_modified)
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000113 << Entry->getName();
Douglas Gregor85795312010-03-22 15:10:57 +0000114
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000115 Buffer.setInt(Buffer.getInt() | InvalidFlag);
Daniel Dunbar7cea5f12009-12-06 05:43:36 +0000116 }
Chris Lattner8fbe98b2010-04-20 18:14:03 +0000117
118 // If the buffer is valid, check to see if it has a UTF Byte Order Mark
119 // (BOM). We only support UTF-8 without a BOM right now. See
120 // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000121 if (!isBufferInvalid()) {
Chris Lattner8fbe98b2010-04-20 18:14:03 +0000122 llvm::StringRef BufStr = Buffer.getPointer()->getBuffer();
Benjamin Kramer5a3f1cf2010-11-18 12:46:39 +0000123 const char *BOM = llvm::StringSwitch<const char *>(BufStr)
124 .StartsWith("\xEF\xBB\xBF", "UTF-8")
125 .StartsWith("\xFE\xFF", "UTF-16 (BE)")
126 .StartsWith("\xFF\xFE", "UTF-16 (LE)")
127 .StartsWith("\x00\x00\xFE\xFF", "UTF-32 (BE)")
128 .StartsWith("\xFF\xFE\x00\x00", "UTF-32 (LE)")
129 .StartsWith("\x2B\x2F\x76", "UTF-7")
130 .StartsWith("\xF7\x64\x4C", "UTF-1")
131 .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
132 .StartsWith("\x0E\xFE\xFF", "SDSU")
133 .StartsWith("\xFB\xEE\x28", "BOCU-1")
134 .StartsWith("\x84\x31\x95\x33", "GB-18030")
135 .Default(0);
136
Chris Lattner8fbe98b2010-04-20 18:14:03 +0000137 if (BOM) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000138 Diag.Report(Loc, diag::err_unsupported_bom)
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000139 << BOM << Entry->getName();
Chris Lattner8fbe98b2010-04-20 18:14:03 +0000140 Buffer.setInt(1);
141 }
142 }
Ted Kremenek763ea552009-01-06 22:43:04 +0000143 }
Douglas Gregor802b7762010-03-15 22:54:52 +0000144
Douglas Gregor82752ec2010-03-16 22:53:51 +0000145 if (Invalid)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000146 *Invalid = isBufferInvalid();
Douglas Gregor82752ec2010-03-16 22:53:51 +0000147
148 return Buffer.getPointer();
Ted Kremenek12c2af42009-01-06 01:55:26 +0000149}
150
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000151unsigned LineTableInfo::getLineTableFilenameID(const char *Ptr, unsigned Len) {
152 // Look up the filename in the string table, returning the pre-existing value
153 // if it exists.
Mike Stump11289f42009-09-09 15:08:12 +0000154 llvm::StringMapEntry<unsigned> &Entry =
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000155 FilenameIDs.GetOrCreateValue(Ptr, Ptr+Len, ~0U);
156 if (Entry.getValue() != ~0U)
157 return Entry.getValue();
Mike Stump11289f42009-09-09 15:08:12 +0000158
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000159 // Otherwise, assign this the next available ID.
160 Entry.setValue(FilenamesByID.size());
161 FilenamesByID.push_back(&Entry);
162 return FilenamesByID.size()-1;
163}
164
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000165/// AddLineNote - Add a line note to the line table that indicates that there
166/// is a #line at the specified FID/Offset location which changes the presumed
167/// location to LineNo/FilenameID.
Chris Lattner153a0f12009-02-04 00:40:31 +0000168void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000169 unsigned LineNo, int FilenameID) {
Chris Lattner153a0f12009-02-04 00:40:31 +0000170 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump11289f42009-09-09 15:08:12 +0000171
Chris Lattner153a0f12009-02-04 00:40:31 +0000172 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
173 "Adding line entries out of order!");
Mike Stump11289f42009-09-09 15:08:12 +0000174
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000175 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
Chris Lattner1c967782009-02-04 06:25:26 +0000176 unsigned IncludeOffset = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000177
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000178 if (!Entries.empty()) {
179 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
180 // that we are still in "foo.h".
181 if (FilenameID == -1)
182 FilenameID = Entries.back().FilenameID;
Mike Stump11289f42009-09-09 15:08:12 +0000183
Chris Lattner1c967782009-02-04 06:25:26 +0000184 // If we are after a line marker that switched us to system header mode, or
185 // that set #include information, preserve it.
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000186 Kind = Entries.back().FileKind;
Chris Lattner1c967782009-02-04 06:25:26 +0000187 IncludeOffset = Entries.back().IncludeOffset;
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000188 }
Mike Stump11289f42009-09-09 15:08:12 +0000189
Chris Lattner1c967782009-02-04 06:25:26 +0000190 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
191 IncludeOffset));
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000192}
193
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000194/// AddLineNote This is the same as the previous version of AddLineNote, but is
195/// used for GNU line markers. If EntryExit is 0, then this doesn't change the
196/// presumed #include stack. If it is 1, this is a file entry, if it is 2 then
197/// this is a file exit. FileKind specifies whether this is a system header or
198/// extern C system header.
199void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
200 unsigned LineNo, int FilenameID,
201 unsigned EntryExit,
202 SrcMgr::CharacteristicKind FileKind) {
203 assert(FilenameID != -1 && "Unspecified filename should use other accessor");
Mike Stump11289f42009-09-09 15:08:12 +0000204
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000205 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump11289f42009-09-09 15:08:12 +0000206
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000207 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
208 "Adding line entries out of order!");
209
Chris Lattner1c967782009-02-04 06:25:26 +0000210 unsigned IncludeOffset = 0;
211 if (EntryExit == 0) { // No #include stack change.
212 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
213 } else if (EntryExit == 1) {
214 IncludeOffset = Offset-1;
215 } else if (EntryExit == 2) {
216 assert(!Entries.empty() && Entries.back().IncludeOffset &&
217 "PPDirectives should have caught case when popping empty include stack");
Mike Stump11289f42009-09-09 15:08:12 +0000218
Chris Lattner1c967782009-02-04 06:25:26 +0000219 // Get the include loc of the last entries' include loc as our include loc.
220 IncludeOffset = 0;
221 if (const LineEntry *PrevEntry =
222 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
223 IncludeOffset = PrevEntry->IncludeOffset;
224 }
Mike Stump11289f42009-09-09 15:08:12 +0000225
Chris Lattner1c967782009-02-04 06:25:26 +0000226 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
227 IncludeOffset));
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000228}
229
230
Chris Lattnerd4293922009-02-04 01:55:42 +0000231/// FindNearestLineEntry - Find the line entry nearest to FID that is before
232/// it. If there is no line entry before Offset in FID, return null.
Mike Stump11289f42009-09-09 15:08:12 +0000233const LineEntry *LineTableInfo::FindNearestLineEntry(unsigned FID,
Chris Lattnerd4293922009-02-04 01:55:42 +0000234 unsigned Offset) {
235 const std::vector<LineEntry> &Entries = LineEntries[FID];
236 assert(!Entries.empty() && "No #line entries for this FID after all!");
237
Chris Lattner334a2ad2009-02-04 04:46:59 +0000238 // It is very common for the query to be after the last #line, check this
239 // first.
240 if (Entries.back().FileOffset <= Offset)
241 return &Entries.back();
Chris Lattnerd4293922009-02-04 01:55:42 +0000242
Chris Lattner334a2ad2009-02-04 04:46:59 +0000243 // Do a binary search to find the maximal element that is still before Offset.
244 std::vector<LineEntry>::const_iterator I =
245 std::upper_bound(Entries.begin(), Entries.end(), Offset);
246 if (I == Entries.begin()) return 0;
247 return &*--I;
Chris Lattnerd4293922009-02-04 01:55:42 +0000248}
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000249
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000250/// \brief Add a new line entry that has already been encoded into
251/// the internal representation of the line table.
Mike Stump11289f42009-09-09 15:08:12 +0000252void LineTableInfo::AddEntry(unsigned FID,
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000253 const std::vector<LineEntry> &Entries) {
254 LineEntries[FID] = Entries;
255}
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000256
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000257/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
Mike Stump11289f42009-09-09 15:08:12 +0000258///
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000259unsigned SourceManager::getLineTableFilenameID(const char *Ptr, unsigned Len) {
260 if (LineTable == 0)
261 LineTable = new LineTableInfo();
262 return LineTable->getLineTableFilenameID(Ptr, Len);
263}
264
265
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000266/// AddLineNote - Add a line note to the line table for the FileID and offset
267/// specified by Loc. If FilenameID is -1, it is considered to be
268/// unspecified.
269void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
270 int FilenameID) {
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000271 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000272
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000273 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
274
275 // Remember that this file has #line directives now if it doesn't already.
276 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump11289f42009-09-09 15:08:12 +0000277
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000278 if (LineTable == 0)
279 LineTable = new LineTableInfo();
Chris Lattner153a0f12009-02-04 00:40:31 +0000280 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID);
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000281}
282
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000283/// AddLineNote - Add a GNU line marker to the line table.
284void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
285 int FilenameID, bool IsFileEntry,
286 bool IsFileExit, bool IsSystemHeader,
287 bool IsExternCHeader) {
288 // If there is no filename and no flags, this is treated just like a #line,
289 // which does not change the flags of the previous line marker.
290 if (FilenameID == -1) {
291 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
292 "Can't set flags without setting the filename!");
293 return AddLineNote(Loc, LineNo, FilenameID);
294 }
Mike Stump11289f42009-09-09 15:08:12 +0000295
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000296 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
297 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
Mike Stump11289f42009-09-09 15:08:12 +0000298
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000299 // Remember that this file has #line directives now if it doesn't already.
300 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump11289f42009-09-09 15:08:12 +0000301
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000302 if (LineTable == 0)
303 LineTable = new LineTableInfo();
Mike Stump11289f42009-09-09 15:08:12 +0000304
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000305 SrcMgr::CharacteristicKind FileKind;
306 if (IsExternCHeader)
307 FileKind = SrcMgr::C_ExternCSystem;
308 else if (IsSystemHeader)
309 FileKind = SrcMgr::C_System;
310 else
311 FileKind = SrcMgr::C_User;
Mike Stump11289f42009-09-09 15:08:12 +0000312
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000313 unsigned EntryExit = 0;
314 if (IsFileEntry)
315 EntryExit = 1;
316 else if (IsFileExit)
317 EntryExit = 2;
Mike Stump11289f42009-09-09 15:08:12 +0000318
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000319 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID,
320 EntryExit, FileKind);
321}
322
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000323LineTableInfo &SourceManager::getLineTable() {
324 if (LineTable == 0)
325 LineTable = new LineTableInfo();
326 return *LineTable;
327}
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000328
Chris Lattner153a0f12009-02-04 00:40:31 +0000329//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +0000330// Private 'Create' methods.
Chris Lattner153a0f12009-02-04 00:40:31 +0000331//===----------------------------------------------------------------------===//
Ted Kremenek12c2af42009-01-06 01:55:26 +0000332
Chris Lattner5159f612010-11-23 08:35:12 +0000333SourceManager::SourceManager(Diagnostic &Diag, FileManager &FileMgr)
334 : Diag(Diag), FileMgr(FileMgr),
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000335 ExternalSLocEntries(0), LineTable(0), NumLinearScans(0),
336 NumBinaryProbes(0) {
337 clearIDTables();
338 Diag.setSourceManager(this);
339}
340
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000341SourceManager::~SourceManager() {
342 delete LineTable;
Mike Stump11289f42009-09-09 15:08:12 +0000343
Chris Lattnerc8233df2009-02-03 07:30:45 +0000344 // Delete FileEntry objects corresponding to content caches. Since the actual
345 // content cache objects are bump pointer allocated, we just have to run the
346 // dtors, but we call the deallocate method for completeness.
347 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
348 MemBufferInfos[i]->~ContentCache();
349 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
350 }
351 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
352 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
353 I->second->~ContentCache();
354 ContentCacheAlloc.Deallocate(I->second);
355 }
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000356}
357
358void SourceManager::clearIDTables() {
359 MainFileID = FileID();
360 SLocEntryTable.clear();
361 LastLineNoFileIDQuery = FileID();
362 LastLineNoContentCache = 0;
363 LastFileIDLookup = FileID();
Mike Stump11289f42009-09-09 15:08:12 +0000364
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000365 if (LineTable)
366 LineTable->clear();
Mike Stump11289f42009-09-09 15:08:12 +0000367
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000368 // Use up FileID #0 as an invalid instantiation.
369 NextOffset = 0;
Chris Lattner9dc9c202009-02-15 20:52:18 +0000370 createInstantiationLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000371}
372
Chris Lattner4fa23622009-01-26 00:43:02 +0000373/// getOrCreateContentCache - Create or return a cached ContentCache for the
374/// specified file.
375const ContentCache *
376SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000377 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump11289f42009-09-09 15:08:12 +0000378
Chris Lattner22eb9722006-06-18 05:43:12 +0000379 // Do we already have information about this file?
Chris Lattnerc8233df2009-02-03 07:30:45 +0000380 ContentCache *&Entry = FileInfos[FileEnt];
381 if (Entry) return Entry;
Mike Stump11289f42009-09-09 15:08:12 +0000382
Chris Lattner9be4f6d2009-02-03 07:41:46 +0000383 // Nope, create a new Cache entry. Make sure it is at least 8-byte aligned
384 // so that FileInfo can use the low 3 bits of the pointer for its own
385 // nefarious purposes.
386 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
387 EntryAlign = std::max(8U, EntryAlign);
388 Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattnerc8233df2009-02-03 07:30:45 +0000389 new (Entry) ContentCache(FileEnt);
390 return Entry;
Chris Lattner22eb9722006-06-18 05:43:12 +0000391}
392
393
Ted Kremenek08bed092007-10-31 17:53:38 +0000394/// createMemBufferContentCache - Create a new ContentCache for the specified
395/// memory buffer. This does no caching.
Ted Kremenekc08bca62007-10-30 21:08:08 +0000396const ContentCache*
397SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
Chris Lattner9be4f6d2009-02-03 07:41:46 +0000398 // Add a new ContentCache to the MemBufferInfos list and return it. Make sure
399 // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of
400 // the pointer for its own nefarious purposes.
401 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
402 EntryAlign = std::max(8U, EntryAlign);
403 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattnerc8233df2009-02-03 07:30:45 +0000404 new (Entry) ContentCache();
405 MemBufferInfos.push_back(Entry);
406 Entry->setBuffer(Buffer);
407 return Entry;
Chris Lattner22eb9722006-06-18 05:43:12 +0000408}
409
Douglas Gregor258ae542009-04-27 06:38:32 +0000410void SourceManager::PreallocateSLocEntries(ExternalSLocEntrySource *Source,
411 unsigned NumSLocEntries,
412 unsigned NextOffset) {
413 ExternalSLocEntries = Source;
414 this->NextOffset = NextOffset;
Sebastian Redl887d6b02010-07-28 21:07:02 +0000415 unsigned CurPrealloc = SLocEntryLoaded.size();
416 // If we've ever preallocated, we must not count the dummy entry.
417 if (CurPrealloc) --CurPrealloc;
Douglas Gregor258ae542009-04-27 06:38:32 +0000418 SLocEntryLoaded.resize(NumSLocEntries + 1);
419 SLocEntryLoaded[0] = true;
Sebastian Redl887d6b02010-07-28 21:07:02 +0000420 SLocEntryTable.resize(SLocEntryTable.size() + NumSLocEntries - CurPrealloc);
Douglas Gregor258ae542009-04-27 06:38:32 +0000421}
422
Douglas Gregor0bc12932009-04-27 21:28:04 +0000423void SourceManager::ClearPreallocatedSLocEntries() {
424 unsigned I = 0;
425 for (unsigned N = SLocEntryLoaded.size(); I != N; ++I)
426 if (!SLocEntryLoaded[I])
427 break;
428
429 // We've already loaded all preallocated source location entries.
430 if (I == SLocEntryLoaded.size())
431 return;
432
433 // Remove everything from location I onward.
434 SLocEntryTable.resize(I);
435 SLocEntryLoaded.clear();
436 ExternalSLocEntries = 0;
437}
438
Douglas Gregor258ae542009-04-27 06:38:32 +0000439
Chris Lattner4fa23622009-01-26 00:43:02 +0000440//===----------------------------------------------------------------------===//
441// Methods to create new FileID's and instantiations.
442//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000443
Dan Gohmance46f022010-08-26 21:27:06 +0000444/// createFileID - Create a new FileID for the specified ContentCache and
Ted Kremeneke26f3c52007-10-30 22:57:35 +0000445/// include position. This works regardless of whether the ContentCache
446/// corresponds to a file or some other input source.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000447FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattner4fa23622009-01-26 00:43:02 +0000448 SourceLocation IncludePos,
Douglas Gregor258ae542009-04-27 06:38:32 +0000449 SrcMgr::CharacteristicKind FileCharacter,
450 unsigned PreallocatedID,
451 unsigned Offset) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000452 if (PreallocatedID) {
453 // If we're filling in a preallocated ID, just load in the file
454 // entry and return.
Mike Stump11289f42009-09-09 15:08:12 +0000455 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor258ae542009-04-27 06:38:32 +0000456 "Preallocate ID out-of-range");
Mike Stump11289f42009-09-09 15:08:12 +0000457 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor258ae542009-04-27 06:38:32 +0000458 "Source location entry already loaded");
459 assert(Offset && "Preallocate source location cannot have zero offset");
Mike Stump11289f42009-09-09 15:08:12 +0000460 SLocEntryTable[PreallocatedID]
Douglas Gregor258ae542009-04-27 06:38:32 +0000461 = SLocEntry::get(Offset, FileInfo::get(IncludePos, File, FileCharacter));
462 SLocEntryLoaded[PreallocatedID] = true;
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +0000463 FileID FID = FileID::get(PreallocatedID);
Douglas Gregor51c23512010-03-19 06:12:06 +0000464 return FID;
Douglas Gregor258ae542009-04-27 06:38:32 +0000465 }
466
Mike Stump11289f42009-09-09 15:08:12 +0000467 SLocEntryTable.push_back(SLocEntry::get(NextOffset,
Chris Lattner4fa23622009-01-26 00:43:02 +0000468 FileInfo::get(IncludePos, File,
469 FileCharacter)));
Ted Kremenek12c2af42009-01-06 01:55:26 +0000470 unsigned FileSize = File->getSize();
Chris Lattner4fa23622009-01-26 00:43:02 +0000471 assert(NextOffset+FileSize+1 > NextOffset && "Ran out of source locations!");
472 NextOffset += FileSize+1;
Mike Stump11289f42009-09-09 15:08:12 +0000473
Chris Lattner4fa23622009-01-26 00:43:02 +0000474 // Set LastFileIDLookup to the newly created file. The next getFileID call is
475 // almost guaranteed to be from that file.
Argyrios Kyrtzidis0152c6c2009-06-23 00:42:06 +0000476 FileID FID = FileID::get(SLocEntryTable.size()-1);
Argyrios Kyrtzidis0152c6c2009-06-23 00:42:06 +0000477 return LastFileIDLookup = FID;
Chris Lattner22eb9722006-06-18 05:43:12 +0000478}
479
Chris Lattner4fa23622009-01-26 00:43:02 +0000480/// createInstantiationLoc - Return a new SourceLocation that encodes the fact
Chris Lattner53e384f2009-01-16 07:00:02 +0000481/// that a token from SpellingLoc should actually be referenced from
Chris Lattner7d6a4f62006-06-30 06:10:08 +0000482/// InstantiationLoc.
Chris Lattner4fa23622009-01-26 00:43:02 +0000483SourceLocation SourceManager::createInstantiationLoc(SourceLocation SpellingLoc,
Chris Lattner9dc9c202009-02-15 20:52:18 +0000484 SourceLocation ILocStart,
485 SourceLocation ILocEnd,
Douglas Gregor258ae542009-04-27 06:38:32 +0000486 unsigned TokLength,
487 unsigned PreallocatedID,
488 unsigned Offset) {
Chris Lattner9dc9c202009-02-15 20:52:18 +0000489 InstantiationInfo II = InstantiationInfo::get(ILocStart,ILocEnd, SpellingLoc);
Douglas Gregor258ae542009-04-27 06:38:32 +0000490 if (PreallocatedID) {
491 // If we're filling in a preallocated ID, just load in the
492 // instantiation entry and return.
Mike Stump11289f42009-09-09 15:08:12 +0000493 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor258ae542009-04-27 06:38:32 +0000494 "Preallocate ID out-of-range");
Mike Stump11289f42009-09-09 15:08:12 +0000495 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor258ae542009-04-27 06:38:32 +0000496 "Source location entry already loaded");
497 assert(Offset && "Preallocate source location cannot have zero offset");
498 SLocEntryTable[PreallocatedID] = SLocEntry::get(Offset, II);
499 SLocEntryLoaded[PreallocatedID] = true;
500 return SourceLocation::getMacroLoc(Offset);
501 }
Chris Lattner9dc9c202009-02-15 20:52:18 +0000502 SLocEntryTable.push_back(SLocEntry::get(NextOffset, II));
Chris Lattner4fa23622009-01-26 00:43:02 +0000503 assert(NextOffset+TokLength+1 > NextOffset && "Ran out of source locations!");
504 NextOffset += TokLength+1;
505 return SourceLocation::getMacroLoc(NextOffset-(TokLength+1));
Chris Lattner7d6a4f62006-06-30 06:10:08 +0000506}
507
Douglas Gregor874cc622010-03-16 00:35:39 +0000508const llvm::MemoryBuffer *
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000509SourceManager::getMemoryBufferForFile(const FileEntry *File,
510 bool *Invalid) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000511 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregor802b7762010-03-15 22:54:52 +0000512 assert(IR && "getOrCreateContentCache() cannot return NULL");
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000513 return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000514}
515
Dan Gohman5d223dc2010-10-26 20:47:28 +0000516void SourceManager::overrideFileContents(const FileEntry *SourceFile,
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000517 const llvm::MemoryBuffer *Buffer,
518 bool DoNotFree) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000519 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
Dan Gohman5d223dc2010-10-26 20:47:28 +0000520 assert(IR && "getOrCreateContentCache() cannot return NULL");
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000521
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000522 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000523}
524
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000525llvm::StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +0000526 bool MyInvalid = false;
527 const llvm::MemoryBuffer *Buf = getBuffer(FID, &MyInvalid);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000528 if (Invalid)
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +0000529 *Invalid = MyInvalid;
530
531 if (MyInvalid)
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000532 return "";
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +0000533
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000534 return Buf->getBuffer();
Douglas Gregor802b7762010-03-15 22:54:52 +0000535}
Chris Lattnerd32480d2009-01-17 06:22:33 +0000536
Chris Lattner153a0f12009-02-04 00:40:31 +0000537//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +0000538// SourceLocation manipulation methods.
Chris Lattner153a0f12009-02-04 00:40:31 +0000539//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +0000540
541/// getFileIDSlow - Return the FileID for a SourceLocation. This is a very hot
542/// method that is used for all SourceManager queries that start with a
543/// SourceLocation object. It is responsible for finding the entry in
544/// SLocEntryTable which contains the specified location.
545///
546FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
547 assert(SLocOffset && "Invalid FileID");
Mike Stump11289f42009-09-09 15:08:12 +0000548
Chris Lattner4fa23622009-01-26 00:43:02 +0000549 // After the first and second level caches, I see two common sorts of
550 // behavior: 1) a lot of searched FileID's are "near" the cached file location
551 // or are "near" the cached instantiation location. 2) others are just
552 // completely random and may be a very long way away.
553 //
554 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
555 // then we fall back to a less cache efficient, but more scalable, binary
556 // search to find the location.
Mike Stump11289f42009-09-09 15:08:12 +0000557
Chris Lattner4fa23622009-01-26 00:43:02 +0000558 // See if this is near the file point - worst case we start scanning from the
559 // most newly created FileID.
560 std::vector<SrcMgr::SLocEntry>::const_iterator I;
Mike Stump11289f42009-09-09 15:08:12 +0000561
Chris Lattner4fa23622009-01-26 00:43:02 +0000562 if (SLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
563 // Neither loc prunes our search.
564 I = SLocEntryTable.end();
565 } else {
566 // Perhaps it is near the file point.
567 I = SLocEntryTable.begin()+LastFileIDLookup.ID;
568 }
569
570 // Find the FileID that contains this. "I" is an iterator that points to a
571 // FileID whose offset is known to be larger than SLocOffset.
572 unsigned NumProbes = 0;
573 while (1) {
574 --I;
Douglas Gregor258ae542009-04-27 06:38:32 +0000575 if (ExternalSLocEntries)
576 getSLocEntry(FileID::get(I - SLocEntryTable.begin()));
Chris Lattner4fa23622009-01-26 00:43:02 +0000577 if (I->getOffset() <= SLocOffset) {
578#if 0
579 printf("lin %d -> %d [%s] %d %d\n", SLocOffset,
580 I-SLocEntryTable.begin(),
581 I->isInstantiation() ? "inst" : "file",
582 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
583#endif
584 FileID Res = FileID::get(I-SLocEntryTable.begin());
Douglas Gregor258ae542009-04-27 06:38:32 +0000585
Chris Lattner4fa23622009-01-26 00:43:02 +0000586 // If this isn't an instantiation, remember it. We have good locality
587 // across FileID lookups.
588 if (!I->isInstantiation())
589 LastFileIDLookup = Res;
590 NumLinearScans += NumProbes+1;
591 return Res;
592 }
593 if (++NumProbes == 8)
594 break;
595 }
Mike Stump11289f42009-09-09 15:08:12 +0000596
Chris Lattner4fa23622009-01-26 00:43:02 +0000597 // Convert "I" back into an index. We know that it is an entry whose index is
598 // larger than the offset we are looking for.
599 unsigned GreaterIndex = I-SLocEntryTable.begin();
600 // LessIndex - This is the lower bound of the range that we're searching.
601 // We know that the offset corresponding to the FileID is is less than
602 // SLocOffset.
603 unsigned LessIndex = 0;
604 NumProbes = 0;
605 while (1) {
606 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregor258ae542009-04-27 06:38:32 +0000607 unsigned MidOffset = getSLocEntry(FileID::get(MiddleIndex)).getOffset();
Mike Stump11289f42009-09-09 15:08:12 +0000608
Chris Lattner4fa23622009-01-26 00:43:02 +0000609 ++NumProbes;
Mike Stump11289f42009-09-09 15:08:12 +0000610
Chris Lattner4fa23622009-01-26 00:43:02 +0000611 // If the offset of the midpoint is too large, chop the high side of the
612 // range to the midpoint.
613 if (MidOffset > SLocOffset) {
614 GreaterIndex = MiddleIndex;
615 continue;
616 }
Mike Stump11289f42009-09-09 15:08:12 +0000617
Chris Lattner4fa23622009-01-26 00:43:02 +0000618 // If the middle index contains the value, succeed and return.
619 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
620#if 0
621 printf("bin %d -> %d [%s] %d %d\n", SLocOffset,
622 I-SLocEntryTable.begin(),
623 I->isInstantiation() ? "inst" : "file",
624 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
625#endif
626 FileID Res = FileID::get(MiddleIndex);
627
628 // If this isn't an instantiation, remember it. We have good locality
629 // across FileID lookups.
630 if (!I->isInstantiation())
631 LastFileIDLookup = Res;
632 NumBinaryProbes += NumProbes;
633 return Res;
634 }
Mike Stump11289f42009-09-09 15:08:12 +0000635
Chris Lattner4fa23622009-01-26 00:43:02 +0000636 // Otherwise, move the low-side up to the middle index.
637 LessIndex = MiddleIndex;
638 }
639}
640
Chris Lattner659ac5f2009-01-26 20:04:19 +0000641SourceLocation SourceManager::
642getInstantiationLocSlowCase(SourceLocation Loc) const {
643 do {
Chris Lattner5647d312010-02-12 19:31:35 +0000644 // Note: If Loc indicates an offset into a token that came from a macro
645 // expansion (e.g. the 5th character of the token) we do not want to add
646 // this offset when going to the instantiation location. The instatiation
647 // location is the macro invocation, which the offset has nothing to do
648 // with. This is unlike when we get the spelling loc, because the offset
649 // directly correspond to the token whose spelling we're inspecting.
650 Loc = getSLocEntry(getFileID(Loc)).getInstantiation()
Chris Lattner9dc9c202009-02-15 20:52:18 +0000651 .getInstantiationLocStart();
Chris Lattner659ac5f2009-01-26 20:04:19 +0000652 } while (!Loc.isFileID());
653
654 return Loc;
655}
656
657SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
658 do {
659 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
660 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
661 Loc = Loc.getFileLocWithOffset(LocInfo.second);
662 } while (!Loc.isFileID());
663 return Loc;
664}
665
666
Chris Lattner4fa23622009-01-26 00:43:02 +0000667std::pair<FileID, unsigned>
668SourceManager::getDecomposedInstantiationLocSlowCase(const SrcMgr::SLocEntry *E,
669 unsigned Offset) const {
670 // If this is an instantiation record, walk through all the instantiation
671 // points.
672 FileID FID;
673 SourceLocation Loc;
674 do {
Chris Lattner9dc9c202009-02-15 20:52:18 +0000675 Loc = E->getInstantiation().getInstantiationLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000676
Chris Lattner4fa23622009-01-26 00:43:02 +0000677 FID = getFileID(Loc);
678 E = &getSLocEntry(FID);
679 Offset += Loc.getOffset()-E->getOffset();
Chris Lattner31af4e02009-01-26 19:41:58 +0000680 } while (!Loc.isFileID());
Mike Stump11289f42009-09-09 15:08:12 +0000681
Chris Lattner4fa23622009-01-26 00:43:02 +0000682 return std::make_pair(FID, Offset);
683}
684
685std::pair<FileID, unsigned>
686SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
687 unsigned Offset) const {
Chris Lattner31af4e02009-01-26 19:41:58 +0000688 // If this is an instantiation record, walk through all the instantiation
689 // points.
690 FileID FID;
691 SourceLocation Loc;
692 do {
693 Loc = E->getInstantiation().getSpellingLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000694
Chris Lattner31af4e02009-01-26 19:41:58 +0000695 FID = getFileID(Loc);
696 E = &getSLocEntry(FID);
697 Offset += Loc.getOffset()-E->getOffset();
698 } while (!Loc.isFileID());
Mike Stump11289f42009-09-09 15:08:12 +0000699
Chris Lattner4fa23622009-01-26 00:43:02 +0000700 return std::make_pair(FID, Offset);
701}
702
Chris Lattner8ad52d52009-02-17 08:04:48 +0000703/// getImmediateSpellingLoc - Given a SourceLocation object, return the
704/// spelling location referenced by the ID. This is the first level down
705/// towards the place where the characters that make up the lexed token can be
706/// found. This should not generally be used by clients.
707SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
708 if (Loc.isFileID()) return Loc;
709 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
710 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
711 return Loc.getFileLocWithOffset(LocInfo.second);
712}
713
714
Chris Lattner9dc9c202009-02-15 20:52:18 +0000715/// getImmediateInstantiationRange - Loc is required to be an instantiation
716/// location. Return the start/end of the instantiation information.
717std::pair<SourceLocation,SourceLocation>
718SourceManager::getImmediateInstantiationRange(SourceLocation Loc) const {
719 assert(Loc.isMacroID() && "Not an instantiation loc!");
720 const InstantiationInfo &II = getSLocEntry(getFileID(Loc)).getInstantiation();
721 return II.getInstantiationLocRange();
722}
723
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000724/// getInstantiationRange - Given a SourceLocation object, return the
725/// range of tokens covered by the instantiation in the ultimate file.
726std::pair<SourceLocation,SourceLocation>
727SourceManager::getInstantiationRange(SourceLocation Loc) const {
728 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000729
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000730 std::pair<SourceLocation,SourceLocation> Res =
731 getImmediateInstantiationRange(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000732
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000733 // Fully resolve the start and end locations to their ultimate instantiation
734 // points.
735 while (!Res.first.isFileID())
736 Res.first = getImmediateInstantiationRange(Res.first).first;
737 while (!Res.second.isFileID())
738 Res.second = getImmediateInstantiationRange(Res.second).second;
739 return Res;
740}
741
Chris Lattner9dc9c202009-02-15 20:52:18 +0000742
Chris Lattner4fa23622009-01-26 00:43:02 +0000743
744//===----------------------------------------------------------------------===//
745// Queries about the code at a SourceLocation.
746//===----------------------------------------------------------------------===//
Chris Lattner30709b032006-06-21 03:01:55 +0000747
Chris Lattnerd01e2912006-06-18 16:22:51 +0000748/// getCharacterData - Return a pointer to the start of the specified location
Chris Lattner739e7392007-04-29 07:12:06 +0000749/// in the appropriate MemoryBuffer.
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000750const char *SourceManager::getCharacterData(SourceLocation SL,
751 bool *Invalid) const {
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000752 // Note that this is a hot function in the getSpelling() path, which is
753 // heavily used by -E mode.
Chris Lattner4fa23622009-01-26 00:43:02 +0000754 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump11289f42009-09-09 15:08:12 +0000755
Ted Kremenek12c2af42009-01-06 01:55:26 +0000756 // Note that calling 'getBuffer()' may lazily page in a source file.
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000757 bool CharDataInvalid = false;
758 const llvm::MemoryBuffer *Buffer
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000759 = getSLocEntry(LocInfo.first).getFile().getContentCache()
760 ->getBuffer(Diag, *this, SourceLocation(), &CharDataInvalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000761 if (Invalid)
762 *Invalid = CharDataInvalid;
763 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000764}
765
Chris Lattner685730f2006-06-26 01:36:22 +0000766
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000767/// getColumnNumber - Return the column # for the specified file position.
Chris Lattnere4ad4172009-02-04 00:55:58 +0000768/// this is significantly cheaper to compute than the line number.
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000769unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
770 bool *Invalid) const {
771 bool MyInvalid = false;
772 const char *Buf = getBuffer(FID, &MyInvalid)->getBufferStart();
773 if (Invalid)
774 *Invalid = MyInvalid;
775
776 if (MyInvalid)
777 return 1;
Mike Stump11289f42009-09-09 15:08:12 +0000778
Chris Lattner22eb9722006-06-18 05:43:12 +0000779 unsigned LineStart = FilePos;
780 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
781 --LineStart;
782 return FilePos-LineStart+1;
783}
784
Zhanyong Wanea6d7f32010-10-05 17:56:33 +0000785// isInvalid - Return the result of calling loc.isInvalid(), and
786// if Invalid is not null, set its value to same.
787static bool isInvalid(SourceLocation Loc, bool *Invalid) {
788 bool MyInvalid = Loc.isInvalid();
789 if (Invalid)
790 *Invalid = MyInvalid;
791 return MyInvalid;
792}
793
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000794unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
795 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +0000796 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattnere4ad4172009-02-04 00:55:58 +0000797 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000798 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattnere4ad4172009-02-04 00:55:58 +0000799}
800
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000801unsigned SourceManager::getInstantiationColumnNumber(SourceLocation Loc,
802 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +0000803 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattnere4ad4172009-02-04 00:55:58 +0000804 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000805 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattnere4ad4172009-02-04 00:55:58 +0000806}
807
Chandler Carruthc3ce5842010-10-23 08:44:57 +0000808static LLVM_ATTRIBUTE_NOINLINE void
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000809ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
810 llvm::BumpPtrAllocator &Alloc,
811 const SourceManager &SM, bool &Invalid);
812static void ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
813 llvm::BumpPtrAllocator &Alloc,
814 const SourceManager &SM, bool &Invalid) {
Ted Kremenek12c2af42009-01-06 01:55:26 +0000815 // Note that calling 'getBuffer()' may lazily page in the file.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000816 const MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(),
817 &Invalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000818 if (Invalid)
819 return;
Mike Stump11289f42009-09-09 15:08:12 +0000820
Chris Lattner8996fff2007-07-24 05:57:19 +0000821 // Find the file offsets of all of the *physical* source lines. This does
822 // not look at trigraphs, escaped newlines, or anything else tricky.
823 std::vector<unsigned> LineOffsets;
Mike Stump11289f42009-09-09 15:08:12 +0000824
Chris Lattner8996fff2007-07-24 05:57:19 +0000825 // Line #1 starts at char 0.
826 LineOffsets.push_back(0);
Mike Stump11289f42009-09-09 15:08:12 +0000827
Chris Lattner8996fff2007-07-24 05:57:19 +0000828 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
829 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
830 unsigned Offs = 0;
831 while (1) {
832 // Skip over the contents of the line.
833 // TODO: Vectorize this? This is very performance sensitive for programs
834 // with lots of diagnostics and in -E mode.
835 const unsigned char *NextBuf = (const unsigned char *)Buf;
836 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
837 ++NextBuf;
838 Offs += NextBuf-Buf;
839 Buf = NextBuf;
Mike Stump11289f42009-09-09 15:08:12 +0000840
Chris Lattner8996fff2007-07-24 05:57:19 +0000841 if (Buf[0] == '\n' || Buf[0] == '\r') {
842 // If this is \n\r or \r\n, skip both characters.
843 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
844 ++Offs, ++Buf;
845 ++Offs, ++Buf;
846 LineOffsets.push_back(Offs);
847 } else {
848 // Otherwise, this is a null. If end of file, exit.
849 if (Buf == End) break;
850 // Otherwise, skip the null.
851 ++Offs, ++Buf;
852 }
853 }
Mike Stump11289f42009-09-09 15:08:12 +0000854
Chris Lattner8996fff2007-07-24 05:57:19 +0000855 // Copy the offsets into the FileInfo structure.
856 FI->NumLines = LineOffsets.size();
Chris Lattnerc8233df2009-02-03 07:30:45 +0000857 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner8996fff2007-07-24 05:57:19 +0000858 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
859}
Chris Lattner9a13bde2006-06-21 04:57:09 +0000860
Chris Lattner53e384f2009-01-16 07:00:02 +0000861/// getLineNumber - Given a SourceLocation, return the spelling line number
Chris Lattner22eb9722006-06-18 05:43:12 +0000862/// for the position indicated. This requires building and caching a table of
Chris Lattner739e7392007-04-29 07:12:06 +0000863/// line offsets for the MemoryBuffer, so this is not cheap: use only when
Chris Lattner22eb9722006-06-18 05:43:12 +0000864/// about to emit a diagnostic.
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000865unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
866 bool *Invalid) const {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000867 ContentCache *Content;
Chris Lattner88ea93e2009-02-04 01:06:56 +0000868 if (LastLineNoFileIDQuery == FID)
Ted Kremenekc08bca62007-10-30 21:08:08 +0000869 Content = LastLineNoContentCache;
Chris Lattner8996fff2007-07-24 05:57:19 +0000870 else
Chris Lattner88ea93e2009-02-04 01:06:56 +0000871 Content = const_cast<ContentCache*>(getSLocEntry(FID)
Chris Lattner4fa23622009-01-26 00:43:02 +0000872 .getFile().getContentCache());
Mike Stump11289f42009-09-09 15:08:12 +0000873
Chris Lattner22eb9722006-06-18 05:43:12 +0000874 // If this is the first use of line information for this buffer, compute the
Chris Lattner8996fff2007-07-24 05:57:19 +0000875 /// SourceLineCache for it on demand.
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000876 if (Content->SourceLineCache == 0) {
877 bool MyInvalid = false;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000878 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000879 if (Invalid)
880 *Invalid = MyInvalid;
881 if (MyInvalid)
882 return 1;
883 } else if (Invalid)
884 *Invalid = false;
Chris Lattner22eb9722006-06-18 05:43:12 +0000885
886 // Okay, we know we have a line number table. Do a binary search to find the
887 // line number that this character position lands on.
Ted Kremenekc08bca62007-10-30 21:08:08 +0000888 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner8996fff2007-07-24 05:57:19 +0000889 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenekc08bca62007-10-30 21:08:08 +0000890 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump11289f42009-09-09 15:08:12 +0000891
Chris Lattner88ea93e2009-02-04 01:06:56 +0000892 unsigned QueriedFilePos = FilePos+1;
Chris Lattner8996fff2007-07-24 05:57:19 +0000893
Daniel Dunbar70f924df82009-05-18 17:30:52 +0000894 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump11289f42009-09-09 15:08:12 +0000895 // complicated as it is, binary search isn't that slow.
Daniel Dunbar70f924df82009-05-18 17:30:52 +0000896 //
897 // If it is worth being optimized, then in my opinion it could be more
898 // performant, simpler, and more obviously correct by just "galloping" outward
899 // from the queried file position. In fact, this could be incorporated into a
900 // generic algorithm such as lower_bound_with_hint.
901 //
902 // If someone gives me a test case where this matters, and I will do it! - DWD
903
Chris Lattner8996fff2007-07-24 05:57:19 +0000904 // If the previous query was to the same file, we know both the file pos from
905 // that query and the line number returned. This allows us to narrow the
906 // search space from the entire file to something near the match.
Chris Lattner88ea93e2009-02-04 01:06:56 +0000907 if (LastLineNoFileIDQuery == FID) {
Chris Lattner8996fff2007-07-24 05:57:19 +0000908 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar70f924df82009-05-18 17:30:52 +0000909 // FIXME: Potential overflow?
Chris Lattner8996fff2007-07-24 05:57:19 +0000910 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump11289f42009-09-09 15:08:12 +0000911
Chris Lattner8996fff2007-07-24 05:57:19 +0000912 // The query is likely to be nearby the previous one. Here we check to
913 // see if it is within 5, 10 or 20 lines. It can be far away in cases
914 // where big comment blocks and vertical whitespace eat up lines but
915 // contribute no tokens.
916 if (SourceLineCache+5 < SourceLineCacheEnd) {
917 if (SourceLineCache[5] > QueriedFilePos)
918 SourceLineCacheEnd = SourceLineCache+5;
919 else if (SourceLineCache+10 < SourceLineCacheEnd) {
920 if (SourceLineCache[10] > QueriedFilePos)
921 SourceLineCacheEnd = SourceLineCache+10;
922 else if (SourceLineCache+20 < SourceLineCacheEnd) {
923 if (SourceLineCache[20] > QueriedFilePos)
924 SourceLineCacheEnd = SourceLineCache+20;
925 }
926 }
927 }
928 } else {
Daniel Dunbar70f924df82009-05-18 17:30:52 +0000929 if (LastLineNoResult < Content->NumLines)
930 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner8996fff2007-07-24 05:57:19 +0000931 }
932 }
Mike Stump11289f42009-09-09 15:08:12 +0000933
Chris Lattner830a77f2007-07-24 06:43:46 +0000934 // If the spread is large, do a "radix" test as our initial guess, based on
935 // the assumption that lines average to approximately the same length.
936 // NOTE: This is currently disabled, as it does not appear to be profitable in
937 // initial measurements.
938 if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
Ted Kremenekc08bca62007-10-30 21:08:08 +0000939 unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
Mike Stump11289f42009-09-09 15:08:12 +0000940
Chris Lattner830a77f2007-07-24 06:43:46 +0000941 // Take a stab at guessing where it is.
Ted Kremenekc08bca62007-10-30 21:08:08 +0000942 unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
Mike Stump11289f42009-09-09 15:08:12 +0000943
Chris Lattner830a77f2007-07-24 06:43:46 +0000944 // Check for -10 and +10 lines.
945 unsigned LowerBound = std::max(int(ApproxPos-10), 0);
946 unsigned UpperBound = std::min(ApproxPos+10, FileLen);
947
948 // If the computed lower bound is less than the query location, move it in.
949 if (SourceLineCache < SourceLineCacheStart+LowerBound &&
950 SourceLineCacheStart[LowerBound] < QueriedFilePos)
951 SourceLineCache = SourceLineCacheStart+LowerBound;
Mike Stump11289f42009-09-09 15:08:12 +0000952
Chris Lattner830a77f2007-07-24 06:43:46 +0000953 // If the computed upper bound is greater than the query location, move it.
954 if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
955 SourceLineCacheStart[UpperBound] >= QueriedFilePos)
956 SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
957 }
Mike Stump11289f42009-09-09 15:08:12 +0000958
Chris Lattner830a77f2007-07-24 06:43:46 +0000959 unsigned *Pos
960 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner8996fff2007-07-24 05:57:19 +0000961 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump11289f42009-09-09 15:08:12 +0000962
Chris Lattner88ea93e2009-02-04 01:06:56 +0000963 LastLineNoFileIDQuery = FID;
Ted Kremenekc08bca62007-10-30 21:08:08 +0000964 LastLineNoContentCache = Content;
Chris Lattner8996fff2007-07-24 05:57:19 +0000965 LastLineNoFilePos = QueriedFilePos;
966 LastLineNoResult = LineNo;
967 return LineNo;
Chris Lattner22eb9722006-06-18 05:43:12 +0000968}
969
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000970unsigned SourceManager::getInstantiationLineNumber(SourceLocation Loc,
971 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +0000972 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner88ea93e2009-02-04 01:06:56 +0000973 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
974 return getLineNumber(LocInfo.first, LocInfo.second);
975}
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000976unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
977 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +0000978 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner88ea93e2009-02-04 01:06:56 +0000979 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
980 return getLineNumber(LocInfo.first, LocInfo.second);
981}
982
Chris Lattner95d9c5e2009-02-04 05:33:01 +0000983/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump11289f42009-09-09 15:08:12 +0000984/// source location, indicating whether this is a normal file, a system
Chris Lattner95d9c5e2009-02-04 05:33:01 +0000985/// header, or an "implicit extern C" system header.
986///
987/// This state can be modified with flags on GNU linemarker directives like:
988/// # 4 "foo.h" 3
989/// which changes all source locations in the current file after that to be
990/// considered to be from a system header.
Mike Stump11289f42009-09-09 15:08:12 +0000991SrcMgr::CharacteristicKind
Chris Lattner95d9c5e2009-02-04 05:33:01 +0000992SourceManager::getFileCharacteristic(SourceLocation Loc) const {
993 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
994 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
995 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
996
997 // If there are no #line directives in this file, just return the whole-file
998 // state.
999 if (!FI.hasLineDirectives())
1000 return FI.getFileCharacteristic();
Mike Stump11289f42009-09-09 15:08:12 +00001001
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001002 assert(LineTable && "Can't have linetable entries without a LineTable!");
1003 // See if there is a #line directive before the location.
1004 const LineEntry *Entry =
1005 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second);
Mike Stump11289f42009-09-09 15:08:12 +00001006
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001007 // If this is before the first line marker, use the file characteristic.
1008 if (!Entry)
1009 return FI.getFileCharacteristic();
1010
1011 return Entry->FileKind;
1012}
1013
Chris Lattnera6f037c2009-02-17 08:39:06 +00001014/// Return the filename or buffer identifier of the buffer the location is in.
1015/// Note that this name does not respect #line directives. Use getPresumedLoc
1016/// for normal clients.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001017const char *SourceManager::getBufferName(SourceLocation Loc,
1018 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001019 if (isInvalid(Loc, Invalid)) return "<invalid loc>";
Mike Stump11289f42009-09-09 15:08:12 +00001020
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001021 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
Chris Lattnera6f037c2009-02-17 08:39:06 +00001022}
1023
Chris Lattner88ea93e2009-02-04 01:06:56 +00001024
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001025/// getPresumedLoc - This method returns the "presumed" location of a
1026/// SourceLocation specifies. A "presumed location" can be modified by #line
1027/// or GNU line marker directives. This provides a view on the data that a
1028/// user should see in diagnostics, for example.
1029///
1030/// Note that a presumed location is always given as the instantiation point
1031/// of an instantiation location, not at the spelling location.
1032PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
1033 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001034
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001035 // Presumed locations are always for instantiation points.
Chris Lattnere4ad4172009-02-04 00:55:58 +00001036 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +00001037
Chris Lattner88ea93e2009-02-04 01:06:56 +00001038 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001039 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump11289f42009-09-09 15:08:12 +00001040
Chris Lattnerd4293922009-02-04 01:55:42 +00001041 // To get the source name, first consult the FileEntry (if one exists)
1042 // before the MemBuffer as this will avoid unnecessarily paging in the
1043 // MemBuffer.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001044 const char *Filename;
1045 if (C->Entry)
1046 Filename = C->Entry->getName();
1047 else
1048 Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
Douglas Gregor75f26d62010-11-02 00:39:22 +00001049 bool Invalid = false;
1050 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1051 if (Invalid)
1052 return PresumedLoc();
1053 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1054 if (Invalid)
1055 return PresumedLoc();
1056
Chris Lattnerd4293922009-02-04 01:55:42 +00001057 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001058
Chris Lattnerd4293922009-02-04 01:55:42 +00001059 // If we have #line directives in this file, update and overwrite the physical
1060 // location info if appropriate.
1061 if (FI.hasLineDirectives()) {
1062 assert(LineTable && "Can't have linetable entries without a LineTable!");
1063 // See if there is a #line directive before this. If so, get it.
1064 if (const LineEntry *Entry =
1065 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) {
Chris Lattnerc1219ff2009-02-04 02:00:59 +00001066 // If the LineEntry indicates a filename, use it.
Chris Lattnerd4293922009-02-04 01:55:42 +00001067 if (Entry->FilenameID != -1)
1068 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerc1219ff2009-02-04 02:00:59 +00001069
1070 // Use the line number specified by the LineEntry. This line number may
1071 // be multiple lines down from the line entry. Add the difference in
1072 // physical line numbers from the query point and the line marker to the
1073 // total.
1074 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1075 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump11289f42009-09-09 15:08:12 +00001076
Chris Lattner20c50ba2009-02-04 02:15:40 +00001077 // Note that column numbers are not molested by line markers.
Mike Stump11289f42009-09-09 15:08:12 +00001078
Chris Lattner1c967782009-02-04 06:25:26 +00001079 // Handle virtual #include manipulation.
1080 if (Entry->IncludeOffset) {
1081 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1082 IncludeLoc = IncludeLoc.getFileLocWithOffset(Entry->IncludeOffset);
1083 }
Chris Lattnerd4293922009-02-04 01:55:42 +00001084 }
1085 }
1086
1087 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattner4fa23622009-01-26 00:43:02 +00001088}
1089
1090//===----------------------------------------------------------------------===//
1091// Other miscellaneous methods.
1092//===----------------------------------------------------------------------===//
1093
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001094/// \brief Get the source location for the given file:line:col triplet.
1095///
1096/// If the source file is included multiple times, the source location will
1097/// be based upon the first inclusion.
1098SourceLocation SourceManager::getLocation(const FileEntry *SourceFile,
1099 unsigned Line, unsigned Col) const {
1100 assert(SourceFile && "Null source file!");
1101 assert(Line && Col && "Line and column should start from 1!");
1102
1103 fileinfo_iterator FI = FileInfos.find(SourceFile);
1104 if (FI == FileInfos.end())
1105 return SourceLocation();
1106 ContentCache *Content = FI->second;
Mike Stump11289f42009-09-09 15:08:12 +00001107
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001108 // If this is the first use of line information for this buffer, compute the
1109 /// SourceLineCache for it on demand.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001110 if (Content->SourceLineCache == 0) {
1111 bool MyInvalid = false;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001112 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001113 if (MyInvalid)
1114 return SourceLocation();
1115 }
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001116
Douglas Gregor2a1b6912009-12-02 05:34:39 +00001117 // Find the first file ID that corresponds to the given file.
1118 FileID FirstFID;
1119
1120 // First, check the main file ID, since it is common to look for a
1121 // location in the main file.
1122 if (!MainFileID.isInvalid()) {
1123 const SLocEntry &MainSLoc = getSLocEntry(MainFileID);
1124 if (MainSLoc.isFile() && MainSLoc.getFile().getContentCache() == Content)
1125 FirstFID = MainFileID;
1126 }
1127
1128 if (FirstFID.isInvalid()) {
1129 // The location we're looking for isn't in the main file; look
1130 // through all of the source locations.
1131 for (unsigned I = 0, N = sloc_entry_size(); I != N; ++I) {
1132 const SLocEntry &SLoc = getSLocEntry(I);
1133 if (SLoc.isFile() && SLoc.getFile().getContentCache() == Content) {
1134 FirstFID = FileID::get(I);
1135 break;
1136 }
1137 }
1138 }
1139
1140 if (FirstFID.isInvalid())
1141 return SourceLocation();
1142
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001143 if (Line > Content->NumLines) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001144 unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001145 if (Size > 0)
1146 --Size;
1147 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(Size);
1148 }
1149
1150 unsigned FilePos = Content->SourceLineCache[Line - 1];
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001151 const char *Buf = Content->getBuffer(Diag, *this)->getBufferStart() + FilePos;
1152 unsigned BufLength = Content->getBuffer(Diag, *this)->getBufferEnd() - Buf;
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001153 unsigned i = 0;
1154
1155 // Check that the given column is valid.
1156 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1157 ++i;
1158 if (i < Col-1)
1159 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + i);
1160
Douglas Gregor2a1b6912009-12-02 05:34:39 +00001161 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + Col - 1);
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001162}
1163
Chris Lattnera99fa1a2010-05-07 20:35:24 +00001164/// Given a decomposed source location, move it up the include/instantiation
1165/// stack to the parent source location. If this is possible, return the
1166/// decomposed version of the parent in Loc and return false. If Loc is the
1167/// top-level entry, return true and don't modify it.
1168static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1169 const SourceManager &SM) {
1170 SourceLocation UpperLoc;
1171 const SrcMgr::SLocEntry &Entry = SM.getSLocEntry(Loc.first);
1172 if (Entry.isInstantiation())
1173 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1174 else
1175 UpperLoc = Entry.getFile().getIncludeLoc();
1176
1177 if (UpperLoc.isInvalid())
1178 return true; // We reached the top.
1179
1180 Loc = SM.getDecomposedLoc(UpperLoc);
1181 return false;
1182}
1183
1184
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001185/// \brief Determines the order of 2 source locations in the translation unit.
1186///
1187/// \returns true if LHS source location comes before RHS, false otherwise.
1188bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1189 SourceLocation RHS) const {
1190 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1191 if (LHS == RHS)
1192 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001193
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001194 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1195 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00001196
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001197 // If the source locations are in the same file, just compare offsets.
1198 if (LOffs.first == ROffs.first)
1199 return LOffs.second < ROffs.second;
1200
1201 // If we are comparing a source location with multiple locations in the same
1202 // file, we get a big win by caching the result.
Chris Lattner46e3b482010-05-07 05:10:46 +00001203 if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
1204 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Mike Stump11289f42009-09-09 15:08:12 +00001205
Chris Lattner66d2f922010-05-07 01:17:07 +00001206 // Okay, we missed in the cache, start updating the cache for this query.
1207 IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first);
Mike Stump11289f42009-09-09 15:08:12 +00001208
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001209 // "Traverse" the include/instantiation stacks of both locations and try to
Chris Lattner06821c92010-05-07 05:51:13 +00001210 // find a common "ancestor". FileIDs build a tree-like structure that
1211 // reflects the #include hierarchy, and this algorithm needs to find the
1212 // nearest common ancestor between the two locations. For example, if you
1213 // have a.c that includes b.h and c.h, and are comparing a location in b.h to
1214 // a location in c.h, we need to find that their nearest common ancestor is
1215 // a.c, and compare the locations of the two #includes to find their relative
1216 // ordering.
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001217 //
Chris Lattner06821c92010-05-07 05:51:13 +00001218 // SourceManager assigns FileIDs in order of parsing. This means that an
1219 // includee always has a larger FileID than an includer. While you might
1220 // think that we could just compare the FileID's here, that doesn't work to
1221 // compare a point at the end of a.c with a point within c.h. Though c.h has
1222 // a larger FileID, we have to compare the include point of c.h to the
1223 // location in a.c.
1224 //
1225 // Despite not being able to directly compare FileID's, we can tell that a
1226 // larger FileID is necessarily more deeply nested than a lower one and use
1227 // this information to walk up the tree to the nearest common ancestor.
1228 do {
1229 // If LOffs is larger than ROffs, then LOffs must be more deeply nested than
1230 // ROffs, walk up the #include chain.
1231 if (LOffs.first.ID > ROffs.first.ID) {
Chris Lattnera99fa1a2010-05-07 20:35:24 +00001232 if (MoveUpIncludeHierarchy(LOffs, *this))
Chris Lattner06821c92010-05-07 05:51:13 +00001233 break; // We reached the top.
1234
Chris Lattner06821c92010-05-07 05:51:13 +00001235 } else {
1236 // Otherwise, ROffs is larger than LOffs, so ROffs must be more deeply
1237 // nested than LOffs, walk up the #include chain.
Chris Lattnera99fa1a2010-05-07 20:35:24 +00001238 if (MoveUpIncludeHierarchy(ROffs, *this))
Chris Lattner06821c92010-05-07 05:51:13 +00001239 break; // We reached the top.
Chris Lattner66d2f922010-05-07 01:17:07 +00001240 }
Chris Lattner06821c92010-05-07 05:51:13 +00001241 } while (LOffs.first != ROffs.first);
Mike Stump11289f42009-09-09 15:08:12 +00001242
Chris Lattner06821c92010-05-07 05:51:13 +00001243 // If we exited because we found a nearest common ancestor, compare the
1244 // locations within the common file and cache them.
1245 if (LOffs.first == ROffs.first) {
1246 IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
1247 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001248 }
Mike Stump11289f42009-09-09 15:08:12 +00001249
Daniel Dunbar465f4c42009-12-01 23:07:57 +00001250 // There is no common ancestor, most probably because one location is in the
Sebastian Redld44cd6a2010-08-18 23:57:06 +00001251 // predefines buffer or an AST file.
Daniel Dunbar465f4c42009-12-01 23:07:57 +00001252 // FIXME: We should rearrange the external interface so this simply never
1253 // happens; it can't conceptually happen. Also see PR5662.
Chris Lattnera99fa1a2010-05-07 20:35:24 +00001254 IsBeforeInTUCache.setQueryFIDs(FileID(), FileID()); // Don't try caching.
1255
1256 // Zip both entries up to the top level record.
1257 while (!MoveUpIncludeHierarchy(LOffs, *this)) /*empty*/;
1258 while (!MoveUpIncludeHierarchy(ROffs, *this)) /*empty*/;
Chris Lattner06821c92010-05-07 05:51:13 +00001259
Daniel Dunbar465f4c42009-12-01 23:07:57 +00001260 // If exactly one location is a memory buffer, assume it preceeds the other.
Chris Lattnera99fa1a2010-05-07 20:35:24 +00001261
1262 // Strip off macro instantation locations, going up to the top-level File
1263 // SLocEntry.
1264 bool LIsMB = getFileEntryForID(LOffs.first) == 0;
1265 bool RIsMB = getFileEntryForID(ROffs.first) == 0;
Chris Lattner06821c92010-05-07 05:51:13 +00001266 if (LIsMB != RIsMB)
Chris Lattner66d2f922010-05-07 01:17:07 +00001267 return LIsMB;
Mike Stump11289f42009-09-09 15:08:12 +00001268
Daniel Dunbar465f4c42009-12-01 23:07:57 +00001269 // Otherwise, just assume FileIDs were created in order.
Chris Lattner66d2f922010-05-07 01:17:07 +00001270 return LOffs.first < ROffs.first;
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001271}
Chris Lattner4fa23622009-01-26 00:43:02 +00001272
Chris Lattner22eb9722006-06-18 05:43:12 +00001273/// PrintStats - Print statistics to stderr.
1274///
1275void SourceManager::PrintStats() const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +00001276 llvm::errs() << "\n*** Source Manager Stats:\n";
1277 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
1278 << " mem buffers mapped.\n";
1279 llvm::errs() << SLocEntryTable.size() << " SLocEntry's allocated, "
1280 << NextOffset << "B of Sloc address space used.\n";
Mike Stump11289f42009-09-09 15:08:12 +00001281
Chris Lattner22eb9722006-06-18 05:43:12 +00001282 unsigned NumLineNumsComputed = 0;
1283 unsigned NumFileBytesMapped = 0;
Chris Lattnerc8233df2009-02-03 07:30:45 +00001284 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
1285 NumLineNumsComputed += I->second->SourceLineCache != 0;
1286 NumFileBytesMapped += I->second->getSizeBytesMapped();
Chris Lattner22eb9722006-06-18 05:43:12 +00001287 }
Mike Stump11289f42009-09-09 15:08:12 +00001288
Benjamin Kramer89b422c2009-08-23 12:08:50 +00001289 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
1290 << NumLineNumsComputed << " files with line #'s computed.\n";
1291 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
1292 << NumBinaryProbes << " binary.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +00001293}
Douglas Gregor258ae542009-04-27 06:38:32 +00001294
1295ExternalSLocEntrySource::~ExternalSLocEntrySource() { }