Coverage Report

Created: 2020-11-24 06:42

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