Coverage Report

Created: 2020-09-22 08:39

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Basic/SourceManager.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- SourceManager.cpp - Track and cache source files -------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file implements the SourceManager interface.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Basic/SourceManager.h"
14
#include "clang/Basic/Diagnostic.h"
15
#include "clang/Basic/FileManager.h"
16
#include "clang/Basic/LLVM.h"
17
#include "clang/Basic/SourceLocation.h"
18
#include "clang/Basic/SourceManagerInternals.h"
19
#include "llvm/ADT/DenseMap.h"
20
#include "llvm/ADT/None.h"
21
#include "llvm/ADT/Optional.h"
22
#include "llvm/ADT/STLExtras.h"
23
#include "llvm/ADT/SmallVector.h"
24
#include "llvm/ADT/StringRef.h"
25
#include "llvm/ADT/StringSwitch.h"
26
#include "llvm/Support/Allocator.h"
27
#include "llvm/Support/Capacity.h"
28
#include "llvm/Support/Compiler.h"
29
#include "llvm/Support/ErrorHandling.h"
30
#include "llvm/Support/FileSystem.h"
31
#include "llvm/Support/MathExtras.h"
32
#include "llvm/Support/MemoryBuffer.h"
33
#include "llvm/Support/Path.h"
34
#include "llvm/Support/raw_ostream.h"
35
#include <algorithm>
36
#include <cassert>
37
#include <cstddef>
38
#include <cstdint>
39
#include <memory>
40
#include <tuple>
41
#include <utility>
42
#include <vector>
43
44
using namespace clang;
45
using namespace SrcMgr;
46
using llvm::MemoryBuffer;
47
48
//===----------------------------------------------------------------------===//
49
// SourceManager Helper Classes
50
//===----------------------------------------------------------------------===//
51
52
421k
ContentCache::~ContentCache() {
53
421k
  if (shouldFreeBuffer())
54
399k
    delete Buffer.getPointer();
55
421k
}
56
57
/// getSizeBytesMapped - Returns the number of bytes actually mapped for this
58
/// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
59
7
unsigned ContentCache::getSizeBytesMapped() const {
60
7
  return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 
00
;
61
7
}
62
63
/// Returns the kind of memory used to back the memory buffer for
64
/// this content cache.  This is used for performance analysis.
65
1
llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
66
1
  assert(Buffer.getPointer());
67
68
  // Should be unreachable, but keep for sanity.
69
1
  if (!Buffer.getPointer())
70
0
    return llvm::MemoryBuffer::MemoryBuffer_Malloc;
71
72
1
  const llvm::MemoryBuffer *buf = Buffer.getPointer();
73
1
  return buf->getBufferKind();
74
1
}
75
76
/// getSize - Returns the size of the content encapsulated by this ContentCache.
77
///  This can be the size of the source file or the size of an arbitrary
78
///  scratch buffer.  If the ContentCache encapsulates a source file, that
79
///  file is not lazily brought in from disk to satisfy this query.
80
1.33M
unsigned ContentCache::getSize() const {
81
421k
  return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
82
914k
                             : (unsigned) ContentsEntry->getSize();
83
1.33M
}
84
85
307k
void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B, bool DoNotFree) {
86
307k
  if (B && 
B == Buffer.getPointer()307k
) {
87
0
    assert(0 && "Replacing with the same buffer");
88
0
    Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
89
0
    return;
90
0
  }
91
92
307k
  if (shouldFreeBuffer())
93
307k
    delete Buffer.getPointer();
94
307k
  Buffer.setPointer(B);
95
307k
  Buffer.setInt((B && 
DoNotFree307k
) ?
DoNotFreeFlag21.6k
:
0286k
);
96
307k
}
97
98
956k
const char *ContentCache::getInvalidBOM(StringRef BufStr) {
99
  // If the buffer is valid, check to see if it has a UTF Byte Order Mark
100
  // (BOM).  We only support UTF-8 with and without a BOM right now.  See
101
  // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
102
956k
  const char *InvalidBOM =
103
956k
      llvm::StringSwitch<const char *>(BufStr)
104
956k
          .StartsWith(llvm::StringLiteral::withInnerNUL("\x00\x00\xFE\xFF"),
105
956k
                      "UTF-32 (BE)")
106
956k
          .StartsWith(llvm::StringLiteral::withInnerNUL("\xFF\xFE\x00\x00"),
107
956k
                      "UTF-32 (LE)")
108
956k
          .StartsWith("\xFE\xFF", "UTF-16 (BE)")
109
956k
          .StartsWith("\xFF\xFE", "UTF-16 (LE)")
110
956k
          .StartsWith("\x2B\x2F\x76", "UTF-7")
111
956k
          .StartsWith("\xF7\x64\x4C", "UTF-1")
112
956k
          .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
113
956k
          .StartsWith("\x0E\xFE\xFF", "SCSU")
114
956k
          .StartsWith("\xFB\xEE\x28", "BOCU-1")
115
956k
          .StartsWith("\x84\x31\x95\x33", "GB-18030")
116
956k
          .Default(nullptr);
117
118
956k
  return InvalidBOM;
119
956k
}
120
121
const llvm::MemoryBuffer *ContentCache::getBuffer(DiagnosticsEngine &Diag,
122
                                                  FileManager &FM,
123
                                                  SourceLocation Loc,
124
137M
                                                  bool *Invalid) const {
125
  // Lazily create the Buffer for ContentCaches that wrap files.  If we already
126
  // computed it, just return what we have.
127
137M
  if (Buffer.getPointer() || 
!ContentsEntry955k
) {
128
136M
    if (Invalid)
129
131M
      *Invalid = isBufferInvalid();
130
131
136M
    return Buffer.getPointer();
132
136M
  }
133
134
  // Check that the file's size fits in an 'unsigned' (with room for a
135
  // past-the-end value). This is deeply regrettable, but various parts of
136
  // Clang (including elsewhere in this file!) use 'unsigned' to represent file
137
  // offsets, line numbers, string literal lengths, and so on, and fail
138
  // miserably on large source files.
139
955k
  if ((uint64_t)ContentsEntry->getSize() >=
140
0
      std::numeric_limits<unsigned>::max()) {
141
    // We can't make a memory buffer of the required size, so just make a small
142
    // one. We should never hit a situation where we've already parsed to a
143
    // later offset of the file, so it shouldn't matter that the buffer is
144
    // smaller than the file.
145
0
    Buffer.setPointer(
146
0
        llvm::MemoryBuffer::getMemBuffer("", ContentsEntry->getName())
147
0
            .release());
148
0
    if (Diag.isDiagnosticInFlight())
149
0
      Diag.SetDelayedDiagnostic(diag::err_file_too_large,
150
0
                                ContentsEntry->getName());
151
0
    else
152
0
      Diag.Report(Loc, diag::err_file_too_large)
153
0
        << ContentsEntry->getName();
154
155
0
    Buffer.setInt(Buffer.getInt() | InvalidFlag);
156
0
    if (Invalid) *Invalid = true;
157
0
    return Buffer.getPointer();
158
0
  }
159
160
955k
  auto BufferOrError = FM.getBufferForFile(ContentsEntry, IsFileVolatile);
161
162
  // If we were unable to open the file, then we are in an inconsistent
163
  // situation where the content cache referenced a file which no longer
164
  // exists. Most likely, we were using a stat cache with an invalid entry but
165
  // the file could also have been removed during processing. Since we can't
166
  // really deal with this situation, just create an empty buffer.
167
  //
168
  // FIXME: This is definitely not ideal, but our immediate clients can't
169
  // currently handle returning a null entry here. Ideally we should detect
170
  // that we are in an inconsistent situation and error out as quickly as
171
  // possible.
172
955k
  if (!BufferOrError) {
173
1
    StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
174
1
    auto BackupBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
175
1
        ContentsEntry->getSize(), "<invalid>");
176
1
    char *Ptr = BackupBuffer->getBufferStart();
177
1
    for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; 
++i0
)
178
0
      Ptr[i] = FillStr[i % FillStr.size()];
179
1
    Buffer.setPointer(BackupBuffer.release());
180
181
1
    if (Diag.isDiagnosticInFlight())
182
0
      Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
183
0
                                ContentsEntry->getName(),
184
0
                                BufferOrError.getError().message());
185
1
    else
186
1
      Diag.Report(Loc, diag::err_cannot_open_file)
187
1
          << ContentsEntry->getName() << BufferOrError.getError().message();
188
189
1
    Buffer.setInt(Buffer.getInt() | InvalidFlag);
190
191
1
    if (Invalid) *Invalid = true;
192
1
    return Buffer.getPointer();
193
1
  }
194
195
955k
  Buffer.setPointer(BufferOrError->release());
196
197
  // Check that the file's size is the same as in the file entry (which may
198
  // have come from a stat cache).
199
955k
  if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) {
200
0
    if (Diag.isDiagnosticInFlight())
201
0
      Diag.SetDelayedDiagnostic(diag::err_file_modified,
202
0
                                ContentsEntry->getName());
203
0
    else
204
0
      Diag.Report(Loc, diag::err_file_modified)
205
0
        << ContentsEntry->getName();
206
207
0
    Buffer.setInt(Buffer.getInt() | InvalidFlag);
208
0
    if (Invalid) *Invalid = true;
209
0
    return Buffer.getPointer();
210
0
  }
211
212
  // If the buffer is valid, check to see if it has a UTF Byte Order Mark
213
  // (BOM).  We only support UTF-8 with and without a BOM right now.  See
214
  // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
215
955k
  StringRef BufStr = Buffer.getPointer()->getBuffer();
216
955k
  const char *InvalidBOM = getInvalidBOM(BufStr);
217
218
955k
  if (InvalidBOM) {
219
1
    Diag.Report(Loc, diag::err_unsupported_bom)
220
1
      << InvalidBOM << ContentsEntry->getName();
221
1
    Buffer.setInt(Buffer.getInt() | InvalidFlag);
222
1
  }
223
224
955k
  if (Invalid)
225
934k
    *Invalid = isBufferInvalid();
226
227
955k
  return Buffer.getPointer();
228
955k
}
229
230
503k
unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
231
503k
  auto IterBool = FilenameIDs.try_emplace(Name, FilenamesByID.size());
232
503k
  if (IterBool.second)
233
393k
    FilenamesByID.push_back(&*IterBool.first);
234
503k
  return IterBool.first->second;
235
503k
}
236
237
/// Add a line note to the line table that indicates that there is a \#line or
238
/// GNU line marker at the specified FID/Offset location which changes the
239
/// presumed location to LineNo/FilenameID. If EntryExit is 0, then this doesn't
240
/// change the presumed \#include stack.  If it is 1, this is a file entry, if
241
/// it is 2 then this is a file exit. FileKind specifies whether this is a
242
/// system header or extern C system header.
243
void LineTableInfo::AddLineNote(FileID FID, unsigned Offset, unsigned LineNo,
244
                                int FilenameID, unsigned EntryExit,
245
309k
                                SrcMgr::CharacteristicKind FileKind) {
246
309k
  std::vector<LineEntry> &Entries = LineEntries[FID];
247
248
  // An unspecified FilenameID means use the last filename if available, or the
249
  // main source file otherwise.
250
309k
  if (FilenameID == -1 && 
!Entries.empty()1.86k
)
251
1.67k
    FilenameID = Entries.back().FilenameID;
252
253
309k
  assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
254
309k
         "Adding line entries out of order!");
255
256
309k
  unsigned IncludeOffset = 0;
257
309k
  if (EntryExit == 0) {  // No #include stack change.
258
135k
    IncludeOffset = Entries.empty() ? 0 : 
Entries.back().IncludeOffset18.5k
;
259
155k
  } else if (EntryExit == 1) {
260
77.6k
    IncludeOffset = Offset-1;
261
77.5k
  } else 
if (77.5k
EntryExit == 277.5k
) {
262
77.5k
    assert(!Entries.empty() && Entries.back().IncludeOffset &&
263
77.5k
       "PPDirectives should have caught case when popping empty include stack");
264
265
    // Get the include loc of the last entries' include loc as our include loc.
266
77.5k
    IncludeOffset = 0;
267
77.5k
    if (const LineEntry *PrevEntry =
268
77.5k
          FindNearestLineEntry(FID, Entries.back().IncludeOffset))
269
77.5k
      IncludeOffset = PrevEntry->IncludeOffset;
270
77.5k
  }
271
272
309k
  Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
273
309k
                                   IncludeOffset));
274
309k
}
275
276
/// FindNearestLineEntry - Find the line entry nearest to FID that is before
277
/// it.  If there is no line entry before Offset in FID, return null.
278
const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID,
279
75.5M
                                                     unsigned Offset) {
280
75.5M
  const std::vector<LineEntry> &Entries = LineEntries[FID];
281
75.5M
  assert(!Entries.empty() && "No #line entries for this FID after all!");
282
283
  // It is very common for the query to be after the last #line, check this
284
  // first.
285
75.5M
  if (Entries.back().FileOffset <= Offset)
286
74.8M
    return &Entries.back();
287
288
  // Do a binary search to find the maximal element that is still before Offset.
289
692k
  std::vector<LineEntry>::const_iterator I = llvm::upper_bound(Entries, Offset);
290
692k
  if (I == Entries.begin())
291
573k
    return nullptr;
292
119k
  return &*--I;
293
119k
}
294
295
/// Add a new line entry that has already been encoded into
296
/// the internal representation of the line table.
297
void LineTableInfo::AddEntry(FileID FID,
298
174k
                             const std::vector<LineEntry> &Entries) {
299
174k
  LineEntries[FID] = Entries;
300
174k
}
301
302
/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
303
307k
unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
304
307k
  return getLineTable().getLineTableFilenameID(Name);
305
307k
}
306
307
/// AddLineNote - Add a line note to the line table for the FileID and offset
308
/// specified by Loc.  If FilenameID is -1, it is considered to be
309
/// unspecified.
310
void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
311
                                int FilenameID, bool IsFileEntry,
312
                                bool IsFileExit,
313
309k
                                SrcMgr::CharacteristicKind FileKind) {
314
309k
  std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
315
316
309k
  bool Invalid = false;
317
309k
  const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
318
309k
  if (!Entry.isFile() || 
Invalid309k
)
319
0
    return;
320
321
309k
  const SrcMgr::FileInfo &FileInfo = Entry.getFile();
322
323
  // Remember that this file has #line directives now if it doesn't already.
324
309k
  const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
325
326
309k
  (void) getLineTable();
327
328
309k
  unsigned EntryExit = 0;
329
309k
  if (IsFileEntry)
330
77.6k
    EntryExit = 1;
331
232k
  else if (IsFileExit)
332
77.5k
    EntryExit = 2;
333
334
309k
  LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,
335
309k
                         EntryExit, FileKind);
336
309k
}
337
338
644k
LineTableInfo &SourceManager::getLineTable() {
339
644k
  if (!LineTable)
340
80.8k
    LineTable.reset(new LineTableInfo());
341
644k
  return *LineTable;
342
644k
}
343
344
//===----------------------------------------------------------------------===//
345
// Private 'Create' methods.
346
//===----------------------------------------------------------------------===//
347
348
SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
349
                             bool UserFilesAreVolatile)
350
161k
  : Diag(Diag), FileMgr(FileMgr), UserFilesAreVolatile(UserFilesAreVolatile) {
351
161k
  clearIDTables();
352
161k
  Diag.setSourceManager(this);
353
161k
}
354
355
152k
SourceManager::~SourceManager() {
356
  // Delete FileEntry objects corresponding to content caches.  Since the actual
357
  // content cache objects are bump pointer allocated, we just have to run the
358
  // dtors, but we call the deallocate method for completeness.
359
284k
  for (unsigned i = 0, e = MemBufferInfos.size(); i != e; 
++i131k
) {
360
131k
    if (MemBufferInfos[i]) {
361
131k
      MemBufferInfos[i]->~ContentCache();
362
131k
      ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
363
131k
    }
364
131k
  }
365
152k
  for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
366
442k
       I = FileInfos.begin(), E = FileInfos.end(); I != E; 
++I289k
) {
367
289k
    if (I->second) {
368
289k
      I->second->~ContentCache();
369
289k
      ContentCacheAlloc.Deallocate(I->second);
370
289k
    }
371
289k
  }
372
152k
}
373
374
181k
void SourceManager::clearIDTables() {
375
181k
  MainFileID = FileID();
376
181k
  LocalSLocEntryTable.clear();
377
181k
  LoadedSLocEntryTable.clear();
378
181k
  SLocEntryLoaded.clear();
379
181k
  LastLineNoFileIDQuery = FileID();
380
181k
  LastLineNoContentCache = nullptr;
381
181k
  LastFileIDLookup = FileID();
382
383
181k
  if (LineTable)
384
44
    LineTable->clear();
385
386
  // Use up FileID #0 as an invalid expansion.
387
181k
  NextLocalOffset = 0;
388
181k
  CurrentLoadedOffset = MaxLoadedOffset;
389
181k
  createExpansionLoc(SourceLocation(), SourceLocation(), SourceLocation(), 1);
390
181k
}
391
392
77
bool SourceManager::isMainFile(FileEntryRef SourceFile) {
393
77
  assert(MainFileID.isValid() && "expected initialized SourceManager");
394
77
  auto FE = getFileEntryRefForID(MainFileID);
395
77
  if (!FE)
396
1
    return false;
397
76
  return FE->getUID() == SourceFile.getUID();
398
76
}
399
400
15
void SourceManager::initializeForReplay(const SourceManager &Old) {
401
15
  assert(MainFileID.isInvalid() && "expected uninitialized SourceManager");
402
403
52
  auto CloneContentCache = [&](const ContentCache *Cache) -> ContentCache * {
404
52
    auto *Clone = new (ContentCacheAlloc.Allocate<ContentCache>()) ContentCache;
405
52
    Clone->OrigEntry = Cache->OrigEntry;
406
52
    Clone->ContentsEntry = Cache->ContentsEntry;
407
52
    Clone->BufferOverridden = Cache->BufferOverridden;
408
52
    Clone->IsFileVolatile = Cache->IsFileVolatile;
409
52
    Clone->IsTransient = Cache->IsTransient;
410
52
    Clone->replaceBuffer(Cache->getRawBuffer(), /*DoNotFree*/true);
411
52
    return Clone;
412
52
  };
413
414
  // Ensure all SLocEntries are loaded from the external source.
415
142
  for (unsigned I = 0, N = Old.LoadedSLocEntryTable.size(); I != N; 
++I127
)
416
127
    if (!Old.SLocEntryLoaded[I])
417
102
      Old.loadSLocEntry(I, nullptr);
418
419
  // Inherit any content cache data from the old source manager.
420
52
  for (auto &FileInfo : Old.FileInfos) {
421
52
    SrcMgr::ContentCache *&Slot = FileInfos[FileInfo.first];
422
52
    if (Slot)
423
0
      continue;
424
52
    Slot = CloneContentCache(FileInfo.second);
425
52
  }
426
15
}
427
428
/// getOrCreateContentCache - Create or return a cached ContentCache for the
429
/// specified file.
430
const ContentCache *
431
SourceManager::getOrCreateContentCache(const FileEntry *FileEnt,
432
1.67M
                                       bool isSystemFile) {
433
1.67M
  assert(FileEnt && "Didn't specify a file entry to use?");
434
435
  // Do we already have information about this file?
436
1.67M
  ContentCache *&Entry = FileInfos[FileEnt];
437
1.67M
  if (Entry) 
return Entry583k
;
438
439
  // Nope, create a new Cache entry.
440
1.08M
  Entry = ContentCacheAlloc.Allocate<ContentCache>();
441
442
1.08M
  if (OverriddenFilesInfo) {
443
    // If the file contents are overridden with contents from another file,
444
    // pass that file to ContentCache.
445
83.9k
    llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
446
83.9k
        overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
447
83.9k
    if (overI == OverriddenFilesInfo->OverriddenFiles.end())
448
83.9k
      new (Entry) ContentCache(FileEnt);
449
9
    else
450
9
      new (Entry) ContentCache(OverridenFilesKeepOriginalName ? 
FileEnt7
451
2
                                                              : overI->second,
452
9
                               overI->second);
453
1.00M
  } else {
454
1.00M
    new (Entry) ContentCache(FileEnt);
455
1.00M
  }
456
457
1.08M
  Entry->IsFileVolatile = UserFilesAreVolatile && 
!isSystemFile2.57k
;
458
1.08M
  Entry->IsTransient = FilesAreTransient;
459
460
1.08M
  return Entry;
461
1.08M
}
462
463
/// Create a new ContentCache for the specified memory buffer.
464
/// This does no caching.
465
const ContentCache *
466
SourceManager::createMemBufferContentCache(const llvm::MemoryBuffer *Buffer,
467
301k
                                           bool DoNotFree) {
468
  // Add a new ContentCache to the MemBufferInfos list and return it.
469
301k
  ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
470
301k
  new (Entry) ContentCache();
471
301k
  MemBufferInfos.push_back(Entry);
472
301k
  Entry->replaceBuffer(Buffer, DoNotFree);
473
301k
  return Entry;
474
301k
}
475
476
const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
477
3.25M
                                                      bool *Invalid) const {
478
3.25M
  assert(!SLocEntryLoaded[Index]);
479
3.25M
  if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
480
88
    if (Invalid)
481
41
      *Invalid = true;
482
    // If the file of the SLocEntry changed we could still have loaded it.
483
88
    if (!SLocEntryLoaded[Index]) {
484
      // Try to recover; create a SLocEntry so the rest of clang can handle it.
485
88
      LoadedSLocEntryTable[Index] = SLocEntry::get(
486
88
          0, FileInfo::get(SourceLocation(), getFakeContentCacheForRecovery(),
487
88
                           SrcMgr::C_User, ""));
488
88
    }
489
88
  }
490
491
3.25M
  return LoadedSLocEntryTable[Index];
492
3.25M
}
493
494
std::pair<int, unsigned>
495
SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
496
21.8k
                                         unsigned TotalSize) {
497
21.8k
  assert(ExternalSLocEntries && "Don't have an external sloc source");
498
  // Make sure we're not about to run out of source locations.
499
21.8k
  if (CurrentLoadedOffset - TotalSize < NextLocalOffset)
500
0
    return std::make_pair(0, 0);
501
21.8k
  LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
502
21.8k
  SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
503
21.8k
  CurrentLoadedOffset -= TotalSize;
504
21.8k
  int ID = LoadedSLocEntryTable.size();
505
21.8k
  return std::make_pair(-ID - 1, CurrentLoadedOffset);
506
21.8k
}
507
508
/// As part of recovering from missing or changed content, produce a
509
/// fake, non-empty buffer.
510
810
llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const {
511
810
  if (!FakeBufferForRecovery)
512
21
    FakeBufferForRecovery =
513
21
        llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
514
515
810
  return FakeBufferForRecovery.get();
516
810
}
517
518
/// As part of recovering from missing or changed content, produce a
519
/// fake content cache.
520
const SrcMgr::ContentCache *
521
88
SourceManager::getFakeContentCacheForRecovery() const {
522
88
  if (!FakeContentCacheForRecovery) {
523
2
    FakeContentCacheForRecovery = std::make_unique<SrcMgr::ContentCache>();
524
2
    FakeContentCacheForRecovery->replaceBuffer(getFakeBufferForRecovery(),
525
2
                                               /*DoNotFree=*/true);
526
2
  }
527
88
  return FakeContentCacheForRecovery.get();
528
88
}
529
530
/// Returns the previous in-order FileID or an invalid FileID if there
531
/// is no previous one.
532
2.92M
FileID SourceManager::getPreviousFileID(FileID FID) const {
533
2.92M
  if (FID.isInvalid())
534
0
    return FileID();
535
536
2.92M
  int ID = FID.ID;
537
2.92M
  if (ID == -1)
538
0
    return FileID();
539
540
2.92M
  if (ID > 0) {
541
2.92M
    if (ID-1 == 0)
542
0
      return FileID();
543
0
  } else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {
544
0
    return FileID();
545
0
  }
546
547
2.92M
  return FileID::get(ID-1);
548
2.92M
}
549
550
/// Returns the next in-order FileID or an invalid FileID if there is
551
/// no next one.
552
44.3k
FileID SourceManager::getNextFileID(FileID FID) const {
553
44.3k
  if (FID.isInvalid())
554
0
    return FileID();
555
556
44.3k
  int ID = FID.ID;
557
44.3k
  if (ID > 0) {
558
44.3k
    if (unsigned(ID+1) >= local_sloc_entry_size())
559
44
      return FileID();
560
0
  } else if (ID+1 >= -1) {
561
0
    return FileID();
562
0
  }
563
564
44.2k
  return FileID::get(ID+1);
565
44.2k
}
566
567
//===----------------------------------------------------------------------===//
568
// Methods to create new FileID's and macro expansions.
569
//===----------------------------------------------------------------------===//
570
571
/// Create a new FileID that represents the specified file
572
/// being \#included from the specified IncludePosition.
573
///
574
/// This translates NULL into standard input.
575
FileID SourceManager::createFileID(const FileEntry *SourceFile,
576
                                   SourceLocation IncludePos,
577
                                   SrcMgr::CharacteristicKind FileCharacter,
578
380k
                                   int LoadedID, unsigned LoadedOffset) {
579
380k
  assert(SourceFile && "Null source file!");
580
380k
  const SrcMgr::ContentCache *IR =
581
380k
      getOrCreateContentCache(SourceFile, isSystem(FileCharacter));
582
380k
  assert(IR && "getOrCreateContentCache() cannot return NULL");
583
380k
  return createFileID(IR, SourceFile->getName(), IncludePos, FileCharacter,
584
380k
          LoadedID, LoadedOffset);
585
380k
}
586
587
FileID SourceManager::createFileID(FileEntryRef SourceFile,
588
                                   SourceLocation IncludePos,
589
                                   SrcMgr::CharacteristicKind FileCharacter,
590
986k
                                   int LoadedID, unsigned LoadedOffset) {
591
986k
  const SrcMgr::ContentCache *IR = getOrCreateContentCache(
592
986k
      &SourceFile.getFileEntry(), isSystem(FileCharacter));
593
986k
  assert(IR && "getOrCreateContentCache() cannot return NULL");
594
986k
  return createFileID(IR, SourceFile.getName(), IncludePos, FileCharacter,
595
986k
          LoadedID, LoadedOffset);
596
986k
}
597
598
/// Create a new FileID that represents the specified memory buffer.
599
///
600
/// This does no caching of the buffer and takes ownership of the
601
/// MemoryBuffer, so only pass a MemoryBuffer to this once.
602
FileID SourceManager::createFileID(std::unique_ptr<llvm::MemoryBuffer> Buffer,
603
                                   SrcMgr::CharacteristicKind FileCharacter,
604
                                   int LoadedID, unsigned LoadedOffset,
605
280k
                                   SourceLocation IncludeLoc) {
606
280k
  StringRef Name = Buffer->getBufferIdentifier();
607
280k
  return createFileID(
608
280k
      createMemBufferContentCache(Buffer.release(), /*DoNotFree*/ false),
609
280k
      Name, IncludeLoc, FileCharacter, LoadedID, LoadedOffset);
610
280k
}
611
612
/// Create a new FileID that represents the specified memory buffer.
613
///
614
/// This does not take ownership of the MemoryBuffer. The memory buffer must
615
/// outlive the SourceManager.
616
FileID SourceManager::createFileID(UnownedTag, const llvm::MemoryBuffer *Buffer,
617
                                   SrcMgr::CharacteristicKind FileCharacter,
618
                                   int LoadedID, unsigned LoadedOffset,
619
21.1k
                                   SourceLocation IncludeLoc) {
620
21.1k
  return createFileID(createMemBufferContentCache(Buffer, /*DoNotFree*/ true),
621
21.1k
          Buffer->getBufferIdentifier(), IncludeLoc,
622
21.1k
          FileCharacter, LoadedID, LoadedOffset);
623
21.1k
}
624
625
/// Get the FileID for \p SourceFile if it exists. Otherwise, create a
626
/// new FileID for the \p SourceFile.
627
FileID
628
SourceManager::getOrCreateFileID(const FileEntry *SourceFile,
629
44.9k
                                 SrcMgr::CharacteristicKind FileCharacter) {
630
44.9k
  FileID ID = translateFile(SourceFile);
631
44.9k
  return ID.isValid() ? ID : createFileID(SourceFile, SourceLocation(),
632
65
            FileCharacter);
633
44.9k
}
634
635
/// createFileID - Create a new FileID for the specified ContentCache and
636
/// include position.  This works regardless of whether the ContentCache
637
/// corresponds to a file or some other input source.
638
FileID SourceManager::createFileID(const ContentCache *File, StringRef Filename,
639
                                   SourceLocation IncludePos,
640
                                   SrcMgr::CharacteristicKind FileCharacter,
641
1.66M
                                   int LoadedID, unsigned LoadedOffset) {
642
1.66M
  if (LoadedID < 0) {
643
332k
    assert(LoadedID != -1 && "Loading sentinel FileID");
644
332k
    unsigned Index = unsigned(-LoadedID) - 2;
645
332k
    assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
646
332k
    assert(!SLocEntryLoaded[Index] && "FileID already loaded");
647
332k
    LoadedSLocEntryTable[Index] = SLocEntry::get(
648
332k
        LoadedOffset, FileInfo::get(IncludePos, File, FileCharacter, Filename));
649
332k
    SLocEntryLoaded[Index] = true;
650
332k
    return FileID::get(LoadedID);
651
332k
  }
652
1.33M
  unsigned FileSize = File->getSize();
653
1.33M
  if (!(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
654
1.33M
        NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset)) {
655
1
    Diag.Report(IncludePos, diag::err_include_too_large);
656
1
    return FileID();
657
1
  }
658
1.33M
  LocalSLocEntryTable.push_back(
659
1.33M
      SLocEntry::get(NextLocalOffset,
660
1.33M
                     FileInfo::get(IncludePos, File, FileCharacter, Filename)));
661
  // We do a +1 here because we want a SourceLocation that means "the end of the
662
  // file", e.g. for the "no newline at the end of the file" diagnostic.
663
1.33M
  NextLocalOffset += FileSize + 1;
664
665
  // Set LastFileIDLookup to the newly created file.  The next getFileID call is
666
  // almost guaranteed to be from that file.
667
1.33M
  FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
668
1.33M
  return LastFileIDLookup = FID;
669
1.33M
}
670
671
SourceLocation
672
SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc,
673
                                          SourceLocation ExpansionLoc,
674
88.2M
                                          unsigned TokLength) {
675
88.2M
  ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
676
88.2M
                                                        ExpansionLoc);
677
88.2M
  return createExpansionLocImpl(Info, TokLength);
678
88.2M
}
679
680
SourceLocation
681
SourceManager::createExpansionLoc(SourceLocation SpellingLoc,
682
                                  SourceLocation ExpansionLocStart,
683
                                  SourceLocation ExpansionLocEnd,
684
                                  unsigned TokLength,
685
                                  bool ExpansionIsTokenRange,
686
                                  int LoadedID,
687
106M
                                  unsigned LoadedOffset) {
688
106M
  ExpansionInfo Info = ExpansionInfo::create(
689
106M
      SpellingLoc, ExpansionLocStart, ExpansionLocEnd, ExpansionIsTokenRange);
690
106M
  return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset);
691
106M
}
692
693
SourceLocation SourceManager::createTokenSplitLoc(SourceLocation Spelling,
694
                                                  SourceLocation TokenStart,
695
17.3k
                                                  SourceLocation TokenEnd) {
696
17.3k
  assert(getFileID(TokenStart) == getFileID(TokenEnd) &&
697
17.3k
         "token spans multiple files");
698
17.3k
  return createExpansionLocImpl(
699
17.3k
      ExpansionInfo::createForTokenSplit(Spelling, TokenStart, TokenEnd),
700
17.3k
      TokenEnd.getOffset() - TokenStart.getOffset());
701
17.3k
}
702
703
SourceLocation
704
SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
705
                                      unsigned TokLength,
706
                                      int LoadedID,
707
194M
                                      unsigned LoadedOffset) {
708
194M
  if (LoadedID < 0) {
709
2.92M
    assert(LoadedID != -1 && "Loading sentinel FileID");
710
2.92M
    unsigned Index = unsigned(-LoadedID) - 2;
711
2.92M
    assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
712
2.92M
    assert(!SLocEntryLoaded[Index] && "FileID already loaded");
713
2.92M
    LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
714
2.92M
    SLocEntryLoaded[Index] = true;
715
2.92M
    return SourceLocation::getMacroLoc(LoadedOffset);
716
2.92M
  }
717
191M
  LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
718
191M
  assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&
719
191M
         NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&
720
191M
         "Ran out of source locations!");
721
  // See createFileID for that +1.
722
191M
  NextLocalOffset += TokLength + 1;
723
191M
  return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
724
191M
}
725
726
const llvm::MemoryBuffer *
727
1.23k
SourceManager::getMemoryBufferForFile(const FileEntry *File, bool *Invalid) {
728
1.23k
  const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
729
1.23k
  assert(IR && "getOrCreateContentCache() cannot return NULL");
730
1.23k
  return IR->getBuffer(Diag, getFileManager(), SourceLocation(), Invalid);
731
1.23k
}
732
733
void SourceManager::overrideFileContents(const FileEntry *SourceFile,
734
                                         llvm::MemoryBuffer *Buffer,
735
5.97k
                                         bool DoNotFree) {
736
5.97k
  const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
737
5.97k
  assert(IR && "getOrCreateContentCache() cannot return NULL");
738
739
5.97k
  const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
740
5.97k
  const_cast<SrcMgr::ContentCache *>(IR)->BufferOverridden = true;
741
742
5.97k
  getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
743
5.97k
}
744
745
void SourceManager::overrideFileContents(const FileEntry *SourceFile,
746
16
                                         const FileEntry *NewFile) {
747
16
  assert(SourceFile->getSize() == NewFile->getSize() &&
748
16
         "Different sizes, use the FileManager to create a virtual file with "
749
16
         "the correct size");
750
16
  assert(FileInfos.count(SourceFile) == 0 &&
751
16
         "This function should be called at the initialization stage, before "
752
16
         "any parsing occurs.");
753
16
  getOverriddenFilesInfo().OverriddenFiles[SourceFile] = NewFile;
754
16
}
755
756
const FileEntry *
757
1
SourceManager::bypassFileContentsOverride(const FileEntry &File) {
758
1
  assert(isFileOverridden(&File));
759
1
  llvm::Optional<FileEntryRef> BypassFile =
760
1
      FileMgr.getBypassFile(FileEntryRef(File.getName(), File));
761
762
  // If the file can't be found in the FS, give up.
763
1
  if (!BypassFile)
764
0
    return nullptr;
765
766
1
  const FileEntry *FE = &BypassFile->getFileEntry();
767
1
  (void)getOrCreateContentCache(FE);
768
1
  return FE;
769
1
}
770
771
2
void SourceManager::setFileIsTransient(const FileEntry *File) {
772
2
  const SrcMgr::ContentCache *CC = getOrCreateContentCache(File);
773
2
  const_cast<SrcMgr::ContentCache *>(CC)->IsTransient = true;
774
2
}
775
776
405k
Optional<FileEntryRef> SourceManager::getFileEntryRefForID(FileID FID) const {
777
405k
  bool Invalid = false;
778
405k
  const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
779
405k
  if (Invalid || 
!Entry.isFile()405k
)
780
0
    return None;
781
782
405k
  const SrcMgr::ContentCache *Content = Entry.getFile().getContentCache();
783
405k
  if (!Content || 
!Content->OrigEntry405k
)
784
6.12k
    return None;
785
399k
  return FileEntryRef(Entry.getFile().getName(), *Content->OrigEntry);
786
399k
}
787
788
70.5M
StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
789
70.5M
  bool MyInvalid = false;
790
70.5M
  const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid);
791
70.5M
  if (!SLoc.isFile() || 
MyInvalid70.5M
) {
792
23
    if (Invalid)
793
23
      *Invalid = true;
794
23
    return "<<<<<INVALID SOURCE LOCATION>>>>>";
795
23
  }
796
797
70.5M
  const llvm::MemoryBuffer *Buf = SLoc.getFile().getContentCache()->getBuffer(
798
70.5M
      Diag, getFileManager(), SourceLocation(), &MyInvalid);
799
70.5M
  if (Invalid)
800
70.4M
    *Invalid = MyInvalid;
801
802
70.5M
  if (MyInvalid)
803
0
    return "<<<<<INVALID SOURCE LOCATION>>>>>";
804
805
70.5M
  return Buf->getBuffer();
806
70.5M
}
807
808
//===----------------------------------------------------------------------===//
809
// SourceLocation manipulation methods.
810
//===----------------------------------------------------------------------===//
811
812
/// Return the FileID for a SourceLocation.
813
///
814
/// This is the cache-miss path of getFileID. Not as hot as that function, but
815
/// still very important. It is responsible for finding the entry in the
816
/// SLocEntry tables that contains the specified location.
817
340M
FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
818
340M
  if (!SLocOffset)
819
1.13M
    return FileID::get(0);
820
821
  // Now it is time to search for the correct file. See where the SLocOffset
822
  // sits in the global view and consult local or loaded buffers for it.
823
338M
  if (SLocOffset < NextLocalOffset)
824
333M
    return getFileIDLocal(SLocOffset);
825
5.31M
  return getFileIDLoaded(SLocOffset);
826
5.31M
}
827
828
/// Return the FileID for a SourceLocation with a low offset.
829
///
830
/// This function knows that the SourceLocation is in a local buffer, not a
831
/// loaded one.
832
333M
FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const {
833
333M
  assert(SLocOffset < NextLocalOffset && "Bad function choice");
834
835
  // After the first and second level caches, I see two common sorts of
836
  // behavior: 1) a lot of searched FileID's are "near" the cached file
837
  // location or are "near" the cached expansion location. 2) others are just
838
  // completely random and may be a very long way away.
839
  //
840
  // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
841
  // then we fall back to a less cache efficient, but more scalable, binary
842
  // search to find the location.
843
844
  // See if this is near the file point - worst case we start scanning from the
845
  // most newly created FileID.
846
333M
  const SrcMgr::SLocEntry *I;
847
848
333M
  if (LastFileIDLookup.ID < 0 ||
849
332M
      LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
850
    // Neither loc prunes our search.
851
154M
    I = LocalSLocEntryTable.end();
852
179M
  } else {
853
    // Perhaps it is near the file point.
854
179M
    I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
855
179M
  }
856
857
  // Find the FileID that contains this.  "I" is an iterator that points to a
858
  // FileID whose offset is known to be larger than SLocOffset.
859
333M
  unsigned NumProbes = 0;
860
1.59G
  while (true) {
861
1.59G
    --I;
862
1.59G
    if (I->getOffset() <= SLocOffset) {
863
201M
      FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
864
      // Remember it.  We have good locality across FileID lookups.
865
201M
      LastFileIDLookup = Res;
866
201M
      NumLinearScans += NumProbes+1;
867
201M
      return Res;
868
201M
    }
869
1.39G
    if (++NumProbes == 8)
870
132M
      break;
871
1.39G
  }
872
873
  // Convert "I" back into an index.  We know that it is an entry whose index is
874
  // larger than the offset we are looking for.
875
132M
  unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
876
  // LessIndex - This is the lower bound of the range that we're searching.
877
  // We know that the offset corresponding to the FileID is is less than
878
  // SLocOffset.
879
132M
  unsigned LessIndex = 0;
880
132M
  NumProbes = 0;
881
1.84G
  while (true) {
882
1.84G
    unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
883
1.84G
    unsigned MidOffset = getLocalSLocEntry(MiddleIndex).getOffset();
884
885
1.84G
    ++NumProbes;
886
887
    // If the offset of the midpoint is too large, chop the high side of the
888
    // range to the midpoint.
889
1.84G
    if (MidOffset > SLocOffset) {
890
756M
      GreaterIndex = MiddleIndex;
891
756M
      continue;
892
756M
    }
893
894
    // If the middle index contains the value, succeed and return.
895
1.09G
    if (MiddleIndex + 1 == LocalSLocEntryTable.size() ||
896
1.09G
        SLocOffset < getLocalSLocEntry(MiddleIndex + 1).getOffset()) {
897
132M
      FileID Res = FileID::get(MiddleIndex);
898
899
      // Remember it.  We have good locality across FileID lookups.
900
132M
      LastFileIDLookup = Res;
901
132M
      NumBinaryProbes += NumProbes;
902
132M
      return Res;
903
132M
    }
904
905
    // Otherwise, move the low-side up to the middle index.
906
960M
    LessIndex = MiddleIndex;
907
960M
  }
908
132M
}
909
910
/// Return the FileID for a SourceLocation with a high offset.
911
///
912
/// This function knows that the SourceLocation is in a loaded buffer, not a
913
/// local one.
914
5.31M
FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
915
  // Sanity checking, otherwise a bug may lead to hanging in release build.
916
5.31M
  if (SLocOffset < CurrentLoadedOffset) {
917
0
    assert(0 && "Invalid SLocOffset or bad function choice");
918
0
    return FileID();
919
0
  }
920
921
  // Essentially the same as the local case, but the loaded array is sorted
922
  // in the other direction.
923
924
  // First do a linear scan from the last lookup position, if possible.
925
5.31M
  unsigned I;
926
5.31M
  int LastID = LastFileIDLookup.ID;
927
5.31M
  if (LastID >= 0 || 
getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset3.86M
)
928
3.44M
    I = 0;
929
1.87M
  else
930
1.87M
    I = (-LastID - 2) + 1;
931
932
5.31M
  unsigned NumProbes;
933
45.9M
  for (NumProbes = 0; NumProbes < 8; 
++NumProbes, ++I40.6M
) {
934
    // Make sure the entry is loaded!
935
40.8M
    const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
936
40.8M
    if (E.getOffset() <= SLocOffset) {
937
266k
      FileID Res = FileID::get(-int(I) - 2);
938
266k
      LastFileIDLookup = Res;
939
266k
      NumLinearScans += NumProbes + 1;
940
266k
      return Res;
941
266k
    }
942
40.8M
  }
943
944
  // Linear scan failed. Do the binary search. Note the reverse sorting of the
945
  // table: GreaterIndex is the one where the offset is greater, which is
946
  // actually a lower index!
947
5.05M
  unsigned GreaterIndex = I;
948
5.05M
  unsigned LessIndex = LoadedSLocEntryTable.size();
949
5.05M
  NumProbes = 0;
950
76.9M
  while (true) {
951
76.9M
    ++NumProbes;
952
76.9M
    unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
953
76.9M
    const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
954
76.9M
    if (E.getOffset() == 0)
955
0
      return FileID(); // invalid entry.
956
957
76.9M
    ++NumProbes;
958
959
76.9M
    if (E.getOffset() > SLocOffset) {
960
      // Sanity checking, otherwise a bug may lead to hanging in release build.
961
31.0M
      if (GreaterIndex == MiddleIndex) {
962
0
        assert(0 && "binary search missed the entry");
963
0
        return FileID();
964
0
      }
965
31.0M
      GreaterIndex = MiddleIndex;
966
31.0M
      continue;
967
31.0M
    }
968
969
45.8M
    if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
970
5.05M
      FileID Res = FileID::get(-int(MiddleIndex) - 2);
971
5.05M
      LastFileIDLookup = Res;
972
5.05M
      NumBinaryProbes += NumProbes;
973
5.05M
      return Res;
974
5.05M
    }
975
976
    // Sanity checking, otherwise a bug may lead to hanging in release build.
977
40.8M
    if (LessIndex == MiddleIndex) {
978
0
      assert(0 && "binary search missed the entry");
979
0
      return FileID();
980
0
    }
981
40.8M
    LessIndex = MiddleIndex;
982
40.8M
  }
983
5.05M
}
984
985
SourceLocation SourceManager::
986
10.5M
getExpansionLocSlowCase(SourceLocation Loc) const {
987
18.2M
  do {
988
    // Note: If Loc indicates an offset into a token that came from a macro
989
    // expansion (e.g. the 5th character of the token) we do not want to add
990
    // this offset when going to the expansion location.  The expansion
991
    // location is the macro invocation, which the offset has nothing to do
992
    // with.  This is unlike when we get the spelling loc, because the offset
993
    // directly correspond to the token whose spelling we're inspecting.
994
18.2M
    Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
995
18.2M
  } while (!Loc.isFileID());
996
997
10.5M
  return Loc;
998
10.5M
}
999
1000
59.0M
SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
1001
59.1M
  do {
1002
59.1M
    std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
1003
59.1M
    Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
1004
59.1M
    Loc = Loc.getLocWithOffset(LocInfo.second);
1005
59.1M
  } while (!Loc.isFileID());
1006
59.0M
  return Loc;
1007
59.0M
}
1008
1009
20.4k
SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
1010
104k
  do {
1011
104k
    if (isMacroArgExpansion(Loc))
1012
24.4k
      Loc = getImmediateSpellingLoc(Loc);
1013
80.3k
    else
1014
80.3k
      Loc = getImmediateExpansionRange(Loc).getBegin();
1015
104k
  } while (!Loc.isFileID());
1016
20.4k
  return Loc;
1017
20.4k
}
1018
1019
1020
std::pair<FileID, unsigned>
1021
SourceManager::getDecomposedExpansionLocSlowCase(
1022
305k
                                             const SrcMgr::SLocEntry *E) const {
1023
  // If this is an expansion record, walk through all the expansion points.
1024
305k
  FileID FID;
1025
305k
  SourceLocation Loc;
1026
305k
  unsigned Offset;
1027
649k
  do {
1028
649k
    Loc = E->getExpansion().getExpansionLocStart();
1029
1030
649k
    FID = getFileID(Loc);
1031
649k
    E = &getSLocEntry(FID);
1032
649k
    Offset = Loc.getOffset()-E->getOffset();
1033
649k
  } while (!Loc.isFileID());
1034
1035
305k
  return std::make_pair(FID, Offset);
1036
305k
}
1037
1038
std::pair<FileID, unsigned>
1039
SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
1040
1.22M
                                                unsigned Offset) const {
1041
  // If this is an expansion record, walk through all the expansion points.
1042
1.22M
  FileID FID;
1043
1.22M
  SourceLocation Loc;
1044
1.32M
  do {
1045
1.32M
    Loc = E->getExpansion().getSpellingLoc();
1046
1.32M
    Loc = Loc.getLocWithOffset(Offset);
1047
1048
1.32M
    FID = getFileID(Loc);
1049
1.32M
    E = &getSLocEntry(FID);
1050
1.32M
    Offset = Loc.getOffset()-E->getOffset();
1051
1.32M
  } while (!Loc.isFileID());
1052
1053
1.22M
  return std::make_pair(FID, Offset);
1054
1.22M
}
1055
1056
/// getImmediateSpellingLoc - Given a SourceLocation object, return the
1057
/// spelling location referenced by the ID.  This is the first level down
1058
/// towards the place where the characters that make up the lexed token can be
1059
/// found.  This should not generally be used by clients.
1060
39.4k
SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
1061
39.4k
  if (Loc.isFileID()) 
return Loc0
;
1062
39.4k
  std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
1063
39.4k
  Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
1064
39.4k
  return Loc.getLocWithOffset(LocInfo.second);
1065
39.4k
}
1066
1067
/// Return the filename of the file containing a SourceLocation.
1068
173k
StringRef SourceManager::getFilename(SourceLocation SpellingLoc) const {
1069
173k
  if (const FileEntry *F = getFileEntryForID(getFileID(SpellingLoc)))
1070
173k
    return F->getName();
1071
151
  return StringRef();
1072
151
}
1073
1074
/// getImmediateExpansionRange - Loc is required to be an expansion location.
1075
/// Return the start/end of the expansion information.
1076
CharSourceRange
1077
31.4M
SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
1078
31.4M
  assert(Loc.isMacroID() && "Not a macro expansion loc!");
1079
31.4M
  const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
1080
31.4M
  return Expansion.getExpansionLocRange();
1081
31.4M
}
1082
1083
5.33k
SourceLocation SourceManager::getTopMacroCallerLoc(SourceLocation Loc) const {
1084
5.49k
  while (isMacroArgExpansion(Loc))
1085
160
    Loc = getImmediateSpellingLoc(Loc);
1086
5.33k
  return Loc;
1087
5.33k
}
1088
1089
/// getExpansionRange - Given a SourceLocation object, return the range of
1090
/// tokens covered by the expansion in the ultimate file.
1091
4.32M
CharSourceRange SourceManager::getExpansionRange(SourceLocation Loc) const {
1092
4.32M
  if (Loc.isFileID())
1093
7.31k
    return CharSourceRange(SourceRange(Loc, Loc), true);
1094
1095
4.31M
  CharSourceRange Res = getImmediateExpansionRange(Loc);
1096
1097
  // Fully resolve the start and end locations to their ultimate expansion
1098
  // points.
1099
9.27M
  while (!Res.getBegin().isFileID())
1100
4.96M
    Res.setBegin(getImmediateExpansionRange(Res.getBegin()).getBegin());
1101
8.14M
  while (!Res.getEnd().isFileID()) {
1102
3.82M
    CharSourceRange EndRange = getImmediateExpansionRange(Res.getEnd());
1103
3.82M
    Res.setEnd(EndRange.getEnd());
1104
3.82M
    Res.setTokenRange(EndRange.isTokenRange());
1105
3.82M
  }
1106
4.31M
  return Res;
1107
4.31M
}
1108
1109
bool SourceManager::isMacroArgExpansion(SourceLocation Loc,
1110
286k
                                        SourceLocation *StartLoc) const {
1111
286k
  if (!Loc.isMacroID()) 
return false143k
;
1112
1113
143k
  FileID FID = getFileID(Loc);
1114
143k
  const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1115
143k
  if (!Expansion.isMacroArgExpansion()) 
return false104k
;
1116
1117
38.8k
  if (StartLoc)
1118
238
    *StartLoc = Expansion.getExpansionLocStart();
1119
38.8k
  return true;
1120
38.8k
}
1121
1122
2.26M
bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const {
1123
2.26M
  if (!Loc.isMacroID()) 
return false2.13M
;
1124
1125
132k
  FileID FID = getFileID(Loc);
1126
132k
  const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1127
132k
  return Expansion.isMacroBodyExpansion();
1128
132k
}
1129
1130
bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
1131
41.7M
                                             SourceLocation *MacroBegin) const {
1132
41.7M
  assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1133
1134
41.7M
  std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);
1135
41.7M
  if (DecompLoc.second > 0)
1136
12.4M
    return false; // Does not point at the start of expansion range.
1137
1138
29.2M
  bool Invalid = false;
1139
29.2M
  const SrcMgr::ExpansionInfo &ExpInfo =
1140
29.2M
      getSLocEntry(DecompLoc.first, &Invalid).getExpansion();
1141
29.2M
  if (Invalid)
1142
0
    return false;
1143
29.2M
  SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();
1144
1145
29.2M
  if (ExpInfo.isMacroArgExpansion()) {
1146
    // For macro argument expansions, check if the previous FileID is part of
1147
    // the same argument expansion, in which case this Loc is not at the
1148
    // beginning of the expansion.
1149
2.92M
    FileID PrevFID = getPreviousFileID(DecompLoc.first);
1150
2.92M
    if (!PrevFID.isInvalid()) {
1151
2.92M
      const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);
1152
2.92M
      if (Invalid)
1153
0
        return false;
1154
2.92M
      if (PrevEntry.isExpansion() &&
1155
2.92M
          PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)
1156
5.16k
        return false;
1157
29.2M
    }
1158
2.92M
  }
1159
1160
29.2M
  if (MacroBegin)
1161
29.2M
    *MacroBegin = ExpLoc;
1162
29.2M
  return true;
1163
29.2M
}
1164
1165
bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
1166
35.9M
                                               SourceLocation *MacroEnd) const {
1167
35.9M
  assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1168
1169
35.9M
  FileID FID = getFileID(Loc);
1170
35.9M
  SourceLocation NextLoc = Loc.getLocWithOffset(1);
1171
35.9M
  if (isInFileID(NextLoc, FID))
1172
5.13M
    return false; // Does not point at the end of expansion range.
1173
1174
30.7M
  bool Invalid = false;
1175
30.7M
  const SrcMgr::ExpansionInfo &ExpInfo =
1176
30.7M
      getSLocEntry(FID, &Invalid).getExpansion();
1177
30.7M
  if (Invalid)
1178
0
    return false;
1179
1180
30.7M
  if (ExpInfo.isMacroArgExpansion()) {
1181
    // For macro argument expansions, check if the next FileID is part of the
1182
    // same argument expansion, in which case this Loc is not at the end of the
1183
    // expansion.
1184
44.3k
    FileID NextFID = getNextFileID(FID);
1185
44.3k
    if (!NextFID.isInvalid()) {
1186
44.2k
      const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);
1187
44.2k
      if (Invalid)
1188
0
        return false;
1189
44.2k
      if (NextEntry.isExpansion() &&
1190
44.2k
          NextEntry.getExpansion().getExpansionLocStart() ==
1191
44.2k
              ExpInfo.getExpansionLocStart())
1192
44.1k
        return false;
1193
30.7M
    }
1194
44.3k
  }
1195
1196
30.7M
  if (MacroEnd)
1197
30.7M
    *MacroEnd = ExpInfo.getExpansionLocEnd();
1198
30.7M
  return true;
1199
30.7M
}
1200
1201
//===----------------------------------------------------------------------===//
1202
// Queries about the code at a SourceLocation.
1203
//===----------------------------------------------------------------------===//
1204
1205
/// getCharacterData - Return a pointer to the start of the specified location
1206
/// in the appropriate MemoryBuffer.
1207
const char *SourceManager::getCharacterData(SourceLocation SL,
1208
12.8M
                                            bool *Invalid) const {
1209
  // Note that this is a hot function in the getSpelling() path, which is
1210
  // heavily used by -E mode.
1211
12.8M
  std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
1212
1213
  // Note that calling 'getBuffer()' may lazily page in a source file.
1214
12.8M
  bool CharDataInvalid = false;
1215
12.8M
  const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
1216
12.8M
  if (CharDataInvalid || 
!Entry.isFile()12.8M
) {
1217
4
    if (Invalid)
1218
0
      *Invalid = true;
1219
1220
4
    return "<<<<INVALID BUFFER>>>>";
1221
4
  }
1222
12.8M
  const llvm::MemoryBuffer *Buffer =
1223
12.8M
      Entry.getFile().getContentCache()->getBuffer(
1224
12.8M
          Diag, getFileManager(), SourceLocation(), &CharDataInvalid);
1225
12.8M
  if (Invalid)
1226
7.20M
    *Invalid = CharDataInvalid;
1227
12.8M
  return Buffer->getBufferStart() + (CharDataInvalid? 
00
: LocInfo.second);
1228
12.8M
}
1229
1230
/// getColumnNumber - Return the column # for the specified file position.
1231
/// this is significantly cheaper to compute than the line number.
1232
unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
1233
47.2M
                                        bool *Invalid) const {
1234
47.2M
  bool MyInvalid = false;
1235
47.2M
  const llvm::MemoryBuffer *MemBuf = getBuffer(FID, &MyInvalid);
1236
47.2M
  if (Invalid)
1237
46.8M
    *Invalid = MyInvalid;
1238
1239
47.2M
  if (MyInvalid)
1240
61
    return 1;
1241
1242
  // It is okay to request a position just past the end of the buffer.
1243
47.2M
  if (FilePos > MemBuf->getBufferSize()) {
1244
1
    if (Invalid)
1245
1
      *Invalid = true;
1246
1
    return 1;
1247
1
  }
1248
1249
47.2M
  const char *Buf = MemBuf->getBufferStart();
1250
  // See if we just calculated the line number for this FilePos and can use
1251
  // that to lookup the start of the line instead of searching for it.
1252
47.2M
  if (LastLineNoFileIDQuery == FID &&
1253
47.2M
      LastLineNoContentCache->SourceLineCache != nullptr &&
1254
47.2M
      LastLineNoResult < LastLineNoContentCache->NumLines) {
1255
47.0M
    unsigned *SourceLineCache = LastLineNoContentCache->SourceLineCache;
1256
47.0M
    unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
1257
47.0M
    unsigned LineEnd = SourceLineCache[LastLineNoResult];
1258
47.0M
    if (FilePos >= LineStart && 
FilePos < LineEnd47.0M
) {
1259
      // LineEnd is the LineStart of the next line.
1260
      // A line ends with separator LF or CR+LF on Windows.
1261
      // FilePos might point to the last separator,
1262
      // but we need a column number at most 1 + the last column.
1263
47.0M
      if (FilePos + 1 == LineEnd && 
FilePos > LineStart327k
) {
1264
320k
        if (Buf[FilePos - 1] == '\r' || Buf[FilePos - 1] == '\n')
1265
0
          --FilePos;
1266
320k
      }
1267
47.0M
      return FilePos - LineStart + 1;
1268
47.0M
    }
1269
176k
  }
1270
1271
176k
  unsigned LineStart = FilePos;
1272
34.5M
  while (LineStart && 
Buf[LineStart-1] != '\n'34.3M
&&
Buf[LineStart-1] != '\r'34.3M
)
1273
34.3M
    --LineStart;
1274
176k
  return FilePos-LineStart+1;
1275
176k
}
1276
1277
// isInvalid - Return the result of calling loc.isInvalid(), and
1278
// if Invalid is not null, set its value to same.
1279
template<typename LocType>
1280
10.5M
static bool isInvalid(LocType Loc, bool *Invalid) {
1281
10.5M
  bool MyInvalid = Loc.isInvalid();
1282
10.5M
  if (Invalid)
1283
277k
    *Invalid = MyInvalid;
1284
10.5M
  return MyInvalid;
1285
10.5M
}
SourceManager.cpp:bool isInvalid<clang::SourceLocation>(clang::SourceLocation, bool*)
Line
Count
Source
1280
8.06M
static bool isInvalid(LocType Loc, bool *Invalid) {
1281
8.06M
  bool MyInvalid = Loc.isInvalid();
1282
8.06M
  if (Invalid)
1283
276k
    *Invalid = MyInvalid;
1284
8.06M
  return MyInvalid;
1285
8.06M
}
SourceManager.cpp:bool isInvalid<clang::PresumedLoc>(clang::PresumedLoc, bool*)
Line
Count
Source
1280
2.51M
static bool isInvalid(LocType Loc, bool *Invalid) {
1281
2.51M
  bool MyInvalid = Loc.isInvalid();
1282
2.51M
  if (Invalid)
1283
1.83k
    *Invalid = MyInvalid;
1284
2.51M
  return MyInvalid;
1285
2.51M
}
1286
1287
unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
1288
141k
                                                bool *Invalid) const {
1289
141k
  if (isInvalid(Loc, Invalid)) 
return 0224
;
1290
141k
  std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1291
141k
  return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1292
141k
}
1293
1294
unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
1295
86.7k
                                                 bool *Invalid) const {
1296
86.7k
  if (isInvalid(Loc, Invalid)) 
return 00
;
1297
86.7k
  std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1298
86.7k
  return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1299
86.7k
}
1300
1301
unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
1302
900
                                                bool *Invalid) const {
1303
900
  PresumedLoc PLoc = getPresumedLoc(Loc);
1304
900
  if (isInvalid(PLoc, Invalid)) 
return 00
;
1305
900
  return PLoc.getColumn();
1306
900
}
1307
1308
#ifdef __SSE2__
1309
#include <emmintrin.h>
1310
#endif
1311
1312
static LLVM_ATTRIBUTE_NOINLINE void
1313
ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
1314
                   llvm::BumpPtrAllocator &Alloc,
1315
                   const SourceManager &SM, bool &Invalid);
1316
static void ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
1317
                               llvm::BumpPtrAllocator &Alloc,
1318
252k
                               const SourceManager &SM, bool &Invalid) {
1319
  // Note that calling 'getBuffer()' may lazily page in the file.
1320
252k
  const MemoryBuffer *Buffer =
1321
252k
      FI->getBuffer(Diag, SM.getFileManager(), SourceLocation(), &Invalid);
1322
252k
  if (Invalid)
1323
0
    return;
1324
1325
  // Find the file offsets of all of the *physical* source lines.  This does
1326
  // not look at trigraphs, escaped newlines, or anything else tricky.
1327
252k
  SmallVector<unsigned, 256> LineOffsets;
1328
1329
  // Line #1 starts at char 0.
1330
252k
  LineOffsets.push_back(0);
1331
1332
252k
  const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
1333
252k
  const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
1334
252k
  const std::size_t BufLen = End - Buf;
1335
252k
  unsigned I = 0;
1336
7.31G
  while (I < BufLen) {
1337
7.31G
    if (Buf[I] == '\n') {
1338
163M
      LineOffsets.push_back(I + 1);
1339
7.15G
    } else if (Buf[I] == '\r') {
1340
      // If this is \r\n, skip both characters.
1341
6.04k
      if (I + 1 < BufLen && Buf[I + 1] == '\n')
1342
6.04k
        ++I;
1343
6.04k
      LineOffsets.push_back(I + 1);
1344
6.04k
    }
1345
7.31G
    ++I;
1346
7.31G
  }
1347
1348
  // Copy the offsets into the FileInfo structure.
1349
252k
  FI->NumLines = LineOffsets.size();
1350
252k
  FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
1351
252k
  std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
1352
252k
}
1353
1354
/// getLineNumber - Given a SourceLocation, return the spelling line number
1355
/// for the position indicated.  This requires building and caching a table of
1356
/// line offsets for the MemoryBuffer, so this is not cheap: use only when
1357
/// about to emit a diagnostic.
1358
unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1359
63.9M
                                      bool *Invalid) const {
1360
63.9M
  if (FID.isInvalid()) {
1361
50
    if (Invalid)
1362
0
      *Invalid = true;
1363
50
    return 1;
1364
50
  }
1365
1366
63.9M
  ContentCache *Content;
1367
63.9M
  if (LastLineNoFileIDQuery == FID)
1368
61.3M
    Content = LastLineNoContentCache;
1369
2.54M
  else {
1370
2.54M
    bool MyInvalid = false;
1371
2.54M
    const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1372
2.54M
    if (MyInvalid || !Entry.isFile()) {
1373
9
      if (Invalid)
1374
0
        *Invalid = true;
1375
9
      return 1;
1376
9
    }
1377
1378
2.54M
    Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
1379
2.54M
  }
1380
1381
  // If this is the first use of line information for this buffer, compute the
1382
  /// SourceLineCache for it on demand.
1383
63.9M
  if (!Content->SourceLineCache) {
1384
252k
    bool MyInvalid = false;
1385
252k
    ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
1386
252k
    if (Invalid)
1387
234k
      *Invalid = MyInvalid;
1388
252k
    if (MyInvalid)
1389
0
      return 1;
1390
63.6M
  } else if (Invalid)
1391
46.4M
    *Invalid = false;
1392
1393
  // Okay, we know we have a line number table.  Do a binary search to find the
1394
  // line number that this character position lands on.
1395
63.9M
  unsigned *SourceLineCache = Content->SourceLineCache;
1396
63.9M
  unsigned *SourceLineCacheStart = SourceLineCache;
1397
63.9M
  unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
1398
1399
63.9M
  unsigned QueriedFilePos = FilePos+1;
1400
1401
  // FIXME: I would like to be convinced that this code is worth being as
1402
  // complicated as it is, binary search isn't that slow.
1403
  //
1404
  // If it is worth being optimized, then in my opinion it could be more
1405
  // performant, simpler, and more obviously correct by just "galloping" outward
1406
  // from the queried file position. In fact, this could be incorporated into a
1407
  // generic algorithm such as lower_bound_with_hint.
1408
  //
1409
  // If someone gives me a test case where this matters, and I will do it! - DWD
1410
1411
  // If the previous query was to the same file, we know both the file pos from
1412
  // that query and the line number returned.  This allows us to narrow the
1413
  // search space from the entire file to something near the match.
1414
63.9M
  if (LastLineNoFileIDQuery == FID) {
1415
61.3M
    if (QueriedFilePos >= LastLineNoFilePos) {
1416
      // FIXME: Potential overflow?
1417
39.0M
      SourceLineCache = SourceLineCache+LastLineNoResult-1;
1418
1419
      // The query is likely to be nearby the previous one.  Here we check to
1420
      // see if it is within 5, 10 or 20 lines.  It can be far away in cases
1421
      // where big comment blocks and vertical whitespace eat up lines but
1422
      // contribute no tokens.
1423
39.0M
      if (SourceLineCache+5 < SourceLineCacheEnd) {
1424
38.5M
        if (SourceLineCache[5] > QueriedFilePos)
1425
17.1M
          SourceLineCacheEnd = SourceLineCache+5;
1426
21.4M
        else if (SourceLineCache+10 < SourceLineCacheEnd) {
1427
21.4M
          if (SourceLineCache[10] > QueriedFilePos)
1428
693k
            SourceLineCacheEnd = SourceLineCache+10;
1429
20.7M
          else if (SourceLineCache+20 < SourceLineCacheEnd) {
1430
20.7M
            if (SourceLineCache[20] > QueriedFilePos)
1431
445k
              SourceLineCacheEnd = SourceLineCache+20;
1432
20.7M
          }
1433
21.4M
        }
1434
38.5M
      }
1435
22.2M
    } else {
1436
22.2M
      if (LastLineNoResult < Content->NumLines)
1437
22.2M
        SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
1438
22.2M
    }
1439
61.3M
  }
1440
1441
63.9M
  unsigned *Pos
1442
63.9M
    = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
1443
63.9M
  unsigned LineNo = Pos-SourceLineCacheStart;
1444
1445
63.9M
  LastLineNoFileIDQuery = FID;
1446
63.9M
  LastLineNoContentCache = Content;
1447
63.9M
  LastLineNoFilePos = QueriedFilePos;
1448
63.9M
  LastLineNoResult = LineNo;
1449
63.9M
  return LineNo;
1450
63.9M
}
1451
1452
unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1453
160k
                                              bool *Invalid) const {
1454
160k
  if (isInvalid(Loc, Invalid)) 
return 01.05k
;
1455
159k
  std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1456
159k
  return getLineNumber(LocInfo.first, LocInfo.second);
1457
159k
}
1458
unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
1459
3.12M
                                               bool *Invalid) const {
1460
3.12M
  if (isInvalid(Loc, Invalid)) 
return 00
;
1461
3.12M
  std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1462
3.12M
  return getLineNumber(LocInfo.first, LocInfo.second);
1463
3.12M
}
1464
unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
1465
2.51M
                                              bool *Invalid) const {
1466
2.51M
  PresumedLoc PLoc = getPresumedLoc(Loc);
1467
2.51M
  if (isInvalid(PLoc, Invalid)) 
return 0145
;
1468
2.51M
  return PLoc.getLine();
1469
2.51M
}
1470
1471
/// getFileCharacteristic - return the file characteristic of the specified
1472
/// source location, indicating whether this is a normal file, a system
1473
/// header, or an "implicit extern C" system header.
1474
///
1475
/// This state can be modified with flags on GNU linemarker directives like:
1476
///   # 4 "foo.h" 3
1477
/// which changes all source locations in the current file after that to be
1478
/// considered to be from a system header.
1479
SrcMgr::CharacteristicKind
1480
139M
SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1481
139M
  assert(Loc.isValid() && "Can't get file characteristic of invalid loc!");
1482
139M
  std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1483
139M
  bool Invalid = false;
1484
139M
  const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
1485
139M
  if (Invalid || 
!SEntry.isFile()139M
)
1486
5
    return C_User;
1487
1488
139M
  const SrcMgr::FileInfo &FI = SEntry.getFile();
1489
1490
  // If there are no #line directives in this file, just return the whole-file
1491
  // state.
1492
139M
  if (!FI.hasLineDirectives())
1493
106M
    return FI.getFileCharacteristic();
1494
1495
33.2M
  assert(LineTable && "Can't have linetable entries without a LineTable!");
1496
  // See if there is a #line directive before the location.
1497
33.2M
  const LineEntry *Entry =
1498
33.2M
    LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
1499
1500
  // If this is before the first line marker, use the file characteristic.
1501
33.2M
  if (!Entry)
1502
568k
    return FI.getFileCharacteristic();
1503
1504
32.6M
  return Entry->FileKind;
1505
32.6M
}
1506
1507
/// Return the filename or buffer identifier of the buffer the location is in.
1508
/// Note that this name does not respect \#line directives.  Use getPresumedLoc
1509
/// for normal clients.
1510
StringRef SourceManager::getBufferName(SourceLocation Loc,
1511
4.55M
                                       bool *Invalid) const {
1512
4.55M
  if (isInvalid(Loc, Invalid)) 
return "<invalid loc>"849
;
1513
1514
4.55M
  return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
1515
4.55M
}
1516
1517
/// getPresumedLoc - This method returns the "presumed" location of a
1518
/// SourceLocation specifies.  A "presumed location" can be modified by \#line
1519
/// or GNU line marker directives.  This provides a view on the data that a
1520
/// user should see in diagnostics, for example.
1521
///
1522
/// Note that a presumed location is always given as the expansion point of an
1523
/// expansion location, not at the spelling location.
1524
PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc,
1525
46.7M
                                          bool UseLineDirectives) const {
1526
46.7M
  if (Loc.isInvalid()) 
return PresumedLoc()25.1k
;
1527
1528
  // Presumed locations are always for expansion points.
1529
46.7M
  std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1530
1531
46.7M
  bool Invalid = false;
1532
46.7M
  const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1533
46.7M
  if (Invalid || 
!Entry.isFile()46.7M
)
1534
4
    return PresumedLoc();
1535
1536
46.7M
  const SrcMgr::FileInfo &FI = Entry.getFile();
1537
46.7M
  const SrcMgr::ContentCache *C = FI.getContentCache();
1538
1539
  // To get the source name, first consult the FileEntry (if one exists)
1540
  // before the MemBuffer as this will avoid unnecessarily paging in the
1541
  // MemBuffer.
1542
46.7M
  FileID FID = LocInfo.first;
1543
46.7M
  StringRef Filename;
1544
46.7M
  if (C->OrigEntry)
1545
46.6M
    Filename = C->OrigEntry->getName();
1546
101k
  else
1547
101k
    Filename = C->getBuffer(Diag, getFileManager())->getBufferIdentifier();
1548
1549
46.7M
  unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1550
46.7M
  if (Invalid)
1551
0
    return PresumedLoc();
1552
46.7M
  unsigned ColNo  = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1553
46.7M
  if (Invalid)
1554
0
    return PresumedLoc();
1555
1556
46.7M
  SourceLocation IncludeLoc = FI.getIncludeLoc();
1557
1558
  // If we have #line directives in this file, update and overwrite the physical
1559
  // location info if appropriate.
1560
46.7M
  if (UseLineDirectives && 
FI.hasLineDirectives()46.7M
) {
1561
13.5M
    assert(LineTable && "Can't have linetable entries without a LineTable!");
1562
    // See if there is a #line directive before this.  If so, get it.
1563
13.5M
    if (const LineEntry *Entry =
1564
13.5M
          LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
1565
      // If the LineEntry indicates a filename, use it.
1566
13.5M
      if (Entry->FilenameID != -1) {
1567
13.5M
        Filename = LineTable->getFilename(Entry->FilenameID);
1568
        // The contents of files referenced by #line are not in the
1569
        // SourceManager
1570
13.5M
        FID = FileID::get(0);
1571
13.5M
      }
1572
1573
      // Use the line number specified by the LineEntry.  This line number may
1574
      // be multiple lines down from the line entry.  Add the difference in
1575
      // physical line numbers from the query point and the line marker to the
1576
      // total.
1577
13.5M
      unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1578
13.5M
      LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
1579
1580
      // Note that column numbers are not molested by line markers.
1581
1582
      // Handle virtual #include manipulation.
1583
13.5M
      if (Entry->IncludeOffset) {
1584
83.2k
        IncludeLoc = getLocForStartOfFile(LocInfo.first);
1585
83.2k
        IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
1586
83.2k
      }
1587
13.5M
    }
1588
13.5M
  }
1589
1590
46.7M
  return PresumedLoc(Filename.data(), FID, LineNo, ColNo, IncludeLoc);
1591
46.7M
}
1592
1593
/// Returns whether the PresumedLoc for a given SourceLocation is
1594
/// in the main file.
1595
///
1596
/// This computes the "presumed" location for a SourceLocation, then checks
1597
/// whether it came from a file other than the main file. This is different
1598
/// from isWrittenInMainFile() because it takes line marker directives into
1599
/// account.
1600
65.3M
bool SourceManager::isInMainFile(SourceLocation Loc) const {
1601
65.3M
  if (Loc.isInvalid()) 
return false297
;
1602
1603
  // Presumed locations are always for expansion points.
1604
65.3M
  std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1605
1606
65.3M
  bool Invalid = false;
1607
65.3M
  const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1608
65.3M
  if (Invalid || 
!Entry.isFile()65.3M
)
1609
2
    return false;
1610
1611
65.3M
  const SrcMgr::FileInfo &FI = Entry.getFile();
1612
1613
  // Check if there is a line directive for this location.
1614
65.3M
  if (FI.hasLineDirectives())
1615
28.6M
    if (const LineEntry *Entry =
1616
28.6M
            LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
1617
28.6M
      if (Entry->IncludeOffset)
1618
315k
        return false;
1619
1620
65.0M
  return FI.getIncludeLoc().isInvalid();
1621
65.0M
}
1622
1623
/// The size of the SLocEntry that \p FID represents.
1624
115k
unsigned SourceManager::getFileIDSize(FileID FID) const {
1625
115k
  bool Invalid = false;
1626
115k
  const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1627
115k
  if (Invalid)
1628
0
    return 0;
1629
1630
115k
  int ID = FID.ID;
1631
115k
  unsigned NextOffset;
1632
115k
  if ((ID > 0 && 
unsigned(ID+1) == local_sloc_entry_size()68.9k
))
1633
46.3k
    NextOffset = getNextLocalOffset();
1634
69.0k
  else if (ID+1 == -1)
1635
7
    NextOffset = MaxLoadedOffset;
1636
69.0k
  else
1637
69.0k
    NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
1638
1639
115k
  return NextOffset - Entry.getOffset() - 1;
1640
115k
}
1641
1642
//===----------------------------------------------------------------------===//
1643
// Other miscellaneous methods.
1644
//===----------------------------------------------------------------------===//
1645
1646
/// Get the source location for the given file:line:col triplet.
1647
///
1648
/// If the source file is included multiple times, the source location will
1649
/// be based upon an arbitrary inclusion.
1650
SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
1651
                                                  unsigned Line,
1652
11.3k
                                                  unsigned Col) const {
1653
11.3k
  assert(SourceFile && "Null source file!");
1654
11.3k
  assert(Line && Col && "Line and column should start from 1!");
1655
1656
11.3k
  FileID FirstFID = translateFile(SourceFile);
1657
11.3k
  return translateLineCol(FirstFID, Line, Col);
1658
11.3k
}
1659
1660
/// Get the FileID for the given file.
1661
///
1662
/// If the source file is included multiple times, the FileID will be the
1663
/// first inclusion.
1664
58.7k
FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
1665
58.7k
  assert(SourceFile && "Null source file!");
1666
1667
  // First, check the main file ID, since it is common to look for a
1668
  // location in the main file.
1669
58.7k
  if (MainFileID.isValid()) {
1670
13.6k
    bool Invalid = false;
1671
13.6k
    const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1672
13.6k
    if (Invalid)
1673
0
      return FileID();
1674
1675
13.6k
    if (MainSLoc.isFile()) {
1676
13.6k
      const ContentCache *MainContentCache =
1677
13.6k
          MainSLoc.getFile().getContentCache();
1678
13.6k
      if (MainContentCache && MainContentCache->OrigEntry == SourceFile)
1679
9.74k
        return MainFileID;
1680
48.9k
    }
1681
13.6k
  }
1682
1683
  // The location we're looking for isn't in the main file; look
1684
  // through all of the local source locations.
1685
1.83M
  
for (unsigned I = 0, N = local_sloc_entry_size(); 48.9k
I != N;
++I1.78M
) {
1686
1.82M
    const SLocEntry &SLoc = getLocalSLocEntry(I);
1687
1.82M
    if (SLoc.isFile() && 
SLoc.getFile().getContentCache()107k
&&
1688
107k
        SLoc.getFile().getContentCache()->OrigEntry == SourceFile)
1689
46.7k
      return FileID::get(I);
1690
1.82M
  }
1691
1692
  // If that still didn't help, try the modules.
1693
129k
  
for (unsigned I = 0, N = loaded_sloc_entry_size(); 2.17k
I != N;
++I127k
) {
1694
129k
    const SLocEntry &SLoc = getLoadedSLocEntry(I);
1695
129k
    if (SLoc.isFile() && 
SLoc.getFile().getContentCache()8.95k
&&
1696
8.95k
        SLoc.getFile().getContentCache()->OrigEntry == SourceFile)
1697
2.06k
      return FileID::get(-int(I) - 2);
1698
129k
  }
1699
1700
113
  return FileID();
1701
2.17k
}
1702
1703
/// Get the source location in \arg FID for the given line:col.
1704
/// Returns null location if \arg FID is not a file SLocEntry.
1705
SourceLocation SourceManager::translateLineCol(FileID FID,
1706
                                               unsigned Line,
1707
93.8k
                                               unsigned Col) const {
1708
  // Lines are used as a one-based index into a zero-based array. This assert
1709
  // checks for possible buffer underruns.
1710
93.8k
  assert(Line && Col && "Line and column should start from 1!");
1711
1712
93.8k
  if (FID.isInvalid())
1713
0
    return SourceLocation();
1714
1715
93.8k
  bool Invalid = false;
1716
93.8k
  const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1717
93.8k
  if (Invalid)
1718
0
    return SourceLocation();
1719
1720
93.8k
  if (!Entry.isFile())
1721
0
    return SourceLocation();
1722
1723
93.8k
  SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
1724
1725
93.8k
  if (Line == 1 && 
Col == 13.70k
)
1726
3.40k
    return FileLoc;
1727
1728
90.4k
  ContentCache *Content
1729
90.4k
    = const_cast<ContentCache *>(Entry.getFile().getContentCache());
1730
90.4k
  if (!Content)
1731
0
    return SourceLocation();
1732
1733
  // If this is the first use of line information for this buffer, compute the
1734
  // SourceLineCache for it on demand.
1735
90.4k
  if (!Content->SourceLineCache) {
1736
546
    bool MyInvalid = false;
1737
546
    ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
1738
546
    if (MyInvalid)
1739
0
      return SourceLocation();
1740
90.4k
  }
1741
1742
90.4k
  if (Line > Content->NumLines) {
1743
3
    unsigned Size = Content->getBuffer(Diag, getFileManager())->getBufferSize();
1744
3
    if (Size > 0)
1745
3
      --Size;
1746
3
    return FileLoc.getLocWithOffset(Size);
1747
3
  }
1748
1749
90.4k
  const llvm::MemoryBuffer *Buffer = Content->getBuffer(Diag, getFileManager());
1750
90.4k
  unsigned FilePos = Content->SourceLineCache[Line - 1];
1751
90.4k
  const char *Buf = Buffer->getBufferStart() + FilePos;
1752
90.4k
  unsigned BufLength = Buffer->getBufferSize() - FilePos;
1753
90.4k
  if (BufLength == 0)
1754
29
    return FileLoc.getLocWithOffset(FilePos);
1755
1756
90.3k
  unsigned i = 0;
1757
1758
  // Check that the given column is valid.
1759
350k
  while (i < BufLength-1 && 
i < Col-1350k
&&
Buf[i] != '\n'260k
&&
Buf[i] != '\r'260k
)
1760
260k
    ++i;
1761
90.3k
  return FileLoc.getLocWithOffset(FilePos + i);
1762
90.3k
}
1763
1764
/// Compute a map of macro argument chunks to their expanded source
1765
/// location. Chunks that are not part of a macro argument will map to an
1766
/// invalid source location. e.g. if a file contains one macro argument at
1767
/// offset 100 with length 10, this is how the map will be formed:
1768
///     0   -> SourceLocation()
1769
///     100 -> Expanded macro arg location
1770
///     110 -> SourceLocation()
1771
void SourceManager::computeMacroArgsCache(MacroArgsMap &MacroArgsCache,
1772
274
                                          FileID FID) const {
1773
274
  assert(FID.isValid());
1774
1775
  // Initially no macro argument chunk is present.
1776
274
  MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
1777
1778
274
  int ID = FID.ID;
1779
1.58k
  while (true) {
1780
1.58k
    ++ID;
1781
    // Stop if there are no more FileIDs to check.
1782
1.58k
    if (ID > 0) {
1783
1.43k
      if (unsigned(ID) >= local_sloc_entry_size())
1784
208
        return;
1785
145
    } else if (ID == -1) {
1786
37
      return;
1787
37
    }
1788
1789
1.33k
    bool Invalid = false;
1790
1.33k
    const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);
1791
1.33k
    if (Invalid)
1792
0
      return;
1793
1.33k
    if (Entry.isFile()) {
1794
402
      SourceLocation IncludeLoc = Entry.getFile().getIncludeLoc();
1795
402
      bool IncludedInFID =
1796
402
          (IncludeLoc.isValid() && 
isInFileID(IncludeLoc, FID)106
) ||
1797
          // Predefined header doesn't have a valid include location in main
1798
          // file, but any files created by it should still be skipped when
1799
          // computing macro args expanded in the main file.
1800
324
          (FID == MainFileID && 
Entry.getFile().Filename == "<built-in>"276
);
1801
402
      if (IncludedInFID) {
1802
        // Skip the files/macros of the #include'd file, we only care about
1803
        // macros that lexed macro arguments from our file.
1804
284
        if (Entry.getFile().NumCreatedFIDs)
1805
281
          ID += Entry.getFile().NumCreatedFIDs - 1 /*because of next ++ID*/;
1806
284
        continue;
1807
118
      } else if (IncludeLoc.isValid()) {
1808
        // If file was included but not from FID, there is no more files/macros
1809
        // that may be "contained" in this file.
1810
28
        return;
1811
28
      }
1812
90
      continue;
1813
90
    }
1814
1815
934
    const ExpansionInfo &ExpInfo = Entry.getExpansion();
1816
1817
934
    if (ExpInfo.getExpansionLocStart().isFileID()) {
1818
364
      if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
1819
1
        return; // No more files/macros that may be "contained" in this file.
1820
933
    }
1821
1822
933
    if (!ExpInfo.isMacroArgExpansion())
1823
430
      continue;
1824
1825
503
    associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1826
503
                                 ExpInfo.getSpellingLoc(),
1827
503
                                 SourceLocation::getMacroLoc(Entry.getOffset()),
1828
503
                                 getFileIDSize(FileID::get(ID)));
1829
503
  }
1830
274
}
1831
1832
void SourceManager::associateFileChunkWithMacroArgExp(
1833
                                         MacroArgsMap &MacroArgsCache,
1834
                                         FileID FID,
1835
                                         SourceLocation SpellLoc,
1836
                                         SourceLocation ExpansionLoc,
1837
546
                                         unsigned ExpansionLength) const {
1838
546
  if (!SpellLoc.isFileID()) {
1839
48
    unsigned SpellBeginOffs = SpellLoc.getOffset();
1840
48
    unsigned SpellEndOffs = SpellBeginOffs + ExpansionLength;
1841
1842
    // The spelling range for this macro argument expansion can span multiple
1843
    // consecutive FileID entries. Go through each entry contained in the
1844
    // spelling range and if one is itself a macro argument expansion, recurse
1845
    // and associate the file chunk that it represents.
1846
1847
48
    FileID SpellFID; // Current FileID in the spelling range.
1848
48
    unsigned SpellRelativeOffs;
1849
48
    std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);
1850
48
    while (true) {
1851
48
      const SLocEntry &Entry = getSLocEntry(SpellFID);
1852
48
      unsigned SpellFIDBeginOffs = Entry.getOffset();
1853
48
      unsigned SpellFIDSize = getFileIDSize(SpellFID);
1854
48
      unsigned SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;
1855
48
      const ExpansionInfo &Info = Entry.getExpansion();
1856
48
      if (Info.isMacroArgExpansion()) {
1857
43
        unsigned CurrSpellLength;
1858
43
        if (SpellFIDEndOffs < SpellEndOffs)
1859
0
          CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
1860
43
        else
1861
43
          CurrSpellLength = ExpansionLength;
1862
43
        associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1863
43
                      Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),
1864
43
                      ExpansionLoc, CurrSpellLength);
1865
43
      }
1866
1867
48
      if (SpellFIDEndOffs >= SpellEndOffs)
1868
48
        return; // we covered all FileID entries in the spelling range.
1869
1870
      // Move to the next FileID entry in the spelling range.
1871
0
      unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
1872
0
      ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);
1873
0
      ExpansionLength -= advance;
1874
0
      ++SpellFID.ID;
1875
0
      SpellRelativeOffs = 0;
1876
0
    }
1877
48
  }
1878
1879
498
  assert(SpellLoc.isFileID());
1880
1881
498
  unsigned BeginOffs;
1882
498
  if (!isInFileID(SpellLoc, FID, &BeginOffs))
1883
0
    return;
1884
1885
498
  unsigned EndOffs = BeginOffs + ExpansionLength;
1886
1887
  // Add a new chunk for this macro argument. A previous macro argument chunk
1888
  // may have been lexed again, so e.g. if the map is
1889
  //     0   -> SourceLocation()
1890
  //     100 -> Expanded loc #1
1891
  //     110 -> SourceLocation()
1892
  // and we found a new macro FileID that lexed from offset 105 with length 3,
1893
  // the new map will be:
1894
  //     0   -> SourceLocation()
1895
  //     100 -> Expanded loc #1
1896
  //     105 -> Expanded loc #2
1897
  //     108 -> Expanded loc #1
1898
  //     110 -> SourceLocation()
1899
  //
1900
  // Since re-lexed macro chunks will always be the same size or less of
1901
  // previous chunks, we only need to find where the ending of the new macro
1902
  // chunk is mapped to and update the map with new begin/end mappings.
1903
1904
498
  MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
1905
498
  --I;
1906
498
  SourceLocation EndOffsMappedLoc = I->second;
1907
498
  MacroArgsCache[BeginOffs] = ExpansionLoc;
1908
498
  MacroArgsCache[EndOffs] = EndOffsMappedLoc;
1909
498
}
1910
1911
/// If \arg Loc points inside a function macro argument, the returned
1912
/// location will be the macro location in which the argument was expanded.
1913
/// If a macro argument is used multiple times, the expanded location will
1914
/// be at the first expansion of the argument.
1915
/// e.g.
1916
///   MY_MACRO(foo);
1917
///             ^
1918
/// Passing a file location pointing at 'foo', will yield a macro location
1919
/// where 'foo' was expanded into.
1920
SourceLocation
1921
9.93k
SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
1922
9.93k
  if (Loc.isInvalid() || !Loc.isFileID())
1923
0
    return Loc;
1924
1925
9.93k
  FileID FID;
1926
9.93k
  unsigned Offset;
1927
9.93k
  std::tie(FID, Offset) = getDecomposedLoc(Loc);
1928
9.93k
  if (FID.isInvalid())
1929
0
    return Loc;
1930
1931
9.93k
  std::unique_ptr<MacroArgsMap> &MacroArgsCache = MacroArgsCacheMap[FID];
1932
9.93k
  if (!MacroArgsCache) {
1933
274
    MacroArgsCache = std::make_unique<MacroArgsMap>();
1934
274
    computeMacroArgsCache(*MacroArgsCache, FID);
1935
274
  }
1936
1937
9.93k
  assert(!MacroArgsCache->empty());
1938
9.93k
  MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
1939
  // In case every element in MacroArgsCache is greater than Offset we can't
1940
  // decrement the iterator.
1941
9.93k
  if (I == MacroArgsCache->begin())
1942
0
    return Loc;
1943
1944
9.93k
  --I;
1945
1946
9.93k
  unsigned MacroArgBeginOffs = I->first;
1947
9.93k
  SourceLocation MacroArgExpandedLoc = I->second;
1948
9.93k
  if (MacroArgExpandedLoc.isValid())
1949
129
    return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
1950
1951
9.80k
  return Loc;
1952
9.80k
}
1953
1954
std::pair<FileID, unsigned>
1955
3.24M
SourceManager::getDecomposedIncludedLoc(FileID FID) const {
1956
3.24M
  if (FID.isInvalid())
1957
0
    return std::make_pair(FileID(), 0);
1958
1959
  // Uses IncludedLocMap to retrieve/cache the decomposed loc.
1960
1961
3.24M
  using DecompTy = std::pair<FileID, unsigned>;
1962
3.24M
  auto InsertOp = IncludedLocMap.try_emplace(FID);
1963
3.24M
  DecompTy &DecompLoc = InsertOp.first->second;
1964
3.24M
  if (!InsertOp.second)
1965
256k
    return DecompLoc; // already in map.
1966
1967
2.99M
  SourceLocation UpperLoc;
1968
2.99M
  bool Invalid = false;
1969
2.99M
  const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1970
2.99M
  if (!Invalid) {
1971
2.99M
    if (Entry.isExpansion())
1972
2.68M
      UpperLoc = Entry.getExpansion().getExpansionLocStart();
1973
304k
    else
1974
304k
      UpperLoc = Entry.getFile().getIncludeLoc();
1975
2.99M
  }
1976
1977
2.99M
  if (UpperLoc.isValid())
1978
2.98M
    DecompLoc = getDecomposedLoc(UpperLoc);
1979
1980
2.99M
  return DecompLoc;
1981
2.99M
}
1982
1983
/// Given a decomposed source location, move it up the include/expansion stack
1984
/// to the parent source location.  If this is possible, return the decomposed
1985
/// version of the parent in Loc and return false.  If Loc is the top-level
1986
/// entry, return true and don't modify it.
1987
static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1988
260k
                                   const SourceManager &SM) {
1989
260k
  std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
1990
260k
  if (UpperLoc.first.isInvalid())
1991
242k
    return true; // We reached the top.
1992
1993
17.2k
  Loc = UpperLoc;
1994
17.2k
  return false;
1995
17.2k
}
1996
1997
/// Return the cache entry for comparing the given file IDs
1998
/// for isBeforeInTranslationUnit.
1999
InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
2000
139k
                                                            FileID RFID) const {
2001
  // This is a magic number for limiting the cache size.  It was experimentally
2002
  // derived from a small Objective-C project (where the cache filled
2003
  // out to ~250 items).  We can make it larger if necessary.
2004
139k
  enum { MagicCacheSize = 300 };
2005
139k
  IsBeforeInTUCacheKey Key(LFID, RFID);
2006
2007
  // If the cache size isn't too large, do a lookup and if necessary default
2008
  // construct an entry.  We can then return it to the caller for direct
2009
  // use.  When they update the value, the cache will get automatically
2010
  // updated as well.
2011
139k
  if (IBTUCache.size() < MagicCacheSize)
2012
139k
    return IBTUCache[Key];
2013
2014
  // Otherwise, do a lookup that will not construct a new value.
2015
173
  InBeforeInTUCache::iterator I = IBTUCache.find(Key);
2016
173
  if (I != IBTUCache.end())
2017
59
    return I->second;
2018
2019
  // Fall back to the overflow value.
2020
114
  return IBTUCacheOverflow;
2021
114
}
2022
2023
/// Determines the order of 2 source locations in the translation unit.
2024
///
2025
/// \returns true if LHS source location comes before RHS, false otherwise.
2026
bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
2027
26.7M
                                              SourceLocation RHS) const {
2028
26.7M
  assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
2029
26.7M
  if (LHS == RHS)
2030
138k
    return false;
2031
2032
26.6M
  std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
2033
26.6M
  std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
2034
2035
  // getDecomposedLoc may have failed to return a valid FileID because, e.g. it
2036
  // is a serialized one referring to a file that was removed after we loaded
2037
  // the PCH.
2038
26.6M
  if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
2039
0
    return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
2040
2041
26.6M
  std::pair<bool, bool> InSameTU = isInTheSameTranslationUnit(LOffs, ROffs);
2042
26.6M
  if (InSameTU.first)
2043
26.4M
    return InSameTU.second;
2044
2045
  // If we arrived here, the location is either in a built-ins buffer or
2046
  // associated with global inline asm. PR5662 and PR22576 are examples.
2047
2048
120k
  StringRef LB = getBuffer(LOffs.first)->getBufferIdentifier();
2049
120k
  StringRef RB = getBuffer(ROffs.first)->getBufferIdentifier();
2050
120k
  bool LIsBuiltins = LB == "<built-in>";
2051
120k
  bool RIsBuiltins = RB == "<built-in>";
2052
  // Sort built-in before non-built-in.
2053
120k
  if (LIsBuiltins || 
RIsBuiltins7.93k
) {
2054
120k
    if (LIsBuiltins != RIsBuiltins)
2055
120k
      return LIsBuiltins;
2056
    // Both are in built-in buffers, but from different files. We just claim that
2057
    // lower IDs come first.
2058
0
    return LOffs.first < ROffs.first;
2059
0
  }
2060
0
  bool LIsAsm = LB == "<inline asm>";
2061
0
  bool RIsAsm = RB == "<inline asm>";
2062
  // Sort assembler after built-ins, but before the rest.
2063
0
  if (LIsAsm || RIsAsm) {
2064
0
    if (LIsAsm != RIsAsm)
2065
0
      return RIsAsm;
2066
0
    assert(LOffs.first == ROffs.first);
2067
0
    return false;
2068
0
  }
2069
0
  bool LIsScratch = LB == "<scratch space>";
2070
0
  bool RIsScratch = RB == "<scratch space>";
2071
  // Sort scratch after inline asm, but before the rest.
2072
0
  if (LIsScratch || RIsScratch) {
2073
0
    if (LIsScratch != RIsScratch)
2074
0
      return LIsScratch;
2075
0
    return LOffs.second < ROffs.second;
2076
0
  }
2077
0
  llvm_unreachable("Unsortable locations found");
2078
0
}
2079
2080
std::pair<bool, bool> SourceManager::isInTheSameTranslationUnit(
2081
    std::pair<FileID, unsigned> &LOffs,
2082
26.7M
    std::pair<FileID, unsigned> &ROffs) const {
2083
  // If the source locations are in the same file, just compare offsets.
2084
26.7M
  if (LOffs.first == ROffs.first)
2085
26.5M
    return std::make_pair(true, LOffs.second < ROffs.second);
2086
2087
  // If we are comparing a source location with multiple locations in the same
2088
  // file, we get a big win by caching the result.
2089
139k
  InBeforeInTUCacheEntry &IsBeforeInTUCache =
2090
139k
    getInBeforeInTUCache(LOffs.first, ROffs.first);
2091
2092
  // If we are comparing a source location with multiple locations in the same
2093
  // file, we get a big win by caching the result.
2094
139k
  if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
2095
16.2k
    return std::make_pair(
2096
16.2k
        true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2097
2098
  // Okay, we missed in the cache, start updating the cache for this query.
2099
123k
  IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
2100
123k
                          /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID);
2101
2102
  // We need to find the common ancestor. The only way of doing this is to
2103
  // build the complete include chain for one and then walking up the chain
2104
  // of the other looking for a match.
2105
  // We use a map from FileID to Offset to store the chain. Easier than writing
2106
  // a custom set hash info that only depends on the first part of a pair.
2107
123k
  using LocSet = llvm::SmallDenseMap<FileID, unsigned, 16>;
2108
123k
  LocSet LChain;
2109
131k
  do {
2110
131k
    LChain.insert(LOffs);
2111
    // We catch the case where LOffs is in a file included by ROffs and
2112
    // quit early. The other way round unfortunately remains suboptimal.
2113
131k
  } while (LOffs.first != ROffs.first && 
!MoveUpIncludeHierarchy(LOffs, *this)130k
);
2114
123k
  LocSet::iterator I;
2115
132k
  while((I = LChain.find(ROffs.first)) == LChain.end()) {
2116
129k
    if (MoveUpIncludeHierarchy(ROffs, *this))
2117
120k
      break; // Met at topmost file.
2118
129k
  }
2119
123k
  if (I != LChain.end())
2120
3.37k
    LOffs = *I;
2121
2122
  // If we exited because we found a nearest common ancestor, compare the
2123
  // locations within the common file and cache them.
2124
123k
  if (LOffs.first == ROffs.first) {
2125
3.37k
    IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
2126
3.37k
    return std::make_pair(
2127
3.37k
        true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2128
3.37k
  }
2129
  // Clear the lookup cache, it depends on a common location.
2130
120k
  IsBeforeInTUCache.clear();
2131
120k
  return std::make_pair(false, false);
2132
120k
}
2133
2134
3
void SourceManager::PrintStats() const {
2135
3
  llvm::errs() << "\n*** Source Manager Stats:\n";
2136
3
  llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
2137
3
               << " mem buffers mapped.\n";
2138
3
  llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
2139
3
               << llvm::capacity_in_bytes(LocalSLocEntryTable)
2140
3
               << " bytes of capacity), "
2141
3
               << NextLocalOffset << "B of Sloc address space used.\n";
2142
3
  llvm::errs() << LoadedSLocEntryTable.size()
2143
3
               << " loaded SLocEntries allocated, "
2144
3
               << MaxLoadedOffset - CurrentLoadedOffset
2145
3
               << "B of Sloc address space used.\n";
2146
2147
3
  unsigned NumLineNumsComputed = 0;
2148
3
  unsigned NumFileBytesMapped = 0;
2149
9
  for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; 
++I6
){
2150
6
    NumLineNumsComputed += I->second->SourceLineCache != nullptr;
2151
6
    NumFileBytesMapped  += I->second->getSizeBytesMapped();
2152
6
  }
2153
3
  unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
2154
2155
3
  llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
2156
3
               << NumLineNumsComputed << " files with line #'s computed, "
2157
3
               << NumMacroArgsComputed << " files with macro args computed.\n";
2158
3
  llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
2159
3
               << NumBinaryProbes << " binary.\n";
2160
3
}
2161
2162
0
LLVM_DUMP_METHOD void SourceManager::dump() const {
2163
0
  llvm::raw_ostream &out = llvm::errs();
2164
2165
0
  auto DumpSLocEntry = [&](int ID, const SrcMgr::SLocEntry &Entry,
2166
0
                           llvm::Optional<unsigned> NextStart) {
2167
0
    out << "SLocEntry <FileID " << ID << "> " << (Entry.isFile() ? "file" : "expansion")
2168
0
        << " <SourceLocation " << Entry.getOffset() << ":";
2169
0
    if (NextStart)
2170
0
      out << *NextStart << ">\n";
2171
0
    else
2172
0
      out << "???\?>\n";
2173
0
    if (Entry.isFile()) {
2174
0
      auto &FI = Entry.getFile();
2175
0
      if (FI.NumCreatedFIDs)
2176
0
        out << "  covers <FileID " << ID << ":" << int(ID + FI.NumCreatedFIDs)
2177
0
            << ">\n";
2178
0
      if (FI.getIncludeLoc().isValid())
2179
0
        out << "  included from " << FI.getIncludeLoc().getOffset() << "\n";
2180
0
      if (auto *CC = FI.getContentCache()) {
2181
0
        out << "  for " << (CC->OrigEntry ? CC->OrigEntry->getName() : "<none>")
2182
0
            << "\n";
2183
0
        if (CC->BufferOverridden)
2184
0
          out << "  contents overridden\n";
2185
0
        if (CC->ContentsEntry != CC->OrigEntry) {
2186
0
          out << "  contents from "
2187
0
              << (CC->ContentsEntry ? CC->ContentsEntry->getName() : "<none>")
2188
0
              << "\n";
2189
0
        }
2190
0
      }
2191
0
    } else {
2192
0
      auto &EI = Entry.getExpansion();
2193
0
      out << "  spelling from " << EI.getSpellingLoc().getOffset() << "\n";
2194
0
      out << "  macro " << (EI.isMacroArgExpansion() ? "arg" : "body")
2195
0
          << " range <" << EI.getExpansionLocStart().getOffset() << ":"
2196
0
          << EI.getExpansionLocEnd().getOffset() << ">\n";
2197
0
    }
2198
0
  };
2199
2200
  // Dump local SLocEntries.
2201
0
  for (unsigned ID = 0, NumIDs = LocalSLocEntryTable.size(); ID != NumIDs; ++ID) {
2202
0
    DumpSLocEntry(ID, LocalSLocEntryTable[ID],
2203
0
                  ID == NumIDs - 1 ? NextLocalOffset
2204
0
                                   : LocalSLocEntryTable[ID + 1].getOffset());
2205
0
  }
2206
  // Dump loaded SLocEntries.
2207
0
  llvm::Optional<unsigned> NextStart;
2208
0
  for (unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
2209
0
    int ID = -(int)Index - 2;
2210
0
    if (SLocEntryLoaded[Index]) {
2211
0
      DumpSLocEntry(ID, LoadedSLocEntryTable[Index], NextStart);
2212
0
      NextStart = LoadedSLocEntryTable[Index].getOffset();
2213
0
    } else {
2214
0
      NextStart = None;
2215
0
    }
2216
0
  }
2217
0
}
2218
2219
11.2k
ExternalSLocEntrySource::~ExternalSLocEntrySource() = default;
2220
2221
/// Return the amount of memory used by memory buffers, breaking down
2222
/// by heap-backed versus mmap'ed memory.
2223
1
SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
2224
1
  size_t malloc_bytes = 0;
2225
1
  size_t mmap_bytes = 0;
2226
2227
2
  for (unsigned i = 0, e = MemBufferInfos.size(); i != e; 
++i1
)
2228
1
    if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
2229
1
      switch (MemBufferInfos[i]->getMemoryBufferKind()) {
2230
0
        case llvm::MemoryBuffer::MemoryBuffer_MMap:
2231
0
          mmap_bytes += sized_mapped;
2232
0
          break;
2233
1
        case llvm::MemoryBuffer::MemoryBuffer_Malloc:
2234
1
          malloc_bytes += sized_mapped;
2235
1
          break;
2236
1
      }
2237
2238
1
  return MemoryBufferSizes(malloc_bytes, mmap_bytes);
2239
1
}
2240
2241
1
size_t SourceManager::getDataStructureSizes() const {
2242
1
  size_t size = llvm::capacity_in_bytes(MemBufferInfos)
2243
1
    + llvm::capacity_in_bytes(LocalSLocEntryTable)
2244
1
    + llvm::capacity_in_bytes(LoadedSLocEntryTable)
2245
1
    + llvm::capacity_in_bytes(SLocEntryLoaded)
2246
1
    + llvm::capacity_in_bytes(FileInfos);
2247
2248
1
  if (OverriddenFilesInfo)
2249
0
    size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);
2250
2251
1
  return size;
2252
1
}
2253
2254
SourceManagerForFile::SourceManagerForFile(StringRef FileName,
2255
36.5k
                                           StringRef Content) {
2256
  // This is referenced by `FileMgr` and will be released by `FileMgr` when it
2257
  // is deleted.
2258
36.5k
  IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
2259
36.5k
      new llvm::vfs::InMemoryFileSystem);
2260
36.5k
  InMemoryFileSystem->addFile(
2261
36.5k
      FileName, 0,
2262
36.5k
      llvm::MemoryBuffer::getMemBuffer(Content, FileName,
2263
36.5k
                                       /*RequiresNullTerminator=*/false));
2264
  // This is passed to `SM` as reference, so the pointer has to be referenced
2265
  // in `Environment` so that `FileMgr` can out-live this function scope.
2266
36.5k
  FileMgr =
2267
36.5k
      std::make_unique<FileManager>(FileSystemOptions(), InMemoryFileSystem);
2268
  // This is passed to `SM` as reference, so the pointer has to be referenced
2269
  // by `Environment` due to the same reason above.
2270
36.5k
  Diagnostics = std::make_unique<DiagnosticsEngine>(
2271
36.5k
      IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
2272
36.5k
      new DiagnosticOptions);
2273
36.5k
  SourceMgr = std::make_unique<SourceManager>(*Diagnostics, *FileMgr);
2274
36.5k
  FileID ID = SourceMgr->createFileID(*FileMgr->getFile(FileName),
2275
36.5k
                                      SourceLocation(), clang::SrcMgr::C_User);
2276
36.5k
  assert(ID.isValid());
2277
36.5k
  SourceMgr->setMainFileID(ID);
2278
36.5k
}