blob: 92f473a3808213626fd97ed51da7e17b9929c7b1 [file] [log] [blame]
Chris Lattner22eb9722006-06-18 05:43:12 +00001//===--- SourceManager.cpp - Track and cache source files -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner22eb9722006-06-18 05:43:12 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the SourceManager interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Basic/SourceManager.h"
Douglas Gregor802b7762010-03-15 22:54:52 +000015#include "clang/Basic/Diagnostic.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000016#include "clang/Basic/FileManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregore6642762011-02-03 17:17:35 +000018#include "llvm/ADT/Optional.h"
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +000019#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "llvm/ADT/StringSwitch.h"
21#include "llvm/Support/Capacity.h"
Chris Lattner8996fff2007-07-24 05:57:19 +000022#include "llvm/Support/Compiler.h"
Chris Lattner739e7392007-04-29 07:12:06 +000023#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000024#include "llvm/Support/Path.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "llvm/Support/raw_ostream.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000026#include <algorithm>
Douglas Gregore0fbb832010-03-16 00:06:06 +000027#include <cstring>
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include <string>
Douglas Gregor802b7762010-03-15 22:54:52 +000029
Chris Lattner22eb9722006-06-18 05:43:12 +000030using namespace clang;
Chris Lattner5f4b1ff2006-06-20 05:02:40 +000031using namespace SrcMgr;
Chris Lattner23b7eb62007-06-15 23:05:46 +000032using llvm::MemoryBuffer;
Chris Lattner22eb9722006-06-18 05:43:12 +000033
Chris Lattner153a0f12009-02-04 00:40:31 +000034//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +000035// SourceManager Helper Classes
Chris Lattner153a0f12009-02-04 00:40:31 +000036//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +000037
Ted Kremenekc08bca62007-10-30 21:08:08 +000038ContentCache::~ContentCache() {
Douglas Gregor3f4bea02010-07-26 21:36:20 +000039 if (shouldFreeBuffer())
40 delete Buffer.getPointer();
Chris Lattner22eb9722006-06-18 05:43:12 +000041}
42
Chandler Carruth64ee7822011-07-26 05:17:23 +000043/// getSizeBytesMapped - Returns the number of bytes actually mapped for this
44/// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
Ted Kremenek12c2af42009-01-06 01:55:26 +000045unsigned ContentCache::getSizeBytesMapped() const {
Douglas Gregor82752ec2010-03-16 22:53:51 +000046 return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
Ted Kremenek12c2af42009-01-06 01:55:26 +000047}
48
Ted Kremenek8d587902011-04-28 20:36:42 +000049/// Returns the kind of memory used to back the memory buffer for
50/// this content cache. This is used for performance analysis.
51llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
52 assert(Buffer.getPointer());
53
54 // Should be unreachable, but keep for sanity.
55 if (!Buffer.getPointer())
56 return llvm::MemoryBuffer::MemoryBuffer_Malloc;
David Blaikie66cc07b2014-06-27 17:40:03 +000057
58 llvm::MemoryBuffer *buf = Buffer.getPointer();
Ted Kremenek8d587902011-04-28 20:36:42 +000059 return buf->getBufferKind();
60}
61
Ted Kremenek12c2af42009-01-06 01:55:26 +000062/// getSize - Returns the size of the content encapsulated by this ContentCache.
63/// This can be the size of the source file or the size of an arbitrary
64/// scratch buffer. If the ContentCache encapsulates a source file, that
Douglas Gregor53ad6b92009-12-02 06:49:09 +000065/// file is not lazily brought in from disk to satisfy this query.
Ted Kremenek12c2af42009-01-06 01:55:26 +000066unsigned ContentCache::getSize() const {
Douglas Gregor82752ec2010-03-16 22:53:51 +000067 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +000068 : (unsigned) ContentsEntry->getSize();
Ted Kremenek12c2af42009-01-06 01:55:26 +000069}
70
David Blaikie66cc07b2014-06-27 17:40:03 +000071void ContentCache::replaceBuffer(llvm::MemoryBuffer *B, bool DoNotFree) {
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +000072 if (B && B == Buffer.getPointer()) {
Argyrios Kyrtzidiscc6107d2011-12-10 01:38:26 +000073 assert(0 && "Replacing with the same buffer");
74 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
75 return;
76 }
Douglas Gregor53ad6b92009-12-02 06:49:09 +000077
Douglas Gregor3f4bea02010-07-26 21:36:20 +000078 if (shouldFreeBuffer())
79 delete Buffer.getPointer();
Douglas Gregor82752ec2010-03-16 22:53:51 +000080 Buffer.setPointer(B);
Douglas Gregor3f4bea02010-07-26 21:36:20 +000081 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
Douglas Gregor53ad6b92009-12-02 06:49:09 +000082}
83
David Blaikie66cc07b2014-06-27 17:40:03 +000084llvm::MemoryBuffer *ContentCache::getBuffer(DiagnosticsEngine &Diag,
85 const SourceManager &SM,
86 SourceLocation Loc,
87 bool *Invalid) const {
Chris Lattner5631b052010-11-23 08:50:03 +000088 // Lazily create the Buffer for ContentCaches that wrap files. If we already
Chris Lattner57540c52011-04-15 05:22:18 +000089 // computed it, just return what we have.
Craig Topperf1186c52014-05-08 06:41:40 +000090 if (Buffer.getPointer() || !ContentsEntry) {
Chris Lattner5631b052010-11-23 08:50:03 +000091 if (Invalid)
92 *Invalid = isBufferInvalid();
Chris Lattner8fbe98b2010-04-20 18:14:03 +000093
Chris Lattner5631b052010-11-23 08:50:03 +000094 return Buffer.getPointer();
95 }
Benjamin Kramer5a3f1cf2010-11-18 12:46:39 +000096
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +000097 bool isVolatile = SM.userFilesAreVolatile() && !IsSystemFile;
Benjamin Kramera8857962014-10-26 22:44:13 +000098 auto BufferOrError =
99 SM.getFileManager().getBufferForFile(ContentsEntry, isVolatile);
Chris Lattner5631b052010-11-23 08:50:03 +0000100
101 // If we were unable to open the file, then we are in an inconsistent
102 // situation where the content cache referenced a file which no longer
103 // exists. Most likely, we were using a stat cache with an invalid entry but
104 // the file could also have been removed during processing. Since we can't
105 // really deal with this situation, just create an empty buffer.
106 //
107 // FIXME: This is definitely not ideal, but our immediate clients can't
108 // currently handle returning a null entry here. Ideally we should detect
109 // that we are in an inconsistent situation and error out as quickly as
110 // possible.
Benjamin Kramera8857962014-10-26 22:44:13 +0000111 if (!BufferOrError) {
Craig Topperbf3e3272014-08-30 16:55:52 +0000112 StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
Benjamin Kramerc7dd5992015-04-06 17:45:11 +0000113 Buffer.setPointer(MemoryBuffer::getNewUninitMemBuffer(
114 ContentsEntry->getSize(), "<invalid>").release());
Chris Lattner5631b052010-11-23 08:50:03 +0000115 char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart());
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000116 for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
Chris Lattner5631b052010-11-23 08:50:03 +0000117 Ptr[i] = FillStr[i % FillStr.size()];
118
119 if (Diag.isDiagnosticInFlight())
Benjamin Kramera8857962014-10-26 22:44:13 +0000120 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
121 ContentsEntry->getName(),
122 BufferOrError.getError().message());
123 else
Chris Lattner5631b052010-11-23 08:50:03 +0000124 Diag.Report(Loc, diag::err_cannot_open_file)
Benjamin Kramera8857962014-10-26 22:44:13 +0000125 << ContentsEntry->getName() << BufferOrError.getError().message();
Chris Lattner5631b052010-11-23 08:50:03 +0000126
127 Buffer.setInt(Buffer.getInt() | InvalidFlag);
128
129 if (Invalid) *Invalid = true;
130 return Buffer.getPointer();
131 }
Benjamin Kramera8857962014-10-26 22:44:13 +0000132
133 Buffer.setPointer(BufferOrError->release());
134
Chris Lattner5631b052010-11-23 08:50:03 +0000135 // Check that the file's size is the same as in the file entry (which may
136 // have come from a stat cache).
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000137 if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) {
Chris Lattner5631b052010-11-23 08:50:03 +0000138 if (Diag.isDiagnosticInFlight())
139 Diag.SetDelayedDiagnostic(diag::err_file_modified,
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000140 ContentsEntry->getName());
Chris Lattner5631b052010-11-23 08:50:03 +0000141 else
142 Diag.Report(Loc, diag::err_file_modified)
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000143 << ContentsEntry->getName();
Chris Lattner5631b052010-11-23 08:50:03 +0000144
145 Buffer.setInt(Buffer.getInt() | InvalidFlag);
146 if (Invalid) *Invalid = true;
147 return Buffer.getPointer();
148 }
Eric Christopher7f36a792011-04-09 00:01:04 +0000149
Chris Lattner5631b052010-11-23 08:50:03 +0000150 // If the buffer is valid, check to see if it has a UTF Byte Order Mark
Eric Christopher7f36a792011-04-09 00:01:04 +0000151 // (BOM). We only support UTF-8 with and without a BOM right now. See
Chris Lattner5631b052010-11-23 08:50:03 +0000152 // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000153 StringRef BufStr = Buffer.getPointer()->getBuffer();
Eric Christopher7f36a792011-04-09 00:01:04 +0000154 const char *InvalidBOM = llvm::StringSwitch<const char *>(BufStr)
Chris Lattner5631b052010-11-23 08:50:03 +0000155 .StartsWith("\xFE\xFF", "UTF-16 (BE)")
156 .StartsWith("\xFF\xFE", "UTF-16 (LE)")
157 .StartsWith("\x00\x00\xFE\xFF", "UTF-32 (BE)")
158 .StartsWith("\xFF\xFE\x00\x00", "UTF-32 (LE)")
159 .StartsWith("\x2B\x2F\x76", "UTF-7")
160 .StartsWith("\xF7\x64\x4C", "UTF-1")
161 .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
162 .StartsWith("\x0E\xFE\xFF", "SDSU")
163 .StartsWith("\xFB\xEE\x28", "BOCU-1")
164 .StartsWith("\x84\x31\x95\x33", "GB-18030")
Craig Topperf1186c52014-05-08 06:41:40 +0000165 .Default(nullptr);
Chris Lattner5631b052010-11-23 08:50:03 +0000166
Eric Christopher7f36a792011-04-09 00:01:04 +0000167 if (InvalidBOM) {
Chris Lattner5631b052010-11-23 08:50:03 +0000168 Diag.Report(Loc, diag::err_unsupported_bom)
Eric Christopher7f36a792011-04-09 00:01:04 +0000169 << InvalidBOM << ContentsEntry->getName();
Chris Lattner5631b052010-11-23 08:50:03 +0000170 Buffer.setInt(Buffer.getInt() | InvalidFlag);
Ted Kremenek763ea552009-01-06 22:43:04 +0000171 }
Douglas Gregor802b7762010-03-15 22:54:52 +0000172
Douglas Gregor82752ec2010-03-16 22:53:51 +0000173 if (Invalid)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000174 *Invalid = isBufferInvalid();
Douglas Gregor82752ec2010-03-16 22:53:51 +0000175
176 return Buffer.getPointer();
Ted Kremenek12c2af42009-01-06 01:55:26 +0000177}
178
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000179unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
David Blaikie13156b62014-11-19 03:06:06 +0000180 auto IterBool =
181 FilenameIDs.insert(std::make_pair(Name, FilenamesByID.size()));
182 if (IterBool.second)
183 FilenamesByID.push_back(&*IterBool.first);
184 return IterBool.first->second;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000185}
186
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000187/// AddLineNote - Add a line note to the line table that indicates that there
James Dennett88b71e42012-06-15 21:28:23 +0000188/// is a \#line at the specified FID/Offset location which changes the presumed
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000189/// location to LineNo/FilenameID.
Douglas Gregor02c2dbf2012-06-08 16:40:28 +0000190void LineTableInfo::AddLineNote(FileID FID, unsigned Offset,
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000191 unsigned LineNo, int FilenameID) {
Chris Lattner153a0f12009-02-04 00:40:31 +0000192 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump11289f42009-09-09 15:08:12 +0000193
Chris Lattner153a0f12009-02-04 00:40:31 +0000194 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
195 "Adding line entries out of order!");
Mike Stump11289f42009-09-09 15:08:12 +0000196
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000197 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
Chris Lattner1c967782009-02-04 06:25:26 +0000198 unsigned IncludeOffset = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000199
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000200 if (!Entries.empty()) {
201 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
202 // that we are still in "foo.h".
203 if (FilenameID == -1)
204 FilenameID = Entries.back().FilenameID;
Mike Stump11289f42009-09-09 15:08:12 +0000205
Chris Lattner1c967782009-02-04 06:25:26 +0000206 // If we are after a line marker that switched us to system header mode, or
207 // that set #include information, preserve it.
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000208 Kind = Entries.back().FileKind;
Chris Lattner1c967782009-02-04 06:25:26 +0000209 IncludeOffset = Entries.back().IncludeOffset;
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000210 }
Mike Stump11289f42009-09-09 15:08:12 +0000211
Chris Lattner1c967782009-02-04 06:25:26 +0000212 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
213 IncludeOffset));
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000214}
215
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000216/// AddLineNote This is the same as the previous version of AddLineNote, but is
217/// used for GNU line markers. If EntryExit is 0, then this doesn't change the
James Dennett87a2acf2012-06-17 03:22:59 +0000218/// presumed \#include stack. If it is 1, this is a file entry, if it is 2 then
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000219/// this is a file exit. FileKind specifies whether this is a system header or
220/// extern C system header.
Douglas Gregor02c2dbf2012-06-08 16:40:28 +0000221void LineTableInfo::AddLineNote(FileID FID, unsigned Offset,
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000222 unsigned LineNo, int FilenameID,
223 unsigned EntryExit,
224 SrcMgr::CharacteristicKind FileKind) {
225 assert(FilenameID != -1 && "Unspecified filename should use other accessor");
Mike Stump11289f42009-09-09 15:08:12 +0000226
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000227 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump11289f42009-09-09 15:08:12 +0000228
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000229 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
230 "Adding line entries out of order!");
231
Chris Lattner1c967782009-02-04 06:25:26 +0000232 unsigned IncludeOffset = 0;
233 if (EntryExit == 0) { // No #include stack change.
234 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
235 } else if (EntryExit == 1) {
236 IncludeOffset = Offset-1;
237 } else if (EntryExit == 2) {
238 assert(!Entries.empty() && Entries.back().IncludeOffset &&
239 "PPDirectives should have caught case when popping empty include stack");
Mike Stump11289f42009-09-09 15:08:12 +0000240
Chris Lattner1c967782009-02-04 06:25:26 +0000241 // Get the include loc of the last entries' include loc as our include loc.
242 IncludeOffset = 0;
243 if (const LineEntry *PrevEntry =
244 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
245 IncludeOffset = PrevEntry->IncludeOffset;
246 }
Mike Stump11289f42009-09-09 15:08:12 +0000247
Chris Lattner1c967782009-02-04 06:25:26 +0000248 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
249 IncludeOffset));
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000250}
251
252
Chris Lattnerd4293922009-02-04 01:55:42 +0000253/// FindNearestLineEntry - Find the line entry nearest to FID that is before
254/// it. If there is no line entry before Offset in FID, return null.
Douglas Gregor02c2dbf2012-06-08 16:40:28 +0000255const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID,
Chris Lattnerd4293922009-02-04 01:55:42 +0000256 unsigned Offset) {
257 const std::vector<LineEntry> &Entries = LineEntries[FID];
258 assert(!Entries.empty() && "No #line entries for this FID after all!");
259
Chris Lattner334a2ad2009-02-04 04:46:59 +0000260 // It is very common for the query to be after the last #line, check this
261 // first.
262 if (Entries.back().FileOffset <= Offset)
263 return &Entries.back();
Chris Lattnerd4293922009-02-04 01:55:42 +0000264
Chris Lattner334a2ad2009-02-04 04:46:59 +0000265 // Do a binary search to find the maximal element that is still before Offset.
266 std::vector<LineEntry>::const_iterator I =
267 std::upper_bound(Entries.begin(), Entries.end(), Offset);
Craig Topperf1186c52014-05-08 06:41:40 +0000268 if (I == Entries.begin()) return nullptr;
Chris Lattner334a2ad2009-02-04 04:46:59 +0000269 return &*--I;
Chris Lattnerd4293922009-02-04 01:55:42 +0000270}
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000271
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000272/// \brief Add a new line entry that has already been encoded into
273/// the internal representation of the line table.
Douglas Gregor02c2dbf2012-06-08 16:40:28 +0000274void LineTableInfo::AddEntry(FileID FID,
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000275 const std::vector<LineEntry> &Entries) {
276 LineEntries[FID] = Entries;
277}
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000278
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000279/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
Mike Stump11289f42009-09-09 15:08:12 +0000280///
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000281unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
Vedant Kumar5eeeab72015-11-12 00:11:19 +0000282 return getLineTable().getLineTableFilenameID(Name);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000283}
284
285
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000286/// AddLineNote - Add a line note to the line table for the FileID and offset
287/// specified by Loc. If FilenameID is -1, it is considered to be
288/// unspecified.
289void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
290 int FilenameID) {
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000291 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000292
Douglas Gregor49f754f2011-04-20 00:21:03 +0000293 bool Invalid = false;
294 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
295 if (!Entry.isFile() || Invalid)
296 return;
297
298 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000299
300 // Remember that this file has #line directives now if it doesn't already.
301 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump11289f42009-09-09 15:08:12 +0000302
Vedant Kumar5eeeab72015-11-12 00:11:19 +0000303 getLineTable().AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID);
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000304}
305
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000306/// AddLineNote - Add a GNU line marker to the line table.
307void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
308 int FilenameID, bool IsFileEntry,
309 bool IsFileExit, bool IsSystemHeader,
310 bool IsExternCHeader) {
311 // If there is no filename and no flags, this is treated just like a #line,
312 // which does not change the flags of the previous line marker.
313 if (FilenameID == -1) {
314 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
315 "Can't set flags without setting the filename!");
316 return AddLineNote(Loc, LineNo, FilenameID);
317 }
Mike Stump11289f42009-09-09 15:08:12 +0000318
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000319 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregor49f754f2011-04-20 00:21:03 +0000320
321 bool Invalid = false;
322 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
323 if (!Entry.isFile() || Invalid)
324 return;
325
326 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
Mike Stump11289f42009-09-09 15:08:12 +0000327
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000328 // Remember that this file has #line directives now if it doesn't already.
329 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump11289f42009-09-09 15:08:12 +0000330
Vedant Kumar5eeeab72015-11-12 00:11:19 +0000331 (void) getLineTable();
Mike Stump11289f42009-09-09 15:08:12 +0000332
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000333 SrcMgr::CharacteristicKind FileKind;
334 if (IsExternCHeader)
335 FileKind = SrcMgr::C_ExternCSystem;
336 else if (IsSystemHeader)
337 FileKind = SrcMgr::C_System;
338 else
339 FileKind = SrcMgr::C_User;
Mike Stump11289f42009-09-09 15:08:12 +0000340
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000341 unsigned EntryExit = 0;
342 if (IsFileEntry)
343 EntryExit = 1;
344 else if (IsFileExit)
345 EntryExit = 2;
Mike Stump11289f42009-09-09 15:08:12 +0000346
Douglas Gregor02c2dbf2012-06-08 16:40:28 +0000347 LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000348 EntryExit, FileKind);
349}
350
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000351LineTableInfo &SourceManager::getLineTable() {
Craig Topperf1186c52014-05-08 06:41:40 +0000352 if (!LineTable)
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000353 LineTable = new LineTableInfo();
354 return *LineTable;
355}
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000356
Chris Lattner153a0f12009-02-04 00:40:31 +0000357//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +0000358// Private 'Create' methods.
Chris Lattner153a0f12009-02-04 00:40:31 +0000359//===----------------------------------------------------------------------===//
Ted Kremenek12c2af42009-01-06 01:55:26 +0000360
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000361SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
362 bool UserFilesAreVolatile)
Argyrios Kyrtzidis97d3a382011-03-08 23:35:24 +0000363 : Diag(Diag), FileMgr(FileMgr), OverridenFilesKeepOriginalName(true),
Richard Smith919ce232015-11-24 04:22:21 +0000364 UserFilesAreVolatile(UserFilesAreVolatile), FilesAreTransient(false),
Craig Topperf1186c52014-05-08 06:41:40 +0000365 ExternalSLocEntries(nullptr), LineTable(nullptr), NumLinearScans(0),
Rafael Espindolae0f6d882014-08-18 18:33:41 +0000366 NumBinaryProbes(0) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000367 clearIDTables();
368 Diag.setSourceManager(this);
369}
370
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000371SourceManager::~SourceManager() {
372 delete LineTable;
Mike Stump11289f42009-09-09 15:08:12 +0000373
Chris Lattnerc8233df2009-02-03 07:30:45 +0000374 // Delete FileEntry objects corresponding to content caches. Since the actual
375 // content cache objects are bump pointer allocated, we just have to run the
376 // dtors, but we call the deallocate method for completeness.
377 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
Argyrios Kyrtzidisaf41b3f2011-12-15 23:37:55 +0000378 if (MemBufferInfos[i]) {
379 MemBufferInfos[i]->~ContentCache();
380 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
381 }
Chris Lattnerc8233df2009-02-03 07:30:45 +0000382 }
383 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
384 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
Argyrios Kyrtzidisaf41b3f2011-12-15 23:37:55 +0000385 if (I->second) {
386 I->second->~ContentCache();
387 ContentCacheAlloc.Deallocate(I->second);
388 }
Chris Lattnerc8233df2009-02-03 07:30:45 +0000389 }
Argyrios Kyrtzidis4bdd6aa2011-09-26 08:01:50 +0000390
Reid Kleckner588c9372014-02-19 23:44:52 +0000391 llvm::DeleteContainerSeconds(MacroArgsCacheMap);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000392}
393
394void SourceManager::clearIDTables() {
395 MainFileID = FileID();
Douglas Gregor925296b2011-07-19 16:10:42 +0000396 LocalSLocEntryTable.clear();
397 LoadedSLocEntryTable.clear();
398 SLocEntryLoaded.clear();
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000399 LastLineNoFileIDQuery = FileID();
Craig Topperf1186c52014-05-08 06:41:40 +0000400 LastLineNoContentCache = nullptr;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000401 LastFileIDLookup = FileID();
Mike Stump11289f42009-09-09 15:08:12 +0000402
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000403 if (LineTable)
404 LineTable->clear();
Mike Stump11289f42009-09-09 15:08:12 +0000405
Chandler Carruth64ee7822011-07-26 05:17:23 +0000406 // Use up FileID #0 as an invalid expansion.
Douglas Gregor925296b2011-07-19 16:10:42 +0000407 NextLocalOffset = 0;
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +0000408 CurrentLoadedOffset = MaxLoadedOffset;
Chandler Carruth115b0772011-07-26 03:03:05 +0000409 createExpansionLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000410}
411
Chris Lattner4fa23622009-01-26 00:43:02 +0000412/// getOrCreateContentCache - Create or return a cached ContentCache for the
413/// specified file.
414const ContentCache *
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000415SourceManager::getOrCreateContentCache(const FileEntry *FileEnt,
416 bool isSystemFile) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000417 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump11289f42009-09-09 15:08:12 +0000418
Chris Lattner22eb9722006-06-18 05:43:12 +0000419 // Do we already have information about this file?
Chris Lattnerc8233df2009-02-03 07:30:45 +0000420 ContentCache *&Entry = FileInfos[FileEnt];
421 if (Entry) return Entry;
Mike Stump11289f42009-09-09 15:08:12 +0000422
Chandler Carruth47c48082014-04-15 21:34:12 +0000423 // Nope, create a new Cache entry.
424 Entry = ContentCacheAlloc.Allocate<ContentCache>();
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000425
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +0000426 if (OverriddenFilesInfo) {
427 // If the file contents are overridden with contents from another file,
428 // pass that file to ContentCache.
429 llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
430 overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
431 if (overI == OverriddenFilesInfo->OverriddenFiles.end())
432 new (Entry) ContentCache(FileEnt);
433 else
434 new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
435 : overI->second,
436 overI->second);
437 } else {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000438 new (Entry) ContentCache(FileEnt);
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +0000439 }
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000440
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000441 Entry->IsSystemFile = isSystemFile;
Richard Smitha8cfffa2015-11-26 02:04:16 +0000442 Entry->IsTransient = FilesAreTransient;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000443
Chris Lattnerc8233df2009-02-03 07:30:45 +0000444 return Entry;
Chris Lattner22eb9722006-06-18 05:43:12 +0000445}
446
447
Ted Kremenek08bed092007-10-31 17:53:38 +0000448/// createMemBufferContentCache - Create a new ContentCache for the specified
449/// memory buffer. This does no caching.
David Blaikie50a5f972014-08-29 07:59:55 +0000450const ContentCache *SourceManager::createMemBufferContentCache(
451 std::unique_ptr<llvm::MemoryBuffer> Buffer) {
Chandler Carruth47c48082014-04-15 21:34:12 +0000452 // Add a new ContentCache to the MemBufferInfos list and return it.
453 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
Chris Lattnerc8233df2009-02-03 07:30:45 +0000454 new (Entry) ContentCache();
455 MemBufferInfos.push_back(Entry);
David Blaikie50a5f972014-08-29 07:59:55 +0000456 Entry->setBuffer(std::move(Buffer));
Chris Lattnerc8233df2009-02-03 07:30:45 +0000457 return Entry;
Chris Lattner22eb9722006-06-18 05:43:12 +0000458}
459
Argyrios Kyrtzidis969fdfd2012-02-20 23:58:07 +0000460const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
461 bool *Invalid) const {
462 assert(!SLocEntryLoaded[Index]);
463 if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
464 if (Invalid)
465 *Invalid = true;
466 // If the file of the SLocEntry changed we could still have loaded it.
467 if (!SLocEntryLoaded[Index]) {
468 // Try to recover; create a SLocEntry so the rest of clang can handle it.
469 LoadedSLocEntryTable[Index] = SLocEntry::get(0,
470 FileInfo::get(SourceLocation(),
471 getFakeContentCacheForRecovery(),
472 SrcMgr::C_User));
473 }
474 }
475
476 return LoadedSLocEntryTable[Index];
477}
478
Douglas Gregor925296b2011-07-19 16:10:42 +0000479std::pair<int, unsigned>
480SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
481 unsigned TotalSize) {
482 assert(ExternalSLocEntries && "Don't have an external sloc source");
Richard Smith78d81ec2015-08-12 22:25:24 +0000483 // Make sure we're not about to run out of source locations.
484 if (CurrentLoadedOffset - TotalSize < NextLocalOffset)
485 return std::make_pair(0, 0);
Douglas Gregor925296b2011-07-19 16:10:42 +0000486 LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
487 SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
488 CurrentLoadedOffset -= TotalSize;
Douglas Gregor925296b2011-07-19 16:10:42 +0000489 int ID = LoadedSLocEntryTable.size();
490 return std::make_pair(-ID - 1, CurrentLoadedOffset);
Douglas Gregor0bc12932009-04-27 21:28:04 +0000491}
492
Douglas Gregor49f754f2011-04-20 00:21:03 +0000493/// \brief As part of recovering from missing or changed content, produce a
494/// fake, non-empty buffer.
David Blaikie66cc07b2014-06-27 17:40:03 +0000495llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const {
Douglas Gregor49f754f2011-04-20 00:21:03 +0000496 if (!FakeBufferForRecovery)
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000497 FakeBufferForRecovery =
498 llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
Rafael Espindolae0f6d882014-08-18 18:33:41 +0000499
500 return FakeBufferForRecovery.get();
Douglas Gregor49f754f2011-04-20 00:21:03 +0000501}
Douglas Gregor258ae542009-04-27 06:38:32 +0000502
Argyrios Kyrtzidis969fdfd2012-02-20 23:58:07 +0000503/// \brief As part of recovering from missing or changed content, produce a
504/// fake content cache.
505const SrcMgr::ContentCache *
506SourceManager::getFakeContentCacheForRecovery() const {
507 if (!FakeContentCacheForRecovery) {
Rafael Espindolae0f6d882014-08-18 18:33:41 +0000508 FakeContentCacheForRecovery = llvm::make_unique<SrcMgr::ContentCache>();
Argyrios Kyrtzidis969fdfd2012-02-20 23:58:07 +0000509 FakeContentCacheForRecovery->replaceBuffer(getFakeBufferForRecovery(),
510 /*DoNotFree=*/true);
511 }
Rafael Espindolae0f6d882014-08-18 18:33:41 +0000512 return FakeContentCacheForRecovery.get();
Argyrios Kyrtzidis969fdfd2012-02-20 23:58:07 +0000513}
514
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000515/// \brief Returns the previous in-order FileID or an invalid FileID if there
516/// is no previous one.
517FileID SourceManager::getPreviousFileID(FileID FID) const {
518 if (FID.isInvalid())
519 return FileID();
520
521 int ID = FID.ID;
522 if (ID == -1)
523 return FileID();
524
525 if (ID > 0) {
526 if (ID-1 == 0)
527 return FileID();
528 } else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {
529 return FileID();
530 }
531
532 return FileID::get(ID-1);
533}
534
535/// \brief Returns the next in-order FileID or an invalid FileID if there is
536/// no next one.
537FileID SourceManager::getNextFileID(FileID FID) const {
538 if (FID.isInvalid())
539 return FileID();
540
541 int ID = FID.ID;
542 if (ID > 0) {
543 if (unsigned(ID+1) >= local_sloc_entry_size())
544 return FileID();
545 } else if (ID+1 >= -1) {
546 return FileID();
547 }
548
549 return FileID::get(ID+1);
550}
551
Chris Lattner4fa23622009-01-26 00:43:02 +0000552//===----------------------------------------------------------------------===//
Chandler Carruth64ee7822011-07-26 05:17:23 +0000553// Methods to create new FileID's and macro expansions.
Chris Lattner4fa23622009-01-26 00:43:02 +0000554//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000555
Dan Gohmance46f022010-08-26 21:27:06 +0000556/// createFileID - Create a new FileID for the specified ContentCache and
Ted Kremeneke26f3c52007-10-30 22:57:35 +0000557/// include position. This works regardless of whether the ContentCache
558/// corresponds to a file or some other input source.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000559FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattner4fa23622009-01-26 00:43:02 +0000560 SourceLocation IncludePos,
Douglas Gregor258ae542009-04-27 06:38:32 +0000561 SrcMgr::CharacteristicKind FileCharacter,
Douglas Gregor925296b2011-07-19 16:10:42 +0000562 int LoadedID, unsigned LoadedOffset) {
563 if (LoadedID < 0) {
564 assert(LoadedID != -1 && "Loading sentinel FileID");
565 unsigned Index = unsigned(-LoadedID) - 2;
566 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
567 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
568 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset,
569 FileInfo::get(IncludePos, File, FileCharacter));
570 SLocEntryLoaded[Index] = true;
571 return FileID::get(LoadedID);
Douglas Gregor258ae542009-04-27 06:38:32 +0000572 }
Douglas Gregor925296b2011-07-19 16:10:42 +0000573 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset,
574 FileInfo::get(IncludePos, File,
575 FileCharacter)));
Ted Kremenek12c2af42009-01-06 01:55:26 +0000576 unsigned FileSize = File->getSize();
Douglas Gregor925296b2011-07-19 16:10:42 +0000577 assert(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
578 NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset &&
579 "Ran out of source locations!");
580 // We do a +1 here because we want a SourceLocation that means "the end of the
581 // file", e.g. for the "no newline at the end of the file" diagnostic.
582 NextLocalOffset += FileSize + 1;
Mike Stump11289f42009-09-09 15:08:12 +0000583
Chris Lattner4fa23622009-01-26 00:43:02 +0000584 // Set LastFileIDLookup to the newly created file. The next getFileID call is
585 // almost guaranteed to be from that file.
Douglas Gregor925296b2011-07-19 16:10:42 +0000586 FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
Argyrios Kyrtzidis0152c6c2009-06-23 00:42:06 +0000587 return LastFileIDLookup = FID;
Chris Lattner22eb9722006-06-18 05:43:12 +0000588}
589
Chandler Carruth402bb382011-07-07 23:56:36 +0000590SourceLocation
Chandler Carruth115b0772011-07-26 03:03:05 +0000591SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc,
592 SourceLocation ExpansionLoc,
593 unsigned TokLength) {
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000594 ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
595 ExpansionLoc);
596 return createExpansionLocImpl(Info, TokLength);
Chandler Carruth402bb382011-07-07 23:56:36 +0000597}
598
599SourceLocation
Chandler Carruth115b0772011-07-26 03:03:05 +0000600SourceManager::createExpansionLoc(SourceLocation SpellingLoc,
601 SourceLocation ExpansionLocStart,
602 SourceLocation ExpansionLocEnd,
603 unsigned TokLength,
604 int LoadedID,
605 unsigned LoadedOffset) {
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000606 ExpansionInfo Info = ExpansionInfo::create(SpellingLoc, ExpansionLocStart,
607 ExpansionLocEnd);
608 return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset);
Chandler Carruth115b0772011-07-26 03:03:05 +0000609}
610
611SourceLocation
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000612SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
Chandler Carruth115b0772011-07-26 03:03:05 +0000613 unsigned TokLength,
614 int LoadedID,
615 unsigned LoadedOffset) {
Douglas Gregor925296b2011-07-19 16:10:42 +0000616 if (LoadedID < 0) {
617 assert(LoadedID != -1 && "Loading sentinel FileID");
618 unsigned Index = unsigned(-LoadedID) - 2;
619 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
620 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000621 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
Douglas Gregor925296b2011-07-19 16:10:42 +0000622 SLocEntryLoaded[Index] = true;
623 return SourceLocation::getMacroLoc(LoadedOffset);
Douglas Gregor258ae542009-04-27 06:38:32 +0000624 }
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000625 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
Douglas Gregor925296b2011-07-19 16:10:42 +0000626 assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&
627 NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&
628 "Ran out of source locations!");
629 // See createFileID for that +1.
630 NextLocalOffset += TokLength + 1;
631 return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
Chris Lattner7d6a4f62006-06-30 06:10:08 +0000632}
633
David Blaikie66cc07b2014-06-27 17:40:03 +0000634llvm::MemoryBuffer *SourceManager::getMemoryBufferForFile(const FileEntry *File,
635 bool *Invalid) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000636 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregor802b7762010-03-15 22:54:52 +0000637 assert(IR && "getOrCreateContentCache() cannot return NULL");
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000638 return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000639}
640
Dan Gohman5d223dc2010-10-26 20:47:28 +0000641void SourceManager::overrideFileContents(const FileEntry *SourceFile,
David Blaikie66cc07b2014-06-27 17:40:03 +0000642 llvm::MemoryBuffer *Buffer,
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000643 bool DoNotFree) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000644 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
Dan Gohman5d223dc2010-10-26 20:47:28 +0000645 assert(IR && "getOrCreateContentCache() cannot return NULL");
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000646
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000647 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
Douglas Gregor9dc32122011-11-16 20:05:18 +0000648 const_cast<SrcMgr::ContentCache *>(IR)->BufferOverridden = true;
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +0000649
650 getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000651}
652
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000653void SourceManager::overrideFileContents(const FileEntry *SourceFile,
654 const FileEntry *NewFile) {
655 assert(SourceFile->getSize() == NewFile->getSize() &&
656 "Different sizes, use the FileManager to create a virtual file with "
657 "the correct size");
658 assert(FileInfos.count(SourceFile) == 0 &&
659 "This function should be called at the initialization stage, before "
660 "any parsing occurs.");
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +0000661 getOverriddenFilesInfo().OverriddenFiles[SourceFile] = NewFile;
662}
663
664void SourceManager::disableFileContentsOverride(const FileEntry *File) {
665 if (!isFileOverridden(File))
666 return;
667
668 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Craig Topperf1186c52014-05-08 06:41:40 +0000669 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(nullptr);
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +0000670 const_cast<SrcMgr::ContentCache *>(IR)->ContentsEntry = IR->OrigEntry;
671
672 assert(OverriddenFilesInfo);
673 OverriddenFilesInfo->OverriddenFiles.erase(File);
674 OverriddenFilesInfo->OverriddenFilesWithBuffer.erase(File);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000675}
676
Richard Smitha8cfffa2015-11-26 02:04:16 +0000677void SourceManager::setFileIsTransient(const FileEntry *File) {
Richard Smithfb1e7f72015-08-14 05:02:58 +0000678 const SrcMgr::ContentCache *CC = getOrCreateContentCache(File);
Richard Smitha8cfffa2015-11-26 02:04:16 +0000679 const_cast<SrcMgr::ContentCache *>(CC)->IsTransient = true;
Richard Smithfb1e7f72015-08-14 05:02:58 +0000680}
681
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000682StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +0000683 bool MyInvalid = false;
Douglas Gregor925296b2011-07-19 16:10:42 +0000684 const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid);
Douglas Gregor49f754f2011-04-20 00:21:03 +0000685 if (!SLoc.isFile() || MyInvalid) {
Douglas Gregor86af9842011-01-31 22:42:36 +0000686 if (Invalid)
687 *Invalid = true;
688 return "<<<<<INVALID SOURCE LOCATION>>>>>";
689 }
David Blaikie66cc07b2014-06-27 17:40:03 +0000690
691 llvm::MemoryBuffer *Buf = SLoc.getFile().getContentCache()->getBuffer(
692 Diag, *this, SourceLocation(), &MyInvalid);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000693 if (Invalid)
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +0000694 *Invalid = MyInvalid;
695
696 if (MyInvalid)
Douglas Gregor86af9842011-01-31 22:42:36 +0000697 return "<<<<<INVALID SOURCE LOCATION>>>>>";
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +0000698
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000699 return Buf->getBuffer();
Douglas Gregor802b7762010-03-15 22:54:52 +0000700}
Chris Lattnerd32480d2009-01-17 06:22:33 +0000701
Chris Lattner153a0f12009-02-04 00:40:31 +0000702//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +0000703// SourceLocation manipulation methods.
Chris Lattner153a0f12009-02-04 00:40:31 +0000704//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +0000705
Douglas Gregor925296b2011-07-19 16:10:42 +0000706/// \brief Return the FileID for a SourceLocation.
Chris Lattner4fa23622009-01-26 00:43:02 +0000707///
Douglas Gregor925296b2011-07-19 16:10:42 +0000708/// This is the cache-miss path of getFileID. Not as hot as that function, but
709/// still very important. It is responsible for finding the entry in the
710/// SLocEntry tables that contains the specified location.
Chris Lattner4fa23622009-01-26 00:43:02 +0000711FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
Douglas Gregor49f754f2011-04-20 00:21:03 +0000712 if (!SLocOffset)
713 return FileID::get(0);
Mike Stump11289f42009-09-09 15:08:12 +0000714
Douglas Gregor925296b2011-07-19 16:10:42 +0000715 // Now it is time to search for the correct file. See where the SLocOffset
716 // sits in the global view and consult local or loaded buffers for it.
717 if (SLocOffset < NextLocalOffset)
718 return getFileIDLocal(SLocOffset);
719 return getFileIDLoaded(SLocOffset);
720}
721
722/// \brief Return the FileID for a SourceLocation with a low offset.
723///
724/// This function knows that the SourceLocation is in a local buffer, not a
725/// loaded one.
726FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const {
727 assert(SLocOffset < NextLocalOffset && "Bad function choice");
728
Chris Lattner4fa23622009-01-26 00:43:02 +0000729 // After the first and second level caches, I see two common sorts of
Chandler Carruth64ee7822011-07-26 05:17:23 +0000730 // behavior: 1) a lot of searched FileID's are "near" the cached file
731 // location or are "near" the cached expansion location. 2) others are just
Chris Lattner4fa23622009-01-26 00:43:02 +0000732 // completely random and may be a very long way away.
733 //
734 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
735 // then we fall back to a less cache efficient, but more scalable, binary
736 // search to find the location.
Mike Stump11289f42009-09-09 15:08:12 +0000737
Chris Lattner4fa23622009-01-26 00:43:02 +0000738 // See if this is near the file point - worst case we start scanning from the
739 // most newly created FileID.
Benjamin Kramer2999b772013-02-22 18:29:39 +0000740 const SrcMgr::SLocEntry *I;
Mike Stump11289f42009-09-09 15:08:12 +0000741
Douglas Gregor925296b2011-07-19 16:10:42 +0000742 if (LastFileIDLookup.ID < 0 ||
743 LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
Chris Lattner4fa23622009-01-26 00:43:02 +0000744 // Neither loc prunes our search.
Douglas Gregor925296b2011-07-19 16:10:42 +0000745 I = LocalSLocEntryTable.end();
Chris Lattner4fa23622009-01-26 00:43:02 +0000746 } else {
747 // Perhaps it is near the file point.
Douglas Gregor925296b2011-07-19 16:10:42 +0000748 I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
Chris Lattner4fa23622009-01-26 00:43:02 +0000749 }
750
751 // Find the FileID that contains this. "I" is an iterator that points to a
752 // FileID whose offset is known to be larger than SLocOffset.
753 unsigned NumProbes = 0;
754 while (1) {
755 --I;
756 if (I->getOffset() <= SLocOffset) {
Douglas Gregor925296b2011-07-19 16:10:42 +0000757 FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
Douglas Gregor258ae542009-04-27 06:38:32 +0000758
Chandler Carruth64ee7822011-07-26 05:17:23 +0000759 // If this isn't an expansion, remember it. We have good locality across
760 // FileID lookups.
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000761 if (!I->isExpansion())
Chris Lattner4fa23622009-01-26 00:43:02 +0000762 LastFileIDLookup = Res;
763 NumLinearScans += NumProbes+1;
764 return Res;
765 }
766 if (++NumProbes == 8)
767 break;
768 }
Mike Stump11289f42009-09-09 15:08:12 +0000769
Chris Lattner4fa23622009-01-26 00:43:02 +0000770 // Convert "I" back into an index. We know that it is an entry whose index is
771 // larger than the offset we are looking for.
Douglas Gregor925296b2011-07-19 16:10:42 +0000772 unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
Chris Lattner4fa23622009-01-26 00:43:02 +0000773 // LessIndex - This is the lower bound of the range that we're searching.
774 // We know that the offset corresponding to the FileID is is less than
775 // SLocOffset.
776 unsigned LessIndex = 0;
777 NumProbes = 0;
778 while (1) {
Douglas Gregor49f754f2011-04-20 00:21:03 +0000779 bool Invalid = false;
Chris Lattner4fa23622009-01-26 00:43:02 +0000780 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregor925296b2011-07-19 16:10:42 +0000781 unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
Douglas Gregor49f754f2011-04-20 00:21:03 +0000782 if (Invalid)
783 return FileID::get(0);
784
Chris Lattner4fa23622009-01-26 00:43:02 +0000785 ++NumProbes;
Mike Stump11289f42009-09-09 15:08:12 +0000786
Chris Lattner4fa23622009-01-26 00:43:02 +0000787 // If the offset of the midpoint is too large, chop the high side of the
788 // range to the midpoint.
789 if (MidOffset > SLocOffset) {
790 GreaterIndex = MiddleIndex;
791 continue;
792 }
Mike Stump11289f42009-09-09 15:08:12 +0000793
Chris Lattner4fa23622009-01-26 00:43:02 +0000794 // If the middle index contains the value, succeed and return.
Douglas Gregor925296b2011-07-19 16:10:42 +0000795 // FIXME: This could be made faster by using a function that's aware of
796 // being in the local area.
Chris Lattner4fa23622009-01-26 00:43:02 +0000797 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
Chris Lattner4fa23622009-01-26 00:43:02 +0000798 FileID Res = FileID::get(MiddleIndex);
799
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000800 // If this isn't a macro expansion, remember it. We have good locality
Chris Lattner4fa23622009-01-26 00:43:02 +0000801 // across FileID lookups.
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000802 if (!LocalSLocEntryTable[MiddleIndex].isExpansion())
Chris Lattner4fa23622009-01-26 00:43:02 +0000803 LastFileIDLookup = Res;
804 NumBinaryProbes += NumProbes;
805 return Res;
806 }
Mike Stump11289f42009-09-09 15:08:12 +0000807
Chris Lattner4fa23622009-01-26 00:43:02 +0000808 // Otherwise, move the low-side up to the middle index.
809 LessIndex = MiddleIndex;
810 }
811}
812
Douglas Gregor925296b2011-07-19 16:10:42 +0000813/// \brief Return the FileID for a SourceLocation with a high offset.
814///
815/// This function knows that the SourceLocation is in a loaded buffer, not a
816/// local one.
817FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
Argyrios Kyrtzidis25029d42011-10-03 23:43:01 +0000818 // Sanity checking, otherwise a bug may lead to hanging in release build.
Argyrios Kyrtzidis8edffaa2011-10-25 00:29:44 +0000819 if (SLocOffset < CurrentLoadedOffset) {
820 assert(0 && "Invalid SLocOffset or bad function choice");
Argyrios Kyrtzidis25029d42011-10-03 23:43:01 +0000821 return FileID();
Argyrios Kyrtzidis8edffaa2011-10-25 00:29:44 +0000822 }
Argyrios Kyrtzidis25029d42011-10-03 23:43:01 +0000823
Douglas Gregor925296b2011-07-19 16:10:42 +0000824 // Essentially the same as the local case, but the loaded array is sorted
825 // in the other direction.
826
827 // First do a linear scan from the last lookup position, if possible.
828 unsigned I;
829 int LastID = LastFileIDLookup.ID;
830 if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
831 I = 0;
832 else
833 I = (-LastID - 2) + 1;
834
835 unsigned NumProbes;
836 for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
837 // Make sure the entry is loaded!
838 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
839 if (E.getOffset() <= SLocOffset) {
840 FileID Res = FileID::get(-int(I) - 2);
841
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000842 if (!E.isExpansion())
Douglas Gregor925296b2011-07-19 16:10:42 +0000843 LastFileIDLookup = Res;
844 NumLinearScans += NumProbes + 1;
845 return Res;
846 }
847 }
848
849 // Linear scan failed. Do the binary search. Note the reverse sorting of the
850 // table: GreaterIndex is the one where the offset is greater, which is
851 // actually a lower index!
852 unsigned GreaterIndex = I;
853 unsigned LessIndex = LoadedSLocEntryTable.size();
854 NumProbes = 0;
855 while (1) {
856 ++NumProbes;
857 unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
858 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
Argyrios Kyrtzidis7dc4f332013-03-01 03:26:00 +0000859 if (E.getOffset() == 0)
860 return FileID(); // invalid entry.
Douglas Gregor925296b2011-07-19 16:10:42 +0000861
862 ++NumProbes;
863
864 if (E.getOffset() > SLocOffset) {
Argyrios Kyrtzidis7dc4f332013-03-01 03:26:00 +0000865 // Sanity checking, otherwise a bug may lead to hanging in release build.
866 if (GreaterIndex == MiddleIndex) {
867 assert(0 && "binary search missed the entry");
868 return FileID();
869 }
Douglas Gregor925296b2011-07-19 16:10:42 +0000870 GreaterIndex = MiddleIndex;
871 continue;
872 }
873
874 if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
875 FileID Res = FileID::get(-int(MiddleIndex) - 2);
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000876 if (!E.isExpansion())
Douglas Gregor925296b2011-07-19 16:10:42 +0000877 LastFileIDLookup = Res;
878 NumBinaryProbes += NumProbes;
879 return Res;
880 }
881
Argyrios Kyrtzidis1ca73442013-03-01 03:43:33 +0000882 // Sanity checking, otherwise a bug may lead to hanging in release build.
883 if (LessIndex == MiddleIndex) {
884 assert(0 && "binary search missed the entry");
885 return FileID();
886 }
Douglas Gregor925296b2011-07-19 16:10:42 +0000887 LessIndex = MiddleIndex;
888 }
889}
890
Chris Lattner659ac5f2009-01-26 20:04:19 +0000891SourceLocation SourceManager::
Chandler Carruthc84d7692011-07-25 20:52:26 +0000892getExpansionLocSlowCase(SourceLocation Loc) const {
Chris Lattner659ac5f2009-01-26 20:04:19 +0000893 do {
Chris Lattner5647d312010-02-12 19:31:35 +0000894 // Note: If Loc indicates an offset into a token that came from a macro
895 // expansion (e.g. the 5th character of the token) we do not want to add
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000896 // this offset when going to the expansion location. The expansion
Chris Lattner5647d312010-02-12 19:31:35 +0000897 // location is the macro invocation, which the offset has nothing to do
898 // with. This is unlike when we get the spelling loc, because the offset
899 // directly correspond to the token whose spelling we're inspecting.
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000900 Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
Chris Lattner659ac5f2009-01-26 20:04:19 +0000901 } while (!Loc.isFileID());
902
903 return Loc;
904}
905
906SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
907 do {
908 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000909 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000910 Loc = Loc.getLocWithOffset(LocInfo.second);
Chris Lattner659ac5f2009-01-26 20:04:19 +0000911 } while (!Loc.isFileID());
912 return Loc;
913}
914
Argyrios Kyrtzidis7f6b0292011-10-12 07:07:40 +0000915SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
916 do {
917 if (isMacroArgExpansion(Loc))
918 Loc = getImmediateSpellingLoc(Loc);
919 else
920 Loc = getImmediateExpansionRange(Loc).first;
921 } while (!Loc.isFileID());
922 return Loc;
923}
924
Chris Lattner659ac5f2009-01-26 20:04:19 +0000925
Chris Lattner4fa23622009-01-26 00:43:02 +0000926std::pair<FileID, unsigned>
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000927SourceManager::getDecomposedExpansionLocSlowCase(
Argyrios Kyrtzidisc8f7e212011-07-07 03:40:27 +0000928 const SrcMgr::SLocEntry *E) const {
Chandler Carruth64ee7822011-07-26 05:17:23 +0000929 // If this is an expansion record, walk through all the expansion points.
Chris Lattner4fa23622009-01-26 00:43:02 +0000930 FileID FID;
931 SourceLocation Loc;
Argyrios Kyrtzidisc8f7e212011-07-07 03:40:27 +0000932 unsigned Offset;
Chris Lattner4fa23622009-01-26 00:43:02 +0000933 do {
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000934 Loc = E->getExpansion().getExpansionLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000935
Chris Lattner4fa23622009-01-26 00:43:02 +0000936 FID = getFileID(Loc);
937 E = &getSLocEntry(FID);
Argyrios Kyrtzidisc8f7e212011-07-07 03:40:27 +0000938 Offset = Loc.getOffset()-E->getOffset();
Chris Lattner31af4e02009-01-26 19:41:58 +0000939 } while (!Loc.isFileID());
Mike Stump11289f42009-09-09 15:08:12 +0000940
Chris Lattner4fa23622009-01-26 00:43:02 +0000941 return std::make_pair(FID, Offset);
942}
943
944std::pair<FileID, unsigned>
945SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
946 unsigned Offset) const {
Chandler Carruth64ee7822011-07-26 05:17:23 +0000947 // If this is an expansion record, walk through all the expansion points.
Chris Lattner31af4e02009-01-26 19:41:58 +0000948 FileID FID;
949 SourceLocation Loc;
950 do {
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000951 Loc = E->getExpansion().getSpellingLoc();
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000952 Loc = Loc.getLocWithOffset(Offset);
Mike Stump11289f42009-09-09 15:08:12 +0000953
Chris Lattner31af4e02009-01-26 19:41:58 +0000954 FID = getFileID(Loc);
955 E = &getSLocEntry(FID);
Argyrios Kyrtzidis2797df62011-08-23 21:02:41 +0000956 Offset = Loc.getOffset()-E->getOffset();
Chris Lattner31af4e02009-01-26 19:41:58 +0000957 } while (!Loc.isFileID());
Mike Stump11289f42009-09-09 15:08:12 +0000958
Chris Lattner4fa23622009-01-26 00:43:02 +0000959 return std::make_pair(FID, Offset);
960}
961
Chris Lattner8ad52d52009-02-17 08:04:48 +0000962/// getImmediateSpellingLoc - Given a SourceLocation object, return the
963/// spelling location referenced by the ID. This is the first level down
964/// towards the place where the characters that make up the lexed token can be
965/// found. This should not generally be used by clients.
966SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
967 if (Loc.isFileID()) return Loc;
968 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000969 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000970 return Loc.getLocWithOffset(LocInfo.second);
Chris Lattner8ad52d52009-02-17 08:04:48 +0000971}
972
973
Chandler Carruth64ee7822011-07-26 05:17:23 +0000974/// getImmediateExpansionRange - Loc is required to be an expansion location.
975/// Return the start/end of the expansion information.
Chris Lattner9dc9c202009-02-15 20:52:18 +0000976std::pair<SourceLocation,SourceLocation>
Chandler Carruthca757582011-07-25 20:52:21 +0000977SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
Chandler Carruth64ee7822011-07-26 05:17:23 +0000978 assert(Loc.isMacroID() && "Not a macro expansion loc!");
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000979 const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000980 return Expansion.getExpansionLocRange();
Chris Lattner9dc9c202009-02-15 20:52:18 +0000981}
982
Chandler Carruth6d28d7f2011-07-25 16:56:02 +0000983/// getExpansionRange - Given a SourceLocation object, return the range of
984/// tokens covered by the expansion in the ultimate file.
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000985std::pair<SourceLocation,SourceLocation>
Chandler Carruth6d28d7f2011-07-25 16:56:02 +0000986SourceManager::getExpansionRange(SourceLocation Loc) const {
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000987 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000988
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000989 std::pair<SourceLocation,SourceLocation> Res =
Chandler Carruthca757582011-07-25 20:52:21 +0000990 getImmediateExpansionRange(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000991
Chandler Carruth64ee7822011-07-26 05:17:23 +0000992 // Fully resolve the start and end locations to their ultimate expansion
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000993 // points.
994 while (!Res.first.isFileID())
Chandler Carruthca757582011-07-25 20:52:21 +0000995 Res.first = getImmediateExpansionRange(Res.first).first;
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000996 while (!Res.second.isFileID())
Chandler Carruthca757582011-07-25 20:52:21 +0000997 Res.second = getImmediateExpansionRange(Res.second).second;
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000998 return Res;
999}
1000
Richard Trieuc3096242015-09-24 01:21:01 +00001001bool SourceManager::isMacroArgExpansion(SourceLocation Loc,
1002 SourceLocation *StartLoc) const {
Chandler Carruth402bb382011-07-07 23:56:36 +00001003 if (!Loc.isMacroID()) return false;
1004
1005 FileID FID = getFileID(Loc);
Matt Beaumont-Gayb1e71a72013-01-12 00:54:16 +00001006 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
Richard Trieuc3096242015-09-24 01:21:01 +00001007 if (!Expansion.isMacroArgExpansion()) return false;
1008
1009 if (StartLoc)
1010 *StartLoc = Expansion.getExpansionLocStart();
1011 return true;
Chandler Carruth402bb382011-07-07 23:56:36 +00001012}
Chris Lattner9dc9c202009-02-15 20:52:18 +00001013
Matt Beaumont-Gayb1e71a72013-01-12 00:54:16 +00001014bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const {
1015 if (!Loc.isMacroID()) return false;
1016
1017 FileID FID = getFileID(Loc);
1018 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1019 return Expansion.isMacroBodyExpansion();
1020}
1021
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +00001022bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
1023 SourceLocation *MacroBegin) const {
1024 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1025
1026 std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);
1027 if (DecompLoc.second > 0)
1028 return false; // Does not point at the start of expansion range.
1029
1030 bool Invalid = false;
1031 const SrcMgr::ExpansionInfo &ExpInfo =
1032 getSLocEntry(DecompLoc.first, &Invalid).getExpansion();
1033 if (Invalid)
1034 return false;
1035 SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();
1036
1037 if (ExpInfo.isMacroArgExpansion()) {
1038 // For macro argument expansions, check if the previous FileID is part of
1039 // the same argument expansion, in which case this Loc is not at the
1040 // beginning of the expansion.
1041 FileID PrevFID = getPreviousFileID(DecompLoc.first);
1042 if (!PrevFID.isInvalid()) {
1043 const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);
1044 if (Invalid)
1045 return false;
1046 if (PrevEntry.isExpansion() &&
1047 PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)
1048 return false;
1049 }
1050 }
1051
1052 if (MacroBegin)
1053 *MacroBegin = ExpLoc;
1054 return true;
1055}
1056
1057bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
1058 SourceLocation *MacroEnd) const {
1059 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1060
1061 FileID FID = getFileID(Loc);
1062 SourceLocation NextLoc = Loc.getLocWithOffset(1);
1063 if (isInFileID(NextLoc, FID))
1064 return false; // Does not point at the end of expansion range.
1065
1066 bool Invalid = false;
1067 const SrcMgr::ExpansionInfo &ExpInfo =
1068 getSLocEntry(FID, &Invalid).getExpansion();
1069 if (Invalid)
1070 return false;
1071
1072 if (ExpInfo.isMacroArgExpansion()) {
1073 // For macro argument expansions, check if the next FileID is part of the
1074 // same argument expansion, in which case this Loc is not at the end of the
1075 // expansion.
1076 FileID NextFID = getNextFileID(FID);
1077 if (!NextFID.isInvalid()) {
1078 const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);
1079 if (Invalid)
1080 return false;
1081 if (NextEntry.isExpansion() &&
1082 NextEntry.getExpansion().getExpansionLocStart() ==
1083 ExpInfo.getExpansionLocStart())
1084 return false;
1085 }
1086 }
1087
1088 if (MacroEnd)
1089 *MacroEnd = ExpInfo.getExpansionLocEnd();
1090 return true;
1091}
1092
Chris Lattner4fa23622009-01-26 00:43:02 +00001093
1094//===----------------------------------------------------------------------===//
1095// Queries about the code at a SourceLocation.
1096//===----------------------------------------------------------------------===//
Chris Lattner30709b032006-06-21 03:01:55 +00001097
Chris Lattnerd01e2912006-06-18 16:22:51 +00001098/// getCharacterData - Return a pointer to the start of the specified location
Chris Lattner739e7392007-04-29 07:12:06 +00001099/// in the appropriate MemoryBuffer.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001100const char *SourceManager::getCharacterData(SourceLocation SL,
1101 bool *Invalid) const {
Chris Lattnerd3a15f72006-07-04 23:01:03 +00001102 // Note that this is a hot function in the getSpelling() path, which is
1103 // heavily used by -E mode.
Chris Lattner4fa23622009-01-26 00:43:02 +00001104 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump11289f42009-09-09 15:08:12 +00001105
Ted Kremenek12c2af42009-01-06 01:55:26 +00001106 // Note that calling 'getBuffer()' may lazily page in a source file.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001107 bool CharDataInvalid = false;
Douglas Gregor49f754f2011-04-20 00:21:03 +00001108 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
1109 if (CharDataInvalid || !Entry.isFile()) {
1110 if (Invalid)
1111 *Invalid = true;
1112
1113 return "<<<<INVALID BUFFER>>>>";
1114 }
David Blaikie66cc07b2014-06-27 17:40:03 +00001115 llvm::MemoryBuffer *Buffer = Entry.getFile().getContentCache()->getBuffer(
1116 Diag, *this, SourceLocation(), &CharDataInvalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001117 if (Invalid)
1118 *Invalid = CharDataInvalid;
1119 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
Chris Lattnerd01e2912006-06-18 16:22:51 +00001120}
1121
Chris Lattner685730f2006-06-26 01:36:22 +00001122
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001123/// getColumnNumber - Return the column # for the specified file position.
Chris Lattnere4ad4172009-02-04 00:55:58 +00001124/// this is significantly cheaper to compute than the line number.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001125unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
1126 bool *Invalid) const {
1127 bool MyInvalid = false;
David Blaikie66cc07b2014-06-27 17:40:03 +00001128 llvm::MemoryBuffer *MemBuf = getBuffer(FID, &MyInvalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001129 if (Invalid)
1130 *Invalid = MyInvalid;
1131
1132 if (MyInvalid)
1133 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00001134
Jordan Rose8d63d5b2012-06-19 03:09:38 +00001135 // It is okay to request a position just past the end of the buffer.
1136 if (FilePos > MemBuf->getBufferSize()) {
Argyrios Kyrtzidis6c8d29f2011-12-10 00:30:38 +00001137 if (Invalid)
Jordan Rose8d63d5b2012-06-19 03:09:38 +00001138 *Invalid = true;
Argyrios Kyrtzidis6c8d29f2011-12-10 00:30:38 +00001139 return 1;
1140 }
1141
Craig Topper5e79ee02012-10-19 04:40:38 +00001142 // See if we just calculated the line number for this FilePos and can use
1143 // that to lookup the start of the line instead of searching for it.
1144 if (LastLineNoFileIDQuery == FID &&
Craig Topperf1186c52014-05-08 06:41:40 +00001145 LastLineNoContentCache->SourceLineCache != nullptr &&
Craig Topperf3b839b2012-12-16 05:58:32 +00001146 LastLineNoResult < LastLineNoContentCache->NumLines) {
Craig Topper5e79ee02012-10-19 04:40:38 +00001147 unsigned *SourceLineCache = LastLineNoContentCache->SourceLineCache;
1148 unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
1149 unsigned LineEnd = SourceLineCache[LastLineNoResult];
1150 if (FilePos >= LineStart && FilePos < LineEnd)
1151 return FilePos - LineStart + 1;
1152 }
1153
Dylan Noblesmith2a8bc152011-12-19 08:51:05 +00001154 const char *Buf = MemBuf->getBufferStart();
Chris Lattner22eb9722006-06-18 05:43:12 +00001155 unsigned LineStart = FilePos;
1156 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
1157 --LineStart;
1158 return FilePos-LineStart+1;
1159}
1160
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001161// isInvalid - Return the result of calling loc.isInvalid(), and
1162// if Invalid is not null, set its value to same.
1163static bool isInvalid(SourceLocation Loc, bool *Invalid) {
1164 bool MyInvalid = Loc.isInvalid();
1165 if (Invalid)
1166 *Invalid = MyInvalid;
1167 return MyInvalid;
1168}
1169
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001170unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
1171 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001172 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattnere4ad4172009-02-04 00:55:58 +00001173 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001174 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattnere4ad4172009-02-04 00:55:58 +00001175}
1176
Chandler Carruth42f35f92011-07-25 20:57:57 +00001177unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
1178 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001179 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001180 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001181 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattnere4ad4172009-02-04 00:55:58 +00001182}
1183
Chandler Carruth1aef0c52011-02-23 00:47:48 +00001184unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
1185 bool *Invalid) const {
1186 if (isInvalid(Loc, Invalid)) return 0;
1187 return getPresumedLoc(Loc).getColumn();
1188}
1189
Benjamin Kramer543036a2012-04-06 20:49:55 +00001190#ifdef __SSE2__
1191#include <emmintrin.h>
1192#endif
1193
Chandler Carruthc3ce5842010-10-23 08:44:57 +00001194static LLVM_ATTRIBUTE_NOINLINE void
David Blaikie9c902b52011-09-25 23:23:43 +00001195ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001196 llvm::BumpPtrAllocator &Alloc,
1197 const SourceManager &SM, bool &Invalid);
David Blaikie9c902b52011-09-25 23:23:43 +00001198static void ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001199 llvm::BumpPtrAllocator &Alloc,
1200 const SourceManager &SM, bool &Invalid) {
Ted Kremenek12c2af42009-01-06 01:55:26 +00001201 // Note that calling 'getBuffer()' may lazily page in the file.
David Blaikie66cc07b2014-06-27 17:40:03 +00001202 MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(), &Invalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001203 if (Invalid)
1204 return;
Mike Stump11289f42009-09-09 15:08:12 +00001205
Chris Lattner8996fff2007-07-24 05:57:19 +00001206 // Find the file offsets of all of the *physical* source lines. This does
1207 // not look at trigraphs, escaped newlines, or anything else tricky.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001208 SmallVector<unsigned, 256> LineOffsets;
Mike Stump11289f42009-09-09 15:08:12 +00001209
Chris Lattner8996fff2007-07-24 05:57:19 +00001210 // Line #1 starts at char 0.
1211 LineOffsets.push_back(0);
Mike Stump11289f42009-09-09 15:08:12 +00001212
Chris Lattner8996fff2007-07-24 05:57:19 +00001213 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
1214 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
1215 unsigned Offs = 0;
1216 while (1) {
1217 // Skip over the contents of the line.
Chris Lattner8996fff2007-07-24 05:57:19 +00001218 const unsigned char *NextBuf = (const unsigned char *)Buf;
Benjamin Kramer543036a2012-04-06 20:49:55 +00001219
1220#ifdef __SSE2__
1221 // Try to skip to the next newline using SSE instructions. This is very
1222 // performance sensitive for programs with lots of diagnostics and in -E
1223 // mode.
1224 __m128i CRs = _mm_set1_epi8('\r');
1225 __m128i LFs = _mm_set1_epi8('\n');
1226
1227 // First fix up the alignment to 16 bytes.
1228 while (((uintptr_t)NextBuf & 0xF) != 0) {
1229 if (*NextBuf == '\n' || *NextBuf == '\r' || *NextBuf == '\0')
1230 goto FoundSpecialChar;
1231 ++NextBuf;
1232 }
1233
1234 // Scan 16 byte chunks for '\r' and '\n'. Ignore '\0'.
1235 while (NextBuf+16 <= End) {
Roman Divackye6377112012-09-06 15:59:27 +00001236 const __m128i Chunk = *(const __m128i*)NextBuf;
Benjamin Kramer543036a2012-04-06 20:49:55 +00001237 __m128i Cmp = _mm_or_si128(_mm_cmpeq_epi8(Chunk, CRs),
1238 _mm_cmpeq_epi8(Chunk, LFs));
1239 unsigned Mask = _mm_movemask_epi8(Cmp);
1240
1241 // If we found a newline, adjust the pointer and jump to the handling code.
1242 if (Mask != 0) {
Michael J. Spencer8c398402013-05-24 21:42:04 +00001243 NextBuf += llvm::countTrailingZeros(Mask);
Benjamin Kramer543036a2012-04-06 20:49:55 +00001244 goto FoundSpecialChar;
1245 }
1246 NextBuf += 16;
1247 }
1248#endif
1249
Chris Lattner8996fff2007-07-24 05:57:19 +00001250 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
1251 ++NextBuf;
Benjamin Kramer543036a2012-04-06 20:49:55 +00001252
1253#ifdef __SSE2__
1254FoundSpecialChar:
1255#endif
Chris Lattner8996fff2007-07-24 05:57:19 +00001256 Offs += NextBuf-Buf;
1257 Buf = NextBuf;
Mike Stump11289f42009-09-09 15:08:12 +00001258
Chris Lattner8996fff2007-07-24 05:57:19 +00001259 if (Buf[0] == '\n' || Buf[0] == '\r') {
1260 // If this is \n\r or \r\n, skip both characters.
Richard Trieucc3949d2016-02-18 22:34:54 +00001261 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1]) {
1262 ++Offs;
1263 ++Buf;
1264 }
1265 ++Offs;
1266 ++Buf;
Chris Lattner8996fff2007-07-24 05:57:19 +00001267 LineOffsets.push_back(Offs);
1268 } else {
1269 // Otherwise, this is a null. If end of file, exit.
1270 if (Buf == End) break;
1271 // Otherwise, skip the null.
Richard Trieucc3949d2016-02-18 22:34:54 +00001272 ++Offs;
1273 ++Buf;
Chris Lattner8996fff2007-07-24 05:57:19 +00001274 }
1275 }
Mike Stump11289f42009-09-09 15:08:12 +00001276
Chris Lattner8996fff2007-07-24 05:57:19 +00001277 // Copy the offsets into the FileInfo structure.
1278 FI->NumLines = LineOffsets.size();
Chris Lattnerc8233df2009-02-03 07:30:45 +00001279 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner8996fff2007-07-24 05:57:19 +00001280 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
1281}
Chris Lattner9a13bde2006-06-21 04:57:09 +00001282
Chris Lattner53e384f2009-01-16 07:00:02 +00001283/// getLineNumber - Given a SourceLocation, return the spelling line number
Chris Lattner22eb9722006-06-18 05:43:12 +00001284/// for the position indicated. This requires building and caching a table of
Chris Lattner739e7392007-04-29 07:12:06 +00001285/// line offsets for the MemoryBuffer, so this is not cheap: use only when
Chris Lattner22eb9722006-06-18 05:43:12 +00001286/// about to emit a diagnostic.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001287unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1288 bool *Invalid) const {
Argyrios Kyrtzidisf15eac12011-05-17 22:09:53 +00001289 if (FID.isInvalid()) {
1290 if (Invalid)
1291 *Invalid = true;
1292 return 1;
1293 }
1294
Chris Lattnerd32480d2009-01-17 06:22:33 +00001295 ContentCache *Content;
Chris Lattner88ea93e2009-02-04 01:06:56 +00001296 if (LastLineNoFileIDQuery == FID)
Ted Kremenekc08bca62007-10-30 21:08:08 +00001297 Content = LastLineNoContentCache;
Douglas Gregor49f754f2011-04-20 00:21:03 +00001298 else {
1299 bool MyInvalid = false;
1300 const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1301 if (MyInvalid || !Entry.isFile()) {
1302 if (Invalid)
1303 *Invalid = true;
1304 return 1;
1305 }
1306
1307 Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
1308 }
1309
Chris Lattner22eb9722006-06-18 05:43:12 +00001310 // If this is the first use of line information for this buffer, compute the
Chris Lattner8996fff2007-07-24 05:57:19 +00001311 /// SourceLineCache for it on demand.
Craig Topperf1186c52014-05-08 06:41:40 +00001312 if (!Content->SourceLineCache) {
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001313 bool MyInvalid = false;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001314 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001315 if (Invalid)
1316 *Invalid = MyInvalid;
1317 if (MyInvalid)
1318 return 1;
1319 } else if (Invalid)
1320 *Invalid = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001321
1322 // Okay, we know we have a line number table. Do a binary search to find the
1323 // line number that this character position lands on.
Ted Kremenekc08bca62007-10-30 21:08:08 +00001324 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner8996fff2007-07-24 05:57:19 +00001325 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenekc08bca62007-10-30 21:08:08 +00001326 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump11289f42009-09-09 15:08:12 +00001327
Chris Lattner88ea93e2009-02-04 01:06:56 +00001328 unsigned QueriedFilePos = FilePos+1;
Chris Lattner8996fff2007-07-24 05:57:19 +00001329
Daniel Dunbar70f924df82009-05-18 17:30:52 +00001330 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump11289f42009-09-09 15:08:12 +00001331 // complicated as it is, binary search isn't that slow.
Daniel Dunbar70f924df82009-05-18 17:30:52 +00001332 //
1333 // If it is worth being optimized, then in my opinion it could be more
1334 // performant, simpler, and more obviously correct by just "galloping" outward
1335 // from the queried file position. In fact, this could be incorporated into a
1336 // generic algorithm such as lower_bound_with_hint.
1337 //
1338 // If someone gives me a test case where this matters, and I will do it! - DWD
1339
Chris Lattner8996fff2007-07-24 05:57:19 +00001340 // If the previous query was to the same file, we know both the file pos from
1341 // that query and the line number returned. This allows us to narrow the
1342 // search space from the entire file to something near the match.
Chris Lattner88ea93e2009-02-04 01:06:56 +00001343 if (LastLineNoFileIDQuery == FID) {
Chris Lattner8996fff2007-07-24 05:57:19 +00001344 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar70f924df82009-05-18 17:30:52 +00001345 // FIXME: Potential overflow?
Chris Lattner8996fff2007-07-24 05:57:19 +00001346 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump11289f42009-09-09 15:08:12 +00001347
Chris Lattner8996fff2007-07-24 05:57:19 +00001348 // The query is likely to be nearby the previous one. Here we check to
1349 // see if it is within 5, 10 or 20 lines. It can be far away in cases
1350 // where big comment blocks and vertical whitespace eat up lines but
1351 // contribute no tokens.
1352 if (SourceLineCache+5 < SourceLineCacheEnd) {
1353 if (SourceLineCache[5] > QueriedFilePos)
1354 SourceLineCacheEnd = SourceLineCache+5;
1355 else if (SourceLineCache+10 < SourceLineCacheEnd) {
1356 if (SourceLineCache[10] > QueriedFilePos)
1357 SourceLineCacheEnd = SourceLineCache+10;
1358 else if (SourceLineCache+20 < SourceLineCacheEnd) {
1359 if (SourceLineCache[20] > QueriedFilePos)
1360 SourceLineCacheEnd = SourceLineCache+20;
1361 }
1362 }
1363 }
1364 } else {
Daniel Dunbar70f924df82009-05-18 17:30:52 +00001365 if (LastLineNoResult < Content->NumLines)
1366 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner8996fff2007-07-24 05:57:19 +00001367 }
1368 }
Mike Stump11289f42009-09-09 15:08:12 +00001369
Chris Lattner830a77f2007-07-24 06:43:46 +00001370 unsigned *Pos
1371 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner8996fff2007-07-24 05:57:19 +00001372 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump11289f42009-09-09 15:08:12 +00001373
Chris Lattner88ea93e2009-02-04 01:06:56 +00001374 LastLineNoFileIDQuery = FID;
Ted Kremenekc08bca62007-10-30 21:08:08 +00001375 LastLineNoContentCache = Content;
Chris Lattner8996fff2007-07-24 05:57:19 +00001376 LastLineNoFilePos = QueriedFilePos;
1377 LastLineNoResult = LineNo;
1378 return LineNo;
Chris Lattner22eb9722006-06-18 05:43:12 +00001379}
1380
Chandler Carruth1aef0c52011-02-23 00:47:48 +00001381unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1382 bool *Invalid) const {
1383 if (isInvalid(Loc, Invalid)) return 0;
1384 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1385 return getLineNumber(LocInfo.first, LocInfo.second);
1386}
Chandler Carruthd48db212011-07-25 21:09:52 +00001387unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
1388 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001389 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001390 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Chris Lattner88ea93e2009-02-04 01:06:56 +00001391 return getLineNumber(LocInfo.first, LocInfo.second);
1392}
Chandler Carruth1aef0c52011-02-23 00:47:48 +00001393unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001394 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001395 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruth1aef0c52011-02-23 00:47:48 +00001396 return getPresumedLoc(Loc).getLine();
Chris Lattner88ea93e2009-02-04 01:06:56 +00001397}
1398
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001399/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump11289f42009-09-09 15:08:12 +00001400/// source location, indicating whether this is a normal file, a system
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001401/// header, or an "implicit extern C" system header.
1402///
1403/// This state can be modified with flags on GNU linemarker directives like:
1404/// # 4 "foo.h" 3
1405/// which changes all source locations in the current file after that to be
1406/// considered to be from a system header.
Mike Stump11289f42009-09-09 15:08:12 +00001407SrcMgr::CharacteristicKind
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001408SourceManager::getFileCharacteristic(SourceLocation Loc) const {
Yaron Keren8b563662015-10-03 10:46:20 +00001409 assert(Loc.isValid() && "Can't get file characteristic of invalid loc!");
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001410 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregor49f754f2011-04-20 00:21:03 +00001411 bool Invalid = false;
1412 const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
1413 if (Invalid || !SEntry.isFile())
1414 return C_User;
1415
1416 const SrcMgr::FileInfo &FI = SEntry.getFile();
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001417
1418 // If there are no #line directives in this file, just return the whole-file
1419 // state.
1420 if (!FI.hasLineDirectives())
1421 return FI.getFileCharacteristic();
Mike Stump11289f42009-09-09 15:08:12 +00001422
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001423 assert(LineTable && "Can't have linetable entries without a LineTable!");
1424 // See if there is a #line directive before the location.
1425 const LineEntry *Entry =
Douglas Gregor02c2dbf2012-06-08 16:40:28 +00001426 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
Mike Stump11289f42009-09-09 15:08:12 +00001427
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001428 // If this is before the first line marker, use the file characteristic.
1429 if (!Entry)
1430 return FI.getFileCharacteristic();
1431
1432 return Entry->FileKind;
1433}
1434
Chris Lattnera6f037c2009-02-17 08:39:06 +00001435/// Return the filename or buffer identifier of the buffer the location is in.
James Dennett87a2acf2012-06-17 03:22:59 +00001436/// Note that this name does not respect \#line directives. Use getPresumedLoc
Chris Lattnera6f037c2009-02-17 08:39:06 +00001437/// for normal clients.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001438const char *SourceManager::getBufferName(SourceLocation Loc,
1439 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001440 if (isInvalid(Loc, Invalid)) return "<invalid loc>";
Mike Stump11289f42009-09-09 15:08:12 +00001441
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001442 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
Chris Lattnera6f037c2009-02-17 08:39:06 +00001443}
1444
Chris Lattner88ea93e2009-02-04 01:06:56 +00001445
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001446/// getPresumedLoc - This method returns the "presumed" location of a
James Dennett87a2acf2012-06-17 03:22:59 +00001447/// SourceLocation specifies. A "presumed location" can be modified by \#line
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001448/// or GNU line marker directives. This provides a view on the data that a
1449/// user should see in diagnostics, for example.
1450///
Chandler Carruth64ee7822011-07-26 05:17:23 +00001451/// Note that a presumed location is always given as the expansion point of an
1452/// expansion location, not at the spelling location.
Richard Smith0b50cb72012-11-14 23:55:25 +00001453PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc,
1454 bool UseLineDirectives) const {
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001455 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001456
Chandler Carruth64ee7822011-07-26 05:17:23 +00001457 // Presumed locations are always for expansion points.
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001458 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +00001459
Douglas Gregor49f754f2011-04-20 00:21:03 +00001460 bool Invalid = false;
1461 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1462 if (Invalid || !Entry.isFile())
1463 return PresumedLoc();
1464
1465 const SrcMgr::FileInfo &FI = Entry.getFile();
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001466 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump11289f42009-09-09 15:08:12 +00001467
Chris Lattnerd4293922009-02-04 01:55:42 +00001468 // To get the source name, first consult the FileEntry (if one exists)
1469 // before the MemBuffer as this will avoid unnecessarily paging in the
1470 // MemBuffer.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001471 const char *Filename;
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001472 if (C->OrigEntry)
1473 Filename = C->OrigEntry->getName();
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001474 else
1475 Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
Douglas Gregor49f754f2011-04-20 00:21:03 +00001476
Douglas Gregor75f26d62010-11-02 00:39:22 +00001477 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1478 if (Invalid)
1479 return PresumedLoc();
1480 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1481 if (Invalid)
1482 return PresumedLoc();
1483
Chris Lattnerd4293922009-02-04 01:55:42 +00001484 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001485
Chris Lattnerd4293922009-02-04 01:55:42 +00001486 // If we have #line directives in this file, update and overwrite the physical
1487 // location info if appropriate.
Richard Smith0b50cb72012-11-14 23:55:25 +00001488 if (UseLineDirectives && FI.hasLineDirectives()) {
Chris Lattnerd4293922009-02-04 01:55:42 +00001489 assert(LineTable && "Can't have linetable entries without a LineTable!");
1490 // See if there is a #line directive before this. If so, get it.
1491 if (const LineEntry *Entry =
Douglas Gregor02c2dbf2012-06-08 16:40:28 +00001492 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
Chris Lattnerc1219ff2009-02-04 02:00:59 +00001493 // If the LineEntry indicates a filename, use it.
Chris Lattnerd4293922009-02-04 01:55:42 +00001494 if (Entry->FilenameID != -1)
1495 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerc1219ff2009-02-04 02:00:59 +00001496
1497 // Use the line number specified by the LineEntry. This line number may
1498 // be multiple lines down from the line entry. Add the difference in
1499 // physical line numbers from the query point and the line marker to the
1500 // total.
1501 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1502 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump11289f42009-09-09 15:08:12 +00001503
Chris Lattner20c50ba2009-02-04 02:15:40 +00001504 // Note that column numbers are not molested by line markers.
Mike Stump11289f42009-09-09 15:08:12 +00001505
Chris Lattner1c967782009-02-04 06:25:26 +00001506 // Handle virtual #include manipulation.
1507 if (Entry->IncludeOffset) {
1508 IncludeLoc = getLocForStartOfFile(LocInfo.first);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001509 IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
Chris Lattner1c967782009-02-04 06:25:26 +00001510 }
Chris Lattnerd4293922009-02-04 01:55:42 +00001511 }
1512 }
1513
1514 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattner4fa23622009-01-26 00:43:02 +00001515}
1516
Benjamin Kramere7800df2013-09-27 17:12:50 +00001517/// \brief Returns whether the PresumedLoc for a given SourceLocation is
1518/// in the main file.
1519///
1520/// This computes the "presumed" location for a SourceLocation, then checks
1521/// whether it came from a file other than the main file. This is different
1522/// from isWrittenInMainFile() because it takes line marker directives into
1523/// account.
1524bool SourceManager::isInMainFile(SourceLocation Loc) const {
1525 if (Loc.isInvalid()) return false;
1526
1527 // Presumed locations are always for expansion points.
1528 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1529
1530 bool Invalid = false;
1531 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1532 if (Invalid || !Entry.isFile())
1533 return false;
1534
1535 const SrcMgr::FileInfo &FI = Entry.getFile();
1536
1537 // Check if there is a line directive for this location.
1538 if (FI.hasLineDirectives())
1539 if (const LineEntry *Entry =
1540 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
1541 if (Entry->IncludeOffset)
1542 return false;
1543
1544 return FI.getIncludeLoc().isInvalid();
1545}
1546
James Dennettaa61cbb2013-11-24 01:47:49 +00001547/// \brief The size of the SLocEntry that \p FID represents.
Argyrios Kyrtzidis296374b52011-08-23 21:02:28 +00001548unsigned SourceManager::getFileIDSize(FileID FID) const {
1549 bool Invalid = false;
1550 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1551 if (Invalid)
1552 return 0;
1553
1554 int ID = FID.ID;
1555 unsigned NextOffset;
1556 if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
1557 NextOffset = getNextLocalOffset();
1558 else if (ID+1 == -1)
1559 NextOffset = MaxLoadedOffset;
1560 else
1561 NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
1562
1563 return NextOffset - Entry.getOffset() - 1;
1564}
1565
Chris Lattner4fa23622009-01-26 00:43:02 +00001566//===----------------------------------------------------------------------===//
1567// Other miscellaneous methods.
1568//===----------------------------------------------------------------------===//
1569
Douglas Gregore6642762011-02-03 17:17:35 +00001570/// \brief Retrieve the inode for the given file entry, if possible.
1571///
1572/// This routine involves a system call, and therefore should only be used
1573/// in non-performance-critical code.
Rafael Espindola073ff102013-07-29 21:26:52 +00001574static Optional<llvm::sys::fs::UniqueID>
1575getActualFileUID(const FileEntry *File) {
Douglas Gregore6642762011-02-03 17:17:35 +00001576 if (!File)
David Blaikie7a30dc52013-02-21 01:47:18 +00001577 return None;
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001578
Rafael Espindola073ff102013-07-29 21:26:52 +00001579 llvm::sys::fs::UniqueID ID;
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001580 if (llvm::sys::fs::getUniqueID(File->getName(), ID))
David Blaikie7a30dc52013-02-21 01:47:18 +00001581 return None;
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001582
1583 return ID;
Douglas Gregore6642762011-02-03 17:17:35 +00001584}
1585
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001586/// \brief Get the source location for the given file:line:col triplet.
1587///
1588/// If the source file is included multiple times, the source location will
Douglas Gregor925296b2011-07-19 16:10:42 +00001589/// be based upon an arbitrary inclusion.
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001590SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001591 unsigned Line,
1592 unsigned Col) const {
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001593 assert(SourceFile && "Null source file!");
1594 assert(Line && Col && "Line and column should start from 1!");
1595
Argyrios Kyrtzidis04a6e5f2011-09-27 17:22:25 +00001596 FileID FirstFID = translateFile(SourceFile);
1597 return translateLineCol(FirstFID, Line, Col);
1598}
1599
1600/// \brief Get the FileID for the given file.
1601///
1602/// If the source file is included multiple times, the FileID will be the
1603/// first inclusion.
1604FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
1605 assert(SourceFile && "Null source file!");
1606
Douglas Gregore6642762011-02-03 17:17:35 +00001607 // Find the first file ID that corresponds to the given file.
1608 FileID FirstFID;
Mike Stump11289f42009-09-09 15:08:12 +00001609
Douglas Gregore6642762011-02-03 17:17:35 +00001610 // First, check the main file ID, since it is common to look for a
1611 // location in the main file.
Rafael Espindola073ff102013-07-29 21:26:52 +00001612 Optional<llvm::sys::fs::UniqueID> SourceFileUID;
David Blaikie05785d12013-02-20 22:23:23 +00001613 Optional<StringRef> SourceFileName;
Yaron Keren8b563662015-10-03 10:46:20 +00001614 if (MainFileID.isValid()) {
Douglas Gregor49f754f2011-04-20 00:21:03 +00001615 bool Invalid = false;
1616 const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1617 if (Invalid)
Argyrios Kyrtzidis04a6e5f2011-09-27 17:22:25 +00001618 return FileID();
Douglas Gregor49f754f2011-04-20 00:21:03 +00001619
Douglas Gregore6642762011-02-03 17:17:35 +00001620 if (MainSLoc.isFile()) {
1621 const ContentCache *MainContentCache
1622 = MainSLoc.getFile().getContentCache();
Douglas Gregor6a5be932011-02-11 18:08:15 +00001623 if (!MainContentCache) {
1624 // Can't do anything
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001625 } else if (MainContentCache->OrigEntry == SourceFile) {
Douglas Gregore6642762011-02-03 17:17:35 +00001626 FirstFID = MainFileID;
Douglas Gregor6a5be932011-02-11 18:08:15 +00001627 } else {
Douglas Gregore6642762011-02-03 17:17:35 +00001628 // Fall back: check whether we have the same base name and inode
1629 // as the main file.
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001630 const FileEntry *MainFile = MainContentCache->OrigEntry;
Douglas Gregore6642762011-02-03 17:17:35 +00001631 SourceFileName = llvm::sys::path::filename(SourceFile->getName());
1632 if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) {
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001633 SourceFileUID = getActualFileUID(SourceFile);
1634 if (SourceFileUID) {
Rafael Espindola073ff102013-07-29 21:26:52 +00001635 if (Optional<llvm::sys::fs::UniqueID> MainFileUID =
1636 getActualFileUID(MainFile)) {
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001637 if (*SourceFileUID == *MainFileUID) {
Douglas Gregord766be62011-02-16 19:09:24 +00001638 FirstFID = MainFileID;
1639 SourceFile = MainFile;
1640 }
1641 }
Douglas Gregore6642762011-02-03 17:17:35 +00001642 }
1643 }
1644 }
1645 }
1646 }
1647
1648 if (FirstFID.isInvalid()) {
1649 // The location we're looking for isn't in the main file; look
Douglas Gregor925296b2011-07-19 16:10:42 +00001650 // through all of the local source locations.
1651 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
Douglas Gregor49f754f2011-04-20 00:21:03 +00001652 bool Invalid = false;
Douglas Gregor925296b2011-07-19 16:10:42 +00001653 const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid);
Douglas Gregor49f754f2011-04-20 00:21:03 +00001654 if (Invalid)
Argyrios Kyrtzidis04a6e5f2011-09-27 17:22:25 +00001655 return FileID();
Douglas Gregor49f754f2011-04-20 00:21:03 +00001656
Douglas Gregore6642762011-02-03 17:17:35 +00001657 if (SLoc.isFile() &&
1658 SLoc.getFile().getContentCache() &&
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001659 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
Douglas Gregore6642762011-02-03 17:17:35 +00001660 FirstFID = FileID::get(I);
1661 break;
1662 }
1663 }
Douglas Gregor925296b2011-07-19 16:10:42 +00001664 // If that still didn't help, try the modules.
1665 if (FirstFID.isInvalid()) {
1666 for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
1667 const SLocEntry &SLoc = getLoadedSLocEntry(I);
1668 if (SLoc.isFile() &&
1669 SLoc.getFile().getContentCache() &&
1670 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1671 FirstFID = FileID::get(-int(I) - 2);
1672 break;
1673 }
1674 }
1675 }
Douglas Gregore6642762011-02-03 17:17:35 +00001676 }
1677
1678 // If we haven't found what we want yet, try again, but this time stat()
1679 // each of the files in case the files have changed since we originally
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001680 // parsed the file.
Douglas Gregore6642762011-02-03 17:17:35 +00001681 if (FirstFID.isInvalid() &&
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001682 (SourceFileName ||
Douglas Gregore6642762011-02-03 17:17:35 +00001683 (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) &&
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001684 (SourceFileUID || (SourceFileUID = getActualFileUID(SourceFile)))) {
Douglas Gregor49f754f2011-04-20 00:21:03 +00001685 bool Invalid = false;
Douglas Gregor925296b2011-07-19 16:10:42 +00001686 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1687 FileID IFileID;
1688 IFileID.ID = I;
1689 const SLocEntry &SLoc = getSLocEntry(IFileID, &Invalid);
Douglas Gregor49f754f2011-04-20 00:21:03 +00001690 if (Invalid)
Argyrios Kyrtzidis04a6e5f2011-09-27 17:22:25 +00001691 return FileID();
Douglas Gregor49f754f2011-04-20 00:21:03 +00001692
Douglas Gregore6642762011-02-03 17:17:35 +00001693 if (SLoc.isFile()) {
1694 const ContentCache *FileContentCache
1695 = SLoc.getFile().getContentCache();
Craig Topperf1186c52014-05-08 06:41:40 +00001696 const FileEntry *Entry = FileContentCache ? FileContentCache->OrigEntry
1697 : nullptr;
Douglas Gregore6642762011-02-03 17:17:35 +00001698 if (Entry &&
Douglas Gregor6a5be932011-02-11 18:08:15 +00001699 *SourceFileName == llvm::sys::path::filename(Entry->getName())) {
Rafael Espindola073ff102013-07-29 21:26:52 +00001700 if (Optional<llvm::sys::fs::UniqueID> EntryUID =
1701 getActualFileUID(Entry)) {
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001702 if (*SourceFileUID == *EntryUID) {
Douglas Gregor6a5be932011-02-11 18:08:15 +00001703 FirstFID = FileID::get(I);
1704 SourceFile = Entry;
1705 break;
1706 }
1707 }
Douglas Gregore6642762011-02-03 17:17:35 +00001708 }
1709 }
1710 }
1711 }
Argyrios Kyrtzidis04a6e5f2011-09-27 17:22:25 +00001712
Ted Kremenekbd1d7fa2012-10-12 22:56:33 +00001713 (void) SourceFile;
Argyrios Kyrtzidis04a6e5f2011-09-27 17:22:25 +00001714 return FirstFID;
Argyrios Kyrtzidis532c5192011-09-19 20:40:29 +00001715}
1716
1717/// \brief Get the source location in \arg FID for the given line:col.
1718/// Returns null location if \arg FID is not a file SLocEntry.
1719SourceLocation SourceManager::translateLineCol(FileID FID,
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001720 unsigned Line,
1721 unsigned Col) const {
Aaron Ballmanef1cf832013-11-18 18:29:00 +00001722 // Lines are used as a one-based index into a zero-based array. This assert
1723 // checks for possible buffer underruns.
Gabor Horvathfe2c0ff2015-12-01 09:00:41 +00001724 assert(Line && Col && "Line and column should start from 1!");
Aaron Ballmanef1cf832013-11-18 18:29:00 +00001725
Argyrios Kyrtzidis532c5192011-09-19 20:40:29 +00001726 if (FID.isInvalid())
1727 return SourceLocation();
1728
1729 bool Invalid = false;
1730 const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1731 if (Invalid)
1732 return SourceLocation();
Alexander Kornienko6d8cf832013-07-29 22:26:10 +00001733
Argyrios Kyrtzidis532c5192011-09-19 20:40:29 +00001734 if (!Entry.isFile())
Douglas Gregore6642762011-02-03 17:17:35 +00001735 return SourceLocation();
1736
Argyrios Kyrtzidis7c2b28a2011-09-20 22:14:54 +00001737 SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
1738
Douglas Gregore6642762011-02-03 17:17:35 +00001739 if (Line == 1 && Col == 1)
Argyrios Kyrtzidis7c2b28a2011-09-20 22:14:54 +00001740 return FileLoc;
Douglas Gregore6642762011-02-03 17:17:35 +00001741
1742 ContentCache *Content
Argyrios Kyrtzidis532c5192011-09-19 20:40:29 +00001743 = const_cast<ContentCache *>(Entry.getFile().getContentCache());
Douglas Gregore6642762011-02-03 17:17:35 +00001744 if (!Content)
1745 return SourceLocation();
Alexander Kornienko6d8cf832013-07-29 22:26:10 +00001746
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001747 // If this is the first use of line information for this buffer, compute the
Douglas Gregor925296b2011-07-19 16:10:42 +00001748 // SourceLineCache for it on demand.
Craig Topperf1186c52014-05-08 06:41:40 +00001749 if (!Content->SourceLineCache) {
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001750 bool MyInvalid = false;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001751 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001752 if (MyInvalid)
1753 return SourceLocation();
1754 }
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001755
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001756 if (Line > Content->NumLines) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001757 unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001758 if (Size > 0)
1759 --Size;
Argyrios Kyrtzidis7c2b28a2011-09-20 22:14:54 +00001760 return FileLoc.getLocWithOffset(Size);
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001761 }
1762
David Blaikie66cc07b2014-06-27 17:40:03 +00001763 llvm::MemoryBuffer *Buffer = Content->getBuffer(Diag, *this);
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001764 unsigned FilePos = Content->SourceLineCache[Line - 1];
Dylan Noblesmith2a8bc152011-12-19 08:51:05 +00001765 const char *Buf = Buffer->getBufferStart() + FilePos;
1766 unsigned BufLength = Buffer->getBufferSize() - FilePos;
Argyrios Kyrtzidis7c2b28a2011-09-20 22:14:54 +00001767 if (BufLength == 0)
1768 return FileLoc.getLocWithOffset(FilePos);
1769
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001770 unsigned i = 0;
1771
1772 // Check that the given column is valid.
1773 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1774 ++i;
Alexander Kornienko6d8cf832013-07-29 22:26:10 +00001775 return FileLoc.getLocWithOffset(FilePos + i);
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001776}
1777
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001778/// \brief Compute a map of macro argument chunks to their expanded source
1779/// location. Chunks that are not part of a macro argument will map to an
1780/// invalid source location. e.g. if a file contains one macro argument at
1781/// offset 100 with length 10, this is how the map will be formed:
1782/// 0 -> SourceLocation()
1783/// 100 -> Expanded macro arg location
1784/// 110 -> SourceLocation()
Argyrios Kyrtzidis4bdd6aa2011-09-26 08:01:50 +00001785void SourceManager::computeMacroArgsCache(MacroArgsMap *&CachePtr,
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001786 FileID FID) const {
Yaron Keren8b563662015-10-03 10:46:20 +00001787 assert(FID.isValid());
Argyrios Kyrtzidis4bdd6aa2011-09-26 08:01:50 +00001788 assert(!CachePtr);
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001789
Argyrios Kyrtzidis4bdd6aa2011-09-26 08:01:50 +00001790 CachePtr = new MacroArgsMap();
1791 MacroArgsMap &MacroArgsCache = *CachePtr;
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001792 // Initially no macro argument chunk is present.
1793 MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
1794
1795 int ID = FID.ID;
1796 while (1) {
1797 ++ID;
1798 // Stop if there are no more FileIDs to check.
1799 if (ID > 0) {
1800 if (unsigned(ID) >= local_sloc_entry_size())
1801 return;
1802 } else if (ID == -1) {
1803 return;
1804 }
1805
Argyrios Kyrtzidisfe683022013-06-07 17:57:59 +00001806 bool Invalid = false;
1807 const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);
1808 if (Invalid)
1809 return;
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001810 if (Entry.isFile()) {
1811 SourceLocation IncludeLoc = Entry.getFile().getIncludeLoc();
1812 if (IncludeLoc.isInvalid())
1813 continue;
1814 if (!isInFileID(IncludeLoc, FID))
1815 return; // No more files/macros that may be "contained" in this file.
1816
1817 // Skip the files/macros of the #include'd file, we only care about macros
1818 // that lexed macro arguments from our file.
1819 if (Entry.getFile().NumCreatedFIDs)
1820 ID += Entry.getFile().NumCreatedFIDs - 1/*because of next ++ID*/;
1821 continue;
1822 }
1823
Argyrios Kyrtzidise841c902011-12-21 16:56:35 +00001824 const ExpansionInfo &ExpInfo = Entry.getExpansion();
1825
1826 if (ExpInfo.getExpansionLocStart().isFileID()) {
1827 if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
1828 return; // No more files/macros that may be "contained" in this file.
1829 }
1830
1831 if (!ExpInfo.isMacroArgExpansion())
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001832 continue;
Argyrios Kyrtzidise841c902011-12-21 16:56:35 +00001833
Argyrios Kyrtzidis73ccdb92012-10-20 00:51:32 +00001834 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1835 ExpInfo.getSpellingLoc(),
1836 SourceLocation::getMacroLoc(Entry.getOffset()),
1837 getFileIDSize(FileID::get(ID)));
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001838 }
1839}
1840
Argyrios Kyrtzidis73ccdb92012-10-20 00:51:32 +00001841void SourceManager::associateFileChunkWithMacroArgExp(
1842 MacroArgsMap &MacroArgsCache,
1843 FileID FID,
1844 SourceLocation SpellLoc,
1845 SourceLocation ExpansionLoc,
1846 unsigned ExpansionLength) const {
1847 if (!SpellLoc.isFileID()) {
1848 unsigned SpellBeginOffs = SpellLoc.getOffset();
1849 unsigned SpellEndOffs = SpellBeginOffs + ExpansionLength;
1850
1851 // The spelling range for this macro argument expansion can span multiple
1852 // consecutive FileID entries. Go through each entry contained in the
1853 // spelling range and if one is itself a macro argument expansion, recurse
1854 // and associate the file chunk that it represents.
1855
1856 FileID SpellFID; // Current FileID in the spelling range.
1857 unsigned SpellRelativeOffs;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001858 std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);
Argyrios Kyrtzidis73ccdb92012-10-20 00:51:32 +00001859 while (1) {
1860 const SLocEntry &Entry = getSLocEntry(SpellFID);
1861 unsigned SpellFIDBeginOffs = Entry.getOffset();
1862 unsigned SpellFIDSize = getFileIDSize(SpellFID);
1863 unsigned SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;
1864 const ExpansionInfo &Info = Entry.getExpansion();
1865 if (Info.isMacroArgExpansion()) {
1866 unsigned CurrSpellLength;
1867 if (SpellFIDEndOffs < SpellEndOffs)
1868 CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
1869 else
1870 CurrSpellLength = ExpansionLength;
1871 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1872 Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),
1873 ExpansionLoc, CurrSpellLength);
1874 }
1875
1876 if (SpellFIDEndOffs >= SpellEndOffs)
1877 return; // we covered all FileID entries in the spelling range.
1878
1879 // Move to the next FileID entry in the spelling range.
1880 unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
1881 ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);
1882 ExpansionLength -= advance;
1883 ++SpellFID.ID;
1884 SpellRelativeOffs = 0;
1885 }
1886
1887 }
1888
1889 assert(SpellLoc.isFileID());
1890
1891 unsigned BeginOffs;
1892 if (!isInFileID(SpellLoc, FID, &BeginOffs))
1893 return;
1894
1895 unsigned EndOffs = BeginOffs + ExpansionLength;
1896
1897 // Add a new chunk for this macro argument. A previous macro argument chunk
1898 // may have been lexed again, so e.g. if the map is
1899 // 0 -> SourceLocation()
1900 // 100 -> Expanded loc #1
1901 // 110 -> SourceLocation()
1902 // and we found a new macro FileID that lexed from offet 105 with length 3,
1903 // the new map will be:
1904 // 0 -> SourceLocation()
1905 // 100 -> Expanded loc #1
1906 // 105 -> Expanded loc #2
1907 // 108 -> Expanded loc #1
1908 // 110 -> SourceLocation()
1909 //
1910 // Since re-lexed macro chunks will always be the same size or less of
1911 // previous chunks, we only need to find where the ending of the new macro
1912 // chunk is mapped to and update the map with new begin/end mappings.
1913
1914 MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
1915 --I;
1916 SourceLocation EndOffsMappedLoc = I->second;
1917 MacroArgsCache[BeginOffs] = ExpansionLoc;
1918 MacroArgsCache[EndOffs] = EndOffsMappedLoc;
1919}
1920
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001921/// \brief If \arg Loc points inside a function macro argument, the returned
1922/// location will be the macro location in which the argument was expanded.
1923/// If a macro argument is used multiple times, the expanded location will
1924/// be at the first expansion of the argument.
1925/// e.g.
1926/// MY_MACRO(foo);
1927/// ^
1928/// Passing a file location pointing at 'foo', will yield a macro location
1929/// where 'foo' was expanded into.
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001930SourceLocation
1931SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001932 if (Loc.isInvalid() || !Loc.isFileID())
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001933 return Loc;
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001934
1935 FileID FID;
1936 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001937 std::tie(FID, Offset) = getDecomposedLoc(Loc);
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001938 if (FID.isInvalid())
1939 return Loc;
1940
Argyrios Kyrtzidis4bdd6aa2011-09-26 08:01:50 +00001941 MacroArgsMap *&MacroArgsCache = MacroArgsCacheMap[FID];
1942 if (!MacroArgsCache)
1943 computeMacroArgsCache(MacroArgsCache, FID);
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001944
Argyrios Kyrtzidis4bdd6aa2011-09-26 08:01:50 +00001945 assert(!MacroArgsCache->empty());
1946 MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001947 --I;
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001948
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001949 unsigned MacroArgBeginOffs = I->first;
1950 SourceLocation MacroArgExpandedLoc = I->second;
1951 if (MacroArgExpandedLoc.isValid())
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001952 return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001953
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001954 return Loc;
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001955}
1956
Argyrios Kyrtzidis37613a92013-04-13 01:03:57 +00001957std::pair<FileID, unsigned>
1958SourceManager::getDecomposedIncludedLoc(FileID FID) const {
Argyrios Kyrtzidis5dca8642013-05-24 22:24:04 +00001959 if (FID.isInvalid())
1960 return std::make_pair(FileID(), 0);
1961
Argyrios Kyrtzidis37613a92013-04-13 01:03:57 +00001962 // Uses IncludedLocMap to retrieve/cache the decomposed loc.
1963
1964 typedef std::pair<FileID, unsigned> DecompTy;
1965 typedef llvm::DenseMap<FileID, DecompTy> MapTy;
1966 std::pair<MapTy::iterator, bool>
1967 InsertOp = IncludedLocMap.insert(std::make_pair(FID, DecompTy()));
1968 DecompTy &DecompLoc = InsertOp.first->second;
1969 if (!InsertOp.second)
1970 return DecompLoc; // already in map.
1971
1972 SourceLocation UpperLoc;
Argyrios Kyrtzidis5dca8642013-05-24 22:24:04 +00001973 bool Invalid = false;
1974 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1975 if (!Invalid) {
1976 if (Entry.isExpansion())
1977 UpperLoc = Entry.getExpansion().getExpansionLocStart();
1978 else
1979 UpperLoc = Entry.getFile().getIncludeLoc();
1980 }
Argyrios Kyrtzidis37613a92013-04-13 01:03:57 +00001981
1982 if (UpperLoc.isValid())
1983 DecompLoc = getDecomposedLoc(UpperLoc);
1984
1985 return DecompLoc;
1986}
1987
Chandler Carruth64ee7822011-07-26 05:17:23 +00001988/// Given a decomposed source location, move it up the include/expansion stack
1989/// to the parent source location. If this is possible, return the decomposed
1990/// version of the parent in Loc and return false. If Loc is the top-level
1991/// entry, return true and don't modify it.
Chris Lattnera99fa1a2010-05-07 20:35:24 +00001992static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1993 const SourceManager &SM) {
Argyrios Kyrtzidis37613a92013-04-13 01:03:57 +00001994 std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
1995 if (UpperLoc.first.isInvalid())
Chris Lattnera99fa1a2010-05-07 20:35:24 +00001996 return true; // We reached the top.
Argyrios Kyrtzidis37613a92013-04-13 01:03:57 +00001997
1998 Loc = UpperLoc;
Chris Lattnera99fa1a2010-05-07 20:35:24 +00001999 return false;
2000}
Ted Kremenek08037042013-02-27 00:00:26 +00002001
2002/// Return the cache entry for comparing the given file IDs
2003/// for isBeforeInTranslationUnit.
2004InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
2005 FileID RFID) const {
2006 // This is a magic number for limiting the cache size. It was experimentally
2007 // derived from a small Objective-C project (where the cache filled
2008 // out to ~250 items). We can make it larger if necessary.
2009 enum { MagicCacheSize = 300 };
2010 IsBeforeInTUCacheKey Key(LFID, RFID);
2011
2012 // If the cache size isn't too large, do a lookup and if necessary default
2013 // construct an entry. We can then return it to the caller for direct
2014 // use. When they update the value, the cache will get automatically
2015 // updated as well.
2016 if (IBTUCache.size() < MagicCacheSize)
2017 return IBTUCache[Key];
2018
2019 // Otherwise, do a lookup that will not construct a new value.
2020 InBeforeInTUCache::iterator I = IBTUCache.find(Key);
2021 if (I != IBTUCache.end())
2022 return I->second;
2023
2024 // Fall back to the overflow value.
2025 return IBTUCacheOverflow;
2026}
Chris Lattnera99fa1a2010-05-07 20:35:24 +00002027
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00002028/// \brief Determines the order of 2 source locations in the translation unit.
2029///
2030/// \returns true if LHS source location comes before RHS, false otherwise.
2031bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
2032 SourceLocation RHS) const {
2033 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
2034 if (LHS == RHS)
2035 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002036
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00002037 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
2038 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00002039
Argyrios Kyrtzidis5fd822c2013-05-24 23:47:43 +00002040 // getDecomposedLoc may have failed to return a valid FileID because, e.g. it
2041 // is a serialized one referring to a file that was removed after we loaded
2042 // the PCH.
Argyrios Kyrtzidis5dca8642013-05-24 22:24:04 +00002043 if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
Argyrios Kyrtzidisd6111d32013-05-25 01:03:03 +00002044 return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
Argyrios Kyrtzidis5dca8642013-05-24 22:24:04 +00002045
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00002046 // If the source locations are in the same file, just compare offsets.
2047 if (LOffs.first == ROffs.first)
2048 return LOffs.second < ROffs.second;
2049
2050 // If we are comparing a source location with multiple locations in the same
2051 // file, we get a big win by caching the result.
Ted Kremenek08037042013-02-27 00:00:26 +00002052 InBeforeInTUCacheEntry &IsBeforeInTUCache =
2053 getInBeforeInTUCache(LOffs.first, ROffs.first);
2054
2055 // If we are comparing a source location with multiple locations in the same
2056 // file, we get a big win by caching the result.
Chris Lattner46e3b482010-05-07 05:10:46 +00002057 if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
2058 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Mike Stump11289f42009-09-09 15:08:12 +00002059
Chris Lattner66d2f922010-05-07 01:17:07 +00002060 // Okay, we missed in the cache, start updating the cache for this query.
Argyrios Kyrtzidisac199bf2011-08-17 00:31:18 +00002061 IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
2062 /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID);
Mike Stump11289f42009-09-09 15:08:12 +00002063
Douglas Gregor925296b2011-07-19 16:10:42 +00002064 // We need to find the common ancestor. The only way of doing this is to
2065 // build the complete include chain for one and then walking up the chain
2066 // of the other looking for a match.
2067 // We use a map from FileID to Offset to store the chain. Easier than writing
2068 // a custom set hash info that only depends on the first part of a pair.
Argyrios Kyrtzidis37613a92013-04-13 01:03:57 +00002069 typedef llvm::SmallDenseMap<FileID, unsigned, 16> LocSet;
Douglas Gregor925296b2011-07-19 16:10:42 +00002070 LocSet LChain;
Chris Lattner06821c92010-05-07 05:51:13 +00002071 do {
Douglas Gregor925296b2011-07-19 16:10:42 +00002072 LChain.insert(LOffs);
2073 // We catch the case where LOffs is in a file included by ROffs and
2074 // quit early. The other way round unfortunately remains suboptimal.
2075 } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
2076 LocSet::iterator I;
2077 while((I = LChain.find(ROffs.first)) == LChain.end()) {
2078 if (MoveUpIncludeHierarchy(ROffs, *this))
2079 break; // Met at topmost file.
2080 }
2081 if (I != LChain.end())
2082 LOffs = *I;
Mike Stump11289f42009-09-09 15:08:12 +00002083
Chris Lattner06821c92010-05-07 05:51:13 +00002084 // If we exited because we found a nearest common ancestor, compare the
2085 // locations within the common file and cache them.
2086 if (LOffs.first == ROffs.first) {
2087 IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
2088 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00002089 }
Mike Stump11289f42009-09-09 15:08:12 +00002090
Joerg Sonnenberger1d3b4312015-03-16 17:54:54 +00002091 // If we arrived here, the location is either in a built-ins buffer or
2092 // associated with global inline asm. PR5662 and PR22576 are examples.
2093
Douglas Gregor925296b2011-07-19 16:10:42 +00002094 // Clear the lookup cache, it depends on a common location.
Argyrios Kyrtzidisac199bf2011-08-17 00:31:18 +00002095 IsBeforeInTUCache.clear();
Yury Gribov976892f2016-01-28 09:27:46 +00002096 const char *LB = getBuffer(LOffs.first)->getBufferIdentifier();
2097 const char *RB = getBuffer(ROffs.first)->getBufferIdentifier();
2098 bool LIsBuiltins = strcmp("<built-in>", LB) == 0;
2099 bool RIsBuiltins = strcmp("<built-in>", RB) == 0;
Joerg Sonnenberger1d3b4312015-03-16 17:54:54 +00002100 // Sort built-in before non-built-in.
2101 if (LIsBuiltins || RIsBuiltins) {
2102 if (LIsBuiltins != RIsBuiltins)
2103 return LIsBuiltins;
2104 // Both are in built-in buffers, but from different files. We just claim that
2105 // lower IDs come first.
2106 return LOffs.first < ROffs.first;
2107 }
Yury Gribov976892f2016-01-28 09:27:46 +00002108 bool LIsAsm = strcmp("<inline asm>", LB) == 0;
2109 bool RIsAsm = strcmp("<inline asm>", RB) == 0;
Joerg Sonnenberger1d3b4312015-03-16 17:54:54 +00002110 // Sort assembler after built-ins, but before the rest.
2111 if (LIsAsm || RIsAsm) {
2112 if (LIsAsm != RIsAsm)
2113 return RIsAsm;
2114 assert(LOffs.first == ROffs.first);
2115 return false;
2116 }
Yury Gribov154e57f2016-01-28 09:28:18 +00002117 bool LIsScratch = strcmp("<scratch space>", LB) == 0;
2118 bool RIsScratch = strcmp("<scratch space>", RB) == 0;
2119 // Sort scratch after inline asm, but before the rest.
2120 if (LIsScratch || RIsScratch) {
2121 if (LIsScratch != RIsScratch)
2122 return LIsScratch;
2123 return LOffs.second < ROffs.second;
2124 }
Joerg Sonnenberger1d3b4312015-03-16 17:54:54 +00002125 llvm_unreachable("Unsortable locations found");
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00002126}
Chris Lattner4fa23622009-01-26 00:43:02 +00002127
Chris Lattner22eb9722006-06-18 05:43:12 +00002128void SourceManager::PrintStats() const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +00002129 llvm::errs() << "\n*** Source Manager Stats:\n";
2130 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
2131 << " mem buffers mapped.\n";
Douglas Gregor925296b2011-07-19 16:10:42 +00002132 llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
Ted Kremenek43e0c4a2011-07-27 18:41:16 +00002133 << llvm::capacity_in_bytes(LocalSLocEntryTable)
Argyrios Kyrtzidis2cc62092011-07-07 03:40:24 +00002134 << " bytes of capacity), "
Douglas Gregor925296b2011-07-19 16:10:42 +00002135 << NextLocalOffset << "B of Sloc address space used.\n";
2136 llvm::errs() << LoadedSLocEntryTable.size()
2137 << " loaded SLocEntries allocated, "
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00002138 << MaxLoadedOffset - CurrentLoadedOffset
Douglas Gregor925296b2011-07-19 16:10:42 +00002139 << "B of Sloc address space used.\n";
2140
Chris Lattner22eb9722006-06-18 05:43:12 +00002141 unsigned NumLineNumsComputed = 0;
2142 unsigned NumFileBytesMapped = 0;
Chris Lattnerc8233df2009-02-03 07:30:45 +00002143 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
Craig Topperf1186c52014-05-08 06:41:40 +00002144 NumLineNumsComputed += I->second->SourceLineCache != nullptr;
Chris Lattnerc8233df2009-02-03 07:30:45 +00002145 NumFileBytesMapped += I->second->getSizeBytesMapped();
Chris Lattner22eb9722006-06-18 05:43:12 +00002146 }
Argyrios Kyrtzidis4bdd6aa2011-09-26 08:01:50 +00002147 unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
Mike Stump11289f42009-09-09 15:08:12 +00002148
Benjamin Kramer89b422c2009-08-23 12:08:50 +00002149 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00002150 << NumLineNumsComputed << " files with line #'s computed, "
2151 << NumMacroArgsComputed << " files with macro args computed.\n";
Benjamin Kramer89b422c2009-08-23 12:08:50 +00002152 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
2153 << NumBinaryProbes << " binary.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +00002154}
Douglas Gregor258ae542009-04-27 06:38:32 +00002155
Richard Smith03a06dd2015-08-13 00:45:11 +00002156LLVM_DUMP_METHOD void SourceManager::dump() const {
2157 llvm::raw_ostream &out = llvm::errs();
2158
2159 auto DumpSLocEntry = [&](int ID, const SrcMgr::SLocEntry &Entry,
2160 llvm::Optional<unsigned> NextStart) {
2161 out << "SLocEntry <FileID " << ID << "> " << (Entry.isFile() ? "file" : "expansion")
2162 << " <SourceLocation " << Entry.getOffset() << ":";
2163 if (NextStart)
2164 out << *NextStart << ">\n";
2165 else
2166 out << "???\?>\n";
2167 if (Entry.isFile()) {
2168 auto &FI = Entry.getFile();
2169 if (FI.NumCreatedFIDs)
2170 out << " covers <FileID " << ID << ":" << int(ID + FI.NumCreatedFIDs)
2171 << ">\n";
2172 if (FI.getIncludeLoc().isValid())
2173 out << " included from " << FI.getIncludeLoc().getOffset() << "\n";
2174 if (auto *CC = FI.getContentCache()) {
2175 out << " for " << (CC->OrigEntry ? CC->OrigEntry->getName() : "<none>")
2176 << "\n";
2177 if (CC->BufferOverridden)
2178 out << " contents overridden\n";
2179 if (CC->ContentsEntry != CC->OrigEntry) {
2180 out << " contents from "
2181 << (CC->ContentsEntry ? CC->ContentsEntry->getName() : "<none>")
2182 << "\n";
2183 }
2184 }
2185 } else {
2186 auto &EI = Entry.getExpansion();
2187 out << " spelling from " << EI.getSpellingLoc().getOffset() << "\n";
2188 out << " macro " << (EI.isMacroArgExpansion() ? "arg" : "body")
2189 << " range <" << EI.getExpansionLocStart().getOffset() << ":"
2190 << EI.getExpansionLocEnd().getOffset() << ">\n";
2191 }
2192 };
2193
2194 // Dump local SLocEntries.
2195 for (unsigned ID = 0, NumIDs = LocalSLocEntryTable.size(); ID != NumIDs; ++ID) {
2196 DumpSLocEntry(ID, LocalSLocEntryTable[ID],
2197 ID == NumIDs - 1 ? NextLocalOffset
2198 : LocalSLocEntryTable[ID + 1].getOffset());
2199 }
2200 // Dump loaded SLocEntries.
2201 llvm::Optional<unsigned> NextStart;
2202 for (unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
2203 int ID = -(int)Index - 2;
2204 if (SLocEntryLoaded[Index]) {
2205 DumpSLocEntry(ID, LoadedSLocEntryTable[Index], NextStart);
2206 NextStart = LoadedSLocEntryTable[Index].getOffset();
2207 } else {
2208 NextStart = None;
2209 }
2210 }
2211}
2212
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00002213ExternalSLocEntrySource::~ExternalSLocEntrySource() { }
Ted Kremenek8d587902011-04-28 20:36:42 +00002214
2215/// Return the amount of memory used by memory buffers, breaking down
2216/// by heap-backed versus mmap'ed memory.
2217SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
2218 size_t malloc_bytes = 0;
2219 size_t mmap_bytes = 0;
2220
2221 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
2222 if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
2223 switch (MemBufferInfos[i]->getMemoryBufferKind()) {
2224 case llvm::MemoryBuffer::MemoryBuffer_MMap:
2225 mmap_bytes += sized_mapped;
2226 break;
2227 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
2228 malloc_bytes += sized_mapped;
2229 break;
2230 }
2231
2232 return MemoryBufferSizes(malloc_bytes, mmap_bytes);
2233}
2234
Ted Kremenek120992a2011-07-26 23:46:06 +00002235size_t SourceManager::getDataStructureSizes() const {
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +00002236 size_t size = llvm::capacity_in_bytes(MemBufferInfos)
Ted Kremenek43e0c4a2011-07-27 18:41:16 +00002237 + llvm::capacity_in_bytes(LocalSLocEntryTable)
2238 + llvm::capacity_in_bytes(LoadedSLocEntryTable)
2239 + llvm::capacity_in_bytes(SLocEntryLoaded)
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +00002240 + llvm::capacity_in_bytes(FileInfos);
2241
2242 if (OverriddenFilesInfo)
2243 size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);
2244
2245 return size;
Ted Kremenek120992a2011-07-26 23:46:06 +00002246}