Coverage Report

Created: 2024-01-17 10:31

/src/llvm-project/clang/lib/Frontend/ASTUnit.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- ASTUnit.cpp - ASTUnit utility --------------------------------------===//
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
// ASTUnit Implementation.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Frontend/ASTUnit.h"
14
#include "clang/AST/ASTConsumer.h"
15
#include "clang/AST/ASTContext.h"
16
#include "clang/AST/CommentCommandTraits.h"
17
#include "clang/AST/Decl.h"
18
#include "clang/AST/DeclBase.h"
19
#include "clang/AST/DeclCXX.h"
20
#include "clang/AST/DeclGroup.h"
21
#include "clang/AST/DeclObjC.h"
22
#include "clang/AST/DeclTemplate.h"
23
#include "clang/AST/DeclarationName.h"
24
#include "clang/AST/ExternalASTSource.h"
25
#include "clang/AST/PrettyPrinter.h"
26
#include "clang/AST/Type.h"
27
#include "clang/AST/TypeOrdering.h"
28
#include "clang/Basic/Diagnostic.h"
29
#include "clang/Basic/FileManager.h"
30
#include "clang/Basic/IdentifierTable.h"
31
#include "clang/Basic/LLVM.h"
32
#include "clang/Basic/LangOptions.h"
33
#include "clang/Basic/LangStandard.h"
34
#include "clang/Basic/Module.h"
35
#include "clang/Basic/SourceLocation.h"
36
#include "clang/Basic/SourceManager.h"
37
#include "clang/Basic/TargetInfo.h"
38
#include "clang/Basic/TargetOptions.h"
39
#include "clang/Frontend/CompilerInstance.h"
40
#include "clang/Frontend/CompilerInvocation.h"
41
#include "clang/Frontend/FrontendAction.h"
42
#include "clang/Frontend/FrontendActions.h"
43
#include "clang/Frontend/FrontendDiagnostic.h"
44
#include "clang/Frontend/FrontendOptions.h"
45
#include "clang/Frontend/MultiplexConsumer.h"
46
#include "clang/Frontend/PrecompiledPreamble.h"
47
#include "clang/Frontend/Utils.h"
48
#include "clang/Lex/HeaderSearch.h"
49
#include "clang/Lex/HeaderSearchOptions.h"
50
#include "clang/Lex/Lexer.h"
51
#include "clang/Lex/PPCallbacks.h"
52
#include "clang/Lex/PreprocessingRecord.h"
53
#include "clang/Lex/Preprocessor.h"
54
#include "clang/Lex/PreprocessorOptions.h"
55
#include "clang/Lex/Token.h"
56
#include "clang/Sema/CodeCompleteConsumer.h"
57
#include "clang/Sema/CodeCompleteOptions.h"
58
#include "clang/Sema/Sema.h"
59
#include "clang/Serialization/ASTBitCodes.h"
60
#include "clang/Serialization/ASTReader.h"
61
#include "clang/Serialization/ASTWriter.h"
62
#include "clang/Serialization/ContinuousRangeMap.h"
63
#include "clang/Serialization/InMemoryModuleCache.h"
64
#include "clang/Serialization/ModuleFile.h"
65
#include "clang/Serialization/PCHContainerOperations.h"
66
#include "llvm/ADT/ArrayRef.h"
67
#include "llvm/ADT/DenseMap.h"
68
#include "llvm/ADT/IntrusiveRefCntPtr.h"
69
#include "llvm/ADT/STLExtras.h"
70
#include "llvm/ADT/ScopeExit.h"
71
#include "llvm/ADT/SmallVector.h"
72
#include "llvm/ADT/StringMap.h"
73
#include "llvm/ADT/StringRef.h"
74
#include "llvm/ADT/StringSet.h"
75
#include "llvm/ADT/Twine.h"
76
#include "llvm/ADT/iterator_range.h"
77
#include "llvm/Bitstream/BitstreamWriter.h"
78
#include "llvm/Support/Allocator.h"
79
#include "llvm/Support/Casting.h"
80
#include "llvm/Support/CrashRecoveryContext.h"
81
#include "llvm/Support/DJB.h"
82
#include "llvm/Support/ErrorHandling.h"
83
#include "llvm/Support/ErrorOr.h"
84
#include "llvm/Support/FileSystem.h"
85
#include "llvm/Support/MemoryBuffer.h"
86
#include "llvm/Support/SaveAndRestore.h"
87
#include "llvm/Support/Timer.h"
88
#include "llvm/Support/VirtualFileSystem.h"
89
#include "llvm/Support/raw_ostream.h"
90
#include <algorithm>
91
#include <atomic>
92
#include <cassert>
93
#include <cstdint>
94
#include <cstdio>
95
#include <cstdlib>
96
#include <memory>
97
#include <mutex>
98
#include <optional>
99
#include <string>
100
#include <tuple>
101
#include <utility>
102
#include <vector>
103
104
using namespace clang;
105
106
using llvm::TimeRecord;
107
108
namespace {
109
110
  class SimpleTimer {
111
    bool WantTiming;
112
    TimeRecord Start;
113
    std::string Output;
114
115
  public:
116
0
    explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
117
0
      if (WantTiming)
118
0
        Start = TimeRecord::getCurrentTime();
119
0
    }
120
121
0
    ~SimpleTimer() {
122
0
      if (WantTiming) {
123
0
        TimeRecord Elapsed = TimeRecord::getCurrentTime();
124
0
        Elapsed -= Start;
125
0
        llvm::errs() << Output << ':';
126
0
        Elapsed.print(Elapsed, llvm::errs());
127
0
        llvm::errs() << '\n';
128
0
      }
129
0
    }
130
131
0
    void setOutput(const Twine &Output) {
132
0
      if (WantTiming)
133
0
        this->Output = Output.str();
134
0
    }
135
  };
136
137
} // namespace
138
139
template <class T>
140
0
static std::unique_ptr<T> valueOrNull(llvm::ErrorOr<std::unique_ptr<T>> Val) {
141
0
  if (!Val)
142
0
    return nullptr;
143
0
  return std::move(*Val);
144
0
}
145
146
template <class T>
147
static bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
148
  if (!Val)
149
    return false;
150
  Output = std::move(*Val);
151
  return true;
152
}
153
154
/// Get a source buffer for \p MainFilePath, handling all file-to-file
155
/// and file-to-buffer remappings inside \p Invocation.
156
static std::unique_ptr<llvm::MemoryBuffer>
157
getBufferForFileHandlingRemapping(const CompilerInvocation &Invocation,
158
                                  llvm::vfs::FileSystem *VFS,
159
0
                                  StringRef FilePath, bool isVolatile) {
160
0
  const auto &PreprocessorOpts = Invocation.getPreprocessorOpts();
161
162
  // Try to determine if the main file has been remapped, either from the
163
  // command line (to another file) or directly through the compiler
164
  // invocation (to a memory buffer).
165
0
  llvm::MemoryBuffer *Buffer = nullptr;
166
0
  std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
167
0
  auto FileStatus = VFS->status(FilePath);
168
0
  if (FileStatus) {
169
0
    llvm::sys::fs::UniqueID MainFileID = FileStatus->getUniqueID();
170
171
    // Check whether there is a file-file remapping of the main file
172
0
    for (const auto &RF : PreprocessorOpts.RemappedFiles) {
173
0
      std::string MPath(RF.first);
174
0
      auto MPathStatus = VFS->status(MPath);
175
0
      if (MPathStatus) {
176
0
        llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
177
0
        if (MainFileID == MID) {
178
          // We found a remapping. Try to load the resulting, remapped source.
179
0
          BufferOwner = valueOrNull(VFS->getBufferForFile(RF.second, -1, true, isVolatile));
180
0
          if (!BufferOwner)
181
0
            return nullptr;
182
0
        }
183
0
      }
184
0
    }
185
186
    // Check whether there is a file-buffer remapping. It supercedes the
187
    // file-file remapping.
188
0
    for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
189
0
      std::string MPath(RB.first);
190
0
      auto MPathStatus = VFS->status(MPath);
191
0
      if (MPathStatus) {
192
0
        llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
193
0
        if (MainFileID == MID) {
194
          // We found a remapping.
195
0
          BufferOwner.reset();
196
0
          Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
197
0
        }
198
0
      }
199
0
    }
200
0
  }
201
202
  // If the main source file was not remapped, load it now.
203
0
  if (!Buffer && !BufferOwner) {
204
0
    BufferOwner = valueOrNull(VFS->getBufferForFile(FilePath, -1, true, isVolatile));
205
0
    if (!BufferOwner)
206
0
      return nullptr;
207
0
  }
208
209
0
  if (BufferOwner)
210
0
    return BufferOwner;
211
0
  if (!Buffer)
212
0
    return nullptr;
213
0
  return llvm::MemoryBuffer::getMemBufferCopy(Buffer->getBuffer(), FilePath);
214
0
}
215
216
struct ASTUnit::ASTWriterData {
217
  SmallString<128> Buffer;
218
  llvm::BitstreamWriter Stream;
219
  ASTWriter Writer;
220
221
  ASTWriterData(InMemoryModuleCache &ModuleCache)
222
0
      : Stream(Buffer), Writer(Stream, Buffer, ModuleCache, {}) {}
223
};
224
225
0
void ASTUnit::clearFileLevelDecls() {
226
0
  FileDecls.clear();
227
0
}
228
229
/// After failing to build a precompiled preamble (due to
230
/// errors in the source that occurs in the preamble), the number of
231
/// reparses during which we'll skip even trying to precompile the
232
/// preamble.
233
const unsigned DefaultPreambleRebuildInterval = 5;
234
235
/// Tracks the number of ASTUnit objects that are currently active.
236
///
237
/// Used for debugging purposes only.
238
static std::atomic<unsigned> ActiveASTUnitObjects;
239
240
ASTUnit::ASTUnit(bool _MainFileIsAST)
241
    : MainFileIsAST(_MainFileIsAST), WantTiming(getenv("LIBCLANG_TIMING")),
242
      ShouldCacheCodeCompletionResults(false),
243
      IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
244
0
      UnsafeToFree(false) {
245
0
  if (getenv("LIBCLANG_OBJTRACKING"))
246
0
    fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
247
0
}
248
249
0
ASTUnit::~ASTUnit() {
250
  // If we loaded from an AST file, balance out the BeginSourceFile call.
251
0
  if (MainFileIsAST && getDiagnostics().getClient()) {
252
0
    getDiagnostics().getClient()->EndSourceFile();
253
0
  }
254
255
0
  clearFileLevelDecls();
256
257
  // Free the buffers associated with remapped files. We are required to
258
  // perform this operation here because we explicitly request that the
259
  // compiler instance *not* free these buffers for each invocation of the
260
  // parser.
261
0
  if (Invocation && OwnsRemappedFileBuffers) {
262
0
    PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
263
0
    for (const auto &RB : PPOpts.RemappedFileBuffers)
264
0
      delete RB.second;
265
0
  }
266
267
0
  ClearCachedCompletionResults();
268
269
0
  if (getenv("LIBCLANG_OBJTRACKING"))
270
0
    fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
271
0
}
272
273
0
void ASTUnit::setPreprocessor(std::shared_ptr<Preprocessor> PP) {
274
0
  this->PP = std::move(PP);
275
0
}
276
277
0
void ASTUnit::enableSourceFileDiagnostics() {
278
0
  assert(getDiagnostics().getClient() && Ctx &&
279
0
      "Bad context for source file");
280
0
  getDiagnostics().getClient()->BeginSourceFile(Ctx->getLangOpts(), PP.get());
281
0
}
282
283
/// Determine the set of code-completion contexts in which this
284
/// declaration should be shown.
285
static uint64_t getDeclShowContexts(const NamedDecl *ND,
286
                                    const LangOptions &LangOpts,
287
0
                                    bool &IsNestedNameSpecifier) {
288
0
  IsNestedNameSpecifier = false;
289
290
0
  if (isa<UsingShadowDecl>(ND))
291
0
    ND = ND->getUnderlyingDecl();
292
0
  if (!ND)
293
0
    return 0;
294
295
0
  uint64_t Contexts = 0;
296
0
  if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
297
0
      isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND) ||
298
0
      isa<TypeAliasTemplateDecl>(ND)) {
299
    // Types can appear in these contexts.
300
0
    if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
301
0
      Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
302
0
               |  (1LL << CodeCompletionContext::CCC_ObjCIvarList)
303
0
               |  (1LL << CodeCompletionContext::CCC_ClassStructUnion)
304
0
               |  (1LL << CodeCompletionContext::CCC_Statement)
305
0
               |  (1LL << CodeCompletionContext::CCC_Type)
306
0
               |  (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
307
308
    // In C++, types can appear in expressions contexts (for functional casts).
309
0
    if (LangOpts.CPlusPlus)
310
0
      Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
311
312
    // In Objective-C, message sends can send interfaces. In Objective-C++,
313
    // all types are available due to functional casts.
314
0
    if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
315
0
      Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
316
317
    // In Objective-C, you can only be a subclass of another Objective-C class
318
0
    if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
319
      // Objective-C interfaces can be used in a class property expression.
320
0
      if (ID->getDefinition())
321
0
        Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
322
0
      Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
323
0
      Contexts |= (1LL << CodeCompletionContext::CCC_ObjCClassForwardDecl);
324
0
    }
325
326
    // Deal with tag names.
327
0
    if (isa<EnumDecl>(ND)) {
328
0
      Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
329
330
      // Part of the nested-name-specifier in C++0x.
331
0
      if (LangOpts.CPlusPlus11)
332
0
        IsNestedNameSpecifier = true;
333
0
    } else if (const auto *Record = dyn_cast<RecordDecl>(ND)) {
334
0
      if (Record->isUnion())
335
0
        Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
336
0
      else
337
0
        Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
338
339
0
      if (LangOpts.CPlusPlus)
340
0
        IsNestedNameSpecifier = true;
341
0
    } else if (isa<ClassTemplateDecl>(ND))
342
0
      IsNestedNameSpecifier = true;
343
0
  } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
344
    // Values can appear in these contexts.
345
0
    Contexts = (1LL << CodeCompletionContext::CCC_Statement)
346
0
             | (1LL << CodeCompletionContext::CCC_Expression)
347
0
             | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
348
0
             | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
349
0
  } else if (isa<ObjCProtocolDecl>(ND)) {
350
0
    Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
351
0
  } else if (isa<ObjCCategoryDecl>(ND)) {
352
0
    Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
353
0
  } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
354
0
    Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
355
356
    // Part of the nested-name-specifier.
357
0
    IsNestedNameSpecifier = true;
358
0
  }
359
360
0
  return Contexts;
361
0
}
362
363
0
void ASTUnit::CacheCodeCompletionResults() {
364
0
  if (!TheSema)
365
0
    return;
366
367
0
  SimpleTimer Timer(WantTiming);
368
0
  Timer.setOutput("Cache global code completions for " + getMainFileName());
369
370
  // Clear out the previous results.
371
0
  ClearCachedCompletionResults();
372
373
  // Gather the set of global code completions.
374
0
  using Result = CodeCompletionResult;
375
0
  SmallVector<Result, 8> Results;
376
0
  CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
377
0
  CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
378
0
  TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
379
0
                                       CCTUInfo, Results);
380
381
  // Translate global code completions into cached completions.
382
0
  llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
383
0
  CodeCompletionContext CCContext(CodeCompletionContext::CCC_TopLevel);
384
385
0
  for (auto &R : Results) {
386
0
    switch (R.Kind) {
387
0
    case Result::RK_Declaration: {
388
0
      bool IsNestedNameSpecifier = false;
389
0
      CachedCodeCompletionResult CachedResult;
390
0
      CachedResult.Completion = R.CreateCodeCompletionString(
391
0
          *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
392
0
          IncludeBriefCommentsInCodeCompletion);
393
0
      CachedResult.ShowInContexts = getDeclShowContexts(
394
0
          R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
395
0
      CachedResult.Priority = R.Priority;
396
0
      CachedResult.Kind = R.CursorKind;
397
0
      CachedResult.Availability = R.Availability;
398
399
      // Keep track of the type of this completion in an ASTContext-agnostic
400
      // way.
401
0
      QualType UsageType = getDeclUsageType(*Ctx, R.Declaration);
402
0
      if (UsageType.isNull()) {
403
0
        CachedResult.TypeClass = STC_Void;
404
0
        CachedResult.Type = 0;
405
0
      } else {
406
0
        CanQualType CanUsageType
407
0
          = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
408
0
        CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
409
410
        // Determine whether we have already seen this type. If so, we save
411
        // ourselves the work of formatting the type string by using the
412
        // temporary, CanQualType-based hash table to find the associated value.
413
0
        unsigned &TypeValue = CompletionTypes[CanUsageType];
414
0
        if (TypeValue == 0) {
415
0
          TypeValue = CompletionTypes.size();
416
0
          CachedCompletionTypes[QualType(CanUsageType).getAsString()]
417
0
            = TypeValue;
418
0
        }
419
420
0
        CachedResult.Type = TypeValue;
421
0
      }
422
423
0
      CachedCompletionResults.push_back(CachedResult);
424
425
      /// Handle nested-name-specifiers in C++.
426
0
      if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
427
0
          !R.StartsNestedNameSpecifier) {
428
        // The contexts in which a nested-name-specifier can appear in C++.
429
0
        uint64_t NNSContexts
430
0
          = (1LL << CodeCompletionContext::CCC_TopLevel)
431
0
          | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
432
0
          | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
433
0
          | (1LL << CodeCompletionContext::CCC_Statement)
434
0
          | (1LL << CodeCompletionContext::CCC_Expression)
435
0
          | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
436
0
          | (1LL << CodeCompletionContext::CCC_EnumTag)
437
0
          | (1LL << CodeCompletionContext::CCC_UnionTag)
438
0
          | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
439
0
          | (1LL << CodeCompletionContext::CCC_Type)
440
0
          | (1LL << CodeCompletionContext::CCC_SymbolOrNewName)
441
0
          | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
442
443
0
        if (isa<NamespaceDecl>(R.Declaration) ||
444
0
            isa<NamespaceAliasDecl>(R.Declaration))
445
0
          NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
446
447
0
        if (uint64_t RemainingContexts
448
0
                                = NNSContexts & ~CachedResult.ShowInContexts) {
449
          // If there any contexts where this completion can be a
450
          // nested-name-specifier but isn't already an option, create a
451
          // nested-name-specifier completion.
452
0
          R.StartsNestedNameSpecifier = true;
453
0
          CachedResult.Completion = R.CreateCodeCompletionString(
454
0
              *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
455
0
              IncludeBriefCommentsInCodeCompletion);
456
0
          CachedResult.ShowInContexts = RemainingContexts;
457
0
          CachedResult.Priority = CCP_NestedNameSpecifier;
458
0
          CachedResult.TypeClass = STC_Void;
459
0
          CachedResult.Type = 0;
460
0
          CachedCompletionResults.push_back(CachedResult);
461
0
        }
462
0
      }
463
0
      break;
464
0
    }
465
466
0
    case Result::RK_Keyword:
467
0
    case Result::RK_Pattern:
468
      // Ignore keywords and patterns; we don't care, since they are so
469
      // easily regenerated.
470
0
      break;
471
472
0
    case Result::RK_Macro: {
473
0
      CachedCodeCompletionResult CachedResult;
474
0
      CachedResult.Completion = R.CreateCodeCompletionString(
475
0
          *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
476
0
          IncludeBriefCommentsInCodeCompletion);
477
0
      CachedResult.ShowInContexts
478
0
        = (1LL << CodeCompletionContext::CCC_TopLevel)
479
0
        | (1LL << CodeCompletionContext::CCC_ObjCInterface)
480
0
        | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
481
0
        | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
482
0
        | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
483
0
        | (1LL << CodeCompletionContext::CCC_Statement)
484
0
        | (1LL << CodeCompletionContext::CCC_Expression)
485
0
        | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
486
0
        | (1LL << CodeCompletionContext::CCC_MacroNameUse)
487
0
        | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
488
0
        | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
489
0
        | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
490
491
0
      CachedResult.Priority = R.Priority;
492
0
      CachedResult.Kind = R.CursorKind;
493
0
      CachedResult.Availability = R.Availability;
494
0
      CachedResult.TypeClass = STC_Void;
495
0
      CachedResult.Type = 0;
496
0
      CachedCompletionResults.push_back(CachedResult);
497
0
      break;
498
0
    }
499
0
    }
500
0
  }
501
502
  // Save the current top-level hash value.
503
0
  CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
504
0
}
505
506
0
void ASTUnit::ClearCachedCompletionResults() {
507
0
  CachedCompletionResults.clear();
508
0
  CachedCompletionTypes.clear();
509
0
  CachedCompletionAllocator = nullptr;
510
0
}
511
512
namespace {
513
514
/// Gathers information from ASTReader that will be used to initialize
515
/// a Preprocessor.
516
class ASTInfoCollector : public ASTReaderListener {
517
  Preprocessor &PP;
518
  ASTContext *Context;
519
  HeaderSearchOptions &HSOpts;
520
  PreprocessorOptions &PPOpts;
521
  LangOptions &LangOpt;
522
  std::shared_ptr<TargetOptions> &TargetOpts;
523
  IntrusiveRefCntPtr<TargetInfo> &Target;
524
  unsigned &Counter;
525
  bool InitializedLanguage = false;
526
  bool InitializedHeaderSearchPaths = false;
527
528
public:
529
  ASTInfoCollector(Preprocessor &PP, ASTContext *Context,
530
                   HeaderSearchOptions &HSOpts, PreprocessorOptions &PPOpts,
531
                   LangOptions &LangOpt,
532
                   std::shared_ptr<TargetOptions> &TargetOpts,
533
                   IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
534
      : PP(PP), Context(Context), HSOpts(HSOpts), PPOpts(PPOpts),
535
        LangOpt(LangOpt), TargetOpts(TargetOpts), Target(Target),
536
0
        Counter(Counter) {}
537
538
  bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
539
0
                           bool AllowCompatibleDifferences) override {
540
0
    if (InitializedLanguage)
541
0
      return false;
542
543
0
    LangOpt = LangOpts;
544
0
    InitializedLanguage = true;
545
546
0
    updated();
547
0
    return false;
548
0
  }
549
550
  bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
551
                               StringRef SpecificModuleCachePath,
552
0
                               bool Complain) override {
553
    // llvm::SaveAndRestore doesn't support bit field.
554
0
    auto ForceCheckCXX20ModulesInputFiles =
555
0
        this->HSOpts.ForceCheckCXX20ModulesInputFiles;
556
0
    llvm::SaveAndRestore X(this->HSOpts.UserEntries);
557
0
    llvm::SaveAndRestore Y(this->HSOpts.SystemHeaderPrefixes);
558
0
    llvm::SaveAndRestore Z(this->HSOpts.VFSOverlayFiles);
559
560
0
    this->HSOpts = HSOpts;
561
0
    this->HSOpts.ForceCheckCXX20ModulesInputFiles =
562
0
        ForceCheckCXX20ModulesInputFiles;
563
564
0
    return false;
565
0
  }
566
567
  bool ReadHeaderSearchPaths(const HeaderSearchOptions &HSOpts,
568
0
                             bool Complain) override {
569
0
    if (InitializedHeaderSearchPaths)
570
0
      return false;
571
572
0
    this->HSOpts.UserEntries = HSOpts.UserEntries;
573
0
    this->HSOpts.SystemHeaderPrefixes = HSOpts.SystemHeaderPrefixes;
574
0
    this->HSOpts.VFSOverlayFiles = HSOpts.VFSOverlayFiles;
575
576
    // Initialize the FileManager. We can't do this in update(), since that
577
    // performs the initialization too late (once both target and language
578
    // options are read).
579
0
    PP.getFileManager().setVirtualFileSystem(createVFSFromOverlayFiles(
580
0
        HSOpts.VFSOverlayFiles, PP.getDiagnostics(),
581
0
        PP.getFileManager().getVirtualFileSystemPtr()));
582
583
0
    InitializedHeaderSearchPaths = true;
584
585
0
    return false;
586
0
  }
587
588
  bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
589
                               bool ReadMacros, bool Complain,
590
0
                               std::string &SuggestedPredefines) override {
591
0
    this->PPOpts = PPOpts;
592
0
    return false;
593
0
  }
594
595
  bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
596
0
                         bool AllowCompatibleDifferences) override {
597
    // If we've already initialized the target, don't do it again.
598
0
    if (Target)
599
0
      return false;
600
601
0
    this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
602
0
    Target =
603
0
        TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
604
605
0
    updated();
606
0
    return false;
607
0
  }
608
609
  void ReadCounter(const serialization::ModuleFile &M,
610
0
                   unsigned Value) override {
611
0
    Counter = Value;
612
0
  }
613
614
private:
615
0
  void updated() {
616
0
    if (!Target || !InitializedLanguage)
617
0
      return;
618
619
    // Inform the target of the language options.
620
    //
621
    // FIXME: We shouldn't need to do this, the target should be immutable once
622
    // created. This complexity should be lifted elsewhere.
623
0
    Target->adjust(PP.getDiagnostics(), LangOpt);
624
625
    // Initialize the preprocessor.
626
0
    PP.Initialize(*Target);
627
628
0
    if (!Context)
629
0
      return;
630
631
    // Initialize the ASTContext
632
0
    Context->InitBuiltinTypes(*Target);
633
634
    // Adjust printing policy based on language options.
635
0
    Context->setPrintingPolicy(PrintingPolicy(LangOpt));
636
637
    // We didn't have access to the comment options when the ASTContext was
638
    // constructed, so register them now.
639
0
    Context->getCommentCommandTraits().registerCommentOptions(
640
0
        LangOpt.CommentOpts);
641
0
  }
642
};
643
644
/// Diagnostic consumer that saves each diagnostic it is given.
645
class FilterAndStoreDiagnosticConsumer : public DiagnosticConsumer {
646
  SmallVectorImpl<StoredDiagnostic> *StoredDiags;
647
  SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags;
648
  bool CaptureNonErrorsFromIncludes = true;
649
  const LangOptions *LangOpts = nullptr;
650
  SourceManager *SourceMgr = nullptr;
651
652
public:
653
  FilterAndStoreDiagnosticConsumer(
654
      SmallVectorImpl<StoredDiagnostic> *StoredDiags,
655
      SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags,
656
      bool CaptureNonErrorsFromIncludes)
657
      : StoredDiags(StoredDiags), StandaloneDiags(StandaloneDiags),
658
0
        CaptureNonErrorsFromIncludes(CaptureNonErrorsFromIncludes) {
659
0
    assert((StoredDiags || StandaloneDiags) &&
660
0
           "No output collections were passed to StoredDiagnosticConsumer.");
661
0
  }
662
663
  void BeginSourceFile(const LangOptions &LangOpts,
664
0
                       const Preprocessor *PP = nullptr) override {
665
0
    this->LangOpts = &LangOpts;
666
0
    if (PP)
667
0
      SourceMgr = &PP->getSourceManager();
668
0
  }
669
670
  void HandleDiagnostic(DiagnosticsEngine::Level Level,
671
                        const Diagnostic &Info) override;
672
};
673
674
/// RAII object that optionally captures and filters diagnostics, if
675
/// there is no diagnostic client to capture them already.
676
class CaptureDroppedDiagnostics {
677
  DiagnosticsEngine &Diags;
678
  FilterAndStoreDiagnosticConsumer Client;
679
  DiagnosticConsumer *PreviousClient = nullptr;
680
  std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
681
682
public:
683
  CaptureDroppedDiagnostics(
684
      CaptureDiagsKind CaptureDiagnostics, DiagnosticsEngine &Diags,
685
      SmallVectorImpl<StoredDiagnostic> *StoredDiags,
686
      SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags)
687
      : Diags(Diags),
688
        Client(StoredDiags, StandaloneDiags,
689
               CaptureDiagnostics !=
690
0
                   CaptureDiagsKind::AllWithoutNonErrorsFromIncludes) {
691
0
    if (CaptureDiagnostics != CaptureDiagsKind::None ||
692
0
        Diags.getClient() == nullptr) {
693
0
      OwningPreviousClient = Diags.takeClient();
694
0
      PreviousClient = Diags.getClient();
695
0
      Diags.setClient(&Client, false);
696
0
    }
697
0
  }
698
699
0
  ~CaptureDroppedDiagnostics() {
700
0
    if (Diags.getClient() == &Client)
701
0
      Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
702
0
  }
703
};
704
705
} // namespace
706
707
static ASTUnit::StandaloneDiagnostic
708
makeStandaloneDiagnostic(const LangOptions &LangOpts,
709
                         const StoredDiagnostic &InDiag);
710
711
0
static bool isInMainFile(const clang::Diagnostic &D) {
712
0
  if (!D.hasSourceManager() || !D.getLocation().isValid())
713
0
    return false;
714
715
0
  auto &M = D.getSourceManager();
716
0
  return M.isWrittenInMainFile(M.getExpansionLoc(D.getLocation()));
717
0
}
718
719
void FilterAndStoreDiagnosticConsumer::HandleDiagnostic(
720
0
    DiagnosticsEngine::Level Level, const Diagnostic &Info) {
721
  // Default implementation (Warnings/errors count).
722
0
  DiagnosticConsumer::HandleDiagnostic(Level, Info);
723
724
  // Only record the diagnostic if it's part of the source manager we know
725
  // about. This effectively drops diagnostics from modules we're building.
726
  // FIXME: In the long run, ee don't want to drop source managers from modules.
727
0
  if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr) {
728
0
    if (!CaptureNonErrorsFromIncludes && Level <= DiagnosticsEngine::Warning &&
729
0
        !isInMainFile(Info)) {
730
0
      return;
731
0
    }
732
733
0
    StoredDiagnostic *ResultDiag = nullptr;
734
0
    if (StoredDiags) {
735
0
      StoredDiags->emplace_back(Level, Info);
736
0
      ResultDiag = &StoredDiags->back();
737
0
    }
738
739
0
    if (StandaloneDiags) {
740
0
      std::optional<StoredDiagnostic> StoredDiag;
741
0
      if (!ResultDiag) {
742
0
        StoredDiag.emplace(Level, Info);
743
0
        ResultDiag = &*StoredDiag;
744
0
      }
745
0
      StandaloneDiags->push_back(
746
0
          makeStandaloneDiagnostic(*LangOpts, *ResultDiag));
747
0
    }
748
0
  }
749
0
}
750
751
0
IntrusiveRefCntPtr<ASTReader> ASTUnit::getASTReader() const {
752
0
  return Reader;
753
0
}
754
755
0
ASTMutationListener *ASTUnit::getASTMutationListener() {
756
0
  if (WriterData)
757
0
    return &WriterData->Writer;
758
0
  return nullptr;
759
0
}
760
761
0
ASTDeserializationListener *ASTUnit::getDeserializationListener() {
762
0
  if (WriterData)
763
0
    return &WriterData->Writer;
764
0
  return nullptr;
765
0
}
766
767
std::unique_ptr<llvm::MemoryBuffer>
768
0
ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
769
0
  assert(FileMgr);
770
0
  auto Buffer = FileMgr->getBufferForFile(Filename, UserFilesAreVolatile);
771
0
  if (Buffer)
772
0
    return std::move(*Buffer);
773
0
  if (ErrorStr)
774
0
    *ErrorStr = Buffer.getError().message();
775
0
  return nullptr;
776
0
}
777
778
/// Configure the diagnostics object for use with ASTUnit.
779
void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
780
                             ASTUnit &AST,
781
0
                             CaptureDiagsKind CaptureDiagnostics) {
782
0
  assert(Diags.get() && "no DiagnosticsEngine was provided");
783
0
  if (CaptureDiagnostics != CaptureDiagsKind::None)
784
0
    Diags->setClient(new FilterAndStoreDiagnosticConsumer(
785
0
        &AST.StoredDiagnostics, nullptr,
786
0
        CaptureDiagnostics != CaptureDiagsKind::AllWithoutNonErrorsFromIncludes));
787
0
}
788
789
std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
790
    const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
791
    WhatToLoad ToLoad, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
792
    const FileSystemOptions &FileSystemOpts,
793
    std::shared_ptr<HeaderSearchOptions> HSOpts, bool OnlyLocalDecls,
794
    CaptureDiagsKind CaptureDiagnostics, bool AllowASTWithCompilerErrors,
795
0
    bool UserFilesAreVolatile, IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
796
0
  std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
797
798
  // Recover resources if we crash before exiting this method.
799
0
  llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
800
0
    ASTUnitCleanup(AST.get());
801
0
  llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
802
0
    llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
803
0
    DiagCleanup(Diags.get());
804
805
0
  ConfigureDiags(Diags, *AST, CaptureDiagnostics);
806
807
0
  AST->LangOpts = std::make_shared<LangOptions>();
808
0
  AST->OnlyLocalDecls = OnlyLocalDecls;
809
0
  AST->CaptureDiagnostics = CaptureDiagnostics;
810
0
  AST->Diagnostics = Diags;
811
0
  AST->FileMgr = new FileManager(FileSystemOpts, VFS);
812
0
  AST->UserFilesAreVolatile = UserFilesAreVolatile;
813
0
  AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
814
0
                                     AST->getFileManager(),
815
0
                                     UserFilesAreVolatile);
816
0
  AST->ModuleCache = new InMemoryModuleCache;
817
0
  AST->HSOpts = HSOpts ? HSOpts : std::make_shared<HeaderSearchOptions>();
818
0
  AST->HSOpts->ModuleFormat = std::string(PCHContainerRdr.getFormats().front());
819
0
  AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
820
0
                                         AST->getSourceManager(),
821
0
                                         AST->getDiagnostics(),
822
0
                                         AST->getLangOpts(),
823
0
                                         /*Target=*/nullptr));
824
0
  AST->PPOpts = std::make_shared<PreprocessorOptions>();
825
826
  // Gather Info for preprocessor construction later on.
827
828
0
  HeaderSearch &HeaderInfo = *AST->HeaderInfo;
829
830
0
  AST->PP = std::make_shared<Preprocessor>(
831
0
      AST->PPOpts, AST->getDiagnostics(), *AST->LangOpts,
832
0
      AST->getSourceManager(), HeaderInfo, AST->ModuleLoader,
833
0
      /*IILookup=*/nullptr,
834
0
      /*OwnsHeaderSearch=*/false);
835
0
  Preprocessor &PP = *AST->PP;
836
837
0
  if (ToLoad >= LoadASTOnly)
838
0
    AST->Ctx = new ASTContext(*AST->LangOpts, AST->getSourceManager(),
839
0
                              PP.getIdentifierTable(), PP.getSelectorTable(),
840
0
                              PP.getBuiltinInfo(),
841
0
                              AST->getTranslationUnitKind());
842
843
0
  DisableValidationForModuleKind disableValid =
844
0
      DisableValidationForModuleKind::None;
845
0
  if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
846
0
    disableValid = DisableValidationForModuleKind::All;
847
0
  AST->Reader = new ASTReader(
848
0
      PP, *AST->ModuleCache, AST->Ctx.get(), PCHContainerRdr, {},
849
0
      /*isysroot=*/"",
850
0
      /*DisableValidationKind=*/disableValid, AllowASTWithCompilerErrors);
851
852
0
  unsigned Counter = 0;
853
0
  AST->Reader->setListener(std::make_unique<ASTInfoCollector>(
854
0
      *AST->PP, AST->Ctx.get(), *AST->HSOpts, *AST->PPOpts, *AST->LangOpts,
855
0
      AST->TargetOpts, AST->Target, Counter));
856
857
  // Attach the AST reader to the AST context as an external AST
858
  // source, so that declarations will be deserialized from the
859
  // AST file as needed.
860
  // We need the external source to be set up before we read the AST, because
861
  // eagerly-deserialized declarations may use it.
862
0
  if (AST->Ctx)
863
0
    AST->Ctx->setExternalSource(AST->Reader);
864
865
0
  switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
866
0
                               SourceLocation(), ASTReader::ARR_None)) {
867
0
  case ASTReader::Success:
868
0
    break;
869
870
0
  case ASTReader::Failure:
871
0
  case ASTReader::Missing:
872
0
  case ASTReader::OutOfDate:
873
0
  case ASTReader::VersionMismatch:
874
0
  case ASTReader::ConfigurationMismatch:
875
0
  case ASTReader::HadErrors:
876
0
    AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
877
0
    return nullptr;
878
0
  }
879
880
0
  AST->OriginalSourceFile = std::string(AST->Reader->getOriginalSourceFile());
881
882
0
  PP.setCounterValue(Counter);
883
884
0
  Module *M = HeaderInfo.lookupModule(AST->getLangOpts().CurrentModule);
885
0
  if (M && AST->getLangOpts().isCompilingModule() && M->isNamedModule())
886
0
    AST->Ctx->setCurrentNamedModule(M);
887
888
  // Create an AST consumer, even though it isn't used.
889
0
  if (ToLoad >= LoadASTOnly)
890
0
    AST->Consumer.reset(new ASTConsumer);
891
892
  // Create a semantic analysis object and tell the AST reader about it.
893
0
  if (ToLoad >= LoadEverything) {
894
0
    AST->TheSema.reset(new Sema(PP, *AST->Ctx, *AST->Consumer));
895
0
    AST->TheSema->Initialize();
896
0
    AST->Reader->InitializeSema(*AST->TheSema);
897
0
  }
898
899
  // Tell the diagnostic client that we have started a source file.
900
0
  AST->getDiagnostics().getClient()->BeginSourceFile(PP.getLangOpts(), &PP);
901
902
0
  return AST;
903
0
}
904
905
/// Add the given macro to the hash of all top-level entities.
906
0
static void AddDefinedMacroToHash(const Token &MacroNameTok, unsigned &Hash) {
907
0
  Hash = llvm::djbHash(MacroNameTok.getIdentifierInfo()->getName(), Hash);
908
0
}
909
910
namespace {
911
912
/// Preprocessor callback class that updates a hash value with the names
913
/// of all macros that have been defined by the translation unit.
914
class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
915
  unsigned &Hash;
916
917
public:
918
0
  explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) {}
919
920
  void MacroDefined(const Token &MacroNameTok,
921
0
                    const MacroDirective *MD) override {
922
0
    AddDefinedMacroToHash(MacroNameTok, Hash);
923
0
  }
924
};
925
926
} // namespace
927
928
/// Add the given declaration to the hash of all top-level entities.
929
0
static void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
930
0
  if (!D)
931
0
    return;
932
933
0
  DeclContext *DC = D->getDeclContext();
934
0
  if (!DC)
935
0
    return;
936
937
0
  if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
938
0
    return;
939
940
0
  if (const auto *ND = dyn_cast<NamedDecl>(D)) {
941
0
    if (const auto *EnumD = dyn_cast<EnumDecl>(D)) {
942
      // For an unscoped enum include the enumerators in the hash since they
943
      // enter the top-level namespace.
944
0
      if (!EnumD->isScoped()) {
945
0
        for (const auto *EI : EnumD->enumerators()) {
946
0
          if (EI->getIdentifier())
947
0
            Hash = llvm::djbHash(EI->getIdentifier()->getName(), Hash);
948
0
        }
949
0
      }
950
0
    }
951
952
0
    if (ND->getIdentifier())
953
0
      Hash = llvm::djbHash(ND->getIdentifier()->getName(), Hash);
954
0
    else if (DeclarationName Name = ND->getDeclName()) {
955
0
      std::string NameStr = Name.getAsString();
956
0
      Hash = llvm::djbHash(NameStr, Hash);
957
0
    }
958
0
    return;
959
0
  }
960
961
0
  if (const auto *ImportD = dyn_cast<ImportDecl>(D)) {
962
0
    if (const Module *Mod = ImportD->getImportedModule()) {
963
0
      std::string ModName = Mod->getFullModuleName();
964
0
      Hash = llvm::djbHash(ModName, Hash);
965
0
    }
966
0
    return;
967
0
  }
968
0
}
969
970
namespace {
971
972
class TopLevelDeclTrackerConsumer : public ASTConsumer {
973
  ASTUnit &Unit;
974
  unsigned &Hash;
975
976
public:
977
  TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
978
0
      : Unit(_Unit), Hash(Hash) {
979
0
    Hash = 0;
980
0
  }
981
982
0
  void handleTopLevelDecl(Decl *D) {
983
0
    if (!D)
984
0
      return;
985
986
    // FIXME: Currently ObjC method declarations are incorrectly being
987
    // reported as top-level declarations, even though their DeclContext
988
    // is the containing ObjC @interface/@implementation.  This is a
989
    // fundamental problem in the parser right now.
990
0
    if (isa<ObjCMethodDecl>(D))
991
0
      return;
992
993
0
    AddTopLevelDeclarationToHash(D, Hash);
994
0
    Unit.addTopLevelDecl(D);
995
996
0
    handleFileLevelDecl(D);
997
0
  }
998
999
0
  void handleFileLevelDecl(Decl *D) {
1000
0
    Unit.addFileLevelDecl(D);
1001
0
    if (auto *NSD = dyn_cast<NamespaceDecl>(D)) {
1002
0
      for (auto *I : NSD->decls())
1003
0
        handleFileLevelDecl(I);
1004
0
    }
1005
0
  }
1006
1007
0
  bool HandleTopLevelDecl(DeclGroupRef D) override {
1008
0
    for (auto *TopLevelDecl : D)
1009
0
      handleTopLevelDecl(TopLevelDecl);
1010
0
    return true;
1011
0
  }
1012
1013
  // We're not interested in "interesting" decls.
1014
0
  void HandleInterestingDecl(DeclGroupRef) override {}
1015
1016
0
  void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
1017
0
    for (auto *TopLevelDecl : D)
1018
0
      handleTopLevelDecl(TopLevelDecl);
1019
0
  }
1020
1021
0
  ASTMutationListener *GetASTMutationListener() override {
1022
0
    return Unit.getASTMutationListener();
1023
0
  }
1024
1025
0
  ASTDeserializationListener *GetASTDeserializationListener() override {
1026
0
    return Unit.getDeserializationListener();
1027
0
  }
1028
};
1029
1030
class TopLevelDeclTrackerAction : public ASTFrontendAction {
1031
public:
1032
  ASTUnit &Unit;
1033
1034
  std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
1035
0
                                                 StringRef InFile) override {
1036
0
    CI.getPreprocessor().addPPCallbacks(
1037
0
        std::make_unique<MacroDefinitionTrackerPPCallbacks>(
1038
0
                                           Unit.getCurrentTopLevelHashValue()));
1039
0
    return std::make_unique<TopLevelDeclTrackerConsumer>(
1040
0
        Unit, Unit.getCurrentTopLevelHashValue());
1041
0
  }
1042
1043
public:
1044
0
  TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
1045
1046
0
  bool hasCodeCompletionSupport() const override { return false; }
1047
1048
0
  TranslationUnitKind getTranslationUnitKind() override {
1049
0
    return Unit.getTranslationUnitKind();
1050
0
  }
1051
};
1052
1053
class ASTUnitPreambleCallbacks : public PreambleCallbacks {
1054
public:
1055
0
  unsigned getHash() const { return Hash; }
1056
1057
0
  std::vector<Decl *> takeTopLevelDecls() { return std::move(TopLevelDecls); }
1058
1059
0
  std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
1060
0
    return std::move(TopLevelDeclIDs);
1061
0
  }
1062
1063
0
  void AfterPCHEmitted(ASTWriter &Writer) override {
1064
0
    TopLevelDeclIDs.reserve(TopLevelDecls.size());
1065
0
    for (const auto *D : TopLevelDecls) {
1066
      // Invalid top-level decls may not have been serialized.
1067
0
      if (D->isInvalidDecl())
1068
0
        continue;
1069
0
      TopLevelDeclIDs.push_back(Writer.getDeclID(D));
1070
0
    }
1071
0
  }
1072
1073
0
  void HandleTopLevelDecl(DeclGroupRef DG) override {
1074
0
    for (auto *D : DG) {
1075
      // FIXME: Currently ObjC method declarations are incorrectly being
1076
      // reported as top-level declarations, even though their DeclContext
1077
      // is the containing ObjC @interface/@implementation.  This is a
1078
      // fundamental problem in the parser right now.
1079
0
      if (isa<ObjCMethodDecl>(D))
1080
0
        continue;
1081
0
      AddTopLevelDeclarationToHash(D, Hash);
1082
0
      TopLevelDecls.push_back(D);
1083
0
    }
1084
0
  }
1085
1086
0
  std::unique_ptr<PPCallbacks> createPPCallbacks() override {
1087
0
    return std::make_unique<MacroDefinitionTrackerPPCallbacks>(Hash);
1088
0
  }
1089
1090
private:
1091
  unsigned Hash = 0;
1092
  std::vector<Decl *> TopLevelDecls;
1093
  std::vector<serialization::DeclID> TopLevelDeclIDs;
1094
  llvm::SmallVector<ASTUnit::StandaloneDiagnostic, 4> PreambleDiags;
1095
};
1096
1097
} // namespace
1098
1099
0
static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
1100
0
  return StoredDiag.getLocation().isValid();
1101
0
}
1102
1103
static void
1104
0
checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
1105
  // Get rid of stored diagnostics except the ones from the driver which do not
1106
  // have a source location.
1107
0
  llvm::erase_if(StoredDiags, isNonDriverDiag);
1108
0
}
1109
1110
static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1111
                                                              StoredDiagnostics,
1112
0
                                  SourceManager &SM) {
1113
  // The stored diagnostic has the old source manager in it; update
1114
  // the locations to refer into the new source manager. Since we've
1115
  // been careful to make sure that the source manager's state
1116
  // before and after are identical, so that we can reuse the source
1117
  // location itself.
1118
0
  for (auto &SD : StoredDiagnostics) {
1119
0
    if (SD.getLocation().isValid()) {
1120
0
      FullSourceLoc Loc(SD.getLocation(), SM);
1121
0
      SD.setLocation(Loc);
1122
0
    }
1123
0
  }
1124
0
}
1125
1126
/// Parse the source file into a translation unit using the given compiler
1127
/// invocation, replacing the current translation unit.
1128
///
1129
/// \returns True if a failure occurred that causes the ASTUnit not to
1130
/// contain any translation-unit information, false otherwise.
1131
bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1132
                    std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer,
1133
0
                    IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
1134
0
  if (!Invocation)
1135
0
    return true;
1136
1137
0
  if (VFS && FileMgr)
1138
0
    assert(VFS == &FileMgr->getVirtualFileSystem() &&
1139
0
           "VFS passed to Parse and VFS in FileMgr are different");
1140
1141
0
  auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
1142
0
  if (OverrideMainBuffer) {
1143
0
    assert(Preamble &&
1144
0
           "No preamble was built, but OverrideMainBuffer is not null");
1145
0
    Preamble->AddImplicitPreamble(*CCInvocation, VFS, OverrideMainBuffer.get());
1146
    // VFS may have changed...
1147
0
  }
1148
1149
  // Create the compiler instance to use for building the AST.
1150
0
  std::unique_ptr<CompilerInstance> Clang(
1151
0
      new CompilerInstance(std::move(PCHContainerOps)));
1152
0
  Clang->setInvocation(CCInvocation);
1153
1154
  // Clean up on error, disengage it if the function returns successfully.
1155
0
  auto CleanOnError = llvm::make_scope_exit([&]() {
1156
    // Remove the overridden buffer we used for the preamble.
1157
0
    SavedMainFileBuffer = nullptr;
1158
1159
    // Keep the ownership of the data in the ASTUnit because the client may
1160
    // want to see the diagnostics.
1161
0
    transferASTDataFromCompilerInstance(*Clang);
1162
0
    FailedParseDiagnostics.swap(StoredDiagnostics);
1163
0
    StoredDiagnostics.clear();
1164
0
    NumStoredDiagnosticsFromDriver = 0;
1165
0
  });
1166
1167
  // Ensure that Clang has a FileManager with the right VFS, which may have
1168
  // changed above in AddImplicitPreamble.  If VFS is nullptr, rely on
1169
  // createFileManager to create one.
1170
0
  if (VFS && FileMgr && &FileMgr->getVirtualFileSystem() == VFS)
1171
0
    Clang->setFileManager(&*FileMgr);
1172
0
  else
1173
0
    FileMgr = Clang->createFileManager(std::move(VFS));
1174
1175
  // Recover resources if we crash before exiting this method.
1176
0
  llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1177
0
    CICleanup(Clang.get());
1178
1179
0
  OriginalSourceFile =
1180
0
      std::string(Clang->getFrontendOpts().Inputs[0].getFile());
1181
1182
  // Set up diagnostics, capturing any diagnostics that would
1183
  // otherwise be dropped.
1184
0
  Clang->setDiagnostics(&getDiagnostics());
1185
1186
  // Create the target instance.
1187
0
  if (!Clang->createTarget())
1188
0
    return true;
1189
1190
0
  assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1191
0
         "Invocation must have exactly one source file!");
1192
0
  assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1193
0
             InputKind::Source &&
1194
0
         "FIXME: AST inputs not yet supported here!");
1195
0
  assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1196
0
             Language::LLVM_IR &&
1197
0
         "IR inputs not support here!");
1198
1199
  // Configure the various subsystems.
1200
0
  LangOpts = Clang->getInvocation().LangOpts;
1201
0
  FileSystemOpts = Clang->getFileSystemOpts();
1202
1203
0
  ResetForParse();
1204
1205
0
  SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1206
0
                                UserFilesAreVolatile);
1207
0
  if (!OverrideMainBuffer) {
1208
0
    checkAndRemoveNonDriverDiags(StoredDiagnostics);
1209
0
    TopLevelDeclsInPreamble.clear();
1210
0
  }
1211
1212
  // Create the source manager.
1213
0
  Clang->setSourceManager(&getSourceManager());
1214
1215
  // If the main file has been overridden due to the use of a preamble,
1216
  // make that override happen and introduce the preamble.
1217
0
  if (OverrideMainBuffer) {
1218
    // The stored diagnostic has the old source manager in it; update
1219
    // the locations to refer into the new source manager. Since we've
1220
    // been careful to make sure that the source manager's state
1221
    // before and after are identical, so that we can reuse the source
1222
    // location itself.
1223
0
    checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
1224
1225
    // Keep track of the override buffer;
1226
0
    SavedMainFileBuffer = std::move(OverrideMainBuffer);
1227
0
  }
1228
1229
0
  std::unique_ptr<TopLevelDeclTrackerAction> Act(
1230
0
      new TopLevelDeclTrackerAction(*this));
1231
1232
  // Recover resources if we crash before exiting this method.
1233
0
  llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1234
0
    ActCleanup(Act.get());
1235
1236
0
  if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
1237
0
    return true;
1238
1239
0
  if (SavedMainFileBuffer)
1240
0
    TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1241
0
                               PreambleDiagnostics, StoredDiagnostics);
1242
0
  else
1243
0
    PreambleSrcLocCache.clear();
1244
1245
0
  if (llvm::Error Err = Act->Execute()) {
1246
0
    consumeError(std::move(Err)); // FIXME this drops errors on the floor.
1247
0
    return true;
1248
0
  }
1249
1250
0
  transferASTDataFromCompilerInstance(*Clang);
1251
1252
0
  Act->EndSourceFile();
1253
1254
0
  FailedParseDiagnostics.clear();
1255
1256
0
  CleanOnError.release();
1257
1258
0
  return false;
1259
0
}
1260
1261
static std::pair<unsigned, unsigned>
1262
makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1263
0
                    const LangOptions &LangOpts) {
1264
0
  CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1265
0
  unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1266
0
  unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1267
0
  return std::make_pair(Offset, EndOffset);
1268
0
}
1269
1270
static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
1271
                                                    const LangOptions &LangOpts,
1272
0
                                                    const FixItHint &InFix) {
1273
0
  ASTUnit::StandaloneFixIt OutFix;
1274
0
  OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1275
0
  OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1276
0
                                               LangOpts);
1277
0
  OutFix.CodeToInsert = InFix.CodeToInsert;
1278
0
  OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
1279
0
  return OutFix;
1280
0
}
1281
1282
static ASTUnit::StandaloneDiagnostic
1283
makeStandaloneDiagnostic(const LangOptions &LangOpts,
1284
0
                         const StoredDiagnostic &InDiag) {
1285
0
  ASTUnit::StandaloneDiagnostic OutDiag;
1286
0
  OutDiag.ID = InDiag.getID();
1287
0
  OutDiag.Level = InDiag.getLevel();
1288
0
  OutDiag.Message = std::string(InDiag.getMessage());
1289
0
  OutDiag.LocOffset = 0;
1290
0
  if (InDiag.getLocation().isInvalid())
1291
0
    return OutDiag;
1292
0
  const SourceManager &SM = InDiag.getLocation().getManager();
1293
0
  SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1294
0
  OutDiag.Filename = std::string(SM.getFilename(FileLoc));
1295
0
  if (OutDiag.Filename.empty())
1296
0
    return OutDiag;
1297
0
  OutDiag.LocOffset = SM.getFileOffset(FileLoc);
1298
0
  for (const auto &Range : InDiag.getRanges())
1299
0
    OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
1300
0
  for (const auto &FixIt : InDiag.getFixIts())
1301
0
    OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
1302
1303
0
  return OutDiag;
1304
0
}
1305
1306
/// Attempt to build or re-use a precompiled preamble when (re-)parsing
1307
/// the source file.
1308
///
1309
/// This routine will compute the preamble of the main source file. If a
1310
/// non-trivial preamble is found, it will precompile that preamble into a
1311
/// precompiled header so that the precompiled preamble can be used to reduce
1312
/// reparsing time. If a precompiled preamble has already been constructed,
1313
/// this routine will determine if it is still valid and, if so, avoid
1314
/// rebuilding the precompiled preamble.
1315
///
1316
/// \param AllowRebuild When true (the default), this routine is
1317
/// allowed to rebuild the precompiled preamble if it is found to be
1318
/// out-of-date.
1319
///
1320
/// \param MaxLines When non-zero, the maximum number of lines that
1321
/// can occur within the preamble.
1322
///
1323
/// \returns If the precompiled preamble can be used, returns a newly-allocated
1324
/// buffer that should be used in place of the main file when doing so.
1325
/// Otherwise, returns a NULL pointer.
1326
std::unique_ptr<llvm::MemoryBuffer>
1327
ASTUnit::getMainBufferWithPrecompiledPreamble(
1328
    std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1329
    CompilerInvocation &PreambleInvocationIn,
1330
    IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS, bool AllowRebuild,
1331
0
    unsigned MaxLines) {
1332
0
  auto MainFilePath =
1333
0
      PreambleInvocationIn.getFrontendOpts().Inputs[0].getFile();
1334
0
  std::unique_ptr<llvm::MemoryBuffer> MainFileBuffer =
1335
0
      getBufferForFileHandlingRemapping(PreambleInvocationIn, VFS.get(),
1336
0
                                        MainFilePath, UserFilesAreVolatile);
1337
0
  if (!MainFileBuffer)
1338
0
    return nullptr;
1339
1340
0
  PreambleBounds Bounds = ComputePreambleBounds(
1341
0
      PreambleInvocationIn.getLangOpts(), *MainFileBuffer, MaxLines);
1342
0
  if (!Bounds.Size)
1343
0
    return nullptr;
1344
1345
0
  if (Preamble) {
1346
0
    if (Preamble->CanReuse(PreambleInvocationIn, *MainFileBuffer, Bounds,
1347
0
                           *VFS)) {
1348
      // Okay! We can re-use the precompiled preamble.
1349
1350
      // Set the state of the diagnostic object to mimic its state
1351
      // after parsing the preamble.
1352
0
      getDiagnostics().Reset();
1353
0
      ProcessWarningOptions(getDiagnostics(),
1354
0
                            PreambleInvocationIn.getDiagnosticOpts());
1355
0
      getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1356
1357
0
      PreambleRebuildCountdown = 1;
1358
0
      return MainFileBuffer;
1359
0
    } else {
1360
0
      Preamble.reset();
1361
0
      PreambleDiagnostics.clear();
1362
0
      TopLevelDeclsInPreamble.clear();
1363
0
      PreambleSrcLocCache.clear();
1364
0
      PreambleRebuildCountdown = 1;
1365
0
    }
1366
0
  }
1367
1368
  // If the preamble rebuild counter > 1, it's because we previously
1369
  // failed to build a preamble and we're not yet ready to try
1370
  // again. Decrement the counter and return a failure.
1371
0
  if (PreambleRebuildCountdown > 1) {
1372
0
    --PreambleRebuildCountdown;
1373
0
    return nullptr;
1374
0
  }
1375
1376
0
  assert(!Preamble && "No Preamble should be stored at that point");
1377
  // If we aren't allowed to rebuild the precompiled preamble, just
1378
  // return now.
1379
0
  if (!AllowRebuild)
1380
0
    return nullptr;
1381
1382
0
  ++PreambleCounter;
1383
1384
0
  SmallVector<StandaloneDiagnostic, 4> NewPreambleDiagsStandalone;
1385
0
  SmallVector<StoredDiagnostic, 4> NewPreambleDiags;
1386
0
  ASTUnitPreambleCallbacks Callbacks;
1387
0
  {
1388
0
    std::optional<CaptureDroppedDiagnostics> Capture;
1389
0
    if (CaptureDiagnostics != CaptureDiagsKind::None)
1390
0
      Capture.emplace(CaptureDiagnostics, *Diagnostics, &NewPreambleDiags,
1391
0
                      &NewPreambleDiagsStandalone);
1392
1393
    // We did not previously compute a preamble, or it can't be reused anyway.
1394
0
    SimpleTimer PreambleTimer(WantTiming);
1395
0
    PreambleTimer.setOutput("Precompiling preamble");
1396
1397
0
    const bool PreviousSkipFunctionBodies =
1398
0
        PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies;
1399
0
    if (SkipFunctionBodies == SkipFunctionBodiesScope::Preamble)
1400
0
      PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies = true;
1401
1402
0
    llvm::ErrorOr<PrecompiledPreamble> NewPreamble = PrecompiledPreamble::Build(
1403
0
        PreambleInvocationIn, MainFileBuffer.get(), Bounds, *Diagnostics, VFS,
1404
0
        PCHContainerOps, StorePreamblesInMemory, PreambleStoragePath,
1405
0
        Callbacks);
1406
1407
0
    PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies =
1408
0
        PreviousSkipFunctionBodies;
1409
1410
0
    if (NewPreamble) {
1411
0
      Preamble = std::move(*NewPreamble);
1412
0
      PreambleRebuildCountdown = 1;
1413
0
    } else {
1414
0
      switch (static_cast<BuildPreambleError>(NewPreamble.getError().value())) {
1415
0
      case BuildPreambleError::CouldntCreateTempFile:
1416
        // Try again next time.
1417
0
        PreambleRebuildCountdown = 1;
1418
0
        return nullptr;
1419
0
      case BuildPreambleError::CouldntCreateTargetInfo:
1420
0
      case BuildPreambleError::BeginSourceFileFailed:
1421
0
      case BuildPreambleError::CouldntEmitPCH:
1422
0
      case BuildPreambleError::BadInputs:
1423
        // These erros are more likely to repeat, retry after some period.
1424
0
        PreambleRebuildCountdown = DefaultPreambleRebuildInterval;
1425
0
        return nullptr;
1426
0
      }
1427
0
      llvm_unreachable("unexpected BuildPreambleError");
1428
0
    }
1429
0
  }
1430
1431
0
  assert(Preamble && "Preamble wasn't built");
1432
1433
0
  TopLevelDecls.clear();
1434
0
  TopLevelDeclsInPreamble = Callbacks.takeTopLevelDeclIDs();
1435
0
  PreambleTopLevelHashValue = Callbacks.getHash();
1436
1437
0
  NumWarningsInPreamble = getDiagnostics().getNumWarnings();
1438
1439
0
  checkAndRemoveNonDriverDiags(NewPreambleDiags);
1440
0
  StoredDiagnostics = std::move(NewPreambleDiags);
1441
0
  PreambleDiagnostics = std::move(NewPreambleDiagsStandalone);
1442
1443
  // If the hash of top-level entities differs from the hash of the top-level
1444
  // entities the last time we rebuilt the preamble, clear out the completion
1445
  // cache.
1446
0
  if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1447
0
    CompletionCacheTopLevelHashValue = 0;
1448
0
    PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1449
0
  }
1450
1451
0
  return MainFileBuffer;
1452
0
}
1453
1454
0
void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1455
0
  assert(Preamble && "Should only be called when preamble was built");
1456
1457
0
  std::vector<Decl *> Resolved;
1458
0
  Resolved.reserve(TopLevelDeclsInPreamble.size());
1459
0
  ExternalASTSource &Source = *getASTContext().getExternalSource();
1460
0
  for (const auto TopLevelDecl : TopLevelDeclsInPreamble) {
1461
    // Resolve the declaration ID to an actual declaration, possibly
1462
    // deserializing the declaration in the process.
1463
0
    if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
1464
0
      Resolved.push_back(D);
1465
0
  }
1466
0
  TopLevelDeclsInPreamble.clear();
1467
0
  TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1468
0
}
1469
1470
0
void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1471
  // Steal the created target, context, and preprocessor if they have been
1472
  // created.
1473
0
  assert(CI.hasInvocation() && "missing invocation");
1474
0
  LangOpts = CI.getInvocation().LangOpts;
1475
0
  TheSema = CI.takeSema();
1476
0
  Consumer = CI.takeASTConsumer();
1477
0
  if (CI.hasASTContext())
1478
0
    Ctx = &CI.getASTContext();
1479
0
  if (CI.hasPreprocessor())
1480
0
    PP = CI.getPreprocessorPtr();
1481
0
  CI.setSourceManager(nullptr);
1482
0
  CI.setFileManager(nullptr);
1483
0
  if (CI.hasTarget())
1484
0
    Target = &CI.getTarget();
1485
0
  Reader = CI.getASTReader();
1486
0
  HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
1487
0
}
1488
1489
0
StringRef ASTUnit::getMainFileName() const {
1490
0
  if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1491
0
    const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1492
0
    if (Input.isFile())
1493
0
      return Input.getFile();
1494
0
    else
1495
0
      return Input.getBuffer().getBufferIdentifier();
1496
0
  }
1497
1498
0
  if (SourceMgr) {
1499
0
    if (OptionalFileEntryRef FE =
1500
0
            SourceMgr->getFileEntryRefForID(SourceMgr->getMainFileID()))
1501
0
      return FE->getName();
1502
0
  }
1503
1504
0
  return {};
1505
0
}
1506
1507
0
StringRef ASTUnit::getASTFileName() const {
1508
0
  if (!isMainFileAST())
1509
0
    return {};
1510
1511
0
  serialization::ModuleFile &
1512
0
    Mod = Reader->getModuleManager().getPrimaryModule();
1513
0
  return Mod.FileName;
1514
0
}
1515
1516
std::unique_ptr<ASTUnit>
1517
ASTUnit::create(std::shared_ptr<CompilerInvocation> CI,
1518
                IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1519
                CaptureDiagsKind CaptureDiagnostics,
1520
0
                bool UserFilesAreVolatile) {
1521
0
  std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1522
0
  ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1523
0
  IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS =
1524
0
      createVFSFromCompilerInvocation(*CI, *Diags);
1525
0
  AST->Diagnostics = Diags;
1526
0
  AST->FileSystemOpts = CI->getFileSystemOpts();
1527
0
  AST->Invocation = std::move(CI);
1528
0
  AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1529
0
  AST->UserFilesAreVolatile = UserFilesAreVolatile;
1530
0
  AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1531
0
                                     UserFilesAreVolatile);
1532
0
  AST->ModuleCache = new InMemoryModuleCache;
1533
1534
0
  return AST;
1535
0
}
1536
1537
ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
1538
    std::shared_ptr<CompilerInvocation> CI,
1539
    std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1540
    IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FrontendAction *Action,
1541
    ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath,
1542
    bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics,
1543
    unsigned PrecompilePreambleAfterNParses, bool CacheCodeCompletionResults,
1544
0
    bool UserFilesAreVolatile, std::unique_ptr<ASTUnit> *ErrAST) {
1545
0
  assert(CI && "A CompilerInvocation is required");
1546
1547
0
  std::unique_ptr<ASTUnit> OwnAST;
1548
0
  ASTUnit *AST = Unit;
1549
0
  if (!AST) {
1550
    // Create the AST unit.
1551
0
    OwnAST = create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile);
1552
0
    AST = OwnAST.get();
1553
0
    if (!AST)
1554
0
      return nullptr;
1555
0
  }
1556
1557
0
  if (!ResourceFilesPath.empty()) {
1558
    // Override the resources path.
1559
0
    CI->getHeaderSearchOpts().ResourceDir = std::string(ResourceFilesPath);
1560
0
  }
1561
0
  AST->OnlyLocalDecls = OnlyLocalDecls;
1562
0
  AST->CaptureDiagnostics = CaptureDiagnostics;
1563
0
  if (PrecompilePreambleAfterNParses > 0)
1564
0
    AST->PreambleRebuildCountdown = PrecompilePreambleAfterNParses;
1565
0
  AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
1566
0
  AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1567
0
  AST->IncludeBriefCommentsInCodeCompletion = false;
1568
1569
  // Recover resources if we crash before exiting this method.
1570
0
  llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1571
0
    ASTUnitCleanup(OwnAST.get());
1572
0
  llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1573
0
    llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
1574
0
    DiagCleanup(Diags.get());
1575
1576
  // We'll manage file buffers ourselves.
1577
0
  CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1578
0
  CI->getFrontendOpts().DisableFree = false;
1579
0
  ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1580
1581
  // Create the compiler instance to use for building the AST.
1582
0
  std::unique_ptr<CompilerInstance> Clang(
1583
0
      new CompilerInstance(std::move(PCHContainerOps)));
1584
1585
  // Recover resources if we crash before exiting this method.
1586
0
  llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1587
0
    CICleanup(Clang.get());
1588
1589
0
  Clang->setInvocation(std::move(CI));
1590
0
  AST->OriginalSourceFile =
1591
0
      std::string(Clang->getFrontendOpts().Inputs[0].getFile());
1592
1593
  // Set up diagnostics, capturing any diagnostics that would
1594
  // otherwise be dropped.
1595
0
  Clang->setDiagnostics(&AST->getDiagnostics());
1596
1597
  // Create the target instance.
1598
0
  if (!Clang->createTarget())
1599
0
    return nullptr;
1600
1601
0
  assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1602
0
         "Invocation must have exactly one source file!");
1603
0
  assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1604
0
             InputKind::Source &&
1605
0
         "FIXME: AST inputs not yet supported here!");
1606
0
  assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1607
0
             Language::LLVM_IR &&
1608
0
         "IR inputs not support here!");
1609
1610
  // Configure the various subsystems.
1611
0
  AST->TheSema.reset();
1612
0
  AST->Ctx = nullptr;
1613
0
  AST->PP = nullptr;
1614
0
  AST->Reader = nullptr;
1615
1616
  // Create a file manager object to provide access to and cache the filesystem.
1617
0
  Clang->setFileManager(&AST->getFileManager());
1618
1619
  // Create the source manager.
1620
0
  Clang->setSourceManager(&AST->getSourceManager());
1621
1622
0
  FrontendAction *Act = Action;
1623
1624
0
  std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
1625
0
  if (!Act) {
1626
0
    TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1627
0
    Act = TrackerAct.get();
1628
0
  }
1629
1630
  // Recover resources if we crash before exiting this method.
1631
0
  llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1632
0
    ActCleanup(TrackerAct.get());
1633
1634
0
  if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1635
0
    AST->transferASTDataFromCompilerInstance(*Clang);
1636
0
    if (OwnAST && ErrAST)
1637
0
      ErrAST->swap(OwnAST);
1638
1639
0
    return nullptr;
1640
0
  }
1641
1642
0
  if (Persistent && !TrackerAct) {
1643
0
    Clang->getPreprocessor().addPPCallbacks(
1644
0
        std::make_unique<MacroDefinitionTrackerPPCallbacks>(
1645
0
                                           AST->getCurrentTopLevelHashValue()));
1646
0
    std::vector<std::unique_ptr<ASTConsumer>> Consumers;
1647
0
    if (Clang->hasASTConsumer())
1648
0
      Consumers.push_back(Clang->takeASTConsumer());
1649
0
    Consumers.push_back(std::make_unique<TopLevelDeclTrackerConsumer>(
1650
0
        *AST, AST->getCurrentTopLevelHashValue()));
1651
0
    Clang->setASTConsumer(
1652
0
        std::make_unique<MultiplexConsumer>(std::move(Consumers)));
1653
0
  }
1654
0
  if (llvm::Error Err = Act->Execute()) {
1655
0
    consumeError(std::move(Err)); // FIXME this drops errors on the floor.
1656
0
    AST->transferASTDataFromCompilerInstance(*Clang);
1657
0
    if (OwnAST && ErrAST)
1658
0
      ErrAST->swap(OwnAST);
1659
1660
0
    return nullptr;
1661
0
  }
1662
1663
  // Steal the created target, context, and preprocessor.
1664
0
  AST->transferASTDataFromCompilerInstance(*Clang);
1665
1666
0
  Act->EndSourceFile();
1667
1668
0
  if (OwnAST)
1669
0
    return OwnAST.release();
1670
0
  else
1671
0
    return AST;
1672
0
}
1673
1674
bool ASTUnit::LoadFromCompilerInvocation(
1675
    std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1676
    unsigned PrecompilePreambleAfterNParses,
1677
0
    IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
1678
0
  if (!Invocation)
1679
0
    return true;
1680
1681
0
  assert(VFS && "VFS is null");
1682
1683
  // We'll manage file buffers ourselves.
1684
0
  Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1685
0
  Invocation->getFrontendOpts().DisableFree = false;
1686
0
  getDiagnostics().Reset();
1687
0
  ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1688
1689
0
  std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1690
0
  if (PrecompilePreambleAfterNParses > 0) {
1691
0
    PreambleRebuildCountdown = PrecompilePreambleAfterNParses;
1692
0
    OverrideMainBuffer =
1693
0
        getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1694
0
    getDiagnostics().Reset();
1695
0
    ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1696
0
  }
1697
1698
0
  SimpleTimer ParsingTimer(WantTiming);
1699
0
  ParsingTimer.setOutput("Parsing " + getMainFileName());
1700
1701
  // Recover resources if we crash before exiting this method.
1702
0
  llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1703
0
    MemBufferCleanup(OverrideMainBuffer.get());
1704
1705
0
  return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
1706
0
}
1707
1708
std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1709
    std::shared_ptr<CompilerInvocation> CI,
1710
    std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1711
    IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
1712
    bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics,
1713
    unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1714
    bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1715
0
    bool UserFilesAreVolatile) {
1716
  // Create the AST unit.
1717
0
  std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1718
0
  ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1719
0
  AST->Diagnostics = Diags;
1720
0
  AST->OnlyLocalDecls = OnlyLocalDecls;
1721
0
  AST->CaptureDiagnostics = CaptureDiagnostics;
1722
0
  AST->TUKind = TUKind;
1723
0
  AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1724
0
  AST->IncludeBriefCommentsInCodeCompletion
1725
0
    = IncludeBriefCommentsInCodeCompletion;
1726
0
  AST->Invocation = std::move(CI);
1727
0
  AST->FileSystemOpts = FileMgr->getFileSystemOpts();
1728
0
  AST->FileMgr = FileMgr;
1729
0
  AST->UserFilesAreVolatile = UserFilesAreVolatile;
1730
1731
  // Recover resources if we crash before exiting this method.
1732
0
  llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1733
0
    ASTUnitCleanup(AST.get());
1734
0
  llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1735
0
    llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
1736
0
    DiagCleanup(Diags.get());
1737
1738
0
  if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1739
0
                                      PrecompilePreambleAfterNParses,
1740
0
                                      &AST->FileMgr->getVirtualFileSystem()))
1741
0
    return nullptr;
1742
0
  return AST;
1743
0
}
1744
1745
std::unique_ptr<ASTUnit> ASTUnit::LoadFromCommandLine(
1746
    const char **ArgBegin, const char **ArgEnd,
1747
    std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1748
    IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1749
    bool StorePreamblesInMemory, StringRef PreambleStoragePath,
1750
    bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics,
1751
    ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
1752
    unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1753
    bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1754
    bool AllowPCHWithCompilerErrors, SkipFunctionBodiesScope SkipFunctionBodies,
1755
    bool SingleFileParse, bool UserFilesAreVolatile, bool ForSerialization,
1756
    bool RetainExcludedConditionalBlocks, std::optional<StringRef> ModuleFormat,
1757
    std::unique_ptr<ASTUnit> *ErrAST,
1758
0
    IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
1759
0
  assert(Diags.get() && "no DiagnosticsEngine was provided");
1760
1761
  // If no VFS was provided, create one that tracks the physical file system.
1762
  // If '-working-directory' was passed as an argument, 'createInvocation' will
1763
  // set this as the current working directory of the VFS.
1764
0
  if (!VFS)
1765
0
    VFS = llvm::vfs::createPhysicalFileSystem();
1766
1767
0
  SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1768
1769
0
  std::shared_ptr<CompilerInvocation> CI;
1770
1771
0
  {
1772
0
    CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
1773
0
                                      &StoredDiagnostics, nullptr);
1774
1775
0
    CreateInvocationOptions CIOpts;
1776
0
    CIOpts.VFS = VFS;
1777
0
    CIOpts.Diags = Diags;
1778
0
    CIOpts.ProbePrecompiled = true; // FIXME: historical default. Needed?
1779
0
    CI = createInvocation(llvm::ArrayRef(ArgBegin, ArgEnd), std::move(CIOpts));
1780
0
    if (!CI)
1781
0
      return nullptr;
1782
0
  }
1783
1784
  // Override any files that need remapping
1785
0
  for (const auto &RemappedFile : RemappedFiles) {
1786
0
    CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1787
0
                                              RemappedFile.second);
1788
0
  }
1789
0
  PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1790
0
  PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1791
0
  PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
1792
0
  PPOpts.SingleFileParseMode = SingleFileParse;
1793
0
  PPOpts.RetainExcludedConditionalBlocks = RetainExcludedConditionalBlocks;
1794
1795
  // Override the resources path.
1796
0
  CI->getHeaderSearchOpts().ResourceDir = std::string(ResourceFilesPath);
1797
1798
0
  CI->getFrontendOpts().SkipFunctionBodies =
1799
0
      SkipFunctionBodies == SkipFunctionBodiesScope::PreambleAndMainFile;
1800
1801
0
  if (ModuleFormat)
1802
0
    CI->getHeaderSearchOpts().ModuleFormat = std::string(*ModuleFormat);
1803
1804
  // Create the AST unit.
1805
0
  std::unique_ptr<ASTUnit> AST;
1806
0
  AST.reset(new ASTUnit(false));
1807
0
  AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1808
0
  AST->StoredDiagnostics.swap(StoredDiagnostics);
1809
0
  ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1810
0
  AST->Diagnostics = Diags;
1811
0
  AST->FileSystemOpts = CI->getFileSystemOpts();
1812
0
  VFS = createVFSFromCompilerInvocation(*CI, *Diags, VFS);
1813
0
  AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1814
0
  AST->StorePreamblesInMemory = StorePreamblesInMemory;
1815
0
  AST->PreambleStoragePath = PreambleStoragePath;
1816
0
  AST->ModuleCache = new InMemoryModuleCache;
1817
0
  AST->OnlyLocalDecls = OnlyLocalDecls;
1818
0
  AST->CaptureDiagnostics = CaptureDiagnostics;
1819
0
  AST->TUKind = TUKind;
1820
0
  AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1821
0
  AST->IncludeBriefCommentsInCodeCompletion
1822
0
    = IncludeBriefCommentsInCodeCompletion;
1823
0
  AST->UserFilesAreVolatile = UserFilesAreVolatile;
1824
0
  AST->Invocation = CI;
1825
0
  AST->SkipFunctionBodies = SkipFunctionBodies;
1826
0
  if (ForSerialization)
1827
0
    AST->WriterData.reset(new ASTWriterData(*AST->ModuleCache));
1828
  // Zero out now to ease cleanup during crash recovery.
1829
0
  CI = nullptr;
1830
0
  Diags = nullptr;
1831
1832
  // Recover resources if we crash before exiting this method.
1833
0
  llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1834
0
    ASTUnitCleanup(AST.get());
1835
1836
0
  if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1837
0
                                      PrecompilePreambleAfterNParses,
1838
0
                                      VFS)) {
1839
    // Some error occurred, if caller wants to examine diagnostics, pass it the
1840
    // ASTUnit.
1841
0
    if (ErrAST) {
1842
0
      AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
1843
0
      ErrAST->swap(AST);
1844
0
    }
1845
0
    return nullptr;
1846
0
  }
1847
1848
0
  return AST;
1849
0
}
1850
1851
bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1852
                      ArrayRef<RemappedFile> RemappedFiles,
1853
0
                      IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
1854
0
  if (!Invocation)
1855
0
    return true;
1856
1857
0
  if (!VFS) {
1858
0
    assert(FileMgr && "FileMgr is null on Reparse call");
1859
0
    VFS = &FileMgr->getVirtualFileSystem();
1860
0
  }
1861
1862
0
  clearFileLevelDecls();
1863
1864
0
  SimpleTimer ParsingTimer(WantTiming);
1865
0
  ParsingTimer.setOutput("Reparsing " + getMainFileName());
1866
1867
  // Remap files.
1868
0
  PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1869
0
  for (const auto &RB : PPOpts.RemappedFileBuffers)
1870
0
    delete RB.second;
1871
1872
0
  Invocation->getPreprocessorOpts().clearRemappedFiles();
1873
0
  for (const auto &RemappedFile : RemappedFiles) {
1874
0
    Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1875
0
                                                      RemappedFile.second);
1876
0
  }
1877
1878
  // If we have a preamble file lying around, or if we might try to
1879
  // build a precompiled preamble, do so now.
1880
0
  std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1881
0
  if (Preamble || PreambleRebuildCountdown > 0)
1882
0
    OverrideMainBuffer =
1883
0
        getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1884
1885
  // Clear out the diagnostics state.
1886
0
  FileMgr.reset();
1887
0
  getDiagnostics().Reset();
1888
0
  ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1889
0
  if (OverrideMainBuffer)
1890
0
    getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1891
1892
  // Parse the sources
1893
0
  bool Result =
1894
0
      Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
1895
1896
  // If we're caching global code-completion results, and the top-level
1897
  // declarations have changed, clear out the code-completion cache.
1898
0
  if (!Result && ShouldCacheCodeCompletionResults &&
1899
0
      CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1900
0
    CacheCodeCompletionResults();
1901
1902
  // We now need to clear out the completion info related to this translation
1903
  // unit; it'll be recreated if necessary.
1904
0
  CCTUInfo.reset();
1905
1906
0
  return Result;
1907
0
}
1908
1909
0
void ASTUnit::ResetForParse() {
1910
0
  SavedMainFileBuffer.reset();
1911
1912
0
  SourceMgr.reset();
1913
0
  TheSema.reset();
1914
0
  Ctx.reset();
1915
0
  PP.reset();
1916
0
  Reader.reset();
1917
1918
0
  TopLevelDecls.clear();
1919
0
  clearFileLevelDecls();
1920
0
}
1921
1922
//----------------------------------------------------------------------------//
1923
// Code completion
1924
//----------------------------------------------------------------------------//
1925
1926
namespace {
1927
1928
  /// Code completion consumer that combines the cached code-completion
1929
  /// results from an ASTUnit with the code-completion results provided to it,
1930
  /// then passes the result on to
1931
  class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1932
    uint64_t NormalContexts;
1933
    ASTUnit &AST;
1934
    CodeCompleteConsumer &Next;
1935
1936
  public:
1937
    AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
1938
                                  const CodeCompleteOptions &CodeCompleteOpts)
1939
0
        : CodeCompleteConsumer(CodeCompleteOpts), AST(AST), Next(Next) {
1940
      // Compute the set of contexts in which we will look when we don't have
1941
      // any information about the specific context.
1942
0
      NormalContexts
1943
0
        = (1LL << CodeCompletionContext::CCC_TopLevel)
1944
0
        | (1LL << CodeCompletionContext::CCC_ObjCInterface)
1945
0
        | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
1946
0
        | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
1947
0
        | (1LL << CodeCompletionContext::CCC_Statement)
1948
0
        | (1LL << CodeCompletionContext::CCC_Expression)
1949
0
        | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
1950
0
        | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
1951
0
        | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
1952
0
        | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
1953
0
        | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
1954
0
        | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
1955
0
        | (1LL << CodeCompletionContext::CCC_Recovery);
1956
1957
0
      if (AST.getASTContext().getLangOpts().CPlusPlus)
1958
0
        NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
1959
0
                       |  (1LL << CodeCompletionContext::CCC_UnionTag)
1960
0
                       |  (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
1961
0
    }
1962
1963
    void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
1964
                                    CodeCompletionResult *Results,
1965
                                    unsigned NumResults) override;
1966
1967
    void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1968
                                   OverloadCandidate *Candidates,
1969
                                   unsigned NumCandidates,
1970
                                   SourceLocation OpenParLoc,
1971
0
                                   bool Braced) override {
1972
0
      Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates,
1973
0
                                     OpenParLoc, Braced);
1974
0
    }
1975
1976
0
    CodeCompletionAllocator &getAllocator() override {
1977
0
      return Next.getAllocator();
1978
0
    }
1979
1980
0
    CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
1981
0
      return Next.getCodeCompletionTUInfo();
1982
0
    }
1983
  };
1984
1985
} // namespace
1986
1987
/// Helper function that computes which global names are hidden by the
1988
/// local code-completion results.
1989
static void CalculateHiddenNames(const CodeCompletionContext &Context,
1990
                                 CodeCompletionResult *Results,
1991
                                 unsigned NumResults,
1992
                                 ASTContext &Ctx,
1993
0
                          llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
1994
0
  bool OnlyTagNames = false;
1995
0
  switch (Context.getKind()) {
1996
0
  case CodeCompletionContext::CCC_Recovery:
1997
0
  case CodeCompletionContext::CCC_TopLevel:
1998
0
  case CodeCompletionContext::CCC_ObjCInterface:
1999
0
  case CodeCompletionContext::CCC_ObjCImplementation:
2000
0
  case CodeCompletionContext::CCC_ObjCIvarList:
2001
0
  case CodeCompletionContext::CCC_ClassStructUnion:
2002
0
  case CodeCompletionContext::CCC_Statement:
2003
0
  case CodeCompletionContext::CCC_Expression:
2004
0
  case CodeCompletionContext::CCC_ObjCMessageReceiver:
2005
0
  case CodeCompletionContext::CCC_DotMemberAccess:
2006
0
  case CodeCompletionContext::CCC_ArrowMemberAccess:
2007
0
  case CodeCompletionContext::CCC_ObjCPropertyAccess:
2008
0
  case CodeCompletionContext::CCC_Namespace:
2009
0
  case CodeCompletionContext::CCC_Type:
2010
0
  case CodeCompletionContext::CCC_Symbol:
2011
0
  case CodeCompletionContext::CCC_SymbolOrNewName:
2012
0
  case CodeCompletionContext::CCC_ParenthesizedExpression:
2013
0
  case CodeCompletionContext::CCC_ObjCInterfaceName:
2014
0
  case CodeCompletionContext::CCC_TopLevelOrExpression:
2015
0
      break;
2016
2017
0
  case CodeCompletionContext::CCC_EnumTag:
2018
0
  case CodeCompletionContext::CCC_UnionTag:
2019
0
  case CodeCompletionContext::CCC_ClassOrStructTag:
2020
0
    OnlyTagNames = true;
2021
0
    break;
2022
2023
0
  case CodeCompletionContext::CCC_ObjCProtocolName:
2024
0
  case CodeCompletionContext::CCC_MacroName:
2025
0
  case CodeCompletionContext::CCC_MacroNameUse:
2026
0
  case CodeCompletionContext::CCC_PreprocessorExpression:
2027
0
  case CodeCompletionContext::CCC_PreprocessorDirective:
2028
0
  case CodeCompletionContext::CCC_NaturalLanguage:
2029
0
  case CodeCompletionContext::CCC_SelectorName:
2030
0
  case CodeCompletionContext::CCC_TypeQualifiers:
2031
0
  case CodeCompletionContext::CCC_Other:
2032
0
  case CodeCompletionContext::CCC_OtherWithMacros:
2033
0
  case CodeCompletionContext::CCC_ObjCInstanceMessage:
2034
0
  case CodeCompletionContext::CCC_ObjCClassMessage:
2035
0
  case CodeCompletionContext::CCC_ObjCCategoryName:
2036
0
  case CodeCompletionContext::CCC_IncludedFile:
2037
0
  case CodeCompletionContext::CCC_Attribute:
2038
0
  case CodeCompletionContext::CCC_NewName:
2039
0
  case CodeCompletionContext::CCC_ObjCClassForwardDecl:
2040
    // We're looking for nothing, or we're looking for names that cannot
2041
    // be hidden.
2042
0
    return;
2043
0
  }
2044
2045
0
  using Result = CodeCompletionResult;
2046
0
  for (unsigned I = 0; I != NumResults; ++I) {
2047
0
    if (Results[I].Kind != Result::RK_Declaration)
2048
0
      continue;
2049
2050
0
    unsigned IDNS
2051
0
      = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2052
2053
0
    bool Hiding = false;
2054
0
    if (OnlyTagNames)
2055
0
      Hiding = (IDNS & Decl::IDNS_Tag);
2056
0
    else {
2057
0
      unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
2058
0
                             Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2059
0
                             Decl::IDNS_NonMemberOperator);
2060
0
      if (Ctx.getLangOpts().CPlusPlus)
2061
0
        HiddenIDNS |= Decl::IDNS_Tag;
2062
0
      Hiding = (IDNS & HiddenIDNS);
2063
0
    }
2064
2065
0
    if (!Hiding)
2066
0
      continue;
2067
2068
0
    DeclarationName Name = Results[I].Declaration->getDeclName();
2069
0
    if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2070
0
      HiddenNames.insert(Identifier->getName());
2071
0
    else
2072
0
      HiddenNames.insert(Name.getAsString());
2073
0
  }
2074
0
}
2075
2076
void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2077
                                            CodeCompletionContext Context,
2078
                                            CodeCompletionResult *Results,
2079
0
                                            unsigned NumResults) {
2080
  // Merge the results we were given with the results we cached.
2081
0
  bool AddedResult = false;
2082
0
  uint64_t InContexts =
2083
0
      Context.getKind() == CodeCompletionContext::CCC_Recovery
2084
0
        ? NormalContexts : (1LL << Context.getKind());
2085
  // Contains the set of names that are hidden by "local" completion results.
2086
0
  llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
2087
0
  using Result = CodeCompletionResult;
2088
0
  SmallVector<Result, 8> AllResults;
2089
0
  for (ASTUnit::cached_completion_iterator
2090
0
            C = AST.cached_completion_begin(),
2091
0
         CEnd = AST.cached_completion_end();
2092
0
       C != CEnd; ++C) {
2093
    // If the context we are in matches any of the contexts we are
2094
    // interested in, we'll add this result.
2095
0
    if ((C->ShowInContexts & InContexts) == 0)
2096
0
      continue;
2097
2098
    // If we haven't added any results previously, do so now.
2099
0
    if (!AddedResult) {
2100
0
      CalculateHiddenNames(Context, Results, NumResults, S.Context,
2101
0
                           HiddenNames);
2102
0
      AllResults.insert(AllResults.end(), Results, Results + NumResults);
2103
0
      AddedResult = true;
2104
0
    }
2105
2106
    // Determine whether this global completion result is hidden by a local
2107
    // completion result. If so, skip it.
2108
0
    if (C->Kind != CXCursor_MacroDefinition &&
2109
0
        HiddenNames.count(C->Completion->getTypedText()))
2110
0
      continue;
2111
2112
    // Adjust priority based on similar type classes.
2113
0
    unsigned Priority = C->Priority;
2114
0
    CodeCompletionString *Completion = C->Completion;
2115
0
    if (!Context.getPreferredType().isNull()) {
2116
0
      if (C->Kind == CXCursor_MacroDefinition) {
2117
0
        Priority = getMacroUsagePriority(C->Completion->getTypedText(),
2118
0
                                         S.getLangOpts(),
2119
0
                               Context.getPreferredType()->isAnyPointerType());
2120
0
      } else if (C->Type) {
2121
0
        CanQualType Expected
2122
0
          = S.Context.getCanonicalType(
2123
0
                               Context.getPreferredType().getUnqualifiedType());
2124
0
        SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2125
0
        if (ExpectedSTC == C->TypeClass) {
2126
          // We know this type is similar; check for an exact match.
2127
0
          llvm::StringMap<unsigned> &CachedCompletionTypes
2128
0
            = AST.getCachedCompletionTypes();
2129
0
          llvm::StringMap<unsigned>::iterator Pos
2130
0
            = CachedCompletionTypes.find(QualType(Expected).getAsString());
2131
0
          if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2132
0
            Priority /= CCF_ExactTypeMatch;
2133
0
          else
2134
0
            Priority /= CCF_SimilarTypeMatch;
2135
0
        }
2136
0
      }
2137
0
    }
2138
2139
    // Adjust the completion string, if required.
2140
0
    if (C->Kind == CXCursor_MacroDefinition &&
2141
0
        Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2142
      // Create a new code-completion string that just contains the
2143
      // macro name, without its arguments.
2144
0
      CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2145
0
                                    CCP_CodePattern, C->Availability);
2146
0
      Builder.AddTypedTextChunk(C->Completion->getTypedText());
2147
0
      Priority = CCP_CodePattern;
2148
0
      Completion = Builder.TakeString();
2149
0
    }
2150
2151
0
    AllResults.push_back(Result(Completion, Priority, C->Kind,
2152
0
                                C->Availability));
2153
0
  }
2154
2155
  // If we did not add any cached completion results, just forward the
2156
  // results we were given to the next consumer.
2157
0
  if (!AddedResult) {
2158
0
    Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2159
0
    return;
2160
0
  }
2161
2162
0
  Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2163
0
                                  AllResults.size());
2164
0
}
2165
2166
void ASTUnit::CodeComplete(
2167
    StringRef File, unsigned Line, unsigned Column,
2168
    ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
2169
    bool IncludeCodePatterns, bool IncludeBriefComments,
2170
    CodeCompleteConsumer &Consumer,
2171
    std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2172
    DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr,
2173
    FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2174
    SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers,
2175
0
    std::unique_ptr<SyntaxOnlyAction> Act) {
2176
0
  if (!Invocation)
2177
0
    return;
2178
2179
0
  SimpleTimer CompletionTimer(WantTiming);
2180
0
  CompletionTimer.setOutput("Code completion @ " + File + ":" +
2181
0
                            Twine(Line) + ":" + Twine(Column));
2182
2183
0
  auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
2184
2185
0
  FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2186
0
  CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
2187
0
  PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
2188
2189
0
  CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2190
0
                                   CachedCompletionResults.empty();
2191
0
  CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2192
0
  CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2193
0
  CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2194
0
  CodeCompleteOpts.LoadExternal = Consumer.loadExternal();
2195
0
  CodeCompleteOpts.IncludeFixIts = Consumer.includeFixIts();
2196
2197
0
  assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2198
2199
0
  FrontendOpts.CodeCompletionAt.FileName = std::string(File);
2200
0
  FrontendOpts.CodeCompletionAt.Line = Line;
2201
0
  FrontendOpts.CodeCompletionAt.Column = Column;
2202
2203
  // Set the language options appropriately.
2204
0
  LangOpts = CCInvocation->getLangOpts();
2205
2206
  // Spell-checking and warnings are wasteful during code-completion.
2207
0
  LangOpts.SpellChecking = false;
2208
0
  CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2209
2210
0
  std::unique_ptr<CompilerInstance> Clang(
2211
0
      new CompilerInstance(PCHContainerOps));
2212
2213
  // Recover resources if we crash before exiting this method.
2214
0
  llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2215
0
    CICleanup(Clang.get());
2216
2217
0
  auto &Inv = *CCInvocation;
2218
0
  Clang->setInvocation(std::move(CCInvocation));
2219
0
  OriginalSourceFile =
2220
0
      std::string(Clang->getFrontendOpts().Inputs[0].getFile());
2221
2222
  // Set up diagnostics, capturing any diagnostics produced.
2223
0
  Clang->setDiagnostics(&Diag);
2224
0
  CaptureDroppedDiagnostics Capture(CaptureDiagsKind::All,
2225
0
                                    Clang->getDiagnostics(),
2226
0
                                    &StoredDiagnostics, nullptr);
2227
0
  ProcessWarningOptions(Diag, Inv.getDiagnosticOpts());
2228
2229
  // Create the target instance.
2230
0
  if (!Clang->createTarget()) {
2231
0
    Clang->setInvocation(nullptr);
2232
0
    return;
2233
0
  }
2234
2235
0
  assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2236
0
         "Invocation must have exactly one source file!");
2237
0
  assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
2238
0
             InputKind::Source &&
2239
0
         "FIXME: AST inputs not yet supported here!");
2240
0
  assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
2241
0
             Language::LLVM_IR &&
2242
0
         "IR inputs not support here!");
2243
2244
  // Use the source and file managers that we were given.
2245
0
  Clang->setFileManager(&FileMgr);
2246
0
  Clang->setSourceManager(&SourceMgr);
2247
2248
  // Remap files.
2249
0
  PreprocessorOpts.clearRemappedFiles();
2250
0
  PreprocessorOpts.RetainRemappedFileBuffers = true;
2251
0
  for (const auto &RemappedFile : RemappedFiles) {
2252
0
    PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2253
0
    OwnedBuffers.push_back(RemappedFile.second);
2254
0
  }
2255
2256
  // Use the code completion consumer we were given, but adding any cached
2257
  // code-completion results.
2258
0
  AugmentedCodeCompleteConsumer *AugmentedConsumer
2259
0
    = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
2260
0
  Clang->setCodeCompletionConsumer(AugmentedConsumer);
2261
2262
0
  auto getUniqueID =
2263
0
      [&FileMgr](StringRef Filename) -> std::optional<llvm::sys::fs::UniqueID> {
2264
0
    if (auto Status = FileMgr.getVirtualFileSystem().status(Filename))
2265
0
      return Status->getUniqueID();
2266
0
    return std::nullopt;
2267
0
  };
2268
2269
0
  auto hasSameUniqueID = [getUniqueID](StringRef LHS, StringRef RHS) {
2270
0
    if (LHS == RHS)
2271
0
      return true;
2272
0
    if (auto LHSID = getUniqueID(LHS))
2273
0
      if (auto RHSID = getUniqueID(RHS))
2274
0
        return *LHSID == *RHSID;
2275
0
    return false;
2276
0
  };
2277
2278
  // If we have a precompiled preamble, try to use it. We only allow
2279
  // the use of the precompiled preamble if we're if the completion
2280
  // point is within the main file, after the end of the precompiled
2281
  // preamble.
2282
0
  std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2283
0
  if (Preamble && Line > 1 && hasSameUniqueID(File, OriginalSourceFile)) {
2284
0
    OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2285
0
        PCHContainerOps, Inv, &FileMgr.getVirtualFileSystem(), false, Line - 1);
2286
0
  }
2287
2288
  // If the main file has been overridden due to the use of a preamble,
2289
  // make that override happen and introduce the preamble.
2290
0
  if (OverrideMainBuffer) {
2291
0
    assert(Preamble &&
2292
0
           "No preamble was built, but OverrideMainBuffer is not null");
2293
2294
0
    IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS =
2295
0
        &FileMgr.getVirtualFileSystem();
2296
0
    Preamble->AddImplicitPreamble(Clang->getInvocation(), VFS,
2297
0
                                  OverrideMainBuffer.get());
2298
    // FIXME: there is no way to update VFS if it was changed by
2299
    // AddImplicitPreamble as FileMgr is accepted as a parameter by this method.
2300
    // We use on-disk preambles instead and rely on FileMgr's VFS to ensure the
2301
    // PCH files are always readable.
2302
0
    OwnedBuffers.push_back(OverrideMainBuffer.release());
2303
0
  } else {
2304
0
    PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2305
0
    PreprocessorOpts.PrecompiledPreambleBytes.second = false;
2306
0
  }
2307
2308
  // Disable the preprocessing record if modules are not enabled.
2309
0
  if (!Clang->getLangOpts().Modules)
2310
0
    PreprocessorOpts.DetailedRecord = false;
2311
2312
0
  if (!Act)
2313
0
    Act.reset(new SyntaxOnlyAction);
2314
2315
0
  if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
2316
0
    if (llvm::Error Err = Act->Execute()) {
2317
0
      consumeError(std::move(Err)); // FIXME this drops errors on the floor.
2318
0
    }
2319
0
    Act->EndSourceFile();
2320
0
  }
2321
0
}
2322
2323
0
bool ASTUnit::Save(StringRef File) {
2324
0
  if (HadModuleLoaderFatalFailure)
2325
0
    return true;
2326
2327
  // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2328
  // unconditionally create a stat cache when we parse the file?
2329
2330
0
  if (llvm::Error Err = llvm::writeToOutput(
2331
0
          File, [this](llvm::raw_ostream &Out) {
2332
0
            return serialize(Out) ? llvm::make_error<llvm::StringError>(
2333
0
                                        "ASTUnit serialization failed",
2334
0
                                        llvm::inconvertibleErrorCode())
2335
0
                                  : llvm::Error::success();
2336
0
          })) {
2337
0
    consumeError(std::move(Err));
2338
0
    return true;
2339
0
  }
2340
0
  return false;
2341
0
}
2342
2343
static bool serializeUnit(ASTWriter &Writer, SmallVectorImpl<char> &Buffer,
2344
0
                          Sema &S, raw_ostream &OS) {
2345
0
  Writer.WriteAST(S, std::string(), nullptr, "");
2346
2347
  // Write the generated bitstream to "Out".
2348
0
  if (!Buffer.empty())
2349
0
    OS.write(Buffer.data(), Buffer.size());
2350
2351
0
  return false;
2352
0
}
2353
2354
0
bool ASTUnit::serialize(raw_ostream &OS) {
2355
0
  if (WriterData)
2356
0
    return serializeUnit(WriterData->Writer, WriterData->Buffer, getSema(), OS);
2357
2358
0
  SmallString<128> Buffer;
2359
0
  llvm::BitstreamWriter Stream(Buffer);
2360
0
  InMemoryModuleCache ModuleCache;
2361
0
  ASTWriter Writer(Stream, Buffer, ModuleCache, {});
2362
0
  return serializeUnit(Writer, Buffer, getSema(), OS);
2363
0
}
2364
2365
using SLocRemap = ContinuousRangeMap<unsigned, int, 2>;
2366
2367
void ASTUnit::TranslateStoredDiagnostics(
2368
                          FileManager &FileMgr,
2369
                          SourceManager &SrcMgr,
2370
                          const SmallVectorImpl<StandaloneDiagnostic> &Diags,
2371
0
                          SmallVectorImpl<StoredDiagnostic> &Out) {
2372
  // Map the standalone diagnostic into the new source manager. We also need to
2373
  // remap all the locations to the new view. This includes the diag location,
2374
  // any associated source ranges, and the source ranges of associated fix-its.
2375
  // FIXME: There should be a cleaner way to do this.
2376
0
  SmallVector<StoredDiagnostic, 4> Result;
2377
0
  Result.reserve(Diags.size());
2378
2379
0
  for (const auto &SD : Diags) {
2380
    // Rebuild the StoredDiagnostic.
2381
0
    if (SD.Filename.empty())
2382
0
      continue;
2383
0
    auto FE = FileMgr.getFile(SD.Filename);
2384
0
    if (!FE)
2385
0
      continue;
2386
0
    SourceLocation FileLoc;
2387
0
    auto ItFileID = PreambleSrcLocCache.find(SD.Filename);
2388
0
    if (ItFileID == PreambleSrcLocCache.end()) {
2389
0
      FileID FID = SrcMgr.translateFile(*FE);
2390
0
      FileLoc = SrcMgr.getLocForStartOfFile(FID);
2391
0
      PreambleSrcLocCache[SD.Filename] = FileLoc;
2392
0
    } else {
2393
0
      FileLoc = ItFileID->getValue();
2394
0
    }
2395
2396
0
    if (FileLoc.isInvalid())
2397
0
      continue;
2398
0
    SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
2399
0
    FullSourceLoc Loc(L, SrcMgr);
2400
2401
0
    SmallVector<CharSourceRange, 4> Ranges;
2402
0
    Ranges.reserve(SD.Ranges.size());
2403
0
    for (const auto &Range : SD.Ranges) {
2404
0
      SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2405
0
      SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
2406
0
      Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
2407
0
    }
2408
2409
0
    SmallVector<FixItHint, 2> FixIts;
2410
0
    FixIts.reserve(SD.FixIts.size());
2411
0
    for (const auto &FixIt : SD.FixIts) {
2412
0
      FixIts.push_back(FixItHint());
2413
0
      FixItHint &FH = FixIts.back();
2414
0
      FH.CodeToInsert = FixIt.CodeToInsert;
2415
0
      SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2416
0
      SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
2417
0
      FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
2418
0
    }
2419
2420
0
    Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2421
0
                                      SD.Message, Loc, Ranges, FixIts));
2422
0
  }
2423
0
  Result.swap(Out);
2424
0
}
2425
2426
0
void ASTUnit::addFileLevelDecl(Decl *D) {
2427
0
  assert(D);
2428
2429
  // We only care about local declarations.
2430
0
  if (D->isFromASTFile())
2431
0
    return;
2432
2433
0
  SourceManager &SM = *SourceMgr;
2434
0
  SourceLocation Loc = D->getLocation();
2435
0
  if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2436
0
    return;
2437
2438
  // We only keep track of the file-level declarations of each file.
2439
0
  if (!D->getLexicalDeclContext()->isFileContext())
2440
0
    return;
2441
2442
0
  SourceLocation FileLoc = SM.getFileLoc(Loc);
2443
0
  assert(SM.isLocalSourceLocation(FileLoc));
2444
0
  FileID FID;
2445
0
  unsigned Offset;
2446
0
  std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2447
0
  if (FID.isInvalid())
2448
0
    return;
2449
2450
0
  std::unique_ptr<LocDeclsTy> &Decls = FileDecls[FID];
2451
0
  if (!Decls)
2452
0
    Decls = std::make_unique<LocDeclsTy>();
2453
2454
0
  std::pair<unsigned, Decl *> LocDecl(Offset, D);
2455
2456
0
  if (Decls->empty() || Decls->back().first <= Offset) {
2457
0
    Decls->push_back(LocDecl);
2458
0
    return;
2459
0
  }
2460
2461
0
  LocDeclsTy::iterator I =
2462
0
      llvm::upper_bound(*Decls, LocDecl, llvm::less_first());
2463
2464
0
  Decls->insert(I, LocDecl);
2465
0
}
2466
2467
void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2468
0
                                  SmallVectorImpl<Decl *> &Decls) {
2469
0
  if (File.isInvalid())
2470
0
    return;
2471
2472
0
  if (SourceMgr->isLoadedFileID(File)) {
2473
0
    assert(Ctx->getExternalSource() && "No external source!");
2474
0
    return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2475
0
                                                         Decls);
2476
0
  }
2477
2478
0
  FileDeclsTy::iterator I = FileDecls.find(File);
2479
0
  if (I == FileDecls.end())
2480
0
    return;
2481
2482
0
  LocDeclsTy &LocDecls = *I->second;
2483
0
  if (LocDecls.empty())
2484
0
    return;
2485
2486
0
  LocDeclsTy::iterator BeginIt =
2487
0
      llvm::partition_point(LocDecls, [=](std::pair<unsigned, Decl *> LD) {
2488
0
        return LD.first < Offset;
2489
0
      });
2490
0
  if (BeginIt != LocDecls.begin())
2491
0
    --BeginIt;
2492
2493
  // If we are pointing at a top-level decl inside an objc container, we need
2494
  // to backtrack until we find it otherwise we will fail to report that the
2495
  // region overlaps with an objc container.
2496
0
  while (BeginIt != LocDecls.begin() &&
2497
0
         BeginIt->second->isTopLevelDeclInObjCContainer())
2498
0
    --BeginIt;
2499
2500
0
  LocDeclsTy::iterator EndIt = llvm::upper_bound(
2501
0
      LocDecls, std::make_pair(Offset + Length, (Decl *)nullptr),
2502
0
      llvm::less_first());
2503
0
  if (EndIt != LocDecls.end())
2504
0
    ++EndIt;
2505
2506
0
  for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2507
0
    Decls.push_back(DIt->second);
2508
0
}
2509
2510
SourceLocation ASTUnit::getLocation(const FileEntry *File,
2511
0
                                    unsigned Line, unsigned Col) const {
2512
0
  const SourceManager &SM = getSourceManager();
2513
0
  SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
2514
0
  return SM.getMacroArgExpandedLocation(Loc);
2515
0
}
2516
2517
SourceLocation ASTUnit::getLocation(const FileEntry *File,
2518
0
                                    unsigned Offset) const {
2519
0
  const SourceManager &SM = getSourceManager();
2520
0
  SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
2521
0
  return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2522
0
}
2523
2524
/// If \arg Loc is a loaded location from the preamble, returns
2525
/// the corresponding local location of the main file, otherwise it returns
2526
/// \arg Loc.
2527
0
SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) const {
2528
0
  FileID PreambleID;
2529
0
  if (SourceMgr)
2530
0
    PreambleID = SourceMgr->getPreambleFileID();
2531
2532
0
  if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid())
2533
0
    return Loc;
2534
2535
0
  unsigned Offs;
2536
0
  if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble->getBounds().Size) {
2537
0
    SourceLocation FileLoc
2538
0
        = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2539
0
    return FileLoc.getLocWithOffset(Offs);
2540
0
  }
2541
2542
0
  return Loc;
2543
0
}
2544
2545
/// If \arg Loc is a local location of the main file but inside the
2546
/// preamble chunk, returns the corresponding loaded location from the
2547
/// preamble, otherwise it returns \arg Loc.
2548
0
SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) const {
2549
0
  FileID PreambleID;
2550
0
  if (SourceMgr)
2551
0
    PreambleID = SourceMgr->getPreambleFileID();
2552
2553
0
  if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid())
2554
0
    return Loc;
2555
2556
0
  unsigned Offs;
2557
0
  if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2558
0
      Offs < Preamble->getBounds().Size) {
2559
0
    SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2560
0
    return FileLoc.getLocWithOffset(Offs);
2561
0
  }
2562
2563
0
  return Loc;
2564
0
}
2565
2566
0
bool ASTUnit::isInPreambleFileID(SourceLocation Loc) const {
2567
0
  FileID FID;
2568
0
  if (SourceMgr)
2569
0
    FID = SourceMgr->getPreambleFileID();
2570
2571
0
  if (Loc.isInvalid() || FID.isInvalid())
2572
0
    return false;
2573
2574
0
  return SourceMgr->isInFileID(Loc, FID);
2575
0
}
2576
2577
0
bool ASTUnit::isInMainFileID(SourceLocation Loc) const {
2578
0
  FileID FID;
2579
0
  if (SourceMgr)
2580
0
    FID = SourceMgr->getMainFileID();
2581
2582
0
  if (Loc.isInvalid() || FID.isInvalid())
2583
0
    return false;
2584
2585
0
  return SourceMgr->isInFileID(Loc, FID);
2586
0
}
2587
2588
0
SourceLocation ASTUnit::getEndOfPreambleFileID() const {
2589
0
  FileID FID;
2590
0
  if (SourceMgr)
2591
0
    FID = SourceMgr->getPreambleFileID();
2592
2593
0
  if (FID.isInvalid())
2594
0
    return {};
2595
2596
0
  return SourceMgr->getLocForEndOfFile(FID);
2597
0
}
2598
2599
0
SourceLocation ASTUnit::getStartOfMainFileID() const {
2600
0
  FileID FID;
2601
0
  if (SourceMgr)
2602
0
    FID = SourceMgr->getMainFileID();
2603
2604
0
  if (FID.isInvalid())
2605
0
    return {};
2606
2607
0
  return SourceMgr->getLocForStartOfFile(FID);
2608
0
}
2609
2610
llvm::iterator_range<PreprocessingRecord::iterator>
2611
0
ASTUnit::getLocalPreprocessingEntities() const {
2612
0
  if (isMainFileAST()) {
2613
0
    serialization::ModuleFile &
2614
0
      Mod = Reader->getModuleManager().getPrimaryModule();
2615
0
    return Reader->getModulePreprocessedEntities(Mod);
2616
0
  }
2617
2618
0
  if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2619
0
    return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
2620
2621
0
  return llvm::make_range(PreprocessingRecord::iterator(),
2622
0
                          PreprocessingRecord::iterator());
2623
0
}
2624
2625
0
bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
2626
0
  if (isMainFileAST()) {
2627
0
    serialization::ModuleFile &
2628
0
      Mod = Reader->getModuleManager().getPrimaryModule();
2629
0
    for (const auto *D : Reader->getModuleFileLevelDecls(Mod)) {
2630
0
      if (!Fn(context, D))
2631
0
        return false;
2632
0
    }
2633
2634
0
    return true;
2635
0
  }
2636
2637
0
  for (ASTUnit::top_level_iterator TL = top_level_begin(),
2638
0
                                TLEnd = top_level_end();
2639
0
         TL != TLEnd; ++TL) {
2640
0
    if (!Fn(context, *TL))
2641
0
      return false;
2642
0
  }
2643
2644
0
  return true;
2645
0
}
2646
2647
0
OptionalFileEntryRef ASTUnit::getPCHFile() {
2648
0
  if (!Reader)
2649
0
    return std::nullopt;
2650
2651
0
  serialization::ModuleFile *Mod = nullptr;
2652
0
  Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) {
2653
0
    switch (M.Kind) {
2654
0
    case serialization::MK_ImplicitModule:
2655
0
    case serialization::MK_ExplicitModule:
2656
0
    case serialization::MK_PrebuiltModule:
2657
0
      return true; // skip dependencies.
2658
0
    case serialization::MK_PCH:
2659
0
      Mod = &M;
2660
0
      return true; // found it.
2661
0
    case serialization::MK_Preamble:
2662
0
      return false; // look in dependencies.
2663
0
    case serialization::MK_MainFile:
2664
0
      return false; // look in dependencies.
2665
0
    }
2666
2667
0
    return true;
2668
0
  });
2669
0
  if (Mod)
2670
0
    return Mod->File;
2671
2672
0
  return std::nullopt;
2673
0
}
2674
2675
0
bool ASTUnit::isModuleFile() const {
2676
0
  return isMainFileAST() && getLangOpts().isCompilingModule();
2677
0
}
2678
2679
0
InputKind ASTUnit::getInputKind() const {
2680
0
  auto &LangOpts = getLangOpts();
2681
2682
0
  Language Lang;
2683
0
  if (LangOpts.OpenCL)
2684
0
    Lang = Language::OpenCL;
2685
0
  else if (LangOpts.CUDA)
2686
0
    Lang = Language::CUDA;
2687
0
  else if (LangOpts.RenderScript)
2688
0
    Lang = Language::RenderScript;
2689
0
  else if (LangOpts.CPlusPlus)
2690
0
    Lang = LangOpts.ObjC ? Language::ObjCXX : Language::CXX;
2691
0
  else
2692
0
    Lang = LangOpts.ObjC ? Language::ObjC : Language::C;
2693
2694
0
  InputKind::Format Fmt = InputKind::Source;
2695
0
  if (LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap)
2696
0
    Fmt = InputKind::ModuleMap;
2697
2698
  // We don't know if input was preprocessed. Assume not.
2699
0
  bool PP = false;
2700
2701
0
  return InputKind(Lang, Fmt, PP);
2702
0
}
2703
2704
#ifndef NDEBUG
2705
0
ASTUnit::ConcurrencyState::ConcurrencyState() {
2706
0
  Mutex = new std::recursive_mutex;
2707
0
}
2708
2709
0
ASTUnit::ConcurrencyState::~ConcurrencyState() {
2710
0
  delete static_cast<std::recursive_mutex *>(Mutex);
2711
0
}
2712
2713
0
void ASTUnit::ConcurrencyState::start() {
2714
0
  bool acquired = static_cast<std::recursive_mutex *>(Mutex)->try_lock();
2715
0
  assert(acquired && "Concurrent access to ASTUnit!");
2716
0
}
2717
2718
0
void ASTUnit::ConcurrencyState::finish() {
2719
0
  static_cast<std::recursive_mutex *>(Mutex)->unlock();
2720
0
}
2721
2722
#else // NDEBUG
2723
2724
ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; }
2725
ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2726
void ASTUnit::ConcurrencyState::start() {}
2727
void ASTUnit::ConcurrencyState::finish() {}
2728
2729
#endif // NDEBUG