blob: ce8aa5d112b36ddba4be12974d018fd20d5715ff [file] [log] [blame]
Eugene Zelenko918e0ca2017-11-03 22:35:27 +00001//===- SourceManager.cpp - Track and cache source files -------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner22eb9722006-06-18 05:43:12 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the SourceManager interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Basic/SourceManager.h"
Douglas Gregor802b7762010-03-15 22:54:52 +000015#include "clang/Basic/Diagnostic.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000016#include "clang/Basic/FileManager.h"
Eugene Zelenko918e0ca2017-11-03 22:35:27 +000017#include "clang/Basic/LLVM.h"
18#include "clang/Basic/SourceLocation.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/Basic/SourceManagerInternals.h"
Eugene Zelenko918e0ca2017-11-03 22:35:27 +000020#include "llvm/ADT/DenseMap.h"
Douglas Gregore6642762011-02-03 17:17:35 +000021#include "llvm/ADT/Optional.h"
Eugene Zelenko918e0ca2017-11-03 22:35:27 +000022#include "llvm/ADT/None.h"
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +000023#include "llvm/ADT/STLExtras.h"
Eugene Zelenko918e0ca2017-11-03 22:35:27 +000024#include "llvm/ADT/SmallVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "llvm/ADT/StringSwitch.h"
Eugene Zelenko918e0ca2017-11-03 22:35:27 +000026#include "llvm/ADT/StringRef.h"
27#include "llvm/Support/Allocator.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "llvm/Support/Capacity.h"
Chris Lattner8996fff2007-07-24 05:57:19 +000029#include "llvm/Support/Compiler.h"
Eugene Zelenko918e0ca2017-11-03 22:35:27 +000030#include "llvm/Support/ErrorHandling.h"
31#include "llvm/Support/FileSystem.h"
32#include "llvm/Support/MathExtras.h"
Chris Lattner739e7392007-04-29 07:12:06 +000033#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000034#include "llvm/Support/Path.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000035#include "llvm/Support/raw_ostream.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000036#include <algorithm>
Eugene Zelenko918e0ca2017-11-03 22:35:27 +000037#include <cassert>
38#include <cstddef>
39#include <cstdint>
40#include <memory>
41#include <tuple>
42#include <utility>
43#include <vector>
Douglas Gregor802b7762010-03-15 22:54:52 +000044
Chris Lattner22eb9722006-06-18 05:43:12 +000045using namespace clang;
Chris Lattner5f4b1ff2006-06-20 05:02:40 +000046using namespace SrcMgr;
Chris Lattner23b7eb62007-06-15 23:05:46 +000047using llvm::MemoryBuffer;
Chris Lattner22eb9722006-06-18 05:43:12 +000048
Chris Lattner153a0f12009-02-04 00:40:31 +000049//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +000050// SourceManager Helper Classes
Chris Lattner153a0f12009-02-04 00:40:31 +000051//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +000052
Ted Kremenekc08bca62007-10-30 21:08:08 +000053ContentCache::~ContentCache() {
Douglas Gregor3f4bea02010-07-26 21:36:20 +000054 if (shouldFreeBuffer())
55 delete Buffer.getPointer();
Chris Lattner22eb9722006-06-18 05:43:12 +000056}
57
Chandler Carruth64ee7822011-07-26 05:17:23 +000058/// getSizeBytesMapped - Returns the number of bytes actually mapped for this
59/// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
Ted Kremenek12c2af42009-01-06 01:55:26 +000060unsigned ContentCache::getSizeBytesMapped() const {
Douglas Gregor82752ec2010-03-16 22:53:51 +000061 return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
Ted Kremenek12c2af42009-01-06 01:55:26 +000062}
63
Ted Kremenek8d587902011-04-28 20:36:42 +000064/// Returns the kind of memory used to back the memory buffer for
65/// this content cache. This is used for performance analysis.
66llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
67 assert(Buffer.getPointer());
68
69 // Should be unreachable, but keep for sanity.
70 if (!Buffer.getPointer())
71 return llvm::MemoryBuffer::MemoryBuffer_Malloc;
David Blaikie66cc07b2014-06-27 17:40:03 +000072
73 llvm::MemoryBuffer *buf = Buffer.getPointer();
Ted Kremenek8d587902011-04-28 20:36:42 +000074 return buf->getBufferKind();
75}
76
Ted Kremenek12c2af42009-01-06 01:55:26 +000077/// getSize - Returns the size of the content encapsulated by this ContentCache.
78/// This can be the size of the source file or the size of an arbitrary
79/// scratch buffer. If the ContentCache encapsulates a source file, that
Douglas Gregor53ad6b92009-12-02 06:49:09 +000080/// file is not lazily brought in from disk to satisfy this query.
Ted Kremenek12c2af42009-01-06 01:55:26 +000081unsigned ContentCache::getSize() const {
Douglas Gregor82752ec2010-03-16 22:53:51 +000082 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +000083 : (unsigned) ContentsEntry->getSize();
Ted Kremenek12c2af42009-01-06 01:55:26 +000084}
85
David Blaikie66cc07b2014-06-27 17:40:03 +000086void ContentCache::replaceBuffer(llvm::MemoryBuffer *B, bool DoNotFree) {
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +000087 if (B && B == Buffer.getPointer()) {
Argyrios Kyrtzidiscc6107d2011-12-10 01:38:26 +000088 assert(0 && "Replacing with the same buffer");
89 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
90 return;
91 }
Richard Smithf878a842017-06-05 22:05:31 +000092
Douglas Gregor3f4bea02010-07-26 21:36:20 +000093 if (shouldFreeBuffer())
94 delete Buffer.getPointer();
Douglas Gregor82752ec2010-03-16 22:53:51 +000095 Buffer.setPointer(B);
Richard Smithf878a842017-06-05 22:05:31 +000096 Buffer.setInt((B && DoNotFree) ? DoNotFreeFlag : 0);
Douglas Gregor53ad6b92009-12-02 06:49:09 +000097}
98
David Blaikie66cc07b2014-06-27 17:40:03 +000099llvm::MemoryBuffer *ContentCache::getBuffer(DiagnosticsEngine &Diag,
100 const SourceManager &SM,
101 SourceLocation Loc,
102 bool *Invalid) const {
Chris Lattner5631b052010-11-23 08:50:03 +0000103 // Lazily create the Buffer for ContentCaches that wrap files. If we already
Chris Lattner57540c52011-04-15 05:22:18 +0000104 // computed it, just return what we have.
Craig Topperf1186c52014-05-08 06:41:40 +0000105 if (Buffer.getPointer() || !ContentsEntry) {
Chris Lattner5631b052010-11-23 08:50:03 +0000106 if (Invalid)
107 *Invalid = isBufferInvalid();
Fangrui Song6907ce22018-07-30 19:24:48 +0000108
Chris Lattner5631b052010-11-23 08:50:03 +0000109 return Buffer.getPointer();
Fangrui Song6907ce22018-07-30 19:24:48 +0000110 }
Benjamin Kramer5a3f1cf2010-11-18 12:46:39 +0000111
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000112 bool isVolatile = SM.userFilesAreVolatile() && !IsSystemFile;
Benjamin Kramera8857962014-10-26 22:44:13 +0000113 auto BufferOrError =
114 SM.getFileManager().getBufferForFile(ContentsEntry, isVolatile);
Chris Lattner5631b052010-11-23 08:50:03 +0000115
116 // If we were unable to open the file, then we are in an inconsistent
117 // situation where the content cache referenced a file which no longer
118 // exists. Most likely, we were using a stat cache with an invalid entry but
119 // the file could also have been removed during processing. Since we can't
120 // really deal with this situation, just create an empty buffer.
121 //
122 // FIXME: This is definitely not ideal, but our immediate clients can't
123 // currently handle returning a null entry here. Ideally we should detect
124 // that we are in an inconsistent situation and error out as quickly as
125 // possible.
Benjamin Kramera8857962014-10-26 22:44:13 +0000126 if (!BufferOrError) {
Craig Topperbf3e3272014-08-30 16:55:52 +0000127 StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
Pavel Labathbf8519b2017-12-20 11:34:38 +0000128 auto BackupBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
129 ContentsEntry->getSize(), "<invalid>");
130 char *Ptr = BackupBuffer->getBufferStart();
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000131 for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
Chris Lattner5631b052010-11-23 08:50:03 +0000132 Ptr[i] = FillStr[i % FillStr.size()];
Pavel Labathbf8519b2017-12-20 11:34:38 +0000133 Buffer.setPointer(BackupBuffer.release());
Chris Lattner5631b052010-11-23 08:50:03 +0000134
135 if (Diag.isDiagnosticInFlight())
Benjamin Kramera8857962014-10-26 22:44:13 +0000136 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
137 ContentsEntry->getName(),
138 BufferOrError.getError().message());
139 else
Chris Lattner5631b052010-11-23 08:50:03 +0000140 Diag.Report(Loc, diag::err_cannot_open_file)
Benjamin Kramera8857962014-10-26 22:44:13 +0000141 << ContentsEntry->getName() << BufferOrError.getError().message();
Chris Lattner5631b052010-11-23 08:50:03 +0000142
143 Buffer.setInt(Buffer.getInt() | InvalidFlag);
Fangrui Song6907ce22018-07-30 19:24:48 +0000144
Chris Lattner5631b052010-11-23 08:50:03 +0000145 if (Invalid) *Invalid = true;
146 return Buffer.getPointer();
147 }
Benjamin Kramera8857962014-10-26 22:44:13 +0000148
149 Buffer.setPointer(BufferOrError->release());
150
Chris Lattner5631b052010-11-23 08:50:03 +0000151 // Check that the file's size is the same as in the file entry (which may
152 // have come from a stat cache).
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000153 if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) {
Chris Lattner5631b052010-11-23 08:50:03 +0000154 if (Diag.isDiagnosticInFlight())
155 Diag.SetDelayedDiagnostic(diag::err_file_modified,
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000156 ContentsEntry->getName());
Chris Lattner5631b052010-11-23 08:50:03 +0000157 else
158 Diag.Report(Loc, diag::err_file_modified)
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000159 << ContentsEntry->getName();
Chris Lattner5631b052010-11-23 08:50:03 +0000160
161 Buffer.setInt(Buffer.getInt() | InvalidFlag);
162 if (Invalid) *Invalid = true;
163 return Buffer.getPointer();
164 }
Eric Christopher7f36a792011-04-09 00:01:04 +0000165
Chris Lattner5631b052010-11-23 08:50:03 +0000166 // If the buffer is valid, check to see if it has a UTF Byte Order Mark
Eric Christopher7f36a792011-04-09 00:01:04 +0000167 // (BOM). We only support UTF-8 with and without a BOM right now. See
Chris Lattner5631b052010-11-23 08:50:03 +0000168 // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000169 StringRef BufStr = Buffer.getPointer()->getBuffer();
Eric Christopher7f36a792011-04-09 00:01:04 +0000170 const char *InvalidBOM = llvm::StringSwitch<const char *>(BufStr)
Chris Lattner5631b052010-11-23 08:50:03 +0000171 .StartsWith("\xFE\xFF", "UTF-16 (BE)")
172 .StartsWith("\xFF\xFE", "UTF-16 (LE)")
David Zarzyckib0c752d2018-02-26 18:42:30 +0000173 .StartsWith(llvm::StringLiteral::withInnerNUL("\x00\x00\xFE\xFF"),
174 "UTF-32 (BE)")
175 .StartsWith(llvm::StringLiteral::withInnerNUL("\xFF\xFE\x00\x00"),
176 "UTF-32 (LE)")
Chris Lattner5631b052010-11-23 08:50:03 +0000177 .StartsWith("\x2B\x2F\x76", "UTF-7")
178 .StartsWith("\xF7\x64\x4C", "UTF-1")
179 .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
180 .StartsWith("\x0E\xFE\xFF", "SDSU")
181 .StartsWith("\xFB\xEE\x28", "BOCU-1")
182 .StartsWith("\x84\x31\x95\x33", "GB-18030")
Craig Topperf1186c52014-05-08 06:41:40 +0000183 .Default(nullptr);
Chris Lattner5631b052010-11-23 08:50:03 +0000184
Eric Christopher7f36a792011-04-09 00:01:04 +0000185 if (InvalidBOM) {
Chris Lattner5631b052010-11-23 08:50:03 +0000186 Diag.Report(Loc, diag::err_unsupported_bom)
Eric Christopher7f36a792011-04-09 00:01:04 +0000187 << InvalidBOM << ContentsEntry->getName();
Chris Lattner5631b052010-11-23 08:50:03 +0000188 Buffer.setInt(Buffer.getInt() | InvalidFlag);
Ted Kremenek763ea552009-01-06 22:43:04 +0000189 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000190
Douglas Gregor82752ec2010-03-16 22:53:51 +0000191 if (Invalid)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000192 *Invalid = isBufferInvalid();
Fangrui Song6907ce22018-07-30 19:24:48 +0000193
Douglas Gregor82752ec2010-03-16 22:53:51 +0000194 return Buffer.getPointer();
Ted Kremenek12c2af42009-01-06 01:55:26 +0000195}
196
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000197unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
Fangrui Songeae2b492018-12-09 01:46:01 +0000198 auto IterBool = FilenameIDs.try_emplace(Name, FilenamesByID.size());
David Blaikie13156b62014-11-19 03:06:06 +0000199 if (IterBool.second)
200 FilenamesByID.push_back(&*IterBool.first);
201 return IterBool.first->second;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000202}
203
Reid Klecknereb00ee02017-05-22 21:42:58 +0000204/// Add a line note to the line table that indicates that there is a \#line or
205/// GNU line marker at the specified FID/Offset location which changes the
206/// presumed location to LineNo/FilenameID. If EntryExit is 0, then this doesn't
207/// change the presumed \#include stack. If it is 1, this is a file entry, if
208/// it is 2 then this is a file exit. FileKind specifies whether this is a
209/// system header or extern C system header.
210void LineTableInfo::AddLineNote(FileID FID, unsigned Offset, unsigned LineNo,
211 int FilenameID, unsigned EntryExit,
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000212 SrcMgr::CharacteristicKind FileKind) {
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000213 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump11289f42009-09-09 15:08:12 +0000214
Reid Klecknereb00ee02017-05-22 21:42:58 +0000215 // An unspecified FilenameID means use the last filename if available, or the
216 // main source file otherwise.
217 if (FilenameID == -1 && !Entries.empty())
218 FilenameID = Entries.back().FilenameID;
219
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000220 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
221 "Adding line entries out of order!");
222
Chris Lattner1c967782009-02-04 06:25:26 +0000223 unsigned IncludeOffset = 0;
224 if (EntryExit == 0) { // No #include stack change.
225 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
226 } else if (EntryExit == 1) {
227 IncludeOffset = Offset-1;
228 } else if (EntryExit == 2) {
229 assert(!Entries.empty() && Entries.back().IncludeOffset &&
230 "PPDirectives should have caught case when popping empty include stack");
Mike Stump11289f42009-09-09 15:08:12 +0000231
Chris Lattner1c967782009-02-04 06:25:26 +0000232 // Get the include loc of the last entries' include loc as our include loc.
233 IncludeOffset = 0;
234 if (const LineEntry *PrevEntry =
235 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
236 IncludeOffset = PrevEntry->IncludeOffset;
237 }
Mike Stump11289f42009-09-09 15:08:12 +0000238
Chris Lattner1c967782009-02-04 06:25:26 +0000239 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
240 IncludeOffset));
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000241}
242
Chris Lattnerd4293922009-02-04 01:55:42 +0000243/// FindNearestLineEntry - Find the line entry nearest to FID that is before
244/// it. If there is no line entry before Offset in FID, return null.
Douglas Gregor02c2dbf2012-06-08 16:40:28 +0000245const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID,
Chris Lattnerd4293922009-02-04 01:55:42 +0000246 unsigned Offset) {
247 const std::vector<LineEntry> &Entries = LineEntries[FID];
248 assert(!Entries.empty() && "No #line entries for this FID after all!");
249
Chris Lattner334a2ad2009-02-04 04:46:59 +0000250 // It is very common for the query to be after the last #line, check this
251 // first.
252 if (Entries.back().FileOffset <= Offset)
253 return &Entries.back();
Chris Lattnerd4293922009-02-04 01:55:42 +0000254
Chris Lattner334a2ad2009-02-04 04:46:59 +0000255 // Do a binary search to find the maximal element that is still before Offset.
256 std::vector<LineEntry>::const_iterator I =
257 std::upper_bound(Entries.begin(), Entries.end(), Offset);
Craig Topperf1186c52014-05-08 06:41:40 +0000258 if (I == Entries.begin()) return nullptr;
Chris Lattner334a2ad2009-02-04 04:46:59 +0000259 return &*--I;
Chris Lattnerd4293922009-02-04 01:55:42 +0000260}
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000261
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000262/// Add a new line entry that has already been encoded into
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000263/// the internal representation of the line table.
Douglas Gregor02c2dbf2012-06-08 16:40:28 +0000264void LineTableInfo::AddEntry(FileID FID,
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000265 const std::vector<LineEntry> &Entries) {
266 LineEntries[FID] = Entries;
267}
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000268
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000269/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000270unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
Vedant Kumar5eeeab72015-11-12 00:11:19 +0000271 return getLineTable().getLineTableFilenameID(Name);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000272}
273
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000274/// AddLineNote - Add a line note to the line table for the FileID and offset
275/// specified by Loc. If FilenameID is -1, it is considered to be
276/// unspecified.
277void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000278 int FilenameID, bool IsFileEntry,
Reid Klecknereb00ee02017-05-22 21:42:58 +0000279 bool IsFileExit,
280 SrcMgr::CharacteristicKind FileKind) {
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000281 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregor49f754f2011-04-20 00:21:03 +0000282
283 bool Invalid = false;
284 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
285 if (!Entry.isFile() || Invalid)
286 return;
Reid Klecknereb00ee02017-05-22 21:42:58 +0000287
Douglas Gregor49f754f2011-04-20 00:21:03 +0000288 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
Mike Stump11289f42009-09-09 15:08:12 +0000289
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000290 // Remember that this file has #line directives now if it doesn't already.
291 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump11289f42009-09-09 15:08:12 +0000292
Vedant Kumar5eeeab72015-11-12 00:11:19 +0000293 (void) getLineTable();
Mike Stump11289f42009-09-09 15:08:12 +0000294
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000295 unsigned EntryExit = 0;
296 if (IsFileEntry)
297 EntryExit = 1;
298 else if (IsFileExit)
299 EntryExit = 2;
Mike Stump11289f42009-09-09 15:08:12 +0000300
Douglas Gregor02c2dbf2012-06-08 16:40:28 +0000301 LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000302 EntryExit, FileKind);
303}
304
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000305LineTableInfo &SourceManager::getLineTable() {
Craig Topperf1186c52014-05-08 06:41:40 +0000306 if (!LineTable)
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000307 LineTable = new LineTableInfo();
308 return *LineTable;
309}
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000310
Chris Lattner153a0f12009-02-04 00:40:31 +0000311//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +0000312// Private 'Create' methods.
Chris Lattner153a0f12009-02-04 00:40:31 +0000313//===----------------------------------------------------------------------===//
Ted Kremenek12c2af42009-01-06 01:55:26 +0000314
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000315SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
316 bool UserFilesAreVolatile)
Eugene Zelenko918e0ca2017-11-03 22:35:27 +0000317 : Diag(Diag), FileMgr(FileMgr), UserFilesAreVolatile(UserFilesAreVolatile) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000318 clearIDTables();
319 Diag.setSourceManager(this);
320}
321
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000322SourceManager::~SourceManager() {
323 delete LineTable;
Mike Stump11289f42009-09-09 15:08:12 +0000324
Chris Lattnerc8233df2009-02-03 07:30:45 +0000325 // Delete FileEntry objects corresponding to content caches. Since the actual
326 // content cache objects are bump pointer allocated, we just have to run the
327 // dtors, but we call the deallocate method for completeness.
328 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
Argyrios Kyrtzidisaf41b3f2011-12-15 23:37:55 +0000329 if (MemBufferInfos[i]) {
330 MemBufferInfos[i]->~ContentCache();
331 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
332 }
Chris Lattnerc8233df2009-02-03 07:30:45 +0000333 }
334 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
335 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
Argyrios Kyrtzidisaf41b3f2011-12-15 23:37:55 +0000336 if (I->second) {
337 I->second->~ContentCache();
338 ContentCacheAlloc.Deallocate(I->second);
339 }
Chris Lattnerc8233df2009-02-03 07:30:45 +0000340 }
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000341}
342
343void SourceManager::clearIDTables() {
344 MainFileID = FileID();
Douglas Gregor925296b2011-07-19 16:10:42 +0000345 LocalSLocEntryTable.clear();
346 LoadedSLocEntryTable.clear();
347 SLocEntryLoaded.clear();
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000348 LastLineNoFileIDQuery = FileID();
Craig Topperf1186c52014-05-08 06:41:40 +0000349 LastLineNoContentCache = nullptr;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000350 LastFileIDLookup = FileID();
Mike Stump11289f42009-09-09 15:08:12 +0000351
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000352 if (LineTable)
353 LineTable->clear();
Mike Stump11289f42009-09-09 15:08:12 +0000354
Chandler Carruth64ee7822011-07-26 05:17:23 +0000355 // Use up FileID #0 as an invalid expansion.
Douglas Gregor925296b2011-07-19 16:10:42 +0000356 NextLocalOffset = 0;
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +0000357 CurrentLoadedOffset = MaxLoadedOffset;
Eugene Zelenko918e0ca2017-11-03 22:35:27 +0000358 createExpansionLoc(SourceLocation(), SourceLocation(), SourceLocation(), 1);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000359}
360
Richard Smithab755972017-06-05 18:10:11 +0000361void SourceManager::initializeForReplay(const SourceManager &Old) {
362 assert(MainFileID.isInvalid() && "expected uninitialized SourceManager");
363
364 auto CloneContentCache = [&](const ContentCache *Cache) -> ContentCache * {
365 auto *Clone = new (ContentCacheAlloc.Allocate<ContentCache>()) ContentCache;
366 Clone->OrigEntry = Cache->OrigEntry;
367 Clone->ContentsEntry = Cache->ContentsEntry;
368 Clone->BufferOverridden = Cache->BufferOverridden;
369 Clone->IsSystemFile = Cache->IsSystemFile;
370 Clone->IsTransient = Cache->IsTransient;
371 Clone->replaceBuffer(Cache->getRawBuffer(), /*DoNotFree*/true);
372 return Clone;
373 };
374
Richard Smithab755972017-06-05 18:10:11 +0000375 // Ensure all SLocEntries are loaded from the external source.
376 for (unsigned I = 0, N = Old.LoadedSLocEntryTable.size(); I != N; ++I)
377 if (!Old.SLocEntryLoaded[I])
378 Old.loadSLocEntry(I, nullptr);
379
380 // Inherit any content cache data from the old source manager.
381 for (auto &FileInfo : Old.FileInfos) {
382 SrcMgr::ContentCache *&Slot = FileInfos[FileInfo.first];
383 if (Slot)
384 continue;
385 Slot = CloneContentCache(FileInfo.second);
386 }
387}
388
Chris Lattner4fa23622009-01-26 00:43:02 +0000389/// getOrCreateContentCache - Create or return a cached ContentCache for the
390/// specified file.
391const ContentCache *
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000392SourceManager::getOrCreateContentCache(const FileEntry *FileEnt,
393 bool isSystemFile) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000394 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump11289f42009-09-09 15:08:12 +0000395
Chris Lattner22eb9722006-06-18 05:43:12 +0000396 // Do we already have information about this file?
Chris Lattnerc8233df2009-02-03 07:30:45 +0000397 ContentCache *&Entry = FileInfos[FileEnt];
398 if (Entry) return Entry;
Mike Stump11289f42009-09-09 15:08:12 +0000399
Chandler Carruth47c48082014-04-15 21:34:12 +0000400 // Nope, create a new Cache entry.
401 Entry = ContentCacheAlloc.Allocate<ContentCache>();
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000402
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +0000403 if (OverriddenFilesInfo) {
404 // If the file contents are overridden with contents from another file,
405 // pass that file to ContentCache.
406 llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
407 overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
408 if (overI == OverriddenFilesInfo->OverriddenFiles.end())
409 new (Entry) ContentCache(FileEnt);
410 else
411 new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
412 : overI->second,
413 overI->second);
414 } else {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000415 new (Entry) ContentCache(FileEnt);
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +0000416 }
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000417
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000418 Entry->IsSystemFile = isSystemFile;
Richard Smitha8cfffa2015-11-26 02:04:16 +0000419 Entry->IsTransient = FilesAreTransient;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000420
Chris Lattnerc8233df2009-02-03 07:30:45 +0000421 return Entry;
Chris Lattner22eb9722006-06-18 05:43:12 +0000422}
423
Richard Smith6d9bc272017-09-09 01:14:04 +0000424/// Create a new ContentCache for the specified memory buffer.
425/// This does no caching.
426const ContentCache *
427SourceManager::createMemBufferContentCache(llvm::MemoryBuffer *Buffer,
428 bool DoNotFree) {
Chandler Carruth47c48082014-04-15 21:34:12 +0000429 // Add a new ContentCache to the MemBufferInfos list and return it.
430 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
Chris Lattnerc8233df2009-02-03 07:30:45 +0000431 new (Entry) ContentCache();
432 MemBufferInfos.push_back(Entry);
Richard Smith6d9bc272017-09-09 01:14:04 +0000433 Entry->replaceBuffer(Buffer, DoNotFree);
Chris Lattnerc8233df2009-02-03 07:30:45 +0000434 return Entry;
Chris Lattner22eb9722006-06-18 05:43:12 +0000435}
436
Argyrios Kyrtzidis969fdfd2012-02-20 23:58:07 +0000437const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
438 bool *Invalid) const {
439 assert(!SLocEntryLoaded[Index]);
440 if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
441 if (Invalid)
442 *Invalid = true;
443 // If the file of the SLocEntry changed we could still have loaded it.
444 if (!SLocEntryLoaded[Index]) {
445 // Try to recover; create a SLocEntry so the rest of clang can handle it.
446 LoadedSLocEntryTable[Index] = SLocEntry::get(0,
447 FileInfo::get(SourceLocation(),
448 getFakeContentCacheForRecovery(),
449 SrcMgr::C_User));
450 }
451 }
452
453 return LoadedSLocEntryTable[Index];
454}
455
Douglas Gregor925296b2011-07-19 16:10:42 +0000456std::pair<int, unsigned>
457SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
458 unsigned TotalSize) {
459 assert(ExternalSLocEntries && "Don't have an external sloc source");
Richard Smith78d81ec2015-08-12 22:25:24 +0000460 // Make sure we're not about to run out of source locations.
461 if (CurrentLoadedOffset - TotalSize < NextLocalOffset)
462 return std::make_pair(0, 0);
Douglas Gregor925296b2011-07-19 16:10:42 +0000463 LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
464 SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
465 CurrentLoadedOffset -= TotalSize;
Douglas Gregor925296b2011-07-19 16:10:42 +0000466 int ID = LoadedSLocEntryTable.size();
467 return std::make_pair(-ID - 1, CurrentLoadedOffset);
Douglas Gregor0bc12932009-04-27 21:28:04 +0000468}
469
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000470/// As part of recovering from missing or changed content, produce a
Douglas Gregor49f754f2011-04-20 00:21:03 +0000471/// fake, non-empty buffer.
David Blaikie66cc07b2014-06-27 17:40:03 +0000472llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const {
Douglas Gregor49f754f2011-04-20 00:21:03 +0000473 if (!FakeBufferForRecovery)
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000474 FakeBufferForRecovery =
475 llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
Rafael Espindolae0f6d882014-08-18 18:33:41 +0000476
477 return FakeBufferForRecovery.get();
Douglas Gregor49f754f2011-04-20 00:21:03 +0000478}
Douglas Gregor258ae542009-04-27 06:38:32 +0000479
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000480/// As part of recovering from missing or changed content, produce a
Argyrios Kyrtzidis969fdfd2012-02-20 23:58:07 +0000481/// fake content cache.
482const SrcMgr::ContentCache *
483SourceManager::getFakeContentCacheForRecovery() const {
484 if (!FakeContentCacheForRecovery) {
Rafael Espindolae0f6d882014-08-18 18:33:41 +0000485 FakeContentCacheForRecovery = llvm::make_unique<SrcMgr::ContentCache>();
Argyrios Kyrtzidis969fdfd2012-02-20 23:58:07 +0000486 FakeContentCacheForRecovery->replaceBuffer(getFakeBufferForRecovery(),
487 /*DoNotFree=*/true);
488 }
Rafael Espindolae0f6d882014-08-18 18:33:41 +0000489 return FakeContentCacheForRecovery.get();
Argyrios Kyrtzidis969fdfd2012-02-20 23:58:07 +0000490}
491
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000492/// Returns the previous in-order FileID or an invalid FileID if there
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000493/// is no previous one.
494FileID SourceManager::getPreviousFileID(FileID FID) const {
495 if (FID.isInvalid())
496 return FileID();
497
498 int ID = FID.ID;
499 if (ID == -1)
500 return FileID();
501
502 if (ID > 0) {
503 if (ID-1 == 0)
504 return FileID();
505 } else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {
506 return FileID();
507 }
508
509 return FileID::get(ID-1);
510}
511
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000512/// Returns the next in-order FileID or an invalid FileID if there is
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000513/// no next one.
514FileID SourceManager::getNextFileID(FileID FID) const {
515 if (FID.isInvalid())
516 return FileID();
517
518 int ID = FID.ID;
519 if (ID > 0) {
520 if (unsigned(ID+1) >= local_sloc_entry_size())
521 return FileID();
522 } else if (ID+1 >= -1) {
523 return FileID();
524 }
525
526 return FileID::get(ID+1);
527}
528
Chris Lattner4fa23622009-01-26 00:43:02 +0000529//===----------------------------------------------------------------------===//
Chandler Carruth64ee7822011-07-26 05:17:23 +0000530// Methods to create new FileID's and macro expansions.
Chris Lattner4fa23622009-01-26 00:43:02 +0000531//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000532
Dan Gohmance46f022010-08-26 21:27:06 +0000533/// createFileID - Create a new FileID for the specified ContentCache and
Ted Kremeneke26f3c52007-10-30 22:57:35 +0000534/// include position. This works regardless of whether the ContentCache
535/// corresponds to a file or some other input source.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000536FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattner4fa23622009-01-26 00:43:02 +0000537 SourceLocation IncludePos,
Douglas Gregor258ae542009-04-27 06:38:32 +0000538 SrcMgr::CharacteristicKind FileCharacter,
Douglas Gregor925296b2011-07-19 16:10:42 +0000539 int LoadedID, unsigned LoadedOffset) {
540 if (LoadedID < 0) {
541 assert(LoadedID != -1 && "Loading sentinel FileID");
542 unsigned Index = unsigned(-LoadedID) - 2;
543 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
544 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
545 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset,
546 FileInfo::get(IncludePos, File, FileCharacter));
547 SLocEntryLoaded[Index] = true;
548 return FileID::get(LoadedID);
Douglas Gregor258ae542009-04-27 06:38:32 +0000549 }
Douglas Gregor925296b2011-07-19 16:10:42 +0000550 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset,
551 FileInfo::get(IncludePos, File,
552 FileCharacter)));
Ted Kremenek12c2af42009-01-06 01:55:26 +0000553 unsigned FileSize = File->getSize();
Douglas Gregor925296b2011-07-19 16:10:42 +0000554 assert(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
555 NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset &&
556 "Ran out of source locations!");
557 // We do a +1 here because we want a SourceLocation that means "the end of the
558 // file", e.g. for the "no newline at the end of the file" diagnostic.
559 NextLocalOffset += FileSize + 1;
Mike Stump11289f42009-09-09 15:08:12 +0000560
Chris Lattner4fa23622009-01-26 00:43:02 +0000561 // Set LastFileIDLookup to the newly created file. The next getFileID call is
562 // almost guaranteed to be from that file.
Douglas Gregor925296b2011-07-19 16:10:42 +0000563 FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
Argyrios Kyrtzidis0152c6c2009-06-23 00:42:06 +0000564 return LastFileIDLookup = FID;
Chris Lattner22eb9722006-06-18 05:43:12 +0000565}
566
Chandler Carruth402bb382011-07-07 23:56:36 +0000567SourceLocation
Chandler Carruth115b0772011-07-26 03:03:05 +0000568SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc,
569 SourceLocation ExpansionLoc,
570 unsigned TokLength) {
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000571 ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
572 ExpansionLoc);
573 return createExpansionLocImpl(Info, TokLength);
Chandler Carruth402bb382011-07-07 23:56:36 +0000574}
575
576SourceLocation
Chandler Carruth115b0772011-07-26 03:03:05 +0000577SourceManager::createExpansionLoc(SourceLocation SpellingLoc,
578 SourceLocation ExpansionLocStart,
579 SourceLocation ExpansionLocEnd,
580 unsigned TokLength,
Richard Smithb5f81712018-04-30 05:25:48 +0000581 bool ExpansionIsTokenRange,
Chandler Carruth115b0772011-07-26 03:03:05 +0000582 int LoadedID,
583 unsigned LoadedOffset) {
Richard Smithb5f81712018-04-30 05:25:48 +0000584 ExpansionInfo Info = ExpansionInfo::create(
585 SpellingLoc, ExpansionLocStart, ExpansionLocEnd, ExpansionIsTokenRange);
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000586 return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset);
Chandler Carruth115b0772011-07-26 03:03:05 +0000587}
588
Richard Smithb5f81712018-04-30 05:25:48 +0000589SourceLocation SourceManager::createTokenSplitLoc(SourceLocation Spelling,
590 SourceLocation TokenStart,
591 SourceLocation TokenEnd) {
592 assert(getFileID(TokenStart) == getFileID(TokenEnd) &&
593 "token spans multiple files");
594 return createExpansionLocImpl(
595 ExpansionInfo::createForTokenSplit(Spelling, TokenStart, TokenEnd),
596 TokenEnd.getOffset() - TokenStart.getOffset());
597}
598
Chandler Carruth115b0772011-07-26 03:03:05 +0000599SourceLocation
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000600SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
Chandler Carruth115b0772011-07-26 03:03:05 +0000601 unsigned TokLength,
602 int LoadedID,
603 unsigned LoadedOffset) {
Douglas Gregor925296b2011-07-19 16:10:42 +0000604 if (LoadedID < 0) {
605 assert(LoadedID != -1 && "Loading sentinel FileID");
606 unsigned Index = unsigned(-LoadedID) - 2;
607 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
608 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000609 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
Douglas Gregor925296b2011-07-19 16:10:42 +0000610 SLocEntryLoaded[Index] = true;
611 return SourceLocation::getMacroLoc(LoadedOffset);
Douglas Gregor258ae542009-04-27 06:38:32 +0000612 }
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000613 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
Douglas Gregor925296b2011-07-19 16:10:42 +0000614 assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&
615 NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&
616 "Ran out of source locations!");
617 // See createFileID for that +1.
618 NextLocalOffset += TokLength + 1;
619 return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
Chris Lattner7d6a4f62006-06-30 06:10:08 +0000620}
621
David Blaikie66cc07b2014-06-27 17:40:03 +0000622llvm::MemoryBuffer *SourceManager::getMemoryBufferForFile(const FileEntry *File,
623 bool *Invalid) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000624 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregor802b7762010-03-15 22:54:52 +0000625 assert(IR && "getOrCreateContentCache() cannot return NULL");
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000626 return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000627}
628
Dan Gohman5d223dc2010-10-26 20:47:28 +0000629void SourceManager::overrideFileContents(const FileEntry *SourceFile,
David Blaikie66cc07b2014-06-27 17:40:03 +0000630 llvm::MemoryBuffer *Buffer,
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000631 bool DoNotFree) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000632 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
Dan Gohman5d223dc2010-10-26 20:47:28 +0000633 assert(IR && "getOrCreateContentCache() cannot return NULL");
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000634
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000635 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
Douglas Gregor9dc32122011-11-16 20:05:18 +0000636 const_cast<SrcMgr::ContentCache *>(IR)->BufferOverridden = true;
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +0000637
638 getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000639}
640
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000641void SourceManager::overrideFileContents(const FileEntry *SourceFile,
642 const FileEntry *NewFile) {
643 assert(SourceFile->getSize() == NewFile->getSize() &&
644 "Different sizes, use the FileManager to create a virtual file with "
645 "the correct size");
646 assert(FileInfos.count(SourceFile) == 0 &&
647 "This function should be called at the initialization stage, before "
648 "any parsing occurs.");
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +0000649 getOverriddenFilesInfo().OverriddenFiles[SourceFile] = NewFile;
650}
651
652void SourceManager::disableFileContentsOverride(const FileEntry *File) {
653 if (!isFileOverridden(File))
654 return;
655
656 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Craig Topperf1186c52014-05-08 06:41:40 +0000657 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(nullptr);
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +0000658 const_cast<SrcMgr::ContentCache *>(IR)->ContentsEntry = IR->OrigEntry;
659
660 assert(OverriddenFilesInfo);
661 OverriddenFilesInfo->OverriddenFiles.erase(File);
662 OverriddenFilesInfo->OverriddenFilesWithBuffer.erase(File);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000663}
664
Richard Smitha8cfffa2015-11-26 02:04:16 +0000665void SourceManager::setFileIsTransient(const FileEntry *File) {
Richard Smithfb1e7f72015-08-14 05:02:58 +0000666 const SrcMgr::ContentCache *CC = getOrCreateContentCache(File);
Richard Smitha8cfffa2015-11-26 02:04:16 +0000667 const_cast<SrcMgr::ContentCache *>(CC)->IsTransient = true;
Richard Smithfb1e7f72015-08-14 05:02:58 +0000668}
669
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000670StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +0000671 bool MyInvalid = false;
Douglas Gregor925296b2011-07-19 16:10:42 +0000672 const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid);
Douglas Gregor49f754f2011-04-20 00:21:03 +0000673 if (!SLoc.isFile() || MyInvalid) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000674 if (Invalid)
Douglas Gregor86af9842011-01-31 22:42:36 +0000675 *Invalid = true;
676 return "<<<<<INVALID SOURCE LOCATION>>>>>";
677 }
David Blaikie66cc07b2014-06-27 17:40:03 +0000678
679 llvm::MemoryBuffer *Buf = SLoc.getFile().getContentCache()->getBuffer(
680 Diag, *this, SourceLocation(), &MyInvalid);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000681 if (Invalid)
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +0000682 *Invalid = MyInvalid;
683
684 if (MyInvalid)
Douglas Gregor86af9842011-01-31 22:42:36 +0000685 return "<<<<<INVALID SOURCE LOCATION>>>>>";
Fangrui Song6907ce22018-07-30 19:24:48 +0000686
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000687 return Buf->getBuffer();
Douglas Gregor802b7762010-03-15 22:54:52 +0000688}
Chris Lattnerd32480d2009-01-17 06:22:33 +0000689
Chris Lattner153a0f12009-02-04 00:40:31 +0000690//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +0000691// SourceLocation manipulation methods.
Chris Lattner153a0f12009-02-04 00:40:31 +0000692//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +0000693
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000694/// Return the FileID for a SourceLocation.
Chris Lattner4fa23622009-01-26 00:43:02 +0000695///
Douglas Gregor925296b2011-07-19 16:10:42 +0000696/// This is the cache-miss path of getFileID. Not as hot as that function, but
697/// still very important. It is responsible for finding the entry in the
698/// SLocEntry tables that contains the specified location.
Chris Lattner4fa23622009-01-26 00:43:02 +0000699FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
Douglas Gregor49f754f2011-04-20 00:21:03 +0000700 if (!SLocOffset)
701 return FileID::get(0);
Mike Stump11289f42009-09-09 15:08:12 +0000702
Douglas Gregor925296b2011-07-19 16:10:42 +0000703 // Now it is time to search for the correct file. See where the SLocOffset
704 // sits in the global view and consult local or loaded buffers for it.
705 if (SLocOffset < NextLocalOffset)
706 return getFileIDLocal(SLocOffset);
707 return getFileIDLoaded(SLocOffset);
708}
709
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000710/// Return the FileID for a SourceLocation with a low offset.
Douglas Gregor925296b2011-07-19 16:10:42 +0000711///
712/// This function knows that the SourceLocation is in a local buffer, not a
713/// loaded one.
714FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const {
715 assert(SLocOffset < NextLocalOffset && "Bad function choice");
716
Chris Lattner4fa23622009-01-26 00:43:02 +0000717 // After the first and second level caches, I see two common sorts of
Chandler Carruth64ee7822011-07-26 05:17:23 +0000718 // behavior: 1) a lot of searched FileID's are "near" the cached file
719 // location or are "near" the cached expansion location. 2) others are just
Chris Lattner4fa23622009-01-26 00:43:02 +0000720 // completely random and may be a very long way away.
721 //
722 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
723 // then we fall back to a less cache efficient, but more scalable, binary
724 // search to find the location.
Mike Stump11289f42009-09-09 15:08:12 +0000725
Chris Lattner4fa23622009-01-26 00:43:02 +0000726 // See if this is near the file point - worst case we start scanning from the
727 // most newly created FileID.
Benjamin Kramer2999b772013-02-22 18:29:39 +0000728 const SrcMgr::SLocEntry *I;
Mike Stump11289f42009-09-09 15:08:12 +0000729
Douglas Gregor925296b2011-07-19 16:10:42 +0000730 if (LastFileIDLookup.ID < 0 ||
731 LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
Chris Lattner4fa23622009-01-26 00:43:02 +0000732 // Neither loc prunes our search.
Douglas Gregor925296b2011-07-19 16:10:42 +0000733 I = LocalSLocEntryTable.end();
Chris Lattner4fa23622009-01-26 00:43:02 +0000734 } else {
735 // Perhaps it is near the file point.
Douglas Gregor925296b2011-07-19 16:10:42 +0000736 I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
Chris Lattner4fa23622009-01-26 00:43:02 +0000737 }
738
739 // Find the FileID that contains this. "I" is an iterator that points to a
740 // FileID whose offset is known to be larger than SLocOffset.
741 unsigned NumProbes = 0;
Eugene Zelenko918e0ca2017-11-03 22:35:27 +0000742 while (true) {
Chris Lattner4fa23622009-01-26 00:43:02 +0000743 --I;
744 if (I->getOffset() <= SLocOffset) {
Douglas Gregor925296b2011-07-19 16:10:42 +0000745 FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
Douglas Gregor258ae542009-04-27 06:38:32 +0000746
Chandler Carruth64ee7822011-07-26 05:17:23 +0000747 // If this isn't an expansion, remember it. We have good locality across
748 // FileID lookups.
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000749 if (!I->isExpansion())
Chris Lattner4fa23622009-01-26 00:43:02 +0000750 LastFileIDLookup = Res;
751 NumLinearScans += NumProbes+1;
752 return Res;
753 }
754 if (++NumProbes == 8)
755 break;
756 }
Mike Stump11289f42009-09-09 15:08:12 +0000757
Chris Lattner4fa23622009-01-26 00:43:02 +0000758 // Convert "I" back into an index. We know that it is an entry whose index is
759 // larger than the offset we are looking for.
Douglas Gregor925296b2011-07-19 16:10:42 +0000760 unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
Chris Lattner4fa23622009-01-26 00:43:02 +0000761 // LessIndex - This is the lower bound of the range that we're searching.
762 // We know that the offset corresponding to the FileID is is less than
763 // SLocOffset.
764 unsigned LessIndex = 0;
765 NumProbes = 0;
Eugene Zelenko918e0ca2017-11-03 22:35:27 +0000766 while (true) {
Douglas Gregor49f754f2011-04-20 00:21:03 +0000767 bool Invalid = false;
Chris Lattner4fa23622009-01-26 00:43:02 +0000768 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregor925296b2011-07-19 16:10:42 +0000769 unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
Douglas Gregor49f754f2011-04-20 00:21:03 +0000770 if (Invalid)
771 return FileID::get(0);
Fangrui Song6907ce22018-07-30 19:24:48 +0000772
Chris Lattner4fa23622009-01-26 00:43:02 +0000773 ++NumProbes;
Mike Stump11289f42009-09-09 15:08:12 +0000774
Chris Lattner4fa23622009-01-26 00:43:02 +0000775 // If the offset of the midpoint is too large, chop the high side of the
776 // range to the midpoint.
777 if (MidOffset > SLocOffset) {
778 GreaterIndex = MiddleIndex;
779 continue;
780 }
Mike Stump11289f42009-09-09 15:08:12 +0000781
Chris Lattner4fa23622009-01-26 00:43:02 +0000782 // If the middle index contains the value, succeed and return.
Douglas Gregor925296b2011-07-19 16:10:42 +0000783 // FIXME: This could be made faster by using a function that's aware of
784 // being in the local area.
Chris Lattner4fa23622009-01-26 00:43:02 +0000785 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
Chris Lattner4fa23622009-01-26 00:43:02 +0000786 FileID Res = FileID::get(MiddleIndex);
787
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000788 // If this isn't a macro expansion, remember it. We have good locality
Chris Lattner4fa23622009-01-26 00:43:02 +0000789 // across FileID lookups.
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000790 if (!LocalSLocEntryTable[MiddleIndex].isExpansion())
Chris Lattner4fa23622009-01-26 00:43:02 +0000791 LastFileIDLookup = Res;
792 NumBinaryProbes += NumProbes;
793 return Res;
794 }
Mike Stump11289f42009-09-09 15:08:12 +0000795
Chris Lattner4fa23622009-01-26 00:43:02 +0000796 // Otherwise, move the low-side up to the middle index.
797 LessIndex = MiddleIndex;
798 }
799}
800
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000801/// Return the FileID for a SourceLocation with a high offset.
Douglas Gregor925296b2011-07-19 16:10:42 +0000802///
803/// This function knows that the SourceLocation is in a loaded buffer, not a
804/// local one.
805FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
Argyrios Kyrtzidis25029d42011-10-03 23:43:01 +0000806 // Sanity checking, otherwise a bug may lead to hanging in release build.
Argyrios Kyrtzidis8edffaa2011-10-25 00:29:44 +0000807 if (SLocOffset < CurrentLoadedOffset) {
808 assert(0 && "Invalid SLocOffset or bad function choice");
Argyrios Kyrtzidis25029d42011-10-03 23:43:01 +0000809 return FileID();
Argyrios Kyrtzidis8edffaa2011-10-25 00:29:44 +0000810 }
Argyrios Kyrtzidis25029d42011-10-03 23:43:01 +0000811
Douglas Gregor925296b2011-07-19 16:10:42 +0000812 // Essentially the same as the local case, but the loaded array is sorted
813 // in the other direction.
814
815 // First do a linear scan from the last lookup position, if possible.
816 unsigned I;
817 int LastID = LastFileIDLookup.ID;
818 if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
819 I = 0;
820 else
821 I = (-LastID - 2) + 1;
822
823 unsigned NumProbes;
824 for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
825 // Make sure the entry is loaded!
826 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
827 if (E.getOffset() <= SLocOffset) {
828 FileID Res = FileID::get(-int(I) - 2);
829
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000830 if (!E.isExpansion())
Douglas Gregor925296b2011-07-19 16:10:42 +0000831 LastFileIDLookup = Res;
832 NumLinearScans += NumProbes + 1;
833 return Res;
834 }
835 }
836
837 // Linear scan failed. Do the binary search. Note the reverse sorting of the
838 // table: GreaterIndex is the one where the offset is greater, which is
839 // actually a lower index!
840 unsigned GreaterIndex = I;
841 unsigned LessIndex = LoadedSLocEntryTable.size();
842 NumProbes = 0;
Eugene Zelenko918e0ca2017-11-03 22:35:27 +0000843 while (true) {
Douglas Gregor925296b2011-07-19 16:10:42 +0000844 ++NumProbes;
845 unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
846 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
Argyrios Kyrtzidis7dc4f332013-03-01 03:26:00 +0000847 if (E.getOffset() == 0)
848 return FileID(); // invalid entry.
Douglas Gregor925296b2011-07-19 16:10:42 +0000849
850 ++NumProbes;
851
852 if (E.getOffset() > SLocOffset) {
Argyrios Kyrtzidis7dc4f332013-03-01 03:26:00 +0000853 // Sanity checking, otherwise a bug may lead to hanging in release build.
854 if (GreaterIndex == MiddleIndex) {
855 assert(0 && "binary search missed the entry");
856 return FileID();
857 }
Douglas Gregor925296b2011-07-19 16:10:42 +0000858 GreaterIndex = MiddleIndex;
859 continue;
860 }
861
862 if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
863 FileID Res = FileID::get(-int(MiddleIndex) - 2);
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000864 if (!E.isExpansion())
Douglas Gregor925296b2011-07-19 16:10:42 +0000865 LastFileIDLookup = Res;
866 NumBinaryProbes += NumProbes;
867 return Res;
868 }
869
Argyrios Kyrtzidis1ca73442013-03-01 03:43:33 +0000870 // Sanity checking, otherwise a bug may lead to hanging in release build.
871 if (LessIndex == MiddleIndex) {
872 assert(0 && "binary search missed the entry");
873 return FileID();
874 }
Douglas Gregor925296b2011-07-19 16:10:42 +0000875 LessIndex = MiddleIndex;
876 }
877}
878
Chris Lattner659ac5f2009-01-26 20:04:19 +0000879SourceLocation SourceManager::
Chandler Carruthc84d7692011-07-25 20:52:26 +0000880getExpansionLocSlowCase(SourceLocation Loc) const {
Chris Lattner659ac5f2009-01-26 20:04:19 +0000881 do {
Chris Lattner5647d312010-02-12 19:31:35 +0000882 // Note: If Loc indicates an offset into a token that came from a macro
883 // expansion (e.g. the 5th character of the token) we do not want to add
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000884 // this offset when going to the expansion location. The expansion
Chris Lattner5647d312010-02-12 19:31:35 +0000885 // location is the macro invocation, which the offset has nothing to do
886 // with. This is unlike when we get the spelling loc, because the offset
887 // directly correspond to the token whose spelling we're inspecting.
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000888 Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
Chris Lattner659ac5f2009-01-26 20:04:19 +0000889 } while (!Loc.isFileID());
890
891 return Loc;
892}
893
894SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
895 do {
896 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000897 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000898 Loc = Loc.getLocWithOffset(LocInfo.second);
Chris Lattner659ac5f2009-01-26 20:04:19 +0000899 } while (!Loc.isFileID());
900 return Loc;
901}
902
Argyrios Kyrtzidis7f6b0292011-10-12 07:07:40 +0000903SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
904 do {
905 if (isMacroArgExpansion(Loc))
906 Loc = getImmediateSpellingLoc(Loc);
907 else
Richard Smithb5f81712018-04-30 05:25:48 +0000908 Loc = getImmediateExpansionRange(Loc).getBegin();
Argyrios Kyrtzidis7f6b0292011-10-12 07:07:40 +0000909 } while (!Loc.isFileID());
910 return Loc;
911}
912
Chris Lattner659ac5f2009-01-26 20:04:19 +0000913
Chris Lattner4fa23622009-01-26 00:43:02 +0000914std::pair<FileID, unsigned>
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000915SourceManager::getDecomposedExpansionLocSlowCase(
Argyrios Kyrtzidisc8f7e212011-07-07 03:40:27 +0000916 const SrcMgr::SLocEntry *E) const {
Chandler Carruth64ee7822011-07-26 05:17:23 +0000917 // If this is an expansion record, walk through all the expansion points.
Chris Lattner4fa23622009-01-26 00:43:02 +0000918 FileID FID;
919 SourceLocation Loc;
Argyrios Kyrtzidisc8f7e212011-07-07 03:40:27 +0000920 unsigned Offset;
Chris Lattner4fa23622009-01-26 00:43:02 +0000921 do {
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000922 Loc = E->getExpansion().getExpansionLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000923
Chris Lattner4fa23622009-01-26 00:43:02 +0000924 FID = getFileID(Loc);
925 E = &getSLocEntry(FID);
Argyrios Kyrtzidisc8f7e212011-07-07 03:40:27 +0000926 Offset = Loc.getOffset()-E->getOffset();
Chris Lattner31af4e02009-01-26 19:41:58 +0000927 } while (!Loc.isFileID());
Mike Stump11289f42009-09-09 15:08:12 +0000928
Chris Lattner4fa23622009-01-26 00:43:02 +0000929 return std::make_pair(FID, Offset);
930}
931
932std::pair<FileID, unsigned>
933SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
934 unsigned Offset) const {
Chandler Carruth64ee7822011-07-26 05:17:23 +0000935 // If this is an expansion record, walk through all the expansion points.
Chris Lattner31af4e02009-01-26 19:41:58 +0000936 FileID FID;
937 SourceLocation Loc;
938 do {
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000939 Loc = E->getExpansion().getSpellingLoc();
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000940 Loc = Loc.getLocWithOffset(Offset);
Mike Stump11289f42009-09-09 15:08:12 +0000941
Chris Lattner31af4e02009-01-26 19:41:58 +0000942 FID = getFileID(Loc);
943 E = &getSLocEntry(FID);
Argyrios Kyrtzidis2797df62011-08-23 21:02:41 +0000944 Offset = Loc.getOffset()-E->getOffset();
Chris Lattner31af4e02009-01-26 19:41:58 +0000945 } while (!Loc.isFileID());
Mike Stump11289f42009-09-09 15:08:12 +0000946
Chris Lattner4fa23622009-01-26 00:43:02 +0000947 return std::make_pair(FID, Offset);
948}
949
Chris Lattner8ad52d52009-02-17 08:04:48 +0000950/// getImmediateSpellingLoc - Given a SourceLocation object, return the
951/// spelling location referenced by the ID. This is the first level down
952/// towards the place where the characters that make up the lexed token can be
953/// found. This should not generally be used by clients.
954SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
955 if (Loc.isFileID()) return Loc;
956 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000957 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000958 return Loc.getLocWithOffset(LocInfo.second);
Chris Lattner8ad52d52009-02-17 08:04:48 +0000959}
960
Chandler Carruth64ee7822011-07-26 05:17:23 +0000961/// getImmediateExpansionRange - Loc is required to be an expansion location.
962/// Return the start/end of the expansion information.
Richard Smithb5f81712018-04-30 05:25:48 +0000963CharSourceRange
Chandler Carruthca757582011-07-25 20:52:21 +0000964SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
Chandler Carruth64ee7822011-07-26 05:17:23 +0000965 assert(Loc.isMacroID() && "Not a macro expansion loc!");
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000966 const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000967 return Expansion.getExpansionLocRange();
Chris Lattner9dc9c202009-02-15 20:52:18 +0000968}
969
George Karpenkov441e8fd2018-02-09 23:30:07 +0000970SourceLocation SourceManager::getTopMacroCallerLoc(SourceLocation Loc) const {
971 while (isMacroArgExpansion(Loc))
972 Loc = getImmediateSpellingLoc(Loc);
973 return Loc;
974}
975
Chandler Carruth6d28d7f2011-07-25 16:56:02 +0000976/// getExpansionRange - Given a SourceLocation object, return the range of
977/// tokens covered by the expansion in the ultimate file.
Richard Smithb5f81712018-04-30 05:25:48 +0000978CharSourceRange SourceManager::getExpansionRange(SourceLocation Loc) const {
979 if (Loc.isFileID())
980 return CharSourceRange(SourceRange(Loc, Loc), true);
Mike Stump11289f42009-09-09 15:08:12 +0000981
Richard Smithb5f81712018-04-30 05:25:48 +0000982 CharSourceRange Res = getImmediateExpansionRange(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000983
Chandler Carruth64ee7822011-07-26 05:17:23 +0000984 // Fully resolve the start and end locations to their ultimate expansion
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000985 // points.
Richard Smithb5f81712018-04-30 05:25:48 +0000986 while (!Res.getBegin().isFileID())
987 Res.setBegin(getImmediateExpansionRange(Res.getBegin()).getBegin());
988 while (!Res.getEnd().isFileID()) {
989 CharSourceRange EndRange = getImmediateExpansionRange(Res.getEnd());
990 Res.setEnd(EndRange.getEnd());
991 Res.setTokenRange(EndRange.isTokenRange());
992 }
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000993 return Res;
994}
995
Richard Trieuc3096242015-09-24 01:21:01 +0000996bool SourceManager::isMacroArgExpansion(SourceLocation Loc,
997 SourceLocation *StartLoc) const {
Chandler Carruth402bb382011-07-07 23:56:36 +0000998 if (!Loc.isMacroID()) return false;
999
1000 FileID FID = getFileID(Loc);
Matt Beaumont-Gayb1e71a72013-01-12 00:54:16 +00001001 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
Richard Trieuc3096242015-09-24 01:21:01 +00001002 if (!Expansion.isMacroArgExpansion()) return false;
1003
1004 if (StartLoc)
1005 *StartLoc = Expansion.getExpansionLocStart();
1006 return true;
Chandler Carruth402bb382011-07-07 23:56:36 +00001007}
Chris Lattner9dc9c202009-02-15 20:52:18 +00001008
Matt Beaumont-Gayb1e71a72013-01-12 00:54:16 +00001009bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const {
1010 if (!Loc.isMacroID()) return false;
1011
1012 FileID FID = getFileID(Loc);
1013 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1014 return Expansion.isMacroBodyExpansion();
1015}
1016
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +00001017bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
1018 SourceLocation *MacroBegin) const {
1019 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1020
1021 std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);
1022 if (DecompLoc.second > 0)
1023 return false; // Does not point at the start of expansion range.
1024
1025 bool Invalid = false;
1026 const SrcMgr::ExpansionInfo &ExpInfo =
1027 getSLocEntry(DecompLoc.first, &Invalid).getExpansion();
1028 if (Invalid)
1029 return false;
1030 SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();
1031
1032 if (ExpInfo.isMacroArgExpansion()) {
1033 // For macro argument expansions, check if the previous FileID is part of
1034 // the same argument expansion, in which case this Loc is not at the
1035 // beginning of the expansion.
1036 FileID PrevFID = getPreviousFileID(DecompLoc.first);
1037 if (!PrevFID.isInvalid()) {
1038 const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);
1039 if (Invalid)
1040 return false;
1041 if (PrevEntry.isExpansion() &&
1042 PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)
1043 return false;
1044 }
1045 }
1046
1047 if (MacroBegin)
1048 *MacroBegin = ExpLoc;
1049 return true;
1050}
1051
1052bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
1053 SourceLocation *MacroEnd) const {
1054 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1055
1056 FileID FID = getFileID(Loc);
1057 SourceLocation NextLoc = Loc.getLocWithOffset(1);
1058 if (isInFileID(NextLoc, FID))
1059 return false; // Does not point at the end of expansion range.
1060
1061 bool Invalid = false;
1062 const SrcMgr::ExpansionInfo &ExpInfo =
1063 getSLocEntry(FID, &Invalid).getExpansion();
1064 if (Invalid)
1065 return false;
1066
1067 if (ExpInfo.isMacroArgExpansion()) {
1068 // For macro argument expansions, check if the next FileID is part of the
1069 // same argument expansion, in which case this Loc is not at the end of the
1070 // expansion.
1071 FileID NextFID = getNextFileID(FID);
1072 if (!NextFID.isInvalid()) {
1073 const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);
1074 if (Invalid)
1075 return false;
1076 if (NextEntry.isExpansion() &&
1077 NextEntry.getExpansion().getExpansionLocStart() ==
1078 ExpInfo.getExpansionLocStart())
1079 return false;
1080 }
1081 }
1082
1083 if (MacroEnd)
1084 *MacroEnd = ExpInfo.getExpansionLocEnd();
1085 return true;
1086}
1087
Chris Lattner4fa23622009-01-26 00:43:02 +00001088//===----------------------------------------------------------------------===//
1089// Queries about the code at a SourceLocation.
1090//===----------------------------------------------------------------------===//
Chris Lattner30709b032006-06-21 03:01:55 +00001091
Chris Lattnerd01e2912006-06-18 16:22:51 +00001092/// getCharacterData - Return a pointer to the start of the specified location
Chris Lattner739e7392007-04-29 07:12:06 +00001093/// in the appropriate MemoryBuffer.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001094const char *SourceManager::getCharacterData(SourceLocation SL,
1095 bool *Invalid) const {
Chris Lattnerd3a15f72006-07-04 23:01:03 +00001096 // Note that this is a hot function in the getSpelling() path, which is
1097 // heavily used by -E mode.
Chris Lattner4fa23622009-01-26 00:43:02 +00001098 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump11289f42009-09-09 15:08:12 +00001099
Ted Kremenek12c2af42009-01-06 01:55:26 +00001100 // Note that calling 'getBuffer()' may lazily page in a source file.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001101 bool CharDataInvalid = false;
Douglas Gregor49f754f2011-04-20 00:21:03 +00001102 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
1103 if (CharDataInvalid || !Entry.isFile()) {
1104 if (Invalid)
1105 *Invalid = true;
Fangrui Song6907ce22018-07-30 19:24:48 +00001106
Douglas Gregor49f754f2011-04-20 00:21:03 +00001107 return "<<<<INVALID BUFFER>>>>";
1108 }
David Blaikie66cc07b2014-06-27 17:40:03 +00001109 llvm::MemoryBuffer *Buffer = Entry.getFile().getContentCache()->getBuffer(
1110 Diag, *this, SourceLocation(), &CharDataInvalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001111 if (Invalid)
1112 *Invalid = CharDataInvalid;
1113 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
Chris Lattnerd01e2912006-06-18 16:22:51 +00001114}
1115
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001116/// getColumnNumber - Return the column # for the specified file position.
Chris Lattnere4ad4172009-02-04 00:55:58 +00001117/// this is significantly cheaper to compute than the line number.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001118unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
1119 bool *Invalid) const {
1120 bool MyInvalid = false;
David Blaikie66cc07b2014-06-27 17:40:03 +00001121 llvm::MemoryBuffer *MemBuf = getBuffer(FID, &MyInvalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001122 if (Invalid)
1123 *Invalid = MyInvalid;
1124
1125 if (MyInvalid)
1126 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00001127
Jordan Rose8d63d5b2012-06-19 03:09:38 +00001128 // It is okay to request a position just past the end of the buffer.
1129 if (FilePos > MemBuf->getBufferSize()) {
Argyrios Kyrtzidis6c8d29f2011-12-10 00:30:38 +00001130 if (Invalid)
Jordan Rose8d63d5b2012-06-19 03:09:38 +00001131 *Invalid = true;
Argyrios Kyrtzidis6c8d29f2011-12-10 00:30:38 +00001132 return 1;
1133 }
1134
Chih-Hung Hsieha0b99e42017-04-06 18:36:50 +00001135 const char *Buf = MemBuf->getBufferStart();
Craig Topper5e79ee02012-10-19 04:40:38 +00001136 // See if we just calculated the line number for this FilePos and can use
1137 // that to lookup the start of the line instead of searching for it.
1138 if (LastLineNoFileIDQuery == FID &&
Craig Topperf1186c52014-05-08 06:41:40 +00001139 LastLineNoContentCache->SourceLineCache != nullptr &&
Craig Topperf3b839b2012-12-16 05:58:32 +00001140 LastLineNoResult < LastLineNoContentCache->NumLines) {
Craig Topper5e79ee02012-10-19 04:40:38 +00001141 unsigned *SourceLineCache = LastLineNoContentCache->SourceLineCache;
1142 unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
1143 unsigned LineEnd = SourceLineCache[LastLineNoResult];
Chih-Hung Hsieha0b99e42017-04-06 18:36:50 +00001144 if (FilePos >= LineStart && FilePos < LineEnd) {
1145 // LineEnd is the LineStart of the next line.
1146 // A line ends with separator LF or CR+LF on Windows.
1147 // FilePos might point to the last separator,
1148 // but we need a column number at most 1 + the last column.
1149 if (FilePos + 1 == LineEnd && FilePos > LineStart) {
1150 if (Buf[FilePos - 1] == '\r' || Buf[FilePos - 1] == '\n')
1151 --FilePos;
1152 }
Craig Topper5e79ee02012-10-19 04:40:38 +00001153 return FilePos - LineStart + 1;
Chih-Hung Hsieha0b99e42017-04-06 18:36:50 +00001154 }
Craig Topper5e79ee02012-10-19 04:40:38 +00001155 }
1156
Chris Lattner22eb9722006-06-18 05:43:12 +00001157 unsigned LineStart = FilePos;
1158 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
1159 --LineStart;
1160 return FilePos-LineStart+1;
1161}
1162
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001163// isInvalid - Return the result of calling loc.isInvalid(), and
1164// if Invalid is not null, set its value to same.
Richard Smith41e66292016-04-28 18:26:32 +00001165template<typename LocType>
1166static bool isInvalid(LocType Loc, bool *Invalid) {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001167 bool MyInvalid = Loc.isInvalid();
1168 if (Invalid)
1169 *Invalid = MyInvalid;
1170 return MyInvalid;
1171}
1172
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001173unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
1174 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001175 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattnere4ad4172009-02-04 00:55:58 +00001176 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001177 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattnere4ad4172009-02-04 00:55:58 +00001178}
1179
Chandler Carruth42f35f92011-07-25 20:57:57 +00001180unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
1181 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001182 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001183 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001184 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattnere4ad4172009-02-04 00:55:58 +00001185}
1186
Chandler Carruth1aef0c52011-02-23 00:47:48 +00001187unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
1188 bool *Invalid) const {
Richard Smith41e66292016-04-28 18:26:32 +00001189 PresumedLoc PLoc = getPresumedLoc(Loc);
1190 if (isInvalid(PLoc, Invalid)) return 0;
1191 return PLoc.getColumn();
Chandler Carruth1aef0c52011-02-23 00:47:48 +00001192}
1193
Benjamin Kramer543036a2012-04-06 20:49:55 +00001194#ifdef __SSE2__
1195#include <emmintrin.h>
1196#endif
1197
Chandler Carruthc3ce5842010-10-23 08:44:57 +00001198static LLVM_ATTRIBUTE_NOINLINE void
David Blaikie9c902b52011-09-25 23:23:43 +00001199ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001200 llvm::BumpPtrAllocator &Alloc,
1201 const SourceManager &SM, bool &Invalid);
David Blaikie9c902b52011-09-25 23:23:43 +00001202static void ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001203 llvm::BumpPtrAllocator &Alloc,
1204 const SourceManager &SM, bool &Invalid) {
Ted Kremenek12c2af42009-01-06 01:55:26 +00001205 // Note that calling 'getBuffer()' may lazily page in the file.
David Blaikie66cc07b2014-06-27 17:40:03 +00001206 MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(), &Invalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001207 if (Invalid)
1208 return;
Mike Stump11289f42009-09-09 15:08:12 +00001209
Chris Lattner8996fff2007-07-24 05:57:19 +00001210 // Find the file offsets of all of the *physical* source lines. This does
1211 // not look at trigraphs, escaped newlines, or anything else tricky.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001212 SmallVector<unsigned, 256> LineOffsets;
Mike Stump11289f42009-09-09 15:08:12 +00001213
Chris Lattner8996fff2007-07-24 05:57:19 +00001214 // Line #1 starts at char 0.
1215 LineOffsets.push_back(0);
Mike Stump11289f42009-09-09 15:08:12 +00001216
Chris Lattner8996fff2007-07-24 05:57:19 +00001217 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
1218 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
Fangrui Songd906e732018-12-10 18:10:35 +00001219 unsigned I = 0;
Eugene Zelenko918e0ca2017-11-03 22:35:27 +00001220 while (true) {
Chris Lattner8996fff2007-07-24 05:57:19 +00001221 // Skip over the contents of the line.
Fangrui Songd906e732018-12-10 18:10:35 +00001222 while (Buf[I] != '\n' && Buf[I] != '\r' && Buf[I] != '\0')
1223 ++I;
Benjamin Kramer543036a2012-04-06 20:49:55 +00001224
Fangrui Songd906e732018-12-10 18:10:35 +00001225 if (Buf[I] == '\n' || Buf[I] == '\r') {
1226 // If this is \r\n, skip both characters.
1227 if (Buf[I] == '\r' && Buf[I+1] == '\n')
1228 ++I;
1229 ++I;
1230 LineOffsets.push_back(I);
Chris Lattner8996fff2007-07-24 05:57:19 +00001231 } else {
Fangrui Songd906e732018-12-10 18:10:35 +00001232 // Otherwise, this is a NUL. If end of file, exit.
1233 if (Buf+I == End) break;
1234 ++I;
Chris Lattner8996fff2007-07-24 05:57:19 +00001235 }
1236 }
Mike Stump11289f42009-09-09 15:08:12 +00001237
Chris Lattner8996fff2007-07-24 05:57:19 +00001238 // Copy the offsets into the FileInfo structure.
1239 FI->NumLines = LineOffsets.size();
Chris Lattnerc8233df2009-02-03 07:30:45 +00001240 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner8996fff2007-07-24 05:57:19 +00001241 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
1242}
Chris Lattner9a13bde2006-06-21 04:57:09 +00001243
Chris Lattner53e384f2009-01-16 07:00:02 +00001244/// getLineNumber - Given a SourceLocation, return the spelling line number
Chris Lattner22eb9722006-06-18 05:43:12 +00001245/// for the position indicated. This requires building and caching a table of
Chris Lattner739e7392007-04-29 07:12:06 +00001246/// line offsets for the MemoryBuffer, so this is not cheap: use only when
Chris Lattner22eb9722006-06-18 05:43:12 +00001247/// about to emit a diagnostic.
Fangrui Song6907ce22018-07-30 19:24:48 +00001248unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001249 bool *Invalid) const {
Argyrios Kyrtzidisf15eac12011-05-17 22:09:53 +00001250 if (FID.isInvalid()) {
1251 if (Invalid)
1252 *Invalid = true;
1253 return 1;
1254 }
1255
Chris Lattnerd32480d2009-01-17 06:22:33 +00001256 ContentCache *Content;
Chris Lattner88ea93e2009-02-04 01:06:56 +00001257 if (LastLineNoFileIDQuery == FID)
Ted Kremenekc08bca62007-10-30 21:08:08 +00001258 Content = LastLineNoContentCache;
Douglas Gregor49f754f2011-04-20 00:21:03 +00001259 else {
1260 bool MyInvalid = false;
1261 const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1262 if (MyInvalid || !Entry.isFile()) {
1263 if (Invalid)
1264 *Invalid = true;
1265 return 1;
1266 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001267
Douglas Gregor49f754f2011-04-20 00:21:03 +00001268 Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
1269 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001270
Chris Lattner22eb9722006-06-18 05:43:12 +00001271 // If this is the first use of line information for this buffer, compute the
Chris Lattner8996fff2007-07-24 05:57:19 +00001272 /// SourceLineCache for it on demand.
Craig Topperf1186c52014-05-08 06:41:40 +00001273 if (!Content->SourceLineCache) {
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001274 bool MyInvalid = false;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001275 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001276 if (Invalid)
1277 *Invalid = MyInvalid;
1278 if (MyInvalid)
1279 return 1;
1280 } else if (Invalid)
1281 *Invalid = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001282
1283 // Okay, we know we have a line number table. Do a binary search to find the
1284 // line number that this character position lands on.
Ted Kremenekc08bca62007-10-30 21:08:08 +00001285 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner8996fff2007-07-24 05:57:19 +00001286 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenekc08bca62007-10-30 21:08:08 +00001287 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump11289f42009-09-09 15:08:12 +00001288
Chris Lattner88ea93e2009-02-04 01:06:56 +00001289 unsigned QueriedFilePos = FilePos+1;
Chris Lattner8996fff2007-07-24 05:57:19 +00001290
Daniel Dunbar70f924df82009-05-18 17:30:52 +00001291 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump11289f42009-09-09 15:08:12 +00001292 // complicated as it is, binary search isn't that slow.
Daniel Dunbar70f924df82009-05-18 17:30:52 +00001293 //
1294 // If it is worth being optimized, then in my opinion it could be more
1295 // performant, simpler, and more obviously correct by just "galloping" outward
1296 // from the queried file position. In fact, this could be incorporated into a
1297 // generic algorithm such as lower_bound_with_hint.
1298 //
1299 // If someone gives me a test case where this matters, and I will do it! - DWD
1300
Chris Lattner8996fff2007-07-24 05:57:19 +00001301 // If the previous query was to the same file, we know both the file pos from
1302 // that query and the line number returned. This allows us to narrow the
1303 // search space from the entire file to something near the match.
Chris Lattner88ea93e2009-02-04 01:06:56 +00001304 if (LastLineNoFileIDQuery == FID) {
Chris Lattner8996fff2007-07-24 05:57:19 +00001305 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar70f924df82009-05-18 17:30:52 +00001306 // FIXME: Potential overflow?
Chris Lattner8996fff2007-07-24 05:57:19 +00001307 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump11289f42009-09-09 15:08:12 +00001308
Chris Lattner8996fff2007-07-24 05:57:19 +00001309 // The query is likely to be nearby the previous one. Here we check to
1310 // see if it is within 5, 10 or 20 lines. It can be far away in cases
1311 // where big comment blocks and vertical whitespace eat up lines but
1312 // contribute no tokens.
1313 if (SourceLineCache+5 < SourceLineCacheEnd) {
1314 if (SourceLineCache[5] > QueriedFilePos)
1315 SourceLineCacheEnd = SourceLineCache+5;
1316 else if (SourceLineCache+10 < SourceLineCacheEnd) {
1317 if (SourceLineCache[10] > QueriedFilePos)
1318 SourceLineCacheEnd = SourceLineCache+10;
1319 else if (SourceLineCache+20 < SourceLineCacheEnd) {
1320 if (SourceLineCache[20] > QueriedFilePos)
1321 SourceLineCacheEnd = SourceLineCache+20;
1322 }
1323 }
1324 }
1325 } else {
Daniel Dunbar70f924df82009-05-18 17:30:52 +00001326 if (LastLineNoResult < Content->NumLines)
1327 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner8996fff2007-07-24 05:57:19 +00001328 }
1329 }
Mike Stump11289f42009-09-09 15:08:12 +00001330
Chris Lattner830a77f2007-07-24 06:43:46 +00001331 unsigned *Pos
1332 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner8996fff2007-07-24 05:57:19 +00001333 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump11289f42009-09-09 15:08:12 +00001334
Chris Lattner88ea93e2009-02-04 01:06:56 +00001335 LastLineNoFileIDQuery = FID;
Ted Kremenekc08bca62007-10-30 21:08:08 +00001336 LastLineNoContentCache = Content;
Chris Lattner8996fff2007-07-24 05:57:19 +00001337 LastLineNoFilePos = QueriedFilePos;
1338 LastLineNoResult = LineNo;
1339 return LineNo;
Chris Lattner22eb9722006-06-18 05:43:12 +00001340}
1341
Fangrui Song6907ce22018-07-30 19:24:48 +00001342unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
Chandler Carruth1aef0c52011-02-23 00:47:48 +00001343 bool *Invalid) const {
1344 if (isInvalid(Loc, Invalid)) return 0;
1345 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1346 return getLineNumber(LocInfo.first, LocInfo.second);
1347}
Chandler Carruthd48db212011-07-25 21:09:52 +00001348unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
1349 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001350 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001351 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Chris Lattner88ea93e2009-02-04 01:06:56 +00001352 return getLineNumber(LocInfo.first, LocInfo.second);
1353}
Chandler Carruth1aef0c52011-02-23 00:47:48 +00001354unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001355 bool *Invalid) const {
Richard Smith9c527672016-04-28 19:54:51 +00001356 PresumedLoc PLoc = getPresumedLoc(Loc);
1357 if (isInvalid(PLoc, Invalid)) return 0;
1358 return PLoc.getLine();
Chris Lattner88ea93e2009-02-04 01:06:56 +00001359}
1360
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001361/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump11289f42009-09-09 15:08:12 +00001362/// source location, indicating whether this is a normal file, a system
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001363/// header, or an "implicit extern C" system header.
1364///
1365/// This state can be modified with flags on GNU linemarker directives like:
1366/// # 4 "foo.h" 3
1367/// which changes all source locations in the current file after that to be
1368/// considered to be from a system header.
Mike Stump11289f42009-09-09 15:08:12 +00001369SrcMgr::CharacteristicKind
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001370SourceManager::getFileCharacteristic(SourceLocation Loc) const {
Yaron Keren8b563662015-10-03 10:46:20 +00001371 assert(Loc.isValid() && "Can't get file characteristic of invalid loc!");
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001372 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregor49f754f2011-04-20 00:21:03 +00001373 bool Invalid = false;
1374 const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
1375 if (Invalid || !SEntry.isFile())
1376 return C_User;
Fangrui Song6907ce22018-07-30 19:24:48 +00001377
Douglas Gregor49f754f2011-04-20 00:21:03 +00001378 const SrcMgr::FileInfo &FI = SEntry.getFile();
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001379
1380 // If there are no #line directives in this file, just return the whole-file
1381 // state.
1382 if (!FI.hasLineDirectives())
1383 return FI.getFileCharacteristic();
Mike Stump11289f42009-09-09 15:08:12 +00001384
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001385 assert(LineTable && "Can't have linetable entries without a LineTable!");
1386 // See if there is a #line directive before the location.
1387 const LineEntry *Entry =
Douglas Gregor02c2dbf2012-06-08 16:40:28 +00001388 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
Mike Stump11289f42009-09-09 15:08:12 +00001389
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001390 // If this is before the first line marker, use the file characteristic.
1391 if (!Entry)
1392 return FI.getFileCharacteristic();
1393
1394 return Entry->FileKind;
1395}
1396
Chris Lattnera6f037c2009-02-17 08:39:06 +00001397/// Return the filename or buffer identifier of the buffer the location is in.
James Dennett87a2acf2012-06-17 03:22:59 +00001398/// Note that this name does not respect \#line directives. Use getPresumedLoc
Chris Lattnera6f037c2009-02-17 08:39:06 +00001399/// for normal clients.
Mehdi Amini99d1b292016-10-01 16:38:28 +00001400StringRef SourceManager::getBufferName(SourceLocation Loc,
1401 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001402 if (isInvalid(Loc, Invalid)) return "<invalid loc>";
Mike Stump11289f42009-09-09 15:08:12 +00001403
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001404 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
Chris Lattnera6f037c2009-02-17 08:39:06 +00001405}
1406
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001407/// getPresumedLoc - This method returns the "presumed" location of a
James Dennett87a2acf2012-06-17 03:22:59 +00001408/// SourceLocation specifies. A "presumed location" can be modified by \#line
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001409/// or GNU line marker directives. This provides a view on the data that a
1410/// user should see in diagnostics, for example.
1411///
Chandler Carruth64ee7822011-07-26 05:17:23 +00001412/// Note that a presumed location is always given as the expansion point of an
1413/// expansion location, not at the spelling location.
Richard Smith0b50cb72012-11-14 23:55:25 +00001414PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc,
1415 bool UseLineDirectives) const {
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001416 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001417
Chandler Carruth64ee7822011-07-26 05:17:23 +00001418 // Presumed locations are always for expansion points.
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001419 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +00001420
Douglas Gregor49f754f2011-04-20 00:21:03 +00001421 bool Invalid = false;
1422 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1423 if (Invalid || !Entry.isFile())
1424 return PresumedLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00001425
Douglas Gregor49f754f2011-04-20 00:21:03 +00001426 const SrcMgr::FileInfo &FI = Entry.getFile();
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001427 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump11289f42009-09-09 15:08:12 +00001428
Chris Lattnerd4293922009-02-04 01:55:42 +00001429 // To get the source name, first consult the FileEntry (if one exists)
1430 // before the MemBuffer as this will avoid unnecessarily paging in the
1431 // MemBuffer.
Mehdi Amini99d1b292016-10-01 16:38:28 +00001432 StringRef Filename;
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001433 if (C->OrigEntry)
1434 Filename = C->OrigEntry->getName();
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001435 else
1436 Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
Douglas Gregor49f754f2011-04-20 00:21:03 +00001437
Douglas Gregor75f26d62010-11-02 00:39:22 +00001438 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1439 if (Invalid)
1440 return PresumedLoc();
1441 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1442 if (Invalid)
1443 return PresumedLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00001444
Chris Lattnerd4293922009-02-04 01:55:42 +00001445 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001446
Chris Lattnerd4293922009-02-04 01:55:42 +00001447 // If we have #line directives in this file, update and overwrite the physical
1448 // location info if appropriate.
Richard Smith0b50cb72012-11-14 23:55:25 +00001449 if (UseLineDirectives && FI.hasLineDirectives()) {
Chris Lattnerd4293922009-02-04 01:55:42 +00001450 assert(LineTable && "Can't have linetable entries without a LineTable!");
1451 // See if there is a #line directive before this. If so, get it.
1452 if (const LineEntry *Entry =
Douglas Gregor02c2dbf2012-06-08 16:40:28 +00001453 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
Chris Lattnerc1219ff2009-02-04 02:00:59 +00001454 // If the LineEntry indicates a filename, use it.
Chris Lattnerd4293922009-02-04 01:55:42 +00001455 if (Entry->FilenameID != -1)
1456 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerc1219ff2009-02-04 02:00:59 +00001457
1458 // Use the line number specified by the LineEntry. This line number may
1459 // be multiple lines down from the line entry. Add the difference in
1460 // physical line numbers from the query point and the line marker to the
1461 // total.
1462 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1463 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump11289f42009-09-09 15:08:12 +00001464
Chris Lattner20c50ba2009-02-04 02:15:40 +00001465 // Note that column numbers are not molested by line markers.
Mike Stump11289f42009-09-09 15:08:12 +00001466
Chris Lattner1c967782009-02-04 06:25:26 +00001467 // Handle virtual #include manipulation.
1468 if (Entry->IncludeOffset) {
1469 IncludeLoc = getLocForStartOfFile(LocInfo.first);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001470 IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
Chris Lattner1c967782009-02-04 06:25:26 +00001471 }
Chris Lattnerd4293922009-02-04 01:55:42 +00001472 }
1473 }
1474
Mehdi Amini99d1b292016-10-01 16:38:28 +00001475 return PresumedLoc(Filename.data(), LineNo, ColNo, IncludeLoc);
Chris Lattner4fa23622009-01-26 00:43:02 +00001476}
1477
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001478/// Returns whether the PresumedLoc for a given SourceLocation is
Benjamin Kramere7800df2013-09-27 17:12:50 +00001479/// in the main file.
1480///
1481/// This computes the "presumed" location for a SourceLocation, then checks
1482/// whether it came from a file other than the main file. This is different
1483/// from isWrittenInMainFile() because it takes line marker directives into
1484/// account.
1485bool SourceManager::isInMainFile(SourceLocation Loc) const {
1486 if (Loc.isInvalid()) return false;
1487
1488 // Presumed locations are always for expansion points.
1489 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1490
1491 bool Invalid = false;
1492 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1493 if (Invalid || !Entry.isFile())
1494 return false;
1495
1496 const SrcMgr::FileInfo &FI = Entry.getFile();
1497
1498 // Check if there is a line directive for this location.
1499 if (FI.hasLineDirectives())
1500 if (const LineEntry *Entry =
1501 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
1502 if (Entry->IncludeOffset)
1503 return false;
1504
1505 return FI.getIncludeLoc().isInvalid();
1506}
1507
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001508/// The size of the SLocEntry that \p FID represents.
Argyrios Kyrtzidis296374b52011-08-23 21:02:28 +00001509unsigned SourceManager::getFileIDSize(FileID FID) const {
1510 bool Invalid = false;
1511 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1512 if (Invalid)
1513 return 0;
1514
1515 int ID = FID.ID;
1516 unsigned NextOffset;
1517 if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
1518 NextOffset = getNextLocalOffset();
1519 else if (ID+1 == -1)
1520 NextOffset = MaxLoadedOffset;
1521 else
1522 NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
1523
1524 return NextOffset - Entry.getOffset() - 1;
1525}
1526
Chris Lattner4fa23622009-01-26 00:43:02 +00001527//===----------------------------------------------------------------------===//
1528// Other miscellaneous methods.
1529//===----------------------------------------------------------------------===//
1530
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001531/// Retrieve the inode for the given file entry, if possible.
Douglas Gregore6642762011-02-03 17:17:35 +00001532///
1533/// This routine involves a system call, and therefore should only be used
1534/// in non-performance-critical code.
Rafael Espindola073ff102013-07-29 21:26:52 +00001535static Optional<llvm::sys::fs::UniqueID>
1536getActualFileUID(const FileEntry *File) {
Douglas Gregore6642762011-02-03 17:17:35 +00001537 if (!File)
David Blaikie7a30dc52013-02-21 01:47:18 +00001538 return None;
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001539
Rafael Espindola073ff102013-07-29 21:26:52 +00001540 llvm::sys::fs::UniqueID ID;
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001541 if (llvm::sys::fs::getUniqueID(File->getName(), ID))
David Blaikie7a30dc52013-02-21 01:47:18 +00001542 return None;
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001543
1544 return ID;
Douglas Gregore6642762011-02-03 17:17:35 +00001545}
1546
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001547/// Get the source location for the given file:line:col triplet.
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001548///
1549/// If the source file is included multiple times, the source location will
Douglas Gregor925296b2011-07-19 16:10:42 +00001550/// be based upon an arbitrary inclusion.
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001551SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001552 unsigned Line,
1553 unsigned Col) const {
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001554 assert(SourceFile && "Null source file!");
1555 assert(Line && Col && "Line and column should start from 1!");
1556
Argyrios Kyrtzidis04a6e5f2011-09-27 17:22:25 +00001557 FileID FirstFID = translateFile(SourceFile);
1558 return translateLineCol(FirstFID, Line, Col);
1559}
1560
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001561/// Get the FileID for the given file.
Argyrios Kyrtzidis04a6e5f2011-09-27 17:22:25 +00001562///
1563/// If the source file is included multiple times, the FileID will be the
1564/// first inclusion.
1565FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
1566 assert(SourceFile && "Null source file!");
1567
Douglas Gregore6642762011-02-03 17:17:35 +00001568 // Find the first file ID that corresponds to the given file.
1569 FileID FirstFID;
Mike Stump11289f42009-09-09 15:08:12 +00001570
Douglas Gregore6642762011-02-03 17:17:35 +00001571 // First, check the main file ID, since it is common to look for a
1572 // location in the main file.
Rafael Espindola073ff102013-07-29 21:26:52 +00001573 Optional<llvm::sys::fs::UniqueID> SourceFileUID;
David Blaikie05785d12013-02-20 22:23:23 +00001574 Optional<StringRef> SourceFileName;
Yaron Keren8b563662015-10-03 10:46:20 +00001575 if (MainFileID.isValid()) {
Douglas Gregor49f754f2011-04-20 00:21:03 +00001576 bool Invalid = false;
1577 const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1578 if (Invalid)
Argyrios Kyrtzidis04a6e5f2011-09-27 17:22:25 +00001579 return FileID();
Fangrui Song6907ce22018-07-30 19:24:48 +00001580
Douglas Gregore6642762011-02-03 17:17:35 +00001581 if (MainSLoc.isFile()) {
1582 const ContentCache *MainContentCache
1583 = MainSLoc.getFile().getContentCache();
Douglas Gregor6a5be932011-02-11 18:08:15 +00001584 if (!MainContentCache) {
1585 // Can't do anything
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001586 } else if (MainContentCache->OrigEntry == SourceFile) {
Douglas Gregore6642762011-02-03 17:17:35 +00001587 FirstFID = MainFileID;
Douglas Gregor6a5be932011-02-11 18:08:15 +00001588 } else {
Douglas Gregore6642762011-02-03 17:17:35 +00001589 // Fall back: check whether we have the same base name and inode
1590 // as the main file.
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001591 const FileEntry *MainFile = MainContentCache->OrigEntry;
Douglas Gregore6642762011-02-03 17:17:35 +00001592 SourceFileName = llvm::sys::path::filename(SourceFile->getName());
1593 if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) {
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001594 SourceFileUID = getActualFileUID(SourceFile);
1595 if (SourceFileUID) {
Rafael Espindola073ff102013-07-29 21:26:52 +00001596 if (Optional<llvm::sys::fs::UniqueID> MainFileUID =
1597 getActualFileUID(MainFile)) {
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001598 if (*SourceFileUID == *MainFileUID) {
Douglas Gregord766be62011-02-16 19:09:24 +00001599 FirstFID = MainFileID;
1600 SourceFile = MainFile;
1601 }
1602 }
Douglas Gregore6642762011-02-03 17:17:35 +00001603 }
1604 }
1605 }
1606 }
1607 }
1608
1609 if (FirstFID.isInvalid()) {
1610 // The location we're looking for isn't in the main file; look
Douglas Gregor925296b2011-07-19 16:10:42 +00001611 // through all of the local source locations.
1612 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
Douglas Gregor49f754f2011-04-20 00:21:03 +00001613 bool Invalid = false;
Douglas Gregor925296b2011-07-19 16:10:42 +00001614 const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid);
Douglas Gregor49f754f2011-04-20 00:21:03 +00001615 if (Invalid)
Argyrios Kyrtzidis04a6e5f2011-09-27 17:22:25 +00001616 return FileID();
Fangrui Song6907ce22018-07-30 19:24:48 +00001617
1618 if (SLoc.isFile() &&
Douglas Gregore6642762011-02-03 17:17:35 +00001619 SLoc.getFile().getContentCache() &&
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001620 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
Douglas Gregore6642762011-02-03 17:17:35 +00001621 FirstFID = FileID::get(I);
1622 break;
1623 }
1624 }
Douglas Gregor925296b2011-07-19 16:10:42 +00001625 // If that still didn't help, try the modules.
1626 if (FirstFID.isInvalid()) {
1627 for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
1628 const SLocEntry &SLoc = getLoadedSLocEntry(I);
Fangrui Song6907ce22018-07-30 19:24:48 +00001629 if (SLoc.isFile() &&
Douglas Gregor925296b2011-07-19 16:10:42 +00001630 SLoc.getFile().getContentCache() &&
1631 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1632 FirstFID = FileID::get(-int(I) - 2);
1633 break;
1634 }
1635 }
1636 }
Douglas Gregore6642762011-02-03 17:17:35 +00001637 }
1638
1639 // If we haven't found what we want yet, try again, but this time stat()
Fangrui Song6907ce22018-07-30 19:24:48 +00001640 // each of the files in case the files have changed since we originally
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001641 // parsed the file.
Douglas Gregore6642762011-02-03 17:17:35 +00001642 if (FirstFID.isInvalid() &&
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001643 (SourceFileName ||
Douglas Gregore6642762011-02-03 17:17:35 +00001644 (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) &&
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001645 (SourceFileUID || (SourceFileUID = getActualFileUID(SourceFile)))) {
Douglas Gregor49f754f2011-04-20 00:21:03 +00001646 bool Invalid = false;
Douglas Gregor925296b2011-07-19 16:10:42 +00001647 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1648 FileID IFileID;
1649 IFileID.ID = I;
1650 const SLocEntry &SLoc = getSLocEntry(IFileID, &Invalid);
Douglas Gregor49f754f2011-04-20 00:21:03 +00001651 if (Invalid)
Argyrios Kyrtzidis04a6e5f2011-09-27 17:22:25 +00001652 return FileID();
Fangrui Song6907ce22018-07-30 19:24:48 +00001653
1654 if (SLoc.isFile()) {
1655 const ContentCache *FileContentCache
Douglas Gregore6642762011-02-03 17:17:35 +00001656 = SLoc.getFile().getContentCache();
Craig Topperf1186c52014-05-08 06:41:40 +00001657 const FileEntry *Entry = FileContentCache ? FileContentCache->OrigEntry
1658 : nullptr;
Fangrui Song6907ce22018-07-30 19:24:48 +00001659 if (Entry &&
Douglas Gregor6a5be932011-02-11 18:08:15 +00001660 *SourceFileName == llvm::sys::path::filename(Entry->getName())) {
Rafael Espindola073ff102013-07-29 21:26:52 +00001661 if (Optional<llvm::sys::fs::UniqueID> EntryUID =
1662 getActualFileUID(Entry)) {
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001663 if (*SourceFileUID == *EntryUID) {
Douglas Gregor6a5be932011-02-11 18:08:15 +00001664 FirstFID = FileID::get(I);
1665 SourceFile = Entry;
1666 break;
1667 }
1668 }
Douglas Gregore6642762011-02-03 17:17:35 +00001669 }
1670 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001671 }
Douglas Gregore6642762011-02-03 17:17:35 +00001672 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001673
Ted Kremenekbd1d7fa2012-10-12 22:56:33 +00001674 (void) SourceFile;
Argyrios Kyrtzidis04a6e5f2011-09-27 17:22:25 +00001675 return FirstFID;
Argyrios Kyrtzidis532c5192011-09-19 20:40:29 +00001676}
1677
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001678/// Get the source location in \arg FID for the given line:col.
Argyrios Kyrtzidis532c5192011-09-19 20:40:29 +00001679/// Returns null location if \arg FID is not a file SLocEntry.
1680SourceLocation SourceManager::translateLineCol(FileID FID,
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001681 unsigned Line,
1682 unsigned Col) const {
Aaron Ballmanef1cf832013-11-18 18:29:00 +00001683 // Lines are used as a one-based index into a zero-based array. This assert
1684 // checks for possible buffer underruns.
Gabor Horvathfe2c0ff2015-12-01 09:00:41 +00001685 assert(Line && Col && "Line and column should start from 1!");
Aaron Ballmanef1cf832013-11-18 18:29:00 +00001686
Argyrios Kyrtzidis532c5192011-09-19 20:40:29 +00001687 if (FID.isInvalid())
1688 return SourceLocation();
1689
1690 bool Invalid = false;
1691 const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1692 if (Invalid)
1693 return SourceLocation();
Alexander Kornienko6d8cf832013-07-29 22:26:10 +00001694
Argyrios Kyrtzidis532c5192011-09-19 20:40:29 +00001695 if (!Entry.isFile())
Douglas Gregore6642762011-02-03 17:17:35 +00001696 return SourceLocation();
1697
Argyrios Kyrtzidis7c2b28a2011-09-20 22:14:54 +00001698 SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
1699
Douglas Gregore6642762011-02-03 17:17:35 +00001700 if (Line == 1 && Col == 1)
Argyrios Kyrtzidis7c2b28a2011-09-20 22:14:54 +00001701 return FileLoc;
Douglas Gregore6642762011-02-03 17:17:35 +00001702
1703 ContentCache *Content
Argyrios Kyrtzidis532c5192011-09-19 20:40:29 +00001704 = const_cast<ContentCache *>(Entry.getFile().getContentCache());
Douglas Gregore6642762011-02-03 17:17:35 +00001705 if (!Content)
1706 return SourceLocation();
Alexander Kornienko6d8cf832013-07-29 22:26:10 +00001707
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001708 // If this is the first use of line information for this buffer, compute the
Douglas Gregor925296b2011-07-19 16:10:42 +00001709 // SourceLineCache for it on demand.
Craig Topperf1186c52014-05-08 06:41:40 +00001710 if (!Content->SourceLineCache) {
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001711 bool MyInvalid = false;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001712 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001713 if (MyInvalid)
1714 return SourceLocation();
1715 }
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001716
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001717 if (Line > Content->NumLines) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001718 unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001719 if (Size > 0)
1720 --Size;
Argyrios Kyrtzidis7c2b28a2011-09-20 22:14:54 +00001721 return FileLoc.getLocWithOffset(Size);
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001722 }
1723
David Blaikie66cc07b2014-06-27 17:40:03 +00001724 llvm::MemoryBuffer *Buffer = Content->getBuffer(Diag, *this);
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001725 unsigned FilePos = Content->SourceLineCache[Line - 1];
Dylan Noblesmith2a8bc152011-12-19 08:51:05 +00001726 const char *Buf = Buffer->getBufferStart() + FilePos;
1727 unsigned BufLength = Buffer->getBufferSize() - FilePos;
Argyrios Kyrtzidis7c2b28a2011-09-20 22:14:54 +00001728 if (BufLength == 0)
1729 return FileLoc.getLocWithOffset(FilePos);
1730
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001731 unsigned i = 0;
1732
1733 // Check that the given column is valid.
1734 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1735 ++i;
Alexander Kornienko6d8cf832013-07-29 22:26:10 +00001736 return FileLoc.getLocWithOffset(FilePos + i);
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001737}
1738
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001739/// Compute a map of macro argument chunks to their expanded source
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001740/// location. Chunks that are not part of a macro argument will map to an
1741/// invalid source location. e.g. if a file contains one macro argument at
1742/// offset 100 with length 10, this is how the map will be formed:
1743/// 0 -> SourceLocation()
1744/// 100 -> Expanded macro arg location
1745/// 110 -> SourceLocation()
Vedant Kumard2c6a6d2016-10-18 00:23:27 +00001746void SourceManager::computeMacroArgsCache(MacroArgsMap &MacroArgsCache,
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001747 FileID FID) const {
Yaron Keren8b563662015-10-03 10:46:20 +00001748 assert(FID.isValid());
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001749
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001750 // Initially no macro argument chunk is present.
1751 MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
1752
1753 int ID = FID.ID;
Eugene Zelenko918e0ca2017-11-03 22:35:27 +00001754 while (true) {
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001755 ++ID;
1756 // Stop if there are no more FileIDs to check.
1757 if (ID > 0) {
1758 if (unsigned(ID) >= local_sloc_entry_size())
1759 return;
1760 } else if (ID == -1) {
1761 return;
1762 }
1763
Argyrios Kyrtzidisfe683022013-06-07 17:57:59 +00001764 bool Invalid = false;
1765 const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);
1766 if (Invalid)
1767 return;
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001768 if (Entry.isFile()) {
1769 SourceLocation IncludeLoc = Entry.getFile().getIncludeLoc();
1770 if (IncludeLoc.isInvalid())
1771 continue;
1772 if (!isInFileID(IncludeLoc, FID))
1773 return; // No more files/macros that may be "contained" in this file.
1774
1775 // Skip the files/macros of the #include'd file, we only care about macros
1776 // that lexed macro arguments from our file.
1777 if (Entry.getFile().NumCreatedFIDs)
1778 ID += Entry.getFile().NumCreatedFIDs - 1/*because of next ++ID*/;
1779 continue;
1780 }
1781
Argyrios Kyrtzidise841c902011-12-21 16:56:35 +00001782 const ExpansionInfo &ExpInfo = Entry.getExpansion();
1783
1784 if (ExpInfo.getExpansionLocStart().isFileID()) {
1785 if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
1786 return; // No more files/macros that may be "contained" in this file.
1787 }
1788
1789 if (!ExpInfo.isMacroArgExpansion())
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001790 continue;
Argyrios Kyrtzidise841c902011-12-21 16:56:35 +00001791
Argyrios Kyrtzidis73ccdb92012-10-20 00:51:32 +00001792 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1793 ExpInfo.getSpellingLoc(),
1794 SourceLocation::getMacroLoc(Entry.getOffset()),
1795 getFileIDSize(FileID::get(ID)));
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001796 }
1797}
1798
Argyrios Kyrtzidis73ccdb92012-10-20 00:51:32 +00001799void SourceManager::associateFileChunkWithMacroArgExp(
1800 MacroArgsMap &MacroArgsCache,
1801 FileID FID,
1802 SourceLocation SpellLoc,
1803 SourceLocation ExpansionLoc,
1804 unsigned ExpansionLength) const {
1805 if (!SpellLoc.isFileID()) {
1806 unsigned SpellBeginOffs = SpellLoc.getOffset();
1807 unsigned SpellEndOffs = SpellBeginOffs + ExpansionLength;
1808
1809 // The spelling range for this macro argument expansion can span multiple
1810 // consecutive FileID entries. Go through each entry contained in the
1811 // spelling range and if one is itself a macro argument expansion, recurse
1812 // and associate the file chunk that it represents.
1813
1814 FileID SpellFID; // Current FileID in the spelling range.
1815 unsigned SpellRelativeOffs;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001816 std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);
Eugene Zelenko918e0ca2017-11-03 22:35:27 +00001817 while (true) {
Argyrios Kyrtzidis73ccdb92012-10-20 00:51:32 +00001818 const SLocEntry &Entry = getSLocEntry(SpellFID);
1819 unsigned SpellFIDBeginOffs = Entry.getOffset();
1820 unsigned SpellFIDSize = getFileIDSize(SpellFID);
1821 unsigned SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;
1822 const ExpansionInfo &Info = Entry.getExpansion();
1823 if (Info.isMacroArgExpansion()) {
1824 unsigned CurrSpellLength;
1825 if (SpellFIDEndOffs < SpellEndOffs)
1826 CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
1827 else
1828 CurrSpellLength = ExpansionLength;
1829 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1830 Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),
1831 ExpansionLoc, CurrSpellLength);
1832 }
1833
1834 if (SpellFIDEndOffs >= SpellEndOffs)
1835 return; // we covered all FileID entries in the spelling range.
1836
1837 // Move to the next FileID entry in the spelling range.
1838 unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
1839 ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);
1840 ExpansionLength -= advance;
1841 ++SpellFID.ID;
1842 SpellRelativeOffs = 0;
1843 }
Argyrios Kyrtzidis73ccdb92012-10-20 00:51:32 +00001844 }
1845
1846 assert(SpellLoc.isFileID());
1847
1848 unsigned BeginOffs;
1849 if (!isInFileID(SpellLoc, FID, &BeginOffs))
1850 return;
1851
1852 unsigned EndOffs = BeginOffs + ExpansionLength;
1853
1854 // Add a new chunk for this macro argument. A previous macro argument chunk
1855 // may have been lexed again, so e.g. if the map is
1856 // 0 -> SourceLocation()
1857 // 100 -> Expanded loc #1
1858 // 110 -> SourceLocation()
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001859 // and we found a new macro FileID that lexed from offset 105 with length 3,
Argyrios Kyrtzidis73ccdb92012-10-20 00:51:32 +00001860 // the new map will be:
1861 // 0 -> SourceLocation()
1862 // 100 -> Expanded loc #1
1863 // 105 -> Expanded loc #2
1864 // 108 -> Expanded loc #1
1865 // 110 -> SourceLocation()
1866 //
1867 // Since re-lexed macro chunks will always be the same size or less of
1868 // previous chunks, we only need to find where the ending of the new macro
1869 // chunk is mapped to and update the map with new begin/end mappings.
1870
1871 MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
1872 --I;
1873 SourceLocation EndOffsMappedLoc = I->second;
1874 MacroArgsCache[BeginOffs] = ExpansionLoc;
1875 MacroArgsCache[EndOffs] = EndOffsMappedLoc;
1876}
1877
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001878/// If \arg Loc points inside a function macro argument, the returned
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001879/// location will be the macro location in which the argument was expanded.
1880/// If a macro argument is used multiple times, the expanded location will
1881/// be at the first expansion of the argument.
1882/// e.g.
1883/// MY_MACRO(foo);
1884/// ^
1885/// Passing a file location pointing at 'foo', will yield a macro location
1886/// where 'foo' was expanded into.
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001887SourceLocation
1888SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001889 if (Loc.isInvalid() || !Loc.isFileID())
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001890 return Loc;
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001891
1892 FileID FID;
1893 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001894 std::tie(FID, Offset) = getDecomposedLoc(Loc);
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001895 if (FID.isInvalid())
1896 return Loc;
1897
Vedant Kumard2c6a6d2016-10-18 00:23:27 +00001898 std::unique_ptr<MacroArgsMap> &MacroArgsCache = MacroArgsCacheMap[FID];
1899 if (!MacroArgsCache) {
1900 MacroArgsCache = llvm::make_unique<MacroArgsMap>();
Vedant Kumarecc31442016-10-18 18:19:02 +00001901 computeMacroArgsCache(*MacroArgsCache, FID);
Vedant Kumard2c6a6d2016-10-18 00:23:27 +00001902 }
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001903
Argyrios Kyrtzidis4bdd6aa2011-09-26 08:01:50 +00001904 assert(!MacroArgsCache->empty());
1905 MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001906 --I;
Fangrui Song6907ce22018-07-30 19:24:48 +00001907
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001908 unsigned MacroArgBeginOffs = I->first;
1909 SourceLocation MacroArgExpandedLoc = I->second;
1910 if (MacroArgExpandedLoc.isValid())
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001911 return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001912
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001913 return Loc;
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001914}
1915
Argyrios Kyrtzidis37613a92013-04-13 01:03:57 +00001916std::pair<FileID, unsigned>
1917SourceManager::getDecomposedIncludedLoc(FileID FID) const {
Argyrios Kyrtzidis5dca8642013-05-24 22:24:04 +00001918 if (FID.isInvalid())
1919 return std::make_pair(FileID(), 0);
1920
Argyrios Kyrtzidis37613a92013-04-13 01:03:57 +00001921 // Uses IncludedLocMap to retrieve/cache the decomposed loc.
1922
Eugene Zelenko918e0ca2017-11-03 22:35:27 +00001923 using DecompTy = std::pair<FileID, unsigned>;
Fangrui Songeae2b492018-12-09 01:46:01 +00001924 auto InsertOp = IncludedLocMap.try_emplace(FID);
Argyrios Kyrtzidis37613a92013-04-13 01:03:57 +00001925 DecompTy &DecompLoc = InsertOp.first->second;
1926 if (!InsertOp.second)
1927 return DecompLoc; // already in map.
1928
1929 SourceLocation UpperLoc;
Argyrios Kyrtzidis5dca8642013-05-24 22:24:04 +00001930 bool Invalid = false;
1931 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1932 if (!Invalid) {
1933 if (Entry.isExpansion())
1934 UpperLoc = Entry.getExpansion().getExpansionLocStart();
1935 else
1936 UpperLoc = Entry.getFile().getIncludeLoc();
1937 }
Argyrios Kyrtzidis37613a92013-04-13 01:03:57 +00001938
1939 if (UpperLoc.isValid())
1940 DecompLoc = getDecomposedLoc(UpperLoc);
1941
1942 return DecompLoc;
1943}
1944
Chandler Carruth64ee7822011-07-26 05:17:23 +00001945/// Given a decomposed source location, move it up the include/expansion stack
1946/// to the parent source location. If this is possible, return the decomposed
1947/// version of the parent in Loc and return false. If Loc is the top-level
1948/// entry, return true and don't modify it.
Chris Lattnera99fa1a2010-05-07 20:35:24 +00001949static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1950 const SourceManager &SM) {
Argyrios Kyrtzidis37613a92013-04-13 01:03:57 +00001951 std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
1952 if (UpperLoc.first.isInvalid())
Chris Lattnera99fa1a2010-05-07 20:35:24 +00001953 return true; // We reached the top.
Argyrios Kyrtzidis37613a92013-04-13 01:03:57 +00001954
1955 Loc = UpperLoc;
Chris Lattnera99fa1a2010-05-07 20:35:24 +00001956 return false;
1957}
Ted Kremenek08037042013-02-27 00:00:26 +00001958
1959/// Return the cache entry for comparing the given file IDs
1960/// for isBeforeInTranslationUnit.
1961InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
1962 FileID RFID) const {
1963 // This is a magic number for limiting the cache size. It was experimentally
1964 // derived from a small Objective-C project (where the cache filled
1965 // out to ~250 items). We can make it larger if necessary.
1966 enum { MagicCacheSize = 300 };
1967 IsBeforeInTUCacheKey Key(LFID, RFID);
1968
1969 // If the cache size isn't too large, do a lookup and if necessary default
1970 // construct an entry. We can then return it to the caller for direct
1971 // use. When they update the value, the cache will get automatically
1972 // updated as well.
1973 if (IBTUCache.size() < MagicCacheSize)
1974 return IBTUCache[Key];
1975
1976 // Otherwise, do a lookup that will not construct a new value.
1977 InBeforeInTUCache::iterator I = IBTUCache.find(Key);
1978 if (I != IBTUCache.end())
1979 return I->second;
1980
1981 // Fall back to the overflow value.
1982 return IBTUCacheOverflow;
1983}
Chris Lattnera99fa1a2010-05-07 20:35:24 +00001984
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001985/// Determines the order of 2 source locations in the translation unit.
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001986///
1987/// \returns true if LHS source location comes before RHS, false otherwise.
1988bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1989 SourceLocation RHS) const {
1990 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1991 if (LHS == RHS)
1992 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001993
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001994 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1995 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00001996
Argyrios Kyrtzidis5fd822c2013-05-24 23:47:43 +00001997 // getDecomposedLoc may have failed to return a valid FileID because, e.g. it
1998 // is a serialized one referring to a file that was removed after we loaded
1999 // the PCH.
Argyrios Kyrtzidis5dca8642013-05-24 22:24:04 +00002000 if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
Argyrios Kyrtzidisd6111d32013-05-25 01:03:03 +00002001 return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
Argyrios Kyrtzidis5dca8642013-05-24 22:24:04 +00002002
Gabor Horvath7848b382017-06-29 06:53:13 +00002003 std::pair<bool, bool> InSameTU = isInTheSameTranslationUnit(LOffs, ROffs);
2004 if (InSameTU.first)
2005 return InSameTU.second;
Mike Stump11289f42009-09-09 15:08:12 +00002006
Joerg Sonnenberger1d3b4312015-03-16 17:54:54 +00002007 // If we arrived here, the location is either in a built-ins buffer or
2008 // associated with global inline asm. PR5662 and PR22576 are examples.
2009
Mehdi Amini99d1b292016-10-01 16:38:28 +00002010 StringRef LB = getBuffer(LOffs.first)->getBufferIdentifier();
2011 StringRef RB = getBuffer(ROffs.first)->getBufferIdentifier();
2012 bool LIsBuiltins = LB == "<built-in>";
2013 bool RIsBuiltins = RB == "<built-in>";
Joerg Sonnenberger1d3b4312015-03-16 17:54:54 +00002014 // Sort built-in before non-built-in.
2015 if (LIsBuiltins || RIsBuiltins) {
2016 if (LIsBuiltins != RIsBuiltins)
2017 return LIsBuiltins;
2018 // Both are in built-in buffers, but from different files. We just claim that
2019 // lower IDs come first.
2020 return LOffs.first < ROffs.first;
2021 }
Mehdi Amini99d1b292016-10-01 16:38:28 +00002022 bool LIsAsm = LB == "<inline asm>";
2023 bool RIsAsm = RB == "<inline asm>";
Joerg Sonnenberger1d3b4312015-03-16 17:54:54 +00002024 // Sort assembler after built-ins, but before the rest.
2025 if (LIsAsm || RIsAsm) {
2026 if (LIsAsm != RIsAsm)
2027 return RIsAsm;
2028 assert(LOffs.first == ROffs.first);
2029 return false;
2030 }
Mehdi Amini99d1b292016-10-01 16:38:28 +00002031 bool LIsScratch = LB == "<scratch space>";
2032 bool RIsScratch = RB == "<scratch space>";
Yury Gribov154e57f2016-01-28 09:28:18 +00002033 // Sort scratch after inline asm, but before the rest.
2034 if (LIsScratch || RIsScratch) {
2035 if (LIsScratch != RIsScratch)
2036 return LIsScratch;
2037 return LOffs.second < ROffs.second;
2038 }
Joerg Sonnenberger1d3b4312015-03-16 17:54:54 +00002039 llvm_unreachable("Unsortable locations found");
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00002040}
Chris Lattner4fa23622009-01-26 00:43:02 +00002041
Gabor Horvath7848b382017-06-29 06:53:13 +00002042std::pair<bool, bool> SourceManager::isInTheSameTranslationUnit(
2043 std::pair<FileID, unsigned> &LOffs,
2044 std::pair<FileID, unsigned> &ROffs) const {
2045 // If the source locations are in the same file, just compare offsets.
2046 if (LOffs.first == ROffs.first)
2047 return std::make_pair(true, LOffs.second < ROffs.second);
2048
2049 // If we are comparing a source location with multiple locations in the same
2050 // file, we get a big win by caching the result.
2051 InBeforeInTUCacheEntry &IsBeforeInTUCache =
2052 getInBeforeInTUCache(LOffs.first, ROffs.first);
2053
2054 // If we are comparing a source location with multiple locations in the same
2055 // file, we get a big win by caching the result.
2056 if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
2057 return std::make_pair(
2058 true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2059
2060 // Okay, we missed in the cache, start updating the cache for this query.
2061 IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
2062 /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID);
2063
2064 // We need to find the common ancestor. The only way of doing this is to
2065 // build the complete include chain for one and then walking up the chain
2066 // of the other looking for a match.
2067 // We use a map from FileID to Offset to store the chain. Easier than writing
2068 // a custom set hash info that only depends on the first part of a pair.
Eugene Zelenko918e0ca2017-11-03 22:35:27 +00002069 using LocSet = llvm::SmallDenseMap<FileID, unsigned, 16>;
Gabor Horvath7848b382017-06-29 06:53:13 +00002070 LocSet LChain;
2071 do {
2072 LChain.insert(LOffs);
2073 // We catch the case where LOffs is in a file included by ROffs and
2074 // quit early. The other way round unfortunately remains suboptimal.
2075 } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
2076 LocSet::iterator I;
2077 while((I = LChain.find(ROffs.first)) == LChain.end()) {
2078 if (MoveUpIncludeHierarchy(ROffs, *this))
2079 break; // Met at topmost file.
2080 }
2081 if (I != LChain.end())
2082 LOffs = *I;
2083
2084 // If we exited because we found a nearest common ancestor, compare the
2085 // locations within the common file and cache them.
2086 if (LOffs.first == ROffs.first) {
2087 IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
2088 return std::make_pair(
2089 true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2090 }
2091 // Clear the lookup cache, it depends on a common location.
2092 IsBeforeInTUCache.clear();
2093 return std::make_pair(false, false);
2094}
2095
Chris Lattner22eb9722006-06-18 05:43:12 +00002096void SourceManager::PrintStats() const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +00002097 llvm::errs() << "\n*** Source Manager Stats:\n";
2098 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
2099 << " mem buffers mapped.\n";
Douglas Gregor925296b2011-07-19 16:10:42 +00002100 llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
Ted Kremenek43e0c4a2011-07-27 18:41:16 +00002101 << llvm::capacity_in_bytes(LocalSLocEntryTable)
Argyrios Kyrtzidis2cc62092011-07-07 03:40:24 +00002102 << " bytes of capacity), "
Douglas Gregor925296b2011-07-19 16:10:42 +00002103 << NextLocalOffset << "B of Sloc address space used.\n";
2104 llvm::errs() << LoadedSLocEntryTable.size()
2105 << " loaded SLocEntries allocated, "
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00002106 << MaxLoadedOffset - CurrentLoadedOffset
Douglas Gregor925296b2011-07-19 16:10:42 +00002107 << "B of Sloc address space used.\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00002108
Chris Lattner22eb9722006-06-18 05:43:12 +00002109 unsigned NumLineNumsComputed = 0;
2110 unsigned NumFileBytesMapped = 0;
Chris Lattnerc8233df2009-02-03 07:30:45 +00002111 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
Craig Topperf1186c52014-05-08 06:41:40 +00002112 NumLineNumsComputed += I->second->SourceLineCache != nullptr;
Chris Lattnerc8233df2009-02-03 07:30:45 +00002113 NumFileBytesMapped += I->second->getSizeBytesMapped();
Chris Lattner22eb9722006-06-18 05:43:12 +00002114 }
Argyrios Kyrtzidis4bdd6aa2011-09-26 08:01:50 +00002115 unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
Mike Stump11289f42009-09-09 15:08:12 +00002116
Benjamin Kramer89b422c2009-08-23 12:08:50 +00002117 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00002118 << NumLineNumsComputed << " files with line #'s computed, "
2119 << NumMacroArgsComputed << " files with macro args computed.\n";
Benjamin Kramer89b422c2009-08-23 12:08:50 +00002120 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
2121 << NumBinaryProbes << " binary.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +00002122}
Douglas Gregor258ae542009-04-27 06:38:32 +00002123
Richard Smith03a06dd2015-08-13 00:45:11 +00002124LLVM_DUMP_METHOD void SourceManager::dump() const {
2125 llvm::raw_ostream &out = llvm::errs();
2126
2127 auto DumpSLocEntry = [&](int ID, const SrcMgr::SLocEntry &Entry,
2128 llvm::Optional<unsigned> NextStart) {
2129 out << "SLocEntry <FileID " << ID << "> " << (Entry.isFile() ? "file" : "expansion")
2130 << " <SourceLocation " << Entry.getOffset() << ":";
2131 if (NextStart)
2132 out << *NextStart << ">\n";
2133 else
2134 out << "???\?>\n";
2135 if (Entry.isFile()) {
2136 auto &FI = Entry.getFile();
2137 if (FI.NumCreatedFIDs)
2138 out << " covers <FileID " << ID << ":" << int(ID + FI.NumCreatedFIDs)
2139 << ">\n";
2140 if (FI.getIncludeLoc().isValid())
2141 out << " included from " << FI.getIncludeLoc().getOffset() << "\n";
2142 if (auto *CC = FI.getContentCache()) {
2143 out << " for " << (CC->OrigEntry ? CC->OrigEntry->getName() : "<none>")
2144 << "\n";
2145 if (CC->BufferOverridden)
2146 out << " contents overridden\n";
2147 if (CC->ContentsEntry != CC->OrigEntry) {
2148 out << " contents from "
2149 << (CC->ContentsEntry ? CC->ContentsEntry->getName() : "<none>")
2150 << "\n";
2151 }
2152 }
2153 } else {
2154 auto &EI = Entry.getExpansion();
2155 out << " spelling from " << EI.getSpellingLoc().getOffset() << "\n";
2156 out << " macro " << (EI.isMacroArgExpansion() ? "arg" : "body")
2157 << " range <" << EI.getExpansionLocStart().getOffset() << ":"
2158 << EI.getExpansionLocEnd().getOffset() << ">\n";
2159 }
2160 };
2161
2162 // Dump local SLocEntries.
2163 for (unsigned ID = 0, NumIDs = LocalSLocEntryTable.size(); ID != NumIDs; ++ID) {
2164 DumpSLocEntry(ID, LocalSLocEntryTable[ID],
2165 ID == NumIDs - 1 ? NextLocalOffset
2166 : LocalSLocEntryTable[ID + 1].getOffset());
2167 }
2168 // Dump loaded SLocEntries.
2169 llvm::Optional<unsigned> NextStart;
2170 for (unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
2171 int ID = -(int)Index - 2;
2172 if (SLocEntryLoaded[Index]) {
2173 DumpSLocEntry(ID, LoadedSLocEntryTable[Index], NextStart);
2174 NextStart = LoadedSLocEntryTable[Index].getOffset();
2175 } else {
2176 NextStart = None;
2177 }
2178 }
2179}
2180
Eugene Zelenko918e0ca2017-11-03 22:35:27 +00002181ExternalSLocEntrySource::~ExternalSLocEntrySource() = default;
Ted Kremenek8d587902011-04-28 20:36:42 +00002182
2183/// Return the amount of memory used by memory buffers, breaking down
2184/// by heap-backed versus mmap'ed memory.
2185SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
2186 size_t malloc_bytes = 0;
2187 size_t mmap_bytes = 0;
Fangrui Song6907ce22018-07-30 19:24:48 +00002188
Ted Kremenek8d587902011-04-28 20:36:42 +00002189 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
2190 if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
2191 switch (MemBufferInfos[i]->getMemoryBufferKind()) {
2192 case llvm::MemoryBuffer::MemoryBuffer_MMap:
2193 mmap_bytes += sized_mapped;
2194 break;
2195 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
2196 malloc_bytes += sized_mapped;
2197 break;
2198 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002199
Ted Kremenek8d587902011-04-28 20:36:42 +00002200 return MemoryBufferSizes(malloc_bytes, mmap_bytes);
2201}
2202
Ted Kremenek120992a2011-07-26 23:46:06 +00002203size_t SourceManager::getDataStructureSizes() const {
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +00002204 size_t size = llvm::capacity_in_bytes(MemBufferInfos)
Ted Kremenek43e0c4a2011-07-27 18:41:16 +00002205 + llvm::capacity_in_bytes(LocalSLocEntryTable)
2206 + llvm::capacity_in_bytes(LoadedSLocEntryTable)
2207 + llvm::capacity_in_bytes(SLocEntryLoaded)
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +00002208 + llvm::capacity_in_bytes(FileInfos);
Fangrui Song6907ce22018-07-30 19:24:48 +00002209
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +00002210 if (OverriddenFilesInfo)
2211 size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);
2212
2213 return size;
Ted Kremenek120992a2011-07-26 23:46:06 +00002214}
Eric Liu2e538082018-05-09 21:35:52 +00002215
2216SourceManagerForFile::SourceManagerForFile(StringRef FileName,
2217 StringRef Content) {
2218 // This is referenced by `FileMgr` and will be released by `FileMgr` when it
2219 // is deleted.
Jonas Devliegherefc514902018-10-10 13:27:25 +00002220 IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
2221 new llvm::vfs::InMemoryFileSystem);
Eric Liu2e538082018-05-09 21:35:52 +00002222 InMemoryFileSystem->addFile(
2223 FileName, 0,
2224 llvm::MemoryBuffer::getMemBuffer(Content, FileName,
2225 /*RequiresNullTerminator=*/false));
2226 // This is passed to `SM` as reference, so the pointer has to be referenced
2227 // in `Environment` so that `FileMgr` can out-live this function scope.
2228 FileMgr =
2229 llvm::make_unique<FileManager>(FileSystemOptions(), InMemoryFileSystem);
2230 // This is passed to `SM` as reference, so the pointer has to be referenced
2231 // by `Environment` due to the same reason above.
2232 Diagnostics = llvm::make_unique<DiagnosticsEngine>(
2233 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
2234 new DiagnosticOptions);
2235 SourceMgr = llvm::make_unique<SourceManager>(*Diagnostics, *FileMgr);
2236 FileID ID = SourceMgr->createFileID(FileMgr->getFile(FileName),
2237 SourceLocation(), clang::SrcMgr::C_User);
2238 assert(ID.isValid());
2239 SourceMgr->setMainFileID(ID);
2240}