blob: ef52e824b14054b82e6aa6c260d0595b1558275a [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 Gregor802b7762010-03-15 22:54:52 +000015#include "clang/Basic/Diagnostic.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000016#include "clang/Basic/FileManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregore6642762011-02-03 17:17:35 +000018#include "llvm/ADT/Optional.h"
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +000019#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "llvm/ADT/StringSwitch.h"
21#include "llvm/Support/Capacity.h"
Chris Lattner8996fff2007-07-24 05:57:19 +000022#include "llvm/Support/Compiler.h"
Chris Lattner739e7392007-04-29 07:12:06 +000023#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000024#include "llvm/Support/Path.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "llvm/Support/raw_ostream.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000026#include <algorithm>
Douglas Gregore0fbb832010-03-16 00:06:06 +000027#include <cstring>
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include <string>
Douglas Gregor802b7762010-03-15 22:54:52 +000029
Chris Lattner22eb9722006-06-18 05:43:12 +000030using namespace clang;
Chris Lattner5f4b1ff2006-06-20 05:02:40 +000031using namespace SrcMgr;
Chris Lattner23b7eb62007-06-15 23:05:46 +000032using llvm::MemoryBuffer;
Chris Lattner22eb9722006-06-18 05:43:12 +000033
Chris Lattner153a0f12009-02-04 00:40:31 +000034//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +000035// SourceManager Helper Classes
Chris Lattner153a0f12009-02-04 00:40:31 +000036//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +000037
Ted Kremenekc08bca62007-10-30 21:08:08 +000038ContentCache::~ContentCache() {
Douglas Gregor3f4bea02010-07-26 21:36:20 +000039 if (shouldFreeBuffer())
40 delete Buffer.getPointer();
Chris Lattner22eb9722006-06-18 05:43:12 +000041}
42
Chandler Carruth64ee7822011-07-26 05:17:23 +000043/// getSizeBytesMapped - Returns the number of bytes actually mapped for this
44/// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
Ted Kremenek12c2af42009-01-06 01:55:26 +000045unsigned ContentCache::getSizeBytesMapped() const {
Douglas Gregor82752ec2010-03-16 22:53:51 +000046 return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
Ted Kremenek12c2af42009-01-06 01:55:26 +000047}
48
Ted Kremenek8d587902011-04-28 20:36:42 +000049/// Returns the kind of memory used to back the memory buffer for
50/// this content cache. This is used for performance analysis.
51llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
52 assert(Buffer.getPointer());
53
54 // Should be unreachable, but keep for sanity.
55 if (!Buffer.getPointer())
56 return llvm::MemoryBuffer::MemoryBuffer_Malloc;
David Blaikie66cc07b2014-06-27 17:40:03 +000057
58 llvm::MemoryBuffer *buf = Buffer.getPointer();
Ted Kremenek8d587902011-04-28 20:36:42 +000059 return buf->getBufferKind();
60}
61
Ted Kremenek12c2af42009-01-06 01:55:26 +000062/// getSize - Returns the size of the content encapsulated by this ContentCache.
63/// This can be the size of the source file or the size of an arbitrary
64/// scratch buffer. If the ContentCache encapsulates a source file, that
Douglas Gregor53ad6b92009-12-02 06:49:09 +000065/// file is not lazily brought in from disk to satisfy this query.
Ted Kremenek12c2af42009-01-06 01:55:26 +000066unsigned ContentCache::getSize() const {
Douglas Gregor82752ec2010-03-16 22:53:51 +000067 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +000068 : (unsigned) ContentsEntry->getSize();
Ted Kremenek12c2af42009-01-06 01:55:26 +000069}
70
David Blaikie66cc07b2014-06-27 17:40:03 +000071void ContentCache::replaceBuffer(llvm::MemoryBuffer *B, bool DoNotFree) {
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +000072 if (B && B == Buffer.getPointer()) {
Argyrios Kyrtzidiscc6107d2011-12-10 01:38:26 +000073 assert(0 && "Replacing with the same buffer");
74 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
75 return;
76 }
Douglas Gregor53ad6b92009-12-02 06:49:09 +000077
Douglas Gregor3f4bea02010-07-26 21:36:20 +000078 if (shouldFreeBuffer())
79 delete Buffer.getPointer();
Douglas Gregor82752ec2010-03-16 22:53:51 +000080 Buffer.setPointer(B);
Douglas Gregor3f4bea02010-07-26 21:36:20 +000081 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
Douglas Gregor53ad6b92009-12-02 06:49:09 +000082}
83
David Blaikie66cc07b2014-06-27 17:40:03 +000084llvm::MemoryBuffer *ContentCache::getBuffer(DiagnosticsEngine &Diag,
85 const SourceManager &SM,
86 SourceLocation Loc,
87 bool *Invalid) const {
Chris Lattner5631b052010-11-23 08:50:03 +000088 // Lazily create the Buffer for ContentCaches that wrap files. If we already
Chris Lattner57540c52011-04-15 05:22:18 +000089 // computed it, just return what we have.
Craig Topperf1186c52014-05-08 06:41:40 +000090 if (Buffer.getPointer() || !ContentsEntry) {
Chris Lattner5631b052010-11-23 08:50:03 +000091 if (Invalid)
92 *Invalid = isBufferInvalid();
Chris Lattner8fbe98b2010-04-20 18:14:03 +000093
Chris Lattner5631b052010-11-23 08:50:03 +000094 return Buffer.getPointer();
95 }
Benjamin Kramer5a3f1cf2010-11-18 12:46:39 +000096
Chris Lattner5631b052010-11-23 08:50:03 +000097 std::string ErrorStr;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +000098 bool isVolatile = SM.userFilesAreVolatile() && !IsSystemFile;
Rafael Espindola6406f7b2014-08-26 19:54:40 +000099 Buffer.setPointer(SM.getFileManager()
100 .getBufferForFile(ContentsEntry, &ErrorStr, isVolatile)
101 .release());
Chris Lattner5631b052010-11-23 08:50:03 +0000102
103 // If we were unable to open the file, then we are in an inconsistent
104 // situation where the content cache referenced a file which no longer
105 // exists. Most likely, we were using a stat cache with an invalid entry but
106 // the file could also have been removed during processing. Since we can't
107 // really deal with this situation, just create an empty buffer.
108 //
109 // FIXME: This is definitely not ideal, but our immediate clients can't
110 // currently handle returning a null entry here. Ideally we should detect
111 // that we are in an inconsistent situation and error out as quickly as
112 // possible.
113 if (!Buffer.getPointer()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000114 const StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000115 Buffer.setPointer(MemoryBuffer::getNewMemBuffer(ContentsEntry->getSize(),
Chris Lattner5631b052010-11-23 08:50:03 +0000116 "<invalid>"));
117 char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart());
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000118 for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
Chris Lattner5631b052010-11-23 08:50:03 +0000119 Ptr[i] = FillStr[i % FillStr.size()];
120
121 if (Diag.isDiagnosticInFlight())
122 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000123 ContentsEntry->getName(), ErrorStr);
Chris Lattner5631b052010-11-23 08:50:03 +0000124 else
125 Diag.Report(Loc, diag::err_cannot_open_file)
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000126 << ContentsEntry->getName() << ErrorStr;
Chris Lattner5631b052010-11-23 08:50:03 +0000127
128 Buffer.setInt(Buffer.getInt() | InvalidFlag);
129
130 if (Invalid) *Invalid = true;
131 return Buffer.getPointer();
132 }
133
134 // Check that the file's size is the same as in the file entry (which may
135 // have come from a stat cache).
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000136 if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) {
Chris Lattner5631b052010-11-23 08:50:03 +0000137 if (Diag.isDiagnosticInFlight())
138 Diag.SetDelayedDiagnostic(diag::err_file_modified,
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000139 ContentsEntry->getName());
Chris Lattner5631b052010-11-23 08:50:03 +0000140 else
141 Diag.Report(Loc, diag::err_file_modified)
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000142 << ContentsEntry->getName();
Chris Lattner5631b052010-11-23 08:50:03 +0000143
144 Buffer.setInt(Buffer.getInt() | InvalidFlag);
145 if (Invalid) *Invalid = true;
146 return Buffer.getPointer();
147 }
Eric Christopher7f36a792011-04-09 00:01:04 +0000148
Chris Lattner5631b052010-11-23 08:50:03 +0000149 // If the buffer is valid, check to see if it has a UTF Byte Order Mark
Eric Christopher7f36a792011-04-09 00:01:04 +0000150 // (BOM). We only support UTF-8 with and without a BOM right now. See
Chris Lattner5631b052010-11-23 08:50:03 +0000151 // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000152 StringRef BufStr = Buffer.getPointer()->getBuffer();
Eric Christopher7f36a792011-04-09 00:01:04 +0000153 const char *InvalidBOM = llvm::StringSwitch<const char *>(BufStr)
Chris Lattner5631b052010-11-23 08:50:03 +0000154 .StartsWith("\xFE\xFF", "UTF-16 (BE)")
155 .StartsWith("\xFF\xFE", "UTF-16 (LE)")
156 .StartsWith("\x00\x00\xFE\xFF", "UTF-32 (BE)")
157 .StartsWith("\xFF\xFE\x00\x00", "UTF-32 (LE)")
158 .StartsWith("\x2B\x2F\x76", "UTF-7")
159 .StartsWith("\xF7\x64\x4C", "UTF-1")
160 .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
161 .StartsWith("\x0E\xFE\xFF", "SDSU")
162 .StartsWith("\xFB\xEE\x28", "BOCU-1")
163 .StartsWith("\x84\x31\x95\x33", "GB-18030")
Craig Topperf1186c52014-05-08 06:41:40 +0000164 .Default(nullptr);
Chris Lattner5631b052010-11-23 08:50:03 +0000165
Eric Christopher7f36a792011-04-09 00:01:04 +0000166 if (InvalidBOM) {
Chris Lattner5631b052010-11-23 08:50:03 +0000167 Diag.Report(Loc, diag::err_unsupported_bom)
Eric Christopher7f36a792011-04-09 00:01:04 +0000168 << InvalidBOM << ContentsEntry->getName();
Chris Lattner5631b052010-11-23 08:50:03 +0000169 Buffer.setInt(Buffer.getInt() | InvalidFlag);
Ted Kremenek763ea552009-01-06 22:43:04 +0000170 }
Douglas Gregor802b7762010-03-15 22:54:52 +0000171
Douglas Gregor82752ec2010-03-16 22:53:51 +0000172 if (Invalid)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000173 *Invalid = isBufferInvalid();
Douglas Gregor82752ec2010-03-16 22:53:51 +0000174
175 return Buffer.getPointer();
Ted Kremenek12c2af42009-01-06 01:55:26 +0000176}
177
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000178unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000179 // Look up the filename in the string table, returning the pre-existing value
180 // if it exists.
Mike Stump11289f42009-09-09 15:08:12 +0000181 llvm::StringMapEntry<unsigned> &Entry =
Jay Foad9a6b0982011-06-21 15:13:30 +0000182 FilenameIDs.GetOrCreateValue(Name, ~0U);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000183 if (Entry.getValue() != ~0U)
184 return Entry.getValue();
Mike Stump11289f42009-09-09 15:08:12 +0000185
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000186 // Otherwise, assign this the next available ID.
187 Entry.setValue(FilenamesByID.size());
188 FilenamesByID.push_back(&Entry);
189 return FilenamesByID.size()-1;
190}
191
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000192/// AddLineNote - Add a line note to the line table that indicates that there
James Dennett88b71e42012-06-15 21:28:23 +0000193/// is a \#line at the specified FID/Offset location which changes the presumed
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000194/// location to LineNo/FilenameID.
Douglas Gregor02c2dbf2012-06-08 16:40:28 +0000195void LineTableInfo::AddLineNote(FileID FID, unsigned Offset,
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000196 unsigned LineNo, int FilenameID) {
Chris Lattner153a0f12009-02-04 00:40:31 +0000197 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump11289f42009-09-09 15:08:12 +0000198
Chris Lattner153a0f12009-02-04 00:40:31 +0000199 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
200 "Adding line entries out of order!");
Mike Stump11289f42009-09-09 15:08:12 +0000201
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000202 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
Chris Lattner1c967782009-02-04 06:25:26 +0000203 unsigned IncludeOffset = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000204
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000205 if (!Entries.empty()) {
206 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
207 // that we are still in "foo.h".
208 if (FilenameID == -1)
209 FilenameID = Entries.back().FilenameID;
Mike Stump11289f42009-09-09 15:08:12 +0000210
Chris Lattner1c967782009-02-04 06:25:26 +0000211 // If we are after a line marker that switched us to system header mode, or
212 // that set #include information, preserve it.
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000213 Kind = Entries.back().FileKind;
Chris Lattner1c967782009-02-04 06:25:26 +0000214 IncludeOffset = Entries.back().IncludeOffset;
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000215 }
Mike Stump11289f42009-09-09 15:08:12 +0000216
Chris Lattner1c967782009-02-04 06:25:26 +0000217 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
218 IncludeOffset));
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000219}
220
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000221/// AddLineNote This is the same as the previous version of AddLineNote, but is
222/// used for GNU line markers. If EntryExit is 0, then this doesn't change the
James Dennett87a2acf2012-06-17 03:22:59 +0000223/// presumed \#include stack. If it is 1, this is a file entry, if it is 2 then
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000224/// this is a file exit. FileKind specifies whether this is a system header or
225/// extern C system header.
Douglas Gregor02c2dbf2012-06-08 16:40:28 +0000226void LineTableInfo::AddLineNote(FileID FID, unsigned Offset,
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000227 unsigned LineNo, int FilenameID,
228 unsigned EntryExit,
229 SrcMgr::CharacteristicKind FileKind) {
230 assert(FilenameID != -1 && "Unspecified filename should use other accessor");
Mike Stump11289f42009-09-09 15:08:12 +0000231
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000232 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump11289f42009-09-09 15:08:12 +0000233
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000234 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
235 "Adding line entries out of order!");
236
Chris Lattner1c967782009-02-04 06:25:26 +0000237 unsigned IncludeOffset = 0;
238 if (EntryExit == 0) { // No #include stack change.
239 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
240 } else if (EntryExit == 1) {
241 IncludeOffset = Offset-1;
242 } else if (EntryExit == 2) {
243 assert(!Entries.empty() && Entries.back().IncludeOffset &&
244 "PPDirectives should have caught case when popping empty include stack");
Mike Stump11289f42009-09-09 15:08:12 +0000245
Chris Lattner1c967782009-02-04 06:25:26 +0000246 // Get the include loc of the last entries' include loc as our include loc.
247 IncludeOffset = 0;
248 if (const LineEntry *PrevEntry =
249 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
250 IncludeOffset = PrevEntry->IncludeOffset;
251 }
Mike Stump11289f42009-09-09 15:08:12 +0000252
Chris Lattner1c967782009-02-04 06:25:26 +0000253 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
254 IncludeOffset));
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000255}
256
257
Chris Lattnerd4293922009-02-04 01:55:42 +0000258/// FindNearestLineEntry - Find the line entry nearest to FID that is before
259/// it. If there is no line entry before Offset in FID, return null.
Douglas Gregor02c2dbf2012-06-08 16:40:28 +0000260const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID,
Chris Lattnerd4293922009-02-04 01:55:42 +0000261 unsigned Offset) {
262 const std::vector<LineEntry> &Entries = LineEntries[FID];
263 assert(!Entries.empty() && "No #line entries for this FID after all!");
264
Chris Lattner334a2ad2009-02-04 04:46:59 +0000265 // It is very common for the query to be after the last #line, check this
266 // first.
267 if (Entries.back().FileOffset <= Offset)
268 return &Entries.back();
Chris Lattnerd4293922009-02-04 01:55:42 +0000269
Chris Lattner334a2ad2009-02-04 04:46:59 +0000270 // Do a binary search to find the maximal element that is still before Offset.
271 std::vector<LineEntry>::const_iterator I =
272 std::upper_bound(Entries.begin(), Entries.end(), Offset);
Craig Topperf1186c52014-05-08 06:41:40 +0000273 if (I == Entries.begin()) return nullptr;
Chris Lattner334a2ad2009-02-04 04:46:59 +0000274 return &*--I;
Chris Lattnerd4293922009-02-04 01:55:42 +0000275}
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000276
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000277/// \brief Add a new line entry that has already been encoded into
278/// the internal representation of the line table.
Douglas Gregor02c2dbf2012-06-08 16:40:28 +0000279void LineTableInfo::AddEntry(FileID FID,
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000280 const std::vector<LineEntry> &Entries) {
281 LineEntries[FID] = Entries;
282}
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000283
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000284/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
Mike Stump11289f42009-09-09 15:08:12 +0000285///
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000286unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
Craig Topperf1186c52014-05-08 06:41:40 +0000287 if (!LineTable)
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000288 LineTable = new LineTableInfo();
Jay Foad9a6b0982011-06-21 15:13:30 +0000289 return LineTable->getLineTableFilenameID(Name);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000290}
291
292
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000293/// AddLineNote - Add a line note to the line table for the FileID and offset
294/// specified by Loc. If FilenameID is -1, it is considered to be
295/// unspecified.
296void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
297 int FilenameID) {
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000298 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000299
Douglas Gregor49f754f2011-04-20 00:21:03 +0000300 bool Invalid = false;
301 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
302 if (!Entry.isFile() || Invalid)
303 return;
304
305 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000306
307 // Remember that this file has #line directives now if it doesn't already.
308 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump11289f42009-09-09 15:08:12 +0000309
Craig Topperf1186c52014-05-08 06:41:40 +0000310 if (!LineTable)
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000311 LineTable = new LineTableInfo();
Douglas Gregor02c2dbf2012-06-08 16:40:28 +0000312 LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID);
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000313}
314
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000315/// AddLineNote - Add a GNU line marker to the line table.
316void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
317 int FilenameID, bool IsFileEntry,
318 bool IsFileExit, bool IsSystemHeader,
319 bool IsExternCHeader) {
320 // If there is no filename and no flags, this is treated just like a #line,
321 // which does not change the flags of the previous line marker.
322 if (FilenameID == -1) {
323 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
324 "Can't set flags without setting the filename!");
325 return AddLineNote(Loc, LineNo, FilenameID);
326 }
Mike Stump11289f42009-09-09 15:08:12 +0000327
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000328 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregor49f754f2011-04-20 00:21:03 +0000329
330 bool Invalid = false;
331 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
332 if (!Entry.isFile() || Invalid)
333 return;
334
335 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
Mike Stump11289f42009-09-09 15:08:12 +0000336
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000337 // Remember that this file has #line directives now if it doesn't already.
338 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump11289f42009-09-09 15:08:12 +0000339
Craig Topperf1186c52014-05-08 06:41:40 +0000340 if (!LineTable)
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000341 LineTable = new LineTableInfo();
Mike Stump11289f42009-09-09 15:08:12 +0000342
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000343 SrcMgr::CharacteristicKind FileKind;
344 if (IsExternCHeader)
345 FileKind = SrcMgr::C_ExternCSystem;
346 else if (IsSystemHeader)
347 FileKind = SrcMgr::C_System;
348 else
349 FileKind = SrcMgr::C_User;
Mike Stump11289f42009-09-09 15:08:12 +0000350
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000351 unsigned EntryExit = 0;
352 if (IsFileEntry)
353 EntryExit = 1;
354 else if (IsFileExit)
355 EntryExit = 2;
Mike Stump11289f42009-09-09 15:08:12 +0000356
Douglas Gregor02c2dbf2012-06-08 16:40:28 +0000357 LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000358 EntryExit, FileKind);
359}
360
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000361LineTableInfo &SourceManager::getLineTable() {
Craig Topperf1186c52014-05-08 06:41:40 +0000362 if (!LineTable)
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000363 LineTable = new LineTableInfo();
364 return *LineTable;
365}
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000366
Chris Lattner153a0f12009-02-04 00:40:31 +0000367//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +0000368// Private 'Create' methods.
Chris Lattner153a0f12009-02-04 00:40:31 +0000369//===----------------------------------------------------------------------===//
Ted Kremenek12c2af42009-01-06 01:55:26 +0000370
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000371SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
372 bool UserFilesAreVolatile)
Argyrios Kyrtzidis97d3a382011-03-08 23:35:24 +0000373 : Diag(Diag), FileMgr(FileMgr), OverridenFilesKeepOriginalName(true),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000374 UserFilesAreVolatile(UserFilesAreVolatile),
Craig Topperf1186c52014-05-08 06:41:40 +0000375 ExternalSLocEntries(nullptr), LineTable(nullptr), NumLinearScans(0),
Rafael Espindolae0f6d882014-08-18 18:33:41 +0000376 NumBinaryProbes(0) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000377 clearIDTables();
378 Diag.setSourceManager(this);
379}
380
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000381SourceManager::~SourceManager() {
382 delete LineTable;
Mike Stump11289f42009-09-09 15:08:12 +0000383
Chris Lattnerc8233df2009-02-03 07:30:45 +0000384 // Delete FileEntry objects corresponding to content caches. Since the actual
385 // content cache objects are bump pointer allocated, we just have to run the
386 // dtors, but we call the deallocate method for completeness.
387 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
Argyrios Kyrtzidisaf41b3f2011-12-15 23:37:55 +0000388 if (MemBufferInfos[i]) {
389 MemBufferInfos[i]->~ContentCache();
390 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
391 }
Chris Lattnerc8233df2009-02-03 07:30:45 +0000392 }
393 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
394 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
Argyrios Kyrtzidisaf41b3f2011-12-15 23:37:55 +0000395 if (I->second) {
396 I->second->~ContentCache();
397 ContentCacheAlloc.Deallocate(I->second);
398 }
Chris Lattnerc8233df2009-02-03 07:30:45 +0000399 }
Argyrios Kyrtzidis4bdd6aa2011-09-26 08:01:50 +0000400
Reid Kleckner588c9372014-02-19 23:44:52 +0000401 llvm::DeleteContainerSeconds(MacroArgsCacheMap);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000402}
403
404void SourceManager::clearIDTables() {
405 MainFileID = FileID();
Douglas Gregor925296b2011-07-19 16:10:42 +0000406 LocalSLocEntryTable.clear();
407 LoadedSLocEntryTable.clear();
408 SLocEntryLoaded.clear();
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000409 LastLineNoFileIDQuery = FileID();
Craig Topperf1186c52014-05-08 06:41:40 +0000410 LastLineNoContentCache = nullptr;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000411 LastFileIDLookup = FileID();
Mike Stump11289f42009-09-09 15:08:12 +0000412
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000413 if (LineTable)
414 LineTable->clear();
Mike Stump11289f42009-09-09 15:08:12 +0000415
Chandler Carruth64ee7822011-07-26 05:17:23 +0000416 // Use up FileID #0 as an invalid expansion.
Douglas Gregor925296b2011-07-19 16:10:42 +0000417 NextLocalOffset = 0;
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +0000418 CurrentLoadedOffset = MaxLoadedOffset;
Chandler Carruth115b0772011-07-26 03:03:05 +0000419 createExpansionLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000420}
421
Chris Lattner4fa23622009-01-26 00:43:02 +0000422/// getOrCreateContentCache - Create or return a cached ContentCache for the
423/// specified file.
424const ContentCache *
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000425SourceManager::getOrCreateContentCache(const FileEntry *FileEnt,
426 bool isSystemFile) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000427 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump11289f42009-09-09 15:08:12 +0000428
Chris Lattner22eb9722006-06-18 05:43:12 +0000429 // Do we already have information about this file?
Chris Lattnerc8233df2009-02-03 07:30:45 +0000430 ContentCache *&Entry = FileInfos[FileEnt];
431 if (Entry) return Entry;
Mike Stump11289f42009-09-09 15:08:12 +0000432
Chandler Carruth47c48082014-04-15 21:34:12 +0000433 // Nope, create a new Cache entry.
434 Entry = ContentCacheAlloc.Allocate<ContentCache>();
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000435
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +0000436 if (OverriddenFilesInfo) {
437 // If the file contents are overridden with contents from another file,
438 // pass that file to ContentCache.
439 llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
440 overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
441 if (overI == OverriddenFilesInfo->OverriddenFiles.end())
442 new (Entry) ContentCache(FileEnt);
443 else
444 new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
445 : overI->second,
446 overI->second);
447 } else {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000448 new (Entry) ContentCache(FileEnt);
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +0000449 }
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000450
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000451 Entry->IsSystemFile = isSystemFile;
452
Chris Lattnerc8233df2009-02-03 07:30:45 +0000453 return Entry;
Chris Lattner22eb9722006-06-18 05:43:12 +0000454}
455
456
Ted Kremenek08bed092007-10-31 17:53:38 +0000457/// createMemBufferContentCache - Create a new ContentCache for the specified
458/// memory buffer. This does no caching.
David Blaikie66cc07b2014-06-27 17:40:03 +0000459const ContentCache *
460SourceManager::createMemBufferContentCache(llvm::MemoryBuffer *Buffer) {
Chandler Carruth47c48082014-04-15 21:34:12 +0000461 // Add a new ContentCache to the MemBufferInfos list and return it.
462 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
Chris Lattnerc8233df2009-02-03 07:30:45 +0000463 new (Entry) ContentCache();
464 MemBufferInfos.push_back(Entry);
465 Entry->setBuffer(Buffer);
466 return Entry;
Chris Lattner22eb9722006-06-18 05:43:12 +0000467}
468
Argyrios Kyrtzidis969fdfd2012-02-20 23:58:07 +0000469const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
470 bool *Invalid) const {
471 assert(!SLocEntryLoaded[Index]);
472 if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
473 if (Invalid)
474 *Invalid = true;
475 // If the file of the SLocEntry changed we could still have loaded it.
476 if (!SLocEntryLoaded[Index]) {
477 // Try to recover; create a SLocEntry so the rest of clang can handle it.
478 LoadedSLocEntryTable[Index] = SLocEntry::get(0,
479 FileInfo::get(SourceLocation(),
480 getFakeContentCacheForRecovery(),
481 SrcMgr::C_User));
482 }
483 }
484
485 return LoadedSLocEntryTable[Index];
486}
487
Douglas Gregor925296b2011-07-19 16:10:42 +0000488std::pair<int, unsigned>
489SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
490 unsigned TotalSize) {
491 assert(ExternalSLocEntries && "Don't have an external sloc source");
492 LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
493 SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
494 CurrentLoadedOffset -= TotalSize;
495 assert(CurrentLoadedOffset >= NextLocalOffset && "Out of source locations");
496 int ID = LoadedSLocEntryTable.size();
497 return std::make_pair(-ID - 1, CurrentLoadedOffset);
Douglas Gregor0bc12932009-04-27 21:28:04 +0000498}
499
Douglas Gregor49f754f2011-04-20 00:21:03 +0000500/// \brief As part of recovering from missing or changed content, produce a
501/// fake, non-empty buffer.
David Blaikie66cc07b2014-06-27 17:40:03 +0000502llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const {
Douglas Gregor49f754f2011-04-20 00:21:03 +0000503 if (!FakeBufferForRecovery)
Rafael Espindolae0f6d882014-08-18 18:33:41 +0000504 FakeBufferForRecovery.reset(
505 llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>"));
506
507 return FakeBufferForRecovery.get();
Douglas Gregor49f754f2011-04-20 00:21:03 +0000508}
Douglas Gregor258ae542009-04-27 06:38:32 +0000509
Argyrios Kyrtzidis969fdfd2012-02-20 23:58:07 +0000510/// \brief As part of recovering from missing or changed content, produce a
511/// fake content cache.
512const SrcMgr::ContentCache *
513SourceManager::getFakeContentCacheForRecovery() const {
514 if (!FakeContentCacheForRecovery) {
Rafael Espindolae0f6d882014-08-18 18:33:41 +0000515 FakeContentCacheForRecovery = llvm::make_unique<SrcMgr::ContentCache>();
Argyrios Kyrtzidis969fdfd2012-02-20 23:58:07 +0000516 FakeContentCacheForRecovery->replaceBuffer(getFakeBufferForRecovery(),
517 /*DoNotFree=*/true);
518 }
Rafael Espindolae0f6d882014-08-18 18:33:41 +0000519 return FakeContentCacheForRecovery.get();
Argyrios Kyrtzidis969fdfd2012-02-20 23:58:07 +0000520}
521
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000522/// \brief Returns the previous in-order FileID or an invalid FileID if there
523/// is no previous one.
524FileID SourceManager::getPreviousFileID(FileID FID) const {
525 if (FID.isInvalid())
526 return FileID();
527
528 int ID = FID.ID;
529 if (ID == -1)
530 return FileID();
531
532 if (ID > 0) {
533 if (ID-1 == 0)
534 return FileID();
535 } else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {
536 return FileID();
537 }
538
539 return FileID::get(ID-1);
540}
541
542/// \brief Returns the next in-order FileID or an invalid FileID if there is
543/// no next one.
544FileID SourceManager::getNextFileID(FileID FID) const {
545 if (FID.isInvalid())
546 return FileID();
547
548 int ID = FID.ID;
549 if (ID > 0) {
550 if (unsigned(ID+1) >= local_sloc_entry_size())
551 return FileID();
552 } else if (ID+1 >= -1) {
553 return FileID();
554 }
555
556 return FileID::get(ID+1);
557}
558
Chris Lattner4fa23622009-01-26 00:43:02 +0000559//===----------------------------------------------------------------------===//
Chandler Carruth64ee7822011-07-26 05:17:23 +0000560// Methods to create new FileID's and macro expansions.
Chris Lattner4fa23622009-01-26 00:43:02 +0000561//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000562
Dan Gohmance46f022010-08-26 21:27:06 +0000563/// createFileID - Create a new FileID for the specified ContentCache and
Ted Kremeneke26f3c52007-10-30 22:57:35 +0000564/// include position. This works regardless of whether the ContentCache
565/// corresponds to a file or some other input source.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000566FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattner4fa23622009-01-26 00:43:02 +0000567 SourceLocation IncludePos,
Douglas Gregor258ae542009-04-27 06:38:32 +0000568 SrcMgr::CharacteristicKind FileCharacter,
Douglas Gregor925296b2011-07-19 16:10:42 +0000569 int LoadedID, unsigned LoadedOffset) {
570 if (LoadedID < 0) {
571 assert(LoadedID != -1 && "Loading sentinel FileID");
572 unsigned Index = unsigned(-LoadedID) - 2;
573 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
574 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
575 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset,
576 FileInfo::get(IncludePos, File, FileCharacter));
577 SLocEntryLoaded[Index] = true;
578 return FileID::get(LoadedID);
Douglas Gregor258ae542009-04-27 06:38:32 +0000579 }
Douglas Gregor925296b2011-07-19 16:10:42 +0000580 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset,
581 FileInfo::get(IncludePos, File,
582 FileCharacter)));
Ted Kremenek12c2af42009-01-06 01:55:26 +0000583 unsigned FileSize = File->getSize();
Douglas Gregor925296b2011-07-19 16:10:42 +0000584 assert(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
585 NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset &&
586 "Ran out of source locations!");
587 // We do a +1 here because we want a SourceLocation that means "the end of the
588 // file", e.g. for the "no newline at the end of the file" diagnostic.
589 NextLocalOffset += FileSize + 1;
Mike Stump11289f42009-09-09 15:08:12 +0000590
Chris Lattner4fa23622009-01-26 00:43:02 +0000591 // Set LastFileIDLookup to the newly created file. The next getFileID call is
592 // almost guaranteed to be from that file.
Douglas Gregor925296b2011-07-19 16:10:42 +0000593 FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
Argyrios Kyrtzidis0152c6c2009-06-23 00:42:06 +0000594 return LastFileIDLookup = FID;
Chris Lattner22eb9722006-06-18 05:43:12 +0000595}
596
Chandler Carruth402bb382011-07-07 23:56:36 +0000597SourceLocation
Chandler Carruth115b0772011-07-26 03:03:05 +0000598SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc,
599 SourceLocation ExpansionLoc,
600 unsigned TokLength) {
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000601 ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
602 ExpansionLoc);
603 return createExpansionLocImpl(Info, TokLength);
Chandler Carruth402bb382011-07-07 23:56:36 +0000604}
605
606SourceLocation
Chandler Carruth115b0772011-07-26 03:03:05 +0000607SourceManager::createExpansionLoc(SourceLocation SpellingLoc,
608 SourceLocation ExpansionLocStart,
609 SourceLocation ExpansionLocEnd,
610 unsigned TokLength,
611 int LoadedID,
612 unsigned LoadedOffset) {
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000613 ExpansionInfo Info = ExpansionInfo::create(SpellingLoc, ExpansionLocStart,
614 ExpansionLocEnd);
615 return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset);
Chandler Carruth115b0772011-07-26 03:03:05 +0000616}
617
618SourceLocation
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000619SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
Chandler Carruth115b0772011-07-26 03:03:05 +0000620 unsigned TokLength,
621 int LoadedID,
622 unsigned LoadedOffset) {
Douglas Gregor925296b2011-07-19 16:10:42 +0000623 if (LoadedID < 0) {
624 assert(LoadedID != -1 && "Loading sentinel FileID");
625 unsigned Index = unsigned(-LoadedID) - 2;
626 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
627 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000628 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
Douglas Gregor925296b2011-07-19 16:10:42 +0000629 SLocEntryLoaded[Index] = true;
630 return SourceLocation::getMacroLoc(LoadedOffset);
Douglas Gregor258ae542009-04-27 06:38:32 +0000631 }
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000632 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
Douglas Gregor925296b2011-07-19 16:10:42 +0000633 assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&
634 NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&
635 "Ran out of source locations!");
636 // See createFileID for that +1.
637 NextLocalOffset += TokLength + 1;
638 return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
Chris Lattner7d6a4f62006-06-30 06:10:08 +0000639}
640
David Blaikie66cc07b2014-06-27 17:40:03 +0000641llvm::MemoryBuffer *SourceManager::getMemoryBufferForFile(const FileEntry *File,
642 bool *Invalid) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000643 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregor802b7762010-03-15 22:54:52 +0000644 assert(IR && "getOrCreateContentCache() cannot return NULL");
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000645 return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000646}
647
Dan Gohman5d223dc2010-10-26 20:47:28 +0000648void SourceManager::overrideFileContents(const FileEntry *SourceFile,
David Blaikie66cc07b2014-06-27 17:40:03 +0000649 llvm::MemoryBuffer *Buffer,
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000650 bool DoNotFree) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000651 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
Dan Gohman5d223dc2010-10-26 20:47:28 +0000652 assert(IR && "getOrCreateContentCache() cannot return NULL");
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000653
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000654 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
Douglas Gregor9dc32122011-11-16 20:05:18 +0000655 const_cast<SrcMgr::ContentCache *>(IR)->BufferOverridden = true;
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +0000656
657 getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000658}
659
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000660void SourceManager::overrideFileContents(const FileEntry *SourceFile,
661 const FileEntry *NewFile) {
662 assert(SourceFile->getSize() == NewFile->getSize() &&
663 "Different sizes, use the FileManager to create a virtual file with "
664 "the correct size");
665 assert(FileInfos.count(SourceFile) == 0 &&
666 "This function should be called at the initialization stage, before "
667 "any parsing occurs.");
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +0000668 getOverriddenFilesInfo().OverriddenFiles[SourceFile] = NewFile;
669}
670
671void SourceManager::disableFileContentsOverride(const FileEntry *File) {
672 if (!isFileOverridden(File))
673 return;
674
675 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Craig Topperf1186c52014-05-08 06:41:40 +0000676 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(nullptr);
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +0000677 const_cast<SrcMgr::ContentCache *>(IR)->ContentsEntry = IR->OrigEntry;
678
679 assert(OverriddenFilesInfo);
680 OverriddenFilesInfo->OverriddenFiles.erase(File);
681 OverriddenFilesInfo->OverriddenFilesWithBuffer.erase(File);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000682}
683
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000684StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +0000685 bool MyInvalid = false;
Douglas Gregor925296b2011-07-19 16:10:42 +0000686 const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid);
Douglas Gregor49f754f2011-04-20 00:21:03 +0000687 if (!SLoc.isFile() || MyInvalid) {
Douglas Gregor86af9842011-01-31 22:42:36 +0000688 if (Invalid)
689 *Invalid = true;
690 return "<<<<<INVALID SOURCE LOCATION>>>>>";
691 }
David Blaikie66cc07b2014-06-27 17:40:03 +0000692
693 llvm::MemoryBuffer *Buf = SLoc.getFile().getContentCache()->getBuffer(
694 Diag, *this, SourceLocation(), &MyInvalid);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000695 if (Invalid)
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +0000696 *Invalid = MyInvalid;
697
698 if (MyInvalid)
Douglas Gregor86af9842011-01-31 22:42:36 +0000699 return "<<<<<INVALID SOURCE LOCATION>>>>>";
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +0000700
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000701 return Buf->getBuffer();
Douglas Gregor802b7762010-03-15 22:54:52 +0000702}
Chris Lattnerd32480d2009-01-17 06:22:33 +0000703
Chris Lattner153a0f12009-02-04 00:40:31 +0000704//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +0000705// SourceLocation manipulation methods.
Chris Lattner153a0f12009-02-04 00:40:31 +0000706//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +0000707
Douglas Gregor925296b2011-07-19 16:10:42 +0000708/// \brief Return the FileID for a SourceLocation.
Chris Lattner4fa23622009-01-26 00:43:02 +0000709///
Douglas Gregor925296b2011-07-19 16:10:42 +0000710/// This is the cache-miss path of getFileID. Not as hot as that function, but
711/// still very important. It is responsible for finding the entry in the
712/// SLocEntry tables that contains the specified location.
Chris Lattner4fa23622009-01-26 00:43:02 +0000713FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
Douglas Gregor49f754f2011-04-20 00:21:03 +0000714 if (!SLocOffset)
715 return FileID::get(0);
Mike Stump11289f42009-09-09 15:08:12 +0000716
Douglas Gregor925296b2011-07-19 16:10:42 +0000717 // Now it is time to search for the correct file. See where the SLocOffset
718 // sits in the global view and consult local or loaded buffers for it.
719 if (SLocOffset < NextLocalOffset)
720 return getFileIDLocal(SLocOffset);
721 return getFileIDLoaded(SLocOffset);
722}
723
724/// \brief Return the FileID for a SourceLocation with a low offset.
725///
726/// This function knows that the SourceLocation is in a local buffer, not a
727/// loaded one.
728FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const {
729 assert(SLocOffset < NextLocalOffset && "Bad function choice");
730
Chris Lattner4fa23622009-01-26 00:43:02 +0000731 // After the first and second level caches, I see two common sorts of
Chandler Carruth64ee7822011-07-26 05:17:23 +0000732 // behavior: 1) a lot of searched FileID's are "near" the cached file
733 // location or are "near" the cached expansion location. 2) others are just
Chris Lattner4fa23622009-01-26 00:43:02 +0000734 // completely random and may be a very long way away.
735 //
736 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
737 // then we fall back to a less cache efficient, but more scalable, binary
738 // search to find the location.
Mike Stump11289f42009-09-09 15:08:12 +0000739
Chris Lattner4fa23622009-01-26 00:43:02 +0000740 // See if this is near the file point - worst case we start scanning from the
741 // most newly created FileID.
Benjamin Kramer2999b772013-02-22 18:29:39 +0000742 const SrcMgr::SLocEntry *I;
Mike Stump11289f42009-09-09 15:08:12 +0000743
Douglas Gregor925296b2011-07-19 16:10:42 +0000744 if (LastFileIDLookup.ID < 0 ||
745 LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
Chris Lattner4fa23622009-01-26 00:43:02 +0000746 // Neither loc prunes our search.
Douglas Gregor925296b2011-07-19 16:10:42 +0000747 I = LocalSLocEntryTable.end();
Chris Lattner4fa23622009-01-26 00:43:02 +0000748 } else {
749 // Perhaps it is near the file point.
Douglas Gregor925296b2011-07-19 16:10:42 +0000750 I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
Chris Lattner4fa23622009-01-26 00:43:02 +0000751 }
752
753 // Find the FileID that contains this. "I" is an iterator that points to a
754 // FileID whose offset is known to be larger than SLocOffset.
755 unsigned NumProbes = 0;
756 while (1) {
757 --I;
758 if (I->getOffset() <= SLocOffset) {
Douglas Gregor925296b2011-07-19 16:10:42 +0000759 FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
Douglas Gregor258ae542009-04-27 06:38:32 +0000760
Chandler Carruth64ee7822011-07-26 05:17:23 +0000761 // If this isn't an expansion, remember it. We have good locality across
762 // FileID lookups.
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000763 if (!I->isExpansion())
Chris Lattner4fa23622009-01-26 00:43:02 +0000764 LastFileIDLookup = Res;
765 NumLinearScans += NumProbes+1;
766 return Res;
767 }
768 if (++NumProbes == 8)
769 break;
770 }
Mike Stump11289f42009-09-09 15:08:12 +0000771
Chris Lattner4fa23622009-01-26 00:43:02 +0000772 // Convert "I" back into an index. We know that it is an entry whose index is
773 // larger than the offset we are looking for.
Douglas Gregor925296b2011-07-19 16:10:42 +0000774 unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
Chris Lattner4fa23622009-01-26 00:43:02 +0000775 // LessIndex - This is the lower bound of the range that we're searching.
776 // We know that the offset corresponding to the FileID is is less than
777 // SLocOffset.
778 unsigned LessIndex = 0;
779 NumProbes = 0;
780 while (1) {
Douglas Gregor49f754f2011-04-20 00:21:03 +0000781 bool Invalid = false;
Chris Lattner4fa23622009-01-26 00:43:02 +0000782 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregor925296b2011-07-19 16:10:42 +0000783 unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
Douglas Gregor49f754f2011-04-20 00:21:03 +0000784 if (Invalid)
785 return FileID::get(0);
786
Chris Lattner4fa23622009-01-26 00:43:02 +0000787 ++NumProbes;
Mike Stump11289f42009-09-09 15:08:12 +0000788
Chris Lattner4fa23622009-01-26 00:43:02 +0000789 // If the offset of the midpoint is too large, chop the high side of the
790 // range to the midpoint.
791 if (MidOffset > SLocOffset) {
792 GreaterIndex = MiddleIndex;
793 continue;
794 }
Mike Stump11289f42009-09-09 15:08:12 +0000795
Chris Lattner4fa23622009-01-26 00:43:02 +0000796 // If the middle index contains the value, succeed and return.
Douglas Gregor925296b2011-07-19 16:10:42 +0000797 // FIXME: This could be made faster by using a function that's aware of
798 // being in the local area.
Chris Lattner4fa23622009-01-26 00:43:02 +0000799 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
Chris Lattner4fa23622009-01-26 00:43:02 +0000800 FileID Res = FileID::get(MiddleIndex);
801
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000802 // If this isn't a macro expansion, remember it. We have good locality
Chris Lattner4fa23622009-01-26 00:43:02 +0000803 // across FileID lookups.
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000804 if (!LocalSLocEntryTable[MiddleIndex].isExpansion())
Chris Lattner4fa23622009-01-26 00:43:02 +0000805 LastFileIDLookup = Res;
806 NumBinaryProbes += NumProbes;
807 return Res;
808 }
Mike Stump11289f42009-09-09 15:08:12 +0000809
Chris Lattner4fa23622009-01-26 00:43:02 +0000810 // Otherwise, move the low-side up to the middle index.
811 LessIndex = MiddleIndex;
812 }
813}
814
Douglas Gregor925296b2011-07-19 16:10:42 +0000815/// \brief Return the FileID for a SourceLocation with a high offset.
816///
817/// This function knows that the SourceLocation is in a loaded buffer, not a
818/// local one.
819FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
Argyrios Kyrtzidis25029d42011-10-03 23:43:01 +0000820 // Sanity checking, otherwise a bug may lead to hanging in release build.
Argyrios Kyrtzidis8edffaa2011-10-25 00:29:44 +0000821 if (SLocOffset < CurrentLoadedOffset) {
822 assert(0 && "Invalid SLocOffset or bad function choice");
Argyrios Kyrtzidis25029d42011-10-03 23:43:01 +0000823 return FileID();
Argyrios Kyrtzidis8edffaa2011-10-25 00:29:44 +0000824 }
Argyrios Kyrtzidis25029d42011-10-03 23:43:01 +0000825
Douglas Gregor925296b2011-07-19 16:10:42 +0000826 // Essentially the same as the local case, but the loaded array is sorted
827 // in the other direction.
828
829 // First do a linear scan from the last lookup position, if possible.
830 unsigned I;
831 int LastID = LastFileIDLookup.ID;
832 if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
833 I = 0;
834 else
835 I = (-LastID - 2) + 1;
836
837 unsigned NumProbes;
838 for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
839 // Make sure the entry is loaded!
840 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
841 if (E.getOffset() <= SLocOffset) {
842 FileID Res = FileID::get(-int(I) - 2);
843
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000844 if (!E.isExpansion())
Douglas Gregor925296b2011-07-19 16:10:42 +0000845 LastFileIDLookup = Res;
846 NumLinearScans += NumProbes + 1;
847 return Res;
848 }
849 }
850
851 // Linear scan failed. Do the binary search. Note the reverse sorting of the
852 // table: GreaterIndex is the one where the offset is greater, which is
853 // actually a lower index!
854 unsigned GreaterIndex = I;
855 unsigned LessIndex = LoadedSLocEntryTable.size();
856 NumProbes = 0;
857 while (1) {
858 ++NumProbes;
859 unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
860 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
Argyrios Kyrtzidis7dc4f332013-03-01 03:26:00 +0000861 if (E.getOffset() == 0)
862 return FileID(); // invalid entry.
Douglas Gregor925296b2011-07-19 16:10:42 +0000863
864 ++NumProbes;
865
866 if (E.getOffset() > SLocOffset) {
Argyrios Kyrtzidis7dc4f332013-03-01 03:26:00 +0000867 // Sanity checking, otherwise a bug may lead to hanging in release build.
868 if (GreaterIndex == MiddleIndex) {
869 assert(0 && "binary search missed the entry");
870 return FileID();
871 }
Douglas Gregor925296b2011-07-19 16:10:42 +0000872 GreaterIndex = MiddleIndex;
873 continue;
874 }
875
876 if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
877 FileID Res = FileID::get(-int(MiddleIndex) - 2);
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000878 if (!E.isExpansion())
Douglas Gregor925296b2011-07-19 16:10:42 +0000879 LastFileIDLookup = Res;
880 NumBinaryProbes += NumProbes;
881 return Res;
882 }
883
Argyrios Kyrtzidis1ca73442013-03-01 03:43:33 +0000884 // Sanity checking, otherwise a bug may lead to hanging in release build.
885 if (LessIndex == MiddleIndex) {
886 assert(0 && "binary search missed the entry");
887 return FileID();
888 }
Douglas Gregor925296b2011-07-19 16:10:42 +0000889 LessIndex = MiddleIndex;
890 }
891}
892
Chris Lattner659ac5f2009-01-26 20:04:19 +0000893SourceLocation SourceManager::
Chandler Carruthc84d7692011-07-25 20:52:26 +0000894getExpansionLocSlowCase(SourceLocation Loc) const {
Chris Lattner659ac5f2009-01-26 20:04:19 +0000895 do {
Chris Lattner5647d312010-02-12 19:31:35 +0000896 // Note: If Loc indicates an offset into a token that came from a macro
897 // expansion (e.g. the 5th character of the token) we do not want to add
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000898 // this offset when going to the expansion location. The expansion
Chris Lattner5647d312010-02-12 19:31:35 +0000899 // location is the macro invocation, which the offset has nothing to do
900 // with. This is unlike when we get the spelling loc, because the offset
901 // directly correspond to the token whose spelling we're inspecting.
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000902 Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
Chris Lattner659ac5f2009-01-26 20:04:19 +0000903 } while (!Loc.isFileID());
904
905 return Loc;
906}
907
908SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
909 do {
910 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000911 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000912 Loc = Loc.getLocWithOffset(LocInfo.second);
Chris Lattner659ac5f2009-01-26 20:04:19 +0000913 } while (!Loc.isFileID());
914 return Loc;
915}
916
Argyrios Kyrtzidis7f6b0292011-10-12 07:07:40 +0000917SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
918 do {
919 if (isMacroArgExpansion(Loc))
920 Loc = getImmediateSpellingLoc(Loc);
921 else
922 Loc = getImmediateExpansionRange(Loc).first;
923 } while (!Loc.isFileID());
924 return Loc;
925}
926
Chris Lattner659ac5f2009-01-26 20:04:19 +0000927
Chris Lattner4fa23622009-01-26 00:43:02 +0000928std::pair<FileID, unsigned>
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000929SourceManager::getDecomposedExpansionLocSlowCase(
Argyrios Kyrtzidisc8f7e212011-07-07 03:40:27 +0000930 const SrcMgr::SLocEntry *E) const {
Chandler Carruth64ee7822011-07-26 05:17:23 +0000931 // If this is an expansion record, walk through all the expansion points.
Chris Lattner4fa23622009-01-26 00:43:02 +0000932 FileID FID;
933 SourceLocation Loc;
Argyrios Kyrtzidisc8f7e212011-07-07 03:40:27 +0000934 unsigned Offset;
Chris Lattner4fa23622009-01-26 00:43:02 +0000935 do {
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000936 Loc = E->getExpansion().getExpansionLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000937
Chris Lattner4fa23622009-01-26 00:43:02 +0000938 FID = getFileID(Loc);
939 E = &getSLocEntry(FID);
Argyrios Kyrtzidisc8f7e212011-07-07 03:40:27 +0000940 Offset = Loc.getOffset()-E->getOffset();
Chris Lattner31af4e02009-01-26 19:41:58 +0000941 } while (!Loc.isFileID());
Mike Stump11289f42009-09-09 15:08:12 +0000942
Chris Lattner4fa23622009-01-26 00:43:02 +0000943 return std::make_pair(FID, Offset);
944}
945
946std::pair<FileID, unsigned>
947SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
948 unsigned Offset) const {
Chandler Carruth64ee7822011-07-26 05:17:23 +0000949 // If this is an expansion record, walk through all the expansion points.
Chris Lattner31af4e02009-01-26 19:41:58 +0000950 FileID FID;
951 SourceLocation Loc;
952 do {
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000953 Loc = E->getExpansion().getSpellingLoc();
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000954 Loc = Loc.getLocWithOffset(Offset);
Mike Stump11289f42009-09-09 15:08:12 +0000955
Chris Lattner31af4e02009-01-26 19:41:58 +0000956 FID = getFileID(Loc);
957 E = &getSLocEntry(FID);
Argyrios Kyrtzidis2797df62011-08-23 21:02:41 +0000958 Offset = Loc.getOffset()-E->getOffset();
Chris Lattner31af4e02009-01-26 19:41:58 +0000959 } while (!Loc.isFileID());
Mike Stump11289f42009-09-09 15:08:12 +0000960
Chris Lattner4fa23622009-01-26 00:43:02 +0000961 return std::make_pair(FID, Offset);
962}
963
Chris Lattner8ad52d52009-02-17 08:04:48 +0000964/// getImmediateSpellingLoc - Given a SourceLocation object, return the
965/// spelling location referenced by the ID. This is the first level down
966/// towards the place where the characters that make up the lexed token can be
967/// found. This should not generally be used by clients.
968SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
969 if (Loc.isFileID()) return Loc;
970 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000971 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000972 return Loc.getLocWithOffset(LocInfo.second);
Chris Lattner8ad52d52009-02-17 08:04:48 +0000973}
974
975
Chandler Carruth64ee7822011-07-26 05:17:23 +0000976/// getImmediateExpansionRange - Loc is required to be an expansion location.
977/// Return the start/end of the expansion information.
Chris Lattner9dc9c202009-02-15 20:52:18 +0000978std::pair<SourceLocation,SourceLocation>
Chandler Carruthca757582011-07-25 20:52:21 +0000979SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
Chandler Carruth64ee7822011-07-26 05:17:23 +0000980 assert(Loc.isMacroID() && "Not a macro expansion loc!");
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000981 const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000982 return Expansion.getExpansionLocRange();
Chris Lattner9dc9c202009-02-15 20:52:18 +0000983}
984
Chandler Carruth6d28d7f2011-07-25 16:56:02 +0000985/// getExpansionRange - Given a SourceLocation object, return the range of
986/// tokens covered by the expansion in the ultimate file.
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000987std::pair<SourceLocation,SourceLocation>
Chandler Carruth6d28d7f2011-07-25 16:56:02 +0000988SourceManager::getExpansionRange(SourceLocation Loc) const {
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000989 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000990
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000991 std::pair<SourceLocation,SourceLocation> Res =
Chandler Carruthca757582011-07-25 20:52:21 +0000992 getImmediateExpansionRange(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000993
Chandler Carruth64ee7822011-07-26 05:17:23 +0000994 // Fully resolve the start and end locations to their ultimate expansion
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000995 // points.
996 while (!Res.first.isFileID())
Chandler Carruthca757582011-07-25 20:52:21 +0000997 Res.first = getImmediateExpansionRange(Res.first).first;
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000998 while (!Res.second.isFileID())
Chandler Carruthca757582011-07-25 20:52:21 +0000999 Res.second = getImmediateExpansionRange(Res.second).second;
Chris Lattnerf52c0b22009-02-15 21:26:50 +00001000 return Res;
1001}
1002
Chandler Carruthaa631532011-07-26 03:03:00 +00001003bool SourceManager::isMacroArgExpansion(SourceLocation Loc) const {
Chandler Carruth402bb382011-07-07 23:56:36 +00001004 if (!Loc.isMacroID()) return false;
1005
1006 FileID FID = getFileID(Loc);
Matt Beaumont-Gayb1e71a72013-01-12 00:54:16 +00001007 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
Chandler Carruth73ee5d72011-07-26 04:41:47 +00001008 return Expansion.isMacroArgExpansion();
Chandler Carruth402bb382011-07-07 23:56:36 +00001009}
Chris Lattner9dc9c202009-02-15 20:52:18 +00001010
Matt Beaumont-Gayb1e71a72013-01-12 00:54:16 +00001011bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const {
1012 if (!Loc.isMacroID()) return false;
1013
1014 FileID FID = getFileID(Loc);
1015 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1016 return Expansion.isMacroBodyExpansion();
1017}
1018
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +00001019bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
1020 SourceLocation *MacroBegin) const {
1021 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1022
1023 std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);
1024 if (DecompLoc.second > 0)
1025 return false; // Does not point at the start of expansion range.
1026
1027 bool Invalid = false;
1028 const SrcMgr::ExpansionInfo &ExpInfo =
1029 getSLocEntry(DecompLoc.first, &Invalid).getExpansion();
1030 if (Invalid)
1031 return false;
1032 SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();
1033
1034 if (ExpInfo.isMacroArgExpansion()) {
1035 // For macro argument expansions, check if the previous FileID is part of
1036 // the same argument expansion, in which case this Loc is not at the
1037 // beginning of the expansion.
1038 FileID PrevFID = getPreviousFileID(DecompLoc.first);
1039 if (!PrevFID.isInvalid()) {
1040 const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);
1041 if (Invalid)
1042 return false;
1043 if (PrevEntry.isExpansion() &&
1044 PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)
1045 return false;
1046 }
1047 }
1048
1049 if (MacroBegin)
1050 *MacroBegin = ExpLoc;
1051 return true;
1052}
1053
1054bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
1055 SourceLocation *MacroEnd) const {
1056 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1057
1058 FileID FID = getFileID(Loc);
1059 SourceLocation NextLoc = Loc.getLocWithOffset(1);
1060 if (isInFileID(NextLoc, FID))
1061 return false; // Does not point at the end of expansion range.
1062
1063 bool Invalid = false;
1064 const SrcMgr::ExpansionInfo &ExpInfo =
1065 getSLocEntry(FID, &Invalid).getExpansion();
1066 if (Invalid)
1067 return false;
1068
1069 if (ExpInfo.isMacroArgExpansion()) {
1070 // For macro argument expansions, check if the next FileID is part of the
1071 // same argument expansion, in which case this Loc is not at the end of the
1072 // expansion.
1073 FileID NextFID = getNextFileID(FID);
1074 if (!NextFID.isInvalid()) {
1075 const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);
1076 if (Invalid)
1077 return false;
1078 if (NextEntry.isExpansion() &&
1079 NextEntry.getExpansion().getExpansionLocStart() ==
1080 ExpInfo.getExpansionLocStart())
1081 return false;
1082 }
1083 }
1084
1085 if (MacroEnd)
1086 *MacroEnd = ExpInfo.getExpansionLocEnd();
1087 return true;
1088}
1089
Chris Lattner4fa23622009-01-26 00:43:02 +00001090
1091//===----------------------------------------------------------------------===//
1092// Queries about the code at a SourceLocation.
1093//===----------------------------------------------------------------------===//
Chris Lattner30709b032006-06-21 03:01:55 +00001094
Chris Lattnerd01e2912006-06-18 16:22:51 +00001095/// getCharacterData - Return a pointer to the start of the specified location
Chris Lattner739e7392007-04-29 07:12:06 +00001096/// in the appropriate MemoryBuffer.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001097const char *SourceManager::getCharacterData(SourceLocation SL,
1098 bool *Invalid) const {
Chris Lattnerd3a15f72006-07-04 23:01:03 +00001099 // Note that this is a hot function in the getSpelling() path, which is
1100 // heavily used by -E mode.
Chris Lattner4fa23622009-01-26 00:43:02 +00001101 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump11289f42009-09-09 15:08:12 +00001102
Ted Kremenek12c2af42009-01-06 01:55:26 +00001103 // Note that calling 'getBuffer()' may lazily page in a source file.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001104 bool CharDataInvalid = false;
Douglas Gregor49f754f2011-04-20 00:21:03 +00001105 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
1106 if (CharDataInvalid || !Entry.isFile()) {
1107 if (Invalid)
1108 *Invalid = true;
1109
1110 return "<<<<INVALID BUFFER>>>>";
1111 }
David Blaikie66cc07b2014-06-27 17:40:03 +00001112 llvm::MemoryBuffer *Buffer = Entry.getFile().getContentCache()->getBuffer(
1113 Diag, *this, SourceLocation(), &CharDataInvalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001114 if (Invalid)
1115 *Invalid = CharDataInvalid;
1116 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
Chris Lattnerd01e2912006-06-18 16:22:51 +00001117}
1118
Chris Lattner685730f2006-06-26 01:36:22 +00001119
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001120/// getColumnNumber - Return the column # for the specified file position.
Chris Lattnere4ad4172009-02-04 00:55:58 +00001121/// this is significantly cheaper to compute than the line number.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001122unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
1123 bool *Invalid) const {
1124 bool MyInvalid = false;
David Blaikie66cc07b2014-06-27 17:40:03 +00001125 llvm::MemoryBuffer *MemBuf = getBuffer(FID, &MyInvalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001126 if (Invalid)
1127 *Invalid = MyInvalid;
1128
1129 if (MyInvalid)
1130 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00001131
Jordan Rose8d63d5b2012-06-19 03:09:38 +00001132 // It is okay to request a position just past the end of the buffer.
1133 if (FilePos > MemBuf->getBufferSize()) {
Argyrios Kyrtzidis6c8d29f2011-12-10 00:30:38 +00001134 if (Invalid)
Jordan Rose8d63d5b2012-06-19 03:09:38 +00001135 *Invalid = true;
Argyrios Kyrtzidis6c8d29f2011-12-10 00:30:38 +00001136 return 1;
1137 }
1138
Craig Topper5e79ee02012-10-19 04:40:38 +00001139 // See if we just calculated the line number for this FilePos and can use
1140 // that to lookup the start of the line instead of searching for it.
1141 if (LastLineNoFileIDQuery == FID &&
Craig Topperf1186c52014-05-08 06:41:40 +00001142 LastLineNoContentCache->SourceLineCache != nullptr &&
Craig Topperf3b839b2012-12-16 05:58:32 +00001143 LastLineNoResult < LastLineNoContentCache->NumLines) {
Craig Topper5e79ee02012-10-19 04:40:38 +00001144 unsigned *SourceLineCache = LastLineNoContentCache->SourceLineCache;
1145 unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
1146 unsigned LineEnd = SourceLineCache[LastLineNoResult];
1147 if (FilePos >= LineStart && FilePos < LineEnd)
1148 return FilePos - LineStart + 1;
1149 }
1150
Dylan Noblesmith2a8bc152011-12-19 08:51:05 +00001151 const char *Buf = MemBuf->getBufferStart();
Chris Lattner22eb9722006-06-18 05:43:12 +00001152 unsigned LineStart = FilePos;
1153 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
1154 --LineStart;
1155 return FilePos-LineStart+1;
1156}
1157
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001158// isInvalid - Return the result of calling loc.isInvalid(), and
1159// if Invalid is not null, set its value to same.
1160static bool isInvalid(SourceLocation Loc, bool *Invalid) {
1161 bool MyInvalid = Loc.isInvalid();
1162 if (Invalid)
1163 *Invalid = MyInvalid;
1164 return MyInvalid;
1165}
1166
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001167unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
1168 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001169 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattnere4ad4172009-02-04 00:55:58 +00001170 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001171 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattnere4ad4172009-02-04 00:55:58 +00001172}
1173
Chandler Carruth42f35f92011-07-25 20:57:57 +00001174unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
1175 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001176 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001177 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001178 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattnere4ad4172009-02-04 00:55:58 +00001179}
1180
Chandler Carruth1aef0c52011-02-23 00:47:48 +00001181unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
1182 bool *Invalid) const {
1183 if (isInvalid(Loc, Invalid)) return 0;
1184 return getPresumedLoc(Loc).getColumn();
1185}
1186
Benjamin Kramer543036a2012-04-06 20:49:55 +00001187#ifdef __SSE2__
1188#include <emmintrin.h>
1189#endif
1190
Chandler Carruthc3ce5842010-10-23 08:44:57 +00001191static LLVM_ATTRIBUTE_NOINLINE void
David Blaikie9c902b52011-09-25 23:23:43 +00001192ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001193 llvm::BumpPtrAllocator &Alloc,
1194 const SourceManager &SM, bool &Invalid);
David Blaikie9c902b52011-09-25 23:23:43 +00001195static void ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001196 llvm::BumpPtrAllocator &Alloc,
1197 const SourceManager &SM, bool &Invalid) {
Ted Kremenek12c2af42009-01-06 01:55:26 +00001198 // Note that calling 'getBuffer()' may lazily page in the file.
David Blaikie66cc07b2014-06-27 17:40:03 +00001199 MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(), &Invalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001200 if (Invalid)
1201 return;
Mike Stump11289f42009-09-09 15:08:12 +00001202
Chris Lattner8996fff2007-07-24 05:57:19 +00001203 // Find the file offsets of all of the *physical* source lines. This does
1204 // not look at trigraphs, escaped newlines, or anything else tricky.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001205 SmallVector<unsigned, 256> LineOffsets;
Mike Stump11289f42009-09-09 15:08:12 +00001206
Chris Lattner8996fff2007-07-24 05:57:19 +00001207 // Line #1 starts at char 0.
1208 LineOffsets.push_back(0);
Mike Stump11289f42009-09-09 15:08:12 +00001209
Chris Lattner8996fff2007-07-24 05:57:19 +00001210 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
1211 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
1212 unsigned Offs = 0;
1213 while (1) {
1214 // Skip over the contents of the line.
Chris Lattner8996fff2007-07-24 05:57:19 +00001215 const unsigned char *NextBuf = (const unsigned char *)Buf;
Benjamin Kramer543036a2012-04-06 20:49:55 +00001216
1217#ifdef __SSE2__
1218 // Try to skip to the next newline using SSE instructions. This is very
1219 // performance sensitive for programs with lots of diagnostics and in -E
1220 // mode.
1221 __m128i CRs = _mm_set1_epi8('\r');
1222 __m128i LFs = _mm_set1_epi8('\n');
1223
1224 // First fix up the alignment to 16 bytes.
1225 while (((uintptr_t)NextBuf & 0xF) != 0) {
1226 if (*NextBuf == '\n' || *NextBuf == '\r' || *NextBuf == '\0')
1227 goto FoundSpecialChar;
1228 ++NextBuf;
1229 }
1230
1231 // Scan 16 byte chunks for '\r' and '\n'. Ignore '\0'.
1232 while (NextBuf+16 <= End) {
Roman Divackye6377112012-09-06 15:59:27 +00001233 const __m128i Chunk = *(const __m128i*)NextBuf;
Benjamin Kramer543036a2012-04-06 20:49:55 +00001234 __m128i Cmp = _mm_or_si128(_mm_cmpeq_epi8(Chunk, CRs),
1235 _mm_cmpeq_epi8(Chunk, LFs));
1236 unsigned Mask = _mm_movemask_epi8(Cmp);
1237
1238 // If we found a newline, adjust the pointer and jump to the handling code.
1239 if (Mask != 0) {
Michael J. Spencer8c398402013-05-24 21:42:04 +00001240 NextBuf += llvm::countTrailingZeros(Mask);
Benjamin Kramer543036a2012-04-06 20:49:55 +00001241 goto FoundSpecialChar;
1242 }
1243 NextBuf += 16;
1244 }
1245#endif
1246
Chris Lattner8996fff2007-07-24 05:57:19 +00001247 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
1248 ++NextBuf;
Benjamin Kramer543036a2012-04-06 20:49:55 +00001249
1250#ifdef __SSE2__
1251FoundSpecialChar:
1252#endif
Chris Lattner8996fff2007-07-24 05:57:19 +00001253 Offs += NextBuf-Buf;
1254 Buf = NextBuf;
Mike Stump11289f42009-09-09 15:08:12 +00001255
Chris Lattner8996fff2007-07-24 05:57:19 +00001256 if (Buf[0] == '\n' || Buf[0] == '\r') {
1257 // If this is \n\r or \r\n, skip both characters.
1258 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
1259 ++Offs, ++Buf;
1260 ++Offs, ++Buf;
1261 LineOffsets.push_back(Offs);
1262 } else {
1263 // Otherwise, this is a null. If end of file, exit.
1264 if (Buf == End) break;
1265 // Otherwise, skip the null.
1266 ++Offs, ++Buf;
1267 }
1268 }
Mike Stump11289f42009-09-09 15:08:12 +00001269
Chris Lattner8996fff2007-07-24 05:57:19 +00001270 // Copy the offsets into the FileInfo structure.
1271 FI->NumLines = LineOffsets.size();
Chris Lattnerc8233df2009-02-03 07:30:45 +00001272 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner8996fff2007-07-24 05:57:19 +00001273 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
1274}
Chris Lattner9a13bde2006-06-21 04:57:09 +00001275
Chris Lattner53e384f2009-01-16 07:00:02 +00001276/// getLineNumber - Given a SourceLocation, return the spelling line number
Chris Lattner22eb9722006-06-18 05:43:12 +00001277/// for the position indicated. This requires building and caching a table of
Chris Lattner739e7392007-04-29 07:12:06 +00001278/// line offsets for the MemoryBuffer, so this is not cheap: use only when
Chris Lattner22eb9722006-06-18 05:43:12 +00001279/// about to emit a diagnostic.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001280unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1281 bool *Invalid) const {
Argyrios Kyrtzidisf15eac12011-05-17 22:09:53 +00001282 if (FID.isInvalid()) {
1283 if (Invalid)
1284 *Invalid = true;
1285 return 1;
1286 }
1287
Chris Lattnerd32480d2009-01-17 06:22:33 +00001288 ContentCache *Content;
Chris Lattner88ea93e2009-02-04 01:06:56 +00001289 if (LastLineNoFileIDQuery == FID)
Ted Kremenekc08bca62007-10-30 21:08:08 +00001290 Content = LastLineNoContentCache;
Douglas Gregor49f754f2011-04-20 00:21:03 +00001291 else {
1292 bool MyInvalid = false;
1293 const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1294 if (MyInvalid || !Entry.isFile()) {
1295 if (Invalid)
1296 *Invalid = true;
1297 return 1;
1298 }
1299
1300 Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
1301 }
1302
Chris Lattner22eb9722006-06-18 05:43:12 +00001303 // If this is the first use of line information for this buffer, compute the
Chris Lattner8996fff2007-07-24 05:57:19 +00001304 /// SourceLineCache for it on demand.
Craig Topperf1186c52014-05-08 06:41:40 +00001305 if (!Content->SourceLineCache) {
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001306 bool MyInvalid = false;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001307 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001308 if (Invalid)
1309 *Invalid = MyInvalid;
1310 if (MyInvalid)
1311 return 1;
1312 } else if (Invalid)
1313 *Invalid = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001314
1315 // Okay, we know we have a line number table. Do a binary search to find the
1316 // line number that this character position lands on.
Ted Kremenekc08bca62007-10-30 21:08:08 +00001317 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner8996fff2007-07-24 05:57:19 +00001318 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenekc08bca62007-10-30 21:08:08 +00001319 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump11289f42009-09-09 15:08:12 +00001320
Chris Lattner88ea93e2009-02-04 01:06:56 +00001321 unsigned QueriedFilePos = FilePos+1;
Chris Lattner8996fff2007-07-24 05:57:19 +00001322
Daniel Dunbar70f924df82009-05-18 17:30:52 +00001323 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump11289f42009-09-09 15:08:12 +00001324 // complicated as it is, binary search isn't that slow.
Daniel Dunbar70f924df82009-05-18 17:30:52 +00001325 //
1326 // If it is worth being optimized, then in my opinion it could be more
1327 // performant, simpler, and more obviously correct by just "galloping" outward
1328 // from the queried file position. In fact, this could be incorporated into a
1329 // generic algorithm such as lower_bound_with_hint.
1330 //
1331 // If someone gives me a test case where this matters, and I will do it! - DWD
1332
Chris Lattner8996fff2007-07-24 05:57:19 +00001333 // If the previous query was to the same file, we know both the file pos from
1334 // that query and the line number returned. This allows us to narrow the
1335 // search space from the entire file to something near the match.
Chris Lattner88ea93e2009-02-04 01:06:56 +00001336 if (LastLineNoFileIDQuery == FID) {
Chris Lattner8996fff2007-07-24 05:57:19 +00001337 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar70f924df82009-05-18 17:30:52 +00001338 // FIXME: Potential overflow?
Chris Lattner8996fff2007-07-24 05:57:19 +00001339 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump11289f42009-09-09 15:08:12 +00001340
Chris Lattner8996fff2007-07-24 05:57:19 +00001341 // The query is likely to be nearby the previous one. Here we check to
1342 // see if it is within 5, 10 or 20 lines. It can be far away in cases
1343 // where big comment blocks and vertical whitespace eat up lines but
1344 // contribute no tokens.
1345 if (SourceLineCache+5 < SourceLineCacheEnd) {
1346 if (SourceLineCache[5] > QueriedFilePos)
1347 SourceLineCacheEnd = SourceLineCache+5;
1348 else if (SourceLineCache+10 < SourceLineCacheEnd) {
1349 if (SourceLineCache[10] > QueriedFilePos)
1350 SourceLineCacheEnd = SourceLineCache+10;
1351 else if (SourceLineCache+20 < SourceLineCacheEnd) {
1352 if (SourceLineCache[20] > QueriedFilePos)
1353 SourceLineCacheEnd = SourceLineCache+20;
1354 }
1355 }
1356 }
1357 } else {
Daniel Dunbar70f924df82009-05-18 17:30:52 +00001358 if (LastLineNoResult < Content->NumLines)
1359 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner8996fff2007-07-24 05:57:19 +00001360 }
1361 }
Mike Stump11289f42009-09-09 15:08:12 +00001362
Chris Lattner830a77f2007-07-24 06:43:46 +00001363 unsigned *Pos
1364 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner8996fff2007-07-24 05:57:19 +00001365 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump11289f42009-09-09 15:08:12 +00001366
Chris Lattner88ea93e2009-02-04 01:06:56 +00001367 LastLineNoFileIDQuery = FID;
Ted Kremenekc08bca62007-10-30 21:08:08 +00001368 LastLineNoContentCache = Content;
Chris Lattner8996fff2007-07-24 05:57:19 +00001369 LastLineNoFilePos = QueriedFilePos;
1370 LastLineNoResult = LineNo;
1371 return LineNo;
Chris Lattner22eb9722006-06-18 05:43:12 +00001372}
1373
Chandler Carruth1aef0c52011-02-23 00:47:48 +00001374unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1375 bool *Invalid) const {
1376 if (isInvalid(Loc, Invalid)) return 0;
1377 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1378 return getLineNumber(LocInfo.first, LocInfo.second);
1379}
Chandler Carruthd48db212011-07-25 21:09:52 +00001380unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
1381 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001382 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001383 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Chris Lattner88ea93e2009-02-04 01:06:56 +00001384 return getLineNumber(LocInfo.first, LocInfo.second);
1385}
Chandler Carruth1aef0c52011-02-23 00:47:48 +00001386unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001387 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001388 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruth1aef0c52011-02-23 00:47:48 +00001389 return getPresumedLoc(Loc).getLine();
Chris Lattner88ea93e2009-02-04 01:06:56 +00001390}
1391
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001392/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump11289f42009-09-09 15:08:12 +00001393/// source location, indicating whether this is a normal file, a system
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001394/// header, or an "implicit extern C" system header.
1395///
1396/// This state can be modified with flags on GNU linemarker directives like:
1397/// # 4 "foo.h" 3
1398/// which changes all source locations in the current file after that to be
1399/// considered to be from a system header.
Mike Stump11289f42009-09-09 15:08:12 +00001400SrcMgr::CharacteristicKind
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001401SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1402 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001403 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregor49f754f2011-04-20 00:21:03 +00001404 bool Invalid = false;
1405 const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
1406 if (Invalid || !SEntry.isFile())
1407 return C_User;
1408
1409 const SrcMgr::FileInfo &FI = SEntry.getFile();
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001410
1411 // If there are no #line directives in this file, just return the whole-file
1412 // state.
1413 if (!FI.hasLineDirectives())
1414 return FI.getFileCharacteristic();
Mike Stump11289f42009-09-09 15:08:12 +00001415
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001416 assert(LineTable && "Can't have linetable entries without a LineTable!");
1417 // See if there is a #line directive before the location.
1418 const LineEntry *Entry =
Douglas Gregor02c2dbf2012-06-08 16:40:28 +00001419 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
Mike Stump11289f42009-09-09 15:08:12 +00001420
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001421 // If this is before the first line marker, use the file characteristic.
1422 if (!Entry)
1423 return FI.getFileCharacteristic();
1424
1425 return Entry->FileKind;
1426}
1427
Chris Lattnera6f037c2009-02-17 08:39:06 +00001428/// Return the filename or buffer identifier of the buffer the location is in.
James Dennett87a2acf2012-06-17 03:22:59 +00001429/// Note that this name does not respect \#line directives. Use getPresumedLoc
Chris Lattnera6f037c2009-02-17 08:39:06 +00001430/// for normal clients.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001431const char *SourceManager::getBufferName(SourceLocation Loc,
1432 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001433 if (isInvalid(Loc, Invalid)) return "<invalid loc>";
Mike Stump11289f42009-09-09 15:08:12 +00001434
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001435 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
Chris Lattnera6f037c2009-02-17 08:39:06 +00001436}
1437
Chris Lattner88ea93e2009-02-04 01:06:56 +00001438
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001439/// getPresumedLoc - This method returns the "presumed" location of a
James Dennett87a2acf2012-06-17 03:22:59 +00001440/// SourceLocation specifies. A "presumed location" can be modified by \#line
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001441/// or GNU line marker directives. This provides a view on the data that a
1442/// user should see in diagnostics, for example.
1443///
Chandler Carruth64ee7822011-07-26 05:17:23 +00001444/// Note that a presumed location is always given as the expansion point of an
1445/// expansion location, not at the spelling location.
Richard Smith0b50cb72012-11-14 23:55:25 +00001446PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc,
1447 bool UseLineDirectives) const {
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001448 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001449
Chandler Carruth64ee7822011-07-26 05:17:23 +00001450 // Presumed locations are always for expansion points.
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001451 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +00001452
Douglas Gregor49f754f2011-04-20 00:21:03 +00001453 bool Invalid = false;
1454 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1455 if (Invalid || !Entry.isFile())
1456 return PresumedLoc();
1457
1458 const SrcMgr::FileInfo &FI = Entry.getFile();
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001459 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump11289f42009-09-09 15:08:12 +00001460
Chris Lattnerd4293922009-02-04 01:55:42 +00001461 // To get the source name, first consult the FileEntry (if one exists)
1462 // before the MemBuffer as this will avoid unnecessarily paging in the
1463 // MemBuffer.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001464 const char *Filename;
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001465 if (C->OrigEntry)
1466 Filename = C->OrigEntry->getName();
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001467 else
1468 Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
Douglas Gregor49f754f2011-04-20 00:21:03 +00001469
Douglas Gregor75f26d62010-11-02 00:39:22 +00001470 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1471 if (Invalid)
1472 return PresumedLoc();
1473 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1474 if (Invalid)
1475 return PresumedLoc();
1476
Chris Lattnerd4293922009-02-04 01:55:42 +00001477 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001478
Chris Lattnerd4293922009-02-04 01:55:42 +00001479 // If we have #line directives in this file, update and overwrite the physical
1480 // location info if appropriate.
Richard Smith0b50cb72012-11-14 23:55:25 +00001481 if (UseLineDirectives && FI.hasLineDirectives()) {
Chris Lattnerd4293922009-02-04 01:55:42 +00001482 assert(LineTable && "Can't have linetable entries without a LineTable!");
1483 // See if there is a #line directive before this. If so, get it.
1484 if (const LineEntry *Entry =
Douglas Gregor02c2dbf2012-06-08 16:40:28 +00001485 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
Chris Lattnerc1219ff2009-02-04 02:00:59 +00001486 // If the LineEntry indicates a filename, use it.
Chris Lattnerd4293922009-02-04 01:55:42 +00001487 if (Entry->FilenameID != -1)
1488 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerc1219ff2009-02-04 02:00:59 +00001489
1490 // Use the line number specified by the LineEntry. This line number may
1491 // be multiple lines down from the line entry. Add the difference in
1492 // physical line numbers from the query point and the line marker to the
1493 // total.
1494 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1495 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump11289f42009-09-09 15:08:12 +00001496
Chris Lattner20c50ba2009-02-04 02:15:40 +00001497 // Note that column numbers are not molested by line markers.
Mike Stump11289f42009-09-09 15:08:12 +00001498
Chris Lattner1c967782009-02-04 06:25:26 +00001499 // Handle virtual #include manipulation.
1500 if (Entry->IncludeOffset) {
1501 IncludeLoc = getLocForStartOfFile(LocInfo.first);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001502 IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
Chris Lattner1c967782009-02-04 06:25:26 +00001503 }
Chris Lattnerd4293922009-02-04 01:55:42 +00001504 }
1505 }
1506
1507 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattner4fa23622009-01-26 00:43:02 +00001508}
1509
Benjamin Kramere7800df2013-09-27 17:12:50 +00001510/// \brief Returns whether the PresumedLoc for a given SourceLocation is
1511/// in the main file.
1512///
1513/// This computes the "presumed" location for a SourceLocation, then checks
1514/// whether it came from a file other than the main file. This is different
1515/// from isWrittenInMainFile() because it takes line marker directives into
1516/// account.
1517bool SourceManager::isInMainFile(SourceLocation Loc) const {
1518 if (Loc.isInvalid()) return false;
1519
1520 // Presumed locations are always for expansion points.
1521 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1522
1523 bool Invalid = false;
1524 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1525 if (Invalid || !Entry.isFile())
1526 return false;
1527
1528 const SrcMgr::FileInfo &FI = Entry.getFile();
1529
1530 // Check if there is a line directive for this location.
1531 if (FI.hasLineDirectives())
1532 if (const LineEntry *Entry =
1533 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
1534 if (Entry->IncludeOffset)
1535 return false;
1536
1537 return FI.getIncludeLoc().isInvalid();
1538}
1539
James Dennettaa61cbb2013-11-24 01:47:49 +00001540/// \brief The size of the SLocEntry that \p FID represents.
Argyrios Kyrtzidis296374b52011-08-23 21:02:28 +00001541unsigned SourceManager::getFileIDSize(FileID FID) const {
1542 bool Invalid = false;
1543 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1544 if (Invalid)
1545 return 0;
1546
1547 int ID = FID.ID;
1548 unsigned NextOffset;
1549 if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
1550 NextOffset = getNextLocalOffset();
1551 else if (ID+1 == -1)
1552 NextOffset = MaxLoadedOffset;
1553 else
1554 NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
1555
1556 return NextOffset - Entry.getOffset() - 1;
1557}
1558
Chris Lattner4fa23622009-01-26 00:43:02 +00001559//===----------------------------------------------------------------------===//
1560// Other miscellaneous methods.
1561//===----------------------------------------------------------------------===//
1562
Douglas Gregore6642762011-02-03 17:17:35 +00001563/// \brief Retrieve the inode for the given file entry, if possible.
1564///
1565/// This routine involves a system call, and therefore should only be used
1566/// in non-performance-critical code.
Rafael Espindola073ff102013-07-29 21:26:52 +00001567static Optional<llvm::sys::fs::UniqueID>
1568getActualFileUID(const FileEntry *File) {
Douglas Gregore6642762011-02-03 17:17:35 +00001569 if (!File)
David Blaikie7a30dc52013-02-21 01:47:18 +00001570 return None;
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001571
Rafael Espindola073ff102013-07-29 21:26:52 +00001572 llvm::sys::fs::UniqueID ID;
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001573 if (llvm::sys::fs::getUniqueID(File->getName(), ID))
David Blaikie7a30dc52013-02-21 01:47:18 +00001574 return None;
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001575
1576 return ID;
Douglas Gregore6642762011-02-03 17:17:35 +00001577}
1578
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001579/// \brief Get the source location for the given file:line:col triplet.
1580///
1581/// If the source file is included multiple times, the source location will
Douglas Gregor925296b2011-07-19 16:10:42 +00001582/// be based upon an arbitrary inclusion.
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001583SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001584 unsigned Line,
1585 unsigned Col) const {
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001586 assert(SourceFile && "Null source file!");
1587 assert(Line && Col && "Line and column should start from 1!");
1588
Argyrios Kyrtzidis04a6e5f2011-09-27 17:22:25 +00001589 FileID FirstFID = translateFile(SourceFile);
1590 return translateLineCol(FirstFID, Line, Col);
1591}
1592
1593/// \brief Get the FileID for the given file.
1594///
1595/// If the source file is included multiple times, the FileID will be the
1596/// first inclusion.
1597FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
1598 assert(SourceFile && "Null source file!");
1599
Douglas Gregore6642762011-02-03 17:17:35 +00001600 // Find the first file ID that corresponds to the given file.
1601 FileID FirstFID;
Mike Stump11289f42009-09-09 15:08:12 +00001602
Douglas Gregore6642762011-02-03 17:17:35 +00001603 // First, check the main file ID, since it is common to look for a
1604 // location in the main file.
Rafael Espindola073ff102013-07-29 21:26:52 +00001605 Optional<llvm::sys::fs::UniqueID> SourceFileUID;
David Blaikie05785d12013-02-20 22:23:23 +00001606 Optional<StringRef> SourceFileName;
Douglas Gregore6642762011-02-03 17:17:35 +00001607 if (!MainFileID.isInvalid()) {
Douglas Gregor49f754f2011-04-20 00:21:03 +00001608 bool Invalid = false;
1609 const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1610 if (Invalid)
Argyrios Kyrtzidis04a6e5f2011-09-27 17:22:25 +00001611 return FileID();
Douglas Gregor49f754f2011-04-20 00:21:03 +00001612
Douglas Gregore6642762011-02-03 17:17:35 +00001613 if (MainSLoc.isFile()) {
1614 const ContentCache *MainContentCache
1615 = MainSLoc.getFile().getContentCache();
Douglas Gregor6a5be932011-02-11 18:08:15 +00001616 if (!MainContentCache) {
1617 // Can't do anything
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001618 } else if (MainContentCache->OrigEntry == SourceFile) {
Douglas Gregore6642762011-02-03 17:17:35 +00001619 FirstFID = MainFileID;
Douglas Gregor6a5be932011-02-11 18:08:15 +00001620 } else {
Douglas Gregore6642762011-02-03 17:17:35 +00001621 // Fall back: check whether we have the same base name and inode
1622 // as the main file.
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001623 const FileEntry *MainFile = MainContentCache->OrigEntry;
Douglas Gregore6642762011-02-03 17:17:35 +00001624 SourceFileName = llvm::sys::path::filename(SourceFile->getName());
1625 if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) {
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001626 SourceFileUID = getActualFileUID(SourceFile);
1627 if (SourceFileUID) {
Rafael Espindola073ff102013-07-29 21:26:52 +00001628 if (Optional<llvm::sys::fs::UniqueID> MainFileUID =
1629 getActualFileUID(MainFile)) {
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001630 if (*SourceFileUID == *MainFileUID) {
Douglas Gregord766be62011-02-16 19:09:24 +00001631 FirstFID = MainFileID;
1632 SourceFile = MainFile;
1633 }
1634 }
Douglas Gregore6642762011-02-03 17:17:35 +00001635 }
1636 }
1637 }
1638 }
1639 }
1640
1641 if (FirstFID.isInvalid()) {
1642 // The location we're looking for isn't in the main file; look
Douglas Gregor925296b2011-07-19 16:10:42 +00001643 // through all of the local source locations.
1644 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
Douglas Gregor49f754f2011-04-20 00:21:03 +00001645 bool Invalid = false;
Douglas Gregor925296b2011-07-19 16:10:42 +00001646 const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid);
Douglas Gregor49f754f2011-04-20 00:21:03 +00001647 if (Invalid)
Argyrios Kyrtzidis04a6e5f2011-09-27 17:22:25 +00001648 return FileID();
Douglas Gregor49f754f2011-04-20 00:21:03 +00001649
Douglas Gregore6642762011-02-03 17:17:35 +00001650 if (SLoc.isFile() &&
1651 SLoc.getFile().getContentCache() &&
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001652 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
Douglas Gregore6642762011-02-03 17:17:35 +00001653 FirstFID = FileID::get(I);
1654 break;
1655 }
1656 }
Douglas Gregor925296b2011-07-19 16:10:42 +00001657 // If that still didn't help, try the modules.
1658 if (FirstFID.isInvalid()) {
1659 for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
1660 const SLocEntry &SLoc = getLoadedSLocEntry(I);
1661 if (SLoc.isFile() &&
1662 SLoc.getFile().getContentCache() &&
1663 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1664 FirstFID = FileID::get(-int(I) - 2);
1665 break;
1666 }
1667 }
1668 }
Douglas Gregore6642762011-02-03 17:17:35 +00001669 }
1670
1671 // If we haven't found what we want yet, try again, but this time stat()
1672 // each of the files in case the files have changed since we originally
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001673 // parsed the file.
Douglas Gregore6642762011-02-03 17:17:35 +00001674 if (FirstFID.isInvalid() &&
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001675 (SourceFileName ||
Douglas Gregore6642762011-02-03 17:17:35 +00001676 (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) &&
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001677 (SourceFileUID || (SourceFileUID = getActualFileUID(SourceFile)))) {
Douglas Gregor49f754f2011-04-20 00:21:03 +00001678 bool Invalid = false;
Douglas Gregor925296b2011-07-19 16:10:42 +00001679 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1680 FileID IFileID;
1681 IFileID.ID = I;
1682 const SLocEntry &SLoc = getSLocEntry(IFileID, &Invalid);
Douglas Gregor49f754f2011-04-20 00:21:03 +00001683 if (Invalid)
Argyrios Kyrtzidis04a6e5f2011-09-27 17:22:25 +00001684 return FileID();
Douglas Gregor49f754f2011-04-20 00:21:03 +00001685
Douglas Gregore6642762011-02-03 17:17:35 +00001686 if (SLoc.isFile()) {
1687 const ContentCache *FileContentCache
1688 = SLoc.getFile().getContentCache();
Craig Topperf1186c52014-05-08 06:41:40 +00001689 const FileEntry *Entry = FileContentCache ? FileContentCache->OrigEntry
1690 : nullptr;
Douglas Gregore6642762011-02-03 17:17:35 +00001691 if (Entry &&
Douglas Gregor6a5be932011-02-11 18:08:15 +00001692 *SourceFileName == llvm::sys::path::filename(Entry->getName())) {
Rafael Espindola073ff102013-07-29 21:26:52 +00001693 if (Optional<llvm::sys::fs::UniqueID> EntryUID =
1694 getActualFileUID(Entry)) {
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001695 if (*SourceFileUID == *EntryUID) {
Douglas Gregor6a5be932011-02-11 18:08:15 +00001696 FirstFID = FileID::get(I);
1697 SourceFile = Entry;
1698 break;
1699 }
1700 }
Douglas Gregore6642762011-02-03 17:17:35 +00001701 }
1702 }
1703 }
1704 }
Argyrios Kyrtzidis04a6e5f2011-09-27 17:22:25 +00001705
Ted Kremenekbd1d7fa2012-10-12 22:56:33 +00001706 (void) SourceFile;
Argyrios Kyrtzidis04a6e5f2011-09-27 17:22:25 +00001707 return FirstFID;
Argyrios Kyrtzidis532c5192011-09-19 20:40:29 +00001708}
1709
1710/// \brief Get the source location in \arg FID for the given line:col.
1711/// Returns null location if \arg FID is not a file SLocEntry.
1712SourceLocation SourceManager::translateLineCol(FileID FID,
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001713 unsigned Line,
1714 unsigned Col) const {
Aaron Ballmanef1cf832013-11-18 18:29:00 +00001715 // Lines are used as a one-based index into a zero-based array. This assert
1716 // checks for possible buffer underruns.
1717 assert(Line != 0 && "Passed a zero-based line");
1718
Argyrios Kyrtzidis532c5192011-09-19 20:40:29 +00001719 if (FID.isInvalid())
1720 return SourceLocation();
1721
1722 bool Invalid = false;
1723 const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1724 if (Invalid)
1725 return SourceLocation();
Alexander Kornienko6d8cf832013-07-29 22:26:10 +00001726
Argyrios Kyrtzidis532c5192011-09-19 20:40:29 +00001727 if (!Entry.isFile())
Douglas Gregore6642762011-02-03 17:17:35 +00001728 return SourceLocation();
1729
Argyrios Kyrtzidis7c2b28a2011-09-20 22:14:54 +00001730 SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
1731
Douglas Gregore6642762011-02-03 17:17:35 +00001732 if (Line == 1 && Col == 1)
Argyrios Kyrtzidis7c2b28a2011-09-20 22:14:54 +00001733 return FileLoc;
Douglas Gregore6642762011-02-03 17:17:35 +00001734
1735 ContentCache *Content
Argyrios Kyrtzidis532c5192011-09-19 20:40:29 +00001736 = const_cast<ContentCache *>(Entry.getFile().getContentCache());
Douglas Gregore6642762011-02-03 17:17:35 +00001737 if (!Content)
1738 return SourceLocation();
Alexander Kornienko6d8cf832013-07-29 22:26:10 +00001739
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001740 // If this is the first use of line information for this buffer, compute the
Douglas Gregor925296b2011-07-19 16:10:42 +00001741 // SourceLineCache for it on demand.
Craig Topperf1186c52014-05-08 06:41:40 +00001742 if (!Content->SourceLineCache) {
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001743 bool MyInvalid = false;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001744 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001745 if (MyInvalid)
1746 return SourceLocation();
1747 }
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001748
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001749 if (Line > Content->NumLines) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001750 unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001751 if (Size > 0)
1752 --Size;
Argyrios Kyrtzidis7c2b28a2011-09-20 22:14:54 +00001753 return FileLoc.getLocWithOffset(Size);
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001754 }
1755
David Blaikie66cc07b2014-06-27 17:40:03 +00001756 llvm::MemoryBuffer *Buffer = Content->getBuffer(Diag, *this);
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001757 unsigned FilePos = Content->SourceLineCache[Line - 1];
Dylan Noblesmith2a8bc152011-12-19 08:51:05 +00001758 const char *Buf = Buffer->getBufferStart() + FilePos;
1759 unsigned BufLength = Buffer->getBufferSize() - FilePos;
Argyrios Kyrtzidis7c2b28a2011-09-20 22:14:54 +00001760 if (BufLength == 0)
1761 return FileLoc.getLocWithOffset(FilePos);
1762
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001763 unsigned i = 0;
1764
1765 // Check that the given column is valid.
1766 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1767 ++i;
Alexander Kornienko6d8cf832013-07-29 22:26:10 +00001768 return FileLoc.getLocWithOffset(FilePos + i);
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001769}
1770
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001771/// \brief Compute a map of macro argument chunks to their expanded source
1772/// location. Chunks that are not part of a macro argument will map to an
1773/// invalid source location. e.g. if a file contains one macro argument at
1774/// offset 100 with length 10, this is how the map will be formed:
1775/// 0 -> SourceLocation()
1776/// 100 -> Expanded macro arg location
1777/// 110 -> SourceLocation()
Argyrios Kyrtzidis4bdd6aa2011-09-26 08:01:50 +00001778void SourceManager::computeMacroArgsCache(MacroArgsMap *&CachePtr,
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001779 FileID FID) const {
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001780 assert(!FID.isInvalid());
Argyrios Kyrtzidis4bdd6aa2011-09-26 08:01:50 +00001781 assert(!CachePtr);
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001782
Argyrios Kyrtzidis4bdd6aa2011-09-26 08:01:50 +00001783 CachePtr = new MacroArgsMap();
1784 MacroArgsMap &MacroArgsCache = *CachePtr;
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001785 // Initially no macro argument chunk is present.
1786 MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
1787
1788 int ID = FID.ID;
1789 while (1) {
1790 ++ID;
1791 // Stop if there are no more FileIDs to check.
1792 if (ID > 0) {
1793 if (unsigned(ID) >= local_sloc_entry_size())
1794 return;
1795 } else if (ID == -1) {
1796 return;
1797 }
1798
Argyrios Kyrtzidisfe683022013-06-07 17:57:59 +00001799 bool Invalid = false;
1800 const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);
1801 if (Invalid)
1802 return;
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001803 if (Entry.isFile()) {
1804 SourceLocation IncludeLoc = Entry.getFile().getIncludeLoc();
1805 if (IncludeLoc.isInvalid())
1806 continue;
1807 if (!isInFileID(IncludeLoc, FID))
1808 return; // No more files/macros that may be "contained" in this file.
1809
1810 // Skip the files/macros of the #include'd file, we only care about macros
1811 // that lexed macro arguments from our file.
1812 if (Entry.getFile().NumCreatedFIDs)
1813 ID += Entry.getFile().NumCreatedFIDs - 1/*because of next ++ID*/;
1814 continue;
1815 }
1816
Argyrios Kyrtzidise841c902011-12-21 16:56:35 +00001817 const ExpansionInfo &ExpInfo = Entry.getExpansion();
1818
1819 if (ExpInfo.getExpansionLocStart().isFileID()) {
1820 if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
1821 return; // No more files/macros that may be "contained" in this file.
1822 }
1823
1824 if (!ExpInfo.isMacroArgExpansion())
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001825 continue;
Argyrios Kyrtzidise841c902011-12-21 16:56:35 +00001826
Argyrios Kyrtzidis73ccdb92012-10-20 00:51:32 +00001827 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1828 ExpInfo.getSpellingLoc(),
1829 SourceLocation::getMacroLoc(Entry.getOffset()),
1830 getFileIDSize(FileID::get(ID)));
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001831 }
1832}
1833
Argyrios Kyrtzidis73ccdb92012-10-20 00:51:32 +00001834void SourceManager::associateFileChunkWithMacroArgExp(
1835 MacroArgsMap &MacroArgsCache,
1836 FileID FID,
1837 SourceLocation SpellLoc,
1838 SourceLocation ExpansionLoc,
1839 unsigned ExpansionLength) const {
1840 if (!SpellLoc.isFileID()) {
1841 unsigned SpellBeginOffs = SpellLoc.getOffset();
1842 unsigned SpellEndOffs = SpellBeginOffs + ExpansionLength;
1843
1844 // The spelling range for this macro argument expansion can span multiple
1845 // consecutive FileID entries. Go through each entry contained in the
1846 // spelling range and if one is itself a macro argument expansion, recurse
1847 // and associate the file chunk that it represents.
1848
1849 FileID SpellFID; // Current FileID in the spelling range.
1850 unsigned SpellRelativeOffs;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001851 std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);
Argyrios Kyrtzidis73ccdb92012-10-20 00:51:32 +00001852 while (1) {
1853 const SLocEntry &Entry = getSLocEntry(SpellFID);
1854 unsigned SpellFIDBeginOffs = Entry.getOffset();
1855 unsigned SpellFIDSize = getFileIDSize(SpellFID);
1856 unsigned SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;
1857 const ExpansionInfo &Info = Entry.getExpansion();
1858 if (Info.isMacroArgExpansion()) {
1859 unsigned CurrSpellLength;
1860 if (SpellFIDEndOffs < SpellEndOffs)
1861 CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
1862 else
1863 CurrSpellLength = ExpansionLength;
1864 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1865 Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),
1866 ExpansionLoc, CurrSpellLength);
1867 }
1868
1869 if (SpellFIDEndOffs >= SpellEndOffs)
1870 return; // we covered all FileID entries in the spelling range.
1871
1872 // Move to the next FileID entry in the spelling range.
1873 unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
1874 ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);
1875 ExpansionLength -= advance;
1876 ++SpellFID.ID;
1877 SpellRelativeOffs = 0;
1878 }
1879
1880 }
1881
1882 assert(SpellLoc.isFileID());
1883
1884 unsigned BeginOffs;
1885 if (!isInFileID(SpellLoc, FID, &BeginOffs))
1886 return;
1887
1888 unsigned EndOffs = BeginOffs + ExpansionLength;
1889
1890 // Add a new chunk for this macro argument. A previous macro argument chunk
1891 // may have been lexed again, so e.g. if the map is
1892 // 0 -> SourceLocation()
1893 // 100 -> Expanded loc #1
1894 // 110 -> SourceLocation()
1895 // and we found a new macro FileID that lexed from offet 105 with length 3,
1896 // the new map will be:
1897 // 0 -> SourceLocation()
1898 // 100 -> Expanded loc #1
1899 // 105 -> Expanded loc #2
1900 // 108 -> Expanded loc #1
1901 // 110 -> SourceLocation()
1902 //
1903 // Since re-lexed macro chunks will always be the same size or less of
1904 // previous chunks, we only need to find where the ending of the new macro
1905 // chunk is mapped to and update the map with new begin/end mappings.
1906
1907 MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
1908 --I;
1909 SourceLocation EndOffsMappedLoc = I->second;
1910 MacroArgsCache[BeginOffs] = ExpansionLoc;
1911 MacroArgsCache[EndOffs] = EndOffsMappedLoc;
1912}
1913
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001914/// \brief If \arg Loc points inside a function macro argument, the returned
1915/// location will be the macro location in which the argument was expanded.
1916/// If a macro argument is used multiple times, the expanded location will
1917/// be at the first expansion of the argument.
1918/// e.g.
1919/// MY_MACRO(foo);
1920/// ^
1921/// Passing a file location pointing at 'foo', will yield a macro location
1922/// where 'foo' was expanded into.
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001923SourceLocation
1924SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001925 if (Loc.isInvalid() || !Loc.isFileID())
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001926 return Loc;
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001927
1928 FileID FID;
1929 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001930 std::tie(FID, Offset) = getDecomposedLoc(Loc);
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001931 if (FID.isInvalid())
1932 return Loc;
1933
Argyrios Kyrtzidis4bdd6aa2011-09-26 08:01:50 +00001934 MacroArgsMap *&MacroArgsCache = MacroArgsCacheMap[FID];
1935 if (!MacroArgsCache)
1936 computeMacroArgsCache(MacroArgsCache, FID);
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001937
Argyrios Kyrtzidis4bdd6aa2011-09-26 08:01:50 +00001938 assert(!MacroArgsCache->empty());
1939 MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001940 --I;
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001941
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001942 unsigned MacroArgBeginOffs = I->first;
1943 SourceLocation MacroArgExpandedLoc = I->second;
1944 if (MacroArgExpandedLoc.isValid())
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001945 return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001946
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001947 return Loc;
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001948}
1949
Argyrios Kyrtzidis37613a92013-04-13 01:03:57 +00001950std::pair<FileID, unsigned>
1951SourceManager::getDecomposedIncludedLoc(FileID FID) const {
Argyrios Kyrtzidis5dca8642013-05-24 22:24:04 +00001952 if (FID.isInvalid())
1953 return std::make_pair(FileID(), 0);
1954
Argyrios Kyrtzidis37613a92013-04-13 01:03:57 +00001955 // Uses IncludedLocMap to retrieve/cache the decomposed loc.
1956
1957 typedef std::pair<FileID, unsigned> DecompTy;
1958 typedef llvm::DenseMap<FileID, DecompTy> MapTy;
1959 std::pair<MapTy::iterator, bool>
1960 InsertOp = IncludedLocMap.insert(std::make_pair(FID, DecompTy()));
1961 DecompTy &DecompLoc = InsertOp.first->second;
1962 if (!InsertOp.second)
1963 return DecompLoc; // already in map.
1964
1965 SourceLocation UpperLoc;
Argyrios Kyrtzidis5dca8642013-05-24 22:24:04 +00001966 bool Invalid = false;
1967 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1968 if (!Invalid) {
1969 if (Entry.isExpansion())
1970 UpperLoc = Entry.getExpansion().getExpansionLocStart();
1971 else
1972 UpperLoc = Entry.getFile().getIncludeLoc();
1973 }
Argyrios Kyrtzidis37613a92013-04-13 01:03:57 +00001974
1975 if (UpperLoc.isValid())
1976 DecompLoc = getDecomposedLoc(UpperLoc);
1977
1978 return DecompLoc;
1979}
1980
Chandler Carruth64ee7822011-07-26 05:17:23 +00001981/// Given a decomposed source location, move it up the include/expansion stack
1982/// to the parent source location. If this is possible, return the decomposed
1983/// version of the parent in Loc and return false. If Loc is the top-level
1984/// entry, return true and don't modify it.
Chris Lattnera99fa1a2010-05-07 20:35:24 +00001985static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1986 const SourceManager &SM) {
Argyrios Kyrtzidis37613a92013-04-13 01:03:57 +00001987 std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
1988 if (UpperLoc.first.isInvalid())
Chris Lattnera99fa1a2010-05-07 20:35:24 +00001989 return true; // We reached the top.
Argyrios Kyrtzidis37613a92013-04-13 01:03:57 +00001990
1991 Loc = UpperLoc;
Chris Lattnera99fa1a2010-05-07 20:35:24 +00001992 return false;
1993}
Ted Kremenek08037042013-02-27 00:00:26 +00001994
1995/// Return the cache entry for comparing the given file IDs
1996/// for isBeforeInTranslationUnit.
1997InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
1998 FileID RFID) const {
1999 // This is a magic number for limiting the cache size. It was experimentally
2000 // derived from a small Objective-C project (where the cache filled
2001 // out to ~250 items). We can make it larger if necessary.
2002 enum { MagicCacheSize = 300 };
2003 IsBeforeInTUCacheKey Key(LFID, RFID);
2004
2005 // If the cache size isn't too large, do a lookup and if necessary default
2006 // construct an entry. We can then return it to the caller for direct
2007 // use. When they update the value, the cache will get automatically
2008 // updated as well.
2009 if (IBTUCache.size() < MagicCacheSize)
2010 return IBTUCache[Key];
2011
2012 // Otherwise, do a lookup that will not construct a new value.
2013 InBeforeInTUCache::iterator I = IBTUCache.find(Key);
2014 if (I != IBTUCache.end())
2015 return I->second;
2016
2017 // Fall back to the overflow value.
2018 return IBTUCacheOverflow;
2019}
Chris Lattnera99fa1a2010-05-07 20:35:24 +00002020
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00002021/// \brief Determines the order of 2 source locations in the translation unit.
2022///
2023/// \returns true if LHS source location comes before RHS, false otherwise.
2024bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
2025 SourceLocation RHS) const {
2026 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
2027 if (LHS == RHS)
2028 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002029
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00002030 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
2031 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00002032
Argyrios Kyrtzidis5fd822c2013-05-24 23:47:43 +00002033 // getDecomposedLoc may have failed to return a valid FileID because, e.g. it
2034 // is a serialized one referring to a file that was removed after we loaded
2035 // the PCH.
Argyrios Kyrtzidis5dca8642013-05-24 22:24:04 +00002036 if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
Argyrios Kyrtzidisd6111d32013-05-25 01:03:03 +00002037 return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
Argyrios Kyrtzidis5dca8642013-05-24 22:24:04 +00002038
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00002039 // If the source locations are in the same file, just compare offsets.
2040 if (LOffs.first == ROffs.first)
2041 return LOffs.second < ROffs.second;
2042
2043 // If we are comparing a source location with multiple locations in the same
2044 // file, we get a big win by caching the result.
Ted Kremenek08037042013-02-27 00:00:26 +00002045 InBeforeInTUCacheEntry &IsBeforeInTUCache =
2046 getInBeforeInTUCache(LOffs.first, ROffs.first);
2047
2048 // If we are comparing a source location with multiple locations in the same
2049 // file, we get a big win by caching the result.
Chris Lattner46e3b482010-05-07 05:10:46 +00002050 if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
2051 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Mike Stump11289f42009-09-09 15:08:12 +00002052
Chris Lattner66d2f922010-05-07 01:17:07 +00002053 // Okay, we missed in the cache, start updating the cache for this query.
Argyrios Kyrtzidisac199bf2011-08-17 00:31:18 +00002054 IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
2055 /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID);
Mike Stump11289f42009-09-09 15:08:12 +00002056
Douglas Gregor925296b2011-07-19 16:10:42 +00002057 // We need to find the common ancestor. The only way of doing this is to
2058 // build the complete include chain for one and then walking up the chain
2059 // of the other looking for a match.
2060 // We use a map from FileID to Offset to store the chain. Easier than writing
2061 // a custom set hash info that only depends on the first part of a pair.
Argyrios Kyrtzidis37613a92013-04-13 01:03:57 +00002062 typedef llvm::SmallDenseMap<FileID, unsigned, 16> LocSet;
Douglas Gregor925296b2011-07-19 16:10:42 +00002063 LocSet LChain;
Chris Lattner06821c92010-05-07 05:51:13 +00002064 do {
Douglas Gregor925296b2011-07-19 16:10:42 +00002065 LChain.insert(LOffs);
2066 // We catch the case where LOffs is in a file included by ROffs and
2067 // quit early. The other way round unfortunately remains suboptimal.
2068 } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
2069 LocSet::iterator I;
2070 while((I = LChain.find(ROffs.first)) == LChain.end()) {
2071 if (MoveUpIncludeHierarchy(ROffs, *this))
2072 break; // Met at topmost file.
2073 }
2074 if (I != LChain.end())
2075 LOffs = *I;
Mike Stump11289f42009-09-09 15:08:12 +00002076
Chris Lattner06821c92010-05-07 05:51:13 +00002077 // If we exited because we found a nearest common ancestor, compare the
2078 // locations within the common file and cache them.
2079 if (LOffs.first == ROffs.first) {
2080 IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
2081 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00002082 }
Mike Stump11289f42009-09-09 15:08:12 +00002083
Douglas Gregor925296b2011-07-19 16:10:42 +00002084 // This can happen if a location is in a built-ins buffer.
2085 // But see PR5662.
2086 // Clear the lookup cache, it depends on a common location.
Argyrios Kyrtzidisac199bf2011-08-17 00:31:18 +00002087 IsBeforeInTUCache.clear();
Douglas Gregor925296b2011-07-19 16:10:42 +00002088 bool LIsBuiltins = strcmp("<built-in>",
2089 getBuffer(LOffs.first)->getBufferIdentifier()) == 0;
2090 bool RIsBuiltins = strcmp("<built-in>",
2091 getBuffer(ROffs.first)->getBufferIdentifier()) == 0;
2092 // built-in is before non-built-in
2093 if (LIsBuiltins != RIsBuiltins)
2094 return LIsBuiltins;
2095 assert(LIsBuiltins && RIsBuiltins &&
2096 "Non-built-in locations must be rooted in the main file");
2097 // Both are in built-in buffers, but from different files. We just claim that
2098 // lower IDs come first.
Chris Lattner66d2f922010-05-07 01:17:07 +00002099 return LOffs.first < ROffs.first;
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00002100}
Chris Lattner4fa23622009-01-26 00:43:02 +00002101
Chris Lattner22eb9722006-06-18 05:43:12 +00002102void SourceManager::PrintStats() const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +00002103 llvm::errs() << "\n*** Source Manager Stats:\n";
2104 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
2105 << " mem buffers mapped.\n";
Douglas Gregor925296b2011-07-19 16:10:42 +00002106 llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
Ted Kremenek43e0c4a2011-07-27 18:41:16 +00002107 << llvm::capacity_in_bytes(LocalSLocEntryTable)
Argyrios Kyrtzidis2cc62092011-07-07 03:40:24 +00002108 << " bytes of capacity), "
Douglas Gregor925296b2011-07-19 16:10:42 +00002109 << NextLocalOffset << "B of Sloc address space used.\n";
2110 llvm::errs() << LoadedSLocEntryTable.size()
2111 << " loaded SLocEntries allocated, "
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00002112 << MaxLoadedOffset - CurrentLoadedOffset
Douglas Gregor925296b2011-07-19 16:10:42 +00002113 << "B of Sloc address space used.\n";
2114
Chris Lattner22eb9722006-06-18 05:43:12 +00002115 unsigned NumLineNumsComputed = 0;
2116 unsigned NumFileBytesMapped = 0;
Chris Lattnerc8233df2009-02-03 07:30:45 +00002117 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
Craig Topperf1186c52014-05-08 06:41:40 +00002118 NumLineNumsComputed += I->second->SourceLineCache != nullptr;
Chris Lattnerc8233df2009-02-03 07:30:45 +00002119 NumFileBytesMapped += I->second->getSizeBytesMapped();
Chris Lattner22eb9722006-06-18 05:43:12 +00002120 }
Argyrios Kyrtzidis4bdd6aa2011-09-26 08:01:50 +00002121 unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
Mike Stump11289f42009-09-09 15:08:12 +00002122
Benjamin Kramer89b422c2009-08-23 12:08:50 +00002123 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00002124 << NumLineNumsComputed << " files with line #'s computed, "
2125 << NumMacroArgsComputed << " files with macro args computed.\n";
Benjamin Kramer89b422c2009-08-23 12:08:50 +00002126 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
2127 << NumBinaryProbes << " binary.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +00002128}
Douglas Gregor258ae542009-04-27 06:38:32 +00002129
2130ExternalSLocEntrySource::~ExternalSLocEntrySource() { }
Ted Kremenek8d587902011-04-28 20:36:42 +00002131
2132/// Return the amount of memory used by memory buffers, breaking down
2133/// by heap-backed versus mmap'ed memory.
2134SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
2135 size_t malloc_bytes = 0;
2136 size_t mmap_bytes = 0;
2137
2138 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
2139 if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
2140 switch (MemBufferInfos[i]->getMemoryBufferKind()) {
2141 case llvm::MemoryBuffer::MemoryBuffer_MMap:
2142 mmap_bytes += sized_mapped;
2143 break;
2144 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
2145 malloc_bytes += sized_mapped;
2146 break;
2147 }
2148
2149 return MemoryBufferSizes(malloc_bytes, mmap_bytes);
2150}
2151
Ted Kremenek120992a2011-07-26 23:46:06 +00002152size_t SourceManager::getDataStructureSizes() const {
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +00002153 size_t size = llvm::capacity_in_bytes(MemBufferInfos)
Ted Kremenek43e0c4a2011-07-27 18:41:16 +00002154 + llvm::capacity_in_bytes(LocalSLocEntryTable)
2155 + llvm::capacity_in_bytes(LoadedSLocEntryTable)
2156 + llvm::capacity_in_bytes(SLocEntryLoaded)
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +00002157 + llvm::capacity_in_bytes(FileInfos);
2158
2159 if (OverriddenFilesInfo)
2160 size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);
2161
2162 return size;
Ted Kremenek120992a2011-07-26 23:46:06 +00002163}