Coverage Report

Created: 2024-01-17 10:31

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