blob: d2d556288d65ff6c8c8c9253f40494af2fd70942 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SourceManager.cpp - Track and cache source files -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the SourceManager interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Basic/SourceManager.h"
Douglas Gregoraea67db2010-03-15 22:54:52 +000015#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "clang/Basic/FileManager.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000017#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregor86a4d0d2011-02-03 17:17:35 +000018#include "llvm/ADT/Optional.h"
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +000019#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "llvm/ADT/StringSwitch.h"
21#include "llvm/Support/Capacity.h"
Chris Lattner5e36a7a2007-07-24 05:57:19 +000022#include "llvm/Support/Compiler.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000024#include "llvm/Support/Path.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000025#include "llvm/Support/raw_ostream.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026#include <algorithm>
Douglas Gregorf715ca12010-03-16 00:06:06 +000027#include <cstring>
Chandler Carruth55fc8732012-12-04 09:13:33 +000028#include <string>
Douglas Gregor86a4d0d2011-02-03 17:17:35 +000029#include <sys/stat.h>
Douglas Gregoraea67db2010-03-15 22:54:52 +000030
Reid Spencer5f016e22007-07-11 17:01:13 +000031using namespace clang;
32using namespace SrcMgr;
33using llvm::MemoryBuffer;
34
Chris Lattner23b5dc62009-02-04 00:40:31 +000035//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +000036// SourceManager Helper Classes
Chris Lattner23b5dc62009-02-04 00:40:31 +000037//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +000038
Ted Kremenek78d85f52007-10-30 21:08:08 +000039ContentCache::~ContentCache() {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000040 if (shouldFreeBuffer())
41 delete Buffer.getPointer();
Reid Spencer5f016e22007-07-11 17:01:13 +000042}
43
Chandler Carruth3201f382011-07-26 05:17:23 +000044/// getSizeBytesMapped - Returns the number of bytes actually mapped for this
45/// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
Ted Kremenekc16c2082009-01-06 01:55:26 +000046unsigned ContentCache::getSizeBytesMapped() const {
Douglas Gregorc8151082010-03-16 22:53:51 +000047 return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
Ted Kremenekc16c2082009-01-06 01:55:26 +000048}
49
Ted Kremenekf61b8312011-04-28 20:36:42 +000050/// Returns the kind of memory used to back the memory buffer for
51/// this content cache. This is used for performance analysis.
52llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
53 assert(Buffer.getPointer());
54
55 // Should be unreachable, but keep for sanity.
56 if (!Buffer.getPointer())
57 return llvm::MemoryBuffer::MemoryBuffer_Malloc;
58
59 const llvm::MemoryBuffer *buf = Buffer.getPointer();
60 return buf->getBufferKind();
61}
62
Ted Kremenekc16c2082009-01-06 01:55:26 +000063/// getSize - Returns the size of the content encapsulated by this ContentCache.
64/// This can be the size of the source file or the size of an arbitrary
65/// scratch buffer. If the ContentCache encapsulates a source file, that
Douglas Gregor29684422009-12-02 06:49:09 +000066/// file is not lazily brought in from disk to satisfy this query.
Ted Kremenekc16c2082009-01-06 01:55:26 +000067unsigned ContentCache::getSize() const {
Douglas Gregorc8151082010-03-16 22:53:51 +000068 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +000069 : (unsigned) ContentsEntry->getSize();
Ted Kremenekc16c2082009-01-06 01:55:26 +000070}
71
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000072void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B,
73 bool DoNotFree) {
Argyrios Kyrtzidisd54dff02012-05-03 21:50:39 +000074 if (B && B == Buffer.getPointer()) {
Argyrios Kyrtzidisa4288c42011-12-10 01:38:26 +000075 assert(0 && "Replacing with the same buffer");
76 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
77 return;
78 }
Douglas Gregor29684422009-12-02 06:49:09 +000079
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000080 if (shouldFreeBuffer())
81 delete Buffer.getPointer();
Douglas Gregorc8151082010-03-16 22:53:51 +000082 Buffer.setPointer(B);
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000083 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
Douglas Gregor29684422009-12-02 06:49:09 +000084}
85
David Blaikied6471f72011-09-25 23:23:43 +000086const llvm::MemoryBuffer *ContentCache::getBuffer(DiagnosticsEngine &Diag,
Chris Lattner5c5db4e2010-04-20 20:49:23 +000087 const SourceManager &SM,
Chris Lattnere127a0d2010-04-20 20:35:58 +000088 SourceLocation Loc,
Douglas Gregor36c35ba2010-03-16 00:35:39 +000089 bool *Invalid) const {
Chris Lattnerb088cd32010-11-23 08:50:03 +000090 // Lazily create the Buffer for ContentCaches that wrap files. If we already
Chris Lattnerfc8f0e12011-04-15 05:22:18 +000091 // computed it, just return what we have.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070092 if (Buffer.getPointer() || !ContentsEntry) {
Chris Lattnerb088cd32010-11-23 08:50:03 +000093 if (Invalid)
94 *Invalid = isBufferInvalid();
Chris Lattner38caec42010-04-20 18:14:03 +000095
Chris Lattnerb088cd32010-11-23 08:50:03 +000096 return Buffer.getPointer();
97 }
Benjamin Kramer5807d9c2010-11-18 12:46:39 +000098
Chris Lattnerb088cd32010-11-23 08:50:03 +000099 std::string ErrorStr;
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000100 bool isVolatile = SM.userFilesAreVolatile() && !IsSystemFile;
101 Buffer.setPointer(SM.getFileManager().getBufferForFile(ContentsEntry,
102 &ErrorStr,
103 isVolatile));
Chris Lattnerb088cd32010-11-23 08:50:03 +0000104
105 // If we were unable to open the file, then we are in an inconsistent
106 // situation where the content cache referenced a file which no longer
107 // exists. Most likely, we were using a stat cache with an invalid entry but
108 // the file could also have been removed during processing. Since we can't
109 // really deal with this situation, just create an empty buffer.
110 //
111 // FIXME: This is definitely not ideal, but our immediate clients can't
112 // currently handle returning a null entry here. Ideally we should detect
113 // that we are in an inconsistent situation and error out as quickly as
114 // possible.
115 if (!Buffer.getPointer()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000116 const StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000117 Buffer.setPointer(MemoryBuffer::getNewMemBuffer(ContentsEntry->getSize(),
Chris Lattnerb088cd32010-11-23 08:50:03 +0000118 "<invalid>"));
119 char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart());
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000120 for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
Chris Lattnerb088cd32010-11-23 08:50:03 +0000121 Ptr[i] = FillStr[i % FillStr.size()];
122
123 if (Diag.isDiagnosticInFlight())
124 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000125 ContentsEntry->getName(), ErrorStr);
Chris Lattnerb088cd32010-11-23 08:50:03 +0000126 else
127 Diag.Report(Loc, diag::err_cannot_open_file)
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000128 << ContentsEntry->getName() << ErrorStr;
Chris Lattnerb088cd32010-11-23 08:50:03 +0000129
130 Buffer.setInt(Buffer.getInt() | InvalidFlag);
131
132 if (Invalid) *Invalid = true;
133 return Buffer.getPointer();
134 }
135
136 // Check that the file's size is the same as in the file entry (which may
137 // have come from a stat cache).
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000138 if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) {
Chris Lattnerb088cd32010-11-23 08:50:03 +0000139 if (Diag.isDiagnosticInFlight())
140 Diag.SetDelayedDiagnostic(diag::err_file_modified,
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000141 ContentsEntry->getName());
Chris Lattnerb088cd32010-11-23 08:50:03 +0000142 else
143 Diag.Report(Loc, diag::err_file_modified)
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000144 << ContentsEntry->getName();
Chris Lattnerb088cd32010-11-23 08:50:03 +0000145
146 Buffer.setInt(Buffer.getInt() | InvalidFlag);
147 if (Invalid) *Invalid = true;
148 return Buffer.getPointer();
149 }
Eric Christopher156119d2011-04-09 00:01:04 +0000150
Chris Lattnerb088cd32010-11-23 08:50:03 +0000151 // If the buffer is valid, check to see if it has a UTF Byte Order Mark
Eric Christopher156119d2011-04-09 00:01:04 +0000152 // (BOM). We only support UTF-8 with and without a BOM right now. See
Chris Lattnerb088cd32010-11-23 08:50:03 +0000153 // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000154 StringRef BufStr = Buffer.getPointer()->getBuffer();
Eric Christopher156119d2011-04-09 00:01:04 +0000155 const char *InvalidBOM = llvm::StringSwitch<const char *>(BufStr)
Chris Lattnerb088cd32010-11-23 08:50:03 +0000156 .StartsWith("\xFE\xFF", "UTF-16 (BE)")
157 .StartsWith("\xFF\xFE", "UTF-16 (LE)")
158 .StartsWith("\x00\x00\xFE\xFF", "UTF-32 (BE)")
159 .StartsWith("\xFF\xFE\x00\x00", "UTF-32 (LE)")
160 .StartsWith("\x2B\x2F\x76", "UTF-7")
161 .StartsWith("\xF7\x64\x4C", "UTF-1")
162 .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
163 .StartsWith("\x0E\xFE\xFF", "SDSU")
164 .StartsWith("\xFB\xEE\x28", "BOCU-1")
165 .StartsWith("\x84\x31\x95\x33", "GB-18030")
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700166 .Default(nullptr);
Chris Lattnerb088cd32010-11-23 08:50:03 +0000167
Eric Christopher156119d2011-04-09 00:01:04 +0000168 if (InvalidBOM) {
Chris Lattnerb088cd32010-11-23 08:50:03 +0000169 Diag.Report(Loc, diag::err_unsupported_bom)
Eric Christopher156119d2011-04-09 00:01:04 +0000170 << InvalidBOM << ContentsEntry->getName();
Chris Lattnerb088cd32010-11-23 08:50:03 +0000171 Buffer.setInt(Buffer.getInt() | InvalidFlag);
Ted Kremenek5b034ad2009-01-06 22:43:04 +0000172 }
Douglas Gregoraea67db2010-03-15 22:54:52 +0000173
Douglas Gregorc8151082010-03-16 22:53:51 +0000174 if (Invalid)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000175 *Invalid = isBufferInvalid();
Douglas Gregorc8151082010-03-16 22:53:51 +0000176
177 return Buffer.getPointer();
Ted Kremenekc16c2082009-01-06 01:55:26 +0000178}
179
Chris Lattner5f9e2722011-07-23 10:55:15 +0000180unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000181 // Look up the filename in the string table, returning the pre-existing value
182 // if it exists.
Mike Stump1eb44332009-09-09 15:08:12 +0000183 llvm::StringMapEntry<unsigned> &Entry =
Jay Foad65aa6882011-06-21 15:13:30 +0000184 FilenameIDs.GetOrCreateValue(Name, ~0U);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000185 if (Entry.getValue() != ~0U)
186 return Entry.getValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000187
Chris Lattner5b9a5042009-01-26 07:57:50 +0000188 // Otherwise, assign this the next available ID.
189 Entry.setValue(FilenamesByID.size());
190 FilenamesByID.push_back(&Entry);
191 return FilenamesByID.size()-1;
192}
193
Chris Lattnerac50e342009-02-03 22:13:05 +0000194/// AddLineNote - Add a line note to the line table that indicates that there
James Dennett7285a062012-06-15 21:28:23 +0000195/// is a \#line at the specified FID/Offset location which changes the presumed
Chris Lattnerac50e342009-02-03 22:13:05 +0000196/// location to LineNo/FilenameID.
Douglas Gregor47d9de62012-06-08 16:40:28 +0000197void LineTableInfo::AddLineNote(FileID FID, unsigned Offset,
Chris Lattnerac50e342009-02-03 22:13:05 +0000198 unsigned LineNo, int FilenameID) {
Chris Lattner23b5dc62009-02-04 00:40:31 +0000199 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000200
Chris Lattner23b5dc62009-02-04 00:40:31 +0000201 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
202 "Adding line entries out of order!");
Mike Stump1eb44332009-09-09 15:08:12 +0000203
Chris Lattner9d79eba2009-02-04 05:21:58 +0000204 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
Chris Lattner137b6a62009-02-04 06:25:26 +0000205 unsigned IncludeOffset = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000206
Chris Lattner9d79eba2009-02-04 05:21:58 +0000207 if (!Entries.empty()) {
208 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
209 // that we are still in "foo.h".
210 if (FilenameID == -1)
211 FilenameID = Entries.back().FilenameID;
Mike Stump1eb44332009-09-09 15:08:12 +0000212
Chris Lattner137b6a62009-02-04 06:25:26 +0000213 // If we are after a line marker that switched us to system header mode, or
214 // that set #include information, preserve it.
Chris Lattner9d79eba2009-02-04 05:21:58 +0000215 Kind = Entries.back().FileKind;
Chris Lattner137b6a62009-02-04 06:25:26 +0000216 IncludeOffset = Entries.back().IncludeOffset;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000217 }
Mike Stump1eb44332009-09-09 15:08:12 +0000218
Chris Lattner137b6a62009-02-04 06:25:26 +0000219 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
220 IncludeOffset));
Chris Lattnerac50e342009-02-03 22:13:05 +0000221}
222
Chris Lattner9d79eba2009-02-04 05:21:58 +0000223/// AddLineNote This is the same as the previous version of AddLineNote, but is
224/// used for GNU line markers. If EntryExit is 0, then this doesn't change the
James Dennettb8950b82012-06-17 03:22:59 +0000225/// presumed \#include stack. If it is 1, this is a file entry, if it is 2 then
Chris Lattner9d79eba2009-02-04 05:21:58 +0000226/// this is a file exit. FileKind specifies whether this is a system header or
227/// extern C system header.
Douglas Gregor47d9de62012-06-08 16:40:28 +0000228void LineTableInfo::AddLineNote(FileID FID, unsigned Offset,
Chris Lattner9d79eba2009-02-04 05:21:58 +0000229 unsigned LineNo, int FilenameID,
230 unsigned EntryExit,
231 SrcMgr::CharacteristicKind FileKind) {
232 assert(FilenameID != -1 && "Unspecified filename should use other accessor");
Mike Stump1eb44332009-09-09 15:08:12 +0000233
Chris Lattner9d79eba2009-02-04 05:21:58 +0000234 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000235
Chris Lattner9d79eba2009-02-04 05:21:58 +0000236 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
237 "Adding line entries out of order!");
238
Chris Lattner137b6a62009-02-04 06:25:26 +0000239 unsigned IncludeOffset = 0;
240 if (EntryExit == 0) { // No #include stack change.
241 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
242 } else if (EntryExit == 1) {
243 IncludeOffset = Offset-1;
244 } else if (EntryExit == 2) {
245 assert(!Entries.empty() && Entries.back().IncludeOffset &&
246 "PPDirectives should have caught case when popping empty include stack");
Mike Stump1eb44332009-09-09 15:08:12 +0000247
Chris Lattner137b6a62009-02-04 06:25:26 +0000248 // Get the include loc of the last entries' include loc as our include loc.
249 IncludeOffset = 0;
250 if (const LineEntry *PrevEntry =
251 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
252 IncludeOffset = PrevEntry->IncludeOffset;
253 }
Mike Stump1eb44332009-09-09 15:08:12 +0000254
Chris Lattner137b6a62009-02-04 06:25:26 +0000255 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
256 IncludeOffset));
Chris Lattner9d79eba2009-02-04 05:21:58 +0000257}
258
259
Chris Lattner3cd949c2009-02-04 01:55:42 +0000260/// FindNearestLineEntry - Find the line entry nearest to FID that is before
261/// it. If there is no line entry before Offset in FID, return null.
Douglas Gregor47d9de62012-06-08 16:40:28 +0000262const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID,
Chris Lattner3cd949c2009-02-04 01:55:42 +0000263 unsigned Offset) {
264 const std::vector<LineEntry> &Entries = LineEntries[FID];
265 assert(!Entries.empty() && "No #line entries for this FID after all!");
266
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000267 // It is very common for the query to be after the last #line, check this
268 // first.
269 if (Entries.back().FileOffset <= Offset)
270 return &Entries.back();
Chris Lattner3cd949c2009-02-04 01:55:42 +0000271
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000272 // Do a binary search to find the maximal element that is still before Offset.
273 std::vector<LineEntry>::const_iterator I =
274 std::upper_bound(Entries.begin(), Entries.end(), Offset);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700275 if (I == Entries.begin()) return nullptr;
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000276 return &*--I;
Chris Lattner3cd949c2009-02-04 01:55:42 +0000277}
Chris Lattnerac50e342009-02-03 22:13:05 +0000278
Douglas Gregorbd945002009-04-13 16:31:14 +0000279/// \brief Add a new line entry that has already been encoded into
280/// the internal representation of the line table.
Douglas Gregor47d9de62012-06-08 16:40:28 +0000281void LineTableInfo::AddEntry(FileID FID,
Douglas Gregorbd945002009-04-13 16:31:14 +0000282 const std::vector<LineEntry> &Entries) {
283 LineEntries[FID] = Entries;
284}
Chris Lattnerac50e342009-02-03 22:13:05 +0000285
Chris Lattner5b9a5042009-01-26 07:57:50 +0000286/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
Mike Stump1eb44332009-09-09 15:08:12 +0000287///
Chris Lattner5f9e2722011-07-23 10:55:15 +0000288unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700289 if (!LineTable)
Chris Lattner5b9a5042009-01-26 07:57:50 +0000290 LineTable = new LineTableInfo();
Jay Foad65aa6882011-06-21 15:13:30 +0000291 return LineTable->getLineTableFilenameID(Name);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000292}
293
294
Chris Lattner4c4ea172009-02-03 21:52:55 +0000295/// AddLineNote - Add a line note to the line table for the FileID and offset
296/// specified by Loc. If FilenameID is -1, it is considered to be
297/// unspecified.
298void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
299 int FilenameID) {
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000300 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000301
Douglas Gregore23ac652011-04-20 00:21:03 +0000302 bool Invalid = false;
303 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
304 if (!Entry.isFile() || Invalid)
305 return;
306
307 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
Chris Lattnerac50e342009-02-03 22:13:05 +0000308
309 // Remember that this file has #line directives now if it doesn't already.
310 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000311
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700312 if (!LineTable)
Chris Lattnerac50e342009-02-03 22:13:05 +0000313 LineTable = new LineTableInfo();
Douglas Gregor47d9de62012-06-08 16:40:28 +0000314 LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID);
Chris Lattner4c4ea172009-02-03 21:52:55 +0000315}
316
Chris Lattner9d79eba2009-02-04 05:21:58 +0000317/// AddLineNote - Add a GNU line marker to the line table.
318void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
319 int FilenameID, bool IsFileEntry,
320 bool IsFileExit, bool IsSystemHeader,
321 bool IsExternCHeader) {
322 // If there is no filename and no flags, this is treated just like a #line,
323 // which does not change the flags of the previous line marker.
324 if (FilenameID == -1) {
325 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
326 "Can't set flags without setting the filename!");
327 return AddLineNote(Loc, LineNo, FilenameID);
328 }
Mike Stump1eb44332009-09-09 15:08:12 +0000329
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000330 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregore23ac652011-04-20 00:21:03 +0000331
332 bool Invalid = false;
333 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
334 if (!Entry.isFile() || Invalid)
335 return;
336
337 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Chris Lattner9d79eba2009-02-04 05:21:58 +0000339 // Remember that this file has #line directives now if it doesn't already.
340 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700342 if (!LineTable)
Chris Lattner9d79eba2009-02-04 05:21:58 +0000343 LineTable = new LineTableInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000344
Chris Lattner9d79eba2009-02-04 05:21:58 +0000345 SrcMgr::CharacteristicKind FileKind;
346 if (IsExternCHeader)
347 FileKind = SrcMgr::C_ExternCSystem;
348 else if (IsSystemHeader)
349 FileKind = SrcMgr::C_System;
350 else
351 FileKind = SrcMgr::C_User;
Mike Stump1eb44332009-09-09 15:08:12 +0000352
Chris Lattner9d79eba2009-02-04 05:21:58 +0000353 unsigned EntryExit = 0;
354 if (IsFileEntry)
355 EntryExit = 1;
356 else if (IsFileExit)
357 EntryExit = 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Douglas Gregor47d9de62012-06-08 16:40:28 +0000359 LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,
Chris Lattner9d79eba2009-02-04 05:21:58 +0000360 EntryExit, FileKind);
361}
362
Douglas Gregorbd945002009-04-13 16:31:14 +0000363LineTableInfo &SourceManager::getLineTable() {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700364 if (!LineTable)
Douglas Gregorbd945002009-04-13 16:31:14 +0000365 LineTable = new LineTableInfo();
366 return *LineTable;
367}
Chris Lattner4c4ea172009-02-03 21:52:55 +0000368
Chris Lattner23b5dc62009-02-04 00:40:31 +0000369//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000370// Private 'Create' methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000371//===----------------------------------------------------------------------===//
Ted Kremenekc16c2082009-01-06 01:55:26 +0000372
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000373SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
374 bool UserFilesAreVolatile)
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +0000375 : Diag(Diag), FileMgr(FileMgr), OverridenFilesKeepOriginalName(true),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000376 UserFilesAreVolatile(UserFilesAreVolatile),
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700377 ExternalSLocEntries(nullptr), LineTable(nullptr), NumLinearScans(0),
378 NumBinaryProbes(0), FakeBufferForRecovery(nullptr),
379 FakeContentCacheForRecovery(nullptr) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000380 clearIDTables();
381 Diag.setSourceManager(this);
382}
383
Chris Lattner5b9a5042009-01-26 07:57:50 +0000384SourceManager::~SourceManager() {
385 delete LineTable;
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000387 // Delete FileEntry objects corresponding to content caches. Since the actual
388 // content cache objects are bump pointer allocated, we just have to run the
389 // dtors, but we call the deallocate method for completeness.
390 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
Argyrios Kyrtzidis99ee0852011-12-15 23:37:55 +0000391 if (MemBufferInfos[i]) {
392 MemBufferInfos[i]->~ContentCache();
393 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
394 }
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000395 }
396 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
397 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
Argyrios Kyrtzidis99ee0852011-12-15 23:37:55 +0000398 if (I->second) {
399 I->second->~ContentCache();
400 ContentCacheAlloc.Deallocate(I->second);
401 }
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000402 }
Douglas Gregore23ac652011-04-20 00:21:03 +0000403
404 delete FakeBufferForRecovery;
Argyrios Kyrtzidisa4c29b62012-02-20 23:58:07 +0000405 delete FakeContentCacheForRecovery;
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +0000406
Stephen Hines651f13c2014-04-23 16:59:28 -0700407 llvm::DeleteContainerSeconds(MacroArgsCacheMap);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000408}
409
410void SourceManager::clearIDTables() {
411 MainFileID = FileID();
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000412 LocalSLocEntryTable.clear();
413 LoadedSLocEntryTable.clear();
414 SLocEntryLoaded.clear();
Chris Lattner5b9a5042009-01-26 07:57:50 +0000415 LastLineNoFileIDQuery = FileID();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700416 LastLineNoContentCache = nullptr;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000417 LastFileIDLookup = FileID();
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Chris Lattner5b9a5042009-01-26 07:57:50 +0000419 if (LineTable)
420 LineTable->clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000421
Chandler Carruth3201f382011-07-26 05:17:23 +0000422 // Use up FileID #0 as an invalid expansion.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000423 NextLocalOffset = 0;
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +0000424 CurrentLoadedOffset = MaxLoadedOffset;
Chandler Carruthbf340e42011-07-26 03:03:05 +0000425 createExpansionLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000426}
427
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000428/// getOrCreateContentCache - Create or return a cached ContentCache for the
429/// specified file.
430const ContentCache *
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000431SourceManager::getOrCreateContentCache(const FileEntry *FileEnt,
432 bool isSystemFile) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000433 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Reid Spencer5f016e22007-07-11 17:01:13 +0000435 // Do we already have information about this file?
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000436 ContentCache *&Entry = FileInfos[FileEnt];
437 if (Entry) return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000438
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700439 // Nope, create a new Cache entry.
440 Entry = ContentCacheAlloc.Allocate<ContentCache>();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000441
Argyrios Kyrtzidisd54dff02012-05-03 21:50:39 +0000442 if (OverriddenFilesInfo) {
443 // If the file contents are overridden with contents from another file,
444 // pass that file to ContentCache.
445 llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
446 overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
447 if (overI == OverriddenFilesInfo->OverriddenFiles.end())
448 new (Entry) ContentCache(FileEnt);
449 else
450 new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
451 : overI->second,
452 overI->second);
453 } else {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000454 new (Entry) ContentCache(FileEnt);
Argyrios Kyrtzidisd54dff02012-05-03 21:50:39 +0000455 }
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000456
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000457 Entry->IsSystemFile = isSystemFile;
458
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000459 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000460}
461
462
Ted Kremenekd1c0eee2007-10-31 17:53:38 +0000463/// createMemBufferContentCache - Create a new ContentCache for the specified
464/// memory buffer. This does no caching.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000465const ContentCache*
466SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700467 // Add a new ContentCache to the MemBufferInfos list and return it.
468 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000469 new (Entry) ContentCache();
470 MemBufferInfos.push_back(Entry);
471 Entry->setBuffer(Buffer);
472 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000473}
474
Argyrios Kyrtzidisa4c29b62012-02-20 23:58:07 +0000475const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
476 bool *Invalid) const {
477 assert(!SLocEntryLoaded[Index]);
478 if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
479 if (Invalid)
480 *Invalid = true;
481 // If the file of the SLocEntry changed we could still have loaded it.
482 if (!SLocEntryLoaded[Index]) {
483 // Try to recover; create a SLocEntry so the rest of clang can handle it.
484 LoadedSLocEntryTable[Index] = SLocEntry::get(0,
485 FileInfo::get(SourceLocation(),
486 getFakeContentCacheForRecovery(),
487 SrcMgr::C_User));
488 }
489 }
490
491 return LoadedSLocEntryTable[Index];
492}
493
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000494std::pair<int, unsigned>
495SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
496 unsigned TotalSize) {
497 assert(ExternalSLocEntries && "Don't have an external sloc source");
498 LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
499 SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
500 CurrentLoadedOffset -= TotalSize;
501 assert(CurrentLoadedOffset >= NextLocalOffset && "Out of source locations");
502 int ID = LoadedSLocEntryTable.size();
503 return std::make_pair(-ID - 1, CurrentLoadedOffset);
Douglas Gregor2bf1eb02009-04-27 21:28:04 +0000504}
505
Douglas Gregore23ac652011-04-20 00:21:03 +0000506/// \brief As part of recovering from missing or changed content, produce a
507/// fake, non-empty buffer.
508const llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const {
509 if (!FakeBufferForRecovery)
510 FakeBufferForRecovery
511 = llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
512
513 return FakeBufferForRecovery;
514}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000515
Argyrios Kyrtzidisa4c29b62012-02-20 23:58:07 +0000516/// \brief As part of recovering from missing or changed content, produce a
517/// fake content cache.
518const SrcMgr::ContentCache *
519SourceManager::getFakeContentCacheForRecovery() const {
520 if (!FakeContentCacheForRecovery) {
521 FakeContentCacheForRecovery = new ContentCache();
522 FakeContentCacheForRecovery->replaceBuffer(getFakeBufferForRecovery(),
523 /*DoNotFree=*/true);
524 }
525 return FakeContentCacheForRecovery;
526}
527
Argyrios Kyrtzidisc50c6ff2013-05-16 21:37:39 +0000528/// \brief Returns the previous in-order FileID or an invalid FileID if there
529/// is no previous one.
530FileID SourceManager::getPreviousFileID(FileID FID) const {
531 if (FID.isInvalid())
532 return FileID();
533
534 int ID = FID.ID;
535 if (ID == -1)
536 return FileID();
537
538 if (ID > 0) {
539 if (ID-1 == 0)
540 return FileID();
541 } else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {
542 return FileID();
543 }
544
545 return FileID::get(ID-1);
546}
547
548/// \brief Returns the next in-order FileID or an invalid FileID if there is
549/// no next one.
550FileID SourceManager::getNextFileID(FileID FID) const {
551 if (FID.isInvalid())
552 return FileID();
553
554 int ID = FID.ID;
555 if (ID > 0) {
556 if (unsigned(ID+1) >= local_sloc_entry_size())
557 return FileID();
558 } else if (ID+1 >= -1) {
559 return FileID();
560 }
561
562 return FileID::get(ID+1);
563}
564
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000565//===----------------------------------------------------------------------===//
Chandler Carruth3201f382011-07-26 05:17:23 +0000566// Methods to create new FileID's and macro expansions.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000567//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000568
Dan Gohman3f86b782010-08-26 21:27:06 +0000569/// createFileID - Create a new FileID for the specified ContentCache and
Ted Kremenek0d892d82007-10-30 22:57:35 +0000570/// include position. This works regardless of whether the ContentCache
571/// corresponds to a file or some other input source.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000572FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000573 SourceLocation IncludePos,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000574 SrcMgr::CharacteristicKind FileCharacter,
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000575 int LoadedID, unsigned LoadedOffset) {
576 if (LoadedID < 0) {
577 assert(LoadedID != -1 && "Loading sentinel FileID");
578 unsigned Index = unsigned(-LoadedID) - 2;
579 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
580 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
581 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset,
582 FileInfo::get(IncludePos, File, FileCharacter));
583 SLocEntryLoaded[Index] = true;
584 return FileID::get(LoadedID);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000585 }
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000586 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset,
587 FileInfo::get(IncludePos, File,
588 FileCharacter)));
Ted Kremenekc16c2082009-01-06 01:55:26 +0000589 unsigned FileSize = File->getSize();
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000590 assert(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
591 NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset &&
592 "Ran out of source locations!");
593 // We do a +1 here because we want a SourceLocation that means "the end of the
594 // file", e.g. for the "no newline at the end of the file" diagnostic.
595 NextLocalOffset += FileSize + 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000596
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000597 // Set LastFileIDLookup to the newly created file. The next getFileID call is
598 // almost guaranteed to be from that file.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000599 FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000600 return LastFileIDLookup = FID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000601}
602
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000603SourceLocation
Chandler Carruthbf340e42011-07-26 03:03:05 +0000604SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc,
605 SourceLocation ExpansionLoc,
606 unsigned TokLength) {
Chandler Carruth78df8362011-07-26 04:41:47 +0000607 ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
608 ExpansionLoc);
609 return createExpansionLocImpl(Info, TokLength);
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000610}
611
612SourceLocation
Chandler Carruthbf340e42011-07-26 03:03:05 +0000613SourceManager::createExpansionLoc(SourceLocation SpellingLoc,
614 SourceLocation ExpansionLocStart,
615 SourceLocation ExpansionLocEnd,
616 unsigned TokLength,
617 int LoadedID,
618 unsigned LoadedOffset) {
Chandler Carruth78df8362011-07-26 04:41:47 +0000619 ExpansionInfo Info = ExpansionInfo::create(SpellingLoc, ExpansionLocStart,
620 ExpansionLocEnd);
621 return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset);
Chandler Carruthbf340e42011-07-26 03:03:05 +0000622}
623
624SourceLocation
Chandler Carruth78df8362011-07-26 04:41:47 +0000625SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
Chandler Carruthbf340e42011-07-26 03:03:05 +0000626 unsigned TokLength,
627 int LoadedID,
628 unsigned LoadedOffset) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000629 if (LoadedID < 0) {
630 assert(LoadedID != -1 && "Loading sentinel FileID");
631 unsigned Index = unsigned(-LoadedID) - 2;
632 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
633 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
Chandler Carruth78df8362011-07-26 04:41:47 +0000634 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000635 SLocEntryLoaded[Index] = true;
636 return SourceLocation::getMacroLoc(LoadedOffset);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000637 }
Chandler Carruth78df8362011-07-26 04:41:47 +0000638 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000639 assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&
640 NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&
641 "Ran out of source locations!");
642 // See createFileID for that +1.
643 NextLocalOffset += TokLength + 1;
644 return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
Reid Spencer5f016e22007-07-11 17:01:13 +0000645}
646
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000647const llvm::MemoryBuffer *
Douglas Gregor50f6af72010-03-16 05:20:39 +0000648SourceManager::getMemoryBufferForFile(const FileEntry *File,
649 bool *Invalid) {
Douglas Gregor29684422009-12-02 06:49:09 +0000650 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregoraea67db2010-03-15 22:54:52 +0000651 assert(IR && "getOrCreateContentCache() cannot return NULL");
Chris Lattnere127a0d2010-04-20 20:35:58 +0000652 return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
Douglas Gregor29684422009-12-02 06:49:09 +0000653}
654
Dan Gohman0d06e992010-10-26 20:47:28 +0000655void SourceManager::overrideFileContents(const FileEntry *SourceFile,
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000656 const llvm::MemoryBuffer *Buffer,
657 bool DoNotFree) {
Douglas Gregor29684422009-12-02 06:49:09 +0000658 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
Dan Gohman0d06e992010-10-26 20:47:28 +0000659 assert(IR && "getOrCreateContentCache() cannot return NULL");
Douglas Gregor29684422009-12-02 06:49:09 +0000660
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000661 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
Douglas Gregora081da52011-11-16 20:05:18 +0000662 const_cast<SrcMgr::ContentCache *>(IR)->BufferOverridden = true;
Argyrios Kyrtzidisd54dff02012-05-03 21:50:39 +0000663
664 getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
Douglas Gregor29684422009-12-02 06:49:09 +0000665}
666
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000667void SourceManager::overrideFileContents(const FileEntry *SourceFile,
668 const FileEntry *NewFile) {
669 assert(SourceFile->getSize() == NewFile->getSize() &&
670 "Different sizes, use the FileManager to create a virtual file with "
671 "the correct size");
672 assert(FileInfos.count(SourceFile) == 0 &&
673 "This function should be called at the initialization stage, before "
674 "any parsing occurs.");
Argyrios Kyrtzidisd54dff02012-05-03 21:50:39 +0000675 getOverriddenFilesInfo().OverriddenFiles[SourceFile] = NewFile;
676}
677
678void SourceManager::disableFileContentsOverride(const FileEntry *File) {
679 if (!isFileOverridden(File))
680 return;
681
682 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700683 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(nullptr);
Argyrios Kyrtzidisd54dff02012-05-03 21:50:39 +0000684 const_cast<SrcMgr::ContentCache *>(IR)->ContentsEntry = IR->OrigEntry;
685
686 assert(OverriddenFilesInfo);
687 OverriddenFilesInfo->OverriddenFiles.erase(File);
688 OverriddenFilesInfo->OverriddenFilesWithBuffer.erase(File);
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000689}
690
Chris Lattner5f9e2722011-07-23 10:55:15 +0000691StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
Douglas Gregoraae58b02010-03-16 20:01:30 +0000692 bool MyInvalid = false;
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000693 const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid);
Douglas Gregore23ac652011-04-20 00:21:03 +0000694 if (!SLoc.isFile() || MyInvalid) {
Douglas Gregor3de84242011-01-31 22:42:36 +0000695 if (Invalid)
696 *Invalid = true;
697 return "<<<<<INVALID SOURCE LOCATION>>>>>";
698 }
699
700 const llvm::MemoryBuffer *Buf
701 = SLoc.getFile().getContentCache()->getBuffer(Diag, *this, SourceLocation(),
702 &MyInvalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000703 if (Invalid)
Douglas Gregoraae58b02010-03-16 20:01:30 +0000704 *Invalid = MyInvalid;
705
706 if (MyInvalid)
Douglas Gregor3de84242011-01-31 22:42:36 +0000707 return "<<<<<INVALID SOURCE LOCATION>>>>>";
Douglas Gregoraae58b02010-03-16 20:01:30 +0000708
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000709 return Buf->getBuffer();
Douglas Gregoraea67db2010-03-15 22:54:52 +0000710}
Chris Lattner2b2453a2009-01-17 06:22:33 +0000711
Chris Lattner23b5dc62009-02-04 00:40:31 +0000712//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000713// SourceLocation manipulation methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000714//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000715
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000716/// \brief Return the FileID for a SourceLocation.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000717///
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000718/// This is the cache-miss path of getFileID. Not as hot as that function, but
719/// still very important. It is responsible for finding the entry in the
720/// SLocEntry tables that contains the specified location.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000721FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
Douglas Gregore23ac652011-04-20 00:21:03 +0000722 if (!SLocOffset)
723 return FileID::get(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000724
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000725 // Now it is time to search for the correct file. See where the SLocOffset
726 // sits in the global view and consult local or loaded buffers for it.
727 if (SLocOffset < NextLocalOffset)
728 return getFileIDLocal(SLocOffset);
729 return getFileIDLoaded(SLocOffset);
730}
731
732/// \brief Return the FileID for a SourceLocation with a low offset.
733///
734/// This function knows that the SourceLocation is in a local buffer, not a
735/// loaded one.
736FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const {
737 assert(SLocOffset < NextLocalOffset && "Bad function choice");
738
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000739 // After the first and second level caches, I see two common sorts of
Chandler Carruth3201f382011-07-26 05:17:23 +0000740 // behavior: 1) a lot of searched FileID's are "near" the cached file
741 // location or are "near" the cached expansion location. 2) others are just
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000742 // completely random and may be a very long way away.
743 //
744 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
745 // then we fall back to a less cache efficient, but more scalable, binary
746 // search to find the location.
Mike Stump1eb44332009-09-09 15:08:12 +0000747
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000748 // See if this is near the file point - worst case we start scanning from the
749 // most newly created FileID.
Benjamin Kramerf512ace2013-02-22 18:29:39 +0000750 const SrcMgr::SLocEntry *I;
Mike Stump1eb44332009-09-09 15:08:12 +0000751
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000752 if (LastFileIDLookup.ID < 0 ||
753 LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000754 // Neither loc prunes our search.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000755 I = LocalSLocEntryTable.end();
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000756 } else {
757 // Perhaps it is near the file point.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000758 I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000759 }
760
761 // Find the FileID that contains this. "I" is an iterator that points to a
762 // FileID whose offset is known to be larger than SLocOffset.
763 unsigned NumProbes = 0;
764 while (1) {
765 --I;
766 if (I->getOffset() <= SLocOffset) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000767 FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000768
Chandler Carruth3201f382011-07-26 05:17:23 +0000769 // If this isn't an expansion, remember it. We have good locality across
770 // FileID lookups.
Chandler Carruth17287622011-07-26 04:56:51 +0000771 if (!I->isExpansion())
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000772 LastFileIDLookup = Res;
773 NumLinearScans += NumProbes+1;
774 return Res;
775 }
776 if (++NumProbes == 8)
777 break;
778 }
Mike Stump1eb44332009-09-09 15:08:12 +0000779
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000780 // Convert "I" back into an index. We know that it is an entry whose index is
781 // larger than the offset we are looking for.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000782 unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000783 // LessIndex - This is the lower bound of the range that we're searching.
784 // We know that the offset corresponding to the FileID is is less than
785 // SLocOffset.
786 unsigned LessIndex = 0;
787 NumProbes = 0;
788 while (1) {
Douglas Gregore23ac652011-04-20 00:21:03 +0000789 bool Invalid = false;
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000790 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000791 unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
Douglas Gregore23ac652011-04-20 00:21:03 +0000792 if (Invalid)
793 return FileID::get(0);
794
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000795 ++NumProbes;
Mike Stump1eb44332009-09-09 15:08:12 +0000796
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000797 // If the offset of the midpoint is too large, chop the high side of the
798 // range to the midpoint.
799 if (MidOffset > SLocOffset) {
800 GreaterIndex = MiddleIndex;
801 continue;
802 }
Mike Stump1eb44332009-09-09 15:08:12 +0000803
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000804 // If the middle index contains the value, succeed and return.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000805 // FIXME: This could be made faster by using a function that's aware of
806 // being in the local area.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000807 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000808 FileID Res = FileID::get(MiddleIndex);
809
Chandler Carruth17287622011-07-26 04:56:51 +0000810 // If this isn't a macro expansion, remember it. We have good locality
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000811 // across FileID lookups.
Chandler Carruth17287622011-07-26 04:56:51 +0000812 if (!LocalSLocEntryTable[MiddleIndex].isExpansion())
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000813 LastFileIDLookup = Res;
814 NumBinaryProbes += NumProbes;
815 return Res;
816 }
Mike Stump1eb44332009-09-09 15:08:12 +0000817
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000818 // Otherwise, move the low-side up to the middle index.
819 LessIndex = MiddleIndex;
820 }
821}
822
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000823/// \brief Return the FileID for a SourceLocation with a high offset.
824///
825/// This function knows that the SourceLocation is in a loaded buffer, not a
826/// local one.
827FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
Argyrios Kyrtzidisc3b45752011-10-03 23:43:01 +0000828 // Sanity checking, otherwise a bug may lead to hanging in release build.
Argyrios Kyrtzidis82ccbe72011-10-25 00:29:44 +0000829 if (SLocOffset < CurrentLoadedOffset) {
830 assert(0 && "Invalid SLocOffset or bad function choice");
Argyrios Kyrtzidisc3b45752011-10-03 23:43:01 +0000831 return FileID();
Argyrios Kyrtzidis82ccbe72011-10-25 00:29:44 +0000832 }
Argyrios Kyrtzidisc3b45752011-10-03 23:43:01 +0000833
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000834 // Essentially the same as the local case, but the loaded array is sorted
835 // in the other direction.
836
837 // First do a linear scan from the last lookup position, if possible.
838 unsigned I;
839 int LastID = LastFileIDLookup.ID;
840 if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
841 I = 0;
842 else
843 I = (-LastID - 2) + 1;
844
845 unsigned NumProbes;
846 for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
847 // Make sure the entry is loaded!
848 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
849 if (E.getOffset() <= SLocOffset) {
850 FileID Res = FileID::get(-int(I) - 2);
851
Chandler Carruth17287622011-07-26 04:56:51 +0000852 if (!E.isExpansion())
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000853 LastFileIDLookup = Res;
854 NumLinearScans += NumProbes + 1;
855 return Res;
856 }
857 }
858
859 // Linear scan failed. Do the binary search. Note the reverse sorting of the
860 // table: GreaterIndex is the one where the offset is greater, which is
861 // actually a lower index!
862 unsigned GreaterIndex = I;
863 unsigned LessIndex = LoadedSLocEntryTable.size();
864 NumProbes = 0;
865 while (1) {
866 ++NumProbes;
867 unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
868 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
Argyrios Kyrtzidis7db4bb92013-03-01 03:26:00 +0000869 if (E.getOffset() == 0)
870 return FileID(); // invalid entry.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000871
872 ++NumProbes;
873
874 if (E.getOffset() > SLocOffset) {
Argyrios Kyrtzidis7db4bb92013-03-01 03:26:00 +0000875 // Sanity checking, otherwise a bug may lead to hanging in release build.
876 if (GreaterIndex == MiddleIndex) {
877 assert(0 && "binary search missed the entry");
878 return FileID();
879 }
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000880 GreaterIndex = MiddleIndex;
881 continue;
882 }
883
884 if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
885 FileID Res = FileID::get(-int(MiddleIndex) - 2);
Chandler Carruth17287622011-07-26 04:56:51 +0000886 if (!E.isExpansion())
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000887 LastFileIDLookup = Res;
888 NumBinaryProbes += NumProbes;
889 return Res;
890 }
891
Argyrios Kyrtzidis838a9202013-03-01 03:43:33 +0000892 // Sanity checking, otherwise a bug may lead to hanging in release build.
893 if (LessIndex == MiddleIndex) {
894 assert(0 && "binary search missed the entry");
895 return FileID();
896 }
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000897 LessIndex = MiddleIndex;
898 }
899}
900
Chris Lattneraddb7972009-01-26 20:04:19 +0000901SourceLocation SourceManager::
Chandler Carruthf84ef952011-07-25 20:52:26 +0000902getExpansionLocSlowCase(SourceLocation Loc) const {
Chris Lattneraddb7972009-01-26 20:04:19 +0000903 do {
Chris Lattnera5c6c582010-02-12 19:31:35 +0000904 // Note: If Loc indicates an offset into a token that came from a macro
905 // expansion (e.g. the 5th character of the token) we do not want to add
Chandler Carruth17287622011-07-26 04:56:51 +0000906 // this offset when going to the expansion location. The expansion
Chris Lattnera5c6c582010-02-12 19:31:35 +0000907 // location is the macro invocation, which the offset has nothing to do
908 // with. This is unlike when we get the spelling loc, because the offset
909 // directly correspond to the token whose spelling we're inspecting.
Chandler Carruth17287622011-07-26 04:56:51 +0000910 Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
Chris Lattneraddb7972009-01-26 20:04:19 +0000911 } while (!Loc.isFileID());
912
913 return Loc;
914}
915
916SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
917 do {
918 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
Chandler Carruth17287622011-07-26 04:56:51 +0000919 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000920 Loc = Loc.getLocWithOffset(LocInfo.second);
Chris Lattneraddb7972009-01-26 20:04:19 +0000921 } while (!Loc.isFileID());
922 return Loc;
923}
924
Argyrios Kyrtzidis796dbfb2011-10-12 07:07:40 +0000925SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
926 do {
927 if (isMacroArgExpansion(Loc))
928 Loc = getImmediateSpellingLoc(Loc);
929 else
930 Loc = getImmediateExpansionRange(Loc).first;
931 } while (!Loc.isFileID());
932 return Loc;
933}
934
Chris Lattneraddb7972009-01-26 20:04:19 +0000935
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000936std::pair<FileID, unsigned>
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000937SourceManager::getDecomposedExpansionLocSlowCase(
Argyrios Kyrtzidis8b86ef02011-07-07 03:40:27 +0000938 const SrcMgr::SLocEntry *E) const {
Chandler Carruth3201f382011-07-26 05:17:23 +0000939 // If this is an expansion record, walk through all the expansion points.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000940 FileID FID;
941 SourceLocation Loc;
Argyrios Kyrtzidis8b86ef02011-07-07 03:40:27 +0000942 unsigned Offset;
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000943 do {
Chandler Carruth17287622011-07-26 04:56:51 +0000944 Loc = E->getExpansion().getExpansionLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000945
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000946 FID = getFileID(Loc);
947 E = &getSLocEntry(FID);
Argyrios Kyrtzidis8b86ef02011-07-07 03:40:27 +0000948 Offset = Loc.getOffset()-E->getOffset();
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000949 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000950
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000951 return std::make_pair(FID, Offset);
952}
953
954std::pair<FileID, unsigned>
955SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
956 unsigned Offset) const {
Chandler Carruth3201f382011-07-26 05:17:23 +0000957 // If this is an expansion record, walk through all the expansion points.
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000958 FileID FID;
959 SourceLocation Loc;
960 do {
Chandler Carruth17287622011-07-26 04:56:51 +0000961 Loc = E->getExpansion().getSpellingLoc();
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000962 Loc = Loc.getLocWithOffset(Offset);
Mike Stump1eb44332009-09-09 15:08:12 +0000963
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000964 FID = getFileID(Loc);
965 E = &getSLocEntry(FID);
Argyrios Kyrtzidisb6c465e2011-08-23 21:02:41 +0000966 Offset = Loc.getOffset()-E->getOffset();
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000967 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000968
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000969 return std::make_pair(FID, Offset);
970}
971
Chris Lattner387616e2009-02-17 08:04:48 +0000972/// getImmediateSpellingLoc - Given a SourceLocation object, return the
973/// spelling location referenced by the ID. This is the first level down
974/// towards the place where the characters that make up the lexed token can be
975/// found. This should not generally be used by clients.
976SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
977 if (Loc.isFileID()) return Loc;
978 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
Chandler Carruth17287622011-07-26 04:56:51 +0000979 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000980 return Loc.getLocWithOffset(LocInfo.second);
Chris Lattner387616e2009-02-17 08:04:48 +0000981}
982
983
Chandler Carruth3201f382011-07-26 05:17:23 +0000984/// getImmediateExpansionRange - Loc is required to be an expansion location.
985/// Return the start/end of the expansion information.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000986std::pair<SourceLocation,SourceLocation>
Chandler Carruth999f7392011-07-25 20:52:21 +0000987SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
Chandler Carruth3201f382011-07-26 05:17:23 +0000988 assert(Loc.isMacroID() && "Not a macro expansion loc!");
Chandler Carruth17287622011-07-26 04:56:51 +0000989 const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
Chandler Carruth78df8362011-07-26 04:41:47 +0000990 return Expansion.getExpansionLocRange();
Chris Lattnere7fb4842009-02-15 20:52:18 +0000991}
992
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000993/// getExpansionRange - Given a SourceLocation object, return the range of
994/// tokens covered by the expansion in the ultimate file.
Chris Lattner66781332009-02-15 21:26:50 +0000995std::pair<SourceLocation,SourceLocation>
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000996SourceManager::getExpansionRange(SourceLocation Loc) const {
Chris Lattner66781332009-02-15 21:26:50 +0000997 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000998
Chris Lattner66781332009-02-15 21:26:50 +0000999 std::pair<SourceLocation,SourceLocation> Res =
Chandler Carruth999f7392011-07-25 20:52:21 +00001000 getImmediateExpansionRange(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +00001001
Chandler Carruth3201f382011-07-26 05:17:23 +00001002 // Fully resolve the start and end locations to their ultimate expansion
Chris Lattner66781332009-02-15 21:26:50 +00001003 // points.
1004 while (!Res.first.isFileID())
Chandler Carruth999f7392011-07-25 20:52:21 +00001005 Res.first = getImmediateExpansionRange(Res.first).first;
Chris Lattner66781332009-02-15 21:26:50 +00001006 while (!Res.second.isFileID())
Chandler Carruth999f7392011-07-25 20:52:21 +00001007 Res.second = getImmediateExpansionRange(Res.second).second;
Chris Lattner66781332009-02-15 21:26:50 +00001008 return Res;
1009}
1010
Chandler Carruth96d35892011-07-26 03:03:00 +00001011bool SourceManager::isMacroArgExpansion(SourceLocation Loc) const {
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +00001012 if (!Loc.isMacroID()) return false;
1013
1014 FileID FID = getFileID(Loc);
Matt Beaumont-Gayc3cd6f72013-01-12 00:54:16 +00001015 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
Chandler Carruth78df8362011-07-26 04:41:47 +00001016 return Expansion.isMacroArgExpansion();
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +00001017}
Chris Lattnere7fb4842009-02-15 20:52:18 +00001018
Matt Beaumont-Gayc3cd6f72013-01-12 00:54:16 +00001019bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const {
1020 if (!Loc.isMacroID()) return false;
1021
1022 FileID FID = getFileID(Loc);
1023 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1024 return Expansion.isMacroBodyExpansion();
1025}
1026
Argyrios Kyrtzidisc50c6ff2013-05-16 21:37:39 +00001027bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
1028 SourceLocation *MacroBegin) const {
1029 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1030
1031 std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);
1032 if (DecompLoc.second > 0)
1033 return false; // Does not point at the start of expansion range.
1034
1035 bool Invalid = false;
1036 const SrcMgr::ExpansionInfo &ExpInfo =
1037 getSLocEntry(DecompLoc.first, &Invalid).getExpansion();
1038 if (Invalid)
1039 return false;
1040 SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();
1041
1042 if (ExpInfo.isMacroArgExpansion()) {
1043 // For macro argument expansions, check if the previous FileID is part of
1044 // the same argument expansion, in which case this Loc is not at the
1045 // beginning of the expansion.
1046 FileID PrevFID = getPreviousFileID(DecompLoc.first);
1047 if (!PrevFID.isInvalid()) {
1048 const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);
1049 if (Invalid)
1050 return false;
1051 if (PrevEntry.isExpansion() &&
1052 PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)
1053 return false;
1054 }
1055 }
1056
1057 if (MacroBegin)
1058 *MacroBegin = ExpLoc;
1059 return true;
1060}
1061
1062bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
1063 SourceLocation *MacroEnd) const {
1064 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1065
1066 FileID FID = getFileID(Loc);
1067 SourceLocation NextLoc = Loc.getLocWithOffset(1);
1068 if (isInFileID(NextLoc, FID))
1069 return false; // Does not point at the end of expansion range.
1070
1071 bool Invalid = false;
1072 const SrcMgr::ExpansionInfo &ExpInfo =
1073 getSLocEntry(FID, &Invalid).getExpansion();
1074 if (Invalid)
1075 return false;
1076
1077 if (ExpInfo.isMacroArgExpansion()) {
1078 // For macro argument expansions, check if the next FileID is part of the
1079 // same argument expansion, in which case this Loc is not at the end of the
1080 // expansion.
1081 FileID NextFID = getNextFileID(FID);
1082 if (!NextFID.isInvalid()) {
1083 const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);
1084 if (Invalid)
1085 return false;
1086 if (NextEntry.isExpansion() &&
1087 NextEntry.getExpansion().getExpansionLocStart() ==
1088 ExpInfo.getExpansionLocStart())
1089 return false;
1090 }
1091 }
1092
1093 if (MacroEnd)
1094 *MacroEnd = ExpInfo.getExpansionLocEnd();
1095 return true;
1096}
1097
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001098
1099//===----------------------------------------------------------------------===//
1100// Queries about the code at a SourceLocation.
1101//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001102
1103/// getCharacterData - Return a pointer to the start of the specified location
1104/// in the appropriate MemoryBuffer.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001105const char *SourceManager::getCharacterData(SourceLocation SL,
1106 bool *Invalid) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001107 // Note that this is a hot function in the getSpelling() path, which is
1108 // heavily used by -E mode.
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001109 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump1eb44332009-09-09 15:08:12 +00001110
Ted Kremenekc16c2082009-01-06 01:55:26 +00001111 // Note that calling 'getBuffer()' may lazily page in a source file.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001112 bool CharDataInvalid = false;
Douglas Gregore23ac652011-04-20 00:21:03 +00001113 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
1114 if (CharDataInvalid || !Entry.isFile()) {
1115 if (Invalid)
1116 *Invalid = true;
1117
1118 return "<<<<INVALID BUFFER>>>>";
1119 }
Douglas Gregor50f6af72010-03-16 05:20:39 +00001120 const llvm::MemoryBuffer *Buffer
Douglas Gregore23ac652011-04-20 00:21:03 +00001121 = Entry.getFile().getContentCache()
1122 ->getBuffer(Diag, *this, SourceLocation(), &CharDataInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001123 if (Invalid)
1124 *Invalid = CharDataInvalid;
1125 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
Reid Spencer5f016e22007-07-11 17:01:13 +00001126}
1127
Reid Spencer5f016e22007-07-11 17:01:13 +00001128
Chris Lattner9dc1f532007-07-20 16:37:10 +00001129/// getColumnNumber - Return the column # for the specified file position.
Chris Lattner7da5aea2009-02-04 00:55:58 +00001130/// this is significantly cheaper to compute than the line number.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001131unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
1132 bool *Invalid) const {
1133 bool MyInvalid = false;
Argyrios Kyrtzidisd5752542011-12-10 00:30:38 +00001134 const llvm::MemoryBuffer *MemBuf = getBuffer(FID, &MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001135 if (Invalid)
1136 *Invalid = MyInvalid;
1137
1138 if (MyInvalid)
1139 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00001140
Jordan Rose2e413f92012-06-19 03:09:38 +00001141 // It is okay to request a position just past the end of the buffer.
1142 if (FilePos > MemBuf->getBufferSize()) {
Argyrios Kyrtzidisd5752542011-12-10 00:30:38 +00001143 if (Invalid)
Jordan Rose2e413f92012-06-19 03:09:38 +00001144 *Invalid = true;
Argyrios Kyrtzidisd5752542011-12-10 00:30:38 +00001145 return 1;
1146 }
1147
Craig Topperd9cad402012-10-19 04:40:38 +00001148 // See if we just calculated the line number for this FilePos and can use
1149 // that to lookup the start of the line instead of searching for it.
1150 if (LastLineNoFileIDQuery == FID &&
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001151 LastLineNoContentCache->SourceLineCache != nullptr &&
Craig Topperd53c2d32012-12-16 05:58:32 +00001152 LastLineNoResult < LastLineNoContentCache->NumLines) {
Craig Topperd9cad402012-10-19 04:40:38 +00001153 unsigned *SourceLineCache = LastLineNoContentCache->SourceLineCache;
1154 unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
1155 unsigned LineEnd = SourceLineCache[LastLineNoResult];
1156 if (FilePos >= LineStart && FilePos < LineEnd)
1157 return FilePos - LineStart + 1;
1158 }
1159
Dylan Noblesmith098eaff2011-12-19 08:51:05 +00001160 const char *Buf = MemBuf->getBufferStart();
Reid Spencer5f016e22007-07-11 17:01:13 +00001161 unsigned LineStart = FilePos;
1162 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
1163 --LineStart;
1164 return FilePos-LineStart+1;
1165}
1166
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001167// isInvalid - Return the result of calling loc.isInvalid(), and
1168// if Invalid is not null, set its value to same.
1169static bool isInvalid(SourceLocation Loc, bool *Invalid) {
1170 bool MyInvalid = Loc.isInvalid();
1171 if (Invalid)
1172 *Invalid = MyInvalid;
1173 return MyInvalid;
1174}
1175
Douglas Gregor50f6af72010-03-16 05:20:39 +00001176unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
1177 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001178 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +00001179 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001180 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +00001181}
1182
Chandler Carrutha77c0312011-07-25 20:57:57 +00001183unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
1184 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001185 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +00001186 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001187 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +00001188}
1189
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001190unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
1191 bool *Invalid) const {
1192 if (isInvalid(Loc, Invalid)) return 0;
1193 return getPresumedLoc(Loc).getColumn();
1194}
1195
Benjamin Kramerd2953ce2012-04-06 20:49:55 +00001196#ifdef __SSE2__
1197#include <emmintrin.h>
1198#endif
1199
Chandler Carruth14bd9652010-10-23 08:44:57 +00001200static LLVM_ATTRIBUTE_NOINLINE void
David Blaikied6471f72011-09-25 23:23:43 +00001201ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
Chris Lattnere127a0d2010-04-20 20:35:58 +00001202 llvm::BumpPtrAllocator &Alloc,
1203 const SourceManager &SM, bool &Invalid);
David Blaikied6471f72011-09-25 23:23:43 +00001204static void ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
Chris Lattnere127a0d2010-04-20 20:35:58 +00001205 llvm::BumpPtrAllocator &Alloc,
1206 const SourceManager &SM, bool &Invalid) {
Ted Kremenekc16c2082009-01-06 01:55:26 +00001207 // Note that calling 'getBuffer()' may lazily page in the file.
Chris Lattnere127a0d2010-04-20 20:35:58 +00001208 const MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(),
1209 &Invalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001210 if (Invalid)
1211 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001212
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001213 // Find the file offsets of all of the *physical* source lines. This does
1214 // not look at trigraphs, escaped newlines, or anything else tricky.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001215 SmallVector<unsigned, 256> LineOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +00001216
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001217 // Line #1 starts at char 0.
1218 LineOffsets.push_back(0);
Mike Stump1eb44332009-09-09 15:08:12 +00001219
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001220 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
1221 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
1222 unsigned Offs = 0;
1223 while (1) {
1224 // Skip over the contents of the line.
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001225 const unsigned char *NextBuf = (const unsigned char *)Buf;
Benjamin Kramerd2953ce2012-04-06 20:49:55 +00001226
1227#ifdef __SSE2__
1228 // Try to skip to the next newline using SSE instructions. This is very
1229 // performance sensitive for programs with lots of diagnostics and in -E
1230 // mode.
1231 __m128i CRs = _mm_set1_epi8('\r');
1232 __m128i LFs = _mm_set1_epi8('\n');
1233
1234 // First fix up the alignment to 16 bytes.
1235 while (((uintptr_t)NextBuf & 0xF) != 0) {
1236 if (*NextBuf == '\n' || *NextBuf == '\r' || *NextBuf == '\0')
1237 goto FoundSpecialChar;
1238 ++NextBuf;
1239 }
1240
1241 // Scan 16 byte chunks for '\r' and '\n'. Ignore '\0'.
1242 while (NextBuf+16 <= End) {
Roman Divacky31ba6132012-09-06 15:59:27 +00001243 const __m128i Chunk = *(const __m128i*)NextBuf;
Benjamin Kramerd2953ce2012-04-06 20:49:55 +00001244 __m128i Cmp = _mm_or_si128(_mm_cmpeq_epi8(Chunk, CRs),
1245 _mm_cmpeq_epi8(Chunk, LFs));
1246 unsigned Mask = _mm_movemask_epi8(Cmp);
1247
1248 // If we found a newline, adjust the pointer and jump to the handling code.
1249 if (Mask != 0) {
Michael J. Spencer9779fdd2013-05-24 21:42:04 +00001250 NextBuf += llvm::countTrailingZeros(Mask);
Benjamin Kramerd2953ce2012-04-06 20:49:55 +00001251 goto FoundSpecialChar;
1252 }
1253 NextBuf += 16;
1254 }
1255#endif
1256
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001257 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
1258 ++NextBuf;
Benjamin Kramerd2953ce2012-04-06 20:49:55 +00001259
1260#ifdef __SSE2__
1261FoundSpecialChar:
1262#endif
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001263 Offs += NextBuf-Buf;
1264 Buf = NextBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00001265
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001266 if (Buf[0] == '\n' || Buf[0] == '\r') {
1267 // If this is \n\r or \r\n, skip both characters.
1268 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
1269 ++Offs, ++Buf;
1270 ++Offs, ++Buf;
1271 LineOffsets.push_back(Offs);
1272 } else {
1273 // Otherwise, this is a null. If end of file, exit.
1274 if (Buf == End) break;
1275 // Otherwise, skip the null.
1276 ++Offs, ++Buf;
1277 }
1278 }
Mike Stump1eb44332009-09-09 15:08:12 +00001279
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001280 // Copy the offsets into the FileInfo structure.
1281 FI->NumLines = LineOffsets.size();
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00001282 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001283 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
1284}
Reid Spencer5f016e22007-07-11 17:01:13 +00001285
Chris Lattnerdf7c17a2009-01-16 07:00:02 +00001286/// getLineNumber - Given a SourceLocation, return the spelling line number
Reid Spencer5f016e22007-07-11 17:01:13 +00001287/// for the position indicated. This requires building and caching a table of
1288/// line offsets for the MemoryBuffer, so this is not cheap: use only when
1289/// about to emit a diagnostic.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001290unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1291 bool *Invalid) const {
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00001292 if (FID.isInvalid()) {
1293 if (Invalid)
1294 *Invalid = true;
1295 return 1;
1296 }
1297
Chris Lattner2b2453a2009-01-17 06:22:33 +00001298 ContentCache *Content;
Chris Lattner30fc9332009-02-04 01:06:56 +00001299 if (LastLineNoFileIDQuery == FID)
Ted Kremenek78d85f52007-10-30 21:08:08 +00001300 Content = LastLineNoContentCache;
Douglas Gregore23ac652011-04-20 00:21:03 +00001301 else {
1302 bool MyInvalid = false;
1303 const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1304 if (MyInvalid || !Entry.isFile()) {
1305 if (Invalid)
1306 *Invalid = true;
1307 return 1;
1308 }
1309
1310 Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
1311 }
1312
Reid Spencer5f016e22007-07-11 17:01:13 +00001313 // If this is the first use of line information for this buffer, compute the
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001314 /// SourceLineCache for it on demand.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001315 if (!Content->SourceLineCache) {
Douglas Gregor50f6af72010-03-16 05:20:39 +00001316 bool MyInvalid = false;
Chris Lattnere127a0d2010-04-20 20:35:58 +00001317 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001318 if (Invalid)
1319 *Invalid = MyInvalid;
1320 if (MyInvalid)
1321 return 1;
1322 } else if (Invalid)
1323 *Invalid = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001324
1325 // Okay, we know we have a line number table. Do a binary search to find the
1326 // line number that this character position lands on.
Ted Kremenek78d85f52007-10-30 21:08:08 +00001327 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001328 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenek78d85f52007-10-30 21:08:08 +00001329 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump1eb44332009-09-09 15:08:12 +00001330
Chris Lattner30fc9332009-02-04 01:06:56 +00001331 unsigned QueriedFilePos = FilePos+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001332
Daniel Dunbar4106d692009-05-18 17:30:52 +00001333 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump1eb44332009-09-09 15:08:12 +00001334 // complicated as it is, binary search isn't that slow.
Daniel Dunbar4106d692009-05-18 17:30:52 +00001335 //
1336 // If it is worth being optimized, then in my opinion it could be more
1337 // performant, simpler, and more obviously correct by just "galloping" outward
1338 // from the queried file position. In fact, this could be incorporated into a
1339 // generic algorithm such as lower_bound_with_hint.
1340 //
1341 // If someone gives me a test case where this matters, and I will do it! - DWD
1342
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001343 // If the previous query was to the same file, we know both the file pos from
1344 // that query and the line number returned. This allows us to narrow the
1345 // search space from the entire file to something near the match.
Chris Lattner30fc9332009-02-04 01:06:56 +00001346 if (LastLineNoFileIDQuery == FID) {
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001347 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar4106d692009-05-18 17:30:52 +00001348 // FIXME: Potential overflow?
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001349 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump1eb44332009-09-09 15:08:12 +00001350
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001351 // The query is likely to be nearby the previous one. Here we check to
1352 // see if it is within 5, 10 or 20 lines. It can be far away in cases
1353 // where big comment blocks and vertical whitespace eat up lines but
1354 // contribute no tokens.
1355 if (SourceLineCache+5 < SourceLineCacheEnd) {
1356 if (SourceLineCache[5] > QueriedFilePos)
1357 SourceLineCacheEnd = SourceLineCache+5;
1358 else if (SourceLineCache+10 < SourceLineCacheEnd) {
1359 if (SourceLineCache[10] > QueriedFilePos)
1360 SourceLineCacheEnd = SourceLineCache+10;
1361 else if (SourceLineCache+20 < SourceLineCacheEnd) {
1362 if (SourceLineCache[20] > QueriedFilePos)
1363 SourceLineCacheEnd = SourceLineCache+20;
1364 }
1365 }
1366 }
1367 } else {
Daniel Dunbar4106d692009-05-18 17:30:52 +00001368 if (LastLineNoResult < Content->NumLines)
1369 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001370 }
1371 }
Mike Stump1eb44332009-09-09 15:08:12 +00001372
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001373 unsigned *Pos
1374 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001375 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump1eb44332009-09-09 15:08:12 +00001376
Chris Lattner30fc9332009-02-04 01:06:56 +00001377 LastLineNoFileIDQuery = FID;
Ted Kremenek78d85f52007-10-30 21:08:08 +00001378 LastLineNoContentCache = Content;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001379 LastLineNoFilePos = QueriedFilePos;
1380 LastLineNoResult = LineNo;
1381 return LineNo;
Reid Spencer5f016e22007-07-11 17:01:13 +00001382}
1383
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001384unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1385 bool *Invalid) const {
1386 if (isInvalid(Loc, Invalid)) return 0;
1387 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1388 return getLineNumber(LocInfo.first, LocInfo.second);
1389}
Chandler Carruth64211622011-07-25 21:09:52 +00001390unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
1391 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001392 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +00001393 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Chris Lattner30fc9332009-02-04 01:06:56 +00001394 return getLineNumber(LocInfo.first, LocInfo.second);
1395}
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001396unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
Douglas Gregor50f6af72010-03-16 05:20:39 +00001397 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001398 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001399 return getPresumedLoc(Loc).getLine();
Chris Lattner30fc9332009-02-04 01:06:56 +00001400}
1401
Chris Lattner6b306672009-02-04 05:33:01 +00001402/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump1eb44332009-09-09 15:08:12 +00001403/// source location, indicating whether this is a normal file, a system
Chris Lattner6b306672009-02-04 05:33:01 +00001404/// header, or an "implicit extern C" system header.
1405///
1406/// This state can be modified with flags on GNU linemarker directives like:
1407/// # 4 "foo.h" 3
1408/// which changes all source locations in the current file after that to be
1409/// considered to be from a system header.
Mike Stump1eb44332009-09-09 15:08:12 +00001410SrcMgr::CharacteristicKind
Chris Lattner6b306672009-02-04 05:33:01 +00001411SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1412 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +00001413 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregore23ac652011-04-20 00:21:03 +00001414 bool Invalid = false;
1415 const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
1416 if (Invalid || !SEntry.isFile())
1417 return C_User;
1418
1419 const SrcMgr::FileInfo &FI = SEntry.getFile();
Chris Lattner6b306672009-02-04 05:33:01 +00001420
1421 // If there are no #line directives in this file, just return the whole-file
1422 // state.
1423 if (!FI.hasLineDirectives())
1424 return FI.getFileCharacteristic();
Mike Stump1eb44332009-09-09 15:08:12 +00001425
Chris Lattner6b306672009-02-04 05:33:01 +00001426 assert(LineTable && "Can't have linetable entries without a LineTable!");
1427 // See if there is a #line directive before the location.
1428 const LineEntry *Entry =
Douglas Gregor47d9de62012-06-08 16:40:28 +00001429 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001430
Chris Lattner6b306672009-02-04 05:33:01 +00001431 // If this is before the first line marker, use the file characteristic.
1432 if (!Entry)
1433 return FI.getFileCharacteristic();
1434
1435 return Entry->FileKind;
1436}
1437
Chris Lattnerbff5c512009-02-17 08:39:06 +00001438/// Return the filename or buffer identifier of the buffer the location is in.
James Dennettb8950b82012-06-17 03:22:59 +00001439/// Note that this name does not respect \#line directives. Use getPresumedLoc
Chris Lattnerbff5c512009-02-17 08:39:06 +00001440/// for normal clients.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001441const char *SourceManager::getBufferName(SourceLocation Loc,
1442 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001443 if (isInvalid(Loc, Invalid)) return "<invalid loc>";
Mike Stump1eb44332009-09-09 15:08:12 +00001444
Douglas Gregor50f6af72010-03-16 05:20:39 +00001445 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
Chris Lattnerbff5c512009-02-17 08:39:06 +00001446}
1447
Chris Lattner30fc9332009-02-04 01:06:56 +00001448
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001449/// getPresumedLoc - This method returns the "presumed" location of a
James Dennettb8950b82012-06-17 03:22:59 +00001450/// SourceLocation specifies. A "presumed location" can be modified by \#line
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001451/// or GNU line marker directives. This provides a view on the data that a
1452/// user should see in diagnostics, for example.
1453///
Chandler Carruth3201f382011-07-26 05:17:23 +00001454/// Note that a presumed location is always given as the expansion point of an
1455/// expansion location, not at the spelling location.
Richard Smith62221b12012-11-14 23:55:25 +00001456PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc,
1457 bool UseLineDirectives) const {
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001458 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001459
Chandler Carruth3201f382011-07-26 05:17:23 +00001460 // Presumed locations are always for expansion points.
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +00001461 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +00001462
Douglas Gregore23ac652011-04-20 00:21:03 +00001463 bool Invalid = false;
1464 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1465 if (Invalid || !Entry.isFile())
1466 return PresumedLoc();
1467
1468 const SrcMgr::FileInfo &FI = Entry.getFile();
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001469 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump1eb44332009-09-09 15:08:12 +00001470
Chris Lattner3cd949c2009-02-04 01:55:42 +00001471 // To get the source name, first consult the FileEntry (if one exists)
1472 // before the MemBuffer as this will avoid unnecessarily paging in the
1473 // MemBuffer.
Chris Lattnere127a0d2010-04-20 20:35:58 +00001474 const char *Filename;
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001475 if (C->OrigEntry)
1476 Filename = C->OrigEntry->getName();
Chris Lattnere127a0d2010-04-20 20:35:58 +00001477 else
1478 Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
Douglas Gregore23ac652011-04-20 00:21:03 +00001479
Douglas Gregorc417fa02010-11-02 00:39:22 +00001480 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1481 if (Invalid)
1482 return PresumedLoc();
1483 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1484 if (Invalid)
1485 return PresumedLoc();
1486
Chris Lattner3cd949c2009-02-04 01:55:42 +00001487 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001488
Chris Lattner3cd949c2009-02-04 01:55:42 +00001489 // If we have #line directives in this file, update and overwrite the physical
1490 // location info if appropriate.
Richard Smith62221b12012-11-14 23:55:25 +00001491 if (UseLineDirectives && FI.hasLineDirectives()) {
Chris Lattner3cd949c2009-02-04 01:55:42 +00001492 assert(LineTable && "Can't have linetable entries without a LineTable!");
1493 // See if there is a #line directive before this. If so, get it.
1494 if (const LineEntry *Entry =
Douglas Gregor47d9de62012-06-08 16:40:28 +00001495 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
Chris Lattnerfc391332009-02-04 02:00:59 +00001496 // If the LineEntry indicates a filename, use it.
Chris Lattner3cd949c2009-02-04 01:55:42 +00001497 if (Entry->FilenameID != -1)
1498 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerfc391332009-02-04 02:00:59 +00001499
1500 // Use the line number specified by the LineEntry. This line number may
1501 // be multiple lines down from the line entry. Add the difference in
1502 // physical line numbers from the query point and the line marker to the
1503 // total.
1504 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1505 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001506
Chris Lattner0e0e5da2009-02-04 02:15:40 +00001507 // Note that column numbers are not molested by line markers.
Mike Stump1eb44332009-09-09 15:08:12 +00001508
Chris Lattner137b6a62009-02-04 06:25:26 +00001509 // Handle virtual #include manipulation.
1510 if (Entry->IncludeOffset) {
1511 IncludeLoc = getLocForStartOfFile(LocInfo.first);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001512 IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
Chris Lattner137b6a62009-02-04 06:25:26 +00001513 }
Chris Lattner3cd949c2009-02-04 01:55:42 +00001514 }
1515 }
1516
1517 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001518}
1519
Benjamin Kramer1b9c5372013-09-27 17:12:50 +00001520/// \brief Returns whether the PresumedLoc for a given SourceLocation is
1521/// in the main file.
1522///
1523/// This computes the "presumed" location for a SourceLocation, then checks
1524/// whether it came from a file other than the main file. This is different
1525/// from isWrittenInMainFile() because it takes line marker directives into
1526/// account.
1527bool SourceManager::isInMainFile(SourceLocation Loc) const {
1528 if (Loc.isInvalid()) return false;
1529
1530 // Presumed locations are always for expansion points.
1531 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1532
1533 bool Invalid = false;
1534 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1535 if (Invalid || !Entry.isFile())
1536 return false;
1537
1538 const SrcMgr::FileInfo &FI = Entry.getFile();
1539
1540 // Check if there is a line directive for this location.
1541 if (FI.hasLineDirectives())
1542 if (const LineEntry *Entry =
1543 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
1544 if (Entry->IncludeOffset)
1545 return false;
1546
1547 return FI.getIncludeLoc().isInvalid();
1548}
1549
Stephen Hines651f13c2014-04-23 16:59:28 -07001550/// \brief The size of the SLocEntry that \p FID represents.
Argyrios Kyrtzidis984e42c2011-08-23 21:02:28 +00001551unsigned SourceManager::getFileIDSize(FileID FID) const {
1552 bool Invalid = false;
1553 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1554 if (Invalid)
1555 return 0;
1556
1557 int ID = FID.ID;
1558 unsigned NextOffset;
1559 if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
1560 NextOffset = getNextLocalOffset();
1561 else if (ID+1 == -1)
1562 NextOffset = MaxLoadedOffset;
1563 else
1564 NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
1565
1566 return NextOffset - Entry.getOffset() - 1;
1567}
1568
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001569//===----------------------------------------------------------------------===//
1570// Other miscellaneous methods.
1571//===----------------------------------------------------------------------===//
1572
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001573/// \brief Retrieve the inode for the given file entry, if possible.
1574///
1575/// This routine involves a system call, and therefore should only be used
1576/// in non-performance-critical code.
Rafael Espindola44888352013-07-29 21:26:52 +00001577static Optional<llvm::sys::fs::UniqueID>
1578getActualFileUID(const FileEntry *File) {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001579 if (!File)
David Blaikie66874fb2013-02-21 01:47:18 +00001580 return None;
Rafael Espindola3dadc852013-07-29 18:43:40 +00001581
Rafael Espindola44888352013-07-29 21:26:52 +00001582 llvm::sys::fs::UniqueID ID;
Rafael Espindola3dadc852013-07-29 18:43:40 +00001583 if (llvm::sys::fs::getUniqueID(File->getName(), ID))
David Blaikie66874fb2013-02-21 01:47:18 +00001584 return None;
Rafael Espindola3dadc852013-07-29 18:43:40 +00001585
1586 return ID;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001587}
1588
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001589/// \brief Get the source location for the given file:line:col triplet.
1590///
1591/// If the source file is included multiple times, the source location will
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001592/// be based upon an arbitrary inclusion.
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001593SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001594 unsigned Line,
1595 unsigned Col) const {
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001596 assert(SourceFile && "Null source file!");
1597 assert(Line && Col && "Line and column should start from 1!");
1598
Argyrios Kyrtzidisb201e162011-09-27 17:22:25 +00001599 FileID FirstFID = translateFile(SourceFile);
1600 return translateLineCol(FirstFID, Line, Col);
1601}
1602
1603/// \brief Get the FileID for the given file.
1604///
1605/// If the source file is included multiple times, the FileID will be the
1606/// first inclusion.
1607FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
1608 assert(SourceFile && "Null source file!");
1609
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001610 // Find the first file ID that corresponds to the given file.
1611 FileID FirstFID;
Mike Stump1eb44332009-09-09 15:08:12 +00001612
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001613 // First, check the main file ID, since it is common to look for a
1614 // location in the main file.
Rafael Espindola44888352013-07-29 21:26:52 +00001615 Optional<llvm::sys::fs::UniqueID> SourceFileUID;
David Blaikiedc84cd52013-02-20 22:23:23 +00001616 Optional<StringRef> SourceFileName;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001617 if (!MainFileID.isInvalid()) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001618 bool Invalid = false;
1619 const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1620 if (Invalid)
Argyrios Kyrtzidisb201e162011-09-27 17:22:25 +00001621 return FileID();
Douglas Gregore23ac652011-04-20 00:21:03 +00001622
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001623 if (MainSLoc.isFile()) {
1624 const ContentCache *MainContentCache
1625 = MainSLoc.getFile().getContentCache();
Douglas Gregorb7a18412011-02-11 18:08:15 +00001626 if (!MainContentCache) {
1627 // Can't do anything
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001628 } else if (MainContentCache->OrigEntry == SourceFile) {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001629 FirstFID = MainFileID;
Douglas Gregorb7a18412011-02-11 18:08:15 +00001630 } else {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001631 // Fall back: check whether we have the same base name and inode
1632 // as the main file.
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001633 const FileEntry *MainFile = MainContentCache->OrigEntry;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001634 SourceFileName = llvm::sys::path::filename(SourceFile->getName());
1635 if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) {
Rafael Espindola3dadc852013-07-29 18:43:40 +00001636 SourceFileUID = getActualFileUID(SourceFile);
1637 if (SourceFileUID) {
Rafael Espindola44888352013-07-29 21:26:52 +00001638 if (Optional<llvm::sys::fs::UniqueID> MainFileUID =
1639 getActualFileUID(MainFile)) {
Rafael Espindola3dadc852013-07-29 18:43:40 +00001640 if (*SourceFileUID == *MainFileUID) {
Douglas Gregor37c02bf2011-02-16 19:09:24 +00001641 FirstFID = MainFileID;
1642 SourceFile = MainFile;
1643 }
1644 }
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001645 }
1646 }
1647 }
1648 }
1649 }
1650
1651 if (FirstFID.isInvalid()) {
1652 // The location we're looking for isn't in the main file; look
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001653 // through all of the local source locations.
1654 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001655 bool Invalid = false;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001656 const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid);
Douglas Gregore23ac652011-04-20 00:21:03 +00001657 if (Invalid)
Argyrios Kyrtzidisb201e162011-09-27 17:22:25 +00001658 return FileID();
Douglas Gregore23ac652011-04-20 00:21:03 +00001659
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001660 if (SLoc.isFile() &&
1661 SLoc.getFile().getContentCache() &&
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001662 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001663 FirstFID = FileID::get(I);
1664 break;
1665 }
1666 }
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001667 // If that still didn't help, try the modules.
1668 if (FirstFID.isInvalid()) {
1669 for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
1670 const SLocEntry &SLoc = getLoadedSLocEntry(I);
1671 if (SLoc.isFile() &&
1672 SLoc.getFile().getContentCache() &&
1673 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1674 FirstFID = FileID::get(-int(I) - 2);
1675 break;
1676 }
1677 }
1678 }
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001679 }
1680
1681 // If we haven't found what we want yet, try again, but this time stat()
1682 // each of the files in case the files have changed since we originally
Rafael Espindola3dadc852013-07-29 18:43:40 +00001683 // parsed the file.
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001684 if (FirstFID.isInvalid() &&
Rafael Espindola3dadc852013-07-29 18:43:40 +00001685 (SourceFileName ||
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001686 (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) &&
Rafael Espindola3dadc852013-07-29 18:43:40 +00001687 (SourceFileUID || (SourceFileUID = getActualFileUID(SourceFile)))) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001688 bool Invalid = false;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001689 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1690 FileID IFileID;
1691 IFileID.ID = I;
1692 const SLocEntry &SLoc = getSLocEntry(IFileID, &Invalid);
Douglas Gregore23ac652011-04-20 00:21:03 +00001693 if (Invalid)
Argyrios Kyrtzidisb201e162011-09-27 17:22:25 +00001694 return FileID();
Douglas Gregore23ac652011-04-20 00:21:03 +00001695
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001696 if (SLoc.isFile()) {
1697 const ContentCache *FileContentCache
1698 = SLoc.getFile().getContentCache();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001699 const FileEntry *Entry = FileContentCache ? FileContentCache->OrigEntry
1700 : nullptr;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001701 if (Entry &&
Douglas Gregorb7a18412011-02-11 18:08:15 +00001702 *SourceFileName == llvm::sys::path::filename(Entry->getName())) {
Rafael Espindola44888352013-07-29 21:26:52 +00001703 if (Optional<llvm::sys::fs::UniqueID> EntryUID =
1704 getActualFileUID(Entry)) {
Rafael Espindola3dadc852013-07-29 18:43:40 +00001705 if (*SourceFileUID == *EntryUID) {
Douglas Gregorb7a18412011-02-11 18:08:15 +00001706 FirstFID = FileID::get(I);
1707 SourceFile = Entry;
1708 break;
1709 }
1710 }
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001711 }
1712 }
1713 }
1714 }
Argyrios Kyrtzidisb201e162011-09-27 17:22:25 +00001715
Ted Kremenek186ec9c2012-10-12 22:56:33 +00001716 (void) SourceFile;
Argyrios Kyrtzidisb201e162011-09-27 17:22:25 +00001717 return FirstFID;
Argyrios Kyrtzidisefa2ff82011-09-19 20:40:29 +00001718}
1719
1720/// \brief Get the source location in \arg FID for the given line:col.
1721/// Returns null location if \arg FID is not a file SLocEntry.
1722SourceLocation SourceManager::translateLineCol(FileID FID,
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001723 unsigned Line,
1724 unsigned Col) const {
Aaron Ballmanfb21ecf2013-11-18 18:29:00 +00001725 // Lines are used as a one-based index into a zero-based array. This assert
1726 // checks for possible buffer underruns.
1727 assert(Line != 0 && "Passed a zero-based line");
1728
Argyrios Kyrtzidisefa2ff82011-09-19 20:40:29 +00001729 if (FID.isInvalid())
1730 return SourceLocation();
1731
1732 bool Invalid = false;
1733 const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1734 if (Invalid)
1735 return SourceLocation();
Alexander Kornienkoc8051e62013-07-29 22:26:10 +00001736
Argyrios Kyrtzidisefa2ff82011-09-19 20:40:29 +00001737 if (!Entry.isFile())
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001738 return SourceLocation();
1739
Argyrios Kyrtzidis5e5e95d2011-09-20 22:14:54 +00001740 SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
1741
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001742 if (Line == 1 && Col == 1)
Argyrios Kyrtzidis5e5e95d2011-09-20 22:14:54 +00001743 return FileLoc;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001744
1745 ContentCache *Content
Argyrios Kyrtzidisefa2ff82011-09-19 20:40:29 +00001746 = const_cast<ContentCache *>(Entry.getFile().getContentCache());
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001747 if (!Content)
1748 return SourceLocation();
Alexander Kornienkoc8051e62013-07-29 22:26:10 +00001749
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001750 // If this is the first use of line information for this buffer, compute the
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001751 // SourceLineCache for it on demand.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001752 if (!Content->SourceLineCache) {
Douglas Gregor50f6af72010-03-16 05:20:39 +00001753 bool MyInvalid = false;
Chris Lattnere127a0d2010-04-20 20:35:58 +00001754 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001755 if (MyInvalid)
1756 return SourceLocation();
1757 }
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001758
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001759 if (Line > Content->NumLines) {
Chris Lattnere127a0d2010-04-20 20:35:58 +00001760 unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001761 if (Size > 0)
1762 --Size;
Argyrios Kyrtzidis5e5e95d2011-09-20 22:14:54 +00001763 return FileLoc.getLocWithOffset(Size);
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001764 }
1765
Dylan Noblesmith098eaff2011-12-19 08:51:05 +00001766 const llvm::MemoryBuffer *Buffer = Content->getBuffer(Diag, *this);
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001767 unsigned FilePos = Content->SourceLineCache[Line - 1];
Dylan Noblesmith098eaff2011-12-19 08:51:05 +00001768 const char *Buf = Buffer->getBufferStart() + FilePos;
1769 unsigned BufLength = Buffer->getBufferSize() - FilePos;
Argyrios Kyrtzidis5e5e95d2011-09-20 22:14:54 +00001770 if (BufLength == 0)
1771 return FileLoc.getLocWithOffset(FilePos);
1772
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001773 unsigned i = 0;
1774
1775 // Check that the given column is valid.
1776 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1777 ++i;
Alexander Kornienkoc8051e62013-07-29 22:26:10 +00001778 return FileLoc.getLocWithOffset(FilePos + i);
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001779}
1780
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001781/// \brief Compute a map of macro argument chunks to their expanded source
1782/// location. Chunks that are not part of a macro argument will map to an
1783/// invalid source location. e.g. if a file contains one macro argument at
1784/// offset 100 with length 10, this is how the map will be formed:
1785/// 0 -> SourceLocation()
1786/// 100 -> Expanded macro arg location
1787/// 110 -> SourceLocation()
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +00001788void SourceManager::computeMacroArgsCache(MacroArgsMap *&CachePtr,
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001789 FileID FID) const {
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001790 assert(!FID.isInvalid());
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +00001791 assert(!CachePtr);
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001792
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +00001793 CachePtr = new MacroArgsMap();
1794 MacroArgsMap &MacroArgsCache = *CachePtr;
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001795 // Initially no macro argument chunk is present.
1796 MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
1797
1798 int ID = FID.ID;
1799 while (1) {
1800 ++ID;
1801 // Stop if there are no more FileIDs to check.
1802 if (ID > 0) {
1803 if (unsigned(ID) >= local_sloc_entry_size())
1804 return;
1805 } else if (ID == -1) {
1806 return;
1807 }
1808
Argyrios Kyrtzidis4ff32252013-06-07 17:57:59 +00001809 bool Invalid = false;
1810 const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);
1811 if (Invalid)
1812 return;
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001813 if (Entry.isFile()) {
1814 SourceLocation IncludeLoc = Entry.getFile().getIncludeLoc();
1815 if (IncludeLoc.isInvalid())
1816 continue;
1817 if (!isInFileID(IncludeLoc, FID))
1818 return; // No more files/macros that may be "contained" in this file.
1819
1820 // Skip the files/macros of the #include'd file, we only care about macros
1821 // that lexed macro arguments from our file.
1822 if (Entry.getFile().NumCreatedFIDs)
1823 ID += Entry.getFile().NumCreatedFIDs - 1/*because of next ++ID*/;
1824 continue;
1825 }
1826
Argyrios Kyrtzidiscee5ec92011-12-21 16:56:35 +00001827 const ExpansionInfo &ExpInfo = Entry.getExpansion();
1828
1829 if (ExpInfo.getExpansionLocStart().isFileID()) {
1830 if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
1831 return; // No more files/macros that may be "contained" in this file.
1832 }
1833
1834 if (!ExpInfo.isMacroArgExpansion())
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001835 continue;
Argyrios Kyrtzidiscee5ec92011-12-21 16:56:35 +00001836
Argyrios Kyrtzidis0872a062012-10-20 00:51:32 +00001837 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1838 ExpInfo.getSpellingLoc(),
1839 SourceLocation::getMacroLoc(Entry.getOffset()),
1840 getFileIDSize(FileID::get(ID)));
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001841 }
1842}
1843
Argyrios Kyrtzidis0872a062012-10-20 00:51:32 +00001844void SourceManager::associateFileChunkWithMacroArgExp(
1845 MacroArgsMap &MacroArgsCache,
1846 FileID FID,
1847 SourceLocation SpellLoc,
1848 SourceLocation ExpansionLoc,
1849 unsigned ExpansionLength) const {
1850 if (!SpellLoc.isFileID()) {
1851 unsigned SpellBeginOffs = SpellLoc.getOffset();
1852 unsigned SpellEndOffs = SpellBeginOffs + ExpansionLength;
1853
1854 // The spelling range for this macro argument expansion can span multiple
1855 // consecutive FileID entries. Go through each entry contained in the
1856 // spelling range and if one is itself a macro argument expansion, recurse
1857 // and associate the file chunk that it represents.
1858
1859 FileID SpellFID; // Current FileID in the spelling range.
1860 unsigned SpellRelativeOffs;
Stephen Hines651f13c2014-04-23 16:59:28 -07001861 std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);
Argyrios Kyrtzidis0872a062012-10-20 00:51:32 +00001862 while (1) {
1863 const SLocEntry &Entry = getSLocEntry(SpellFID);
1864 unsigned SpellFIDBeginOffs = Entry.getOffset();
1865 unsigned SpellFIDSize = getFileIDSize(SpellFID);
1866 unsigned SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;
1867 const ExpansionInfo &Info = Entry.getExpansion();
1868 if (Info.isMacroArgExpansion()) {
1869 unsigned CurrSpellLength;
1870 if (SpellFIDEndOffs < SpellEndOffs)
1871 CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
1872 else
1873 CurrSpellLength = ExpansionLength;
1874 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1875 Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),
1876 ExpansionLoc, CurrSpellLength);
1877 }
1878
1879 if (SpellFIDEndOffs >= SpellEndOffs)
1880 return; // we covered all FileID entries in the spelling range.
1881
1882 // Move to the next FileID entry in the spelling range.
1883 unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
1884 ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);
1885 ExpansionLength -= advance;
1886 ++SpellFID.ID;
1887 SpellRelativeOffs = 0;
1888 }
1889
1890 }
1891
1892 assert(SpellLoc.isFileID());
1893
1894 unsigned BeginOffs;
1895 if (!isInFileID(SpellLoc, FID, &BeginOffs))
1896 return;
1897
1898 unsigned EndOffs = BeginOffs + ExpansionLength;
1899
1900 // Add a new chunk for this macro argument. A previous macro argument chunk
1901 // may have been lexed again, so e.g. if the map is
1902 // 0 -> SourceLocation()
1903 // 100 -> Expanded loc #1
1904 // 110 -> SourceLocation()
1905 // and we found a new macro FileID that lexed from offet 105 with length 3,
1906 // the new map will be:
1907 // 0 -> SourceLocation()
1908 // 100 -> Expanded loc #1
1909 // 105 -> Expanded loc #2
1910 // 108 -> Expanded loc #1
1911 // 110 -> SourceLocation()
1912 //
1913 // Since re-lexed macro chunks will always be the same size or less of
1914 // previous chunks, we only need to find where the ending of the new macro
1915 // chunk is mapped to and update the map with new begin/end mappings.
1916
1917 MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
1918 --I;
1919 SourceLocation EndOffsMappedLoc = I->second;
1920 MacroArgsCache[BeginOffs] = ExpansionLoc;
1921 MacroArgsCache[EndOffs] = EndOffsMappedLoc;
1922}
1923
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001924/// \brief If \arg Loc points inside a function macro argument, the returned
1925/// location will be the macro location in which the argument was expanded.
1926/// If a macro argument is used multiple times, the expanded location will
1927/// be at the first expansion of the argument.
1928/// e.g.
1929/// MY_MACRO(foo);
1930/// ^
1931/// Passing a file location pointing at 'foo', will yield a macro location
1932/// where 'foo' was expanded into.
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001933SourceLocation
1934SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001935 if (Loc.isInvalid() || !Loc.isFileID())
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001936 return Loc;
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001937
1938 FileID FID;
1939 unsigned Offset;
Stephen Hines651f13c2014-04-23 16:59:28 -07001940 std::tie(FID, Offset) = getDecomposedLoc(Loc);
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001941 if (FID.isInvalid())
1942 return Loc;
1943
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +00001944 MacroArgsMap *&MacroArgsCache = MacroArgsCacheMap[FID];
1945 if (!MacroArgsCache)
1946 computeMacroArgsCache(MacroArgsCache, FID);
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001947
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +00001948 assert(!MacroArgsCache->empty());
1949 MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001950 --I;
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001951
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001952 unsigned MacroArgBeginOffs = I->first;
1953 SourceLocation MacroArgExpandedLoc = I->second;
1954 if (MacroArgExpandedLoc.isValid())
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001955 return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001956
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001957 return Loc;
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001958}
1959
Argyrios Kyrtzidisecc65232013-04-13 01:03:57 +00001960std::pair<FileID, unsigned>
1961SourceManager::getDecomposedIncludedLoc(FileID FID) const {
Argyrios Kyrtzidis5b8e1322013-05-24 22:24:04 +00001962 if (FID.isInvalid())
1963 return std::make_pair(FileID(), 0);
1964
Argyrios Kyrtzidisecc65232013-04-13 01:03:57 +00001965 // Uses IncludedLocMap to retrieve/cache the decomposed loc.
1966
1967 typedef std::pair<FileID, unsigned> DecompTy;
1968 typedef llvm::DenseMap<FileID, DecompTy> MapTy;
1969 std::pair<MapTy::iterator, bool>
1970 InsertOp = IncludedLocMap.insert(std::make_pair(FID, DecompTy()));
1971 DecompTy &DecompLoc = InsertOp.first->second;
1972 if (!InsertOp.second)
1973 return DecompLoc; // already in map.
1974
1975 SourceLocation UpperLoc;
Argyrios Kyrtzidis5b8e1322013-05-24 22:24:04 +00001976 bool Invalid = false;
1977 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1978 if (!Invalid) {
1979 if (Entry.isExpansion())
1980 UpperLoc = Entry.getExpansion().getExpansionLocStart();
1981 else
1982 UpperLoc = Entry.getFile().getIncludeLoc();
1983 }
Argyrios Kyrtzidisecc65232013-04-13 01:03:57 +00001984
1985 if (UpperLoc.isValid())
1986 DecompLoc = getDecomposedLoc(UpperLoc);
1987
1988 return DecompLoc;
1989}
1990
Chandler Carruth3201f382011-07-26 05:17:23 +00001991/// Given a decomposed source location, move it up the include/expansion stack
1992/// to the parent source location. If this is possible, return the decomposed
1993/// version of the parent in Loc and return false. If Loc is the top-level
1994/// entry, return true and don't modify it.
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001995static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1996 const SourceManager &SM) {
Argyrios Kyrtzidisecc65232013-04-13 01:03:57 +00001997 std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
1998 if (UpperLoc.first.isInvalid())
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001999 return true; // We reached the top.
Argyrios Kyrtzidisecc65232013-04-13 01:03:57 +00002000
2001 Loc = UpperLoc;
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00002002 return false;
2003}
Ted Kremenek2564f812013-02-27 00:00:26 +00002004
2005/// Return the cache entry for comparing the given file IDs
2006/// for isBeforeInTranslationUnit.
2007InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
2008 FileID RFID) const {
2009 // This is a magic number for limiting the cache size. It was experimentally
2010 // derived from a small Objective-C project (where the cache filled
2011 // out to ~250 items). We can make it larger if necessary.
2012 enum { MagicCacheSize = 300 };
2013 IsBeforeInTUCacheKey Key(LFID, RFID);
2014
2015 // If the cache size isn't too large, do a lookup and if necessary default
2016 // construct an entry. We can then return it to the caller for direct
2017 // use. When they update the value, the cache will get automatically
2018 // updated as well.
2019 if (IBTUCache.size() < MagicCacheSize)
2020 return IBTUCache[Key];
2021
2022 // Otherwise, do a lookup that will not construct a new value.
2023 InBeforeInTUCache::iterator I = IBTUCache.find(Key);
2024 if (I != IBTUCache.end())
2025 return I->second;
2026
2027 // Fall back to the overflow value.
2028 return IBTUCacheOverflow;
2029}
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00002030
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00002031/// \brief Determines the order of 2 source locations in the translation unit.
2032///
2033/// \returns true if LHS source location comes before RHS, false otherwise.
2034bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
2035 SourceLocation RHS) const {
2036 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
2037 if (LHS == RHS)
2038 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002039
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00002040 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
2041 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002042
Argyrios Kyrtzidisecdbbfa2013-05-24 23:47:43 +00002043 // getDecomposedLoc may have failed to return a valid FileID because, e.g. it
2044 // is a serialized one referring to a file that was removed after we loaded
2045 // the PCH.
Argyrios Kyrtzidis5b8e1322013-05-24 22:24:04 +00002046 if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
Argyrios Kyrtzidis45e1f0e2013-05-25 01:03:03 +00002047 return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
Argyrios Kyrtzidis5b8e1322013-05-24 22:24:04 +00002048
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00002049 // If the source locations are in the same file, just compare offsets.
2050 if (LOffs.first == ROffs.first)
2051 return LOffs.second < ROffs.second;
2052
2053 // If we are comparing a source location with multiple locations in the same
2054 // file, we get a big win by caching the result.
Ted Kremenek2564f812013-02-27 00:00:26 +00002055 InBeforeInTUCacheEntry &IsBeforeInTUCache =
2056 getInBeforeInTUCache(LOffs.first, ROffs.first);
2057
2058 // If we are comparing a source location with multiple locations in the same
2059 // file, we get a big win by caching the result.
Chris Lattner66a915f2010-05-07 05:10:46 +00002060 if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
2061 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Mike Stump1eb44332009-09-09 15:08:12 +00002062
Chris Lattnerdcb1d682010-05-07 01:17:07 +00002063 // Okay, we missed in the cache, start updating the cache for this query.
Argyrios Kyrtzidis37e59a12011-08-17 00:31:18 +00002064 IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
2065 /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID);
Mike Stump1eb44332009-09-09 15:08:12 +00002066
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002067 // We need to find the common ancestor. The only way of doing this is to
2068 // build the complete include chain for one and then walking up the chain
2069 // of the other looking for a match.
2070 // We use a map from FileID to Offset to store the chain. Easier than writing
2071 // a custom set hash info that only depends on the first part of a pair.
Argyrios Kyrtzidisecc65232013-04-13 01:03:57 +00002072 typedef llvm::SmallDenseMap<FileID, unsigned, 16> LocSet;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002073 LocSet LChain;
Chris Lattner48296ba2010-05-07 05:51:13 +00002074 do {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002075 LChain.insert(LOffs);
2076 // We catch the case where LOffs is in a file included by ROffs and
2077 // quit early. The other way round unfortunately remains suboptimal.
2078 } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
2079 LocSet::iterator I;
2080 while((I = LChain.find(ROffs.first)) == LChain.end()) {
2081 if (MoveUpIncludeHierarchy(ROffs, *this))
2082 break; // Met at topmost file.
2083 }
2084 if (I != LChain.end())
2085 LOffs = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00002086
Chris Lattner48296ba2010-05-07 05:51:13 +00002087 // If we exited because we found a nearest common ancestor, compare the
2088 // locations within the common file and cache them.
2089 if (LOffs.first == ROffs.first) {
2090 IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
2091 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00002092 }
Mike Stump1eb44332009-09-09 15:08:12 +00002093
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002094 // This can happen if a location is in a built-ins buffer.
2095 // But see PR5662.
2096 // Clear the lookup cache, it depends on a common location.
Argyrios Kyrtzidis37e59a12011-08-17 00:31:18 +00002097 IsBeforeInTUCache.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002098 bool LIsBuiltins = strcmp("<built-in>",
2099 getBuffer(LOffs.first)->getBufferIdentifier()) == 0;
2100 bool RIsBuiltins = strcmp("<built-in>",
2101 getBuffer(ROffs.first)->getBufferIdentifier()) == 0;
2102 // built-in is before non-built-in
2103 if (LIsBuiltins != RIsBuiltins)
2104 return LIsBuiltins;
2105 assert(LIsBuiltins && RIsBuiltins &&
2106 "Non-built-in locations must be rooted in the main file");
2107 // Both are in built-in buffers, but from different files. We just claim that
2108 // lower IDs come first.
Chris Lattnerdcb1d682010-05-07 01:17:07 +00002109 return LOffs.first < ROffs.first;
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00002110}
Chris Lattnerde7aeef2009-01-26 00:43:02 +00002111
Reid Spencer5f016e22007-07-11 17:01:13 +00002112void SourceManager::PrintStats() const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00002113 llvm::errs() << "\n*** Source Manager Stats:\n";
2114 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
2115 << " mem buffers mapped.\n";
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002116 llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
Ted Kremenek6e36c122011-07-27 18:41:16 +00002117 << llvm::capacity_in_bytes(LocalSLocEntryTable)
Argyrios Kyrtzidisd410e742011-07-07 03:40:24 +00002118 << " bytes of capacity), "
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002119 << NextLocalOffset << "B of Sloc address space used.\n";
2120 llvm::errs() << LoadedSLocEntryTable.size()
2121 << " loaded SLocEntries allocated, "
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00002122 << MaxLoadedOffset - CurrentLoadedOffset
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002123 << "B of Sloc address space used.\n";
2124
Reid Spencer5f016e22007-07-11 17:01:13 +00002125 unsigned NumLineNumsComputed = 0;
2126 unsigned NumFileBytesMapped = 0;
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00002127 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002128 NumLineNumsComputed += I->second->SourceLineCache != nullptr;
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00002129 NumFileBytesMapped += I->second->getSizeBytesMapped();
Reid Spencer5f016e22007-07-11 17:01:13 +00002130 }
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +00002131 unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
Mike Stump1eb44332009-09-09 15:08:12 +00002132
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00002133 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00002134 << NumLineNumsComputed << " files with line #'s computed, "
2135 << NumMacroArgsComputed << " files with macro args computed.\n";
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00002136 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
2137 << NumBinaryProbes << " binary.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +00002138}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002139
2140ExternalSLocEntrySource::~ExternalSLocEntrySource() { }
Ted Kremenekf61b8312011-04-28 20:36:42 +00002141
2142/// Return the amount of memory used by memory buffers, breaking down
2143/// by heap-backed versus mmap'ed memory.
2144SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
2145 size_t malloc_bytes = 0;
2146 size_t mmap_bytes = 0;
2147
2148 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
2149 if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
2150 switch (MemBufferInfos[i]->getMemoryBufferKind()) {
2151 case llvm::MemoryBuffer::MemoryBuffer_MMap:
2152 mmap_bytes += sized_mapped;
2153 break;
2154 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
2155 malloc_bytes += sized_mapped;
2156 break;
2157 }
2158
2159 return MemoryBufferSizes(malloc_bytes, mmap_bytes);
2160}
2161
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00002162size_t SourceManager::getDataStructureSizes() const {
Argyrios Kyrtzidisd54dff02012-05-03 21:50:39 +00002163 size_t size = llvm::capacity_in_bytes(MemBufferInfos)
Ted Kremenek6e36c122011-07-27 18:41:16 +00002164 + llvm::capacity_in_bytes(LocalSLocEntryTable)
2165 + llvm::capacity_in_bytes(LoadedSLocEntryTable)
2166 + llvm::capacity_in_bytes(SLocEntryLoaded)
Argyrios Kyrtzidisd54dff02012-05-03 21:50:39 +00002167 + llvm::capacity_in_bytes(FileInfos);
2168
2169 if (OverriddenFilesInfo)
2170 size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);
2171
2172 return size;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00002173}