Coverage Report

Created: 2020-02-18 08:44

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