blob: fc4c6d3038012bb0fd49002d04a090a22bdca97b [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>
Douglas Gregor802b7762010-03-15 22:54:52 +000028
Chris Lattner22eb9722006-06-18 05:43:12 +000029using namespace clang;
Chris Lattner5f4b1ff2006-06-20 05:02:40 +000030using namespace SrcMgr;
Chris Lattner23b7eb62007-06-15 23:05:46 +000031using llvm::MemoryBuffer;
Chris Lattner22eb9722006-06-18 05:43:12 +000032
Chris Lattner153a0f12009-02-04 00:40:31 +000033//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +000034// SourceManager Helper Classes
Chris Lattner153a0f12009-02-04 00:40:31 +000035//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +000036
Ted Kremenekc08bca62007-10-30 21:08:08 +000037ContentCache::~ContentCache() {
Douglas Gregor3f4bea02010-07-26 21:36:20 +000038 if (shouldFreeBuffer())
39 delete Buffer.getPointer();
Chris Lattner22eb9722006-06-18 05:43:12 +000040}
41
Chandler Carruth64ee7822011-07-26 05:17:23 +000042/// getSizeBytesMapped - Returns the number of bytes actually mapped for this
43/// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
Ted Kremenek12c2af42009-01-06 01:55:26 +000044unsigned ContentCache::getSizeBytesMapped() const {
Douglas Gregor82752ec2010-03-16 22:53:51 +000045 return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
Ted Kremenek12c2af42009-01-06 01:55:26 +000046}
47
Ted Kremenek8d587902011-04-28 20:36:42 +000048/// Returns the kind of memory used to back the memory buffer for
49/// this content cache. This is used for performance analysis.
50llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
51 assert(Buffer.getPointer());
52
53 // Should be unreachable, but keep for sanity.
54 if (!Buffer.getPointer())
55 return llvm::MemoryBuffer::MemoryBuffer_Malloc;
David Blaikie66cc07b2014-06-27 17:40:03 +000056
57 llvm::MemoryBuffer *buf = Buffer.getPointer();
Ted Kremenek8d587902011-04-28 20:36:42 +000058 return buf->getBufferKind();
59}
60
Ted Kremenek12c2af42009-01-06 01:55:26 +000061/// getSize - Returns the size of the content encapsulated by this ContentCache.
62/// This can be the size of the source file or the size of an arbitrary
63/// scratch buffer. If the ContentCache encapsulates a source file, that
Douglas Gregor53ad6b92009-12-02 06:49:09 +000064/// file is not lazily brought in from disk to satisfy this query.
Ted Kremenek12c2af42009-01-06 01:55:26 +000065unsigned ContentCache::getSize() const {
Douglas Gregor82752ec2010-03-16 22:53:51 +000066 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +000067 : (unsigned) ContentsEntry->getSize();
Ted Kremenek12c2af42009-01-06 01:55:26 +000068}
69
David Blaikie66cc07b2014-06-27 17:40:03 +000070void ContentCache::replaceBuffer(llvm::MemoryBuffer *B, bool DoNotFree) {
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +000071 if (B && B == Buffer.getPointer()) {
Argyrios Kyrtzidiscc6107d2011-12-10 01:38:26 +000072 assert(0 && "Replacing with the same buffer");
73 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
74 return;
75 }
Richard Smithf878a842017-06-05 22:05:31 +000076
Douglas Gregor3f4bea02010-07-26 21:36:20 +000077 if (shouldFreeBuffer())
78 delete Buffer.getPointer();
Douglas Gregor82752ec2010-03-16 22:53:51 +000079 Buffer.setPointer(B);
Richard Smithf878a842017-06-05 22:05:31 +000080 Buffer.setInt((B && DoNotFree) ? DoNotFreeFlag : 0);
Douglas Gregor53ad6b92009-12-02 06:49:09 +000081}
82
David Blaikie66cc07b2014-06-27 17:40:03 +000083llvm::MemoryBuffer *ContentCache::getBuffer(DiagnosticsEngine &Diag,
84 const SourceManager &SM,
85 SourceLocation Loc,
86 bool *Invalid) const {
Chris Lattner5631b052010-11-23 08:50:03 +000087 // Lazily create the Buffer for ContentCaches that wrap files. If we already
Chris Lattner57540c52011-04-15 05:22:18 +000088 // computed it, just return what we have.
Craig Topperf1186c52014-05-08 06:41:40 +000089 if (Buffer.getPointer() || !ContentsEntry) {
Chris Lattner5631b052010-11-23 08:50:03 +000090 if (Invalid)
91 *Invalid = isBufferInvalid();
Chris Lattner8fbe98b2010-04-20 18:14:03 +000092
Chris Lattner5631b052010-11-23 08:50:03 +000093 return Buffer.getPointer();
94 }
Benjamin Kramer5a3f1cf2010-11-18 12:46:39 +000095
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +000096 bool isVolatile = SM.userFilesAreVolatile() && !IsSystemFile;
Benjamin Kramera8857962014-10-26 22:44:13 +000097 auto BufferOrError =
98 SM.getFileManager().getBufferForFile(ContentsEntry, isVolatile);
Chris Lattner5631b052010-11-23 08:50:03 +000099
100 // If we were unable to open the file, then we are in an inconsistent
101 // situation where the content cache referenced a file which no longer
102 // exists. Most likely, we were using a stat cache with an invalid entry but
103 // the file could also have been removed during processing. Since we can't
104 // really deal with this situation, just create an empty buffer.
105 //
106 // FIXME: This is definitely not ideal, but our immediate clients can't
107 // currently handle returning a null entry here. Ideally we should detect
108 // that we are in an inconsistent situation and error out as quickly as
109 // possible.
Benjamin Kramera8857962014-10-26 22:44:13 +0000110 if (!BufferOrError) {
Craig Topperbf3e3272014-08-30 16:55:52 +0000111 StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
Benjamin Kramerc7dd5992015-04-06 17:45:11 +0000112 Buffer.setPointer(MemoryBuffer::getNewUninitMemBuffer(
113 ContentsEntry->getSize(), "<invalid>").release());
Chris Lattner5631b052010-11-23 08:50:03 +0000114 char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart());
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000115 for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
Chris Lattner5631b052010-11-23 08:50:03 +0000116 Ptr[i] = FillStr[i % FillStr.size()];
117
118 if (Diag.isDiagnosticInFlight())
Benjamin Kramera8857962014-10-26 22:44:13 +0000119 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
120 ContentsEntry->getName(),
121 BufferOrError.getError().message());
122 else
Chris Lattner5631b052010-11-23 08:50:03 +0000123 Diag.Report(Loc, diag::err_cannot_open_file)
Benjamin Kramera8857962014-10-26 22:44:13 +0000124 << ContentsEntry->getName() << BufferOrError.getError().message();
Chris Lattner5631b052010-11-23 08:50:03 +0000125
126 Buffer.setInt(Buffer.getInt() | InvalidFlag);
127
128 if (Invalid) *Invalid = true;
129 return Buffer.getPointer();
130 }
Benjamin Kramera8857962014-10-26 22:44:13 +0000131
132 Buffer.setPointer(BufferOrError->release());
133
Chris Lattner5631b052010-11-23 08:50:03 +0000134 // 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) {
David Blaikie13156b62014-11-19 03:06:06 +0000179 auto IterBool =
180 FilenameIDs.insert(std::make_pair(Name, FilenamesByID.size()));
181 if (IterBool.second)
182 FilenamesByID.push_back(&*IterBool.first);
183 return IterBool.first->second;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000184}
185
Reid Klecknereb00ee02017-05-22 21:42:58 +0000186/// Add a line note to the line table that indicates that there is a \#line or
187/// GNU line marker at the specified FID/Offset location which changes the
188/// presumed location to LineNo/FilenameID. If EntryExit is 0, then this doesn't
189/// change the presumed \#include stack. If it is 1, this is a file entry, if
190/// it is 2 then this is a file exit. FileKind specifies whether this is a
191/// system header or extern C system header.
192void LineTableInfo::AddLineNote(FileID FID, unsigned Offset, unsigned LineNo,
193 int FilenameID, unsigned EntryExit,
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000194 SrcMgr::CharacteristicKind FileKind) {
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000195 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump11289f42009-09-09 15:08:12 +0000196
Reid Klecknereb00ee02017-05-22 21:42:58 +0000197 // An unspecified FilenameID means use the last filename if available, or the
198 // main source file otherwise.
199 if (FilenameID == -1 && !Entries.empty())
200 FilenameID = Entries.back().FilenameID;
201
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000202 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
203 "Adding line entries out of order!");
204
Chris Lattner1c967782009-02-04 06:25:26 +0000205 unsigned IncludeOffset = 0;
206 if (EntryExit == 0) { // No #include stack change.
207 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
208 } else if (EntryExit == 1) {
209 IncludeOffset = Offset-1;
210 } else if (EntryExit == 2) {
211 assert(!Entries.empty() && Entries.back().IncludeOffset &&
212 "PPDirectives should have caught case when popping empty include stack");
Mike Stump11289f42009-09-09 15:08:12 +0000213
Chris Lattner1c967782009-02-04 06:25:26 +0000214 // Get the include loc of the last entries' include loc as our include loc.
215 IncludeOffset = 0;
216 if (const LineEntry *PrevEntry =
217 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
218 IncludeOffset = PrevEntry->IncludeOffset;
219 }
Mike Stump11289f42009-09-09 15:08:12 +0000220
Chris Lattner1c967782009-02-04 06:25:26 +0000221 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
222 IncludeOffset));
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000223}
224
225
Chris Lattnerd4293922009-02-04 01:55:42 +0000226/// FindNearestLineEntry - Find the line entry nearest to FID that is before
227/// it. If there is no line entry before Offset in FID, return null.
Douglas Gregor02c2dbf2012-06-08 16:40:28 +0000228const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID,
Chris Lattnerd4293922009-02-04 01:55:42 +0000229 unsigned Offset) {
230 const std::vector<LineEntry> &Entries = LineEntries[FID];
231 assert(!Entries.empty() && "No #line entries for this FID after all!");
232
Chris Lattner334a2ad2009-02-04 04:46:59 +0000233 // It is very common for the query to be after the last #line, check this
234 // first.
235 if (Entries.back().FileOffset <= Offset)
236 return &Entries.back();
Chris Lattnerd4293922009-02-04 01:55:42 +0000237
Chris Lattner334a2ad2009-02-04 04:46:59 +0000238 // Do a binary search to find the maximal element that is still before Offset.
239 std::vector<LineEntry>::const_iterator I =
240 std::upper_bound(Entries.begin(), Entries.end(), Offset);
Craig Topperf1186c52014-05-08 06:41:40 +0000241 if (I == Entries.begin()) return nullptr;
Chris Lattner334a2ad2009-02-04 04:46:59 +0000242 return &*--I;
Chris Lattnerd4293922009-02-04 01:55:42 +0000243}
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000244
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000245/// \brief Add a new line entry that has already been encoded into
246/// the internal representation of the line table.
Douglas Gregor02c2dbf2012-06-08 16:40:28 +0000247void LineTableInfo::AddEntry(FileID FID,
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000248 const std::vector<LineEntry> &Entries) {
249 LineEntries[FID] = Entries;
250}
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000251
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000252/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
Mike Stump11289f42009-09-09 15:08:12 +0000253///
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000254unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
Vedant Kumar5eeeab72015-11-12 00:11:19 +0000255 return getLineTable().getLineTableFilenameID(Name);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000256}
257
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000258/// AddLineNote - Add a line note to the line table for the FileID and offset
259/// specified by Loc. If FilenameID is -1, it is considered to be
260/// unspecified.
261void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000262 int FilenameID, bool IsFileEntry,
Reid Klecknereb00ee02017-05-22 21:42:58 +0000263 bool IsFileExit,
264 SrcMgr::CharacteristicKind FileKind) {
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000265 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregor49f754f2011-04-20 00:21:03 +0000266
267 bool Invalid = false;
268 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
269 if (!Entry.isFile() || Invalid)
270 return;
Reid Klecknereb00ee02017-05-22 21:42:58 +0000271
Douglas Gregor49f754f2011-04-20 00:21:03 +0000272 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
Mike Stump11289f42009-09-09 15:08:12 +0000273
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000274 // Remember that this file has #line directives now if it doesn't already.
275 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump11289f42009-09-09 15:08:12 +0000276
Vedant Kumar5eeeab72015-11-12 00:11:19 +0000277 (void) getLineTable();
Mike Stump11289f42009-09-09 15:08:12 +0000278
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000279 unsigned EntryExit = 0;
280 if (IsFileEntry)
281 EntryExit = 1;
282 else if (IsFileExit)
283 EntryExit = 2;
Mike Stump11289f42009-09-09 15:08:12 +0000284
Douglas Gregor02c2dbf2012-06-08 16:40:28 +0000285 LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000286 EntryExit, FileKind);
287}
288
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000289LineTableInfo &SourceManager::getLineTable() {
Craig Topperf1186c52014-05-08 06:41:40 +0000290 if (!LineTable)
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000291 LineTable = new LineTableInfo();
292 return *LineTable;
293}
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000294
Chris Lattner153a0f12009-02-04 00:40:31 +0000295//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +0000296// Private 'Create' methods.
Chris Lattner153a0f12009-02-04 00:40:31 +0000297//===----------------------------------------------------------------------===//
Ted Kremenek12c2af42009-01-06 01:55:26 +0000298
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000299SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
300 bool UserFilesAreVolatile)
Argyrios Kyrtzidis97d3a382011-03-08 23:35:24 +0000301 : Diag(Diag), FileMgr(FileMgr), OverridenFilesKeepOriginalName(true),
Richard Smith919ce232015-11-24 04:22:21 +0000302 UserFilesAreVolatile(UserFilesAreVolatile), FilesAreTransient(false),
Craig Topperf1186c52014-05-08 06:41:40 +0000303 ExternalSLocEntries(nullptr), LineTable(nullptr), NumLinearScans(0),
Rafael Espindolae0f6d882014-08-18 18:33:41 +0000304 NumBinaryProbes(0) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000305 clearIDTables();
306 Diag.setSourceManager(this);
307}
308
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000309SourceManager::~SourceManager() {
310 delete LineTable;
Mike Stump11289f42009-09-09 15:08:12 +0000311
Chris Lattnerc8233df2009-02-03 07:30:45 +0000312 // Delete FileEntry objects corresponding to content caches. Since the actual
313 // content cache objects are bump pointer allocated, we just have to run the
314 // dtors, but we call the deallocate method for completeness.
315 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
Argyrios Kyrtzidisaf41b3f2011-12-15 23:37:55 +0000316 if (MemBufferInfos[i]) {
317 MemBufferInfos[i]->~ContentCache();
318 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
319 }
Chris Lattnerc8233df2009-02-03 07:30:45 +0000320 }
321 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
322 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
Argyrios Kyrtzidisaf41b3f2011-12-15 23:37:55 +0000323 if (I->second) {
324 I->second->~ContentCache();
325 ContentCacheAlloc.Deallocate(I->second);
326 }
Chris Lattnerc8233df2009-02-03 07:30:45 +0000327 }
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000328}
329
330void SourceManager::clearIDTables() {
331 MainFileID = FileID();
Douglas Gregor925296b2011-07-19 16:10:42 +0000332 LocalSLocEntryTable.clear();
333 LoadedSLocEntryTable.clear();
334 SLocEntryLoaded.clear();
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000335 LastLineNoFileIDQuery = FileID();
Craig Topperf1186c52014-05-08 06:41:40 +0000336 LastLineNoContentCache = nullptr;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000337 LastFileIDLookup = FileID();
Mike Stump11289f42009-09-09 15:08:12 +0000338
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000339 if (LineTable)
340 LineTable->clear();
Mike Stump11289f42009-09-09 15:08:12 +0000341
Chandler Carruth64ee7822011-07-26 05:17:23 +0000342 // Use up FileID #0 as an invalid expansion.
Douglas Gregor925296b2011-07-19 16:10:42 +0000343 NextLocalOffset = 0;
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +0000344 CurrentLoadedOffset = MaxLoadedOffset;
Chandler Carruth115b0772011-07-26 03:03:05 +0000345 createExpansionLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000346}
347
Richard Smithab755972017-06-05 18:10:11 +0000348void SourceManager::initializeForReplay(const SourceManager &Old) {
349 assert(MainFileID.isInvalid() && "expected uninitialized SourceManager");
350
351 auto CloneContentCache = [&](const ContentCache *Cache) -> ContentCache * {
352 auto *Clone = new (ContentCacheAlloc.Allocate<ContentCache>()) ContentCache;
353 Clone->OrigEntry = Cache->OrigEntry;
354 Clone->ContentsEntry = Cache->ContentsEntry;
355 Clone->BufferOverridden = Cache->BufferOverridden;
356 Clone->IsSystemFile = Cache->IsSystemFile;
357 Clone->IsTransient = Cache->IsTransient;
358 Clone->replaceBuffer(Cache->getRawBuffer(), /*DoNotFree*/true);
359 return Clone;
360 };
361
362 // Set up our main file ID as a copy of the old source manager's main file.
363 const SLocEntry &OldMainFile = Old.getSLocEntry(Old.getMainFileID());
364 assert(OldMainFile.isFile() && "main file is macro expansion?");
Richard Smithf878a842017-06-05 22:05:31 +0000365 auto *MainCC = CloneContentCache(OldMainFile.getFile().getContentCache());
366 MemBufferInfos.push_back(MainCC);
367 setMainFileID(createFileID(MainCC, SourceLocation(),
368 OldMainFile.getFile().getFileCharacteristic(),
369 0, 0));
Richard Smithab755972017-06-05 18:10:11 +0000370
371 // Ensure all SLocEntries are loaded from the external source.
372 for (unsigned I = 0, N = Old.LoadedSLocEntryTable.size(); I != N; ++I)
373 if (!Old.SLocEntryLoaded[I])
374 Old.loadSLocEntry(I, nullptr);
375
376 // Inherit any content cache data from the old source manager.
377 for (auto &FileInfo : Old.FileInfos) {
378 SrcMgr::ContentCache *&Slot = FileInfos[FileInfo.first];
379 if (Slot)
380 continue;
381 Slot = CloneContentCache(FileInfo.second);
382 }
383}
384
Chris Lattner4fa23622009-01-26 00:43:02 +0000385/// getOrCreateContentCache - Create or return a cached ContentCache for the
386/// specified file.
387const ContentCache *
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000388SourceManager::getOrCreateContentCache(const FileEntry *FileEnt,
389 bool isSystemFile) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000390 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump11289f42009-09-09 15:08:12 +0000391
Chris Lattner22eb9722006-06-18 05:43:12 +0000392 // Do we already have information about this file?
Chris Lattnerc8233df2009-02-03 07:30:45 +0000393 ContentCache *&Entry = FileInfos[FileEnt];
394 if (Entry) return Entry;
Mike Stump11289f42009-09-09 15:08:12 +0000395
Chandler Carruth47c48082014-04-15 21:34:12 +0000396 // Nope, create a new Cache entry.
397 Entry = ContentCacheAlloc.Allocate<ContentCache>();
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000398
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +0000399 if (OverriddenFilesInfo) {
400 // If the file contents are overridden with contents from another file,
401 // pass that file to ContentCache.
402 llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
403 overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
404 if (overI == OverriddenFilesInfo->OverriddenFiles.end())
405 new (Entry) ContentCache(FileEnt);
406 else
407 new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
408 : overI->second,
409 overI->second);
410 } else {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000411 new (Entry) ContentCache(FileEnt);
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +0000412 }
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000413
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000414 Entry->IsSystemFile = isSystemFile;
Richard Smitha8cfffa2015-11-26 02:04:16 +0000415 Entry->IsTransient = FilesAreTransient;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000416
Chris Lattnerc8233df2009-02-03 07:30:45 +0000417 return Entry;
Chris Lattner22eb9722006-06-18 05:43:12 +0000418}
419
420
Ted Kremenek08bed092007-10-31 17:53:38 +0000421/// createMemBufferContentCache - Create a new ContentCache for the specified
422/// memory buffer. This does no caching.
David Blaikie50a5f972014-08-29 07:59:55 +0000423const ContentCache *SourceManager::createMemBufferContentCache(
424 std::unique_ptr<llvm::MemoryBuffer> Buffer) {
Chandler Carruth47c48082014-04-15 21:34:12 +0000425 // Add a new ContentCache to the MemBufferInfos list and return it.
426 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
Chris Lattnerc8233df2009-02-03 07:30:45 +0000427 new (Entry) ContentCache();
428 MemBufferInfos.push_back(Entry);
David Blaikie50a5f972014-08-29 07:59:55 +0000429 Entry->setBuffer(std::move(Buffer));
Chris Lattnerc8233df2009-02-03 07:30:45 +0000430 return Entry;
Chris Lattner22eb9722006-06-18 05:43:12 +0000431}
432
Argyrios Kyrtzidis969fdfd2012-02-20 23:58:07 +0000433const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
434 bool *Invalid) const {
435 assert(!SLocEntryLoaded[Index]);
436 if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
437 if (Invalid)
438 *Invalid = true;
439 // If the file of the SLocEntry changed we could still have loaded it.
440 if (!SLocEntryLoaded[Index]) {
441 // Try to recover; create a SLocEntry so the rest of clang can handle it.
442 LoadedSLocEntryTable[Index] = SLocEntry::get(0,
443 FileInfo::get(SourceLocation(),
444 getFakeContentCacheForRecovery(),
445 SrcMgr::C_User));
446 }
447 }
448
449 return LoadedSLocEntryTable[Index];
450}
451
Douglas Gregor925296b2011-07-19 16:10:42 +0000452std::pair<int, unsigned>
453SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
454 unsigned TotalSize) {
455 assert(ExternalSLocEntries && "Don't have an external sloc source");
Richard Smith78d81ec2015-08-12 22:25:24 +0000456 // Make sure we're not about to run out of source locations.
457 if (CurrentLoadedOffset - TotalSize < NextLocalOffset)
458 return std::make_pair(0, 0);
Douglas Gregor925296b2011-07-19 16:10:42 +0000459 LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
460 SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
461 CurrentLoadedOffset -= TotalSize;
Douglas Gregor925296b2011-07-19 16:10:42 +0000462 int ID = LoadedSLocEntryTable.size();
463 return std::make_pair(-ID - 1, CurrentLoadedOffset);
Douglas Gregor0bc12932009-04-27 21:28:04 +0000464}
465
Douglas Gregor49f754f2011-04-20 00:21:03 +0000466/// \brief As part of recovering from missing or changed content, produce a
467/// fake, non-empty buffer.
David Blaikie66cc07b2014-06-27 17:40:03 +0000468llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const {
Douglas Gregor49f754f2011-04-20 00:21:03 +0000469 if (!FakeBufferForRecovery)
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000470 FakeBufferForRecovery =
471 llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
Rafael Espindolae0f6d882014-08-18 18:33:41 +0000472
473 return FakeBufferForRecovery.get();
Douglas Gregor49f754f2011-04-20 00:21:03 +0000474}
Douglas Gregor258ae542009-04-27 06:38:32 +0000475
Argyrios Kyrtzidis969fdfd2012-02-20 23:58:07 +0000476/// \brief As part of recovering from missing or changed content, produce a
477/// fake content cache.
478const SrcMgr::ContentCache *
479SourceManager::getFakeContentCacheForRecovery() const {
480 if (!FakeContentCacheForRecovery) {
Rafael Espindolae0f6d882014-08-18 18:33:41 +0000481 FakeContentCacheForRecovery = llvm::make_unique<SrcMgr::ContentCache>();
Argyrios Kyrtzidis969fdfd2012-02-20 23:58:07 +0000482 FakeContentCacheForRecovery->replaceBuffer(getFakeBufferForRecovery(),
483 /*DoNotFree=*/true);
484 }
Rafael Espindolae0f6d882014-08-18 18:33:41 +0000485 return FakeContentCacheForRecovery.get();
Argyrios Kyrtzidis969fdfd2012-02-20 23:58:07 +0000486}
487
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000488/// \brief Returns the previous in-order FileID or an invalid FileID if there
489/// is no previous one.
490FileID SourceManager::getPreviousFileID(FileID FID) const {
491 if (FID.isInvalid())
492 return FileID();
493
494 int ID = FID.ID;
495 if (ID == -1)
496 return FileID();
497
498 if (ID > 0) {
499 if (ID-1 == 0)
500 return FileID();
501 } else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {
502 return FileID();
503 }
504
505 return FileID::get(ID-1);
506}
507
508/// \brief Returns the next in-order FileID or an invalid FileID if there is
509/// no next one.
510FileID SourceManager::getNextFileID(FileID FID) const {
511 if (FID.isInvalid())
512 return FileID();
513
514 int ID = FID.ID;
515 if (ID > 0) {
516 if (unsigned(ID+1) >= local_sloc_entry_size())
517 return FileID();
518 } else if (ID+1 >= -1) {
519 return FileID();
520 }
521
522 return FileID::get(ID+1);
523}
524
Chris Lattner4fa23622009-01-26 00:43:02 +0000525//===----------------------------------------------------------------------===//
Chandler Carruth64ee7822011-07-26 05:17:23 +0000526// Methods to create new FileID's and macro expansions.
Chris Lattner4fa23622009-01-26 00:43:02 +0000527//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000528
Dan Gohmance46f022010-08-26 21:27:06 +0000529/// createFileID - Create a new FileID for the specified ContentCache and
Ted Kremeneke26f3c52007-10-30 22:57:35 +0000530/// include position. This works regardless of whether the ContentCache
531/// corresponds to a file or some other input source.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000532FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattner4fa23622009-01-26 00:43:02 +0000533 SourceLocation IncludePos,
Douglas Gregor258ae542009-04-27 06:38:32 +0000534 SrcMgr::CharacteristicKind FileCharacter,
Douglas Gregor925296b2011-07-19 16:10:42 +0000535 int LoadedID, unsigned LoadedOffset) {
536 if (LoadedID < 0) {
537 assert(LoadedID != -1 && "Loading sentinel FileID");
538 unsigned Index = unsigned(-LoadedID) - 2;
539 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
540 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
541 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset,
542 FileInfo::get(IncludePos, File, FileCharacter));
543 SLocEntryLoaded[Index] = true;
544 return FileID::get(LoadedID);
Douglas Gregor258ae542009-04-27 06:38:32 +0000545 }
Douglas Gregor925296b2011-07-19 16:10:42 +0000546 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset,
547 FileInfo::get(IncludePos, File,
548 FileCharacter)));
Ted Kremenek12c2af42009-01-06 01:55:26 +0000549 unsigned FileSize = File->getSize();
Douglas Gregor925296b2011-07-19 16:10:42 +0000550 assert(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
551 NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset &&
552 "Ran out of source locations!");
553 // We do a +1 here because we want a SourceLocation that means "the end of the
554 // file", e.g. for the "no newline at the end of the file" diagnostic.
555 NextLocalOffset += FileSize + 1;
Mike Stump11289f42009-09-09 15:08:12 +0000556
Chris Lattner4fa23622009-01-26 00:43:02 +0000557 // Set LastFileIDLookup to the newly created file. The next getFileID call is
558 // almost guaranteed to be from that file.
Douglas Gregor925296b2011-07-19 16:10:42 +0000559 FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
Argyrios Kyrtzidis0152c6c2009-06-23 00:42:06 +0000560 return LastFileIDLookup = FID;
Chris Lattner22eb9722006-06-18 05:43:12 +0000561}
562
Chandler Carruth402bb382011-07-07 23:56:36 +0000563SourceLocation
Chandler Carruth115b0772011-07-26 03:03:05 +0000564SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc,
565 SourceLocation ExpansionLoc,
566 unsigned TokLength) {
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000567 ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
568 ExpansionLoc);
569 return createExpansionLocImpl(Info, TokLength);
Chandler Carruth402bb382011-07-07 23:56:36 +0000570}
571
572SourceLocation
Chandler Carruth115b0772011-07-26 03:03:05 +0000573SourceManager::createExpansionLoc(SourceLocation SpellingLoc,
574 SourceLocation ExpansionLocStart,
575 SourceLocation ExpansionLocEnd,
576 unsigned TokLength,
577 int LoadedID,
578 unsigned LoadedOffset) {
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000579 ExpansionInfo Info = ExpansionInfo::create(SpellingLoc, ExpansionLocStart,
580 ExpansionLocEnd);
581 return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset);
Chandler Carruth115b0772011-07-26 03:03:05 +0000582}
583
584SourceLocation
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000585SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
Chandler Carruth115b0772011-07-26 03:03:05 +0000586 unsigned TokLength,
587 int LoadedID,
588 unsigned LoadedOffset) {
Douglas Gregor925296b2011-07-19 16:10:42 +0000589 if (LoadedID < 0) {
590 assert(LoadedID != -1 && "Loading sentinel FileID");
591 unsigned Index = unsigned(-LoadedID) - 2;
592 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
593 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000594 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
Douglas Gregor925296b2011-07-19 16:10:42 +0000595 SLocEntryLoaded[Index] = true;
596 return SourceLocation::getMacroLoc(LoadedOffset);
Douglas Gregor258ae542009-04-27 06:38:32 +0000597 }
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000598 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
Douglas Gregor925296b2011-07-19 16:10:42 +0000599 assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&
600 NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&
601 "Ran out of source locations!");
602 // See createFileID for that +1.
603 NextLocalOffset += TokLength + 1;
604 return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
Chris Lattner7d6a4f62006-06-30 06:10:08 +0000605}
606
David Blaikie66cc07b2014-06-27 17:40:03 +0000607llvm::MemoryBuffer *SourceManager::getMemoryBufferForFile(const FileEntry *File,
608 bool *Invalid) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000609 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregor802b7762010-03-15 22:54:52 +0000610 assert(IR && "getOrCreateContentCache() cannot return NULL");
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000611 return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000612}
613
Dan Gohman5d223dc2010-10-26 20:47:28 +0000614void SourceManager::overrideFileContents(const FileEntry *SourceFile,
David Blaikie66cc07b2014-06-27 17:40:03 +0000615 llvm::MemoryBuffer *Buffer,
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000616 bool DoNotFree) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000617 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
Dan Gohman5d223dc2010-10-26 20:47:28 +0000618 assert(IR && "getOrCreateContentCache() cannot return NULL");
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000619
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000620 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
Douglas Gregor9dc32122011-11-16 20:05:18 +0000621 const_cast<SrcMgr::ContentCache *>(IR)->BufferOverridden = true;
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +0000622
623 getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000624}
625
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000626void SourceManager::overrideFileContents(const FileEntry *SourceFile,
627 const FileEntry *NewFile) {
628 assert(SourceFile->getSize() == NewFile->getSize() &&
629 "Different sizes, use the FileManager to create a virtual file with "
630 "the correct size");
631 assert(FileInfos.count(SourceFile) == 0 &&
632 "This function should be called at the initialization stage, before "
633 "any parsing occurs.");
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +0000634 getOverriddenFilesInfo().OverriddenFiles[SourceFile] = NewFile;
635}
636
637void SourceManager::disableFileContentsOverride(const FileEntry *File) {
638 if (!isFileOverridden(File))
639 return;
640
641 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Craig Topperf1186c52014-05-08 06:41:40 +0000642 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(nullptr);
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +0000643 const_cast<SrcMgr::ContentCache *>(IR)->ContentsEntry = IR->OrigEntry;
644
645 assert(OverriddenFilesInfo);
646 OverriddenFilesInfo->OverriddenFiles.erase(File);
647 OverriddenFilesInfo->OverriddenFilesWithBuffer.erase(File);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000648}
649
Richard Smitha8cfffa2015-11-26 02:04:16 +0000650void SourceManager::setFileIsTransient(const FileEntry *File) {
Richard Smithfb1e7f72015-08-14 05:02:58 +0000651 const SrcMgr::ContentCache *CC = getOrCreateContentCache(File);
Richard Smitha8cfffa2015-11-26 02:04:16 +0000652 const_cast<SrcMgr::ContentCache *>(CC)->IsTransient = true;
Richard Smithfb1e7f72015-08-14 05:02:58 +0000653}
654
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000655StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +0000656 bool MyInvalid = false;
Douglas Gregor925296b2011-07-19 16:10:42 +0000657 const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid);
Douglas Gregor49f754f2011-04-20 00:21:03 +0000658 if (!SLoc.isFile() || MyInvalid) {
Douglas Gregor86af9842011-01-31 22:42:36 +0000659 if (Invalid)
660 *Invalid = true;
661 return "<<<<<INVALID SOURCE LOCATION>>>>>";
662 }
David Blaikie66cc07b2014-06-27 17:40:03 +0000663
664 llvm::MemoryBuffer *Buf = SLoc.getFile().getContentCache()->getBuffer(
665 Diag, *this, SourceLocation(), &MyInvalid);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000666 if (Invalid)
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +0000667 *Invalid = MyInvalid;
668
669 if (MyInvalid)
Douglas Gregor86af9842011-01-31 22:42:36 +0000670 return "<<<<<INVALID SOURCE LOCATION>>>>>";
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +0000671
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000672 return Buf->getBuffer();
Douglas Gregor802b7762010-03-15 22:54:52 +0000673}
Chris Lattnerd32480d2009-01-17 06:22:33 +0000674
Chris Lattner153a0f12009-02-04 00:40:31 +0000675//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +0000676// SourceLocation manipulation methods.
Chris Lattner153a0f12009-02-04 00:40:31 +0000677//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +0000678
Douglas Gregor925296b2011-07-19 16:10:42 +0000679/// \brief Return the FileID for a SourceLocation.
Chris Lattner4fa23622009-01-26 00:43:02 +0000680///
Douglas Gregor925296b2011-07-19 16:10:42 +0000681/// This is the cache-miss path of getFileID. Not as hot as that function, but
682/// still very important. It is responsible for finding the entry in the
683/// SLocEntry tables that contains the specified location.
Chris Lattner4fa23622009-01-26 00:43:02 +0000684FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
Douglas Gregor49f754f2011-04-20 00:21:03 +0000685 if (!SLocOffset)
686 return FileID::get(0);
Mike Stump11289f42009-09-09 15:08:12 +0000687
Douglas Gregor925296b2011-07-19 16:10:42 +0000688 // Now it is time to search for the correct file. See where the SLocOffset
689 // sits in the global view and consult local or loaded buffers for it.
690 if (SLocOffset < NextLocalOffset)
691 return getFileIDLocal(SLocOffset);
692 return getFileIDLoaded(SLocOffset);
693}
694
695/// \brief Return the FileID for a SourceLocation with a low offset.
696///
697/// This function knows that the SourceLocation is in a local buffer, not a
698/// loaded one.
699FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const {
700 assert(SLocOffset < NextLocalOffset && "Bad function choice");
701
Chris Lattner4fa23622009-01-26 00:43:02 +0000702 // After the first and second level caches, I see two common sorts of
Chandler Carruth64ee7822011-07-26 05:17:23 +0000703 // behavior: 1) a lot of searched FileID's are "near" the cached file
704 // location or are "near" the cached expansion location. 2) others are just
Chris Lattner4fa23622009-01-26 00:43:02 +0000705 // completely random and may be a very long way away.
706 //
707 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
708 // then we fall back to a less cache efficient, but more scalable, binary
709 // search to find the location.
Mike Stump11289f42009-09-09 15:08:12 +0000710
Chris Lattner4fa23622009-01-26 00:43:02 +0000711 // See if this is near the file point - worst case we start scanning from the
712 // most newly created FileID.
Benjamin Kramer2999b772013-02-22 18:29:39 +0000713 const SrcMgr::SLocEntry *I;
Mike Stump11289f42009-09-09 15:08:12 +0000714
Douglas Gregor925296b2011-07-19 16:10:42 +0000715 if (LastFileIDLookup.ID < 0 ||
716 LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
Chris Lattner4fa23622009-01-26 00:43:02 +0000717 // Neither loc prunes our search.
Douglas Gregor925296b2011-07-19 16:10:42 +0000718 I = LocalSLocEntryTable.end();
Chris Lattner4fa23622009-01-26 00:43:02 +0000719 } else {
720 // Perhaps it is near the file point.
Douglas Gregor925296b2011-07-19 16:10:42 +0000721 I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
Chris Lattner4fa23622009-01-26 00:43:02 +0000722 }
723
724 // Find the FileID that contains this. "I" is an iterator that points to a
725 // FileID whose offset is known to be larger than SLocOffset.
726 unsigned NumProbes = 0;
727 while (1) {
728 --I;
729 if (I->getOffset() <= SLocOffset) {
Douglas Gregor925296b2011-07-19 16:10:42 +0000730 FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
Douglas Gregor258ae542009-04-27 06:38:32 +0000731
Chandler Carruth64ee7822011-07-26 05:17:23 +0000732 // If this isn't an expansion, remember it. We have good locality across
733 // FileID lookups.
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000734 if (!I->isExpansion())
Chris Lattner4fa23622009-01-26 00:43:02 +0000735 LastFileIDLookup = Res;
736 NumLinearScans += NumProbes+1;
737 return Res;
738 }
739 if (++NumProbes == 8)
740 break;
741 }
Mike Stump11289f42009-09-09 15:08:12 +0000742
Chris Lattner4fa23622009-01-26 00:43:02 +0000743 // Convert "I" back into an index. We know that it is an entry whose index is
744 // larger than the offset we are looking for.
Douglas Gregor925296b2011-07-19 16:10:42 +0000745 unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
Chris Lattner4fa23622009-01-26 00:43:02 +0000746 // LessIndex - This is the lower bound of the range that we're searching.
747 // We know that the offset corresponding to the FileID is is less than
748 // SLocOffset.
749 unsigned LessIndex = 0;
750 NumProbes = 0;
751 while (1) {
Douglas Gregor49f754f2011-04-20 00:21:03 +0000752 bool Invalid = false;
Chris Lattner4fa23622009-01-26 00:43:02 +0000753 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregor925296b2011-07-19 16:10:42 +0000754 unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
Douglas Gregor49f754f2011-04-20 00:21:03 +0000755 if (Invalid)
756 return FileID::get(0);
757
Chris Lattner4fa23622009-01-26 00:43:02 +0000758 ++NumProbes;
Mike Stump11289f42009-09-09 15:08:12 +0000759
Chris Lattner4fa23622009-01-26 00:43:02 +0000760 // If the offset of the midpoint is too large, chop the high side of the
761 // range to the midpoint.
762 if (MidOffset > SLocOffset) {
763 GreaterIndex = MiddleIndex;
764 continue;
765 }
Mike Stump11289f42009-09-09 15:08:12 +0000766
Chris Lattner4fa23622009-01-26 00:43:02 +0000767 // If the middle index contains the value, succeed and return.
Douglas Gregor925296b2011-07-19 16:10:42 +0000768 // FIXME: This could be made faster by using a function that's aware of
769 // being in the local area.
Chris Lattner4fa23622009-01-26 00:43:02 +0000770 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
Chris Lattner4fa23622009-01-26 00:43:02 +0000771 FileID Res = FileID::get(MiddleIndex);
772
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000773 // If this isn't a macro expansion, remember it. We have good locality
Chris Lattner4fa23622009-01-26 00:43:02 +0000774 // across FileID lookups.
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000775 if (!LocalSLocEntryTable[MiddleIndex].isExpansion())
Chris Lattner4fa23622009-01-26 00:43:02 +0000776 LastFileIDLookup = Res;
777 NumBinaryProbes += NumProbes;
778 return Res;
779 }
Mike Stump11289f42009-09-09 15:08:12 +0000780
Chris Lattner4fa23622009-01-26 00:43:02 +0000781 // Otherwise, move the low-side up to the middle index.
782 LessIndex = MiddleIndex;
783 }
784}
785
Douglas Gregor925296b2011-07-19 16:10:42 +0000786/// \brief Return the FileID for a SourceLocation with a high offset.
787///
788/// This function knows that the SourceLocation is in a loaded buffer, not a
789/// local one.
790FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
Argyrios Kyrtzidis25029d42011-10-03 23:43:01 +0000791 // Sanity checking, otherwise a bug may lead to hanging in release build.
Argyrios Kyrtzidis8edffaa2011-10-25 00:29:44 +0000792 if (SLocOffset < CurrentLoadedOffset) {
793 assert(0 && "Invalid SLocOffset or bad function choice");
Argyrios Kyrtzidis25029d42011-10-03 23:43:01 +0000794 return FileID();
Argyrios Kyrtzidis8edffaa2011-10-25 00:29:44 +0000795 }
Argyrios Kyrtzidis25029d42011-10-03 23:43:01 +0000796
Douglas Gregor925296b2011-07-19 16:10:42 +0000797 // Essentially the same as the local case, but the loaded array is sorted
798 // in the other direction.
799
800 // First do a linear scan from the last lookup position, if possible.
801 unsigned I;
802 int LastID = LastFileIDLookup.ID;
803 if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
804 I = 0;
805 else
806 I = (-LastID - 2) + 1;
807
808 unsigned NumProbes;
809 for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
810 // Make sure the entry is loaded!
811 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
812 if (E.getOffset() <= SLocOffset) {
813 FileID Res = FileID::get(-int(I) - 2);
814
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000815 if (!E.isExpansion())
Douglas Gregor925296b2011-07-19 16:10:42 +0000816 LastFileIDLookup = Res;
817 NumLinearScans += NumProbes + 1;
818 return Res;
819 }
820 }
821
822 // Linear scan failed. Do the binary search. Note the reverse sorting of the
823 // table: GreaterIndex is the one where the offset is greater, which is
824 // actually a lower index!
825 unsigned GreaterIndex = I;
826 unsigned LessIndex = LoadedSLocEntryTable.size();
827 NumProbes = 0;
828 while (1) {
829 ++NumProbes;
830 unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
831 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
Argyrios Kyrtzidis7dc4f332013-03-01 03:26:00 +0000832 if (E.getOffset() == 0)
833 return FileID(); // invalid entry.
Douglas Gregor925296b2011-07-19 16:10:42 +0000834
835 ++NumProbes;
836
837 if (E.getOffset() > SLocOffset) {
Argyrios Kyrtzidis7dc4f332013-03-01 03:26:00 +0000838 // Sanity checking, otherwise a bug may lead to hanging in release build.
839 if (GreaterIndex == MiddleIndex) {
840 assert(0 && "binary search missed the entry");
841 return FileID();
842 }
Douglas Gregor925296b2011-07-19 16:10:42 +0000843 GreaterIndex = MiddleIndex;
844 continue;
845 }
846
847 if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
848 FileID Res = FileID::get(-int(MiddleIndex) - 2);
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000849 if (!E.isExpansion())
Douglas Gregor925296b2011-07-19 16:10:42 +0000850 LastFileIDLookup = Res;
851 NumBinaryProbes += NumProbes;
852 return Res;
853 }
854
Argyrios Kyrtzidis1ca73442013-03-01 03:43:33 +0000855 // Sanity checking, otherwise a bug may lead to hanging in release build.
856 if (LessIndex == MiddleIndex) {
857 assert(0 && "binary search missed the entry");
858 return FileID();
859 }
Douglas Gregor925296b2011-07-19 16:10:42 +0000860 LessIndex = MiddleIndex;
861 }
862}
863
Chris Lattner659ac5f2009-01-26 20:04:19 +0000864SourceLocation SourceManager::
Chandler Carruthc84d7692011-07-25 20:52:26 +0000865getExpansionLocSlowCase(SourceLocation Loc) const {
Chris Lattner659ac5f2009-01-26 20:04:19 +0000866 do {
Chris Lattner5647d312010-02-12 19:31:35 +0000867 // Note: If Loc indicates an offset into a token that came from a macro
868 // expansion (e.g. the 5th character of the token) we do not want to add
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000869 // this offset when going to the expansion location. The expansion
Chris Lattner5647d312010-02-12 19:31:35 +0000870 // location is the macro invocation, which the offset has nothing to do
871 // with. This is unlike when we get the spelling loc, because the offset
872 // directly correspond to the token whose spelling we're inspecting.
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000873 Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
Chris Lattner659ac5f2009-01-26 20:04:19 +0000874 } while (!Loc.isFileID());
875
876 return Loc;
877}
878
879SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
880 do {
881 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000882 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000883 Loc = Loc.getLocWithOffset(LocInfo.second);
Chris Lattner659ac5f2009-01-26 20:04:19 +0000884 } while (!Loc.isFileID());
885 return Loc;
886}
887
Argyrios Kyrtzidis7f6b0292011-10-12 07:07:40 +0000888SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
889 do {
890 if (isMacroArgExpansion(Loc))
891 Loc = getImmediateSpellingLoc(Loc);
892 else
893 Loc = getImmediateExpansionRange(Loc).first;
894 } while (!Loc.isFileID());
895 return Loc;
896}
897
Chris Lattner659ac5f2009-01-26 20:04:19 +0000898
Chris Lattner4fa23622009-01-26 00:43:02 +0000899std::pair<FileID, unsigned>
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000900SourceManager::getDecomposedExpansionLocSlowCase(
Argyrios Kyrtzidisc8f7e212011-07-07 03:40:27 +0000901 const SrcMgr::SLocEntry *E) const {
Chandler Carruth64ee7822011-07-26 05:17:23 +0000902 // If this is an expansion record, walk through all the expansion points.
Chris Lattner4fa23622009-01-26 00:43:02 +0000903 FileID FID;
904 SourceLocation Loc;
Argyrios Kyrtzidisc8f7e212011-07-07 03:40:27 +0000905 unsigned Offset;
Chris Lattner4fa23622009-01-26 00:43:02 +0000906 do {
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000907 Loc = E->getExpansion().getExpansionLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000908
Chris Lattner4fa23622009-01-26 00:43:02 +0000909 FID = getFileID(Loc);
910 E = &getSLocEntry(FID);
Argyrios Kyrtzidisc8f7e212011-07-07 03:40:27 +0000911 Offset = Loc.getOffset()-E->getOffset();
Chris Lattner31af4e02009-01-26 19:41:58 +0000912 } while (!Loc.isFileID());
Mike Stump11289f42009-09-09 15:08:12 +0000913
Chris Lattner4fa23622009-01-26 00:43:02 +0000914 return std::make_pair(FID, Offset);
915}
916
917std::pair<FileID, unsigned>
918SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
919 unsigned Offset) const {
Chandler Carruth64ee7822011-07-26 05:17:23 +0000920 // If this is an expansion record, walk through all the expansion points.
Chris Lattner31af4e02009-01-26 19:41:58 +0000921 FileID FID;
922 SourceLocation Loc;
923 do {
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000924 Loc = E->getExpansion().getSpellingLoc();
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000925 Loc = Loc.getLocWithOffset(Offset);
Mike Stump11289f42009-09-09 15:08:12 +0000926
Chris Lattner31af4e02009-01-26 19:41:58 +0000927 FID = getFileID(Loc);
928 E = &getSLocEntry(FID);
Argyrios Kyrtzidis2797df62011-08-23 21:02:41 +0000929 Offset = Loc.getOffset()-E->getOffset();
Chris Lattner31af4e02009-01-26 19:41:58 +0000930 } while (!Loc.isFileID());
Mike Stump11289f42009-09-09 15:08:12 +0000931
Chris Lattner4fa23622009-01-26 00:43:02 +0000932 return std::make_pair(FID, Offset);
933}
934
Chris Lattner8ad52d52009-02-17 08:04:48 +0000935/// getImmediateSpellingLoc - Given a SourceLocation object, return the
936/// spelling location referenced by the ID. This is the first level down
937/// towards the place where the characters that make up the lexed token can be
938/// found. This should not generally be used by clients.
939SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
940 if (Loc.isFileID()) return Loc;
941 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000942 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000943 return Loc.getLocWithOffset(LocInfo.second);
Chris Lattner8ad52d52009-02-17 08:04:48 +0000944}
945
946
Chandler Carruth64ee7822011-07-26 05:17:23 +0000947/// getImmediateExpansionRange - Loc is required to be an expansion location.
948/// Return the start/end of the expansion information.
Chris Lattner9dc9c202009-02-15 20:52:18 +0000949std::pair<SourceLocation,SourceLocation>
Chandler Carruthca757582011-07-25 20:52:21 +0000950SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
Chandler Carruth64ee7822011-07-26 05:17:23 +0000951 assert(Loc.isMacroID() && "Not a macro expansion loc!");
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000952 const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000953 return Expansion.getExpansionLocRange();
Chris Lattner9dc9c202009-02-15 20:52:18 +0000954}
955
Chandler Carruth6d28d7f2011-07-25 16:56:02 +0000956/// getExpansionRange - Given a SourceLocation object, return the range of
957/// tokens covered by the expansion in the ultimate file.
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000958std::pair<SourceLocation,SourceLocation>
Chandler Carruth6d28d7f2011-07-25 16:56:02 +0000959SourceManager::getExpansionRange(SourceLocation Loc) const {
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000960 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000961
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000962 std::pair<SourceLocation,SourceLocation> Res =
Chandler Carruthca757582011-07-25 20:52:21 +0000963 getImmediateExpansionRange(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000964
Chandler Carruth64ee7822011-07-26 05:17:23 +0000965 // Fully resolve the start and end locations to their ultimate expansion
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000966 // points.
967 while (!Res.first.isFileID())
Chandler Carruthca757582011-07-25 20:52:21 +0000968 Res.first = getImmediateExpansionRange(Res.first).first;
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000969 while (!Res.second.isFileID())
Chandler Carruthca757582011-07-25 20:52:21 +0000970 Res.second = getImmediateExpansionRange(Res.second).second;
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000971 return Res;
972}
973
Richard Trieuc3096242015-09-24 01:21:01 +0000974bool SourceManager::isMacroArgExpansion(SourceLocation Loc,
975 SourceLocation *StartLoc) const {
Chandler Carruth402bb382011-07-07 23:56:36 +0000976 if (!Loc.isMacroID()) return false;
977
978 FileID FID = getFileID(Loc);
Matt Beaumont-Gayb1e71a72013-01-12 00:54:16 +0000979 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
Richard Trieuc3096242015-09-24 01:21:01 +0000980 if (!Expansion.isMacroArgExpansion()) return false;
981
982 if (StartLoc)
983 *StartLoc = Expansion.getExpansionLocStart();
984 return true;
Chandler Carruth402bb382011-07-07 23:56:36 +0000985}
Chris Lattner9dc9c202009-02-15 20:52:18 +0000986
Matt Beaumont-Gayb1e71a72013-01-12 00:54:16 +0000987bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const {
988 if (!Loc.isMacroID()) return false;
989
990 FileID FID = getFileID(Loc);
991 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
992 return Expansion.isMacroBodyExpansion();
993}
994
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000995bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
996 SourceLocation *MacroBegin) const {
997 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
998
999 std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);
1000 if (DecompLoc.second > 0)
1001 return false; // Does not point at the start of expansion range.
1002
1003 bool Invalid = false;
1004 const SrcMgr::ExpansionInfo &ExpInfo =
1005 getSLocEntry(DecompLoc.first, &Invalid).getExpansion();
1006 if (Invalid)
1007 return false;
1008 SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();
1009
1010 if (ExpInfo.isMacroArgExpansion()) {
1011 // For macro argument expansions, check if the previous FileID is part of
1012 // the same argument expansion, in which case this Loc is not at the
1013 // beginning of the expansion.
1014 FileID PrevFID = getPreviousFileID(DecompLoc.first);
1015 if (!PrevFID.isInvalid()) {
1016 const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);
1017 if (Invalid)
1018 return false;
1019 if (PrevEntry.isExpansion() &&
1020 PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)
1021 return false;
1022 }
1023 }
1024
1025 if (MacroBegin)
1026 *MacroBegin = ExpLoc;
1027 return true;
1028}
1029
1030bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
1031 SourceLocation *MacroEnd) const {
1032 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1033
1034 FileID FID = getFileID(Loc);
1035 SourceLocation NextLoc = Loc.getLocWithOffset(1);
1036 if (isInFileID(NextLoc, FID))
1037 return false; // Does not point at the end of expansion range.
1038
1039 bool Invalid = false;
1040 const SrcMgr::ExpansionInfo &ExpInfo =
1041 getSLocEntry(FID, &Invalid).getExpansion();
1042 if (Invalid)
1043 return false;
1044
1045 if (ExpInfo.isMacroArgExpansion()) {
1046 // For macro argument expansions, check if the next FileID is part of the
1047 // same argument expansion, in which case this Loc is not at the end of the
1048 // expansion.
1049 FileID NextFID = getNextFileID(FID);
1050 if (!NextFID.isInvalid()) {
1051 const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);
1052 if (Invalid)
1053 return false;
1054 if (NextEntry.isExpansion() &&
1055 NextEntry.getExpansion().getExpansionLocStart() ==
1056 ExpInfo.getExpansionLocStart())
1057 return false;
1058 }
1059 }
1060
1061 if (MacroEnd)
1062 *MacroEnd = ExpInfo.getExpansionLocEnd();
1063 return true;
1064}
1065
Chris Lattner4fa23622009-01-26 00:43:02 +00001066
1067//===----------------------------------------------------------------------===//
1068// Queries about the code at a SourceLocation.
1069//===----------------------------------------------------------------------===//
Chris Lattner30709b032006-06-21 03:01:55 +00001070
Chris Lattnerd01e2912006-06-18 16:22:51 +00001071/// getCharacterData - Return a pointer to the start of the specified location
Chris Lattner739e7392007-04-29 07:12:06 +00001072/// in the appropriate MemoryBuffer.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001073const char *SourceManager::getCharacterData(SourceLocation SL,
1074 bool *Invalid) const {
Chris Lattnerd3a15f72006-07-04 23:01:03 +00001075 // Note that this is a hot function in the getSpelling() path, which is
1076 // heavily used by -E mode.
Chris Lattner4fa23622009-01-26 00:43:02 +00001077 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump11289f42009-09-09 15:08:12 +00001078
Ted Kremenek12c2af42009-01-06 01:55:26 +00001079 // Note that calling 'getBuffer()' may lazily page in a source file.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001080 bool CharDataInvalid = false;
Douglas Gregor49f754f2011-04-20 00:21:03 +00001081 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
1082 if (CharDataInvalid || !Entry.isFile()) {
1083 if (Invalid)
1084 *Invalid = true;
1085
1086 return "<<<<INVALID BUFFER>>>>";
1087 }
David Blaikie66cc07b2014-06-27 17:40:03 +00001088 llvm::MemoryBuffer *Buffer = Entry.getFile().getContentCache()->getBuffer(
1089 Diag, *this, SourceLocation(), &CharDataInvalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001090 if (Invalid)
1091 *Invalid = CharDataInvalid;
1092 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
Chris Lattnerd01e2912006-06-18 16:22:51 +00001093}
1094
Chris Lattner685730f2006-06-26 01:36:22 +00001095
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001096/// getColumnNumber - Return the column # for the specified file position.
Chris Lattnere4ad4172009-02-04 00:55:58 +00001097/// this is significantly cheaper to compute than the line number.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001098unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
1099 bool *Invalid) const {
1100 bool MyInvalid = false;
David Blaikie66cc07b2014-06-27 17:40:03 +00001101 llvm::MemoryBuffer *MemBuf = getBuffer(FID, &MyInvalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001102 if (Invalid)
1103 *Invalid = MyInvalid;
1104
1105 if (MyInvalid)
1106 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00001107
Jordan Rose8d63d5b2012-06-19 03:09:38 +00001108 // It is okay to request a position just past the end of the buffer.
1109 if (FilePos > MemBuf->getBufferSize()) {
Argyrios Kyrtzidis6c8d29f2011-12-10 00:30:38 +00001110 if (Invalid)
Jordan Rose8d63d5b2012-06-19 03:09:38 +00001111 *Invalid = true;
Argyrios Kyrtzidis6c8d29f2011-12-10 00:30:38 +00001112 return 1;
1113 }
1114
Chih-Hung Hsieha0b99e42017-04-06 18:36:50 +00001115 const char *Buf = MemBuf->getBufferStart();
Craig Topper5e79ee02012-10-19 04:40:38 +00001116 // See if we just calculated the line number for this FilePos and can use
1117 // that to lookup the start of the line instead of searching for it.
1118 if (LastLineNoFileIDQuery == FID &&
Craig Topperf1186c52014-05-08 06:41:40 +00001119 LastLineNoContentCache->SourceLineCache != nullptr &&
Craig Topperf3b839b2012-12-16 05:58:32 +00001120 LastLineNoResult < LastLineNoContentCache->NumLines) {
Craig Topper5e79ee02012-10-19 04:40:38 +00001121 unsigned *SourceLineCache = LastLineNoContentCache->SourceLineCache;
1122 unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
1123 unsigned LineEnd = SourceLineCache[LastLineNoResult];
Chih-Hung Hsieha0b99e42017-04-06 18:36:50 +00001124 if (FilePos >= LineStart && FilePos < LineEnd) {
1125 // LineEnd is the LineStart of the next line.
1126 // A line ends with separator LF or CR+LF on Windows.
1127 // FilePos might point to the last separator,
1128 // but we need a column number at most 1 + the last column.
1129 if (FilePos + 1 == LineEnd && FilePos > LineStart) {
1130 if (Buf[FilePos - 1] == '\r' || Buf[FilePos - 1] == '\n')
1131 --FilePos;
1132 }
Craig Topper5e79ee02012-10-19 04:40:38 +00001133 return FilePos - LineStart + 1;
Chih-Hung Hsieha0b99e42017-04-06 18:36:50 +00001134 }
Craig Topper5e79ee02012-10-19 04:40:38 +00001135 }
1136
Chris Lattner22eb9722006-06-18 05:43:12 +00001137 unsigned LineStart = FilePos;
1138 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
1139 --LineStart;
1140 return FilePos-LineStart+1;
1141}
1142
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001143// isInvalid - Return the result of calling loc.isInvalid(), and
1144// if Invalid is not null, set its value to same.
Richard Smith41e66292016-04-28 18:26:32 +00001145template<typename LocType>
1146static bool isInvalid(LocType Loc, bool *Invalid) {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001147 bool MyInvalid = Loc.isInvalid();
1148 if (Invalid)
1149 *Invalid = MyInvalid;
1150 return MyInvalid;
1151}
1152
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001153unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
1154 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001155 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattnere4ad4172009-02-04 00:55:58 +00001156 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001157 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattnere4ad4172009-02-04 00:55:58 +00001158}
1159
Chandler Carruth42f35f92011-07-25 20:57:57 +00001160unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
1161 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001162 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001163 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001164 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattnere4ad4172009-02-04 00:55:58 +00001165}
1166
Chandler Carruth1aef0c52011-02-23 00:47:48 +00001167unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
1168 bool *Invalid) const {
Richard Smith41e66292016-04-28 18:26:32 +00001169 PresumedLoc PLoc = getPresumedLoc(Loc);
1170 if (isInvalid(PLoc, Invalid)) return 0;
1171 return PLoc.getColumn();
Chandler Carruth1aef0c52011-02-23 00:47:48 +00001172}
1173
Benjamin Kramer543036a2012-04-06 20:49:55 +00001174#ifdef __SSE2__
1175#include <emmintrin.h>
1176#endif
1177
Chandler Carruthc3ce5842010-10-23 08:44:57 +00001178static LLVM_ATTRIBUTE_NOINLINE void
David Blaikie9c902b52011-09-25 23:23:43 +00001179ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001180 llvm::BumpPtrAllocator &Alloc,
1181 const SourceManager &SM, bool &Invalid);
David Blaikie9c902b52011-09-25 23:23:43 +00001182static void ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001183 llvm::BumpPtrAllocator &Alloc,
1184 const SourceManager &SM, bool &Invalid) {
Ted Kremenek12c2af42009-01-06 01:55:26 +00001185 // Note that calling 'getBuffer()' may lazily page in the file.
David Blaikie66cc07b2014-06-27 17:40:03 +00001186 MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(), &Invalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001187 if (Invalid)
1188 return;
Mike Stump11289f42009-09-09 15:08:12 +00001189
Chris Lattner8996fff2007-07-24 05:57:19 +00001190 // Find the file offsets of all of the *physical* source lines. This does
1191 // not look at trigraphs, escaped newlines, or anything else tricky.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001192 SmallVector<unsigned, 256> LineOffsets;
Mike Stump11289f42009-09-09 15:08:12 +00001193
Chris Lattner8996fff2007-07-24 05:57:19 +00001194 // Line #1 starts at char 0.
1195 LineOffsets.push_back(0);
Mike Stump11289f42009-09-09 15:08:12 +00001196
Chris Lattner8996fff2007-07-24 05:57:19 +00001197 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
1198 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
1199 unsigned Offs = 0;
1200 while (1) {
1201 // Skip over the contents of the line.
Chris Lattner8996fff2007-07-24 05:57:19 +00001202 const unsigned char *NextBuf = (const unsigned char *)Buf;
Benjamin Kramer543036a2012-04-06 20:49:55 +00001203
1204#ifdef __SSE2__
1205 // Try to skip to the next newline using SSE instructions. This is very
1206 // performance sensitive for programs with lots of diagnostics and in -E
1207 // mode.
1208 __m128i CRs = _mm_set1_epi8('\r');
1209 __m128i LFs = _mm_set1_epi8('\n');
1210
1211 // First fix up the alignment to 16 bytes.
1212 while (((uintptr_t)NextBuf & 0xF) != 0) {
1213 if (*NextBuf == '\n' || *NextBuf == '\r' || *NextBuf == '\0')
1214 goto FoundSpecialChar;
1215 ++NextBuf;
1216 }
1217
1218 // Scan 16 byte chunks for '\r' and '\n'. Ignore '\0'.
1219 while (NextBuf+16 <= End) {
Roman Divackye6377112012-09-06 15:59:27 +00001220 const __m128i Chunk = *(const __m128i*)NextBuf;
Benjamin Kramer543036a2012-04-06 20:49:55 +00001221 __m128i Cmp = _mm_or_si128(_mm_cmpeq_epi8(Chunk, CRs),
1222 _mm_cmpeq_epi8(Chunk, LFs));
1223 unsigned Mask = _mm_movemask_epi8(Cmp);
1224
1225 // If we found a newline, adjust the pointer and jump to the handling code.
1226 if (Mask != 0) {
Michael J. Spencer8c398402013-05-24 21:42:04 +00001227 NextBuf += llvm::countTrailingZeros(Mask);
Benjamin Kramer543036a2012-04-06 20:49:55 +00001228 goto FoundSpecialChar;
1229 }
1230 NextBuf += 16;
1231 }
1232#endif
1233
Chris Lattner8996fff2007-07-24 05:57:19 +00001234 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
1235 ++NextBuf;
Benjamin Kramer543036a2012-04-06 20:49:55 +00001236
1237#ifdef __SSE2__
1238FoundSpecialChar:
1239#endif
Chris Lattner8996fff2007-07-24 05:57:19 +00001240 Offs += NextBuf-Buf;
1241 Buf = NextBuf;
Mike Stump11289f42009-09-09 15:08:12 +00001242
Chris Lattner8996fff2007-07-24 05:57:19 +00001243 if (Buf[0] == '\n' || Buf[0] == '\r') {
1244 // If this is \n\r or \r\n, skip both characters.
Richard Trieucc3949d2016-02-18 22:34:54 +00001245 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1]) {
1246 ++Offs;
1247 ++Buf;
1248 }
1249 ++Offs;
1250 ++Buf;
Chris Lattner8996fff2007-07-24 05:57:19 +00001251 LineOffsets.push_back(Offs);
1252 } else {
1253 // Otherwise, this is a null. If end of file, exit.
1254 if (Buf == End) break;
1255 // Otherwise, skip the null.
Richard Trieucc3949d2016-02-18 22:34:54 +00001256 ++Offs;
1257 ++Buf;
Chris Lattner8996fff2007-07-24 05:57:19 +00001258 }
1259 }
Mike Stump11289f42009-09-09 15:08:12 +00001260
Chris Lattner8996fff2007-07-24 05:57:19 +00001261 // Copy the offsets into the FileInfo structure.
1262 FI->NumLines = LineOffsets.size();
Chris Lattnerc8233df2009-02-03 07:30:45 +00001263 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner8996fff2007-07-24 05:57:19 +00001264 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
1265}
Chris Lattner9a13bde2006-06-21 04:57:09 +00001266
Chris Lattner53e384f2009-01-16 07:00:02 +00001267/// getLineNumber - Given a SourceLocation, return the spelling line number
Chris Lattner22eb9722006-06-18 05:43:12 +00001268/// for the position indicated. This requires building and caching a table of
Chris Lattner739e7392007-04-29 07:12:06 +00001269/// line offsets for the MemoryBuffer, so this is not cheap: use only when
Chris Lattner22eb9722006-06-18 05:43:12 +00001270/// about to emit a diagnostic.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001271unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1272 bool *Invalid) const {
Argyrios Kyrtzidisf15eac12011-05-17 22:09:53 +00001273 if (FID.isInvalid()) {
1274 if (Invalid)
1275 *Invalid = true;
1276 return 1;
1277 }
1278
Chris Lattnerd32480d2009-01-17 06:22:33 +00001279 ContentCache *Content;
Chris Lattner88ea93e2009-02-04 01:06:56 +00001280 if (LastLineNoFileIDQuery == FID)
Ted Kremenekc08bca62007-10-30 21:08:08 +00001281 Content = LastLineNoContentCache;
Douglas Gregor49f754f2011-04-20 00:21:03 +00001282 else {
1283 bool MyInvalid = false;
1284 const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1285 if (MyInvalid || !Entry.isFile()) {
1286 if (Invalid)
1287 *Invalid = true;
1288 return 1;
1289 }
1290
1291 Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
1292 }
1293
Chris Lattner22eb9722006-06-18 05:43:12 +00001294 // If this is the first use of line information for this buffer, compute the
Chris Lattner8996fff2007-07-24 05:57:19 +00001295 /// SourceLineCache for it on demand.
Craig Topperf1186c52014-05-08 06:41:40 +00001296 if (!Content->SourceLineCache) {
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001297 bool MyInvalid = false;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001298 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001299 if (Invalid)
1300 *Invalid = MyInvalid;
1301 if (MyInvalid)
1302 return 1;
1303 } else if (Invalid)
1304 *Invalid = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001305
1306 // Okay, we know we have a line number table. Do a binary search to find the
1307 // line number that this character position lands on.
Ted Kremenekc08bca62007-10-30 21:08:08 +00001308 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner8996fff2007-07-24 05:57:19 +00001309 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenekc08bca62007-10-30 21:08:08 +00001310 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump11289f42009-09-09 15:08:12 +00001311
Chris Lattner88ea93e2009-02-04 01:06:56 +00001312 unsigned QueriedFilePos = FilePos+1;
Chris Lattner8996fff2007-07-24 05:57:19 +00001313
Daniel Dunbar70f924df82009-05-18 17:30:52 +00001314 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump11289f42009-09-09 15:08:12 +00001315 // complicated as it is, binary search isn't that slow.
Daniel Dunbar70f924df82009-05-18 17:30:52 +00001316 //
1317 // If it is worth being optimized, then in my opinion it could be more
1318 // performant, simpler, and more obviously correct by just "galloping" outward
1319 // from the queried file position. In fact, this could be incorporated into a
1320 // generic algorithm such as lower_bound_with_hint.
1321 //
1322 // If someone gives me a test case where this matters, and I will do it! - DWD
1323
Chris Lattner8996fff2007-07-24 05:57:19 +00001324 // If the previous query was to the same file, we know both the file pos from
1325 // that query and the line number returned. This allows us to narrow the
1326 // search space from the entire file to something near the match.
Chris Lattner88ea93e2009-02-04 01:06:56 +00001327 if (LastLineNoFileIDQuery == FID) {
Chris Lattner8996fff2007-07-24 05:57:19 +00001328 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar70f924df82009-05-18 17:30:52 +00001329 // FIXME: Potential overflow?
Chris Lattner8996fff2007-07-24 05:57:19 +00001330 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump11289f42009-09-09 15:08:12 +00001331
Chris Lattner8996fff2007-07-24 05:57:19 +00001332 // The query is likely to be nearby the previous one. Here we check to
1333 // see if it is within 5, 10 or 20 lines. It can be far away in cases
1334 // where big comment blocks and vertical whitespace eat up lines but
1335 // contribute no tokens.
1336 if (SourceLineCache+5 < SourceLineCacheEnd) {
1337 if (SourceLineCache[5] > QueriedFilePos)
1338 SourceLineCacheEnd = SourceLineCache+5;
1339 else if (SourceLineCache+10 < SourceLineCacheEnd) {
1340 if (SourceLineCache[10] > QueriedFilePos)
1341 SourceLineCacheEnd = SourceLineCache+10;
1342 else if (SourceLineCache+20 < SourceLineCacheEnd) {
1343 if (SourceLineCache[20] > QueriedFilePos)
1344 SourceLineCacheEnd = SourceLineCache+20;
1345 }
1346 }
1347 }
1348 } else {
Daniel Dunbar70f924df82009-05-18 17:30:52 +00001349 if (LastLineNoResult < Content->NumLines)
1350 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner8996fff2007-07-24 05:57:19 +00001351 }
1352 }
Mike Stump11289f42009-09-09 15:08:12 +00001353
Chris Lattner830a77f2007-07-24 06:43:46 +00001354 unsigned *Pos
1355 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner8996fff2007-07-24 05:57:19 +00001356 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump11289f42009-09-09 15:08:12 +00001357
Chris Lattner88ea93e2009-02-04 01:06:56 +00001358 LastLineNoFileIDQuery = FID;
Ted Kremenekc08bca62007-10-30 21:08:08 +00001359 LastLineNoContentCache = Content;
Chris Lattner8996fff2007-07-24 05:57:19 +00001360 LastLineNoFilePos = QueriedFilePos;
1361 LastLineNoResult = LineNo;
1362 return LineNo;
Chris Lattner22eb9722006-06-18 05:43:12 +00001363}
1364
Chandler Carruth1aef0c52011-02-23 00:47:48 +00001365unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1366 bool *Invalid) const {
1367 if (isInvalid(Loc, Invalid)) return 0;
1368 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1369 return getLineNumber(LocInfo.first, LocInfo.second);
1370}
Chandler Carruthd48db212011-07-25 21:09:52 +00001371unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
1372 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001373 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001374 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Chris Lattner88ea93e2009-02-04 01:06:56 +00001375 return getLineNumber(LocInfo.first, LocInfo.second);
1376}
Chandler Carruth1aef0c52011-02-23 00:47:48 +00001377unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001378 bool *Invalid) const {
Richard Smith9c527672016-04-28 19:54:51 +00001379 PresumedLoc PLoc = getPresumedLoc(Loc);
1380 if (isInvalid(PLoc, Invalid)) return 0;
1381 return PLoc.getLine();
Chris Lattner88ea93e2009-02-04 01:06:56 +00001382}
1383
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001384/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump11289f42009-09-09 15:08:12 +00001385/// source location, indicating whether this is a normal file, a system
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001386/// header, or an "implicit extern C" system header.
1387///
1388/// This state can be modified with flags on GNU linemarker directives like:
1389/// # 4 "foo.h" 3
1390/// which changes all source locations in the current file after that to be
1391/// considered to be from a system header.
Mike Stump11289f42009-09-09 15:08:12 +00001392SrcMgr::CharacteristicKind
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001393SourceManager::getFileCharacteristic(SourceLocation Loc) const {
Yaron Keren8b563662015-10-03 10:46:20 +00001394 assert(Loc.isValid() && "Can't get file characteristic of invalid loc!");
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001395 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregor49f754f2011-04-20 00:21:03 +00001396 bool Invalid = false;
1397 const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
1398 if (Invalid || !SEntry.isFile())
1399 return C_User;
1400
1401 const SrcMgr::FileInfo &FI = SEntry.getFile();
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001402
1403 // If there are no #line directives in this file, just return the whole-file
1404 // state.
1405 if (!FI.hasLineDirectives())
1406 return FI.getFileCharacteristic();
Mike Stump11289f42009-09-09 15:08:12 +00001407
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001408 assert(LineTable && "Can't have linetable entries without a LineTable!");
1409 // See if there is a #line directive before the location.
1410 const LineEntry *Entry =
Douglas Gregor02c2dbf2012-06-08 16:40:28 +00001411 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
Mike Stump11289f42009-09-09 15:08:12 +00001412
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001413 // If this is before the first line marker, use the file characteristic.
1414 if (!Entry)
1415 return FI.getFileCharacteristic();
1416
1417 return Entry->FileKind;
1418}
1419
Chris Lattnera6f037c2009-02-17 08:39:06 +00001420/// Return the filename or buffer identifier of the buffer the location is in.
James Dennett87a2acf2012-06-17 03:22:59 +00001421/// Note that this name does not respect \#line directives. Use getPresumedLoc
Chris Lattnera6f037c2009-02-17 08:39:06 +00001422/// for normal clients.
Mehdi Amini99d1b292016-10-01 16:38:28 +00001423StringRef SourceManager::getBufferName(SourceLocation Loc,
1424 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001425 if (isInvalid(Loc, Invalid)) return "<invalid loc>";
Mike Stump11289f42009-09-09 15:08:12 +00001426
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001427 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
Chris Lattnera6f037c2009-02-17 08:39:06 +00001428}
1429
Chris Lattner88ea93e2009-02-04 01:06:56 +00001430
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001431/// getPresumedLoc - This method returns the "presumed" location of a
James Dennett87a2acf2012-06-17 03:22:59 +00001432/// SourceLocation specifies. A "presumed location" can be modified by \#line
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001433/// or GNU line marker directives. This provides a view on the data that a
1434/// user should see in diagnostics, for example.
1435///
Chandler Carruth64ee7822011-07-26 05:17:23 +00001436/// Note that a presumed location is always given as the expansion point of an
1437/// expansion location, not at the spelling location.
Richard Smith0b50cb72012-11-14 23:55:25 +00001438PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc,
1439 bool UseLineDirectives) const {
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001440 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001441
Chandler Carruth64ee7822011-07-26 05:17:23 +00001442 // Presumed locations are always for expansion points.
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001443 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +00001444
Douglas Gregor49f754f2011-04-20 00:21:03 +00001445 bool Invalid = false;
1446 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1447 if (Invalid || !Entry.isFile())
1448 return PresumedLoc();
1449
1450 const SrcMgr::FileInfo &FI = Entry.getFile();
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001451 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump11289f42009-09-09 15:08:12 +00001452
Chris Lattnerd4293922009-02-04 01:55:42 +00001453 // To get the source name, first consult the FileEntry (if one exists)
1454 // before the MemBuffer as this will avoid unnecessarily paging in the
1455 // MemBuffer.
Mehdi Amini99d1b292016-10-01 16:38:28 +00001456 StringRef Filename;
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001457 if (C->OrigEntry)
1458 Filename = C->OrigEntry->getName();
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001459 else
1460 Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
Douglas Gregor49f754f2011-04-20 00:21:03 +00001461
Douglas Gregor75f26d62010-11-02 00:39:22 +00001462 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1463 if (Invalid)
1464 return PresumedLoc();
1465 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1466 if (Invalid)
1467 return PresumedLoc();
1468
Chris Lattnerd4293922009-02-04 01:55:42 +00001469 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001470
Chris Lattnerd4293922009-02-04 01:55:42 +00001471 // If we have #line directives in this file, update and overwrite the physical
1472 // location info if appropriate.
Richard Smith0b50cb72012-11-14 23:55:25 +00001473 if (UseLineDirectives && FI.hasLineDirectives()) {
Chris Lattnerd4293922009-02-04 01:55:42 +00001474 assert(LineTable && "Can't have linetable entries without a LineTable!");
1475 // See if there is a #line directive before this. If so, get it.
1476 if (const LineEntry *Entry =
Douglas Gregor02c2dbf2012-06-08 16:40:28 +00001477 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
Chris Lattnerc1219ff2009-02-04 02:00:59 +00001478 // If the LineEntry indicates a filename, use it.
Chris Lattnerd4293922009-02-04 01:55:42 +00001479 if (Entry->FilenameID != -1)
1480 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerc1219ff2009-02-04 02:00:59 +00001481
1482 // Use the line number specified by the LineEntry. This line number may
1483 // be multiple lines down from the line entry. Add the difference in
1484 // physical line numbers from the query point and the line marker to the
1485 // total.
1486 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1487 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump11289f42009-09-09 15:08:12 +00001488
Chris Lattner20c50ba2009-02-04 02:15:40 +00001489 // Note that column numbers are not molested by line markers.
Mike Stump11289f42009-09-09 15:08:12 +00001490
Chris Lattner1c967782009-02-04 06:25:26 +00001491 // Handle virtual #include manipulation.
1492 if (Entry->IncludeOffset) {
1493 IncludeLoc = getLocForStartOfFile(LocInfo.first);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001494 IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
Chris Lattner1c967782009-02-04 06:25:26 +00001495 }
Chris Lattnerd4293922009-02-04 01:55:42 +00001496 }
1497 }
1498
Mehdi Amini99d1b292016-10-01 16:38:28 +00001499 return PresumedLoc(Filename.data(), LineNo, ColNo, IncludeLoc);
Chris Lattner4fa23622009-01-26 00:43:02 +00001500}
1501
Benjamin Kramere7800df2013-09-27 17:12:50 +00001502/// \brief Returns whether the PresumedLoc for a given SourceLocation is
1503/// in the main file.
1504///
1505/// This computes the "presumed" location for a SourceLocation, then checks
1506/// whether it came from a file other than the main file. This is different
1507/// from isWrittenInMainFile() because it takes line marker directives into
1508/// account.
1509bool SourceManager::isInMainFile(SourceLocation Loc) const {
1510 if (Loc.isInvalid()) return false;
1511
1512 // Presumed locations are always for expansion points.
1513 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1514
1515 bool Invalid = false;
1516 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1517 if (Invalid || !Entry.isFile())
1518 return false;
1519
1520 const SrcMgr::FileInfo &FI = Entry.getFile();
1521
1522 // Check if there is a line directive for this location.
1523 if (FI.hasLineDirectives())
1524 if (const LineEntry *Entry =
1525 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
1526 if (Entry->IncludeOffset)
1527 return false;
1528
1529 return FI.getIncludeLoc().isInvalid();
1530}
1531
James Dennettaa61cbb2013-11-24 01:47:49 +00001532/// \brief The size of the SLocEntry that \p FID represents.
Argyrios Kyrtzidis296374b52011-08-23 21:02:28 +00001533unsigned SourceManager::getFileIDSize(FileID FID) const {
1534 bool Invalid = false;
1535 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1536 if (Invalid)
1537 return 0;
1538
1539 int ID = FID.ID;
1540 unsigned NextOffset;
1541 if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
1542 NextOffset = getNextLocalOffset();
1543 else if (ID+1 == -1)
1544 NextOffset = MaxLoadedOffset;
1545 else
1546 NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
1547
1548 return NextOffset - Entry.getOffset() - 1;
1549}
1550
Chris Lattner4fa23622009-01-26 00:43:02 +00001551//===----------------------------------------------------------------------===//
1552// Other miscellaneous methods.
1553//===----------------------------------------------------------------------===//
1554
Douglas Gregore6642762011-02-03 17:17:35 +00001555/// \brief Retrieve the inode for the given file entry, if possible.
1556///
1557/// This routine involves a system call, and therefore should only be used
1558/// in non-performance-critical code.
Rafael Espindola073ff102013-07-29 21:26:52 +00001559static Optional<llvm::sys::fs::UniqueID>
1560getActualFileUID(const FileEntry *File) {
Douglas Gregore6642762011-02-03 17:17:35 +00001561 if (!File)
David Blaikie7a30dc52013-02-21 01:47:18 +00001562 return None;
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001563
Rafael Espindola073ff102013-07-29 21:26:52 +00001564 llvm::sys::fs::UniqueID ID;
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001565 if (llvm::sys::fs::getUniqueID(File->getName(), ID))
David Blaikie7a30dc52013-02-21 01:47:18 +00001566 return None;
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001567
1568 return ID;
Douglas Gregore6642762011-02-03 17:17:35 +00001569}
1570
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001571/// \brief Get the source location for the given file:line:col triplet.
1572///
1573/// If the source file is included multiple times, the source location will
Douglas Gregor925296b2011-07-19 16:10:42 +00001574/// be based upon an arbitrary inclusion.
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001575SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001576 unsigned Line,
1577 unsigned Col) const {
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001578 assert(SourceFile && "Null source file!");
1579 assert(Line && Col && "Line and column should start from 1!");
1580
Argyrios Kyrtzidis04a6e5f2011-09-27 17:22:25 +00001581 FileID FirstFID = translateFile(SourceFile);
1582 return translateLineCol(FirstFID, Line, Col);
1583}
1584
1585/// \brief Get the FileID for the given file.
1586///
1587/// If the source file is included multiple times, the FileID will be the
1588/// first inclusion.
1589FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
1590 assert(SourceFile && "Null source file!");
1591
Douglas Gregore6642762011-02-03 17:17:35 +00001592 // Find the first file ID that corresponds to the given file.
1593 FileID FirstFID;
Mike Stump11289f42009-09-09 15:08:12 +00001594
Douglas Gregore6642762011-02-03 17:17:35 +00001595 // First, check the main file ID, since it is common to look for a
1596 // location in the main file.
Rafael Espindola073ff102013-07-29 21:26:52 +00001597 Optional<llvm::sys::fs::UniqueID> SourceFileUID;
David Blaikie05785d12013-02-20 22:23:23 +00001598 Optional<StringRef> SourceFileName;
Yaron Keren8b563662015-10-03 10:46:20 +00001599 if (MainFileID.isValid()) {
Douglas Gregor49f754f2011-04-20 00:21:03 +00001600 bool Invalid = false;
1601 const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1602 if (Invalid)
Argyrios Kyrtzidis04a6e5f2011-09-27 17:22:25 +00001603 return FileID();
Douglas Gregor49f754f2011-04-20 00:21:03 +00001604
Douglas Gregore6642762011-02-03 17:17:35 +00001605 if (MainSLoc.isFile()) {
1606 const ContentCache *MainContentCache
1607 = MainSLoc.getFile().getContentCache();
Douglas Gregor6a5be932011-02-11 18:08:15 +00001608 if (!MainContentCache) {
1609 // Can't do anything
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001610 } else if (MainContentCache->OrigEntry == SourceFile) {
Douglas Gregore6642762011-02-03 17:17:35 +00001611 FirstFID = MainFileID;
Douglas Gregor6a5be932011-02-11 18:08:15 +00001612 } else {
Douglas Gregore6642762011-02-03 17:17:35 +00001613 // Fall back: check whether we have the same base name and inode
1614 // as the main file.
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001615 const FileEntry *MainFile = MainContentCache->OrigEntry;
Douglas Gregore6642762011-02-03 17:17:35 +00001616 SourceFileName = llvm::sys::path::filename(SourceFile->getName());
1617 if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) {
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001618 SourceFileUID = getActualFileUID(SourceFile);
1619 if (SourceFileUID) {
Rafael Espindola073ff102013-07-29 21:26:52 +00001620 if (Optional<llvm::sys::fs::UniqueID> MainFileUID =
1621 getActualFileUID(MainFile)) {
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001622 if (*SourceFileUID == *MainFileUID) {
Douglas Gregord766be62011-02-16 19:09:24 +00001623 FirstFID = MainFileID;
1624 SourceFile = MainFile;
1625 }
1626 }
Douglas Gregore6642762011-02-03 17:17:35 +00001627 }
1628 }
1629 }
1630 }
1631 }
1632
1633 if (FirstFID.isInvalid()) {
1634 // The location we're looking for isn't in the main file; look
Douglas Gregor925296b2011-07-19 16:10:42 +00001635 // through all of the local source locations.
1636 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
Douglas Gregor49f754f2011-04-20 00:21:03 +00001637 bool Invalid = false;
Douglas Gregor925296b2011-07-19 16:10:42 +00001638 const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid);
Douglas Gregor49f754f2011-04-20 00:21:03 +00001639 if (Invalid)
Argyrios Kyrtzidis04a6e5f2011-09-27 17:22:25 +00001640 return FileID();
Douglas Gregor49f754f2011-04-20 00:21:03 +00001641
Douglas Gregore6642762011-02-03 17:17:35 +00001642 if (SLoc.isFile() &&
1643 SLoc.getFile().getContentCache() &&
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001644 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
Douglas Gregore6642762011-02-03 17:17:35 +00001645 FirstFID = FileID::get(I);
1646 break;
1647 }
1648 }
Douglas Gregor925296b2011-07-19 16:10:42 +00001649 // If that still didn't help, try the modules.
1650 if (FirstFID.isInvalid()) {
1651 for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
1652 const SLocEntry &SLoc = getLoadedSLocEntry(I);
1653 if (SLoc.isFile() &&
1654 SLoc.getFile().getContentCache() &&
1655 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1656 FirstFID = FileID::get(-int(I) - 2);
1657 break;
1658 }
1659 }
1660 }
Douglas Gregore6642762011-02-03 17:17:35 +00001661 }
1662
1663 // If we haven't found what we want yet, try again, but this time stat()
1664 // each of the files in case the files have changed since we originally
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001665 // parsed the file.
Douglas Gregore6642762011-02-03 17:17:35 +00001666 if (FirstFID.isInvalid() &&
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001667 (SourceFileName ||
Douglas Gregore6642762011-02-03 17:17:35 +00001668 (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) &&
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001669 (SourceFileUID || (SourceFileUID = getActualFileUID(SourceFile)))) {
Douglas Gregor49f754f2011-04-20 00:21:03 +00001670 bool Invalid = false;
Douglas Gregor925296b2011-07-19 16:10:42 +00001671 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1672 FileID IFileID;
1673 IFileID.ID = I;
1674 const SLocEntry &SLoc = getSLocEntry(IFileID, &Invalid);
Douglas Gregor49f754f2011-04-20 00:21:03 +00001675 if (Invalid)
Argyrios Kyrtzidis04a6e5f2011-09-27 17:22:25 +00001676 return FileID();
Douglas Gregor49f754f2011-04-20 00:21:03 +00001677
Douglas Gregore6642762011-02-03 17:17:35 +00001678 if (SLoc.isFile()) {
1679 const ContentCache *FileContentCache
1680 = SLoc.getFile().getContentCache();
Craig Topperf1186c52014-05-08 06:41:40 +00001681 const FileEntry *Entry = FileContentCache ? FileContentCache->OrigEntry
1682 : nullptr;
Douglas Gregore6642762011-02-03 17:17:35 +00001683 if (Entry &&
Douglas Gregor6a5be932011-02-11 18:08:15 +00001684 *SourceFileName == llvm::sys::path::filename(Entry->getName())) {
Rafael Espindola073ff102013-07-29 21:26:52 +00001685 if (Optional<llvm::sys::fs::UniqueID> EntryUID =
1686 getActualFileUID(Entry)) {
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001687 if (*SourceFileUID == *EntryUID) {
Douglas Gregor6a5be932011-02-11 18:08:15 +00001688 FirstFID = FileID::get(I);
1689 SourceFile = Entry;
1690 break;
1691 }
1692 }
Douglas Gregore6642762011-02-03 17:17:35 +00001693 }
1694 }
1695 }
1696 }
Argyrios Kyrtzidis04a6e5f2011-09-27 17:22:25 +00001697
Ted Kremenekbd1d7fa2012-10-12 22:56:33 +00001698 (void) SourceFile;
Argyrios Kyrtzidis04a6e5f2011-09-27 17:22:25 +00001699 return FirstFID;
Argyrios Kyrtzidis532c5192011-09-19 20:40:29 +00001700}
1701
1702/// \brief Get the source location in \arg FID for the given line:col.
1703/// Returns null location if \arg FID is not a file SLocEntry.
1704SourceLocation SourceManager::translateLineCol(FileID FID,
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001705 unsigned Line,
1706 unsigned Col) const {
Aaron Ballmanef1cf832013-11-18 18:29:00 +00001707 // Lines are used as a one-based index into a zero-based array. This assert
1708 // checks for possible buffer underruns.
Gabor Horvathfe2c0ff2015-12-01 09:00:41 +00001709 assert(Line && Col && "Line and column should start from 1!");
Aaron Ballmanef1cf832013-11-18 18:29:00 +00001710
Argyrios Kyrtzidis532c5192011-09-19 20:40:29 +00001711 if (FID.isInvalid())
1712 return SourceLocation();
1713
1714 bool Invalid = false;
1715 const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1716 if (Invalid)
1717 return SourceLocation();
Alexander Kornienko6d8cf832013-07-29 22:26:10 +00001718
Argyrios Kyrtzidis532c5192011-09-19 20:40:29 +00001719 if (!Entry.isFile())
Douglas Gregore6642762011-02-03 17:17:35 +00001720 return SourceLocation();
1721
Argyrios Kyrtzidis7c2b28a2011-09-20 22:14:54 +00001722 SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
1723
Douglas Gregore6642762011-02-03 17:17:35 +00001724 if (Line == 1 && Col == 1)
Argyrios Kyrtzidis7c2b28a2011-09-20 22:14:54 +00001725 return FileLoc;
Douglas Gregore6642762011-02-03 17:17:35 +00001726
1727 ContentCache *Content
Argyrios Kyrtzidis532c5192011-09-19 20:40:29 +00001728 = const_cast<ContentCache *>(Entry.getFile().getContentCache());
Douglas Gregore6642762011-02-03 17:17:35 +00001729 if (!Content)
1730 return SourceLocation();
Alexander Kornienko6d8cf832013-07-29 22:26:10 +00001731
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001732 // If this is the first use of line information for this buffer, compute the
Douglas Gregor925296b2011-07-19 16:10:42 +00001733 // SourceLineCache for it on demand.
Craig Topperf1186c52014-05-08 06:41:40 +00001734 if (!Content->SourceLineCache) {
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001735 bool MyInvalid = false;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001736 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001737 if (MyInvalid)
1738 return SourceLocation();
1739 }
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001740
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001741 if (Line > Content->NumLines) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001742 unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001743 if (Size > 0)
1744 --Size;
Argyrios Kyrtzidis7c2b28a2011-09-20 22:14:54 +00001745 return FileLoc.getLocWithOffset(Size);
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001746 }
1747
David Blaikie66cc07b2014-06-27 17:40:03 +00001748 llvm::MemoryBuffer *Buffer = Content->getBuffer(Diag, *this);
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001749 unsigned FilePos = Content->SourceLineCache[Line - 1];
Dylan Noblesmith2a8bc152011-12-19 08:51:05 +00001750 const char *Buf = Buffer->getBufferStart() + FilePos;
1751 unsigned BufLength = Buffer->getBufferSize() - FilePos;
Argyrios Kyrtzidis7c2b28a2011-09-20 22:14:54 +00001752 if (BufLength == 0)
1753 return FileLoc.getLocWithOffset(FilePos);
1754
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001755 unsigned i = 0;
1756
1757 // Check that the given column is valid.
1758 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1759 ++i;
Alexander Kornienko6d8cf832013-07-29 22:26:10 +00001760 return FileLoc.getLocWithOffset(FilePos + i);
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001761}
1762
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001763/// \brief Compute a map of macro argument chunks to their expanded source
1764/// location. Chunks that are not part of a macro argument will map to an
1765/// invalid source location. e.g. if a file contains one macro argument at
1766/// offset 100 with length 10, this is how the map will be formed:
1767/// 0 -> SourceLocation()
1768/// 100 -> Expanded macro arg location
1769/// 110 -> SourceLocation()
Vedant Kumard2c6a6d2016-10-18 00:23:27 +00001770void SourceManager::computeMacroArgsCache(MacroArgsMap &MacroArgsCache,
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001771 FileID FID) const {
Yaron Keren8b563662015-10-03 10:46:20 +00001772 assert(FID.isValid());
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001773
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001774 // Initially no macro argument chunk is present.
1775 MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
1776
1777 int ID = FID.ID;
1778 while (1) {
1779 ++ID;
1780 // Stop if there are no more FileIDs to check.
1781 if (ID > 0) {
1782 if (unsigned(ID) >= local_sloc_entry_size())
1783 return;
1784 } else if (ID == -1) {
1785 return;
1786 }
1787
Argyrios Kyrtzidisfe683022013-06-07 17:57:59 +00001788 bool Invalid = false;
1789 const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);
1790 if (Invalid)
1791 return;
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001792 if (Entry.isFile()) {
1793 SourceLocation IncludeLoc = Entry.getFile().getIncludeLoc();
1794 if (IncludeLoc.isInvalid())
1795 continue;
1796 if (!isInFileID(IncludeLoc, FID))
1797 return; // No more files/macros that may be "contained" in this file.
1798
1799 // Skip the files/macros of the #include'd file, we only care about macros
1800 // that lexed macro arguments from our file.
1801 if (Entry.getFile().NumCreatedFIDs)
1802 ID += Entry.getFile().NumCreatedFIDs - 1/*because of next ++ID*/;
1803 continue;
1804 }
1805
Argyrios Kyrtzidise841c902011-12-21 16:56:35 +00001806 const ExpansionInfo &ExpInfo = Entry.getExpansion();
1807
1808 if (ExpInfo.getExpansionLocStart().isFileID()) {
1809 if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
1810 return; // No more files/macros that may be "contained" in this file.
1811 }
1812
1813 if (!ExpInfo.isMacroArgExpansion())
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001814 continue;
Argyrios Kyrtzidise841c902011-12-21 16:56:35 +00001815
Argyrios Kyrtzidis73ccdb92012-10-20 00:51:32 +00001816 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1817 ExpInfo.getSpellingLoc(),
1818 SourceLocation::getMacroLoc(Entry.getOffset()),
1819 getFileIDSize(FileID::get(ID)));
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001820 }
1821}
1822
Argyrios Kyrtzidis73ccdb92012-10-20 00:51:32 +00001823void SourceManager::associateFileChunkWithMacroArgExp(
1824 MacroArgsMap &MacroArgsCache,
1825 FileID FID,
1826 SourceLocation SpellLoc,
1827 SourceLocation ExpansionLoc,
1828 unsigned ExpansionLength) const {
1829 if (!SpellLoc.isFileID()) {
1830 unsigned SpellBeginOffs = SpellLoc.getOffset();
1831 unsigned SpellEndOffs = SpellBeginOffs + ExpansionLength;
1832
1833 // The spelling range for this macro argument expansion can span multiple
1834 // consecutive FileID entries. Go through each entry contained in the
1835 // spelling range and if one is itself a macro argument expansion, recurse
1836 // and associate the file chunk that it represents.
1837
1838 FileID SpellFID; // Current FileID in the spelling range.
1839 unsigned SpellRelativeOffs;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001840 std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);
Argyrios Kyrtzidis73ccdb92012-10-20 00:51:32 +00001841 while (1) {
1842 const SLocEntry &Entry = getSLocEntry(SpellFID);
1843 unsigned SpellFIDBeginOffs = Entry.getOffset();
1844 unsigned SpellFIDSize = getFileIDSize(SpellFID);
1845 unsigned SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;
1846 const ExpansionInfo &Info = Entry.getExpansion();
1847 if (Info.isMacroArgExpansion()) {
1848 unsigned CurrSpellLength;
1849 if (SpellFIDEndOffs < SpellEndOffs)
1850 CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
1851 else
1852 CurrSpellLength = ExpansionLength;
1853 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1854 Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),
1855 ExpansionLoc, CurrSpellLength);
1856 }
1857
1858 if (SpellFIDEndOffs >= SpellEndOffs)
1859 return; // we covered all FileID entries in the spelling range.
1860
1861 // Move to the next FileID entry in the spelling range.
1862 unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
1863 ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);
1864 ExpansionLength -= advance;
1865 ++SpellFID.ID;
1866 SpellRelativeOffs = 0;
1867 }
1868
1869 }
1870
1871 assert(SpellLoc.isFileID());
1872
1873 unsigned BeginOffs;
1874 if (!isInFileID(SpellLoc, FID, &BeginOffs))
1875 return;
1876
1877 unsigned EndOffs = BeginOffs + ExpansionLength;
1878
1879 // Add a new chunk for this macro argument. A previous macro argument chunk
1880 // may have been lexed again, so e.g. if the map is
1881 // 0 -> SourceLocation()
1882 // 100 -> Expanded loc #1
1883 // 110 -> SourceLocation()
1884 // and we found a new macro FileID that lexed from offet 105 with length 3,
1885 // the new map will be:
1886 // 0 -> SourceLocation()
1887 // 100 -> Expanded loc #1
1888 // 105 -> Expanded loc #2
1889 // 108 -> Expanded loc #1
1890 // 110 -> SourceLocation()
1891 //
1892 // Since re-lexed macro chunks will always be the same size or less of
1893 // previous chunks, we only need to find where the ending of the new macro
1894 // chunk is mapped to and update the map with new begin/end mappings.
1895
1896 MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
1897 --I;
1898 SourceLocation EndOffsMappedLoc = I->second;
1899 MacroArgsCache[BeginOffs] = ExpansionLoc;
1900 MacroArgsCache[EndOffs] = EndOffsMappedLoc;
1901}
1902
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001903/// \brief If \arg Loc points inside a function macro argument, the returned
1904/// location will be the macro location in which the argument was expanded.
1905/// If a macro argument is used multiple times, the expanded location will
1906/// be at the first expansion of the argument.
1907/// e.g.
1908/// MY_MACRO(foo);
1909/// ^
1910/// Passing a file location pointing at 'foo', will yield a macro location
1911/// where 'foo' was expanded into.
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001912SourceLocation
1913SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001914 if (Loc.isInvalid() || !Loc.isFileID())
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001915 return Loc;
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001916
1917 FileID FID;
1918 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001919 std::tie(FID, Offset) = getDecomposedLoc(Loc);
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001920 if (FID.isInvalid())
1921 return Loc;
1922
Vedant Kumard2c6a6d2016-10-18 00:23:27 +00001923 std::unique_ptr<MacroArgsMap> &MacroArgsCache = MacroArgsCacheMap[FID];
1924 if (!MacroArgsCache) {
1925 MacroArgsCache = llvm::make_unique<MacroArgsMap>();
Vedant Kumarecc31442016-10-18 18:19:02 +00001926 computeMacroArgsCache(*MacroArgsCache, FID);
Vedant Kumard2c6a6d2016-10-18 00:23:27 +00001927 }
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001928
Argyrios Kyrtzidis4bdd6aa2011-09-26 08:01:50 +00001929 assert(!MacroArgsCache->empty());
1930 MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001931 --I;
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001932
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001933 unsigned MacroArgBeginOffs = I->first;
1934 SourceLocation MacroArgExpandedLoc = I->second;
1935 if (MacroArgExpandedLoc.isValid())
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001936 return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001937
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001938 return Loc;
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001939}
1940
Argyrios Kyrtzidis37613a92013-04-13 01:03:57 +00001941std::pair<FileID, unsigned>
1942SourceManager::getDecomposedIncludedLoc(FileID FID) const {
Argyrios Kyrtzidis5dca8642013-05-24 22:24:04 +00001943 if (FID.isInvalid())
1944 return std::make_pair(FileID(), 0);
1945
Argyrios Kyrtzidis37613a92013-04-13 01:03:57 +00001946 // Uses IncludedLocMap to retrieve/cache the decomposed loc.
1947
1948 typedef std::pair<FileID, unsigned> DecompTy;
1949 typedef llvm::DenseMap<FileID, DecompTy> MapTy;
1950 std::pair<MapTy::iterator, bool>
1951 InsertOp = IncludedLocMap.insert(std::make_pair(FID, DecompTy()));
1952 DecompTy &DecompLoc = InsertOp.first->second;
1953 if (!InsertOp.second)
1954 return DecompLoc; // already in map.
1955
1956 SourceLocation UpperLoc;
Argyrios Kyrtzidis5dca8642013-05-24 22:24:04 +00001957 bool Invalid = false;
1958 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1959 if (!Invalid) {
1960 if (Entry.isExpansion())
1961 UpperLoc = Entry.getExpansion().getExpansionLocStart();
1962 else
1963 UpperLoc = Entry.getFile().getIncludeLoc();
1964 }
Argyrios Kyrtzidis37613a92013-04-13 01:03:57 +00001965
1966 if (UpperLoc.isValid())
1967 DecompLoc = getDecomposedLoc(UpperLoc);
1968
1969 return DecompLoc;
1970}
1971
Chandler Carruth64ee7822011-07-26 05:17:23 +00001972/// Given a decomposed source location, move it up the include/expansion stack
1973/// to the parent source location. If this is possible, return the decomposed
1974/// version of the parent in Loc and return false. If Loc is the top-level
1975/// entry, return true and don't modify it.
Chris Lattnera99fa1a2010-05-07 20:35:24 +00001976static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1977 const SourceManager &SM) {
Argyrios Kyrtzidis37613a92013-04-13 01:03:57 +00001978 std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
1979 if (UpperLoc.first.isInvalid())
Chris Lattnera99fa1a2010-05-07 20:35:24 +00001980 return true; // We reached the top.
Argyrios Kyrtzidis37613a92013-04-13 01:03:57 +00001981
1982 Loc = UpperLoc;
Chris Lattnera99fa1a2010-05-07 20:35:24 +00001983 return false;
1984}
Ted Kremenek08037042013-02-27 00:00:26 +00001985
1986/// Return the cache entry for comparing the given file IDs
1987/// for isBeforeInTranslationUnit.
1988InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
1989 FileID RFID) const {
1990 // This is a magic number for limiting the cache size. It was experimentally
1991 // derived from a small Objective-C project (where the cache filled
1992 // out to ~250 items). We can make it larger if necessary.
1993 enum { MagicCacheSize = 300 };
1994 IsBeforeInTUCacheKey Key(LFID, RFID);
1995
1996 // If the cache size isn't too large, do a lookup and if necessary default
1997 // construct an entry. We can then return it to the caller for direct
1998 // use. When they update the value, the cache will get automatically
1999 // updated as well.
2000 if (IBTUCache.size() < MagicCacheSize)
2001 return IBTUCache[Key];
2002
2003 // Otherwise, do a lookup that will not construct a new value.
2004 InBeforeInTUCache::iterator I = IBTUCache.find(Key);
2005 if (I != IBTUCache.end())
2006 return I->second;
2007
2008 // Fall back to the overflow value.
2009 return IBTUCacheOverflow;
2010}
Chris Lattnera99fa1a2010-05-07 20:35:24 +00002011
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00002012/// \brief Determines the order of 2 source locations in the translation unit.
2013///
2014/// \returns true if LHS source location comes before RHS, false otherwise.
2015bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
2016 SourceLocation RHS) const {
2017 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
2018 if (LHS == RHS)
2019 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002020
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00002021 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
2022 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00002023
Argyrios Kyrtzidis5fd822c2013-05-24 23:47:43 +00002024 // getDecomposedLoc may have failed to return a valid FileID because, e.g. it
2025 // is a serialized one referring to a file that was removed after we loaded
2026 // the PCH.
Argyrios Kyrtzidis5dca8642013-05-24 22:24:04 +00002027 if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
Argyrios Kyrtzidisd6111d32013-05-25 01:03:03 +00002028 return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
Argyrios Kyrtzidis5dca8642013-05-24 22:24:04 +00002029
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00002030 // If the source locations are in the same file, just compare offsets.
2031 if (LOffs.first == ROffs.first)
2032 return LOffs.second < ROffs.second;
2033
2034 // If we are comparing a source location with multiple locations in the same
2035 // file, we get a big win by caching the result.
Ted Kremenek08037042013-02-27 00:00:26 +00002036 InBeforeInTUCacheEntry &IsBeforeInTUCache =
2037 getInBeforeInTUCache(LOffs.first, ROffs.first);
2038
2039 // If we are comparing a source location with multiple locations in the same
2040 // file, we get a big win by caching the result.
Chris Lattner46e3b482010-05-07 05:10:46 +00002041 if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
2042 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Mike Stump11289f42009-09-09 15:08:12 +00002043
Chris Lattner66d2f922010-05-07 01:17:07 +00002044 // Okay, we missed in the cache, start updating the cache for this query.
Argyrios Kyrtzidisac199bf2011-08-17 00:31:18 +00002045 IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
2046 /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID);
Mike Stump11289f42009-09-09 15:08:12 +00002047
Douglas Gregor925296b2011-07-19 16:10:42 +00002048 // We need to find the common ancestor. The only way of doing this is to
2049 // build the complete include chain for one and then walking up the chain
2050 // of the other looking for a match.
2051 // We use a map from FileID to Offset to store the chain. Easier than writing
2052 // a custom set hash info that only depends on the first part of a pair.
Argyrios Kyrtzidis37613a92013-04-13 01:03:57 +00002053 typedef llvm::SmallDenseMap<FileID, unsigned, 16> LocSet;
Douglas Gregor925296b2011-07-19 16:10:42 +00002054 LocSet LChain;
Chris Lattner06821c92010-05-07 05:51:13 +00002055 do {
Douglas Gregor925296b2011-07-19 16:10:42 +00002056 LChain.insert(LOffs);
2057 // We catch the case where LOffs is in a file included by ROffs and
2058 // quit early. The other way round unfortunately remains suboptimal.
2059 } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
2060 LocSet::iterator I;
2061 while((I = LChain.find(ROffs.first)) == LChain.end()) {
2062 if (MoveUpIncludeHierarchy(ROffs, *this))
2063 break; // Met at topmost file.
2064 }
2065 if (I != LChain.end())
2066 LOffs = *I;
Mike Stump11289f42009-09-09 15:08:12 +00002067
Chris Lattner06821c92010-05-07 05:51:13 +00002068 // If we exited because we found a nearest common ancestor, compare the
2069 // locations within the common file and cache them.
2070 if (LOffs.first == ROffs.first) {
2071 IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
2072 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00002073 }
Mike Stump11289f42009-09-09 15:08:12 +00002074
Joerg Sonnenberger1d3b4312015-03-16 17:54:54 +00002075 // If we arrived here, the location is either in a built-ins buffer or
2076 // associated with global inline asm. PR5662 and PR22576 are examples.
2077
Douglas Gregor925296b2011-07-19 16:10:42 +00002078 // Clear the lookup cache, it depends on a common location.
Argyrios Kyrtzidisac199bf2011-08-17 00:31:18 +00002079 IsBeforeInTUCache.clear();
Mehdi Amini99d1b292016-10-01 16:38:28 +00002080 StringRef LB = getBuffer(LOffs.first)->getBufferIdentifier();
2081 StringRef RB = getBuffer(ROffs.first)->getBufferIdentifier();
2082 bool LIsBuiltins = LB == "<built-in>";
2083 bool RIsBuiltins = RB == "<built-in>";
Joerg Sonnenberger1d3b4312015-03-16 17:54:54 +00002084 // Sort built-in before non-built-in.
2085 if (LIsBuiltins || RIsBuiltins) {
2086 if (LIsBuiltins != RIsBuiltins)
2087 return LIsBuiltins;
2088 // Both are in built-in buffers, but from different files. We just claim that
2089 // lower IDs come first.
2090 return LOffs.first < ROffs.first;
2091 }
Mehdi Amini99d1b292016-10-01 16:38:28 +00002092 bool LIsAsm = LB == "<inline asm>";
2093 bool RIsAsm = RB == "<inline asm>";
Joerg Sonnenberger1d3b4312015-03-16 17:54:54 +00002094 // Sort assembler after built-ins, but before the rest.
2095 if (LIsAsm || RIsAsm) {
2096 if (LIsAsm != RIsAsm)
2097 return RIsAsm;
2098 assert(LOffs.first == ROffs.first);
2099 return false;
2100 }
Mehdi Amini99d1b292016-10-01 16:38:28 +00002101 bool LIsScratch = LB == "<scratch space>";
2102 bool RIsScratch = RB == "<scratch space>";
Yury Gribov154e57f2016-01-28 09:28:18 +00002103 // Sort scratch after inline asm, but before the rest.
2104 if (LIsScratch || RIsScratch) {
2105 if (LIsScratch != RIsScratch)
2106 return LIsScratch;
2107 return LOffs.second < ROffs.second;
2108 }
Joerg Sonnenberger1d3b4312015-03-16 17:54:54 +00002109 llvm_unreachable("Unsortable locations found");
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00002110}
Chris Lattner4fa23622009-01-26 00:43:02 +00002111
Chris Lattner22eb9722006-06-18 05:43:12 +00002112void SourceManager::PrintStats() const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +00002113 llvm::errs() << "\n*** Source Manager Stats:\n";
2114 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
2115 << " mem buffers mapped.\n";
Douglas Gregor925296b2011-07-19 16:10:42 +00002116 llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
Ted Kremenek43e0c4a2011-07-27 18:41:16 +00002117 << llvm::capacity_in_bytes(LocalSLocEntryTable)
Argyrios Kyrtzidis2cc62092011-07-07 03:40:24 +00002118 << " bytes of capacity), "
Douglas Gregor925296b2011-07-19 16:10:42 +00002119 << NextLocalOffset << "B of Sloc address space used.\n";
2120 llvm::errs() << LoadedSLocEntryTable.size()
2121 << " loaded SLocEntries allocated, "
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00002122 << MaxLoadedOffset - CurrentLoadedOffset
Douglas Gregor925296b2011-07-19 16:10:42 +00002123 << "B of Sloc address space used.\n";
2124
Chris Lattner22eb9722006-06-18 05:43:12 +00002125 unsigned NumLineNumsComputed = 0;
2126 unsigned NumFileBytesMapped = 0;
Chris Lattnerc8233df2009-02-03 07:30:45 +00002127 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
Craig Topperf1186c52014-05-08 06:41:40 +00002128 NumLineNumsComputed += I->second->SourceLineCache != nullptr;
Chris Lattnerc8233df2009-02-03 07:30:45 +00002129 NumFileBytesMapped += I->second->getSizeBytesMapped();
Chris Lattner22eb9722006-06-18 05:43:12 +00002130 }
Argyrios Kyrtzidis4bdd6aa2011-09-26 08:01:50 +00002131 unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
Mike Stump11289f42009-09-09 15:08:12 +00002132
Benjamin Kramer89b422c2009-08-23 12:08:50 +00002133 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00002134 << NumLineNumsComputed << " files with line #'s computed, "
2135 << NumMacroArgsComputed << " files with macro args computed.\n";
Benjamin Kramer89b422c2009-08-23 12:08:50 +00002136 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
2137 << NumBinaryProbes << " binary.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +00002138}
Douglas Gregor258ae542009-04-27 06:38:32 +00002139
Richard Smith03a06dd2015-08-13 00:45:11 +00002140LLVM_DUMP_METHOD void SourceManager::dump() const {
2141 llvm::raw_ostream &out = llvm::errs();
2142
2143 auto DumpSLocEntry = [&](int ID, const SrcMgr::SLocEntry &Entry,
2144 llvm::Optional<unsigned> NextStart) {
2145 out << "SLocEntry <FileID " << ID << "> " << (Entry.isFile() ? "file" : "expansion")
2146 << " <SourceLocation " << Entry.getOffset() << ":";
2147 if (NextStart)
2148 out << *NextStart << ">\n";
2149 else
2150 out << "???\?>\n";
2151 if (Entry.isFile()) {
2152 auto &FI = Entry.getFile();
2153 if (FI.NumCreatedFIDs)
2154 out << " covers <FileID " << ID << ":" << int(ID + FI.NumCreatedFIDs)
2155 << ">\n";
2156 if (FI.getIncludeLoc().isValid())
2157 out << " included from " << FI.getIncludeLoc().getOffset() << "\n";
2158 if (auto *CC = FI.getContentCache()) {
2159 out << " for " << (CC->OrigEntry ? CC->OrigEntry->getName() : "<none>")
2160 << "\n";
2161 if (CC->BufferOverridden)
2162 out << " contents overridden\n";
2163 if (CC->ContentsEntry != CC->OrigEntry) {
2164 out << " contents from "
2165 << (CC->ContentsEntry ? CC->ContentsEntry->getName() : "<none>")
2166 << "\n";
2167 }
2168 }
2169 } else {
2170 auto &EI = Entry.getExpansion();
2171 out << " spelling from " << EI.getSpellingLoc().getOffset() << "\n";
2172 out << " macro " << (EI.isMacroArgExpansion() ? "arg" : "body")
2173 << " range <" << EI.getExpansionLocStart().getOffset() << ":"
2174 << EI.getExpansionLocEnd().getOffset() << ">\n";
2175 }
2176 };
2177
2178 // Dump local SLocEntries.
2179 for (unsigned ID = 0, NumIDs = LocalSLocEntryTable.size(); ID != NumIDs; ++ID) {
2180 DumpSLocEntry(ID, LocalSLocEntryTable[ID],
2181 ID == NumIDs - 1 ? NextLocalOffset
2182 : LocalSLocEntryTable[ID + 1].getOffset());
2183 }
2184 // Dump loaded SLocEntries.
2185 llvm::Optional<unsigned> NextStart;
2186 for (unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
2187 int ID = -(int)Index - 2;
2188 if (SLocEntryLoaded[Index]) {
2189 DumpSLocEntry(ID, LoadedSLocEntryTable[Index], NextStart);
2190 NextStart = LoadedSLocEntryTable[Index].getOffset();
2191 } else {
2192 NextStart = None;
2193 }
2194 }
2195}
2196
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00002197ExternalSLocEntrySource::~ExternalSLocEntrySource() { }
Ted Kremenek8d587902011-04-28 20:36:42 +00002198
2199/// Return the amount of memory used by memory buffers, breaking down
2200/// by heap-backed versus mmap'ed memory.
2201SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
2202 size_t malloc_bytes = 0;
2203 size_t mmap_bytes = 0;
2204
2205 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
2206 if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
2207 switch (MemBufferInfos[i]->getMemoryBufferKind()) {
2208 case llvm::MemoryBuffer::MemoryBuffer_MMap:
2209 mmap_bytes += sized_mapped;
2210 break;
2211 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
2212 malloc_bytes += sized_mapped;
2213 break;
2214 }
2215
2216 return MemoryBufferSizes(malloc_bytes, mmap_bytes);
2217}
2218
Ted Kremenek120992a2011-07-26 23:46:06 +00002219size_t SourceManager::getDataStructureSizes() const {
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +00002220 size_t size = llvm::capacity_in_bytes(MemBufferInfos)
Ted Kremenek43e0c4a2011-07-27 18:41:16 +00002221 + llvm::capacity_in_bytes(LocalSLocEntryTable)
2222 + llvm::capacity_in_bytes(LoadedSLocEntryTable)
2223 + llvm::capacity_in_bytes(SLocEntryLoaded)
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +00002224 + llvm::capacity_in_bytes(FileInfos);
2225
2226 if (OverriddenFilesInfo)
2227 size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);
2228
2229 return size;
Ted Kremenek120992a2011-07-26 23:46:06 +00002230}