Coverage Report

Created: 2022-05-17 06:19

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