Coverage Report

Created: 2017-10-03 07:32

/Users/buildslave/jenkins/sharedspace/clang-stage2-coverage-R@2/llvm/tools/clang/lib/Serialization/ASTReader.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- ASTReader.cpp - AST File Reader -----------------------------------===//
2
//
3
//                     The LLVM Compiler Infrastructure
4
//
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
7
//
8
//===----------------------------------------------------------------------===//
9
//
10
//  This file defines the ASTReader class, which reads AST files.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/Serialization/ASTReader.h"
15
#include "ASTCommon.h"
16
#include "ASTReaderInternals.h"
17
#include "clang/AST/ASTConsumer.h"
18
#include "clang/AST/ASTContext.h"
19
#include "clang/AST/ASTMutationListener.h"
20
#include "clang/AST/ASTUnresolvedSet.h"
21
#include "clang/AST/Decl.h"
22
#include "clang/AST/DeclCXX.h"
23
#include "clang/AST/DeclGroup.h"
24
#include "clang/AST/DeclObjC.h"
25
#include "clang/AST/DeclTemplate.h"
26
#include "clang/AST/Expr.h"
27
#include "clang/AST/ExprCXX.h"
28
#include "clang/AST/NestedNameSpecifier.h"
29
#include "clang/AST/ODRHash.h"
30
#include "clang/AST/RawCommentList.h"
31
#include "clang/AST/Type.h"
32
#include "clang/AST/TypeLocVisitor.h"
33
#include "clang/AST/UnresolvedSet.h"
34
#include "clang/Basic/CommentOptions.h"
35
#include "clang/Basic/DiagnosticOptions.h"
36
#include "clang/Basic/ExceptionSpecificationType.h"
37
#include "clang/Basic/FileManager.h"
38
#include "clang/Basic/FileSystemOptions.h"
39
#include "clang/Basic/LangOptions.h"
40
#include "clang/Basic/MemoryBufferCache.h"
41
#include "clang/Basic/ObjCRuntime.h"
42
#include "clang/Basic/OperatorKinds.h"
43
#include "clang/Basic/Sanitizers.h"
44
#include "clang/Basic/SourceManager.h"
45
#include "clang/Basic/SourceManagerInternals.h"
46
#include "clang/Basic/Specifiers.h"
47
#include "clang/Basic/TargetInfo.h"
48
#include "clang/Basic/TargetOptions.h"
49
#include "clang/Basic/TokenKinds.h"
50
#include "clang/Basic/Version.h"
51
#include "clang/Basic/VersionTuple.h"
52
#include "clang/Frontend/PCHContainerOperations.h"
53
#include "clang/Lex/HeaderSearch.h"
54
#include "clang/Lex/HeaderSearchOptions.h"
55
#include "clang/Lex/MacroInfo.h"
56
#include "clang/Lex/ModuleMap.h"
57
#include "clang/Lex/PreprocessingRecord.h"
58
#include "clang/Lex/Preprocessor.h"
59
#include "clang/Lex/PreprocessorOptions.h"
60
#include "clang/Sema/Scope.h"
61
#include "clang/Sema/Sema.h"
62
#include "clang/Sema/Weak.h"
63
#include "clang/Serialization/ASTDeserializationListener.h"
64
#include "clang/Serialization/GlobalModuleIndex.h"
65
#include "clang/Serialization/ModuleManager.h"
66
#include "clang/Serialization/SerializationDiagnostic.h"
67
#include "llvm/ADT/APFloat.h"
68
#include "llvm/ADT/APInt.h"
69
#include "llvm/ADT/APSInt.h"
70
#include "llvm/ADT/Hashing.h"
71
#include "llvm/ADT/SmallString.h"
72
#include "llvm/ADT/StringExtras.h"
73
#include "llvm/ADT/Triple.h"
74
#include "llvm/Bitcode/BitstreamReader.h"
75
#include "llvm/Support/Compression.h"
76
#include "llvm/Support/Compiler.h"
77
#include "llvm/Support/Error.h"
78
#include "llvm/Support/ErrorHandling.h"
79
#include "llvm/Support/FileSystem.h"
80
#include "llvm/Support/MemoryBuffer.h"
81
#include "llvm/Support/Path.h"
82
#include "llvm/Support/SaveAndRestore.h"
83
#include "llvm/Support/raw_ostream.h"
84
#include <algorithm>
85
#include <cassert>
86
#include <cstdint>
87
#include <cstdio>
88
#include <cstring>
89
#include <ctime>
90
#include <iterator>
91
#include <limits>
92
#include <map>
93
#include <memory>
94
#include <new>
95
#include <string>
96
#include <system_error>
97
#include <tuple>
98
#include <utility>
99
#include <vector>
100
101
using namespace clang;
102
using namespace clang::serialization;
103
using namespace clang::serialization::reader;
104
using llvm::BitstreamCursor;
105
106
//===----------------------------------------------------------------------===//
107
// ChainedASTReaderListener implementation
108
//===----------------------------------------------------------------------===//
109
110
bool
111
0
ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
112
0
  return First->ReadFullVersionInformation(FullVersion) ||
113
0
         Second->ReadFullVersionInformation(FullVersion);
114
0
}
115
116
1.21k
void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
117
1.21k
  First->ReadModuleName(ModuleName);
118
1.21k
  Second->ReadModuleName(ModuleName);
119
1.21k
}
120
121
1.16k
void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
122
1.16k
  First->ReadModuleMapFile(ModuleMapPath);
123
1.16k
  Second->ReadModuleMapFile(ModuleMapPath);
124
1.16k
}
125
126
bool
127
ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
128
                                              bool Complain,
129
421
                                              bool AllowCompatibleDifferences) {
130
421
  return First->ReadLanguageOptions(LangOpts, Complain,
131
421
                                    AllowCompatibleDifferences) ||
132
421
         Second->ReadLanguageOptions(LangOpts, Complain,
133
421
                                     AllowCompatibleDifferences);
134
421
}
135
136
bool ChainedASTReaderListener::ReadTargetOptions(
137
    const TargetOptions &TargetOpts, bool Complain,
138
421
    bool AllowCompatibleDifferences) {
139
421
  return First->ReadTargetOptions(TargetOpts, Complain,
140
421
                                  AllowCompatibleDifferences) ||
141
421
         Second->ReadTargetOptions(TargetOpts, Complain,
142
421
                                   AllowCompatibleDifferences);
143
421
}
144
145
bool ChainedASTReaderListener::ReadDiagnosticOptions(
146
55
    IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
147
55
  return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
148
55
         Second->ReadDiagnosticOptions(DiagOpts, Complain);
149
55
}
150
151
bool
152
ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
153
55
                                                bool Complain) {
154
55
  return First->ReadFileSystemOptions(FSOpts, Complain) ||
155
55
         Second->ReadFileSystemOptions(FSOpts, Complain);
156
55
}
157
158
bool ChainedASTReaderListener::ReadHeaderSearchOptions(
159
    const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
160
55
    bool Complain) {
161
55
  return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
162
55
                                        Complain) ||
163
55
         Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
164
55
                                         Complain);
165
55
}
166
167
bool ChainedASTReaderListener::ReadPreprocessorOptions(
168
    const PreprocessorOptions &PPOpts, bool Complain,
169
55
    std::string &SuggestedPredefines) {
170
55
  return First->ReadPreprocessorOptions(PPOpts, Complain,
171
55
                                        SuggestedPredefines) ||
172
55
         Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
173
55
}
174
void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
175
0
                                           unsigned Value) {
176
0
  First->ReadCounter(M, Value);
177
0
  Second->ReadCounter(M, Value);
178
0
}
179
1.24k
bool ChainedASTReaderListener::needsInputFileVisitation() {
180
1.24k
  return First->needsInputFileVisitation() ||
181
1.16k
         Second->needsInputFileVisitation();
182
1.24k
}
183
67
bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
184
67
  return First->needsSystemInputFileVisitation() ||
185
43
  Second->needsSystemInputFileVisitation();
186
67
}
187
void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
188
1.22k
                                               ModuleKind Kind) {
189
1.22k
  First->visitModuleFile(Filename, Kind);
190
1.22k
  Second->visitModuleFile(Filename, Kind);
191
1.22k
}
192
193
bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
194
                                              bool isSystem,
195
                                              bool isOverridden,
196
210
                                              bool isExplicitModule) {
197
210
  bool Continue = false;
198
210
  if (First->needsInputFileVisitation() &&
199
191
      
(!isSystem || 191
First->needsSystemInputFileVisitation()46
))
200
191
    Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
201
191
                                      isExplicitModule);
202
210
  if (Second->needsInputFileVisitation() &&
203
19
      
(!isSystem || 19
Second->needsSystemInputFileVisitation()0
))
204
19
    Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
205
19
                                       isExplicitModule);
206
210
  return Continue;
207
210
}
208
209
void ChainedASTReaderListener::readModuleFileExtension(
210
0
       const ModuleFileExtensionMetadata &Metadata) {
211
0
  First->readModuleFileExtension(Metadata);
212
0
  Second->readModuleFileExtension(Metadata);
213
0
}
214
215
//===----------------------------------------------------------------------===//
216
// PCH validator implementation
217
//===----------------------------------------------------------------------===//
218
219
4.45k
ASTReaderListener::~ASTReaderListener() {}
220
221
/// \brief Compare the given set of language options against an existing set of
222
/// language options.
223
///
224
/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
225
/// \param AllowCompatibleDifferences If true, differences between compatible
226
///        language options will be permitted.
227
///
228
/// \returns true if the languagae options mis-match, false otherwise.
229
static bool checkLanguageOptions(const LangOptions &LangOpts,
230
                                 const LangOptions &ExistingLangOpts,
231
                                 DiagnosticsEngine *Diags,
232
2.62k
                                 bool AllowCompatibleDifferences = true) {
233
2.62k
#define LANGOPT(Name, Bits, Default, Description)                 \
234
258k
  
if (258k
ExistingLangOpts.Name != LangOpts.Name258k
) { \
235
21
    if (Diags)                                                    \
236
4
      Diags->Report(diag::err_pch_langopt_mismatch)               \
237
4
        << Description << LangOpts.Name << ExistingLangOpts.Name; \
238
258k
    return true;                                                  \
239
258k
  }
240
2.62k
241
2.62k
#define VALUE_LANGOPT(Name, Bits, Default, Description)   \
242
17.4k
  
if (17.4k
ExistingLangOpts.Name != LangOpts.Name17.4k
) { \
243
0
    if (Diags)                                            \
244
0
      Diags->Report(diag::err_pch_langopt_value_mismatch) \
245
0
        << Description;                                   \
246
17.4k
    return true;                                          \
247
17.4k
  }
248
2.62k
249
2.62k
#define ENUM_LANGOPT(Name, Type, Bits, Default, Description)   \
250
23.4k
  
if (23.4k
ExistingLangOpts.get##Name() != LangOpts.get##Name()23.4k
) { \
251
0
    if (Diags)                                                 \
252
0
      Diags->Report(diag::err_pch_langopt_value_mismatch)      \
253
0
        << Description;                                        \
254
23.4k
    return true;                                               \
255
23.4k
  }
256
2.62k
257
2.62k
#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description)  \
258
33.8k
  
if (33.8k
!AllowCompatibleDifferences33.8k
) \
259
33.8k
    LANGOPT(Name, Bits, Default, Description)
260
2.62k
261
2.62k
#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description)  \
262
2.62k
  if (!AllowCompatibleDifferences)                                 \
263
2.62k
    ENUM_LANGOPT(Name, Bits, Default, Description)
264
2.62k
265
2.62k
#define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
266
5.20k
  
if (5.20k
!AllowCompatibleDifferences5.20k
) \
267
5.20k
    VALUE_LANGOPT(Name, Bits, Default, Description)
268
2.62k
269
2.62k
#define BENIGN_LANGOPT(Name, Bits, Default, Description)
270
2.62k
#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
271
2.62k
#define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
272
2.62k
#include 
"clang/Basic/LangOptions.def"2.62k
273
302k
274
2.60k
  
if (2.60k
ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures2.60k
) {
275
1
    if (Diags)
276
1
      Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
277
1
    return true;
278
1
  }
279
2.60k
280
2.60k
  
if (2.60k
ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime2.60k
) {
281
0
    if (Diags)
282
0
      Diags->Report(diag::err_pch_langopt_value_mismatch)
283
0
      << "target Objective-C runtime";
284
0
    return true;
285
0
  }
286
2.60k
287
2.60k
  
if (2.60k
ExistingLangOpts.CommentOpts.BlockCommandNames !=
288
2.60k
      LangOpts.CommentOpts.BlockCommandNames) {
289
0
    if (Diags)
290
0
      Diags->Report(diag::err_pch_langopt_value_mismatch)
291
0
        << "block command names";
292
0
    return true;
293
0
  }
294
2.60k
295
2.60k
  // Sanitizer feature mismatches are treated as compatible differences. If
296
2.60k
  // compatible differences aren't allowed, we still only want to check for
297
2.60k
  // mismatches of non-modular sanitizers (the only ones which can affect AST
298
2.60k
  // generation).
299
2.60k
  
if (2.60k
!AllowCompatibleDifferences2.60k
) {
300
2.21k
    SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
301
2.21k
    SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
302
2.21k
    SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
303
2.21k
    ExistingSanitizers.clear(ModularSanitizers);
304
2.21k
    ImportedSanitizers.clear(ModularSanitizers);
305
2.21k
    if (
ExistingSanitizers.Mask != ImportedSanitizers.Mask2.21k
) {
306
1
      const std::string Flag = "-fsanitize=";
307
1
      if (
Diags1
) {
308
1
#define SANITIZER(NAME, ID)                                                    \
309
43
  {                                                                            \
310
43
    bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID);         \
311
43
    bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID);         \
312
43
    if (InExistingModule != InImportedModule)                                  \
313
1
      Diags->Report(diag::err_pch_targetopt_feature_mismatch)                  \
314
1
          << InExistingModule << (Flag + NAME);                                \
315
43
  }
316
1
#include "clang/Basic/Sanitizers.def"
317
1
      }
318
1
      return true;
319
1
    }
320
2.59k
  }
321
2.59k
322
2.59k
  return false;
323
2.59k
}
324
325
/// \brief Compare the given set of target options against an existing set of
326
/// target options.
327
///
328
/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
329
///
330
/// \returns true if the target options mis-match, false otherwise.
331
static bool checkTargetOptions(const TargetOptions &TargetOpts,
332
                               const TargetOptions &ExistingTargetOpts,
333
                               DiagnosticsEngine *Diags,
334
2.62k
                               bool AllowCompatibleDifferences = true) {
335
2.62k
#define CHECK_TARGET_OPT(Field, Name)                             \
336
7.46k
  
if (7.46k
TargetOpts.Field != ExistingTargetOpts.Field7.46k
) { \
337
5
    if (Diags)                                                    \
338
2
      Diags->Report(diag::err_pch_targetopt_mismatch)             \
339
2
        << Name << TargetOpts.Field << ExistingTargetOpts.Field;  \
340
7.46k
    return true;                                                  \
341
7.46k
  }
342
2.62k
343
2.62k
  // The triple and ABI must match exactly.
344
2.62k
  
CHECK_TARGET_OPT2.62k
(Triple, "target");
345
2.61k
  
CHECK_TARGET_OPT2.61k
(ABI, "target ABI");
346
2.61k
347
2.61k
  // We can tolerate different CPUs in many cases, notably when one CPU
348
2.61k
  // supports a strict superset of another. When allowing compatible
349
2.61k
  // differences skip this check.
350
2.61k
  if (!AllowCompatibleDifferences)
351
2.61k
    
CHECK_TARGET_OPT2.23k
(CPU, "target CPU");
352
2.61k
353
2.61k
#undef CHECK_TARGET_OPT
354
2.61k
355
2.61k
  // Compare feature sets.
356
2.61k
  SmallVector<StringRef, 4> ExistingFeatures(
357
2.61k
                                             ExistingTargetOpts.FeaturesAsWritten.begin(),
358
2.61k
                                             ExistingTargetOpts.FeaturesAsWritten.end());
359
2.61k
  SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
360
2.61k
                                         TargetOpts.FeaturesAsWritten.end());
361
2.61k
  std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
362
2.61k
  std::sort(ReadFeatures.begin(), ReadFeatures.end());
363
2.61k
364
2.61k
  // We compute the set difference in both directions explicitly so that we can
365
2.61k
  // diagnose the differences differently.
366
2.61k
  SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
367
2.61k
  std::set_difference(
368
2.61k
      ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
369
2.61k
      ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
370
2.61k
  std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
371
2.61k
                      ExistingFeatures.begin(), ExistingFeatures.end(),
372
2.61k
                      std::back_inserter(UnmatchedReadFeatures));
373
2.61k
374
2.61k
  // If we are allowing compatible differences and the read feature set is
375
2.61k
  // a strict subset of the existing feature set, there is nothing to diagnose.
376
2.61k
  if (
AllowCompatibleDifferences && 2.61k
UnmatchedReadFeatures.empty()387
)
377
385
    return false;
378
2.23k
379
2.23k
  
if (2.23k
Diags2.23k
) {
380
2.21k
    for (StringRef Feature : UnmatchedReadFeatures)
381
0
      Diags->Report(diag::err_pch_targetopt_feature_mismatch)
382
0
          << /* is-existing-feature */ false << Feature;
383
2.21k
    for (StringRef Feature : UnmatchedExistingFeatures)
384
0
      Diags->Report(diag::err_pch_targetopt_feature_mismatch)
385
0
          << /* is-existing-feature */ true << Feature;
386
2.21k
  }
387
2.23k
388
2.23k
  return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
389
2.62k
}
390
391
bool
392
PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
393
                                  bool Complain,
394
2.61k
                                  bool AllowCompatibleDifferences) {
395
2.61k
  const LangOptions &ExistingLangOpts = PP.getLangOpts();
396
2.61k
  return checkLanguageOptions(LangOpts, ExistingLangOpts,
397
2.61k
                              Complain ? 
&Reader.Diags2.21k
:
nullptr393
,
398
2.61k
                              AllowCompatibleDifferences);
399
2.61k
}
400
401
bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
402
                                     bool Complain,
403
2.61k
                                     bool AllowCompatibleDifferences) {
404
2.61k
  const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
405
2.61k
  return checkTargetOptions(TargetOpts, ExistingTargetOpts,
406
2.61k
                            Complain ? 
&Reader.Diags2.21k
:
nullptr393
,
407
2.61k
                            AllowCompatibleDifferences);
408
2.61k
}
409
410
namespace {
411
412
  typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
413
    MacroDefinitionsMap;
414
  typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
415
    DeclsMap;
416
417
} // end anonymous namespace
418
419
static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
420
                                         DiagnosticsEngine &Diags,
421
1.37k
                                         bool Complain) {
422
1.37k
  typedef DiagnosticsEngine::Level Level;
423
1.37k
424
1.37k
  // Check current mappings for new -Werror mappings, and the stored mappings
425
1.37k
  // for cases that were explicitly mapped to *not* be errors that are now
426
1.37k
  // errors because of options like -Werror.
427
1.37k
  DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
428
1.37k
429
2.73k
  for (DiagnosticsEngine *MappingSource : MappingSources) {
430
19.5k
    for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
431
19.5k
      diag::kind DiagID = DiagIDMappingPair.first;
432
19.5k
      Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
433
19.5k
      if (CurLevel < DiagnosticsEngine::Error)
434
18.0k
        continue; // not significant
435
1.53k
      Level StoredLevel =
436
1.53k
          StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
437
1.53k
      if (
StoredLevel < DiagnosticsEngine::Error1.53k
) {
438
5
        if (Complain)
439
0
          Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
440
0
              Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
441
5
        return true;
442
5
      }
443
1.36k
    }
444
2.73k
  }
445
1.36k
446
1.36k
  return false;
447
1.36k
}
448
449
1.37k
static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
450
1.37k
  diag::Severity Ext = Diags.getExtensionHandlingBehavior();
451
1.37k
  if (
Ext == diag::Severity::Warning && 1.37k
Diags.getWarningsAsErrors()5
)
452
5
    return true;
453
1.37k
  return Ext >= diag::Severity::Error;
454
1.37k
}
455
456
static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
457
                                    DiagnosticsEngine &Diags,
458
1.46k
                                    bool IsSystem, bool Complain) {
459
1.46k
  // Top-level options
460
1.46k
  if (
IsSystem1.46k
) {
461
92
    if (Diags.getSuppressSystemWarnings())
462
88
      return false;
463
4
    // If -Wsystem-headers was not enabled before, be conservative
464
4
    
if (4
StoredDiags.getSuppressSystemWarnings()4
) {
465
2
      if (Complain)
466
0
        Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
467
2
      return true;
468
2
    }
469
1.37k
  }
470
1.37k
471
1.37k
  
if (1.37k
Diags.getWarningsAsErrors() && 1.37k
!StoredDiags.getWarningsAsErrors()43
) {
472
5
    if (Complain)
473
0
      Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
474
5
    return true;
475
5
  }
476
1.37k
477
1.37k
  
if (1.37k
Diags.getWarningsAsErrors() && 1.37k
Diags.getEnableAllWarnings()38
&&
478
1.37k
      
!StoredDiags.getEnableAllWarnings()0
) {
479
0
    if (Complain)
480
0
      Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
481
0
    return true;
482
0
  }
483
1.37k
484
1.37k
  
if (1.37k
isExtHandlingFromDiagsError(Diags) &&
485
1.37k
      
!isExtHandlingFromDiagsError(StoredDiags)4
) {
486
1
    if (Complain)
487
0
      Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
488
1
    return true;
489
1
  }
490
1.37k
491
1.37k
  return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
492
1.37k
}
493
494
/// Return the top import module if it is implicit, nullptr otherwise.
495
static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
496
2.24k
                                          Preprocessor &PP) {
497
2.24k
  // If the original import came from a file explicitly generated by the user,
498
2.24k
  // don't check the diagnostic mappings.
499
2.24k
  // FIXME: currently this is approximated by checking whether this is not a
500
2.24k
  // module import of an implicitly-loaded module file.
501
2.24k
  // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
502
2.24k
  // the transitive closure of its imports, since unrelated modules cannot be
503
2.24k
  // imported until after this module finishes validation.
504
2.24k
  ModuleFile *TopImport = &*ModuleMgr.rbegin();
505
2.24k
  while (!TopImport->ImportedBy.empty())
506
0
    TopImport = TopImport->ImportedBy[0];
507
2.24k
  if (TopImport->Kind != MK_ImplicitModule)
508
782
    return nullptr;
509
1.46k
510
1.46k
  StringRef ModuleName = TopImport->ModuleName;
511
1.46k
  assert(!ModuleName.empty() && "diagnostic options read before module name");
512
1.46k
513
1.46k
  Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
514
1.46k
  assert(M && "missing module");
515
1.46k
  return M;
516
1.46k
}
517
518
bool PCHValidator::ReadDiagnosticOptions(
519
2.24k
    IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
520
2.24k
  DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
521
2.24k
  IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
522
2.24k
  IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
523
2.24k
      new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
524
2.24k
  // This should never fail, because we would have processed these options
525
2.24k
  // before writing them to an ASTFile.
526
2.24k
  ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
527
2.24k
528
2.24k
  ModuleManager &ModuleMgr = Reader.getModuleManager();
529
2.24k
  assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
530
2.24k
531
2.24k
  Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
532
2.24k
  if (!TopM)
533
782
    return false;
534
1.46k
535
1.46k
  // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
536
1.46k
  // contains the union of their flags.
537
1.46k
  return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
538
1.46k
                                 Complain);
539
1.46k
}
540
541
/// \brief Collect the macro definitions provided by the given preprocessor
542
/// options.
543
static void
544
collectMacroDefinitions(const PreprocessorOptions &PPOpts,
545
                        MacroDefinitionsMap &Macros,
546
5.16k
                        SmallVectorImpl<StringRef> *MacroNames = nullptr) {
547
7.86k
  for (unsigned I = 0, N = PPOpts.Macros.size(); 
I != N7.86k
;
++I2.70k
) {
548
2.70k
    StringRef Macro = PPOpts.Macros[I].first;
549
2.70k
    bool IsUndef = PPOpts.Macros[I].second;
550
2.70k
551
2.70k
    std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
552
2.70k
    StringRef MacroName = MacroPair.first;
553
2.70k
    StringRef MacroBody = MacroPair.second;
554
2.70k
555
2.70k
    // For an #undef'd macro, we only care about the name.
556
2.70k
    if (
IsUndef2.70k
) {
557
11
      if (
MacroNames && 11
!Macros.count(MacroName)7
)
558
7
        MacroNames->push_back(MacroName);
559
11
560
11
      Macros[MacroName] = std::make_pair("", true);
561
11
      continue;
562
11
    }
563
2.69k
564
2.69k
    // For a #define'd macro, figure out the actual definition.
565
2.69k
    
if (2.69k
MacroName.size() == Macro.size()2.69k
)
566
2.52k
      MacroBody = "1";
567
167
    else {
568
167
      // Note: GCC drops anything following an end-of-line character.
569
167
      StringRef::size_type End = MacroBody.find_first_of("\n\r");
570
167
      MacroBody = MacroBody.substr(0, End);
571
167
    }
572
2.69k
573
2.69k
    if (
MacroNames && 2.69k
!Macros.count(MacroName)1.31k
)
574
1.31k
      MacroNames->push_back(MacroName);
575
2.70k
    Macros[MacroName] = std::make_pair(MacroBody, false);
576
2.70k
  }
577
5.16k
}
578
579
/// \brief Check the preprocessor options deserialized from the control block
580
/// against the preprocessor options in an existing preprocessor.
581
///
582
/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
583
/// \param Validate If true, validate preprocessor options. If false, allow
584
///        macros defined by \p ExistingPPOpts to override those defined by
585
///        \p PPOpts in SuggestedPredefines.
586
static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
587
                                     const PreprocessorOptions &ExistingPPOpts,
588
                                     DiagnosticsEngine *Diags,
589
                                     FileManager &FileMgr,
590
                                     std::string &SuggestedPredefines,
591
                                     const LangOptions &LangOpts,
592
2.58k
                                     bool Validate = true) {
593
2.58k
  // Check macro definitions.
594
2.58k
  MacroDefinitionsMap ASTFileMacros;
595
2.58k
  collectMacroDefinitions(PPOpts, ASTFileMacros);
596
2.58k
  MacroDefinitionsMap ExistingMacros;
597
2.58k
  SmallVector<StringRef, 4> ExistingMacroNames;
598
2.58k
  collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
599
2.58k
600
3.89k
  for (unsigned I = 0, N = ExistingMacroNames.size(); 
I != N3.89k
;
++I1.31k
) {
601
1.32k
    // Dig out the macro definition in the existing preprocessor options.
602
1.32k
    StringRef MacroName = ExistingMacroNames[I];
603
1.32k
    std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
604
1.32k
605
1.32k
    // Check whether we know anything about this macro name or not.
606
1.32k
    llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
607
1.32k
      = ASTFileMacros.find(MacroName);
608
1.32k
    if (
!Validate || 1.32k
Known == ASTFileMacros.end()1.31k
) {
609
56
      // FIXME: Check whether this identifier was referenced anywhere in the
610
56
      // AST file. If so, we should reject the AST file. Unfortunately, this
611
56
      // information isn't in the control block. What shall we do about it?
612
56
613
56
      if (
Existing.second56
) {
614
2
        SuggestedPredefines += "#undef ";
615
2
        SuggestedPredefines += MacroName.str();
616
2
        SuggestedPredefines += '\n';
617
56
      } else {
618
54
        SuggestedPredefines += "#define ";
619
54
        SuggestedPredefines += MacroName.str();
620
54
        SuggestedPredefines += ' ';
621
54
        SuggestedPredefines += Existing.first.str();
622
54
        SuggestedPredefines += '\n';
623
54
      }
624
56
      continue;
625
56
    }
626
1.26k
627
1.26k
    // If the macro was defined in one but undef'd in the other, we have a
628
1.26k
    // conflict.
629
1.26k
    
if (1.26k
Existing.second != Known->second.second1.26k
) {
630
1
      if (
Diags1
) {
631
1
        Diags->Report(diag::err_pch_macro_def_undef)
632
1
          << MacroName << Known->second.second;
633
1
      }
634
1
      return true;
635
1
    }
636
1.26k
637
1.26k
    // If the macro was #undef'd in both, or if the macro bodies are identical,
638
1.26k
    // it's fine.
639
1.26k
    
if (1.26k
Existing.second || 1.26k
Existing.first == Known->second.first1.26k
)
640
1.26k
      continue;
641
5
642
5
    // The macro bodies differ; complain.
643
5
    
if (5
Diags5
) {
644
2
      Diags->Report(diag::err_pch_macro_def_conflict)
645
2
        << MacroName << Known->second.first << Existing.first;
646
2
    }
647
1.32k
    return true;
648
1.32k
  }
649
2.58k
650
2.58k
  // Check whether we're using predefines.
651
2.57k
  
if (2.57k
PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && 2.57k
Validate1
) {
652
1
    if (
Diags1
) {
653
1
      Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
654
1
    }
655
1
    return true;
656
1
  }
657
2.57k
658
2.57k
  // Detailed record is important since it is used for the module cache hash.
659
2.57k
  
if (2.57k
LangOpts.Modules &&
660
2.57k
      
PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord1.50k
&&
Validate0
) {
661
0
    if (
Diags0
) {
662
0
      Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
663
0
    }
664
0
    return true;
665
0
  }
666
2.57k
667
2.57k
  // Compute the #include and #include_macros lines we need.
668
2.59k
  
for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); 2.57k
I != N2.59k
;
++I21
) {
669
21
    StringRef File = ExistingPPOpts.Includes[I];
670
21
    if (File == ExistingPPOpts.ImplicitPCHInclude)
671
0
      continue;
672
21
673
21
    
if (21
std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
674
21
          != PPOpts.Includes.end())
675
0
      continue;
676
21
677
21
    SuggestedPredefines += "#include \"";
678
21
    SuggestedPredefines += File;
679
21
    SuggestedPredefines += "\"\n";
680
21
  }
681
2.57k
682
2.57k
  for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); 
I != N2.57k
;
++I0
) {
683
0
    StringRef File = ExistingPPOpts.MacroIncludes[I];
684
0
    if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
685
0
                  File)
686
0
        != PPOpts.MacroIncludes.end())
687
0
      continue;
688
0
689
0
    SuggestedPredefines += "#__include_macros \"";
690
0
    SuggestedPredefines += File;
691
0
    SuggestedPredefines += "\"\n##\n";
692
0
  }
693
2.58k
694
2.58k
  return false;
695
2.58k
}
696
697
bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
698
                                           bool Complain,
699
2.22k
                                           std::string &SuggestedPredefines) {
700
2.22k
  const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
701
2.22k
702
2.22k
  return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
703
2.22k
                                  Complain? 
&Reader.Diags2.21k
:
nullptr6
,
704
2.22k
                                  PP.getFileManager(),
705
2.22k
                                  SuggestedPredefines,
706
2.22k
                                  PP.getLangOpts());
707
2.22k
}
708
709
bool SimpleASTReaderListener::ReadPreprocessorOptions(
710
                                  const PreprocessorOptions &PPOpts,
711
                                  bool Complain,
712
346
                                  std::string &SuggestedPredefines) {
713
346
  return checkPreprocessorOptions(PPOpts,
714
346
                                  PP.getPreprocessorOpts(),
715
346
                                  nullptr,
716
346
                                  PP.getFileManager(),
717
346
                                  SuggestedPredefines,
718
346
                                  PP.getLangOpts(),
719
346
                                  false);
720
346
}
721
722
/// Check the header search options deserialized from the control block
723
/// against the header search options in an existing preprocessor.
724
///
725
/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
726
static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
727
                                     StringRef SpecificModuleCachePath,
728
                                     StringRef ExistingModuleCachePath,
729
                                     DiagnosticsEngine *Diags,
730
2.23k
                                     const LangOptions &LangOpts) {
731
2.23k
  if (
LangOpts.Modules2.23k
) {
732
1.48k
    if (
SpecificModuleCachePath != ExistingModuleCachePath1.48k
) {
733
2
      if (Diags)
734
2
        Diags->Report(diag::err_pch_modulecache_mismatch)
735
2
          << SpecificModuleCachePath << ExistingModuleCachePath;
736
2
      return true;
737
2
    }
738
2.23k
  }
739
2.23k
740
2.23k
  return false;
741
2.23k
}
742
743
bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
744
                                           StringRef SpecificModuleCachePath,
745
2.22k
                                           bool Complain) {
746
2.22k
  return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
747
2.22k
                                  PP.getHeaderSearchInfo().getModuleCachePath(),
748
2.22k
                                  Complain ? 
&Reader.Diags2.21k
:
nullptr6
,
749
2.22k
                                  PP.getLangOpts());
750
2.22k
}
751
752
3
void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
753
3
  PP.setCounterValue(Value);
754
3
}
755
756
//===----------------------------------------------------------------------===//
757
// AST reader implementation
758
//===----------------------------------------------------------------------===//
759
760
void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
761
3.36k
                                           bool TakeOwnership) {
762
3.36k
  DeserializationListener = Listener;
763
3.36k
  OwnsDeserializationListener = TakeOwnership;
764
3.36k
}
765
766
218
unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
767
218
  return serialization::ComputeHash(Sel);
768
218
}
769
770
std::pair<unsigned, unsigned>
771
172
ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
772
172
  using namespace llvm::support;
773
172
  unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
774
172
  unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
775
172
  return std::make_pair(KeyLen, DataLen);
776
172
}
777
778
ASTSelectorLookupTrait::internal_key_type
779
398
ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
780
398
  using namespace llvm::support;
781
398
  SelectorTable &SelTable = Reader.getContext().Selectors;
782
398
  unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
783
398
  IdentifierInfo *FirstII = Reader.getLocalIdentifier(
784
398
      F, endian::readNext<uint32_t, little, unaligned>(d));
785
398
  if (N == 0)
786
240
    return SelTable.getNullarySelector(FirstII);
787
158
  else 
if (158
N == 1158
)
788
135
    return SelTable.getUnarySelector(FirstII);
789
23
790
23
  SmallVector<IdentifierInfo *, 16> Args;
791
23
  Args.push_back(FirstII);
792
52
  for (unsigned I = 1; 
I != N52
;
++I29
)
793
29
    Args.push_back(Reader.getLocalIdentifier(
794
29
        F, endian::readNext<uint32_t, little, unaligned>(d)));
795
398
796
398
  return SelTable.getSelector(N, Args.data());
797
398
}
798
799
ASTSelectorLookupTrait::data_type
800
ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
801
80
                                 unsigned DataLen) {
802
80
  using namespace llvm::support;
803
80
804
80
  data_type Result;
805
80
806
80
  Result.ID = Reader.getGlobalSelectorID(
807
80
      F, endian::readNext<uint32_t, little, unaligned>(d));
808
80
  unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
809
80
  unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
810
80
  Result.InstanceBits = FullInstanceBits & 0x3;
811
80
  Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
812
80
  Result.FactoryBits = FullFactoryBits & 0x3;
813
80
  Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
814
80
  unsigned NumInstanceMethods = FullInstanceBits >> 3;
815
80
  unsigned NumFactoryMethods = FullFactoryBits >> 3;
816
80
817
80
  // Load instance methods
818
155
  for (unsigned I = 0; 
I != NumInstanceMethods155
;
++I75
) {
819
75
    if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
820
75
            F, endian::readNext<uint32_t, little, unaligned>(d)))
821
75
      Result.Instance.push_back(Method);
822
75
  }
823
80
824
80
  // Load factory methods
825
87
  for (unsigned I = 0; 
I != NumFactoryMethods87
;
++I7
) {
826
7
    if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
827
7
            F, endian::readNext<uint32_t, little, unaligned>(d)))
828
7
      Result.Factory.push_back(Method);
829
7
  }
830
80
831
80
  return Result;
832
80
}
833
834
1.07M
unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
835
1.07M
  return llvm::HashString(a);
836
1.07M
}
837
838
std::pair<unsigned, unsigned>
839
1.46M
ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
840
1.46M
  using namespace llvm::support;
841
1.46M
  unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
842
1.46M
  unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
843
1.46M
  return std::make_pair(KeyLen, DataLen);
844
1.46M
}
845
846
ASTIdentifierLookupTraitBase::internal_key_type
847
623k
ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
848
623k
  assert(n >= 2 && d[n-1] == '\0');
849
623k
  return StringRef((const char*) d, n-1);
850
623k
}
851
852
/// \brief Whether the given identifier is "interesting".
853
static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
854
359k
                                    bool IsModule) {
855
359k
  return II.hadMacroDefinition() ||
856
352k
         II.isPoisoned() ||
857
351k
         
(IsModule ? 351k
II.hasRevertedBuiltin()10.2k
:
II.getObjCOrBuiltinID()340k
) ||
858
350k
         II.hasRevertedTokenIDToIdentifier() ||
859
350k
         
(!(IsModule && 350k
Reader.getPreprocessor().getLangOpts().CPlusPlus10.2k
) &&
860
350k
          II.getFETokenInfo<void>());
861
359k
}
862
863
2.00M
static bool readBit(unsigned &Bits) {
864
2.00M
  bool Value = Bits & 0x1;
865
2.00M
  Bits >>= 1;
866
2.00M
  return Value;
867
2.00M
}
868
869
3.72k
IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
870
3.72k
  using namespace llvm::support;
871
3.72k
  unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
872
3.72k
  return Reader.getGlobalIdentifierID(F, RawID >> 1);
873
3.72k
}
874
875
397k
static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
876
397k
  if (
!II.isFromAST()397k
) {
877
359k
    II.setIsFromAST();
878
359k
    bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
879
359k
    if (isInterestingIdentifier(Reader, II, IsModule))
880
10.9k
      II.setChangedSinceDeserialization();
881
359k
  }
882
397k
}
883
884
IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
885
                                                   const unsigned char* d,
886
350k
                                                   unsigned DataLen) {
887
350k
  using namespace llvm::support;
888
350k
  unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
889
350k
  bool IsInteresting = RawID & 0x01;
890
350k
891
350k
  // Wipe out the "is interesting" bit.
892
350k
  RawID = RawID >> 1;
893
350k
894
350k
  // Build the IdentifierInfo and link the identifier ID with it.
895
350k
  IdentifierInfo *II = KnownII;
896
350k
  if (
!II350k
) {
897
350k
    II = &Reader.getIdentifierTable().getOwn(k);
898
350k
    KnownII = II;
899
350k
  }
900
350k
  markIdentifierFromAST(Reader, *II);
901
350k
  Reader.markIdentifierUpToDate(II);
902
350k
903
350k
  IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
904
350k
  if (
!IsInteresting350k
) {
905
17.4k
    // For uninteresting identifiers, there's nothing else to do. Just notify
906
17.4k
    // the reader that we've finished loading this identifier.
907
17.4k
    Reader.SetIdentifierInfo(ID, II);
908
17.4k
    return II;
909
17.4k
  }
910
333k
911
333k
  unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
912
333k
  unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
913
333k
  bool CPlusPlusOperatorKeyword = readBit(Bits);
914
333k
  bool HasRevertedTokenIDToIdentifier = readBit(Bits);
915
333k
  bool HasRevertedBuiltin = readBit(Bits);
916
333k
  bool Poisoned = readBit(Bits);
917
333k
  bool ExtensionToken = readBit(Bits);
918
333k
  bool HadMacroDefinition = readBit(Bits);
919
333k
920
333k
  assert(Bits == 0 && "Extra bits in the identifier?");
921
333k
  DataLen -= 8;
922
333k
923
333k
  // Set or check the various bits in the IdentifierInfo structure.
924
333k
  // Token IDs are read-only.
925
333k
  if (
HasRevertedTokenIDToIdentifier && 333k
II->getTokenID() != tok::identifier52
)
926
51
    II->revertTokenIDToIdentifier();
927
333k
  if (!F.isModule())
928
325k
    II->setObjCOrBuiltinID(ObjCOrBuiltinID);
929
8.27k
  else 
if (8.27k
HasRevertedBuiltin && 8.27k
II->getBuiltinID()5
) {
930
5
    II->revertBuiltin();
931
5
    assert((II->hasRevertedBuiltin() ||
932
5
            II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
933
5
           "Incorrect ObjC keyword or builtin ID");
934
5
  }
935
333k
  assert(II->isExtensionToken() == ExtensionToken &&
936
333k
         "Incorrect extension token flag");
937
333k
  (void)ExtensionToken;
938
333k
  if (Poisoned)
939
305
    II->setIsPoisoned(true);
940
333k
  assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
941
333k
         "Incorrect C++ operator keyword flag");
942
333k
  (void)CPlusPlusOperatorKeyword;
943
333k
944
333k
  // If this identifier is a macro, deserialize the macro
945
333k
  // definition.
946
333k
  if (
HadMacroDefinition333k
) {
947
34.5k
    uint32_t MacroDirectivesOffset =
948
34.5k
        endian::readNext<uint32_t, little, unaligned>(d);
949
34.5k
    DataLen -= 4;
950
34.5k
951
34.5k
    Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
952
34.5k
  }
953
333k
954
333k
  Reader.SetIdentifierInfo(ID, II);
955
333k
956
333k
  // Read all of the declarations visible at global scope with this
957
333k
  // name.
958
333k
  if (
DataLen > 0333k
) {
959
17.7k
    SmallVector<uint32_t, 4> DeclIDs;
960
35.8k
    for (; 
DataLen > 035.8k
;
DataLen -= 418.1k
)
961
18.1k
      DeclIDs.push_back(Reader.getGlobalDeclID(
962
18.1k
          F, endian::readNext<uint32_t, little, unaligned>(d)));
963
17.7k
    Reader.SetGloballyVisibleDecls(II, DeclIDs);
964
17.7k
  }
965
350k
966
350k
  return II;
967
350k
}
968
969
DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
970
85.8k
    : Kind(Name.getNameKind()) {
971
85.8k
  switch (Kind) {
972
66.1k
  case DeclarationName::Identifier:
973
66.1k
    Data = (uint64_t)Name.getAsIdentifierInfo();
974
66.1k
    break;
975
14.0k
  case DeclarationName::ObjCZeroArgSelector:
976
14.0k
  case DeclarationName::ObjCOneArgSelector:
977
14.0k
  case DeclarationName::ObjCMultiArgSelector:
978
14.0k
    Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
979
14.0k
    break;
980
1.01k
  case DeclarationName::CXXOperatorName:
981
1.01k
    Data = Name.getCXXOverloadedOperator();
982
1.01k
    break;
983
2
  case DeclarationName::CXXLiteralOperatorName:
984
2
    Data = (uint64_t)Name.getCXXLiteralIdentifier();
985
2
    break;
986
0
  case DeclarationName::CXXDeductionGuideName:
987
0
    Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
988
0
               ->getDeclName().getAsIdentifierInfo();
989
0
    break;
990
4.56k
  case DeclarationName::CXXConstructorName:
991
4.56k
  case DeclarationName::CXXDestructorName:
992
4.56k
  case DeclarationName::CXXConversionFunctionName:
993
4.56k
  case DeclarationName::CXXUsingDirective:
994
4.56k
    Data = 0;
995
4.56k
    break;
996
85.8k
  }
997
85.8k
}
998
999
88.8k
unsigned DeclarationNameKey::getHash() const {
1000
88.8k
  llvm::FoldingSetNodeID ID;
1001
88.8k
  ID.AddInteger(Kind);
1002
88.8k
1003
88.8k
  switch (Kind) {
1004
69.1k
  case DeclarationName::Identifier:
1005
69.1k
  case DeclarationName::CXXLiteralOperatorName:
1006
69.1k
  case DeclarationName::CXXDeductionGuideName:
1007
69.1k
    ID.AddString(((IdentifierInfo*)Data)->getName());
1008
69.1k
    break;
1009
14.0k
  case DeclarationName::ObjCZeroArgSelector:
1010
14.0k
  case DeclarationName::ObjCOneArgSelector:
1011
14.0k
  case DeclarationName::ObjCMultiArgSelector:
1012
14.0k
    ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1013
14.0k
    break;
1014
1.02k
  case DeclarationName::CXXOperatorName:
1015
1.02k
    ID.AddInteger((OverloadedOperatorKind)Data);
1016
1.02k
    break;
1017
4.61k
  case DeclarationName::CXXConstructorName:
1018
4.61k
  case DeclarationName::CXXDestructorName:
1019
4.61k
  case DeclarationName::CXXConversionFunctionName:
1020
4.61k
  case DeclarationName::CXXUsingDirective:
1021
4.61k
    break;
1022
88.8k
  }
1023
88.8k
1024
88.8k
  return ID.ComputeHash();
1025
88.8k
}
1026
1027
ModuleFile *
1028
1.46k
ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
1029
1.46k
  using namespace llvm::support;
1030
1.46k
  uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
1031
1.46k
  return Reader.getLocalModuleFile(F, ModuleFileID);
1032
1.46k
}
1033
1034
std::pair<unsigned, unsigned>
1035
25.3k
ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
1036
25.3k
  using namespace llvm::support;
1037
25.3k
  unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
1038
25.3k
  unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
1039
25.3k
  return std::make_pair(KeyLen, DataLen);
1040
25.3k
}
1041
1042
ASTDeclContextNameLookupTrait::internal_key_type
1043
13.7k
ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1044
13.7k
  using namespace llvm::support;
1045
13.7k
1046
13.7k
  auto Kind = (DeclarationName::NameKind)*d++;
1047
13.7k
  uint64_t Data;
1048
13.7k
  switch (Kind) {
1049
12.1k
  case DeclarationName::Identifier:
1050
12.1k
  case DeclarationName::CXXLiteralOperatorName:
1051
12.1k
  case DeclarationName::CXXDeductionGuideName:
1052
12.1k
    Data = (uint64_t)Reader.getLocalIdentifier(
1053
12.1k
        F, endian::readNext<uint32_t, little, unaligned>(d));
1054
12.1k
    break;
1055
114
  case DeclarationName::ObjCZeroArgSelector:
1056
114
  case DeclarationName::ObjCOneArgSelector:
1057
114
  case DeclarationName::ObjCMultiArgSelector:
1058
114
    Data =
1059
114
        (uint64_t)Reader.getLocalSelector(
1060
114
                             F, endian::readNext<uint32_t, little, unaligned>(
1061
114
                                    d)).getAsOpaquePtr();
1062
114
    break;
1063
281
  case DeclarationName::CXXOperatorName:
1064
281
    Data = *d++; // OverloadedOperatorKind
1065
281
    break;
1066
1.15k
  case DeclarationName::CXXConstructorName:
1067
1.15k
  case DeclarationName::CXXDestructorName:
1068
1.15k
  case DeclarationName::CXXConversionFunctionName:
1069
1.15k
  case DeclarationName::CXXUsingDirective:
1070
1.15k
    Data = 0;
1071
1.15k
    break;
1072
13.7k
  }
1073
13.7k
1074
13.7k
  return DeclarationNameKey(Kind, Data);
1075
13.7k
}
1076
1077
void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1078
                                                 const unsigned char *d,
1079
                                                 unsigned DataLen,
1080
13.7k
                                                 data_type_builder &Val) {
1081
13.7k
  using namespace llvm::support;
1082
35.5k
  for (unsigned NumDecls = DataLen / 4; 
NumDecls35.5k
;
--NumDecls21.8k
) {
1083
21.8k
    uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1084
21.8k
    Val.insert(Reader.getGlobalDeclID(F, LocalID));
1085
21.8k
  }
1086
13.7k
}
1087
1088
bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1089
                                              BitstreamCursor &Cursor,
1090
                                              uint64_t Offset,
1091
12.3k
                                              DeclContext *DC) {
1092
12.3k
  assert(Offset != 0);
1093
12.3k
1094
12.3k
  SavedStreamPosition SavedPosition(Cursor);
1095
12.3k
  Cursor.JumpToBit(Offset);
1096
12.3k
1097
12.3k
  RecordData Record;
1098
12.3k
  StringRef Blob;
1099
12.3k
  unsigned Code = Cursor.ReadCode();
1100
12.3k
  unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1101
12.3k
  if (
RecCode != DECL_CONTEXT_LEXICAL12.3k
) {
1102
0
    Error("Expected lexical block");
1103
0
    return true;
1104
0
  }
1105
12.3k
1106
12.3k
  assert(!isa<TranslationUnitDecl>(DC) &&
1107
12.3k
         "expected a TU_UPDATE_LEXICAL record for TU");
1108
12.3k
  // If we are handling a C++ class template instantiation, we can see multiple
1109
12.3k
  // lexical updates for the same record. It's important that we select only one
1110
12.3k
  // of them, so that field numbering works properly. Just pick the first one we
1111
12.3k
  // see.
1112
12.3k
  auto &Lex = LexicalDecls[DC];
1113
12.3k
  if (
!Lex.first12.3k
) {
1114
12.3k
    Lex = std::make_pair(
1115
12.3k
        &M, llvm::makeArrayRef(
1116
12.3k
                reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1117
12.3k
                    Blob.data()),
1118
12.3k
                Blob.size() / 4));
1119
12.3k
  }
1120
12.3k
  DC->setHasExternalLexicalStorage(true);
1121
12.3k
  return false;
1122
12.3k
}
1123
1124
bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1125
                                              BitstreamCursor &Cursor,
1126
                                              uint64_t Offset,
1127
5.19k
                                              DeclID ID) {
1128
5.19k
  assert(Offset != 0);
1129
5.19k
1130
5.19k
  SavedStreamPosition SavedPosition(Cursor);
1131
5.19k
  Cursor.JumpToBit(Offset);
1132
5.19k
1133
5.19k
  RecordData Record;
1134
5.19k
  StringRef Blob;
1135
5.19k
  unsigned Code = Cursor.ReadCode();
1136
5.19k
  unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1137
5.19k
  if (
RecCode != DECL_CONTEXT_VISIBLE5.19k
) {
1138
0
    Error("Expected visible lookup table block");
1139
0
    return true;
1140
0
  }
1141
5.19k
1142
5.19k
  // We can't safely determine the primary context yet, so delay attaching the
1143
5.19k
  // lookup table until we're done with recursive deserialization.
1144
5.19k
  auto *Data = (const unsigned char*)Blob.data();
1145
5.19k
  PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
1146
5.19k
  return false;
1147
5.19k
}
1148
1149
3
void ASTReader::Error(StringRef Msg) const {
1150
3
  Error(diag::err_fe_pch_malformed, Msg);
1151
3
  if (
PP.getLangOpts().Modules && 3
!Diags.isDiagnosticInFlight()2
&&
1152
3
      
!PP.getHeaderSearchInfo().getModuleCachePath().empty()1
) {
1153
0
    Diag(diag::note_module_cache_path)
1154
0
      << PP.getHeaderSearchInfo().getModuleCachePath();
1155
0
  }
1156
3
}
1157
1158
void ASTReader::Error(unsigned DiagID,
1159
12
                      StringRef Arg1, StringRef Arg2) const {
1160
12
  if (Diags.isDiagnosticInFlight())
1161
1
    Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1162
12
  else
1163
11
    Diag(DiagID) << Arg1 << Arg2;
1164
12
}
1165
1166
//===----------------------------------------------------------------------===//
1167
// Source Manager Deserialization
1168
//===----------------------------------------------------------------------===//
1169
1170
/// \brief Read the line table in the source manager block.
1171
/// \returns true if there was an error.
1172
bool ASTReader::ParseLineTable(ModuleFile &F,
1173
4.48k
                               const RecordData &Record) {
1174
4.48k
  unsigned Idx = 0;
1175
4.48k
  LineTableInfo &LineTable = SourceMgr.getLineTable();
1176
4.48k
1177
4.48k
  // Parse the file names
1178
4.48k
  std::map<int, int> FileIDs;
1179
13.2k
  for (unsigned I = 0; 
Record[Idx]13.2k
;
++I8.80k
) {
1180
8.80k
    // Extract the file name
1181
8.80k
    auto Filename = ReadPath(F, Record, Idx);
1182
8.80k
    FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1183
8.80k
  }
1184
4.48k
  ++Idx;
1185
4.48k
1186
4.48k
  // Parse the line entries
1187
4.48k
  std::vector<LineEntry> Entries;
1188
8.87k
  while (
Idx < Record.size()8.87k
) {
1189
4.38k
    int FID = Record[Idx++];
1190
4.38k
    assert(FID >= 0 && "Serialized line entries for non-local file.");
1191
4.38k
    // Remap FileID from 1-based old view.
1192
4.38k
    FID += F.SLocEntryBaseID - 1;
1193
4.38k
1194
4.38k
    // Extract the line entries
1195
4.38k
    unsigned NumEntries = Record[Idx++];
1196
4.38k
    assert(NumEntries && "no line entries for file ID");
1197
4.38k
    Entries.clear();
1198
4.38k
    Entries.reserve(NumEntries);
1199
17.7k
    for (unsigned I = 0; 
I != NumEntries17.7k
;
++I13.3k
) {
1200
13.3k
      unsigned FileOffset = Record[Idx++];
1201
13.3k
      unsigned LineNo = Record[Idx++];
1202
13.3k
      int FilenameID = FileIDs[Record[Idx++]];
1203
13.3k
      SrcMgr::CharacteristicKind FileKind
1204
13.3k
        = (SrcMgr::CharacteristicKind)Record[Idx++];
1205
13.3k
      unsigned IncludeOffset = Record[Idx++];
1206
13.3k
      Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1207
13.3k
                                       FileKind, IncludeOffset));
1208
13.3k
    }
1209
4.38k
    LineTable.AddEntry(FileID::get(FID), Entries);
1210
4.38k
  }
1211
4.48k
1212
4.48k
  return false;
1213
4.48k
}
1214
1215
/// \brief Read a source manager block
1216
4.48k
bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1217
4.48k
  using namespace SrcMgr;
1218
4.48k
1219
4.48k
  BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1220
4.48k
1221
4.48k
  // Set the source-location entry cursor to the current position in
1222
4.48k
  // the stream. This cursor will be used to read the contents of the
1223
4.48k
  // source manager block initially, and then lazily read
1224
4.48k
  // source-location entries as needed.
1225
4.48k
  SLocEntryCursor = F.Stream;
1226
4.48k
1227
4.48k
  // The stream itself is going to skip over the source manager block.
1228
4.48k
  if (
F.Stream.SkipBlock()4.48k
) {
1229
0
    Error("malformed block record in AST file");
1230
0
    return true;
1231
0
  }
1232
4.48k
1233
4.48k
  // Enter the source manager block.
1234
4.48k
  
if (4.48k
SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)4.48k
) {
1235
0
    Error("malformed source manager block record in AST file");
1236
0
    return true;
1237
0
  }
1238
4.48k
1239
4.48k
  RecordData Record;
1240
4.48k
  while (
true4.48k
) {
1241
4.48k
    llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1242
4.48k
1243
4.48k
    switch (E.Kind) {
1244
0
    case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1245
0
    case llvm::BitstreamEntry::Error:
1246
0
      Error("malformed block record in AST file");
1247
0
      return true;
1248
0
    case llvm::BitstreamEntry::EndBlock:
1249
0
      return false;
1250
4.48k
    case llvm::BitstreamEntry::Record:
1251
4.48k
      // The interesting case.
1252
4.48k
      break;
1253
4.48k
    }
1254
4.48k
1255
4.48k
    // Read a record.
1256
4.48k
    Record.clear();
1257
4.48k
    StringRef Blob;
1258
4.48k
    switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
1259
0
    default:  // Default behavior: ignore.
1260
0
      break;
1261
4.48k
1262
4.48k
    case SM_SLOC_FILE_ENTRY:
1263
4.48k
    case SM_SLOC_BUFFER_ENTRY:
1264
4.48k
    case SM_SLOC_EXPANSION_ENTRY:
1265
4.48k
      // Once we hit one of the source location entries, we're done.
1266
4.48k
      return false;
1267
4.48k
    }
1268
4.48k
  }
1269
4.48k
}
1270
1271
/// \brief If a header file is not found at the path that we expect it to be
1272
/// and the PCH file was moved from its original location, try to resolve the
1273
/// file by assuming that header+PCH were moved together and the header is in
1274
/// the same place relative to the PCH.
1275
static std::string
1276
resolveFileRelativeToOriginalDir(const std::string &Filename,
1277
                                 const std::string &OriginalDir,
1278
38
                                 const std::string &CurrDir) {
1279
38
  assert(OriginalDir != CurrDir &&
1280
38
         "No point trying to resolve the file if the PCH dir didn't change");
1281
38
  using namespace llvm::sys;
1282
38
  SmallString<128> filePath(Filename);
1283
38
  fs::make_absolute(filePath);
1284
38
  assert(path::is_absolute(OriginalDir));
1285
38
  SmallString<128> currPCHPath(CurrDir);
1286
38
1287
38
  path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1288
38
                       fileDirE = path::end(path::parent_path(filePath));
1289
38
  path::const_iterator origDirI = path::begin(OriginalDir),
1290
38
                       origDirE = path::end(OriginalDir);
1291
38
  // Skip the common path components from filePath and OriginalDir.
1292
253
  while (
fileDirI != fileDirE && 253
origDirI != origDirE253
&&
1293
253
         
*fileDirI == *origDirI253
) {
1294
215
    ++fileDirI;
1295
215
    ++origDirI;
1296
215
  }
1297
298
  for (; 
origDirI != origDirE298
;
++origDirI260
)
1298
260
    path::append(currPCHPath, "..");
1299
38
  path::append(currPCHPath, fileDirI, fileDirE);
1300
38
  path::append(currPCHPath, path::filename(Filename));
1301
38
  return currPCHPath.str();
1302
38
}
1303
1304
9.00k
bool ASTReader::ReadSLocEntry(int ID) {
1305
9.00k
  if (ID == 0)
1306
0
    return false;
1307
9.00k
1308
9.00k
  
if (9.00k
unsigned(-ID) - 2 >= getTotalNumSLocs() || 9.00k
ID > 09.00k
) {
1309
0
    Error("source location entry ID out-of-range for AST file");
1310
0
    return true;
1311
0
  }
1312
9.00k
1313
9.00k
  // Local helper to read the (possibly-compressed) buffer data following the
1314
9.00k
  // entry record.
1315
9.00k
  auto ReadBuffer = [this](
1316
9.00k
      BitstreamCursor &SLocEntryCursor,
1317
5.10k
      StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1318
5.10k
    RecordData Record;
1319
5.10k
    StringRef Blob;
1320
5.10k
    unsigned Code = SLocEntryCursor.ReadCode();
1321
5.10k
    unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1322
5.10k
1323
5.10k
    if (
RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED5.10k
) {
1324
5.10k
      if (
!llvm::zlib::isAvailable()5.10k
) {
1325
0
        Error("zlib is not available");
1326
0
        return nullptr;
1327
0
      }
1328
5.10k
      SmallString<0> Uncompressed;
1329
5.10k
      if (llvm::Error E =
1330
0
              llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
1331
0
        Error("could not decompress embedded file contents: " +
1332
0
              llvm::toString(std::move(E)));
1333
0
        return nullptr;
1334
0
      }
1335
5.10k
      return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1336
0
    } else 
if (0
RecCode == SM_SLOC_BUFFER_BLOB0
) {
1337
0
      return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1338
0
    } else {
1339
0
      Error("AST record has invalid code");
1340
0
      return nullptr;
1341
0
    }
1342
0
  };
1343
9.00k
1344
9.00k
  ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1345
9.00k
  F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
1346
9.00k
  BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1347
9.00k
  unsigned BaseOffset = F->SLocEntryBaseOffset;
1348
9.00k
1349
9.00k
  ++NumSLocEntriesRead;
1350
9.00k
  llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1351
9.00k
  if (
Entry.Kind != llvm::BitstreamEntry::Record9.00k
) {
1352
0
    Error("incorrectly-formatted source location entry in AST file");
1353
0
    return true;
1354
0
  }
1355
9.00k
1356
9.00k
  RecordData Record;
1357
9.00k
  StringRef Blob;
1358
9.00k
  switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
1359
0
  default:
1360
0
    Error("incorrectly-formatted source location entry in AST file");
1361
0
    return true;
1362
9.00k
1363
3.46k
  case SM_SLOC_FILE_ENTRY: {
1364
3.46k
    // We will detect whether a file changed and return 'Failure' for it, but
1365
3.46k
    // we will also try to fail gracefully by setting up the SLocEntry.
1366
3.46k
    unsigned InputID = Record[4];
1367
3.46k
    InputFile IF = getInputFile(*F, InputID);
1368
3.46k
    const FileEntry *File = IF.getFile();
1369
3.46k
    bool OverriddenBuffer = IF.isOverridden();
1370
3.46k
1371
3.46k
    // Note that we only check if a File was returned. If it was out-of-date
1372
3.46k
    // we have complained but we will continue creating a FileID to recover
1373
3.46k
    // gracefully.
1374
3.46k
    if (!File)
1375
78
      return true;
1376
3.38k
1377
3.38k
    SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1378
3.38k
    if (
IncludeLoc.isInvalid() && 3.38k
F->Kind != MK_MainFile1.46k
) {
1379
1.36k
      // This is the module's main file.
1380
1.36k
      IncludeLoc = getImportLocation(F);
1381
1.36k
    }
1382
3.38k
    SrcMgr::CharacteristicKind
1383
3.38k
      FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1384
3.38k
    FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1385
3.38k
                                        ID, BaseOffset + Record[0]);
1386
3.38k
    SrcMgr::FileInfo &FileInfo =
1387
3.38k
          const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1388
3.38k
    FileInfo.NumCreatedFIDs = Record[5];
1389
3.38k
    if (Record[3])
1390
20
      FileInfo.setHasLineDirectives();
1391
3.38k
1392
3.38k
    const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1393
3.38k
    unsigned NumFileDecls = Record[7];
1394
3.38k
    if (
NumFileDecls && 3.38k
ContextObj2.35k
) {
1395
2.30k
      assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1396
2.30k
      FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1397
2.30k
                                                             NumFileDecls));
1398
2.30k
    }
1399
3.38k
1400
3.38k
    const SrcMgr::ContentCache *ContentCache
1401
3.38k
      = SourceMgr.getOrCreateContentCache(File, isSystem(FileCharacter));
1402
3.38k
    if (
OverriddenBuffer && 3.38k
!ContentCache->BufferOverridden227
&&
1403
42
        ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1404
3.38k
        
!ContentCache->getRawBuffer()42
) {
1405
40
      auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1406
40
      if (!Buffer)
1407
0
        return true;
1408
40
      SourceMgr.overrideFileContents(File, std::move(Buffer));
1409
40
    }
1410
3.38k
1411
3.38k
    break;
1412
3.38k
  }
1413
3.38k
1414
5.06k
  case SM_SLOC_BUFFER_ENTRY: {
1415
5.06k
    const char *Name = Blob.data();
1416
5.06k
    unsigned Offset = Record[0];
1417
5.06k
    SrcMgr::CharacteristicKind
1418
5.06k
      FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1419
5.06k
    SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1420
5.06k
    if (
IncludeLoc.isInvalid() && 5.06k
F->isModule()5.06k
) {
1421
3.68k
      IncludeLoc = getImportLocation(F);
1422
3.68k
    }
1423
5.06k
1424
5.06k
    auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1425
5.06k
    if (!Buffer)
1426
0
      return true;
1427
5.06k
    SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
1428
5.06k
                           BaseOffset + Offset, IncludeLoc);
1429
5.06k
    break;
1430
5.06k
  }
1431
5.06k
1432
471
  case SM_SLOC_EXPANSION_ENTRY: {
1433
471
    SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1434
471
    SourceMgr.createExpansionLoc(SpellingLoc,
1435
471
                                     ReadSourceLocation(*F, Record[2]),
1436
471
                                     ReadSourceLocation(*F, Record[3]),
1437
471
                                     Record[4],
1438
471
                                     ID,
1439
471
                                     BaseOffset + Record[0]);
1440
471
    break;
1441
8.92k
  }
1442
8.92k
  }
1443
8.92k
1444
8.92k
  return false;
1445
8.92k
}
1446
1447
36
std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1448
36
  if (ID == 0)
1449
0
    return std::make_pair(SourceLocation(), "");
1450
36
1451
36
  
if (36
unsigned(-ID) - 2 >= getTotalNumSLocs() || 36
ID > 036
) {
1452
0
    Error("source location entry ID out-of-range for AST file");
1453
0
    return std::make_pair(SourceLocation(), "");
1454
0
  }
1455
36
1456
36
  // Find which module file this entry lands in.
1457
36
  ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1458
36
  if (!M->isModule())
1459
10
    return std::make_pair(SourceLocation(), "");
1460
26
1461
26
  // FIXME: Can we map this down to a particular submodule? That would be
1462
26
  // ideal.
1463
26
  return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
1464
26
}
1465
1466
/// \brief Find the location where the module F is imported.
1467
5.04k
SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1468
5.04k
  if (F->ImportLoc.isValid())
1469
2.71k
    return F->ImportLoc;
1470
2.33k
1471
2.33k
  // Otherwise we have a PCH. It's considered to be "imported" at the first
1472
2.33k
  // location of its includer.
1473
2.33k
  
if (2.33k
F->ImportedBy.empty() || 2.33k
!F->ImportedBy[0]1.21k
) {
1474
1.12k
    // Main file is the importer.
1475
1.12k
    assert(SourceMgr.getMainFileID().isValid() && "missing main file");
1476
1.12k
    return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
1477
1.12k
  }
1478
1.21k
  return F->ImportedBy[0]->FirstLoc;
1479
1.21k
}
1480
1481
/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1482
/// specified cursor.  Read the abbreviations that are at the top of the block
1483
/// and then leave the cursor pointing into the block.
1484
18.6k
bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
1485
18.6k
  if (Cursor.EnterSubBlock(BlockID))
1486
0
    return true;
1487
18.6k
1488
95.6k
  
while (18.6k
true95.6k
) {
1489
95.6k
    uint64_t Offset = Cursor.GetCurrentBitNo();
1490
95.6k
    unsigned Code = Cursor.ReadCode();
1491
95.6k
1492
95.6k
    // We expect all abbrevs to be at the start of the block.
1493
95.6k
    if (
Code != llvm::bitc::DEFINE_ABBREV95.6k
) {
1494
18.6k
      Cursor.JumpToBit(Offset);
1495
18.6k
      return false;
1496
18.6k
    }
1497
77.0k
    Cursor.ReadAbbrevRecord();
1498
77.0k
  }
1499
18.6k
}
1500
1501
Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
1502
41.9k
                           unsigned &Idx) {
1503
41.9k
  Token Tok;
1504
41.9k
  Tok.startToken();
1505
41.9k
  Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1506
41.9k
  Tok.setLength(Record[Idx++]);
1507
41.9k
  if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1508
9.14k
    Tok.setIdentifierInfo(II);
1509
41.9k
  Tok.setKind((tok::TokenKind)Record[Idx++]);
1510
41.9k
  Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1511
41.9k
  return Tok;
1512
41.9k
}
1513
1514
34.7k
MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
1515
34.7k
  BitstreamCursor &Stream = F.MacroCursor;
1516
34.7k
1517
34.7k
  // Keep track of where we are in the stream, then jump back there
1518
34.7k
  // after reading this macro.
1519
34.7k
  SavedStreamPosition SavedPosition(Stream);
1520
34.7k
1521
34.7k
  Stream.JumpToBit(Offset);
1522
34.7k
  RecordData Record;
1523
34.7k
  SmallVector<IdentifierInfo*, 16> MacroParams;
1524
34.7k
  MacroInfo *Macro = nullptr;
1525
34.7k
1526
110k
  while (
true110k
) {
1527
110k
    // Advance to the next record, but if we get to the end of the block, don't
1528
110k
    // pop it (removing all the abbreviations from the cursor) since we want to
1529
110k
    // be able to reseek within the block and read entries.
1530
110k
    unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
1531
110k
    llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1532
110k
1533
110k
    switch (Entry.Kind) {
1534
0
    case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1535
0
    case llvm::BitstreamEntry::Error:
1536
0
      Error("malformed block record in AST file");
1537
0
      return Macro;
1538
745
    case llvm::BitstreamEntry::EndBlock:
1539
745
      return Macro;
1540
110k
    case llvm::BitstreamEntry::Record:
1541
110k
      // The interesting case.
1542
110k
      break;
1543
110k
    }
1544
110k
1545
110k
    // Read a record.
1546
110k
    Record.clear();
1547
110k
    PreprocessorRecordTypes RecType =
1548
110k
      (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
1549
110k
    switch (RecType) {
1550
0
    case PP_MODULE_MACRO:
1551
0
    case PP_MACRO_DIRECTIVE_HISTORY:
1552
0
      return Macro;
1553
0
1554
68.6k
    case PP_MACRO_OBJECT_LIKE:
1555
68.6k
    case PP_MACRO_FUNCTION_LIKE: {
1556
68.6k
      // If we already have a macro, that means that we've hit the end
1557
68.6k
      // of the definition of the macro we were looking for. We're
1558
68.6k
      // done.
1559
68.6k
      if (Macro)
1560
33.9k
        return Macro;
1561
34.7k
1562
34.7k
      unsigned NextIndex = 1; // Skip identifier ID.
1563
34.7k
      SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
1564
34.7k
      MacroInfo *MI = PP.AllocateMacroInfo(Loc);
1565
34.7k
      MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
1566
34.7k
      MI->setIsUsed(Record[NextIndex++]);
1567
34.7k
      MI->setUsedForHeaderGuard(Record[NextIndex++]);
1568
34.7k
1569
34.7k
      if (
RecType == PP_MACRO_FUNCTION_LIKE34.7k
) {
1570
643
        // Decode function-like macro info.
1571
643
        bool isC99VarArgs = Record[NextIndex++];
1572
643
        bool isGNUVarArgs = Record[NextIndex++];
1573
643
        bool hasCommaPasting = Record[NextIndex++];
1574
643
        MacroParams.clear();
1575
643
        unsigned NumArgs = Record[NextIndex++];
1576
1.33k
        for (unsigned i = 0; 
i != NumArgs1.33k
;
++i696
)
1577
696
          MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1578
643
1579
643
        // Install function-like macro info.
1580
643
        MI->setIsFunctionLike();
1581
643
        if (
isC99VarArgs643
)
MI->setIsC99Varargs()2
;
1582
643
        if (
isGNUVarArgs643
)
MI->setIsGNUVarargs()0
;
1583
643
        if (
hasCommaPasting643
)
MI->setHasCommaPasting()0
;
1584
643
        MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
1585
643
      }
1586
34.7k
1587
34.7k
      // Remember that we saw this macro last so that we add the tokens that
1588
34.7k
      // form its body to it.
1589
34.7k
      Macro = MI;
1590
34.7k
1591
34.7k
      if (
NextIndex + 1 == Record.size() && 34.7k
PP.getPreprocessingRecord()31.7k
&&
1592
34.7k
          
Record[NextIndex]31.7k
) {
1593
31.7k
        // We have a macro definition. Register the association
1594
31.7k
        PreprocessedEntityID
1595
31.7k
            GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1596
31.7k
        PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
1597
31.7k
        PreprocessingRecord::PPEntityID PPID =
1598
31.7k
            PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1599
31.7k
        MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1600
31.7k
            PPRec.getPreprocessedEntity(PPID));
1601
31.7k
        if (PPDef)
1602
31.7k
          PPRec.RegisterMacroDefinition(Macro, PPDef);
1603
31.7k
      }
1604
34.7k
1605
34.7k
      ++NumMacrosRead;
1606
34.7k
      break;
1607
34.7k
    }
1608
34.7k
1609
41.4k
    case PP_TOKEN: {
1610
41.4k
      // If we see a TOKEN before a PP_MACRO_*, then the file is
1611
41.4k
      // erroneous, just pretend we didn't see this.
1612
41.4k
      if (
!Macro41.4k
)
break0
;
1613
41.4k
1614
41.4k
      unsigned Idx = 0;
1615
41.4k
      Token Tok = ReadToken(F, Record, Idx);
1616
41.4k
      Macro->AddTokenToBody(Tok);
1617
41.4k
      break;
1618
41.4k
    }
1619
110k
    }
1620
110k
  }
1621
34.7k
}
1622
1623
PreprocessedEntityID
1624
ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
1625
31.7k
                                         unsigned LocalID) const {
1626
31.7k
  if (!M.ModuleOffsetMap.empty())
1627
0
    ReadModuleOffsetMap(M);
1628
31.7k
1629
31.7k
  ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1630
31.7k
    I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1631
31.7k
  assert(I != M.PreprocessedEntityRemap.end()
1632
31.7k
         && "Invalid index into preprocessed entity index remap");
1633
31.7k
1634
31.7k
  return LocalID + I->second;
1635
31.7k
}
1636
1637
54.1k
unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1638
54.1k
  return llvm::hash_combine(ikey.Size, ikey.ModTime);
1639
54.1k
}
1640
1641
HeaderFileInfoTrait::internal_key_type
1642
54.1k
HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1643
54.1k
  internal_key_type ikey = {FE->getSize(),
1644
54.1k
                            M.HasTimestamps ? 
FE->getModificationTime()25.2k
:
028.8k
,
1645
54.1k
                            FE->getName(), /*Imported*/ false};
1646
54.1k
  return ikey;
1647
54.1k
}
1648
1649
12.9k
bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1650
12.9k
  if (
a.Size != b.Size || 12.9k
(a.ModTime && 12.9k
b.ModTime2.64k
&&
a.ModTime != b.ModTime2.64k
))
1651
0
    return false;
1652
12.9k
1653
12.9k
  
if (12.9k
llvm::sys::path::is_absolute(a.Filename) && 12.9k
a.Filename == b.Filename759
)
1654
737
    return true;
1655
12.1k
1656
12.1k
  // Determine whether the actual files are equivalent.
1657
12.1k
  FileManager &FileMgr = Reader.getFileManager();
1658
24.3k
  auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1659
24.3k
    if (!Key.Imported)
1660
12.1k
      return FileMgr.getFile(Key.Filename);
1661
12.1k
1662
12.1k
    std::string Resolved = Key.Filename;
1663
12.1k
    Reader.ResolveImportedPath(M, Resolved);
1664
12.1k
    return FileMgr.getFile(Resolved);
1665
12.1k
  };
1666
12.1k
1667
12.1k
  const FileEntry *FEA = GetFile(a);
1668
12.1k
  const FileEntry *FEB = GetFile(b);
1669
12.1k
  return FEA && FEA == FEB;
1670
12.9k
}
1671
1672
std::pair<unsigned, unsigned>
1673
78.0k
HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1674
78.0k
  using namespace llvm::support;
1675
78.0k
  unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
1676
78.0k
  unsigned DataLen = (unsigned) *d++;
1677
78.0k
  return std::make_pair(KeyLen, DataLen);
1678
78.0k
}
1679
1680
HeaderFileInfoTrait::internal_key_type
1681
12.9k
HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
1682
12.9k
  using namespace llvm::support;
1683
12.9k
  internal_key_type ikey;
1684
12.9k
  ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1685
12.9k
  ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
1686
12.9k
  ikey.Filename = (const char *)d;
1687
12.9k
  ikey.Imported = true;
1688
12.9k
  return ikey;
1689
12.9k
}
1690
1691
HeaderFileInfoTrait::data_type
1692
HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
1693
3.37k
                              unsigned DataLen) {
1694
3.37k
  const unsigned char *End = d + DataLen;
1695
3.37k
  using namespace llvm::support;
1696
3.37k
  HeaderFileInfo HFI;
1697
3.37k
  unsigned Flags = *d++;
1698
3.37k
  // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1699
3.37k
  HFI.isImport |= (Flags >> 5) & 0x01;
1700
3.37k
  HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
1701
3.37k
  HFI.DirInfo = (Flags >> 1) & 0x07;
1702
3.37k
  HFI.IndexHeaderMapHeader = Flags & 0x01;
1703
3.37k
  // FIXME: Find a better way to handle this. Maybe just store a
1704
3.37k
  // "has been included" flag?
1705
3.37k
  HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1706
3.37k
                             HFI.NumIncludes);
1707
3.37k
  HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1708
3.37k
      M, endian::readNext<uint32_t, little, unaligned>(d));
1709
3.37k
  if (unsigned FrameworkOffset =
1710
0
          endian::readNext<uint32_t, little, unaligned>(d)) {
1711
0
    // The framework offset is 1 greater than the actual offset,
1712
0
    // since 0 is used as an indicator for "no framework name".
1713
0
    StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1714
0
    HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1715
0
  }
1716
3.37k
1717
3.37k
  assert((End - d) % 4 == 0 &&
1718
3.37k
         "Wrong data length in HeaderFileInfo deserialization");
1719
5.94k
  while (
d != End5.94k
) {
1720
2.57k
    uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
1721
2.57k
    auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1722
2.57k
    LocalSMID >>= 2;
1723
2.57k
1724
2.57k
    // This header is part of a module. Associate it with the module to enable
1725
2.57k
    // implicit module import.
1726
2.57k
    SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1727
2.57k
    Module *Mod = Reader.getSubmodule(GlobalSMID);
1728
2.57k
    FileManager &FileMgr = Reader.getFileManager();
1729
2.57k
    ModuleMap &ModMap =
1730
2.57k
        Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1731
2.57k
1732
2.57k
    std::string Filename = key.Filename;
1733
2.57k
    if (key.Imported)
1734
2.57k
      Reader.ResolveImportedPath(M, Filename);
1735
2.57k
    // FIXME: This is not always the right filename-as-written, but we're not
1736
2.57k
    // going to use this information to rebuild the module, so it doesn't make
1737
2.57k
    // a lot of difference.
1738
2.57k
    Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
1739
2.57k
    ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1740
2.57k
    HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
1741
2.57k
  }
1742
3.37k
1743
3.37k
  // This HeaderFileInfo was externally loaded.
1744
3.37k
  HFI.External = true;
1745
3.37k
  HFI.IsValid = true;
1746
3.37k
  return HFI;
1747
3.37k
}
1748
1749
void ASTReader::addPendingMacro(IdentifierInfo *II,
1750
                                ModuleFile *M,
1751
34.5k
                                uint64_t MacroDirectivesOffset) {
1752
34.5k
  assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1753
34.5k
  PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
1754
34.5k
}
1755
1756
70
void ASTReader::ReadDefinedMacros() {
1757
70
  // Note that we are loading defined macros.
1758
70
  Deserializing Macros(this);
1759
70
1760
84
  for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
1761
84
    BitstreamCursor &MacroCursor = I.MacroCursor;
1762
84
1763
84
    // If there was no preprocessor block, skip this file.
1764
84
    if (MacroCursor.getBitcodeBytes().empty())
1765
0
      continue;
1766
84
1767
84
    BitstreamCursor Cursor = MacroCursor;
1768
84
    Cursor.JumpToBit(I.MacroStartOffset);
1769
84
1770
84
    RecordData Record;
1771
75.2k
    while (
true75.2k
) {
1772
75.2k
      llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1773
75.2k
1774
75.2k
      switch (E.Kind) {
1775
0
      case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1776
0
      case llvm::BitstreamEntry::Error:
1777
0
        Error("malformed block record in AST file");
1778
0
        return;
1779
84
      case llvm::BitstreamEntry::EndBlock:
1780
84
        goto NextCursor;
1781
0
1782
75.1k
      case llvm::BitstreamEntry::Record:
1783
75.1k
        Record.clear();
1784
75.1k
        switch (Cursor.readRecord(E.ID, Record)) {
1785
23.3k
        default:  // Default behavior: ignore.
1786
23.3k
          break;
1787
75.1k
1788
23.4k
        case PP_MACRO_OBJECT_LIKE:
1789
23.4k
        case PP_MACRO_FUNCTION_LIKE: {
1790
23.4k
          IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
1791
23.4k
          if (II->isOutOfDate())
1792
16
            updateOutOfDateIdentifier(*II);
1793
23.4k
          break;
1794
23.4k
        }
1795
23.4k
1796
28.3k
        case PP_TOKEN:
1797
28.3k
          // Ignore tokens.
1798
28.3k
          break;
1799
75.1k
        }
1800
75.1k
        break;
1801
75.2k
      }
1802
75.2k
    }
1803
84
    NextCursor:  ;
1804
84
  }
1805
70
}
1806
1807
namespace {
1808
1809
  /// \brief Visitor class used to look up identifirs in an AST file.
1810
  class IdentifierLookupVisitor {
1811
    StringRef Name;
1812
    unsigned NameHash;
1813
    unsigned PriorGeneration;
1814
    unsigned &NumIdentifierLookups;
1815
    unsigned &NumIdentifierLookupHits;
1816
    IdentifierInfo *Found;
1817
1818
  public:
1819
    IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1820
                            unsigned &NumIdentifierLookups,
1821
                            unsigned &NumIdentifierLookupHits)
1822
      : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1823
        PriorGeneration(PriorGeneration),
1824
        NumIdentifierLookups(NumIdentifierLookups),
1825
        NumIdentifierLookupHits(NumIdentifierLookupHits),
1826
        Found()
1827
1.07M
    {
1828
1.07M
    }
1829
1830
1.16M
    bool operator()(ModuleFile &M) {
1831
1.16M
      // If we've already searched this module file, skip it now.
1832
1.16M
      if (M.Generation <= PriorGeneration)
1833
623
        return true;
1834
1.16M
1835
1.16M
      ASTIdentifierLookupTable *IdTable
1836
1.16M
        = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1837
1.16M
      if (!IdTable)
1838
1
        return false;
1839
1.16M
1840
1.16M
      ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
1841
1.16M
                                     Found);
1842
1.16M
      ++NumIdentifierLookups;
1843
1.16M
      ASTIdentifierLookupTable::iterator Pos =
1844
1.16M
          IdTable->find_hashed(Name, NameHash, &Trait);
1845
1.16M
      if (Pos == IdTable->end())
1846
810k
        return false;
1847
350k
1848
350k
      // Dereferencing the iterator has the effect of building the
1849
350k
      // IdentifierInfo node and populating it with the various
1850
350k
      // declarations it needs.
1851
350k
      ++NumIdentifierLookupHits;
1852
350k
      Found = *Pos;
1853
350k
      return true;
1854
350k
    }
1855
1856
    // \brief Retrieve the identifier info found within the module
1857
    // files.
1858
492k
    IdentifierInfo *getIdentifierInfo() const { return Found; }
1859
  };
1860
1861
} // end anonymous namespace
1862
1863
586k
void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1864
586k
  // Note that we are loading an identifier.
1865
586k
  Deserializing AnIdentifier(this);
1866
586k
1867
586k
  unsigned PriorGeneration = 0;
1868
586k
  if (getContext().getLangOpts().Modules)
1869
568k
    PriorGeneration = IdentifierGeneration[&II];
1870
586k
1871
586k
  // If there is a global index, look there first to determine which modules
1872
586k
  // provably do not have any results for this identifier.
1873
586k
  GlobalModuleIndex::HitSet Hits;
1874
586k
  GlobalModuleIndex::HitSet *HitsPtr = nullptr;
1875
586k
  if (
!loadGlobalIndex()586k
) {
1876
141k
    if (
GlobalIndex->lookupIdentifier(II.getName(), Hits)141k
) {
1877
141k
      HitsPtr = &Hits;
1878
141k
    }
1879
141k
  }
1880
586k
1881
586k
  IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
1882
586k
                                  NumIdentifierLookups,
1883
586k
                                  NumIdentifierLookupHits);
1884
586k
  ModuleMgr.visit(Visitor, HitsPtr);
1885
586k
  markIdentifierUpToDate(&II);
1886
586k
}
1887
1888
1.42M
void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1889
1.42M
  if (!II)
1890
152k
    return;
1891
1.27M
1892
1.27M
  II->setOutOfDate(false);
1893
1.27M
1894
1.27M
  // Update the generation for this identifier.
1895
1.27M
  if (getContext().getLangOpts().Modules)
1896
910k
    IdentifierGeneration[II] = getGeneration();
1897
1.42M
}
1898
1899
void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1900
34.5k
                                    const PendingMacroInfo &PMInfo) {
1901
34.5k
  ModuleFile &M = *PMInfo.M;
1902
34.5k
1903
34.5k
  BitstreamCursor &Cursor = M.MacroCursor;
1904
34.5k
  SavedStreamPosition SavedPosition(Cursor);
1905
34.5k
  Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
1906
34.5k
1907
34.5k
  struct ModuleMacroRecord {
1908
34.5k
    SubmoduleID SubModID;
1909
34.5k
    MacroInfo *MI;
1910
34.5k
    SmallVector<SubmoduleID, 8> Overrides;
1911
34.5k
  };
1912
34.5k
  llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
1913
34.5k
1914
34.5k
  // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1915
34.5k
  // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1916
34.5k
  // macro histroy.
1917
34.5k
  RecordData Record;
1918
35.5k
  while (
true35.5k
) {
1919
35.5k
    llvm::BitstreamEntry Entry =
1920
35.5k
        Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1921
35.5k
    if (
Entry.Kind != llvm::BitstreamEntry::Record35.5k
) {
1922
0
      Error("malformed block record in AST file");
1923
0
      return;
1924
0
    }
1925
35.5k
1926
35.5k
    Record.clear();
1927
35.5k
    switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
1928
34.5k
    case PP_MACRO_DIRECTIVE_HISTORY:
1929
34.5k
      break;
1930
35.5k
1931
1.07k
    case PP_MODULE_MACRO: {
1932
1.07k
      ModuleMacros.push_back(ModuleMacroRecord());
1933
1.07k
      auto &Info = ModuleMacros.back();
1934
1.07k
      Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1935
1.07k
      Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
1936
1.16k
      for (int I = 2, N = Record.size(); 
I != N1.16k
;
++I93
)
1937
93
        Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
1938
1.07k
      continue;
1939
35.5k
    }
1940
35.5k
1941
0
    default:
1942
0
      Error("malformed block record in AST file");
1943
0
      return;
1944
34.5k
    }
1945
34.5k
1946
34.5k
    // We found the macro directive history; that's the last record
1947
34.5k
    // for this macro.
1948
34.5k
    break;
1949
34.5k
  }
1950
34.5k
1951
34.5k
  // Module macros are listed in reverse dependency order.
1952
34.5k
  {
1953
34.5k
    std::reverse(ModuleMacros.begin(), ModuleMacros.end());
1954
34.5k
    llvm::SmallVector<ModuleMacro*, 8> Overrides;
1955
1.07k
    for (auto &MMR : ModuleMacros) {
1956
1.07k
      Overrides.clear();
1957
93
      for (unsigned ModID : MMR.Overrides) {
1958
93
        Module *Mod = getSubmodule(ModID);
1959
93
        auto *Macro = PP.getModuleMacro(Mod, II);
1960
93
        assert(Macro && "missing definition for overridden macro");
1961
93
        Overrides.push_back(Macro);
1962
93
      }
1963
1.07k
1964
1.07k
      bool Inserted = false;
1965
1.07k
      Module *Owner = getSubmodule(MMR.SubModID);
1966
1.07k
      PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
1967
1.07k
    }
1968
34.5k
  }
1969
34.5k
1970
34.5k
  // Don't read the directive history for a module; we don't have anywhere
1971
34.5k
  // to put it.
1972
34.5k
  if (M.isModule())
1973
783
    return;
1974
33.7k
1975
33.7k
  // Deserialize the macro directives history in reverse source-order.
1976
33.7k
  MacroDirective *Latest = nullptr, *Earliest = nullptr;
1977
33.7k
  unsigned Idx = 0, N = Record.size();
1978
67.5k
  while (
Idx < N67.5k
) {
1979
33.7k
    MacroDirective *MD = nullptr;
1980
33.7k
    SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
1981
33.7k
    MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1982
33.7k
    switch (K) {
1983
33.7k
    case MacroDirective::MD_Define: {
1984
33.7k
      MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
1985
33.7k
      MD = PP.AllocateDefMacroDirective(MI, Loc);
1986
33.7k
      break;
1987
33.7k
    }
1988
21
    case MacroDirective::MD_Undefine: {
1989
21
      MD = PP.AllocateUndefMacroDirective(Loc);
1990
21
      break;
1991
33.7k
    }
1992
4
    case MacroDirective::MD_Visibility:
1993
4
      bool isPublic = Record[Idx++];
1994
4
      MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1995
4
      break;
1996
33.7k
    }
1997
33.7k
1998
33.7k
    
if (33.7k
!Latest33.7k
)
1999
33.7k
      Latest = MD;
2000
33.7k
    if (Earliest)
2001
61
      Earliest->setPrevious(MD);
2002
33.7k
    Earliest = MD;
2003
33.7k
  }
2004
33.7k
2005
33.7k
  
if (33.7k
Latest33.7k
)
2006
33.7k
    PP.setLoadedMacroDirective(II, Earliest, Latest);
2007
34.5k
}
2008
2009
ASTReader::InputFileInfo
2010
8.03k
ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
2011
8.03k
  // Go find this input file.
2012
8.03k
  BitstreamCursor &Cursor = F.InputFilesCursor;
2013
8.03k
  SavedStreamPosition SavedPosition(Cursor);
2014
8.03k
  Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2015
8.03k
2016
8.03k
  unsigned Code = Cursor.ReadCode();
2017
8.03k
  RecordData Record;
2018
8.03k
  StringRef Blob;
2019
8.03k
2020
8.03k
  unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2021
8.03k
  assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2022
8.03k
         "invalid record type for input file");
2023
8.03k
  (void)Result;
2024
8.03k
2025
8.03k
  assert(Record[0] == ID && "Bogus stored ID or offset");
2026
8.03k
  InputFileInfo R;
2027
8.03k
  R.StoredSize = static_cast<off_t>(Record[1]);
2028
8.03k
  R.StoredTime = static_cast<time_t>(Record[2]);
2029
8.03k
  R.Overridden = static_cast<bool>(Record[3]);
2030
8.03k
  R.Transient = static_cast<bool>(Record[4]);
2031
8.03k
  R.TopLevelModuleMap = static_cast<bool>(Record[5]);
2032
8.03k
  R.Filename = Blob;
2033
8.03k
  ResolveImportedPath(F, R.Filename);
2034
8.03k
  return R;
2035
8.03k
}
2036
2037
static unsigned moduleKindForDiagnostic(ModuleKind Kind);
2038
10.0k
InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
2039
10.0k
  // If this ID is bogus, just return an empty input file.
2040
10.0k
  if (
ID == 0 || 10.0k
ID > F.InputFilesLoaded.size()10.0k
)
2041
0
    return InputFile();
2042
10.0k
2043
10.0k
  // If we've already loaded this input file, return it.
2044
10.0k
  
if (10.0k
F.InputFilesLoaded[ID-1].getFile()10.0k
)
2045
2.20k
    return F.InputFilesLoaded[ID-1];
2046
7.88k
2047
7.88k
  
if (7.88k
F.InputFilesLoaded[ID-1].isNotFound()7.88k
)
2048
76
    return InputFile();
2049
7.80k
2050
7.80k
  // Go find this input file.
2051
7.80k
  BitstreamCursor &Cursor = F.InputFilesCursor;
2052
7.80k
  SavedStreamPosition SavedPosition(Cursor);
2053
7.80k
  Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2054
7.80k
2055
7.80k
  InputFileInfo FI = readInputFileInfo(F, ID);
2056
7.80k
  off_t StoredSize = FI.StoredSize;
2057
7.80k
  time_t StoredTime = FI.StoredTime;
2058
7.80k
  bool Overridden = FI.Overridden;
2059
7.80k
  bool Transient = FI.Transient;
2060
7.80k
  StringRef Filename = FI.Filename;
2061
7.80k
2062
7.80k
  const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
2063
7.80k
  // If we didn't find the file, resolve it relative to the
2064
7.80k
  // original directory from which this AST file was created.
2065
7.80k
  if (
File == nullptr && 7.80k
!F.OriginalDir.empty()46
&&
!F.BaseDirectory.empty()46
&&
2066
7.80k
      
F.OriginalDir != F.BaseDirectory44
) {
2067
38
    std::string Resolved = resolveFileRelativeToOriginalDir(
2068
38
        Filename, F.OriginalDir, F.BaseDirectory);
2069
38
    if (!Resolved.empty())
2070
38
      File = FileMgr.getFile(Resolved);
2071
38
  }
2072
7.80k
2073
7.80k
  // For an overridden file, create a virtual file with the stored
2074
7.80k
  // size/timestamp.
2075
7.80k
  if (
(Overridden || 7.80k
Transient7.46k
) &&
File == nullptr354
)
2076
43
    File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
2077
7.80k
2078
7.80k
  if (
File == nullptr7.80k
) {
2079
3
    if (
Complain3
) {
2080
3
      std::string ErrorStr = "could not find file '";
2081
3
      ErrorStr += Filename;
2082
3
      ErrorStr += "' referenced by AST file '";
2083
3
      ErrorStr += F.FileName;
2084
3
      ErrorStr += "'";
2085
3
      Error(ErrorStr);
2086
3
    }
2087
3
    // Record that we didn't find the file.
2088
3
    F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2089
3
    return InputFile();
2090
3
  }
2091
7.80k
2092
7.80k
  // Check if there was a request to override the contents of the file
2093
7.80k
  // that was part of the precompiled header. Overridding such a file
2094
7.80k
  // can lead to problems when lexing using the source locations from the
2095
7.80k
  // PCH.
2096
7.80k
  SourceManager &SM = getSourceManager();
2097
7.80k
  // FIXME: Reject if the overrides are different.
2098
7.80k
  if (
(!Overridden && 7.80k
!Transient7.46k
) &&
SM.isFileOverridden(File)7.44k
) {
2099
1
    if (Complain)
2100
1
      Error(diag::err_fe_pch_file_overridden, Filename);
2101
1
    // After emitting the diagnostic, recover by disabling the override so
2102
1
    // that the original file will be used.
2103
1
    //
2104
1
    // FIXME: This recovery is just as broken as the original state; there may
2105
1
    // be another precompiled module that's using the overridden contents, or
2106
1
    // we might be half way through parsing it. Instead, we should treat the
2107
1
    // overridden contents as belonging to a separate FileEntry.
2108
1
    SM.disableFileContentsOverride(File);
2109
1
    // The FileEntry is a virtual file entry with the size of the contents
2110
1
    // that would override the original contents. Set it to the original's
2111
1
    // size/time.
2112
1
    FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2113
1
                            StoredSize, StoredTime);
2114
1
  }
2115
7.80k
2116
7.80k
  bool IsOutOfDate = false;
2117
7.80k
2118
7.80k
  // For an overridden file, there is nothing to validate.
2119
7.80k
  if (!Overridden && //
2120
7.46k
      (StoredSize != File->getSize() ||
2121
7.43k
       
(StoredTime && 7.43k
StoredTime != File->getModificationTime()6.64k
&&
2122
7.43k
        !DisableValidation)
2123
33
       )) {
2124
33
    if (
Complain33
) {
2125
8
      // Build a list of the PCH imports that got us here (in reverse).
2126
8
      SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2127
9
      while (ImportStack.back()->ImportedBy.size() > 0)
2128
1
        ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
2129
8
2130
8
      // The top-level PCH is stale.
2131
8
      StringRef TopLevelPCHName(ImportStack.back()->FileName);
2132
8
      unsigned DiagnosticKind = moduleKindForDiagnostic(ImportStack.back()->Kind);
2133
8
      if (DiagnosticKind == 0)
2134
6
        Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
2135
2
      else 
if (2
DiagnosticKind == 12
)
2136
1
        Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName);
2137
2
      else
2138
1
        Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName);
2139
8
2140
8
      // Print the import stack.
2141
8
      if (
ImportStack.size() > 1 && 8
!Diags.isDiagnosticInFlight()1
) {
2142
1
        Diag(diag::note_pch_required_by)
2143
1
          << Filename << ImportStack[0]->FileName;
2144
2
        for (unsigned I = 1; 
I < ImportStack.size()2
;
++I1
)
2145
1
          Diag(diag::note_pch_required_by)
2146
1
            << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
2147
1
      }
2148
8
2149
8
      if (!Diags.isDiagnosticInFlight())
2150
8
        Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
2151
8
    }
2152
33
2153
33
    IsOutOfDate = true;
2154
33
  }
2155
7.80k
  // FIXME: If the file is overridden and we've already opened it,
2156
7.80k
  // issue an error (or split it into a separate FileEntry).
2157
7.80k
2158
7.46k
  InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
2159
10.0k
2160
10.0k
  // Note that we've loaded this input file.
2161
10.0k
  F.InputFilesLoaded[ID-1] = IF;
2162
10.0k
  return IF;
2163
10.0k
}
2164
2165
/// \brief If we are loading a relocatable PCH or module file, and the filename
2166
/// is not an absolute path, add the system or module root to the beginning of
2167
/// the file name.
2168
39.3k
void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2169
39.3k
  // Resolve relative to the base directory, if we have one.
2170
39.3k
  if (!M.BaseDirectory.empty())
2171
33.1k
    return ResolveImportedPath(Filename, M.BaseDirectory);
2172
6.17k
}
2173
2174
33.1k
void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
2175
33.1k
  if (
Filename.empty() || 33.1k
llvm::sys::path::is_absolute(Filename)33.1k
)
2176
7.31k
    return;
2177
25.8k
2178
25.8k
  SmallString<128> Buffer;
2179
25.8k
  llvm::sys::path::append(Buffer, Prefix, Filename);
2180
25.8k
  Filename.assign(Buffer.begin(), Buffer.end());
2181
25.8k
}
2182
2183
2.63k
static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2184
2.63k
  switch (ARR) {
2185
5
  case ASTReader::Failure: return true;
2186
1
  case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2187
31
  case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2188
0
  case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2189
0
  case ASTReader::ConfigurationMismatch:
2190
0
    return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2191
0
  case ASTReader::HadErrors: return true;
2192
2.60k
  case ASTReader::Success: return false;
2193
0
  }
2194
0
2195
0
  
llvm_unreachable0
("unknown ASTReadResult");
2196
0
}
2197
2198
ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2199
    BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2200
    bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
2201
3.08k
    std::string &SuggestedPredefines) {
2202
3.08k
  if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2203
0
    return Failure;
2204
3.08k
2205
3.08k
  // Read all of the records in the options block.
2206
3.08k
  RecordData Record;
2207
3.08k
  ASTReadResult Result = Success;
2208
18.5k
  while (
true18.5k
) {
2209
18.5k
    llvm::BitstreamEntry Entry = Stream.advance();
2210
18.5k
2211
18.5k
    switch (Entry.Kind) {
2212
0
    case llvm::BitstreamEntry::Error:
2213
0
    case llvm::BitstreamEntry::SubBlock:
2214
0
      return Failure;
2215
0
2216
3.08k
    case llvm::BitstreamEntry::EndBlock:
2217
3.08k
      return Result;
2218
0
2219
15.4k
    case llvm::BitstreamEntry::Record:
2220
15.4k
      // The interesting case.
2221
15.4k
      break;
2222
15.4k
    }
2223
15.4k
2224
15.4k
    // Read and process a record.
2225
15.4k
    Record.clear();
2226
15.4k
    switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2227
3.08k
    case LANGUAGE_OPTIONS: {
2228
3.08k
      bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2229
3.08k
      if (ParseLanguageOptions(Record, Complain, Listener,
2230
3.08k
                               AllowCompatibleConfigurationMismatch))
2231
23
        Result = ConfigurationMismatch;
2232
3.08k
      break;
2233
15.4k
    }
2234
15.4k
2235
3.08k
    case TARGET_OPTIONS: {
2236
3.08k
      bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2237
3.08k
      if (ParseTargetOptions(Record, Complain, Listener,
2238
3.08k
                             AllowCompatibleConfigurationMismatch))
2239
7
        Result = ConfigurationMismatch;
2240
3.08k
      break;
2241
15.4k
    }
2242
15.4k
2243
3.08k
    case FILE_SYSTEM_OPTIONS: {
2244
3.08k
      bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2245
3.08k
      if (!AllowCompatibleConfigurationMismatch &&
2246
2.69k
          ParseFileSystemOptions(Record, Complain, Listener))
2247
0
        Result = ConfigurationMismatch;
2248
3.08k
      break;
2249
15.4k
    }
2250
15.4k
2251
3.08k
    case HEADER_SEARCH_OPTIONS: {
2252
3.08k
      bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2253
3.08k
      if (!AllowCompatibleConfigurationMismatch &&
2254
2.69k
          ParseHeaderSearchOptions(Record, Complain, Listener))
2255
2
        Result = ConfigurationMismatch;
2256
3.08k
      break;
2257
15.4k
    }
2258
15.4k
2259
3.08k
    case PREPROCESSOR_OPTIONS:
2260
3.08k
      bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2261
3.08k
      if (!AllowCompatibleConfigurationMismatch &&
2262
2.69k
          ParsePreprocessorOptions(Record, Complain, Listener,
2263
2.69k
                                   SuggestedPredefines))
2264
7
        Result = ConfigurationMismatch;
2265
3.08k
      break;
2266
18.5k
    }
2267
18.5k
  }
2268
3.08k
}
2269
2270
ASTReader::ASTReadResult
2271
ASTReader::ReadControlBlock(ModuleFile &F,
2272
                            SmallVectorImpl<ImportedModule> &Loaded,
2273
                            const ModuleFile *ImportedBy,
2274
4.60k
                            unsigned ClientLoadCapabilities) {
2275
4.60k
  BitstreamCursor &Stream = F.Stream;
2276
4.60k
  ASTReadResult Result = Success;
2277
4.60k
2278
4.60k
  if (
Stream.EnterSubBlock(CONTROL_BLOCK_ID)4.60k
) {
2279
0
    Error("malformed block record in AST file");
2280
0
    return Failure;
2281
0
  }
2282
4.60k
2283
4.60k
  // Lambda to read the unhashed control block the first time it's called.
2284
4.60k
  //
2285
4.60k
  // For PCM files, the unhashed control block cannot be read until after the
2286
4.60k
  // MODULE_NAME record.  However, PCH files have no MODULE_NAME, and yet still
2287
4.60k
  // need to look ahead before reading the IMPORTS record.  For consistency,
2288
4.60k
  // this block is always read somehow (see BitstreamEntry::EndBlock).
2289
4.60k
  bool HasReadUnhashedControlBlock = false;
2290
11.2k
  auto readUnhashedControlBlockOnce = [&]() {
2291
11.2k
    if (
!HasReadUnhashedControlBlock11.2k
) {
2292
4.59k
      HasReadUnhashedControlBlock = true;
2293
4.59k
      if (ASTReadResult Result =
2294
4.59k
              readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2295
11
        return Result;
2296
11.2k
    }
2297
11.2k
    return Success;
2298
11.2k
  };
2299
4.60k
2300
4.60k
  // Read all of the records and blocks in the control block.
2301
4.60k
  RecordData Record;
2302
4.60k
  unsigned NumInputs = 0;
2303
4.60k
  unsigned NumUserInputs = 0;
2304
45.6k
  while (
true45.6k
) {
2305
45.6k
    llvm::BitstreamEntry Entry = Stream.advance();
2306
45.6k
2307
45.6k
    switch (Entry.Kind) {
2308
0
    case llvm::BitstreamEntry::Error:
2309
0
      Error("malformed block record in AST file");
2310
0
      return Failure;
2311
4.53k
    case llvm::BitstreamEntry::EndBlock: {
2312
4.53k
      // Validate the module before returning.  This call catches an AST with
2313
4.53k
      // no module name and no imports.
2314
4.53k
      if (ASTReadResult Result = readUnhashedControlBlockOnce())
2315
0
        return Result;
2316
4.53k
2317
4.53k
      // Validate input files.
2318
4.53k
      const HeaderSearchOptions &HSOpts =
2319
4.53k
          PP.getHeaderSearchInfo().getHeaderSearchOpts();
2320
4.53k
2321
4.53k
      // All user input files reside at the index range [0, NumUserInputs), and
2322
4.53k
      // system input files reside at [NumUserInputs, NumInputs). For explicitly
2323
4.53k
      // loaded module files, ignore missing inputs.
2324
4.53k
      if (
!DisableValidation && 4.53k
F.Kind != MK_ExplicitModule4.06k
&&
2325
4.53k
          
F.Kind != MK_PrebuiltModule2.87k
) {
2326
2.86k
        bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2327
2.86k
2328
2.86k
        // If we are reading a module, we will create a verification timestamp,
2329
2.86k
        // so we verify all input files.  Otherwise, verify only user input
2330
2.86k
        // files.
2331
2.86k
2332
2.86k
        unsigned N = NumUserInputs;
2333
2.86k
        if (ValidateSystemInputs ||
2334
2.85k
            (HSOpts.ModulesValidateOncePerBuildSession &&
2335
11
             F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
2336
5
             F.Kind == MK_ImplicitModule))
2337
16
          N = NumInputs;
2338
2.86k
2339
9.42k
        for (unsigned I = 0; 
I < N9.42k
;
++I6.56k
) {
2340
6.59k
          InputFile IF = getInputFile(F, I+1, Complain);
2341
6.59k
          if (
!IF.getFile() || 6.59k
IF.isOutOfDate()6.59k
)
2342
33
            return OutOfDate;
2343
6.59k
        }
2344
2.86k
      }
2345
4.53k
2346
4.49k
      
if (4.49k
Listener4.49k
)
2347
4.49k
        Listener->visitModuleFile(F.FileName, F.Kind);
2348
4.49k
2349
4.49k
      if (
Listener && 4.49k
Listener->needsInputFileVisitation()4.49k
) {
2350
24
        unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2351
37
                                                                : NumUserInputs;
2352
252
        for (unsigned I = 0; 
I < N252
;
++I191
) {
2353
191
          bool IsSystem = I >= NumUserInputs;
2354
191
          InputFileInfo FI = readInputFileInfo(F, I+1);
2355
191
          Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
2356
191
                                   F.Kind == MK_ExplicitModule ||
2357
172
                                   F.Kind == MK_PrebuiltModule);
2358
191
        }
2359
61
      }
2360
4.49k
2361
4.49k
      return Result;
2362
4.53k
    }
2363
4.53k
2364
9.07k
    case llvm::BitstreamEntry::SubBlock:
2365
9.07k
      switch (Entry.ID) {
2366
4.53k
      case INPUT_FILES_BLOCK_ID:
2367
4.53k
        F.InputFilesCursor = Stream;
2368
4.53k
        if (Stream.SkipBlock() || // Skip with the main cursor
2369
4.53k
            // Read the abbreviations
2370
4.53k
            
ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)4.53k
) {
2371
0
          Error("malformed block record in AST file");
2372
0
          return Failure;
2373
0
        }
2374
4.53k
        continue;
2375
4.53k
2376
4.54k
      case OPTIONS_BLOCK_ID:
2377
4.54k
        // If we're reading the first module for this group, check its options
2378
4.54k
        // are compatible with ours. For modules it imports, no further checking
2379
4.54k
        // is required, because we checked them when we built it.
2380
4.54k
        if (
Listener && 4.54k
!ImportedBy4.54k
) {
2381
3.07k
          // Should we allow the configuration of the module file to differ from
2382
3.07k
          // the configuration of the current translation unit in a compatible
2383
3.07k
          // way?
2384
3.07k
          //
2385
3.07k
          // FIXME: Allow this for files explicitly specified with -include-pch.
2386
3.07k
          bool AllowCompatibleConfigurationMismatch =
2387
2.68k
              F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
2388
3.07k
2389
3.07k
          Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2390
3.07k
                                    AllowCompatibleConfigurationMismatch,
2391
3.07k
                                    *Listener, SuggestedPredefines);
2392
3.07k
          if (
Result == Failure3.07k
) {
2393
0
            Error("malformed block record in AST file");
2394
0
            return Result;
2395
0
          }
2396
3.07k
2397
3.07k
          
if (3.07k
DisableValidation ||
2398
2.72k
              
(AllowConfigurationMismatch && 2.72k
Result == ConfigurationMismatch6
))
2399
352
            Result = Success;
2400
3.07k
2401
3.07k
          // If we can't load the module, exit early since we likely
2402
3.07k
          // will rebuild the module anyway. The stream may be in the
2403
3.07k
          // middle of a block.
2404
3.07k
          if (Result != Success)
2405
19
            return Result;
2406
1.47k
        } else 
if (1.47k
Stream.SkipBlock()1.47k
) {
2407
0
          Error("malformed block record in AST file");
2408
0
          return Failure;
2409
0
        }
2410
4.53k
        continue;
2411
4.53k
2412
0
      default:
2413
0
        if (
Stream.SkipBlock()0
) {
2414
0
          Error("malformed block record in AST file");
2415
0
          return Failure;
2416
0
        }
2417
0
        continue;
2418
0
      }
2419
0
2420
32.0k
    case llvm::BitstreamEntry::Record:
2421
32.0k
      // The interesting case.
2422
32.0k
      break;
2423
32.0k
    }
2424
32.0k
2425
32.0k
    // Read and process a record.
2426
32.0k
    Record.clear();
2427
32.0k
    StringRef Blob;
2428
32.0k
    switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
2429
4.60k
    case METADATA: {
2430
4.60k
      if (
Record[0] != VERSION_MAJOR && 4.60k
!DisableValidation0
) {
2431
0
        if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2432
0
          
Diag(Record[0] < VERSION_MAJOR? 0
diag::err_pch_version_too_old0
2433
0
                                        : diag::err_pch_version_too_new);
2434
0
        return VersionMismatch;
2435
0
      }
2436
4.60k
2437
4.60k
      bool hasErrors = Record[6];
2438
4.60k
      if (
hasErrors && 4.60k
!DisableValidation34
&&
!AllowASTWithCompilerErrors7
) {
2439
1
        Diag(diag::err_pch_with_compiler_errors);
2440
1
        return HadErrors;
2441
1
      }
2442
4.60k
      
if (4.60k
hasErrors4.60k
) {
2443
33
        Diags.ErrorOccurred = true;
2444
33
        Diags.UncompilableErrorOccurred = true;
2445
33
        Diags.UnrecoverableErrorOccurred = true;
2446
33
      }
2447
4.60k
2448
4.60k
      F.RelocatablePCH = Record[4];
2449
4.60k
      // Relative paths in a relocatable PCH are relative to our sysroot.
2450
4.60k
      if (F.RelocatablePCH)
2451
2
        
F.BaseDirectory = isysroot.empty() ? 2
"/"0
:
isysroot2
;
2452
4.60k
2453
4.60k
      F.HasTimestamps = Record[5];
2454
4.60k
2455
4.60k
      const std::string &CurBranch = getClangFullRepositoryVersion();
2456
4.60k
      StringRef ASTBranch = Blob;
2457
4.60k
      if (
StringRef(CurBranch) != ASTBranch && 4.60k
!DisableValidation0
) {
2458
0
        if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2459
0
          Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
2460
0
        return VersionMismatch;
2461
0
      }
2462
4.60k
      break;
2463
4.60k
    }
2464
4.60k
2465
3.44k
    case IMPORTS: {
2466
3.44k
      // Validate the AST before processing any imports (otherwise, untangling
2467
3.44k
      // them can be error-prone and expensive).  A module will have a name and
2468
3.44k
      // will already have been validated, but this catches the PCH case.
2469
3.44k
      if (ASTReadResult Result = readUnhashedControlBlockOnce())
2470
0
        return Result;
2471
3.44k
2472
3.44k
      // Load each of the imported PCH files.
2473
3.44k
      unsigned Idx = 0, N = Record.size();
2474
6.04k
      while (
Idx < N6.04k
) {
2475
2.63k
        // Read information about the AST file.
2476
2.63k
        ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2477
2.63k
        // The import location will be the local one for now; we will adjust
2478
2.63k
        // all import locations of module imports after the global source
2479
2.63k
        // location info are setup, in ReadAST.
2480
2.63k
        SourceLocation ImportLoc =
2481
2.63k
            ReadUntranslatedSourceLocation(Record[Idx++]);
2482
2.63k
        off_t StoredSize = (off_t)Record[Idx++];
2483
2.63k
        time_t StoredModTime = (time_t)Record[Idx++];
2484
2.63k
        ASTFileSignature StoredSignature = {
2485
2.63k
            {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2486
2.63k
              (uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2487
2.63k
              (uint32_t)Record[Idx++]}}};
2488
2.63k
2489
2.63k
        std::string ImportedName = ReadString(Record, Idx);
2490
2.63k
        std::string ImportedFile;
2491
2.63k
2492
2.63k
        // For prebuilt and explicit modules first consult the file map for
2493
2.63k
        // an override. Note that here we don't search prebuilt module
2494
2.63k
        // directories, only the explicit name to file mappings. Also, we will
2495
2.63k
        // still verify the size/signature making sure it is essentially the
2496
2.63k
        // same file but perhaps in a different location.
2497
2.63k
        if (
ImportedKind == MK_PrebuiltModule || 2.63k
ImportedKind == MK_ExplicitModule2.63k
)
2498
1.69k
          ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
2499
1.69k
            ImportedName, /*FileMapOnly*/ true);
2500
2.63k
2501
2.63k
        if (ImportedFile.empty())
2502
2.63k
          ImportedFile = ReadPath(F, Record, Idx);
2503
2.63k
        else
2504
5
          SkipPath(Record, Idx);
2505
2.63k
2506
2.63k
        // If our client can't cope with us being out of date, we can't cope with
2507
2.63k
        // our dependency being missing.
2508
2.63k
        unsigned Capabilities = ClientLoadCapabilities;
2509
2.63k
        if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2510
2.47k
          Capabilities &= ~ARR_Missing;
2511
2.63k
2512
2.63k
        // Load the AST file.
2513
2.63k
        auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2514
2.63k
                                  Loaded, StoredSize, StoredModTime,
2515
2.63k
                                  StoredSignature, Capabilities);
2516
2.63k
2517
2.63k
        // If we diagnosed a problem, produce a backtrace.
2518
2.63k
        if (isDiagnosedResult(Result, Capabilities))
2519
12
          Diag(diag::note_module_file_imported_by)
2520
12
              << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2521
2.63k
2522
2.63k
        switch (Result) {
2523
5
        case Failure: return Failure;
2524
2.63k
          // If we have to ignore the dependency, we'll have to ignore this too.
2525
32
        case Missing:
2526
32
        case OutOfDate: return OutOfDate;
2527
0
        case VersionMismatch: return VersionMismatch;
2528
0
        case ConfigurationMismatch: return ConfigurationMismatch;
2529
0
        case HadErrors: return HadErrors;
2530
2.60k
        case Success: break;
2531
2.63k
        }
2532
2.63k
      }
2533
3.40k
      break;
2534
3.44k
    }
2535
3.44k
2536
1.43k
    case ORIGINAL_FILE:
2537
1.43k
      F.OriginalSourceFileID = FileID::get(Record[0]);
2538
1.43k
      F.ActualOriginalSourceFileName = Blob;
2539
1.43k
      F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2540
1.43k
      ResolveImportedPath(F, F.OriginalSourceFileName);
2541
1.43k
      break;
2542
3.44k
2543
4.53k
    case ORIGINAL_FILE_ID:
2544
4.53k
      F.OriginalSourceFileID = FileID::get(Record[0]);
2545
4.53k
      break;
2546
3.44k
2547
3.93k
    case ORIGINAL_PCH_DIR:
2548
3.93k
      F.OriginalDir = Blob;
2549
3.93k
      break;
2550
3.44k
2551
3.25k
    case MODULE_NAME:
2552
3.25k
      F.ModuleName = Blob;
2553
3.25k
      if (Listener)
2554
3.25k
        Listener->ReadModuleName(F.ModuleName);
2555
3.25k
2556
3.25k
      // Validate the AST as soon as we have a name so we can exit early on
2557
3.25k
      // failure.
2558
3.25k
      if (ASTReadResult Result = readUnhashedControlBlockOnce())
2559
11
        return Result;
2560
3.24k
2561
3.24k
      break;
2562
3.24k
2563
3.13k
    case MODULE_DIRECTORY: {
2564
3.13k
      assert(!F.ModuleName.empty() &&
2565
3.13k
             "MODULE_DIRECTORY found before MODULE_NAME");
2566
3.13k
      // If we've already loaded a module map file covering this module, we may
2567
3.13k
      // have a better path for it (relative to the current build).
2568
3.13k
      Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2569
3.13k
      if (
M && 3.13k
M->Directory2.97k
) {
2570
2.97k
        // If we're implicitly loading a module, the base directory can't
2571
2.97k
        // change between the build and use.
2572
2.97k
        if (
F.Kind != MK_ExplicitModule && 2.97k
F.Kind != MK_PrebuiltModule1.97k
) {
2573
1.97k
          const DirectoryEntry *BuildDir =
2574
1.97k
              PP.getFileManager().getDirectory(Blob);
2575
1.97k
          if (
!BuildDir || 1.97k
BuildDir != M->Directory1.97k
) {
2576
2
            if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2577
1
              Diag(diag::err_imported_module_relocated)
2578
1
                  << F.ModuleName << Blob << M->Directory->getName();
2579
2
            return OutOfDate;
2580
2
          }
2581
2.97k
        }
2582
2.97k
        F.BaseDirectory = M->Directory->getName();
2583
3.13k
      } else {
2584
154
        F.BaseDirectory = Blob;
2585
154
      }
2586
3.12k
      break;
2587
3.13k
    }
2588
3.13k
2589
3.17k
    case MODULE_MAP_FILE:
2590
3.17k
      if (ASTReadResult Result =
2591
3.17k
              ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2592
5
        return Result;
2593
3.17k
      break;
2594
3.17k
2595
4.53k
    case INPUT_FILE_OFFSETS:
2596
4.53k
      NumInputs = Record[0];
2597
4.53k
      NumUserInputs = Record[1];
2598
4.53k
      F.InputFileOffsets =
2599
4.53k
          (const llvm::support::unaligned_uint64_t *)Blob.data();
2600
4.53k
      F.InputFilesLoaded.resize(NumInputs);
2601
4.53k
      F.NumUserInputFiles = NumUserInputs;
2602
4.53k
      break;
2603
45.6k
    }
2604
45.6k
  }
2605
4.60k
}
2606
2607
ASTReader::ASTReadResult
2608
4.48k
ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
2609
4.48k
  BitstreamCursor &Stream = F.Stream;
2610
4.48k
2611
4.48k
  if (
Stream.EnterSubBlock(AST_BLOCK_ID)4.48k
) {
2612
0
    Error("malformed block record in AST file");
2613
0
    return Failure;
2614
0
  }
2615
4.48k
2616
4.48k
  // Read all of the records and blocks for the AST file.
2617
4.48k
  RecordData Record;
2618
120k
  while (
true120k
) {
2619
120k
    llvm::BitstreamEntry Entry = Stream.advance();
2620
120k
2621
120k
    switch (Entry.Kind) {
2622
0
    case llvm::BitstreamEntry::Error:
2623
0
      Error("error at end of module block in AST file");
2624
0
      return Failure;
2625
4.48k
    case llvm::BitstreamEntry::EndBlock: {
2626
4.48k
      // Outside of C++, we do not store a lookup map for the translation unit.
2627
4.48k
      // Instead, mark it as needing a lookup map to be built if this module
2628
4.48k
      // contains any declarations lexically within it (which it always does!).
2629
4.48k
      // This usually has no cost, since we very rarely need the lookup map for
2630
4.48k
      // the translation unit outside C++.
2631
4.48k
      if (ASTContext *
Ctx4.48k
= ContextObj) {
2632
4.46k
        DeclContext *DC = Ctx->getTranslationUnitDecl();
2633
4.46k
        if (
DC->hasExternalLexicalStorage() && 4.46k
!Ctx->getLangOpts().CPlusPlus4.46k
)
2634
1.56k
          DC->setMustBuildLookupTable();
2635
4.46k
      }
2636
4.48k
2637
4.48k
      return Success;
2638
120k
    }
2639
21.7k
    case llvm::BitstreamEntry::SubBlock:
2640
21.7k
      switch (Entry.ID) {
2641
4.48k
      case DECLTYPES_BLOCK_ID:
2642
4.48k
        // We lazily load the decls block, but we want to set up the
2643
4.48k
        // DeclsCursor cursor to point into it.  Clone our current bitcode
2644
4.48k
        // cursor to it, enter the block and read the abbrevs in that block.
2645
4.48k
        // With the main cursor, we just skip over it.
2646
4.48k
        F.DeclsCursor = Stream;
2647
4.48k
        if (Stream.SkipBlock() ||  // Skip with the main cursor.
2648
4.48k
            // Read the abbrevs.
2649
4.48k
            
ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)4.48k
) {
2650
0
          Error("malformed block record in AST file");
2651
0
          return Failure;
2652
0
        }
2653
4.48k
        break;
2654
4.48k
2655
4.48k
      case PREPROCESSOR_BLOCK_ID:
2656
4.48k
        F.MacroCursor = Stream;
2657
4.48k
        if (!PP.getExternalSource())
2658
2.53k
          PP.setExternalSource(this);
2659
4.48k
2660
4.48k
        if (Stream.SkipBlock() ||
2661
4.48k
            
ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)4.48k
) {
2662
0
          Error("malformed block record in AST file");
2663
0
          return Failure;
2664
0
        }
2665
4.48k
        F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2666
4.48k
        break;
2667
4.48k
2668
647
      case PREPROCESSOR_DETAIL_BLOCK_ID:
2669
647
        F.PreprocessorDetailCursor = Stream;
2670
647
        if (Stream.SkipBlock() ||
2671
647
            ReadBlockAbbrevs(F.PreprocessorDetailCursor,
2672
647
                             PREPROCESSOR_DETAIL_BLOCK_ID)) {
2673
0
              Error("malformed preprocessor detail record in AST file");
2674
0
              return Failure;
2675
0
            }
2676
647
        F.PreprocessorDetailStartOffset
2677
647
        = F.PreprocessorDetailCursor.GetCurrentBitNo();
2678
647
2679
647
        if (!PP.getPreprocessingRecord())
2680
106
          PP.createPreprocessingRecord();
2681
647
        if (!PP.getPreprocessingRecord()->getExternalSource())
2682
506
          PP.getPreprocessingRecord()->SetExternalSource(*this);
2683
647
        break;
2684
647
2685
4.48k
      case SOURCE_MANAGER_BLOCK_ID:
2686
4.48k
        if (ReadSourceManagerBlock(F))
2687
0
          return Failure;
2688
4.48k
        break;
2689
4.48k
2690
3.16k
      case SUBMODULE_BLOCK_ID:
2691
3.16k
        if (ASTReadResult Result =
2692
3.16k
                ReadSubmoduleBlock(F, ClientLoadCapabilities))
2693
4
          return Result;
2694
3.16k
        break;
2695
3.16k
2696
4.48k
      case COMMENTS_BLOCK_ID: {
2697
4.48k
        BitstreamCursor C = Stream;
2698
4.48k
        if (Stream.SkipBlock() ||
2699
4.48k
            
ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)4.48k
) {
2700
0
          Error("malformed comments block in AST file");
2701
0
          return Failure;
2702
0
        }
2703
4.48k
        CommentsCursors.push_back(std::make_pair(C, &F));
2704
4.48k
        break;
2705
4.48k
      }
2706
4.48k
2707
0
      default:
2708
0
        if (
Stream.SkipBlock()0
) {
2709
0
          Error("malformed block record in AST file");
2710
0
          return Failure;
2711
0
        }
2712
0
        break;
2713
21.7k
      }
2714
21.7k
      continue;
2715
21.7k
2716
93.8k
    case llvm::BitstreamEntry::Record:
2717
93.8k
      // The interesting case.
2718
93.8k
      break;
2719
93.8k
    }
2720
93.8k
2721
93.8k
    // Read and process a record.
2722
93.8k
    Record.clear();
2723
93.8k
    StringRef Blob;
2724
93.8k
    auto RecordType =
2725
93.8k
        (ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob);
2726
93.8k
2727
93.8k
    // If we're not loading an AST context, we don't care about most records.
2728
93.8k
    if (
!ContextObj93.8k
) {
2729
441
      switch (RecordType) {
2730
221
      case IDENTIFIER_TABLE:
2731
221
      case IDENTIFIER_OFFSET:
2732
221
      case INTERESTING_IDENTIFIERS:
2733
221
      case STATISTICS:
2734
221
      case PP_CONDITIONAL_STACK:
2735
221
      case PP_COUNTER_VALUE:
2736
221
      case SOURCE_LOCATION_OFFSETS:
2737
221
      case MODULE_OFFSET_MAP:
2738
221
      case SOURCE_MANAGER_LINE_TABLE:
2739
221
      case SOURCE_LOCATION_PRELOADS:
2740
221
      case PPD_ENTITIES_OFFSETS:
2741
221
      case HEADER_SEARCH_TABLE:
2742
221
      case IMPORTED_MODULES:
2743
221
      case MACRO_OFFSET:
2744
221
        break;
2745
220
      default:
2746
220
        continue;
2747
93.6k
      }
2748
93.6k
    }
2749
93.6k
2750
93.6k
    switch (RecordType) {
2751
4.46k
    default:  // Default behavior: ignore.
2752
4.46k
      break;
2753
93.6k
2754
4.46k
    case TYPE_OFFSET: {
2755
4.46k
      if (
F.LocalNumTypes != 04.46k
) {
2756
0
        Error("duplicate TYPE_OFFSET record in AST file");
2757
0
        return Failure;
2758
0
      }
2759
4.46k
      F.TypeOffsets = (const uint32_t *)Blob.data();
2760
4.46k
      F.LocalNumTypes = Record[0];
2761
4.46k
      unsigned LocalBaseTypeIndex = Record[1];
2762
4.46k
      F.BaseTypeIndex = getTotalNumTypes();
2763
4.46k
2764
4.46k
      if (
F.LocalNumTypes > 04.46k
) {
2765
4.32k
        // Introduce the global -> local mapping for types within this module.
2766
4.32k
        GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2767
4.32k
2768
4.32k
        // Introduce the local -> global mapping for types within this module.
2769
4.32k
        F.TypeRemap.insertOrReplace(
2770
4.32k
          std::make_pair(LocalBaseTypeIndex,
2771
4.32k
                         F.BaseTypeIndex - LocalBaseTypeIndex));
2772
4.32k
2773
4.32k
        TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2774
4.32k
      }
2775
4.46k
      break;
2776
4.46k
    }
2777
4.46k
2778
4.46k
    case DECL_OFFSET: {
2779
4.46k
      if (
F.LocalNumDecls != 04.46k
) {
2780
0
        Error("duplicate DECL_OFFSET record in AST file");
2781
0
        return Failure;
2782
0
      }
2783
4.46k
      F.DeclOffsets = (const DeclOffset *)Blob.data();
2784
4.46k
      F.LocalNumDecls = Record[0];
2785
4.46k
      unsigned LocalBaseDeclID = Record[1];
2786
4.46k
      F.BaseDeclID = getTotalNumDecls();
2787
4.46k
2788
4.46k
      if (
F.LocalNumDecls > 04.46k
) {
2789
4.25k
        // Introduce the global -> local mapping for declarations within this
2790
4.25k
        // module.
2791
4.25k
        GlobalDeclMap.insert(
2792
4.25k
          std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2793
4.25k
2794
4.25k
        // Introduce the local -> global mapping for declarations within this
2795
4.25k
        // module.
2796
4.25k
        F.DeclRemap.insertOrReplace(
2797
4.25k
          std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2798
4.25k
2799
4.25k
        // Introduce the global -> local mapping for declarations within this
2800
4.25k
        // module.
2801
4.25k
        F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2802
4.25k
2803
4.25k
        DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2804
4.25k
      }
2805
4.46k
      break;
2806
4.46k
    }
2807
4.46k
2808
4.46k
    case TU_UPDATE_LEXICAL: {
2809
4.46k
      DeclContext *TU = ContextObj->getTranslationUnitDecl();
2810
4.46k
      LexicalContents Contents(
2811
4.46k
          reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2812
4.46k
              Blob.data()),
2813
4.46k
          static_cast<unsigned int>(Blob.size() / 4));
2814
4.46k
      TULexicalDecls.push_back(std::make_pair(&F, Contents));
2815
4.46k
      TU->setHasExternalLexicalStorage(true);
2816
4.46k
      break;
2817
4.46k
    }
2818
4.46k
2819
2.57k
    case UPDATE_VISIBLE: {
2820
2.57k
      unsigned Idx = 0;
2821
2.57k
      serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2822
2.57k
      auto *Data = (const unsigned char*)Blob.data();
2823
2.57k
      PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
2824
2.57k
      // If we've already loaded the decl, perform the updates when we finish
2825
2.57k
      // loading this block.
2826
2.57k
      if (Decl *D = GetExistingDecl(ID))
2827
2.41k
        PendingUpdateRecords.push_back(
2828
2.41k
            PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
2829
2.57k
      break;
2830
4.46k
    }
2831
4.46k
2832
4.48k
    case IDENTIFIER_TABLE:
2833
4.48k
      F.IdentifierTableData = Blob.data();
2834
4.48k
      if (
Record[0]4.48k
) {
2835
4.48k
        F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2836
4.48k
            (const unsigned char *)F.IdentifierTableData + Record[0],
2837
4.48k
            (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2838
4.48k
            (const unsigned char *)F.IdentifierTableData,
2839
4.48k
            ASTIdentifierLookupTrait(*this, F));
2840
4.48k
2841
4.48k
        PP.getIdentifierTable().setExternalIdentifierLookup(this);
2842
4.48k
      }
2843
4.48k
      break;
2844
4.46k
2845
4.48k
    case IDENTIFIER_OFFSET: {
2846
4.48k
      if (
F.LocalNumIdentifiers != 04.48k
) {
2847
0
        Error("duplicate IDENTIFIER_OFFSET record in AST file");
2848
0
        return Failure;
2849
0
      }
2850
4.48k
      F.IdentifierOffsets = (const uint32_t *)Blob.data();
2851
4.48k
      F.LocalNumIdentifiers = Record[0];
2852
4.48k
      unsigned LocalBaseIdentifierID = Record[1];
2853
4.48k
      F.BaseIdentifierID = getTotalNumIdentifiers();
2854
4.48k
2855
4.48k
      if (
F.LocalNumIdentifiers > 04.48k
) {
2856
3.51k
        // Introduce the global -> local mapping for identifiers within this
2857
3.51k
        // module.
2858
3.51k
        GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2859
3.51k
                                                  &F));
2860
3.51k
2861
3.51k
        // Introduce the local -> global mapping for identifiers within this
2862
3.51k
        // module.
2863
3.51k
        F.IdentifierRemap.insertOrReplace(
2864
3.51k
          std::make_pair(LocalBaseIdentifierID,
2865
3.51k
                         F.BaseIdentifierID - LocalBaseIdentifierID));
2866
3.51k
2867
3.51k
        IdentifiersLoaded.resize(IdentifiersLoaded.size()
2868
3.51k
                                 + F.LocalNumIdentifiers);
2869
3.51k
      }
2870
4.48k
      break;
2871
4.48k
    }
2872
4.48k
2873
2.26k
    case INTERESTING_IDENTIFIERS:
2874
2.26k
      F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2875
2.26k
      break;
2876
4.48k
2877
761
    case EAGERLY_DESERIALIZED_DECLS:
2878
761
      // FIXME: Skip reading this record if our ASTConsumer doesn't care
2879
761
      // about "interesting" decls (for instance, if we're building a module).
2880
2.85k
      for (unsigned I = 0, N = Record.size(); 
I != N2.85k
;
++I2.09k
)
2881
2.09k
        EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2882
761
      break;
2883
4.48k
2884
73
    case MODULAR_CODEGEN_DECLS:
2885
73
      // FIXME: Skip reading this record if our ASTConsumer doesn't care about
2886
73
      // them (ie: if we're not codegenerating this module).
2887
73
      if (F.Kind == MK_MainFile)
2888
39
        
for (unsigned I = 0, N = Record.size(); 9
I != N39
;
++I30
)
2889
30
          EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2890
73
      break;
2891
4.48k
2892
4.46k
    case SPECIAL_TYPES:
2893
4.46k
      if (
SpecialTypes.empty()4.46k
) {
2894
22.7k
        for (unsigned I = 0, N = Record.size(); 
I != N22.7k
;
++I20.2k
)
2895
20.2k
          SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2896
2.52k
        break;
2897
2.52k
      }
2898
1.93k
2899
1.93k
      
if (1.93k
SpecialTypes.size() != Record.size()1.93k
) {
2900
0
        Error("invalid special-types record");
2901
0
        return Failure;
2902
0
      }
2903
1.93k
2904
17.4k
      
for (unsigned I = 0, N = Record.size(); 1.93k
I != N17.4k
;
++I15.4k
) {
2905
15.4k
        serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2906
15.4k
        if (!SpecialTypes[I])
2907
13.4k
          SpecialTypes[I] = ID;
2908
15.4k
        // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2909
15.4k
        // merge step?
2910
15.4k
      }
2911
1.93k
      break;
2912
1.93k
2913
4.48k
    case STATISTICS:
2914
4.48k
      TotalNumStatements += Record[0];
2915
4.48k
      TotalNumMacros += Record[1];
2916
4.48k
      TotalLexicalDeclContexts += Record[2];
2917
4.48k
      TotalVisibleDeclContexts += Record[3];
2918
4.48k
      break;
2919
1.93k
2920
12
    case UNUSED_FILESCOPED_DECLS:
2921
24
      for (unsigned I = 0, N = Record.size(); 
I != N24
;
++I12
)
2922
12
        UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2923
12
      break;
2924
1.93k
2925
1
    case DELEGATING_CTORS:
2926
4
      for (unsigned I = 0, N = Record.size(); 
I != N4
;
++I3
)
2927
3
        DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2928
1
      break;
2929
1.93k
2930
30
    case WEAK_UNDECLARED_IDENTIFIERS:
2931
30
      if (
Record.size() % 4 != 030
) {
2932
0
        Error("invalid weak identifiers record");
2933
0
        return Failure;
2934
0
      }
2935
30
2936
30
      // FIXME: Ignore weak undeclared identifiers from non-original PCH
2937
30
      // files. This isn't the way to do it :)
2938
30
      WeakUndeclaredIdentifiers.clear();
2939
30
2940
30
      // Translate the weak, undeclared identifiers into global IDs.
2941
196
      for (unsigned I = 0, N = Record.size(); 
I < N196
; /* in loop */) {
2942
166
        WeakUndeclaredIdentifiers.push_back(
2943
166
          getGlobalIdentifierID(F, Record[I++]));
2944
166
        WeakUndeclaredIdentifiers.push_back(
2945
166
          getGlobalIdentifierID(F, Record[I++]));
2946
166
        WeakUndeclaredIdentifiers.push_back(
2947
166
          ReadSourceLocation(F, Record, I).getRawEncoding());
2948
166
        WeakUndeclaredIdentifiers.push_back(Record[I++]);
2949
166
      }
2950
30
      break;
2951
30
2952
280
    case SELECTOR_OFFSETS: {
2953
280
      F.SelectorOffsets = (const uint32_t *)Blob.data();
2954
280
      F.LocalNumSelectors = Record[0];
2955
280
      unsigned LocalBaseSelectorID = Record[1];
2956
280
      F.BaseSelectorID = getTotalNumSelectors();
2957
280
2958
280
      if (
F.LocalNumSelectors > 0280
) {
2959
276
        // Introduce the global -> local mapping for selectors within this
2960
276
        // module.
2961
276
        GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2962
276
2963
276
        // Introduce the local -> global mapping for selectors within this
2964
276
        // module.
2965
276
        F.SelectorRemap.insertOrReplace(
2966
276
          std::make_pair(LocalBaseSelectorID,
2967
276
                         F.BaseSelectorID - LocalBaseSelectorID));
2968
276
2969
276
        SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2970
276
      }
2971
280
      break;
2972
30
    }
2973
30
2974
280
    case METHOD_POOL:
2975
280
      F.SelectorLookupTableData = (const unsigned char *)Blob.data();
2976
280
      if (Record[0])
2977
280
        F.SelectorLookupTable
2978
280
          = ASTSelectorLookupTable::Create(
2979
280
                        F.SelectorLookupTableData + Record[0],
2980
280
                        F.SelectorLookupTableData,
2981
280
                        ASTSelectorLookupTrait(*this, F));
2982
280
      TotalNumMethodPoolEntries += Record[1];
2983
280
      break;
2984
30
2985
3
    case REFERENCED_SELECTOR_POOL:
2986
3
      if (
!Record.empty()3
) {
2987
6
        for (unsigned Idx = 0, N = Record.size() - 1; 
Idx < N6
; /* in loop */) {
2988
3
          ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2989
3
                                                                Record[Idx++]));
2990
3
          ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2991
3
                                              getRawEncoding());
2992
3
        }
2993
3
      }
2994
3
      break;
2995
30
2996
20
    case PP_CONDITIONAL_STACK:
2997
20
      if (
!Record.empty()20
) {
2998
20
        SmallVector<PPConditionalInfo, 4> ConditionalStack;
2999
40
        for (unsigned Idx = 0, N = Record.size() - 1; 
Idx < N40
; /* in loop */) {
3000
20
          auto Loc = ReadSourceLocation(F, Record, Idx);
3001
20
          bool WasSkipping = Record[Idx++];
3002
20
          bool FoundNonSkip = Record[Idx++];
3003
20
          bool FoundElse = Record[Idx++];
3004
20
          ConditionalStack.push_back(
3005
20
              {Loc, WasSkipping, FoundNonSkip, FoundElse});
3006
20
        }
3007
20
        PP.setReplayablePreambleConditionalStack(ConditionalStack);
3008
20
      }
3009
20
      break;
3010
30
3011
3
    case PP_COUNTER_VALUE:
3012
3
      if (
!Record.empty() && 3
Listener3
)
3013
3
        Listener->ReadCounter(F, Record[0]);
3014
3
      break;
3015
30
3016
4.46k
    case FILE_SORTED_DECLS:
3017
4.46k
      F.FileSortedDecls = (const DeclID *)Blob.data();
3018
4.46k
      F.NumFileSortedDecls = Record[0];
3019
4.46k
      break;
3020
30
3021
4.48k
    case SOURCE_LOCATION_OFFSETS: {
3022
4.48k
      F.SLocEntryOffsets = (const uint32_t *)Blob.data();
3023
4.48k
      F.LocalNumSLocEntries = Record[0];
3024
4.48k
      unsigned SLocSpaceSize = Record[1];
3025
4.48k
      std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
3026
4.48k
          SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
3027
4.48k
                                              SLocSpaceSize);
3028
4.48k
      if (
!F.SLocEntryBaseID4.48k
) {
3029
0
        Error("ran out of source locations");
3030
0
        break;
3031
0
      }
3032
4.48k
      // Make our entry in the range map. BaseID is negative and growing, so
3033
4.48k
      // we invert it. Because we invert it, though, we need the other end of
3034
4.48k
      // the range.
3035
4.48k
      unsigned RangeStart =
3036
4.48k
          unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
3037
4.48k
      GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
3038
4.48k
      F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
3039
4.48k
3040
4.48k
      // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3041
4.48k
      assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
3042
4.48k
      GlobalSLocOffsetMap.insert(
3043
4.48k
          std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
3044
4.48k
                           - SLocSpaceSize,&F));
3045
4.48k
3046
4.48k
      // Initialize the remapping table.
3047
4.48k
      // Invalid stays invalid.
3048
4.48k
      F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
3049
4.48k
      // This module. Base was 2 when being compiled.
3050
4.48k
      F.SLocRemap.insertOrReplace(std::make_pair(2U,
3051
4.48k
                                  static_cast<int>(F.SLocEntryBaseOffset - 2)));
3052
4.48k
3053
4.48k
      TotalNumSLocEntries += F.LocalNumSLocEntries;
3054
4.48k
      break;
3055
4.48k
    }
3056
4.48k
3057
3.36k
    case MODULE_OFFSET_MAP:
3058
3.36k
      F.ModuleOffsetMap = Blob;
3059
3.36k
      break;
3060
4.48k
3061
4.48k
    case SOURCE_MANAGER_LINE_TABLE:
3062
4.48k
      if (ParseLineTable(F, Record))
3063
0
        return Failure;
3064
4.48k
      break;
3065
4.48k
3066
4.48k
    case SOURCE_LOCATION_PRELOADS: {
3067
4.48k
      // Need to transform from the local view (1-based IDs) to the global view,
3068
4.48k
      // which is based off F.SLocEntryBaseID.
3069
4.48k
      if (
!F.PreloadSLocEntries.empty()4.48k
) {
3070
0
        Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
3071
0
        return Failure;
3072
0
      }
3073
4.48k
3074
4.48k
      F.PreloadSLocEntries.swap(Record);
3075
4.48k
      break;
3076
4.48k
    }
3077
4.48k
3078
19
    case EXT_VECTOR_DECLS:
3079
472
      for (unsigned I = 0, N = Record.size(); 
I != N472
;
++I453
)
3080
453
        ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3081
19
      break;
3082
4.48k
3083
3
    case VTABLE_USES:
3084
3
      if (
Record.size() % 3 != 03
) {
3085
0
        Error("Invalid VTABLE_USES record");
3086
0
        return Failure;
3087
0
      }
3088
3
3089
3
      // Later tables overwrite earlier ones.
3090
3
      // FIXME: Modules will have some trouble with this. This is clearly not
3091
3
      // the right way to do this.
3092
3
      VTableUses.clear();
3093
3
3094
7
      for (unsigned Idx = 0, N = Record.size(); 
Idx != N7
; /* In loop */) {
3095
4
        VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3096
4
        VTableUses.push_back(
3097
4
          ReadSourceLocation(F, Record, Idx).getRawEncoding());
3098
4
        VTableUses.push_back(Record[Idx++]);
3099
4
      }
3100
3
      break;
3101
3
3102
246
    case PENDING_IMPLICIT_INSTANTIATIONS:
3103
246
      if (
PendingInstantiations.size() % 2 != 0246
) {
3104
0
        Error("Invalid existing PendingInstantiations");
3105
0
        return Failure;
3106
0
      }
3107
246
3108
246
      
if (246
Record.size() % 2 != 0246
) {
3109
0
        Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
3110
0
        return Failure;
3111
0
      }
3112
246
3113
881
      
for (unsigned I = 0, N = Record.size(); 246
I != N881
; /* in loop */) {
3114
635
        PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3115
635
        PendingInstantiations.push_back(
3116
635
          ReadSourceLocation(F, Record, I).getRawEncoding());
3117
635
      }
3118
246
      break;
3119
246
3120
51
    case SEMA_DECL_REFS:
3121
51
      if (
Record.size() != 351
) {
3122
0
        Error("Invalid SEMA_DECL_REFS block");
3123
0
        return Failure;
3124
0
      }
3125
204
      
for (unsigned I = 0, N = Record.size(); 51
I != N204
;
++I153
)
3126
153
        SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3127
51
      break;
3128
51
3129
647
    case PPD_ENTITIES_OFFSETS: {
3130
647
      F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3131
647
      assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3132
647
      F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
3133
647
3134
647
      unsigned LocalBasePreprocessedEntityID = Record[0];
3135
647
3136
647
      unsigned StartingID;
3137
647
      if (!PP.getPreprocessingRecord())
3138
0
        PP.createPreprocessingRecord();
3139
647
      if (!PP.getPreprocessingRecord()->getExternalSource())
3140
0
        PP.getPreprocessingRecord()->SetExternalSource(*this);
3141
647
      StartingID
3142
647
        = PP.getPreprocessingRecord()
3143
647
            ->allocateLoadedEntities(F.NumPreprocessedEntities);
3144
647
      F.BasePreprocessedEntityID = StartingID;
3145
647
3146
647
      if (
F.NumPreprocessedEntities > 0647
) {
3147
647
        // Introduce the global -> local mapping for preprocessed entities in
3148
647
        // this module.
3149
647
        GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3150
647
3151
647
        // Introduce the local -> global mapping for preprocessed entities in
3152
647
        // this module.
3153
647
        F.PreprocessedEntityRemap.insertOrReplace(
3154
647
          std::make_pair(LocalBasePreprocessedEntityID,
3155
647
            F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3156
647
      }
3157
647
3158
647
      break;
3159
51
    }
3160
51
3161
864
    case DECL_UPDATE_OFFSETS: {
3162
864
      if (
Record.size() % 2 != 0864
) {
3163
0
        Error("invalid DECL_UPDATE_OFFSETS block in AST file");
3164
0
        return Failure;
3165
0
      }
3166
3.91k
      
for (unsigned I = 0, N = Record.size(); 864
I != N3.91k
;
I += 23.05k
) {
3167
3.05k
        GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3168
3.05k
        DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3169
3.05k
3170
3.05k
        // If we've already loaded the decl, perform the updates when we finish
3171
3.05k
        // loading this block.
3172
3.05k
        if (Decl *D = GetExistingDecl(ID))
3173
139
          PendingUpdateRecords.push_back(
3174
139
              PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3175
3.05k
      }
3176
864
      break;
3177
864
    }
3178
864
3179
4.46k
    case OBJC_CATEGORIES_MAP: {
3180
4.46k
      if (
F.LocalNumObjCCategoriesInMap != 04.46k
) {
3181
0
        Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
3182
0
        return Failure;
3183
0
      }
3184
4.46k
3185
4.46k
      F.LocalNumObjCCategoriesInMap = Record[0];
3186
4.46k
      F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
3187
4.46k
      break;
3188
4.46k
    }
3189
4.46k
3190
4.46k
    case OBJC_CATEGORIES:
3191
4.46k
      F.ObjCCategories.swap(Record);
3192
4.46k
      break;
3193
4.46k
3194
1
    case CUDA_SPECIAL_DECL_REFS:
3195
1
      // Later tables overwrite earlier ones.
3196
1
      // FIXME: Modules will have trouble with this.
3197
1
      CUDASpecialDeclRefs.clear();
3198
2
      for (unsigned I = 0, N = Record.size(); 
I != N2
;
++I1
)
3199
1
        CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3200
1
      break;
3201
4.46k
3202
4.48k
    case HEADER_SEARCH_TABLE: {
3203
4.48k
      F.HeaderFileInfoTableData = Blob.data();
3204
4.48k
      F.LocalNumHeaderFileInfos = Record[1];
3205
4.48k
      if (
Record[0]4.48k
) {
3206
4.48k
        F.HeaderFileInfoTable
3207
4.48k
          = HeaderFileInfoLookupTable::Create(
3208
4.48k
                   (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3209
4.48k
                   (const unsigned char *)F.HeaderFileInfoTableData,
3210
4.48k
                   HeaderFileInfoTrait(*this, F,
3211
4.48k
                                       &PP.getHeaderSearchInfo(),
3212
4.48k
                                       Blob.data() + Record[2]));
3213
4.48k
3214
4.48k
        PP.getHeaderSearchInfo().SetExternalSource(this);
3215
4.48k
        if (!PP.getHeaderSearchInfo().getExternalLookup())
3216
2.53k
          PP.getHeaderSearchInfo().SetExternalLookup(this);
3217
4.48k
      }
3218
4.48k
      break;
3219
4.46k
    }
3220
4.46k
3221
4.46k
    case FP_PRAGMA_OPTIONS:
3222
4.46k
      // Later tables overwrite earlier ones.
3223
4.46k
      FPPragmaOptions.swap(Record);
3224
4.46k
      break;
3225
4.46k
3226
13
    case OPENCL_EXTENSIONS:
3227
443
      for (unsigned I = 0, E = Record.size(); 
I != E443
; ) {
3228
430
        auto Name = ReadString(Record, I);
3229
430
        auto &Opt = OpenCLExtensions.OptMap[Name];
3230
430
        Opt.Supported = Record[I++] != 0;
3231
430
        Opt.Enabled = Record[I++] != 0;
3232
430
        Opt.Avail = Record[I++];
3233
430
        Opt.Core = Record[I++];
3234
430
      }
3235
13
      break;
3236
4.46k
3237
13
    case OPENCL_EXTENSION_TYPES:
3238
213
      for (unsigned I = 0, E = Record.size(); 
I != E213
;) {
3239
200
        auto TypeID = static_cast<::TypeID>(Record[I++]);
3240
200
        auto *Type = GetType(TypeID).getTypePtr();
3241
200
        auto NumExt = static_cast<unsigned>(Record[I++]);
3242
424
        for (unsigned II = 0; 
II != NumExt424
;
++II224
) {
3243
224
          auto Ext = ReadString(Record, I);
3244
224
          OpenCLTypeExtMap[Type].insert(Ext);
3245
224
        }
3246
200
      }
3247
13
      break;
3248
4.46k
3249
13
    case OPENCL_EXTENSION_DECLS:
3250
18
      for (unsigned I = 0, E = Record.size(); 
I != E18
;) {
3251
5
        auto DeclID = static_cast<::DeclID>(Record[I++]);
3252
5
        auto *Decl = GetDecl(DeclID);
3253
5
        auto NumExt = static_cast<unsigned>(Record[I++]);
3254
10
        for (unsigned II = 0; 
II != NumExt10
;
++II5
) {
3255
5
          auto Ext = ReadString(Record, I);
3256
5
          OpenCLDeclExtMap[Decl].insert(Ext);
3257
5
        }
3258
5
      }
3259
13
      break;
3260
4.46k
3261
216
    case TENTATIVE_DEFINITIONS:
3262
1.18k
      for (unsigned I = 0, N = Record.size(); 
I != N1.18k
;
++I968
)
3263
968
        TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3264
216
      break;
3265
4.46k
3266
296
    case KNOWN_NAMESPACES:
3267
978
      for (unsigned I = 0, N = Record.size(); 
I != N978
;
++I682
)
3268
682
        KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3269
296
      break;
3270
4.46k
3271
121
    case UNDEFINED_BUT_USED:
3272
121
      if (
UndefinedButUsed.size() % 2 != 0121
) {
3273
0
        Error("Invalid existing UndefinedButUsed");
3274
0
        return Failure;
3275
0
      }
3276
121
3277
121
      
if (121
Record.size() % 2 != 0121
) {
3278
0
        Error("invalid undefined-but-used record");
3279
0
        return Failure;
3280
0
      }
3281
458
      
for (unsigned I = 0, N = Record.size(); 121
I != N458
; /* in loop */) {
3282
337
        UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3283
337
        UndefinedButUsed.push_back(
3284
337
            ReadSourceLocation(F, Record, I).getRawEncoding());
3285
337
      }
3286
121
      break;
3287
1
    case DELETE_EXPRS_TO_ANALYZE:
3288
2
      for (unsigned I = 0, N = Record.size(); 
I != N2
;) {
3289
1
        DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3290
1
        const uint64_t Count = Record[I++];
3291
1
        DelayedDeleteExprs.push_back(Count);
3292
2
        for (uint64_t C = 0; 
C < Count2
;
++C1
) {
3293
1
          DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3294
1
          bool IsArrayForm = Record[I++] == 1;
3295
1
          DelayedDeleteExprs.push_back(IsArrayForm);
3296
1
        }
3297
1
      }
3298
1
      break;
3299
121
3300
47
    case IMPORTED_MODULES: {
3301
47
      if (
!F.isModule()47
) {
3302
47
        // If we aren't loading a module (which has its own exports), make
3303
47
        // all of the imported modules visible.
3304
47
        // FIXME: Deal with macros-only imports.
3305
103
        for (unsigned I = 0, N = Record.size(); 
I != N103
; /**/) {
3306
56
          unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3307
56
          SourceLocation Loc = ReadSourceLocation(F, Record, I);
3308
56
          if (
GlobalID56
) {
3309
56
            ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
3310
56
            if (DeserializationListener)
3311
2
              DeserializationListener->ModuleImportRead(GlobalID, Loc);
3312
56
          }
3313
56
        }
3314
47
      }
3315
47
      break;
3316
121
    }
3317
121
3318
4.48k
    case MACRO_OFFSET: {
3319
4.48k
      if (
F.LocalNumMacros != 04.48k
) {
3320
0
        Error("duplicate MACRO_OFFSET record in AST file");
3321
0
        return Failure;
3322
0
      }
3323
4.48k
      F.MacroOffsets = (const uint32_t *)Blob.data();
3324
4.48k
      F.LocalNumMacros = Record[0];
3325
4.48k
      unsigned LocalBaseMacroID = Record[1];
3326
4.48k
      F.BaseMacroID = getTotalNumMacros();
3327
4.48k
3328
4.48k
      if (
F.LocalNumMacros > 04.48k
) {
3329
2.28k
        // Introduce the global -> local mapping for macros within this module.
3330
2.28k
        GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3331
2.28k
3332
2.28k
        // Introduce the local -> global mapping for macros within this module.
3333
2.28k
        F.MacroRemap.insertOrReplace(
3334
2.28k
          std::make_pair(LocalBaseMacroID,
3335
2.28k
                         F.BaseMacroID - LocalBaseMacroID));
3336
2.28k
3337
2.28k
        MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3338
2.28k
      }
3339
4.48k
      break;
3340
4.48k
    }
3341
4.48k
3342
8
    case LATE_PARSED_TEMPLATE: {
3343
8
      LateParsedTemplates.append(Record.begin(), Record.end());
3344
8
      break;
3345
4.48k
    }
3346
4.48k
3347
1.32k
    case OPTIMIZE_PRAGMA_OPTIONS:
3348
1.32k
      if (
Record.size() != 11.32k
) {
3349
0
        Error("invalid pragma optimize record");
3350
0
        return Failure;
3351
0
      }
3352
1.32k
      OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3353
1.32k
      break;
3354
1.32k
3355
1.32k
    case MSSTRUCT_PRAGMA_OPTIONS:
3356
1.32k
      if (
Record.size() != 11.32k
) {
3357
0
        Error("invalid pragma ms_struct record");
3358
0
        return Failure;
3359
0
      }
3360
1.32k
      PragmaMSStructState = Record[0];
3361
1.32k
      break;
3362
1.32k
3363
1.32k
    case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3364
1.32k
      if (
Record.size() != 21.32k
) {
3365
0
        Error("invalid pragma ms_struct record");
3366
0
        return Failure;
3367
0
      }
3368
1.32k
      PragmaMSPointersToMembersState = Record[0];
3369
1.32k
      PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3370
1.32k
      break;
3371
1.32k
3372
4
    case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3373
8
      for (unsigned I = 0, N = Record.size(); 
I != N8
;
++I4
)
3374
4
        UnusedLocalTypedefNameCandidates.push_back(
3375
4
            getGlobalDeclID(F, Record[I]));
3376
4
      break;
3377
1.32k
3378
1
    case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3379
1
      if (
Record.size() != 11
) {
3380
0
        Error("invalid cuda pragma options record");
3381
0
        return Failure;
3382
0
      }
3383
1
      ForceCUDAHostDeviceDepth = Record[0];
3384
1
      break;
3385
1
3386
1.32k
    case PACK_PRAGMA_OPTIONS: {
3387
1.32k
      if (
Record.size() < 31.32k
) {
3388
0
        Error("invalid pragma pack record");
3389
0
        return Failure;
3390
0
      }
3391
1.32k
      PragmaPackCurrentValue = Record[0];
3392
1.32k
      PragmaPackCurrentLocation = ReadSourceLocation(F, Record[1]);
3393
1.32k
      unsigned NumStackEntries = Record[2];
3394
1.32k
      unsigned Idx = 3;
3395
1.32k
      // Reset the stack when importing a new module.
3396
1.32k
      PragmaPackStack.clear();
3397
1.32k
      for (unsigned I = 0; 
I < NumStackEntries1.32k
;
++I4
) {
3398
4
        PragmaPackStackEntry Entry;
3399
4
        Entry.Value = Record[Idx++];
3400
4
        Entry.Location = ReadSourceLocation(F, Record[Idx++]);
3401
4
        Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
3402
4
        PragmaPackStrings.push_back(ReadString(Record, Idx));
3403
4
        Entry.SlotLabel = PragmaPackStrings.back();
3404
4
        PragmaPackStack.push_back(Entry);
3405
4
      }
3406
4.46k
      break;
3407
4.46k
    }
3408
120k
    }
3409
120k
  }
3410
4.48k
}
3411
3412
1.70k
void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3413
1.70k
  assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3414
1.70k
3415
1.70k
  // Additional remapping information.
3416
1.70k
  const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
3417
1.70k
  const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3418
1.70k
  F.ModuleOffsetMap = StringRef();
3419
1.70k
3420
1.70k
  // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3421
1.70k
  if (
F.SLocRemap.find(0) == F.SLocRemap.end()1.70k
) {
3422
833
    F.SLocRemap.insert(std::make_pair(0U, 0));
3423
833
    F.SLocRemap.insert(std::make_pair(2U, 1));
3424
833
  }
3425
1.70k
3426
1.70k
  // Continuous range maps we may be updating in our module.
3427
1.70k
  typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
3428
1.70k
      RemapBuilder;
3429
1.70k
  RemapBuilder SLocRemap(F.SLocRemap);
3430
1.70k
  RemapBuilder IdentifierRemap(F.IdentifierRemap);
3431
1.70k
  RemapBuilder MacroRemap(F.MacroRemap);
3432
1.70k
  RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3433
1.70k
  RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3434
1.70k
  RemapBuilder SelectorRemap(F.SelectorRemap);
3435
1.70k
  RemapBuilder DeclRemap(F.DeclRemap);
3436
1.70k
  RemapBuilder TypeRemap(F.TypeRemap);
3437
1.70k
3438
14.3k
  while (
Data < DataEnd14.3k
) {
3439
12.6k
    // FIXME: Looking up dependency modules by filename is horrible. Let's
3440
12.6k
    // start fixing this with prebuilt and explicit modules and see how it
3441
12.6k
    // goes...
3442
12.6k
    using namespace llvm::support;
3443
12.6k
    ModuleKind Kind = static_cast<ModuleKind>(
3444
12.6k
      endian::readNext<uint8_t, little, unaligned>(Data));
3445
12.6k
    uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3446
12.6k
    StringRef Name = StringRef((const char*)Data, Len);
3447
12.6k
    Data += Len;
3448
12.6k
    ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule
3449
11.5k
                      ? ModuleMgr.lookupByModuleName(Name)
3450
1.09k
                      : ModuleMgr.lookupByFileName(Name));
3451
12.6k
    if (
!OM12.6k
) {
3452
0
      std::string Msg =
3453
0
          "SourceLocation remap refers to unknown module, cannot find ";
3454
0
      Msg.append(Name);
3455
0
      Error(Msg);
3456
0
      return;
3457
0
    }
3458
12.6k
3459
12.6k
    uint32_t SLocOffset =
3460
12.6k
        endian::readNext<uint32_t, little, unaligned>(Data);
3461
12.6k
    uint32_t IdentifierIDOffset =
3462
12.6k
        endian::readNext<uint32_t, little, unaligned>(Data);
3463
12.6k
    uint32_t MacroIDOffset =
3464
12.6k
        endian::readNext<uint32_t, little, unaligned>(Data);
3465
12.6k
    uint32_t PreprocessedEntityIDOffset =
3466
12.6k
        endian::readNext<uint32_t, little, unaligned>(Data);
3467
12.6k
    uint32_t SubmoduleIDOffset =
3468
12.6k
        endian::readNext<uint32_t, little, unaligned>(Data);
3469
12.6k
    uint32_t SelectorIDOffset =
3470
12.6k
        endian::readNext<uint32_t, little, unaligned>(Data);
3471
12.6k
    uint32_t DeclIDOffset =
3472
12.6k
        endian::readNext<uint32_t, little, unaligned>(Data);
3473
12.6k
    uint32_t TypeIndexOffset =
3474
12.6k
        endian::readNext<uint32_t, little, unaligned>(Data);
3475
12.6k
3476
12.6k
    uint32_t None = std::numeric_limits<uint32_t>::max();
3477
12.6k
3478
12.6k
    auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3479
101k
                         RemapBuilder &Remap) {
3480
101k
      if (Offset != None)
3481
55.6k
        Remap.insert(std::make_pair(Offset,
3482
55.6k
                                    static_cast<int>(BaseOffset - Offset)));
3483
101k
    };
3484
12.6k
    mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3485
12.6k
    mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3486
12.6k
    mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3487
12.6k
    mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3488
12.6k
              PreprocessedEntityRemap);
3489
12.6k
    mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3490
12.6k
    mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3491
12.6k
    mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3492
12.6k
    mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3493
12.6k
3494
12.6k
    // Global -> local mappings.
3495
12.6k
    F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3496
12.6k
  }
3497
1.70k
}
3498
3499
ASTReader::ASTReadResult
3500
ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3501
                                  const ModuleFile *ImportedBy,
3502
3.17k
                                  unsigned ClientLoadCapabilities) {
3503
3.17k
  unsigned Idx = 0;
3504
3.17k
  F.ModuleMapPath = ReadPath(F, Record, Idx);
3505
3.17k
3506
3.17k
  // Try to resolve ModuleName in the current header search context and
3507
3.17k
  // verify that it is found in the same module map file as we saved. If the
3508
3.17k
  // top-level AST file is a main file, skip this check because there is no
3509
3.17k
  // usable header search context.
3510
3.17k
  assert(!F.ModuleName.empty() &&
3511
3.17k
         "MODULE_NAME should come before MODULE_MAP_FILE");
3512
3.17k
  if (
F.Kind == MK_ImplicitModule && 3.17k
ModuleMgr.begin()->Kind != MK_MainFile1.99k
) {
3513
1.98k
    // An implicitly-loaded module file should have its module listed in some
3514
1.98k
    // module map file that we've already loaded.
3515
1.98k
    Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
3516
1.98k
    auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3517
1.98k
    const FileEntry *ModMap = M ? 
Map.getModuleMapFileForUniquing(M)1.97k
:
nullptr2
;
3518
1.98k
    if (
!ModMap1.98k
) {
3519
3
      assert(ImportedBy && "top-level import should be verified");
3520
3
      if (
(ClientLoadCapabilities & ARR_OutOfDate) == 03
) {
3521
3
        if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3522
3
          // This module was defined by an imported (explicit) module.
3523
1
          Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3524
1
                                               << ASTFE->getName();
3525
3
        else
3526
3
          // This module was built with a different module map.
3527
2
          Diag(diag::err_imported_module_not_found)
3528
2
              << F.ModuleName << F.FileName << ImportedBy->FileName
3529
2
              << F.ModuleMapPath;
3530
3
      }
3531
3
      return OutOfDate;
3532
3
    }
3533
1.97k
3534
1.98k
    assert(M->Name == F.ModuleName && "found module with different name");
3535
1.97k
3536
1.97k
    // Check the primary module map file.
3537
1.97k
    const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
3538
1.97k
    if (
StoredModMap == nullptr || 1.97k
StoredModMap != ModMap1.97k
) {
3539
0
      assert(ModMap && "found module is missing module map file");
3540
0
      assert(ImportedBy && "top-level import should be verified");
3541
0
      if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3542
0
        Diag(diag::err_imported_module_modmap_changed)
3543
0
          << F.ModuleName << ImportedBy->FileName
3544
0
          << ModMap->getName() << F.ModuleMapPath;
3545
0
      return OutOfDate;
3546
0
    }
3547
1.97k
3548
1.97k
    llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3549
2.02k
    for (unsigned I = 0, N = Record[Idx++]; 
I < N2.02k
;
++I49
) {
3550
50
      // FIXME: we should use input files rather than storing names.
3551
50
      std::string Filename = ReadPath(F, Record, Idx);
3552
50
      const FileEntry *F =
3553
50
          FileMgr.getFile(Filename, false, false);
3554
50
      if (
F == nullptr50
) {
3555
1
        if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3556
0
          Error("could not find file '" + Filename +"' referenced by AST file");
3557
1
        return OutOfDate;
3558
1
      }
3559
49
      AdditionalStoredMaps.insert(F);
3560
49
    }
3561
1.97k
3562
1.97k
    // Check any additional module map files (e.g. module.private.modulemap)
3563
1.97k
    // that are not in the pcm.
3564
1.97k
    
if (auto *1.97k
AdditionalModuleMaps1.97k
= Map.getAdditionalModuleMapFiles(M)) {
3565
50
      for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3566
50
        // Remove files that match
3567
50
        // Note: SmallPtrSet::erase is really remove
3568
50
        if (
!AdditionalStoredMaps.erase(ModMap)50
) {
3569
1
          if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3570
0
            Diag(diag::err_module_different_modmap)
3571
0
              << F.ModuleName << /*new*/0 << ModMap->getName();
3572
1
          return OutOfDate;
3573
1
        }
3574
1.97k
      }
3575
50
    }
3576
1.97k
3577
1.97k
    // Check any additional module map files that are in the pcm, but not
3578
1.97k
    // found in header search. Cases that match are already removed.
3579
1.97k
    
for (const FileEntry *ModMap : AdditionalStoredMaps) 1.97k
{
3580
0
      if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3581
0
        Diag(diag::err_module_different_modmap)
3582
0
          << F.ModuleName << /*not new*/1 << ModMap->getName();
3583
0
      return OutOfDate;
3584
0
    }
3585
3.17k
  }
3586
3.17k
3587
3.17k
  
if (3.17k
Listener3.17k
)
3588
3.17k
    Listener->ReadModuleMapFile(F.ModuleMapPath);
3589
3.17k
  return Success;
3590
3.17k
}
3591
3592
3593
/// \brief Move the given method to the back of the global list of methods.
3594
6
static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3595
6
  // Find the entry for this selector in the method pool.
3596
6
  Sema::GlobalMethodPool::iterator Known
3597
6
    = S.MethodPool.find(Method->getSelector());
3598
6
  if (Known == S.MethodPool.end())
3599
0
    return;
3600
6
3601
6
  // Retrieve the appropriate method list.
3602
6
  
ObjCMethodList &Start = Method->isInstanceMethod()? 6
Known->second.first6
3603
0
                                                    : Known->second.second;
3604
6
  bool Found = false;
3605
16
  for (ObjCMethodList *List = &Start; 
List16
;
List = List->getNext()10
) {
3606
10
    if (
!Found10
) {
3607
8
      if (
List->getMethod() == Method8
) {
3608
5
        Found = true;
3609
8
      } else {
3610
3
        // Keep searching.
3611
3
        continue;
3612
3
      }
3613
7
    }
3614
7
3615
7
    
if (7
List->getNext()7
)
3616
2
      List->setMethod(List->getNext()->getMethod());
3617
7
    else
3618
5
      List->setMethod(Method);
3619
10
  }
3620
6
}
3621
3622
1.06k
void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
3623
1.06k
  assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
3624
5.81k
  for (Decl *D : Names) {
3625
5.81k
    bool wasHidden = D->isHidden();
3626
5.81k
    D->setVisibleDespiteOwningModule();
3627
5.81k
3628
5.81k
    if (
wasHidden && 5.81k
SemaObj3.21k
) {
3629
3.20k
      if (ObjCMethodDecl *
Method3.20k
= dyn_cast<ObjCMethodDecl>(D)) {
3630
6
        moveMethodToBackOfGlobalList(*SemaObj, Method);
3631
6
      }
3632
3.20k
    }
3633
5.81k
  }
3634
1.06k
}
3635
3636
void ASTReader::makeModuleVisible(Module *Mod,
3637
                                  Module::NameVisibilityKind NameVisibility,
3638
6.68k
                                  SourceLocation ImportLoc) {
3639
6.68k
  llvm::SmallPtrSet<Module *, 4> Visited;
3640
6.68k
  SmallVector<Module *, 4> Stack;
3641
6.68k
  Stack.push_back(Mod);
3642
15.6k
  while (
!Stack.empty()15.6k
) {
3643
8.98k
    Mod = Stack.pop_back_val();
3644
8.98k
3645
8.98k
    if (
NameVisibility <= Mod->NameVisibility8.98k
) {
3646
3.23k
      // This module already has this level of visibility (or greater), so
3647
3.23k
      // there is nothing more to do.
3648
3.23k
      continue;
3649
3.23k
    }
3650
5.74k
3651
5.74k
    
if (5.74k
!Mod->isAvailable()5.74k
) {
3652
14
      // Modules that aren't available cannot be made visible.
3653
14
      continue;
3654
14
    }
3655
5.73k
3656
5.73k
    // Update the module's name visibility.
3657
5.73k
    Mod->NameVisibility = NameVisibility;
3658
5.73k
3659
5.73k
    // If we've already deserialized any names from this module,
3660
5.73k
    // mark them as visible.
3661
5.73k
    HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3662
5.73k
    if (
Hidden != HiddenNamesMap.end()5.73k
) {
3663
1.06k
      auto HiddenNames = std::move(*Hidden);
3664
1.06k
      HiddenNamesMap.erase(Hidden);
3665
1.06k
      makeNamesVisible(HiddenNames.second, HiddenNames.first);
3666
1.06k
      assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3667
1.06k
             "making names visible added hidden names");
3668
1.06k
    }
3669
5.73k
3670
5.73k
    // Push any exported modules onto the stack to be marked as visible.
3671
5.73k
    SmallVector<Module *, 16> Exports;
3672
5.73k
    Mod->getExportedModules(Exports);
3673
5.73k
    for (SmallVectorImpl<Module *>::iterator
3674
9.02k
           I = Exports.begin(), E = Exports.end(); 
I != E9.02k
;
++I3.29k
) {
3675
3.29k
      Module *Exported = *I;
3676
3.29k
      if (Visited.insert(Exported).second)
3677
2.29k
        Stack.push_back(Exported);
3678
3.29k
    }
3679
8.98k
  }
3680
6.68k
}
3681
3682
/// We've merged the definition \p MergedDef into the existing definition
3683
/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
3684
/// visible.
3685
void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
3686
1.13k
                                          NamedDecl *MergedDef) {
3687
1.13k
  // FIXME: This doesn't correctly handle the case where MergedDef is visible
3688
1.13k
  // in modules other than its owning module. We should instead give the
3689
1.13k
  // ASTContext a list of merged definitions for Def.
3690
1.13k
  if (
Def->isHidden()1.13k
) {
3691
316
    // If MergedDef is visible or becomes visible, make the definition visible.
3692
316
    if (!MergedDef->isHidden())
3693
43
      Def->setVisibleDespiteOwningModule();
3694
273
    else 
if (273
getContext().getLangOpts().ModulesLocalVisibility273
) {
3695
57
      getContext().mergeDefinitionIntoModule(
3696
57
          Def, MergedDef->getImportedOwningModule(),
3697
57
          /*NotifyListeners*/ false);
3698
57
      PendingMergedDefinitionsToDeduplicate.insert(Def);
3699
273
    } else {
3700
216
      auto SubmoduleID = MergedDef->getOwningModuleID();
3701
216
      assert(SubmoduleID && "hidden definition in no module");
3702
216
      HiddenNamesMap[getSubmodule(SubmoduleID)].push_back(Def);
3703
216
    }
3704
316
  }
3705
1.13k
}
3706
3707
897k
bool ASTReader::loadGlobalIndex() {
3708
897k
  if (GlobalIndex)
3709
257k
    return false;
3710
640k
3711
640k
  
if (640k
TriedLoadingGlobalIndex || 640k
!UseGlobalIndex176k
||
3712
173k
      !PP.getLangOpts().Modules)
3713
639k
    return true;
3714
880
3715
880
  // Try to load the global index.
3716
880
  TriedLoadingGlobalIndex = true;
3717
880
  StringRef ModuleCachePath
3718
880
    = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3719
880
  std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
3720
880
    = GlobalModuleIndex::readIndex(ModuleCachePath);
3721
880
  if (!Result.first)
3722
705
    return true;
3723
175
3724
175
  GlobalIndex.reset(Result.first);
3725
175
  ModuleMgr.setGlobalIndex(GlobalIndex.get());
3726
175
  return false;
3727
175
}
3728
3729
2.73k
bool ASTReader::isGlobalIndexUnavailable() const {
3730
1.69k
  return PP.getLangOpts().Modules && UseGlobalIndex &&
3731
2.73k
         
!hasGlobalIndex()1.69k
&&
TriedLoadingGlobalIndex1.55k
;
3732
2.73k
}
3733
3734
10
static void updateModuleTimestamp(ModuleFile &MF) {
3735
10
  // Overwrite the timestamp file contents so that file's mtime changes.
3736
10
  std::string TimestampFilename = MF.getTimestampFilename();
3737
10
  std::error_code EC;
3738
10
  llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3739
10
  if (EC)
3740
0
    return;
3741
10
  OS << "Timestamp file\n";
3742
10
  OS.close();
3743
10
  OS.clear_error(); // Avoid triggering a fatal error.
3744
10
}
3745
3746
/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3747
/// cursor into the start of the given block ID, returning false on success and
3748
/// true on failure.
3749
10.7k
static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
3750
31.7k
  while (
true31.7k
) {
3751
31.7k
    llvm::BitstreamEntry Entry = Cursor.advance();
3752
31.7k
    switch (Entry.Kind) {
3753
4.49k
    case llvm::BitstreamEntry::Error:
3754
4.49k
    case llvm::BitstreamEntry::EndBlock:
3755
4.49k
      return true;
3756
4.49k
3757
0
    case llvm::BitstreamEntry::Record:
3758
0
      // Ignore top-level records.
3759
0
      Cursor.skipRecord(Entry.ID);
3760
0
      break;
3761
4.49k
3762
27.3k
    case llvm::BitstreamEntry::SubBlock:
3763
27.3k
      if (
Entry.ID == BlockID27.3k
) {
3764
6.26k
        if (Cursor.EnterSubBlock(BlockID))
3765
0
          return true;
3766
6.26k
        // Found it!
3767
6.26k
        return false;
3768
6.26k
      }
3769
21.0k
3770
21.0k
      
if (21.0k
Cursor.SkipBlock()21.0k
)
3771
0
        return true;
3772
31.7k
    }
3773
31.7k
  }
3774
10.7k
}
3775
3776
ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
3777
                                            ModuleKind Type,
3778
                                            SourceLocation ImportLoc,
3779
                                            unsigned ClientLoadCapabilities,
3780
4.19k
                                            SmallVectorImpl<ImportedSubmodule> *Imported) {
3781
4.19k
  llvm::SaveAndRestore<SourceLocation>
3782
4.19k
    SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3783
4.19k
3784
4.19k
  // Defer any pending actions until we get to the end of reading the AST file.
3785
4.19k
  Deserializing AnASTFile(this);
3786
4.19k
3787
4.19k
  // Bump the generation number.
3788
4.19k
  unsigned PreviousGeneration = 0;
3789
4.19k
  if (ContextObj)
3790
4.18k
    PreviousGeneration = incrementGeneration(*ContextObj);
3791
4.19k
3792
4.19k
  unsigned NumModules = ModuleMgr.size();
3793
4.19k
  SmallVector<ImportedModule, 4> Loaded;
3794
4.19k
  switch (ASTReadResult ReadResult =
3795
4.19k
              ReadASTCore(FileName, Type, ImportLoc,
3796
4.19k
                          /*ImportedBy=*/nullptr, Loaded, 0, 0,
3797
4.19k
                          ASTFileSignature(), ClientLoadCapabilities)) {
3798
1.11k
  case Failure:
3799
1.11k
  case Missing:
3800
1.11k
  case OutOfDate:
3801
1.11k
  case VersionMismatch:
3802
1.11k
  case ConfigurationMismatch:
3803
1.11k
  case HadErrors: {
3804
1.11k
    llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3805
1.11k
    for (const ImportedModule &IM : Loaded)
3806
6
      LoadedSet.insert(IM.Mod);
3807
1.11k
3808
1.11k
    ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet,
3809
1.11k
                            PP.getLangOpts().Modules
3810
1.09k
                                ? &PP.getHeaderSearchInfo().getModuleMap()
3811
18
                                : nullptr);
3812
1.11k
3813
1.11k
    // If we find that any modules are unusable, the global index is going
3814
1.11k
    // to be out-of-date. Just remove it.
3815
1.11k
    GlobalIndex.reset();
3816
1.11k
    ModuleMgr.setGlobalIndex(nullptr);
3817
1.11k
    return ReadResult;
3818
1.11k
  }
3819
3.08k
  case Success:
3820
3.08k
    break;
3821
3.08k
  }
3822
3.08k
3823
3.08k
  // Here comes stuff that we only do once the entire chain is loaded.
3824
3.08k
3825
3.08k
  // Load the AST blocks of all of the modules that we loaded.
3826
3.08k
  for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3827
3.08k
                                              MEnd = Loaded.end();
3828
7.56k
       
M != MEnd7.56k
;
++M4.48k
) {
3829
4.48k
    ModuleFile &F = *M->Mod;
3830
4.48k
3831
4.48k
    // Read the AST block.
3832
4.48k
    if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3833
4
      return Result;
3834
4.48k
3835
4.48k
    // Read the extension blocks.
3836
4.50k
    
while (4.48k
!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)4.50k
) {
3837
18
      if (ASTReadResult Result = ReadExtensionBlock(F))
3838
0
        return Result;
3839
18
    }
3840
4.48k
3841
4.48k
    // Once read, set the ModuleFile bit base offset and update the size in
3842
4.48k
    // bits of all files we've seen.
3843
4.48k
    F.GlobalBitOffset = TotalModulesSizeInBits;
3844
4.48k
    TotalModulesSizeInBits += F.SizeInBits;
3845
4.48k
    GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3846
4.48k
3847
4.48k
    // Preload SLocEntries.
3848
8.97k
    for (unsigned I = 0, N = F.PreloadSLocEntries.size(); 
I != N8.97k
;
++I4.48k
) {
3849
4.48k
      int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3850
4.48k
      // Load it through the SourceManager and don't call ReadSLocEntry()
3851
4.48k
      // directly because the entry may have already been loaded in which case
3852
4.48k
      // calling ReadSLocEntry() directly would trigger an assertion in
3853
4.48k
      // SourceManager.
3854
4.48k
      SourceMgr.getLoadedSLocEntryByID(Index);
3855
4.48k
    }
3856
4.48k
3857
4.48k
    // Map the original source file ID into the ID space of the current
3858
4.48k
    // compilation.
3859
4.48k
    if (
F.OriginalSourceFileID.isValid()4.48k
) {
3860
4.48k
      F.OriginalSourceFileID = FileID::get(
3861
4.48k
          F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1);
3862
4.48k
    }
3863
4.48k
3864
4.48k
    // Preload all the pending interesting identifiers by marking them out of
3865
4.48k
    // date.
3866
3.72k
    for (auto Offset : F.PreloadIdentifierOffsets) {
3867
3.72k
      const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3868
3.72k
          F.IdentifierTableData + Offset);
3869
3.72k
3870
3.72k
      ASTIdentifierLookupTrait Trait(*this, F);
3871
3.72k
      auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3872
3.72k
      auto Key = Trait.ReadKey(Data, KeyDataLen.first);
3873
3.72k
      auto &II = PP.getIdentifierTable().getOwn(Key);
3874
3.72k
      II.setOutOfDate(true);
3875
3.72k
3876
3.72k
      // Mark this identifier as being from an AST file so that we can track
3877
3.72k
      // whether we need to serialize it.
3878
3.72k
      markIdentifierFromAST(*this, II);
3879
3.72k
3880
3.72k
      // Associate the ID with the identifier so that the writer can reuse it.
3881
3.72k
      auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3882
3.72k
      SetIdentifierInfo(ID, &II);
3883
3.72k
    }
3884
4.48k
  }
3885
3.08k
3886
3.08k
  // Setup the import locations and notify the module manager that we've
3887
3.08k
  // committed to these module files.
3888
3.07k
  for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3889
3.07k
                                              MEnd = Loaded.end();
3890
7.56k
       
M != MEnd7.56k
;
++M4.48k
) {
3891
4.48k
    ModuleFile &F = *M->Mod;
3892
4.48k
3893
4.48k
    ModuleMgr.moduleFileAccepted(&F);
3894
4.48k
3895
4.48k
    // Set the import location.
3896
4.48k
    F.DirectImportLoc = ImportLoc;
3897
4.48k
    // FIXME: We assume that locations from PCH / preamble do not need
3898
4.48k
    // any translation.
3899
4.48k
    if (!M->ImportedBy)
3900
3.02k
      F.ImportLoc = M->ImportLoc;
3901
4.48k
    else
3902
1.46k
      F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
3903
4.48k
  }
3904
3.07k
3905
3.07k
  if (!PP.getLangOpts().CPlusPlus ||
3906
1.83k
      
(Type != MK_ImplicitModule && 1.83k
Type != MK_ExplicitModule1.00k
&&
3907
3.07k
       
Type != MK_PrebuiltModule641
)) {
3908
1.88k
    // Mark all of the identifiers in the identifier table as being out of date,
3909
1.88k
    // so that various accessors know to check the loaded modules when the
3910
1.88k
    // identifier is used.
3911
1.88k
    //
3912
1.88k
    // For C++ modules, we don't need information on many identifiers (just
3913
1.88k
    // those that provide macros or are poisoned), so we mark all of
3914
1.88k
    // the interesting ones via PreloadIdentifierOffsets.
3915
1.88k
    for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3916
1.88k
                                IdEnd = PP.getIdentifierTable().end();
3917
2.31M
         
Id != IdEnd2.31M
;
++Id2.31M
)
3918
2.31M
      Id->second->setOutOfDate(true);
3919
1.88k
  }
3920
3.07k
  // Mark selectors as out of date.
3921
3.07k
  for (auto Sel : SelectorGeneration)
3922
29
    SelectorOutOfDate[Sel.first] = true;
3923
3.07k
3924
3.07k
  // Resolve any unresolved module exports.
3925
9.53k
  for (unsigned I = 0, N = UnresolvedModuleRefs.size(); 
I != N9.53k
;
++I6.45k
) {
3926
6.45k
    UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
3927
6.45k
    SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3928
6.45k
    Module *ResolvedMod = getSubmodule(GlobalID);
3929
6.45k
3930
6.45k
    switch (Unresolved.Kind) {
3931
1
    case UnresolvedModuleRef::Conflict:
3932
1
      if (
ResolvedMod1
) {
3933
1
        Module::Conflict Conflict;
3934
1
        Conflict.Other = ResolvedMod;
3935
1
        Conflict.Message = Unresolved.String.str();
3936
1
        Unresolved.Mod->Conflicts.push_back(Conflict);
3937
1
      }
3938
1
      continue;
3939
6.45k
3940
3.10k
    case UnresolvedModuleRef::Import:
3941
3.10k
      if (ResolvedMod)
3942
3.10k
        Unresolved.Mod->Imports.insert(ResolvedMod);
3943
3.10k
      continue;
3944
6.45k
3945
3.34k
    case UnresolvedModuleRef::Export:
3946
3.34k
      if (
ResolvedMod || 3.34k
Unresolved.IsWildcard3.20k
)
3947
3.34k
        Unresolved.Mod->Exports.push_back(
3948
3.34k
          Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3949
3.34k
      continue;
3950
6.45k
    }
3951
6.45k
  }
3952
3.07k
  UnresolvedModuleRefs.clear();
3953
3.07k
3954
3.07k
  if (Imported)
3955
0
    Imported->append(ImportedModules.begin(),
3956
0
                     ImportedModules.end());
3957
3.07k
3958
3.07k
  // FIXME: How do we load the 'use'd modules? They may not be submodules.
3959
3.07k
  // Might be unnecessary as use declarations are only used to build the
3960
3.07k
  // module itself.
3961
3.07k
3962
3.07k
  if (ContextObj)
3963
3.06k
    InitializeContext();
3964
3.07k
3965
3.07k
  if (SemaObj)
3966
1.44k
    UpdateSema();
3967
3.07k
3968
3.07k
  if (DeserializationListener)
3969
792
    DeserializationListener->ReaderInitialized(this);
3970
3.07k
3971
3.07k
  ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3972
3.07k
  if (
PrimaryModule.OriginalSourceFileID.isValid()3.07k
) {
3973
3.07k
    // If this AST file is a precompiled preamble, then set the
3974
3.07k
    // preamble file ID of the source manager to the file source file
3975
3.07k
    // from which the preamble was built.
3976
3.07k
    if (
Type == MK_Preamble3.07k
) {
3977
297
      SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3978
3.07k
    } else 
if (2.78k
Type == MK_MainFile2.78k
) {
3979
112
      SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3980
112
    }
3981
3.07k
  }
3982
3.07k
3983
3.07k
  // For any Objective-C class definitions we have already loaded, make sure
3984
3.07k
  // that we load any additional categories.
3985
3.07k
  if (
ContextObj3.07k
) {
3986
3.10k
    for (unsigned I = 0, N = ObjCClassesLoaded.size(); 
I != N3.10k
;
++I41
) {
3987
41
      loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3988
41
                         ObjCClassesLoaded[I],
3989
41
                         PreviousGeneration);
3990
41
    }
3991
3.06k
  }
3992
3.07k
3993
3.07k
  if (PP.getHeaderSearchInfo()
3994
3.07k
          .getHeaderSearchOpts()
3995
3.07k
          .ModulesValidateOncePerBuildSession) {
3996
10
    // Now we are certain that the module and all modules it depends on are
3997
10
    // up to date.  Create or update timestamp files for modules that are
3998
10
    // located in the module cache (not for PCH files that could be anywhere
3999
10
    // in the filesystem).
4000
20
    for (unsigned I = 0, N = Loaded.size(); 
I != N20
;
++I10
) {
4001
10
      ImportedModule &M = Loaded[I];
4002
10
      if (
M.Mod->Kind == MK_ImplicitModule10
) {
4003
10
        updateModuleTimestamp(*M.Mod);
4004
10
      }
4005
10
    }
4006
10
  }
4007
3.07k
4008
3.07k
  return Success;
4009
4.19k
}
4010
4011
static ASTFileSignature readASTFileSignature(StringRef PCH);
4012
4013
/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
4014
10.8k
static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
4015
10.8k
  return Stream.canSkipToPos(4) &&
4016
10.8k
         Stream.Read(8) == 'C' &&
4017
10.8k
         Stream.Read(8) == 'P' &&
4018
10.8k
         Stream.Read(8) == 'C' &&
4019
10.8k
         Stream.Read(8) == 'H';
4020
10.8k
}
4021
4022
18
static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
4023
18
  switch (Kind) {
4024
7
  case MK_PCH:
4025
7
    return 0; // PCH
4026
10
  case MK_ImplicitModule:
4027
10
  case MK_ExplicitModule:
4028
10
  case MK_PrebuiltModule:
4029
10
    return 1; // module
4030
1
  case MK_MainFile:
4031
1
  case MK_Preamble:
4032
1
    return 2; // main source file
4033
0
  }
4034
0
  
llvm_unreachable0
("unknown module kind");
4035
0
}
4036
4037
ASTReader::ASTReadResult
4038
ASTReader::ReadASTCore(StringRef FileName,
4039
                       ModuleKind Type,
4040
                       SourceLocation ImportLoc,
4041
                       ModuleFile *ImportedBy,
4042
                       SmallVectorImpl<ImportedModule> &Loaded,
4043
                       off_t ExpectedSize, time_t ExpectedModTime,
4044
                       ASTFileSignature ExpectedSignature,
4045
6.83k
                       unsigned ClientLoadCapabilities) {
4046
6.83k
  ModuleFile *M;
4047
6.83k
  std::string ErrorStr;
4048
6.83k
  ModuleManager::AddModuleResult AddResult
4049
6.83k
    = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
4050
6.83k
                          getGeneration(), ExpectedSize, ExpectedModTime,
4051
6.83k
                          ExpectedSignature, readASTFileSignature,
4052
6.83k
                          M, ErrorStr);
4053
6.83k
4054
6.83k
  switch (AddResult) {
4055
1.18k
  case ModuleManager::AlreadyLoaded:
4056
1.18k
    return Success;
4057
6.83k
4058
4.61k
  case ModuleManager::NewlyLoaded:
4059
4.61k
    // Load module file below.
4060
4.61k
    break;
4061
6.83k
4062
1.02k
  case ModuleManager::Missing:
4063
1.02k
    // The module file was missing; if the client can handle that, return
4064
1.02k
    // it.
4065
1.02k
    if (ClientLoadCapabilities & ARR_Missing)
4066
1.02k
      return Missing;
4067
4
4068
4
    // Otherwise, return an error.
4069
4
    Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
4070
4
                                          << FileName << !ErrorStr.empty()
4071
4
                                          << ErrorStr;
4072
4
    return Failure;
4073
4
4074
10
  case ModuleManager::OutOfDate:
4075
10
    // We couldn't load the module file because it is out-of-date. If the
4076
10
    // client can handle out-of-date, return it.
4077
10
    if (ClientLoadCapabilities & ARR_OutOfDate)
4078
9
      return OutOfDate;
4079
1
4080
1
    // Otherwise, return an error.
4081
1
    Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
4082
1
                                            << FileName << !ErrorStr.empty()
4083
1
                                            << ErrorStr;
4084
1
    return Failure;
4085
4.61k
  }
4086
4.61k
4087
6.83k
  assert(M && "Missing module file");
4088
4.61k
4089
4.61k
  ModuleFile &F = *M;
4090
4.61k
  BitstreamCursor &Stream = F.Stream;
4091
4.61k
  Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
4092
4.61k
  F.SizeInBits = F.Buffer->getBufferSize() * 8;
4093
4.61k
4094
4.61k
  // Sniff for the signature.
4095
4.61k
  if (
!startsWithASTFileMagic(Stream)4.61k
) {
4096
5
    Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
4097
5
                                        << FileName;
4098
5
    return Failure;
4099
5
  }
4100
4.60k
4101
4.60k
  // This is used for compatibility with older PCH formats.
4102
4.60k
  bool HaveReadControlBlock = false;
4103
13.7k
  while (
true13.7k
) {
4104
13.7k
    llvm::BitstreamEntry Entry = Stream.advance();
4105
13.7k
4106
13.7k
    switch (Entry.Kind) {
4107
0
    case llvm::BitstreamEntry::Error:
4108
0
    case llvm::BitstreamEntry::Record:
4109
0
    case llvm::BitstreamEntry::EndBlock:
4110
0
      Error("invalid record at top-level of AST file");
4111
0
      return Failure;
4112
0
4113
13.7k
    case llvm::BitstreamEntry::SubBlock:
4114
13.7k
      break;
4115
13.7k
    }
4116
13.7k
4117
13.7k
    switch (Entry.ID) {
4118
4.60k
    case CONTROL_BLOCK_ID:
4119
4.60k
      HaveReadControlBlock = true;
4120
4.60k
      switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
4121
4.49k
      case Success:
4122
4.49k
        // Check that we didn't try to load a non-module AST file as a module.
4123
4.49k
        //
4124
4.49k
        // FIXME: Should we also perform the converse check? Loading a module as
4125
4.49k
        // a PCH file sort of works, but it's a bit wonky.
4126
4.49k
        if (
(Type == MK_ImplicitModule || 4.49k
Type == MK_ExplicitModule2.56k
||
4127
1.36k
             Type == MK_PrebuiltModule) &&
4128
4.49k
            
F.ModuleName.empty()3.13k
) {
4129
1
          auto Result = (Type == MK_ImplicitModule) ? 
OutOfDate0
:
Failure1
;
4130
1
          if (Result != OutOfDate ||
4131
0
              (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4132
1
            Diag(diag::err_module_file_not_module) << FileName;
4133
1
          return Result;
4134
1
        }
4135
4.49k
        break;
4136
4.49k
4137
5
      case Failure: return Failure;
4138
0
      case Missing: return Missing;
4139
83
      case OutOfDate: return OutOfDate;
4140
0
      case VersionMismatch: return VersionMismatch;
4141
19
      case ConfigurationMismatch: return ConfigurationMismatch;
4142
1
      case HadErrors: return HadErrors;
4143
4.49k
      }
4144
4.49k
      break;
4145
4.49k
4146
4.49k
    case AST_BLOCK_ID:
4147
4.49k
      if (
!HaveReadControlBlock4.49k
) {
4148
0
        if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
4149
0
          Diag(diag::err_pch_version_too_old);
4150
0
        return VersionMismatch;
4151
0
      }
4152
4.49k
4153
4.49k
      // Record that we've loaded this module.
4154
4.49k
      Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4155
4.49k
      return Success;
4156
4.49k
4157
0
    case UNHASHED_CONTROL_BLOCK_ID:
4158
0
      // This block is handled using look-ahead during ReadControlBlock.  We
4159
0
      // shouldn't get here!
4160
0
      Error("malformed block record in AST file");
4161
0
      return Failure;
4162
4.49k
4163
4.60k
    default:
4164
4.60k
      if (
Stream.SkipBlock()4.60k
) {
4165
0
        Error("malformed block record in AST file");
4166
0
        return Failure;
4167
0
      }
4168
4.60k
      break;
4169
13.7k
    }
4170
13.7k
  }
4171
4.60k
4172
0
  return Success;
4173
6.83k
}
4174
4175
ASTReader::ASTReadResult
4176
ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4177
4.59k
                                    unsigned ClientLoadCapabilities) {
4178
4.59k
  const HeaderSearchOptions &HSOpts =
4179
4.59k
      PP.getHeaderSearchInfo().getHeaderSearchOpts();
4180
4.59k
  bool AllowCompatibleConfigurationMismatch =
4181
3.39k
      F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4182
4.59k
4183
4.59k
  ASTReadResult Result = readUnhashedControlBlockImpl(
4184
4.59k
      &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4185
4.59k
      Listener.get(),
4186
4.59k
      WasImportedBy ? 
false1.49k
:
HSOpts.ModulesValidateDiagnosticOptions3.10k
);
4187
4.59k
4188
4.59k
  // If F was directly imported by another module, it's implicitly validated by
4189
4.59k
  // the importing module.
4190
4.59k
  if (
DisableValidation || 4.59k
WasImportedBy4.13k
||
4191
2.75k
      
(AllowConfigurationMismatch && 2.75k
Result == ConfigurationMismatch7
))
4192
1.84k
    return Success;
4193
2.75k
4194
2.75k
  
if (2.75k
Result == Failure2.75k
) {
4195
0
    Error("malformed block record in AST file");
4196
0
    return Failure;
4197
0
  }
4198
2.75k
4199
2.75k
  
if (2.75k
Result == OutOfDate && 2.75k
F.Kind == MK_ImplicitModule13
) {
4200
13
    // If this module has already been finalized in the PCMCache, we're stuck
4201
13
    // with it; we can only load a single version of each module.
4202
13
    //
4203
13
    // This can happen when a module is imported in two contexts: in one, as a
4204
13
    // user module; in another, as a system module (due to an import from
4205
13
    // another module marked with the [system] flag).  It usually indicates a
4206
13
    // bug in the module map: this module should also be marked with [system].
4207
13
    //
4208
13
    // If -Wno-system-headers (the default), and the first import is as a
4209
13
    // system module, then validation will fail during the as-user import,
4210
13
    // since -Werror flags won't have been validated.  However, it's reasonable
4211
13
    // to treat this consistently as a system module.
4212
13
    //
4213
13
    // If -Wsystem-headers, the PCM on disk was built with
4214
13
    // -Wno-system-headers, and the first import is as a user module, then
4215
13
    // validation will fail during the as-system import since the PCM on disk
4216
13
    // doesn't guarantee that -Werror was respected.  However, the -Werror
4217
13
    // flags were checked during the initial as-user import.
4218
13
    if (
PCMCache.isBufferFinal(F.FileName)13
) {
4219
2
      Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4220
2
      return Success;
4221
2
    }
4222
2.75k
  }
4223
2.75k
4224
2.75k
  return Result;
4225
2.75k
}
4226
4227
ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4228
    ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4229
    bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4230
4.60k
    bool ValidateDiagnosticOptions) {
4231
4.60k
  // Initialize a stream.
4232
4.60k
  BitstreamCursor Stream(StreamData);
4233
4.60k
4234
4.60k
  // Sniff for the signature.
4235
4.60k
  if (!startsWithASTFileMagic(Stream))
4236
0
    return Failure;
4237
4.60k
4238
4.60k
  // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4239
4.60k
  
if (4.60k
SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID)4.60k
)
4240
0
    return Failure;
4241
4.60k
4242
4.60k
  // Read all of the records in the options block.
4243
4.60k
  RecordData Record;
4244
4.60k
  ASTReadResult Result = Success;
4245
15.8k
  while (
115.8k
) {
4246
15.8k
    llvm::BitstreamEntry Entry = Stream.advance();
4247
15.8k
4248
15.8k
    switch (Entry.Kind) {
4249
0
    case llvm::BitstreamEntry::Error:
4250
0
    case llvm::BitstreamEntry::SubBlock:
4251
0
      return Failure;
4252
0
4253
4.60k
    case llvm::BitstreamEntry::EndBlock:
4254
4.60k
      return Result;
4255
0
4256
11.2k
    case llvm::BitstreamEntry::Record:
4257
11.2k
      // The interesting case.
4258
11.2k
      break;
4259
11.2k
    }
4260
11.2k
4261
11.2k
    // Read and process a record.
4262
11.2k
    Record.clear();
4263
11.2k
    switch (
4264
11.2k
        (UnhashedControlBlockRecordTypes)Stream.readRecord(Entry.ID, Record)) {
4265
2.00k
    case SIGNATURE: {
4266
2.00k
      if (F)
4267
2.00k
        std::copy(Record.begin(), Record.end(), F->Signature.data());
4268
2.00k
      break;
4269
11.2k
    }
4270
4.60k
    case DIAGNOSTIC_OPTIONS: {
4271
4.60k
      bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4272
4.60k
      if (
Listener && 4.60k
ValidateDiagnosticOptions4.60k
&&
4273
3.10k
          !AllowCompatibleConfigurationMismatch &&
4274
2.71k
          ParseDiagnosticOptions(Record, Complain, *Listener))
4275
13
        Result = OutOfDate; // Don't return early.  Read the signature.
4276
4.60k
      break;
4277
11.2k
    }
4278
4.60k
    case DIAG_PRAGMA_MAPPINGS:
4279
4.60k
      if (!F)
4280
8
        break;
4281
4.59k
      
if (4.59k
F->PragmaDiagMappings.empty()4.59k
)
4282
4.59k
        F->PragmaDiagMappings.swap(Record);
4283
4.59k
      else
4284
0
        F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4285
0
                                     Record.begin(), Record.end());
4286
4.60k
      break;
4287
15.8k
    }
4288
15.8k
  }
4289
4.60k
}
4290
4291
/// Parse a record and blob containing module file extension metadata.
4292
static bool parseModuleFileExtensionMetadata(
4293
              const SmallVectorImpl<uint64_t> &Record,
4294
              StringRef Blob,
4295
20
              ModuleFileExtensionMetadata &Metadata) {
4296
20
  if (
Record.size() < 420
)
return true0
;
4297
20
4298
20
  Metadata.MajorVersion = Record[0];
4299
20
  Metadata.MinorVersion = Record[1];
4300
20
4301
20
  unsigned BlockNameLen = Record[2];
4302
20
  unsigned UserInfoLen = Record[3];
4303
20
4304
20
  if (
BlockNameLen + UserInfoLen > Blob.size()20
)
return true0
;
4305
20
4306
20
  Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4307
20
  Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4308
20
                                  Blob.data() + BlockNameLen + UserInfoLen);
4309
20
  return false;
4310
20
}
4311
4312
18
ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4313
18
  BitstreamCursor &Stream = F.Stream;
4314
18
4315
18
  RecordData Record;
4316
54
  while (
true54
) {
4317
54
    llvm::BitstreamEntry Entry = Stream.advance();
4318
54
    switch (Entry.Kind) {
4319
0
    case llvm::BitstreamEntry::SubBlock:
4320
0
      if (Stream.SkipBlock())
4321
0
        return Failure;
4322
0
4323
0
      continue;
4324
0
4325
18
    case llvm::BitstreamEntry::EndBlock:
4326
18
      return Success;
4327
0
4328
0
    case llvm::BitstreamEntry::Error:
4329
0
      return HadErrors;
4330
0
4331
36
    case llvm::BitstreamEntry::Record:
4332
36
      break;
4333
36
    }
4334
36
4335
36
    Record.clear();
4336
36
    StringRef Blob;
4337
36
    unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4338
36
    switch (RecCode) {
4339
18
    case EXTENSION_METADATA: {
4340
18
      ModuleFileExtensionMetadata Metadata;
4341
18
      if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4342
0
        return Failure;
4343
18
4344
18
      // Find a module file extension with this block name.
4345
18
      auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4346
18
      if (
Known == ModuleFileExtensions.end()18
)
break3
;
4347
15
4348
15
      // Form a reader.
4349
15
      
if (auto 15
Reader15
= Known->second->createExtensionReader(Metadata, *this,
4350
13
                                                             F, Stream)) {
4351
13
        F.ExtensionReaders.push_back(std::move(Reader));
4352
13
      }
4353
18
4354
18
      break;
4355
18
    }
4356
54
    }
4357
54
  }
4358
18
4359
0
  return Success;
4360
18
}
4361
4362
3.06k
void ASTReader::InitializeContext() {
4363
3.06k
  assert(ContextObj && "no context to initialize");
4364
3.06k
  ASTContext &Context = *ContextObj;
4365
3.06k
4366
3.06k
  // If there's a listener, notify them that we "read" the translation unit.
4367
3.06k
  if (DeserializationListener)
4368
792
    DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
4369
792
                                      Context.getTranslationUnitDecl());
4370
3.06k
4371
3.06k
  // FIXME: Find a better way to deal with collisions between these
4372
3.06k
  // built-in types. Right now, we just ignore the problem.
4373
3.06k
4374
3.06k
  // Load the special types.
4375
3.06k
  if (
SpecialTypes.size() >= NumSpecialTypeIDs3.06k
) {
4376
3.06k
    if (unsigned 
String3.06k
= SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4377
3.06k
      if (!Context.CFConstantStringTypeDecl)
4378
1.46k
        Context.setCFConstantStringType(GetType(String));
4379
3.06k
    }
4380
3.06k
4381
3.06k
    if (unsigned 
File3.06k
= SpecialTypes[SPECIAL_TYPE_FILE]) {
4382
188
      QualType FileType = GetType(File);
4383
188
      if (
FileType.isNull()188
) {
4384
0
        Error("FILE type is NULL");
4385
0
        return;
4386
0
      }
4387
188
4388
188
      
if (188
!Context.FILEDecl188
) {
4389
161
        if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
4390
161
          Context.setFILEDecl(Typedef->getDecl());
4391
0
        else {
4392
0
          const TagType *Tag = FileType->getAs<TagType>();
4393
0
          if (
!Tag0
) {
4394
0
            Error("Invalid FILE type in AST file");
4395
0
            return;
4396
0
          }
4397
0
          Context.setFILEDecl(Tag->getDecl());
4398
0
        }
4399
161
      }
4400
188
    }
4401
3.06k
4402
3.06k
    
if (unsigned 3.06k
Jmp_buf3.06k
= SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4403
1
      QualType Jmp_bufType = GetType(Jmp_buf);
4404
1
      if (
Jmp_bufType.isNull()1
) {
4405
0
        Error("jmp_buf type is NULL");
4406
0
        return;
4407
0
      }
4408
1
4409
1
      
if (1
!Context.jmp_bufDecl1
) {
4410
1
        if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4411
1
          Context.setjmp_bufDecl(Typedef->getDecl());
4412
0
        else {
4413
0
          const TagType *Tag = Jmp_bufType->getAs<TagType>();
4414
0
          if (
!Tag0
) {
4415
0
            Error("Invalid jmp_buf type in AST file");
4416
0
            return;
4417
0
          }
4418
0
          Context.setjmp_bufDecl(Tag->getDecl());
4419
0
        }
4420
1
      }
4421
1
    }
4422
3.06k
4423
3.06k
    
if (unsigned 3.06k
Sigjmp_buf3.06k
= SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4424
1
      QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4425
1
      if (
Sigjmp_bufType.isNull()1
) {
4426
0
        Error("sigjmp_buf type is NULL");
4427
0
        return;
4428
0
      }
4429
1
4430
1
      
if (1
!Context.sigjmp_bufDecl1
) {
4431
1
        if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4432
1
          Context.setsigjmp_bufDecl(Typedef->getDecl());
4433
0
        else {
4434
0
          const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4435
0
          assert(Tag && "Invalid sigjmp_buf type in AST file");
4436
0
          Context.setsigjmp_bufDecl(Tag->getDecl());
4437
0
        }
4438
1
      }
4439
1
    }
4440
3.06k
4441
3.06k
    
if (unsigned 3.06k
ObjCIdRedef3.06k
4442
2
          = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4443
2
      if (Context.ObjCIdRedefinitionType.isNull())
4444
2
        Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4445
2
    }
4446
3.06k
4447
3.06k
    if (unsigned ObjCClassRedef
4448
4
          = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4449
4
      if (Context.ObjCClassRedefinitionType.isNull())
4450
4
        Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4451
4
    }
4452
3.06k
4453
3.06k
    if (unsigned ObjCSelRedef
4454
2
          = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4455
2
      if (Context.ObjCSelRedefinitionType.isNull())
4456
2
        Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4457
2
    }
4458
3.06k
4459
3.06k
    if (unsigned 
Ucontext_t3.06k
= SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4460
1
      QualType Ucontext_tType = GetType(Ucontext_t);
4461
1
      if (
Ucontext_tType.isNull()1
) {
4462
0
        Error("ucontext_t type is NULL");
4463
0
        return;
4464
0
      }
4465
1
4466
1
      
if (1
!Context.ucontext_tDecl1
) {
4467
1
        if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4468
1
          Context.setucontext_tDecl(Typedef->getDecl());
4469
0
        else {
4470
0
          const TagType *Tag = Ucontext_tType->getAs<TagType>();
4471
0
          assert(Tag && "Invalid ucontext_t type in AST file");
4472
0
          Context.setucontext_tDecl(Tag->getDecl());
4473
0
        }
4474
1
      }
4475
1
    }
4476
3.06k
  }
4477
3.06k
4478
3.06k
  ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4479
3.06k
4480
3.06k
  // If there were any CUDA special declarations, deserialize them.
4481
3.06k
  if (
!CUDASpecialDeclRefs.empty()3.06k
) {
4482
1
    assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4483
1
    Context.setcudaConfigureCallDecl(
4484
1
                           cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4485
1
  }
4486
3.06k
4487
3.06k
  // Re-export any modules that were imported by a non-module AST file.
4488
3.06k
  // FIXME: This does not make macro-only imports visible again.
4489
56
  for (auto &Import : ImportedModules) {
4490
56
    if (Module *
Imported56
= getSubmodule(Import.ID)) {
4491
56
      makeModuleVisible(Imported, Module::AllVisible,
4492
56
                        /*ImportLoc=*/Import.ImportLoc);
4493
56
      if (Import.ImportLoc.isValid())
4494
54
        PP.makeModuleVisible(Imported, Import.ImportLoc);
4495
56
      // FIXME: should we tell Sema to make the module visible too?
4496
56
    }
4497
56
  }
4498
3.06k
  ImportedModules.clear();
4499
3.06k
}
4500
4501
1.38k
void ASTReader::finalizeForWriting() {
4502
1.38k
  // Nothing to do for now.
4503
1.38k
}
4504
4505
/// \brief Reads and return the signature record from \p PCH's control block, or
4506
/// else returns 0.
4507
533
static ASTFileSignature readASTFileSignature(StringRef PCH) {
4508
533
  BitstreamCursor Stream(PCH);
4509
533
  if (!startsWithASTFileMagic(Stream))
4510
0
    return ASTFileSignature();
4511
533
4512
533
  // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4513
533
  
if (533
SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID)533
)
4514
0
    return ASTFileSignature();
4515
533
4516
533
  // Scan for SIGNATURE inside the diagnostic options block.
4517
533
  ASTReader::RecordData Record;
4518
533
  while (
true533
) {
4519
533
    llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4520
533
    if (Entry.Kind != llvm::BitstreamEntry::Record)
4521
0
      return ASTFileSignature();
4522
533
4523
533
    Record.clear();
4524
533
    StringRef Blob;
4525
533
    if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4526
533
      return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
4527
533
                (uint32_t)Record[3], (uint32_t)Record[4]}}};
4528
533
  }
4529
533
}
4530
4531
/// \brief Retrieve the name of the original source file name
4532
/// directly from the AST file, without actually loading the AST
4533
/// file.
4534
std::string ASTReader::getOriginalSourceFile(
4535
    const std::string &ASTFileName, FileManager &FileMgr,
4536
1.09k
    const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
4537
1.09k
  // Open the AST file.
4538
1.09k
  auto Buffer = FileMgr.getBufferForFile(ASTFileName);
4539
1.09k
  if (
!Buffer1.09k
) {
4540
0
    Diags.Report(diag::err_fe_unable_to_read_pch_file)
4541
0
        << ASTFileName << Buffer.getError().message();
4542
0
    return std::string();
4543
0
  }
4544
1.09k
4545
1.09k
  // Initialize the stream
4546
1.09k
  BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
4547
1.09k
4548
1.09k
  // Sniff for the signature.
4549
1.09k
  if (
!startsWithASTFileMagic(Stream)1.09k
) {
4550
1
    Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4551
1
    return std::string();
4552
1
  }
4553
1.09k
4554
1.09k
  // Scan for the CONTROL_BLOCK_ID block.
4555
1.09k
  
if (1.09k
SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)1.09k
) {
4556
0
    Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4557
0
    return std::string();
4558
0
  }
4559
1.09k
4560
1.09k
  // Scan for ORIGINAL_FILE inside the control block.
4561
1.09k
  RecordData Record;
4562
2.36k
  while (
true2.36k
) {
4563
2.36k
    llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4564
2.36k
    if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4565
0
      return std::string();
4566
2.36k
4567
2.36k
    
if (2.36k
Entry.Kind != llvm::BitstreamEntry::Record2.36k
) {
4568
0
      Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4569
0
      return std::string();
4570
0
    }
4571
2.36k
4572
2.36k
    Record.clear();
4573
2.36k
    StringRef Blob;
4574
2.36k
    if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4575
1.09k
      return Blob.str();
4576
2.36k
  }
4577
1.09k
}
4578
4579
namespace {
4580
4581
  class SimplePCHValidator : public ASTReaderListener {
4582
    const LangOptions &ExistingLangOpts;
4583
    const TargetOptions &ExistingTargetOpts;
4584
    const PreprocessorOptions &ExistingPPOpts;
4585
    std::string ExistingModuleCachePath;
4586
    FileManager &FileMgr;
4587
4588
  public:
4589
    SimplePCHValidator(const LangOptions &ExistingLangOpts,
4590
                       const TargetOptions &ExistingTargetOpts,
4591
                       const PreprocessorOptions &ExistingPPOpts,
4592
                       StringRef ExistingModuleCachePath,
4593
                       FileManager &FileMgr)
4594
      : ExistingLangOpts(ExistingLangOpts),
4595
        ExistingTargetOpts(ExistingTargetOpts),
4596
        ExistingPPOpts(ExistingPPOpts),
4597
        ExistingModuleCachePath(ExistingModuleCachePath),
4598
        FileMgr(FileMgr)
4599
13
    {
4600
13
    }
4601
4602
    bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4603
12
                             bool AllowCompatibleDifferences) override {
4604
12
      return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4605
12
                                  AllowCompatibleDifferences);
4606
12
    }
4607
4608
    bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4609
12
                           bool AllowCompatibleDifferences) override {
4610
12
      return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4611
12
                                AllowCompatibleDifferences);
4612
12
    }
4613
4614
    bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4615
                                 StringRef SpecificModuleCachePath,
4616
12
                                 bool Complain) override {
4617
12
      return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4618
12
                                      ExistingModuleCachePath,
4619
12
                                      nullptr, ExistingLangOpts);
4620
12
    }
4621
4622
    bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4623
                                 bool Complain,
4624
12
                                 std::string &SuggestedPredefines) override {
4625
12
      return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
4626
12
                                      SuggestedPredefines, ExistingLangOpts);
4627
12
    }
4628
  };
4629
4630
} // end anonymous namespace
4631
4632
bool ASTReader::readASTFileControlBlock(
4633
    StringRef Filename, FileManager &FileMgr,
4634
    const PCHContainerReader &PCHContainerRdr,
4635
    bool FindModuleFileExtensions,
4636
18
    ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
4637
18
  // Open the AST file.
4638
18
  // FIXME: This allows use of the VFS; we do not allow use of the
4639
18
  // VFS when actually loading a module.
4640
18
  auto Buffer = FileMgr.getBufferForFile(Filename);
4641
18
  if (
!Buffer18
) {
4642
0
    return true;
4643
0
  }
4644
18
4645
18
  // Initialize the stream
4646
18
  StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer);
4647
18
  BitstreamCursor Stream(Bytes);
4648
18
4649
18
  // Sniff for the signature.
4650
18
  if (!startsWithASTFileMagic(Stream))
4651
1
    return true;
4652
17
4653
17
  // Scan for the CONTROL_BLOCK_ID block.
4654
17
  
if (17
SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)17
)
4655
0
    return true;
4656
17
4657
17
  bool NeedsInputFiles = Listener.needsInputFileVisitation();
4658
17
  bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
4659
17
  bool NeedsImports = Listener.needsImportVisitation();
4660
17
  BitstreamCursor InputFilesCursor;
4661
17
4662
17
  RecordData Record;
4663
17
  std::string ModuleDir;
4664
17
  bool DoneWithControlBlock = false;
4665
97
  while (
!DoneWithControlBlock97
) {
4666
97
    llvm::BitstreamEntry Entry = Stream.advance();
4667
97
4668
97
    switch (Entry.Kind) {
4669
25
    case llvm::BitstreamEntry::SubBlock: {
4670
25
      switch (Entry.ID) {
4671
17
      case OPTIONS_BLOCK_ID: {
4672
17
        std::string IgnoredSuggestedPredefines;
4673
17
        if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4674
17
                             /*AllowCompatibleConfigurationMismatch*/ false,
4675
17
                             Listener, IgnoredSuggestedPredefines) != Success)
4676
9
          return true;
4677
8
        break;
4678
8
      }
4679
8
4680
8
      case INPUT_FILES_BLOCK_ID:
4681
8
        InputFilesCursor = Stream;
4682
8
        if (Stream.SkipBlock() ||
4683
8
            (NeedsInputFiles &&
4684
0
             ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4685
0
          return true;
4686
8
        break;
4687
8
4688
0
      default:
4689
0
        if (Stream.SkipBlock())
4690
0
          return true;
4691
0
        break;
4692
16
      }
4693
16
4694
16
      continue;
4695
16
    }
4696
16
4697
8
    case llvm::BitstreamEntry::EndBlock:
4698
8
      DoneWithControlBlock = true;
4699
8
      break;
4700
16
4701
0
    case llvm::BitstreamEntry::Error:
4702
0
      return true;
4703
16
4704
64
    case llvm::BitstreamEntry::Record:
4705
64
      break;
4706
72
    }
4707
72
4708
72
    
if (72
DoneWithControlBlock72
)
break8
;
4709
64
4710
64
    Record.clear();
4711
64
    StringRef Blob;
4712
64
    unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4713
64
    switch ((ControlRecordTypes)RecCode) {
4714
17
    case METADATA: {
4715
17
      if (Record[0] != VERSION_MAJOR)
4716
0
        return true;
4717
17
4718
17
      
if (17
Listener.ReadFullVersionInformation(Blob)17
)
4719
0
        return true;
4720
17
4721
17
      break;
4722
17
    }
4723
5
    case MODULE_NAME:
4724
5
      Listener.ReadModuleName(Blob);
4725
5
      break;
4726
5
    case MODULE_DIRECTORY:
4727
5
      ModuleDir = Blob;
4728
5
      break;
4729
5
    case MODULE_MAP_FILE: {
4730
5
      unsigned Idx = 0;
4731
5
      auto Path = ReadString(Record, Idx);
4732
5
      ResolveImportedPath(Path, ModuleDir);
4733
5
      Listener.ReadModuleMapFile(Path);
4734
5
      break;
4735
17
    }
4736
8
    case INPUT_FILE_OFFSETS: {
4737
8
      if (!NeedsInputFiles)
4738
8
        break;
4739
0
4740
0
      unsigned NumInputFiles = Record[0];
4741
0
      unsigned NumUserFiles = Record[1];
4742
0
      const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
4743
0
      for (unsigned I = 0; 
I != NumInputFiles0
;
++I0
) {
4744
0
        // Go find this input file.
4745
0
        bool isSystemFile = I >= NumUserFiles;
4746
0
4747
0
        if (
isSystemFile && 0
!NeedsSystemInputFiles0
)
4748
0
          break; // the rest are system input files
4749
0
4750
0
        BitstreamCursor &Cursor = InputFilesCursor;
4751
0
        SavedStreamPosition SavedPosition(Cursor);
4752
0
        Cursor.JumpToBit(InputFileOffs[I]);
4753
0
4754
0
        unsigned Code = Cursor.ReadCode();
4755
0
        RecordData Record;
4756
0
        StringRef Blob;
4757
0
        bool shouldContinue = false;
4758
0
        switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4759
0
        case INPUT_FILE:
4760
0
          bool Overridden = static_cast<bool>(Record[3]);
4761
0
          std::string Filename = Blob;
4762
0
          ResolveImportedPath(Filename, ModuleDir);
4763
0
          shouldContinue = Listener.visitInputFile(
4764
0
              Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
4765
0
          break;
4766
0
        }
4767
0
        
if (0
!shouldContinue0
)
4768
0
          break;
4769
0
      }
4770
0
      break;
4771
0
    }
4772
0
4773
5
    case IMPORTS: {
4774
5
      if (!NeedsImports)
4775
5
        break;
4776
0
4777
0
      unsigned Idx = 0, N = Record.size();
4778
0
      while (
Idx < N0
) {
4779
0
        // Read information about the AST file.
4780
0
        Idx += 5; // ImportLoc, Size, ModTime, Signature
4781
0
        SkipString(Record, Idx); // Module name; FIXME: pass to listener?
4782
0
        std::string Filename = ReadString(Record, Idx);
4783
0
        ResolveImportedPath(Filename, ModuleDir);
4784
0
        Listener.visitImport(Filename);
4785
0
      }
4786
0
      break;
4787
0
    }
4788
0
4789
19
    default:
4790
19
      // No other validation to perform.
4791
19
      break;
4792
97
    }
4793
97
  }
4794
17
4795
17
  // Look for module file extension blocks, if requested.
4796
8
  
if (8
FindModuleFileExtensions8
) {
4797
5
    BitstreamCursor SavedStream = Stream;
4798
7
    while (
!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)7
) {
4799
2
      bool DoneWithExtensionBlock = false;
4800
8
      while (
!DoneWithExtensionBlock8
) {
4801
6
       llvm::BitstreamEntry Entry = Stream.advance();
4802
6
4803
6
       switch (Entry.Kind) {
4804
0
       case llvm::BitstreamEntry::SubBlock:
4805
0
         if (Stream.SkipBlock())
4806
0
           return true;
4807
0
4808
0
         continue;
4809
0
4810
2
       case llvm::BitstreamEntry::EndBlock:
4811
2
         DoneWithExtensionBlock = true;
4812
2
         continue;
4813
0
4814
0
       case llvm::BitstreamEntry::Error:
4815
0
         return true;
4816
0
4817
4
       case llvm::BitstreamEntry::Record:
4818
4
         break;
4819
4
       }
4820
4
4821
4
       Record.clear();
4822
4
       StringRef Blob;
4823
4
       unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4824
4
       switch (RecCode) {
4825
2
       case EXTENSION_METADATA: {
4826
2
         ModuleFileExtensionMetadata Metadata;
4827
2
         if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4828
0
           return true;
4829
2
4830
2
         Listener.readModuleFileExtension(Metadata);
4831
2
         break;
4832
2
       }
4833
6
       }
4834
6
      }
4835
2
    }
4836
5
    Stream = SavedStream;
4837
5
  }
4838
8
4839
8
  // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4840
8
  
if (8
readUnhashedControlBlockImpl(
4841
8
          nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
4842
8
          /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
4843
8
          ValidateDiagnosticOptions) != Success)
4844
0
    return true;
4845
8
4846
8
  return false;
4847
8
}
4848
4849
bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
4850
                                    const PCHContainerReader &PCHContainerRdr,
4851
                                    const LangOptions &LangOpts,
4852
                                    const TargetOptions &TargetOpts,
4853
                                    const PreprocessorOptions &PPOpts,
4854
13
                                    StringRef ExistingModuleCachePath) {
4855
13
  SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4856
13
                               ExistingModuleCachePath, FileMgr);
4857
13
  return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
4858
13
                                  /*FindModuleFileExtensions=*/false,
4859
13
                                  validator,
4860
13
                                  /*ValidateDiagnosticOptions=*/true);
4861
13
}
4862
4863
ASTReader::ASTReadResult
4864
3.16k
ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
4865
3.16k
  // Enter the submodule block.
4866
3.16k
  if (
F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)3.16k
) {
4867
0
    Error("malformed submodule block record in AST file");
4868
0
    return Failure;
4869
0
  }
4870
3.16k
4871
3.16k
  ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4872
3.16k
  bool First = true;
4873
3.16k
  Module *CurrentModule = nullptr;
4874
3.16k
  RecordData Record;
4875
28.2k
  while (
true28.2k
) {
4876
28.2k
    llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4877
28.2k
4878
28.2k
    switch (Entry.Kind) {
4879
0
    case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4880
0
    case llvm::BitstreamEntry::Error:
4881
0
      Error("malformed block record in AST file");
4882
0
      return Failure;
4883
3.16k
    case llvm::BitstreamEntry::EndBlock:
4884
3.16k
      return Success;
4885
25.1k
    case llvm::BitstreamEntry::Record:
4886
25.1k
      // The interesting case.
4887
25.1k
      break;
4888
25.1k
    }
4889
25.1k
4890
25.1k
    // Read a record.
4891
25.1k
    StringRef Blob;
4892
25.1k
    Record.clear();
4893
25.1k
    auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4894
25.1k
4895
25.1k
    if (
(Kind == SUBMODULE_METADATA) != First25.1k
) {
4896
0
      Error("submodule metadata record should be at beginning of block");
4897
0
      return Failure;
4898
0
    }
4899
25.1k
    First = false;
4900
25.1k
4901
25.1k
    // Submodule information is only valid if we have a current module.
4902
25.1k
    // FIXME: Should we error on these cases?
4903
25.1k
    if (
!CurrentModule && 25.1k
Kind != SUBMODULE_METADATA6.32k
&&
4904
3.16k
        Kind != SUBMODULE_DEFINITION)
4905
0
      continue;
4906
25.1k
4907
25.1k
    switch (Kind) {
4908
0
    default:  // Default behavior: ignore.
4909
0
      break;
4910
25.1k
4911
6.03k
    case SUBMODULE_DEFINITION: {
4912
6.03k
      if (
Record.size() < 86.03k
) {
4913
0
        Error("malformed module definition");
4914
0
        return Failure;
4915
0
      }
4916
6.03k
4917
6.03k
      StringRef Name = Blob;
4918
6.03k
      unsigned Idx = 0;
4919
6.03k
      SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4920
6.03k
      SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4921
6.03k
      Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++];
4922
6.03k
      bool IsFramework = Record[Idx++];
4923
6.03k
      bool IsExplicit = Record[Idx++];
4924
6.03k
      bool IsSystem = Record[Idx++];
4925
6.03k
      bool IsExternC = Record[Idx++];
4926
6.03k
      bool InferSubmodules = Record[Idx++];
4927
6.03k
      bool InferExplicitSubmodules = Record[Idx++];
4928
6.03k
      bool InferExportWildcard = Record[Idx++];
4929
6.03k
      bool ConfigMacrosExhaustive = Record[Idx++];
4930
6.03k
4931
6.03k
      Module *ParentModule = nullptr;
4932
6.03k
      if (Parent)
4933
2.87k
        ParentModule = getSubmodule(Parent);
4934
6.03k
4935
6.03k
      // Retrieve this (sub)module from the module map, creating it if
4936
6.03k
      // necessary.
4937
6.03k
      CurrentModule =
4938
6.03k
          ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
4939
6.03k
              .first;
4940
6.03k
4941
6.03k
      // FIXME: set the definition loc for CurrentModule, or call
4942
6.03k
      // ModMap.setInferredModuleAllowedBy()
4943
6.03k
4944
6.03k
      SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4945
6.03k
      if (GlobalIndex >= SubmodulesLoaded.size() ||
4946
6.03k
          
SubmodulesLoaded[GlobalIndex]6.03k
) {
4947
0
        Error("too many submodules");
4948
0
        return Failure;
4949
0
      }
4950
6.03k
4951
6.03k
      
if (6.03k
!ParentModule6.03k
) {
4952
3.16k
        if (const FileEntry *
CurFile3.16k
= CurrentModule->getASTFile()) {
4953
4
          if (
CurFile != F.File4
) {
4954
4
            if (
!Diags.isDiagnosticInFlight()4
) {
4955
4
              Diag(diag::err_module_file_conflict)
4956
4
                << CurrentModule->getTopLevelModuleName()
4957
4
                << CurFile->getName()
4958
4
                << F.File->getName();
4959
4
            }
4960
4
            return Failure;
4961
4
          }
4962
3.16k
        }
4963
3.16k
4964
3.16k
        CurrentModule->setASTFile(F.File);
4965
3.16k
        CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
4966
3.16k
      }
4967
6.03k
4968
6.03k
      CurrentModule->Kind = Kind;
4969
6.03k
      CurrentModule->Signature = F.Signature;
4970
6.03k
      CurrentModule->IsFromModuleFile = true;
4971
5.49k
      CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
4972
6.03k
      CurrentModule->IsExternC = IsExternC;
4973
6.03k
      CurrentModule->InferSubmodules = InferSubmodules;
4974
6.03k
      CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4975
6.03k
      CurrentModule->InferExportWildcard = InferExportWildcard;
4976
6.03k
      CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
4977
6.03k
      if (DeserializationListener)
4978
2.33k
        DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4979
6.03k
4980
6.03k
      SubmodulesLoaded[GlobalIndex] = CurrentModule;
4981
6.03k
4982
6.03k
      // Clear out data that will be replaced by what is in the module file.
4983
6.03k
      CurrentModule->LinkLibraries.clear();
4984
6.03k
      CurrentModule->ConfigMacros.clear();
4985
6.03k
      CurrentModule->UnresolvedConflicts.clear();
4986
6.03k
      CurrentModule->Conflicts.clear();
4987
6.03k
4988
6.03k
      // The module is available unless it's missing a requirement; relevant
4989
6.03k
      // requirements will be (re-)added by SUBMODULE_REQUIRES records.
4990
6.03k
      // Missing headers that were present when the module was built do not
4991
6.03k
      // make it unavailable -- if we got this far, this must be an explicitly
4992
6.03k
      // imported module file.
4993
6.03k
      CurrentModule->Requirements.clear();
4994
6.03k
      CurrentModule->MissingHeaders.clear();
4995
6.03k
      CurrentModule->IsMissingRequirement =
4996
2.87k
          ParentModule && ParentModule->IsMissingRequirement;
4997
6.03k
      CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
4998
6.03k
      break;
4999
6.03k
    }
5000
6.03k
5001
410
    case SUBMODULE_UMBRELLA_HEADER: {
5002
410
      std::string Filename = Blob;
5003
410
      ResolveImportedPath(F, Filename);
5004
410
      if (auto *
Umbrella410
= PP.getFileManager().getFile(Filename)) {
5005
408
        if (!CurrentModule->getUmbrellaHeader())
5006
30
          ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
5007
378
        else 
if (378
CurrentModule->getUmbrellaHeader().Entry != Umbrella378
) {
5008
0
          if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5009
0
            Error("mismatched umbrella headers in submodule");
5010
378
          return OutOfDate;
5011
378
        }
5012
410
      }
5013
410
      break;
5014
410
    }
5015
410
5016
4.19k
    case SUBMODULE_HEADER:
5017
4.19k
    case SUBMODULE_EXCLUDED_HEADER:
5018
4.19k
    case SUBMODULE_PRIVATE_HEADER:
5019
4.19k
      // We lazily associate headers with their modules via the HeaderInfo table.
5020
4.19k
      // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
5021
4.19k
      // of complete filenames or remove it entirely.
5022
4.19k
      break;
5023
4.19k
5024
166
    case SUBMODULE_TEXTUAL_HEADER:
5025
166
    case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
5026
166
      // FIXME: Textual headers are not marked in the HeaderInfo table. Load
5027
166
      // them here.
5028
166
      break;
5029
166
5030
4.82k
    case SUBMODULE_TOPHEADER: {
5031
4.82k
      CurrentModule->addTopHeaderFilename(Blob);
5032
4.82k
      break;
5033
166
    }
5034
166
5035
17
    case SUBMODULE_UMBRELLA_DIR: {
5036
17
      std::string Dirname = Blob;
5037
17
      ResolveImportedPath(F, Dirname);
5038
17
      if (auto *
Umbrella17
= PP.getFileManager().getDirectory(Dirname)) {
5039
17
        if (!CurrentModule->getUmbrellaDir())
5040
0
          ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
5041
17
        else 
if (17
CurrentModule->getUmbrellaDir().Entry != Umbrella17
) {
5042
0
          if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5043
0
            Error("mismatched umbrella directories in submodule");
5044
17
          return OutOfDate;
5045
17
        }
5046
17
      }
5047
17
      break;
5048
17
    }
5049
17
5050
3.16k
    case SUBMODULE_METADATA: {
5051
3.16k
      F.BaseSubmoduleID = getTotalNumSubmodules();
5052
3.16k
      F.LocalNumSubmodules = Record[0];
5053
3.16k
      unsigned LocalBaseSubmoduleID = Record[1];
5054
3.16k
      if (
F.LocalNumSubmodules > 03.16k
) {
5055
3.16k
        // Introduce the global -> local mapping for submodules within this
5056
3.16k
        // module.
5057
3.16k
        GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
5058
3.16k
5059
3.16k
        // Introduce the local -> global mapping for submodules within this
5060
3.16k
        // module.
5061
3.16k
        F.SubmoduleRemap.insertOrReplace(
5062
3.16k
          std::make_pair(LocalBaseSubmoduleID,
5063
3.16k
                         F.BaseSubmoduleID - LocalBaseSubmoduleID));
5064
3.16k
5065
3.16k
        SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5066
3.16k
      }
5067
3.16k
      break;
5068
17
    }
5069
17
5070
2.03k
    case SUBMODULE_IMPORTS: {
5071
5.14k
      for (unsigned Idx = 0; 
Idx != Record.size()5.14k
;
++Idx3.10k
) {
5072
3.10k
        UnresolvedModuleRef Unresolved;
5073
3.10k
        Unresolved.File = &F;
5074
3.10k
        Unresolved.Mod = CurrentModule;
5075
3.10k
        Unresolved.ID = Record[Idx];
5076
3.10k
        Unresolved.Kind = UnresolvedModuleRef::Import;
5077
3.10k
        Unresolved.IsWildcard = false;
5078
3.10k
        UnresolvedModuleRefs.push_back(Unresolved);
5079
3.10k
      }
5080
2.03k
      break;
5081
17
    }
5082
17
5083
3.31k
    case SUBMODULE_EXPORTS: {
5084
6.66k
      for (unsigned Idx = 0; 
Idx + 1 < Record.size()6.66k
;
Idx += 23.34k
) {
5085
3.34k
        UnresolvedModuleRef Unresolved;
5086
3.34k
        Unresolved.File = &F;
5087
3.34k
        Unresolved.Mod = CurrentModule;
5088
3.34k
        Unresolved.ID = Record[Idx];
5089
3.34k
        Unresolved.Kind = UnresolvedModuleRef::Export;
5090
3.34k
        Unresolved.IsWildcard = Record[Idx + 1];
5091
3.34k
        UnresolvedModuleRefs.push_back(Unresolved);
5092
3.34k
      }
5093
3.31k
5094
3.31k
      // Once we've loaded the set of exports, there's no reason to keep
5095
3.31k
      // the parsed, unresolved exports around.
5096
3.31k
      CurrentModule->UnresolvedExports.clear();
5097
3.31k
      break;
5098
17
    }
5099
449
    case SUBMODULE_REQUIRES: {
5100
449
      CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
5101
449
                                    PP.getTargetInfo());
5102
449
      break;
5103
17
    }
5104
17
5105
178
    case SUBMODULE_LINK_LIBRARY:
5106
178
      CurrentModule->LinkLibraries.push_back(
5107
178
                                         Module::LinkLibrary(Blob, Record[0]));
5108
178
      break;
5109
17
5110
2
    case SUBMODULE_CONFIG_MACRO:
5111
2
      CurrentModule->ConfigMacros.push_back(Blob.str());
5112
2
      break;
5113
17
5114
1
    case SUBMODULE_CONFLICT: {
5115
1
      UnresolvedModuleRef Unresolved;
5116
1
      Unresolved.File = &F;
5117
1
      Unresolved.Mod = CurrentModule;
5118
1
      Unresolved.ID = Record[0];
5119
1
      Unresolved.Kind = UnresolvedModuleRef::Conflict;
5120
1
      Unresolved.IsWildcard = false;
5121
1
      Unresolved.String = Blob;
5122
1
      UnresolvedModuleRefs.push_back(Unresolved);
5123
1
      break;
5124
17
    }
5125
17
5126
316
    case SUBMODULE_INITIALIZERS: {
5127
316
      if (!ContextObj)
5128
0
        break;
5129
316
      SmallVector<uint32_t, 16> Inits;
5130
316
      for (auto &ID : Record)
5131
481
        Inits.push_back(getGlobalDeclID(F, ID));
5132
316
      ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
5133
316
      break;
5134
316
    }
5135
316
5136
0
    case SUBMODULE_EXPORT_AS:
5137
0
      CurrentModule->ExportAsModule = Blob.str();
5138
0
      break;
5139
28.2k
    }
5140
28.2k
  }
5141
3.16k
}
5142
5143
/// \brief Parse the record that corresponds to a LangOptions data
5144
/// structure.
5145
///
5146
/// This routine parses the language options from the AST file and then gives
5147
/// them to the AST listener if one is set.
5148
///
5149
/// \returns true if the listener deems the file unacceptable, false otherwise.
5150
bool ASTReader::ParseLanguageOptions(const RecordData &Record,
5151
                                     bool Complain,
5152
                                     ASTReaderListener &Listener,
5153
3.08k
                                     bool AllowCompatibleDifferences) {
5154
3.08k
  LangOptions LangOpts;
5155
3.08k
  unsigned Idx = 0;
5156
3.08k
#define LANGOPT(Name, Bits, Default, Description) \
5157
447k
  LangOpts.Name = Record[Idx++];
5158
3.08k
#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
5159
30.8k
  LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
5160
3.08k
#include "clang/Basic/LangOptions.def"
5161
3.08k
#define SANITIZER(NAME, ID)                                                    \
5162
132k
  LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
5163
3.08k
#include "clang/Basic/Sanitizers.def"
5164
3.08k
5165
3.11k
  for (unsigned N = Record[Idx++]; 
N3.11k
;
--N25
)
5166
25
    LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
5167
3.08k
5168
3.08k
  ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
5169
3.08k
  VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
5170
3.08k
  LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
5171
3.08k
5172
3.08k
  LangOpts.CurrentModule = ReadString(Record, Idx);
5173
3.08k
5174
3.08k
  // Comment options.
5175
3.08k
  for (unsigned N = Record[Idx++]; 
N3.08k
;
--N2
) {
5176
2
    LangOpts.CommentOpts.BlockCommandNames.push_back(
5177
2
      ReadString(Record, Idx));
5178
2
  }
5179
3.08k
  LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
5180
3.08k
5181
3.08k
  // OpenMP offloading options.
5182
3.29k
  for (unsigned N = Record[Idx++]; 
N3.29k
;
--N205
) {
5183
205
    LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
5184
205
  }
5185
3.08k
5186
3.08k
  LangOpts.OMPHostIRFile = ReadString(Record, Idx);
5187
3.08k
5188
3.08k
  return Listener.ReadLanguageOptions(LangOpts, Complain,
5189
3.08k
                                      AllowCompatibleDifferences);
5190
3.08k
}
5191
5192
bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
5193
                                   ASTReaderListener &Listener,
5194
3.08k
                                   bool AllowCompatibleDifferences) {
5195
3.08k
  unsigned Idx = 0;
5196
3.08k
  TargetOptions TargetOpts;
5197
3.08k
  TargetOpts.Triple = ReadString(Record, Idx);
5198
3.08k
  TargetOpts.CPU = ReadString(Record, Idx);
5199
3.08k
  TargetOpts.ABI = ReadString(Record, Idx);
5200
3.09k
  for (unsigned N = Record[Idx++]; 
N3.09k
;
--N5
) {
5201
5
    TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
5202
5
  }
5203
17.9k
  for (unsigned N = Record[Idx++]; 
N17.9k
;
--N14.8k
) {
5204
14.8k
    TargetOpts.Features.push_back(ReadString(Record, Idx));
5205
14.8k
  }
5206
3.08k
5207
3.08k
  return Listener.ReadTargetOptions(TargetOpts, Complain,
5208
3.08k
                                    AllowCompatibleDifferences);
5209
3.08k
}
5210
5211
bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
5212
2.71k
                                       ASTReaderListener &Listener) {
5213
2.71k
  IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
5214
2.71k
  unsigned Idx = 0;
5215
76.0k
#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
5216
2.71k
#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
5217
8.14k
  DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
5218
2.71k
#include "clang/Basic/DiagnosticOptions.def"
5219
2.71k
5220
3.28k
  for (unsigned N = Record[Idx++]; 
N3.28k
;
--N574
)
5221
574
    DiagOpts->Warnings.push_back(ReadString(Record, Idx));
5222
2.76k
  for (unsigned N = Record[Idx++]; 
N2.76k
;
--N53
)
5223
53
    DiagOpts->Remarks.push_back(ReadString(Record, Idx));
5224
2.71k
5225
2.71k
  return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
5226
2.71k
}
5227
5228
bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
5229
2.69k
                                       ASTReaderListener &Listener) {
5230
2.69k
  FileSystemOptions FSOpts;
5231
2.69k
  unsigned Idx = 0;
5232
2.69k
  FSOpts.WorkingDir = ReadString(Record, Idx);
5233
2.69k
  return Listener.ReadFileSystemOptions(FSOpts, Complain);
5234
2.69k
}
5235
5236
bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
5237
                                         bool Complain,
5238
2.69k
                                         ASTReaderListener &Listener) {
5239
2.69k
  HeaderSearchOptions HSOpts;
5240
2.69k
  unsigned Idx = 0;
5241
2.69k
  HSOpts.Sysroot = ReadString(Record, Idx);
5242
2.69k
5243
2.69k
  // Include entries.
5244
6.55k
  for (unsigned N = Record[Idx++]; 
N6.55k
;
--N3.85k
) {
5245
3.85k
    std::string Path = ReadString(Record, Idx);
5246
3.85k
    frontend::IncludeDirGroup Group
5247
3.85k
      = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
5248
3.85k
    bool IsFramework = Record[Idx++];
5249
3.85k
    bool IgnoreSysRoot = Record[Idx++];
5250
3.85k
    HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
5251
3.85k
                                    IgnoreSysRoot);
5252
3.85k
  }
5253
2.69k
5254
2.69k
  // System header prefixes.
5255
2.69k
  for (unsigned N = Record[Idx++]; 
N2.69k
;
--N0
) {
5256
0
    std::string Prefix = ReadString(Record, Idx);
5257
0
    bool IsSystemHeader = Record[Idx++];
5258
0
    HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
5259
0
  }
5260
2.69k
5261
2.69k
  HSOpts.ResourceDir = ReadString(Record, Idx);
5262
2.69k
  HSOpts.ModuleCachePath = ReadString(Record, Idx);
5263
2.69k
  HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
5264
2.69k
  HSOpts.DisableModuleHash = Record[Idx++];
5265
2.69k
  HSOpts.ImplicitModuleMaps = Record[Idx++];
5266
2.69k
  HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
5267
2.69k
  HSOpts.UseBuiltinIncludes = Record[Idx++];
5268
2.69k
  HSOpts.UseStandardSystemIncludes = Record[Idx++];
5269
2.69k
  HSOpts.UseStandardCXXIncludes = Record[Idx++];
5270
2.69k
  HSOpts.UseLibcxx = Record[Idx++];
5271
2.69k
  std::string SpecificModuleCachePath = ReadString(Record, Idx);
5272
2.69k
5273
2.69k
  return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5274
2.69k
                                          Complain);
5275
2.69k
}
5276
5277
bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5278
                                         bool Complain,
5279
                                         ASTReaderListener &Listener,
5280
2.69k
                                         std::string &SuggestedPredefines) {
5281
2.69k
  PreprocessorOptions PPOpts;
5282
2.69k
  unsigned Idx = 0;
5283
2.69k
5284
2.69k
  // Macro definitions/undefs
5285
4.09k
  for (unsigned N = Record[Idx++]; 
N4.09k
;
--N1.39k
) {
5286
1.39k
    std::string Macro = ReadString(Record, Idx);
5287
1.39k
    bool IsUndef = Record[Idx++];
5288
1.39k
    PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5289
1.39k
  }
5290
2.69k
5291
2.69k
  // Includes
5292
2.70k
  for (unsigned N = Record[Idx++]; 
N2.70k
;
--N3
) {
5293
3
    PPOpts.Includes.push_back(ReadString(Record, Idx));
5294
3
  }
5295
2.69k
5296
2.69k
  // Macro Includes
5297
2.69k
  for (unsigned N = Record[Idx++]; 
N2.69k
;
--N0
) {
5298
0
    PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5299
0
  }
5300
2.69k
5301
2.69k
  PPOpts.UsePredefines = Record[Idx++];
5302
2.69k
  PPOpts.DetailedRecord = Record[Idx++];
5303
2.69k
  PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
5304
2.69k
  PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
5305
2.69k
  PPOpts.ObjCXXARCStandardLibrary =
5306
2.69k
    static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5307
2.69k
  SuggestedPredefines.clear();
5308
2.69k
  return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5309
2.69k
                                          SuggestedPredefines);
5310
2.69k
}
5311
5312
std::pair<ModuleFile *, unsigned>
5313
48.9k
ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5314
48.9k
  GlobalPreprocessedEntityMapType::iterator
5315
48.9k
  I = GlobalPreprocessedEntityMap.find(GlobalIndex);
5316
48.9k
  assert(I != GlobalPreprocessedEntityMap.end() &&
5317
48.9k
         "Corrupted global preprocessed entity map");
5318
48.9k
  ModuleFile *M = I->second;
5319
48.9k
  unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5320
48.9k
  return std::make_pair(M, LocalIndex);
5321
48.9k
}
5322
5323
llvm::iterator_range<PreprocessingRecord::iterator>
5324
8
ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5325
8
  if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5326
8
    return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5327
8
                                             Mod.NumPreprocessedEntities);
5328
0
5329
0
  return llvm::make_range(PreprocessingRecord::iterator(),
5330
0
                          PreprocessingRecord::iterator());
5331
0
}
5332
5333
llvm::iterator_range<ASTReader::ModuleDeclIterator>
5334
10
ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
5335
10
  return llvm::make_range(
5336
10
      ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5337
10
      ModuleDeclIterator(this, &Mod,
5338
10
                         Mod.FileSortedDecls + Mod.NumFileSortedDecls));
5339
10
}
5340
5341
45.4k
PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5342
45.4k
  PreprocessedEntityID PPID = Index+1;
5343
45.4k
  std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5344
45.4k
  ModuleFile &M = *PPInfo.first;
5345
45.4k
  unsigned LocalIndex = PPInfo.second;
5346
45.4k
  const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5347
45.4k
5348
45.4k
  if (
!PP.getPreprocessingRecord()45.4k
) {
5349
0
    Error("no preprocessing record");
5350
0
    return nullptr;
5351
0
  }
5352
45.4k
5353
45.4k
  SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
5354
45.4k
  M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
5355
45.4k
5356
45.4k
  llvm::BitstreamEntry Entry =
5357
45.4k
    M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5358
45.4k
  if (Entry.Kind != llvm::BitstreamEntry::Record)
5359
0
    return nullptr;
5360
45.4k
5361
45.4k
  // Read the record.
5362
45.4k
  SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5363
45.4k
                    TranslateSourceLocation(M, PPOffs.getEnd()));
5364
45.4k
  PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
5365
45.4k
  StringRef Blob;
5366
45.4k
  RecordData Record;
5367
45.4k
  PreprocessorDetailRecordTypes RecType =
5368
45.4k
    (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
5369
45.4k
                                          Entry.ID, Record, &Blob);
5370
45.4k
  switch (RecType) {
5371
15
  case PPD_MACRO_EXPANSION: {
5372
15
    bool isBuiltin = Record[0];
5373
15
    IdentifierInfo *Name = nullptr;
5374
15
    MacroDefinitionRecord *Def = nullptr;
5375
15
    if (isBuiltin)
5376
0
      Name = getLocalIdentifier(M, Record[1]);
5377
15
    else {
5378
15
      PreprocessedEntityID GlobalID =
5379
15
          getGlobalPreprocessedEntityID(M, Record[1]);
5380
15
      Def = cast<MacroDefinitionRecord>(
5381
15
          PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
5382
15
    }
5383
15
5384
15
    MacroExpansion *ME;
5385
15
    if (isBuiltin)
5386
0
      ME = new (PPRec) MacroExpansion(Name, Range);
5387
15
    else
5388
15
      ME = new (PPRec) MacroExpansion(Def, Range);
5389
15
5390
15
    return ME;
5391
45.4k
  }
5392
45.4k
5393
45.3k
  case PPD_MACRO_DEFINITION: {
5394
45.3k
    // Decode the identifier info and then check again; if the macro is
5395
45.3k
    // still defined and associated with the identifier,
5396
45.3k
    IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
5397
45.3k
    MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
5398
45.3k
5399
45.3k
    if (DeserializationListener)
5400
62
      DeserializationListener->MacroDefinitionRead(PPID, MD);
5401
45.3k
5402
45.3k
    return MD;
5403
45.4k
  }
5404
45.4k
5405
63
  case PPD_INCLUSION_DIRECTIVE: {
5406
63
    const char *FullFileNameStart = Blob.data() + Record[0];
5407
63
    StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
5408
63
    const FileEntry *File = nullptr;
5409
63
    if (!FullFileName.empty())
5410
62
      File = PP.getFileManager().getFile(FullFileName);
5411
63
5412
63
    // FIXME: Stable encoding
5413
63
    InclusionDirective::InclusionKind Kind
5414
63
      = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5415
63
    InclusionDirective *ID
5416
63
      = new (PPRec) InclusionDirective(PPRec, Kind,
5417
63
                                       StringRef(Blob.data(), Record[0]),
5418
63
                                       Record[1], Record[3],
5419
63
                                       File,
5420
63
                                       Range);
5421
63
    return ID;
5422
0
  }
5423
0
  }
5424
0
5425
0
  
llvm_unreachable0
("Invalid PreprocessorDetailRecordTypes");
5426
0
}
5427
5428
/// \brief \arg SLocMapI points at a chunk of a module that contains no
5429
/// preprocessed entities or the entities it contains are not the ones we are
5430
/// looking for. Find the next module that contains entities and return the ID
5431
/// of the first entry.
5432
PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5433
459
                       GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5434
459
  ++SLocMapI;
5435
459
  for (GlobalSLocOffsetMapType::const_iterator
5436
459
         EndI = GlobalSLocOffsetMap.end(); 
SLocMapI != EndI459
;
++SLocMapI0
) {
5437
2
    ModuleFile &M = *SLocMapI->second;
5438
2
    if (M.NumPreprocessedEntities)
5439
2
      return M.BasePreprocessedEntityID;
5440
2
  }
5441
459
5442
457
  return getTotalNumPreprocessedEntities();
5443
459
}
5444
5445
namespace {
5446
5447
struct PPEntityComp {
5448
  const ASTReader &Reader;
5449
  ModuleFile &M;
5450
5451
835
  PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
5452
5453
0
  bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5454
0
    SourceLocation LHS = getLoc(L);
5455
0
    SourceLocation RHS = getLoc(R);
5456
0
    return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5457
0
  }
5458
5459
0
  bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5460
0
    SourceLocation LHS = getLoc(L);
5461
0
    return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5462
0
  }
5463
5464
6.59k
  bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5465
6.59k
    SourceLocation RHS = getLoc(R);
5466
6.59k
    return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5467
6.59k
  }
5468
5469
6.59k
  SourceLocation getLoc(const PPEntityOffset &PPE) const {
5470
6.59k
    return Reader.TranslateSourceLocation(M, PPE.getBegin());
5471
6.59k
  }
5472
};
5473
5474
} // end anonymous namespace
5475
5476
PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5477
1.67k
                                                       bool EndsAfter) const {
5478
1.67k
  if (SourceMgr.isLocalSourceLocation(Loc))
5479
0
    return getTotalNumPreprocessedEntities();
5480
1.67k
5481
1.67k
  GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5482
1.67k
      SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
5483
1.67k
  assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5484
1.67k
         "Corrupted global sloc offset map");
5485
1.67k
5486
1.67k
  if (SLocMapI->second->NumPreprocessedEntities == 0)
5487
0
    return findNextPreprocessedEntity(SLocMapI);
5488
1.67k
5489
1.67k
  ModuleFile &M = *SLocMapI->second;
5490
1.67k
  typedef const PPEntityOffset *pp_iterator;
5491
1.67k
  pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5492
1.67k
  pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5493
1.67k
5494
1.67k
  size_t Count = M.NumPreprocessedEntities;
5495
1.67k
  size_t Half;
5496
1.67k
  pp_iterator First = pp_begin;
5497
1.67k
  pp_iterator PPI;
5498
1.67k
5499
1.67k
  if (
EndsAfter1.67k
) {
5500
835
    PPI = std::upper_bound(pp_begin, pp_end, Loc,
5501
835
                           PPEntityComp(*this, M));
5502
1.67k
  } else {
5503
835
    // Do a binary search manually instead of using std::lower_bound because
5504
835
    // The end locations of entities may be unordered (when a macro expansion
5505
835
    // is inside another macro argument), but for this case it is not important
5506
835
    // whether we get the first macro expansion or its containing macro.
5507
7.44k
    while (
Count > 07.44k
) {
5508
6.61k
      Half = Count / 2;
5509
6.61k
      PPI = First;
5510
6.61k
      std::advance(PPI, Half);
5511
6.61k
      if (SourceMgr.isBeforeInTranslationUnit(
5512
6.61k
              TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
5513
6.18k
        First = PPI;
5514
6.18k
        ++First;
5515
6.18k
        Count = Count - Half - 1;
5516
6.18k
      } else
5517
425
        Count = Half;
5518
6.61k
    }
5519
835
  }
5520
1.67k
5521
1.67k
  if (PPI == pp_end)
5522
459
    return findNextPreprocessedEntity(SLocMapI);
5523
1.21k
5524
1.21k
  return M.BasePreprocessedEntityID + (PPI - pp_begin);
5525
1.21k
}
5526
5527
/// \brief Returns a pair of [Begin, End) indices of preallocated
5528
/// preprocessed entities that \arg Range encompasses.
5529
std::pair<unsigned, unsigned>
5530
835
    ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5531
835
  if (Range.isInvalid())
5532
0
    return std::make_pair(0,0);
5533
835
  assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5534
835
5535
835
  PreprocessedEntityID BeginID =
5536
835
      findPreprocessedEntity(Range.getBegin(), false);
5537
835
  PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
5538
835
  return std::make_pair(BeginID, EndID);
5539
835
}
5540
5541
/// \brief Optionally returns true or false if the preallocated preprocessed
5542
/// entity with index \arg Index came from file \arg FID.
5543
Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
5544
3.49k
                                                             FileID FID) {
5545
3.49k
  if (FID.isInvalid())
5546
0
    return false;
5547
3.49k
5548
3.49k
  std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5549
3.49k
  ModuleFile &M = *PPInfo.first;
5550
3.49k
  unsigned LocalIndex = PPInfo.second;
5551
3.49k
  const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5552
3.49k
5553
3.49k
  SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
5554
3.49k
  if (Loc.isInvalid())
5555
0
    return false;
5556
3.49k
5557
3.49k
  
if (3.49k
SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID)3.49k
)
5558
31
    return true;
5559
3.49k
  else
5560
3.45k
    return false;
5561
0
}
5562
5563
namespace {
5564
5565
  /// \brief Visitor used to search for information about a header file.
5566
  class HeaderFileInfoVisitor {
5567
    const FileEntry *FE;
5568
5569
    Optional<HeaderFileInfo> HFI;
5570
5571
  public:
5572
    explicit HeaderFileInfoVisitor(const FileEntry *FE)
5573
23.9k
      : FE(FE) { }
5574
5575
54.4k
    bool operator()(ModuleFile &M) {
5576
54.4k
      HeaderFileInfoLookupTable *Table
5577
54.4k
        = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5578
54.4k
      if (!Table)
5579
256
        return false;
5580
54.1k
5581
54.1k
      // Look in the on-disk hash table for an entry for this file name.
5582
54.1k
      HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
5583
54.1k
      if (Pos == Table->end())
5584
50.7k
        return false;
5585
3.37k
5586
3.37k
      HFI = *Pos;
5587
3.37k
      return true;
5588
3.37k
    }
5589
5590
23.9k
    Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
5591
  };
5592
5593
} // end anonymous namespace
5594
5595
23.9k
HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
5596
23.9k
  HeaderFileInfoVisitor Visitor(FE);
5597
23.9k
  ModuleMgr.visit(Visitor);
5598
23.9k
  if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
5599
3.31k
    return *HFI;
5600
20.6k
5601
20.6k
  return HeaderFileInfo();
5602
20.6k
}
5603
5604
3.06k
void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5605
3.06k
  using DiagState = DiagnosticsEngine::DiagState;
5606
3.06k
  SmallVector<DiagState *, 32> DiagStates;
5607
3.06k
5608
7.08k
  for (ModuleFile &F : ModuleMgr) {
5609
7.08k
    unsigned Idx = 0;
5610
7.08k
    auto &Record = F.PragmaDiagMappings;
5611
7.08k
    if (Record.empty())
5612
2.62k
      continue;
5613
4.46k
5614
4.46k
    DiagStates.clear();
5615
4.46k
5616
4.46k
    auto ReadDiagState =
5617
4.46k
        [&](const DiagState &BasedOn, SourceLocation Loc,
5618
7.19k
            bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
5619
7.19k
      unsigned BackrefID = Record[Idx++];
5620
7.19k
      if (BackrefID != 0)
5621
4.47k
        return DiagStates[BackrefID - 1];
5622
2.72k
5623
2.72k
      // A new DiagState was created here.
5624
2.72k
      Diag.DiagStates.push_back(BasedOn);
5625
2.72k
      DiagState *NewState = &Diag.DiagStates.back();
5626
2.72k
      DiagStates.push_back(NewState);
5627
2.72k
      unsigned Size = Record[Idx++];
5628
2.72k
      assert(Idx + Size * 2 <= Record.size() &&
5629
2.72k
             "Invalid data, not enough diag/map pairs");
5630
43.1k
      while (
Size--43.1k
) {
5631
40.3k
        unsigned DiagID = Record[Idx++];
5632
40.3k
        DiagnosticMapping NewMapping =
5633
40.3k
            DiagnosticMapping::deserialize(Record[Idx++]);
5634
40.3k
        if (
!NewMapping.isPragma() && 40.3k
!IncludeNonPragmaStates14.1k
)
5635
417
          continue;
5636
39.9k
5637
39.9k
        DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
5638
39.9k
5639
39.9k
        // If this mapping was specified as a warning but the severity was
5640
39.9k
        // upgraded due to diagnostic settings, simulate the current diagnostic
5641
39.9k
        // settings (and use a warning).
5642
39.9k
        if (
NewMapping.wasUpgradedFromWarning() && 39.9k
!Mapping.isErrorOrFatal()2
) {
5643
1
          NewMapping.setSeverity(diag::Severity::Warning);
5644
1
          NewMapping.setUpgradedFromWarning(false);
5645
1
        }
5646
40.3k
5647
40.3k
        Mapping = NewMapping;
5648
40.3k
      }
5649
7.19k
      return NewState;
5650
7.19k
    };
5651
4.46k
5652
4.46k
    // Read the first state.
5653
4.46k
    DiagState *FirstState;
5654
4.46k
    if (
F.Kind == MK_ImplicitModule4.46k
) {
5655
1.92k
      // Implicitly-built modules are reused with different diagnostic
5656
1.92k
      // settings.  Use the initial diagnostic state from Diag to simulate this
5657
1.92k
      // compilation's diagnostic settings.
5658
1.92k
      FirstState = Diag.DiagStatesByLoc.FirstDiagState;
5659
1.92k
      DiagStates.push_back(FirstState);
5660
1.92k
5661
1.92k
      // Skip the initial diagnostic state from the serialized module.
5662
1.92k
      assert(Record[1] == 0 &&
5663
1.92k
             "Invalid data, unexpected backref in initial state");
5664
1.92k
      Idx = 3 + Record[2] * 2;
5665
1.92k
      assert(Idx < Record.size() &&
5666
1.92k
             "Invalid data, not enough state change pairs in initial state");
5667
4.46k
    } else 
if (2.53k
F.isModule()2.53k
) {
5668
1.19k
      // For an explicit module, preserve the flags from the module build
5669
1.19k
      // command line (-w, -Weverything, -Werror, ...) along with any explicit
5670
1.19k
      // -Wblah flags.
5671
1.19k
      unsigned Flags = Record[Idx++];
5672
1.19k
      DiagState Initial;
5673
1.19k
      Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
5674
1.19k
      Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
5675
1.19k
      Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
5676
1.19k
      Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
5677
1.19k
      Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
5678
1.19k
      Initial.ExtBehavior = (diag::Severity)Flags;
5679
1.19k
      FirstState = ReadDiagState(Initial, SourceLocation(), true);
5680
1.19k
5681
1.19k
      // Set up the root buffer of the module to start with the initial
5682
1.19k
      // diagnostic state of the module itself, to cover files that contain no
5683
1.19k
      // explicit transitions (for which we did not serialize anything).
5684
1.19k
      Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
5685
1.19k
          .StateTransitions.push_back({FirstState, 0});
5686
2.53k
    } else {
5687
1.34k
      // For prefix ASTs, start with whatever the user configured on the
5688
1.34k
      // command line.
5689
1.34k
      Idx++; // Skip flags.
5690
1.34k
      FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState,
5691
1.34k
                                 SourceLocation(), false);
5692
1.34k
    }
5693
4.46k
5694
4.46k
    // Read the state transitions.
5695
4.46k
    unsigned NumLocations = Record[Idx++];
5696
4.53k
    while (
NumLocations--4.53k
) {
5697
72
      assert(Idx < Record.size() &&
5698
72
             "Invalid data, missing pragma diagnostic states");
5699
72
      SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
5700
72
      auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
5701
72
      assert(IDAndOffset.second == 0 && "not a start location for a FileID");
5702
72
      unsigned Transitions = Record[Idx++];
5703
72
5704
72
      // Note that we don't need to set up Parent/ParentOffset here, because
5705
72
      // we won't be changing the diagnostic state within imported FileIDs
5706
72
      // (other than perhaps appending to the main source file, which has no
5707
72
      // parent).
5708
72
      auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
5709
72
      F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
5710
270
      for (unsigned I = 0; 
I != Transitions270
;
++I198
) {
5711
198
        unsigned Offset = Record[Idx++];
5712
198
        auto *State =
5713
198
            ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
5714
198
        F.StateTransitions.push_back({State, Offset});
5715
198
      }
5716
72
    }
5717
4.46k
5718
4.46k
    // Read the final state.
5719
4.46k
    assert(Idx < Record.size() &&
5720
4.46k
           "Invalid data, missing final pragma diagnostic state");
5721
4.46k
    SourceLocation CurStateLoc =
5722
4.46k
        ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5723
4.46k
    auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
5724
4.46k
5725
4.46k
    if (
!F.isModule()4.46k
) {
5726
1.34k
      Diag.DiagStatesByLoc.CurDiagState = CurState;
5727
1.34k
      Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
5728
1.34k
5729
1.34k
      // Preserve the property that the imaginary root file describes the
5730
1.34k
      // current state.
5731
1.34k
      auto &T = Diag.DiagStatesByLoc.Files[FileID()].StateTransitions;
5732
1.34k
      if (T.empty())
5733
1.20k
        T.push_back({CurState, 0});
5734
1.34k
      else
5735
143
        T[0].State = CurState;
5736
1.34k
    }
5737
7.08k
5738
7.08k
    // Don't try to read these mappings again.
5739
7.08k
    Record.clear();
5740
7.08k
  }
5741
3.06k
}
5742
5743
/// \brief Get the correct cursor and offset for loading a type.
5744
56.8k
ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5745
56.8k
  GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5746
56.8k
  assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5747
56.8k
  ModuleFile *M = I->second;
5748
56.8k
  return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5749
56.8k
}
5750
5751
/// \brief Read and return the type with the given index..
5752
///
5753
/// The index is the type ID, shifted and minus the number of predefs. This
5754
/// routine actually reads the record corresponding to the type at the given
5755
/// location. It is a helper routine for GetType, which deals with reading type
5756
/// IDs.
5757
56.8k
QualType ASTReader::readTypeRecord(unsigned Index) {
5758
56.8k
  assert(ContextObj && "reading type with no AST context");
5759
56.8k
  ASTContext &Context = *ContextObj;
5760
56.8k
  RecordLocation Loc = TypeCursorForIndex(Index);
5761
56.8k
  BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
5762
56.8k
5763
56.8k
  // Keep track of where we are in the stream, then jump back there
5764
56.8k
  // after reading this type.
5765
56.8k
  SavedStreamPosition SavedPosition(DeclsCursor);
5766
56.8k
5767
56.8k
  ReadingKindTracker ReadingKind(Read_Type, *this);
5768
56.8k
5769
56.8k
  // Note that we are loading a type record.
5770
56.8k
  Deserializing AType(this);
5771
56.8k
5772
56.8k
  unsigned Idx = 0;
5773
56.8k
  DeclsCursor.JumpToBit(Loc.Offset);
5774
56.8k
  RecordData Record;
5775
56.8k
  unsigned Code = DeclsCursor.ReadCode();
5776
56.8k
  switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
5777
13
  case TYPE_EXT_QUAL: {
5778
13
    if (
Record.size() != 213
) {
5779
0
      Error("Incorrect encoding of extended qualifier type");
5780
0
      return QualType();
5781
0
    }
5782
13
    QualType Base = readType(*Loc.F, Record, Idx);
5783
13
    Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5784
13
    return Context.getQualifiedType(Base, Quals);
5785
13
  }
5786
13
5787
23
  case TYPE_COMPLEX: {
5788
23
    if (
Record.size() != 123
) {
5789
0
      Error("Incorrect encoding of complex type");
5790
0
      return QualType();
5791
0
    }
5792
23
    QualType ElemType = readType(*Loc.F, Record, Idx);
5793
23
    return Context.getComplexType(ElemType);
5794
23
  }
5795
23
5796
5.72k
  case TYPE_POINTER: {
5797
5.72k
    if (
Record.size() != 15.72k
) {
5798
0
      Error("Incorrect encoding of pointer type");
5799
0
      return QualType();
5800
0
    }
5801
5.72k
    QualType PointeeType = readType(*Loc.F, Record, Idx);
5802
5.72k
    return Context.getPointerType(PointeeType);
5803
5.72k
  }
5804
5.72k
5805
22
  case TYPE_DECAYED: {
5806
22
    if (
Record.size() != 122
) {
5807
0
      Error("Incorrect encoding of decayed type");
5808
0
      return QualType();
5809
0
    }
5810
22
    QualType OriginalType = readType(*Loc.F, Record, Idx);
5811
22
    QualType DT = Context.getAdjustedParameterType(OriginalType);
5812
22
    if (!isa<DecayedType>(DT))
5813
0
      Error("Decayed type does not decay");
5814
22
    return DT;
5815
22
  }
5816
22
5817
0
  case TYPE_ADJUSTED: {
5818
0
    if (
Record.size() != 20
) {
5819
0
      Error("Incorrect encoding of adjusted type");
5820
0
      return QualType();
5821
0
    }
5822
0
    QualType OriginalTy = readType(*Loc.F, Record, Idx);
5823
0
    QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5824
0
    return Context.getAdjustedType(OriginalTy, AdjustedTy);
5825
0
  }
5826
0
5827
12
  case TYPE_BLOCK_POINTER: {
5828
12
    if (
Record.size() != 112
) {
5829
0
      Error("Incorrect encoding of block pointer type");
5830
0
      return QualType();
5831
0
    }
5832
12
    QualType PointeeType = readType(*Loc.F, Record, Idx);
5833
12
    return Context.getBlockPointerType(PointeeType);
5834
12
  }
5835
12
5836
1.97k
  case TYPE_LVALUE_REFERENCE: {
5837
1.97k
    if (
Record.size() != 21.97k
) {
5838
0
      Error("Incorrect encoding of lvalue reference type");
5839
0
      return QualType();
5840
0
    }
5841
1.97k
    QualType PointeeType = readType(*Loc.F, Record, Idx);
5842
1.97k
    return Context.getLValueReferenceType(PointeeType, Record[1]);
5843
1.97k
  }
5844
1.97k
5845
454
  case TYPE_RVALUE_REFERENCE: {
5846
454
    if (
Record.size() != 1454
) {
5847
0
      Error("Incorrect encoding of rvalue reference type");
5848
0
      return QualType();
5849
0
    }
5850
454
    QualType PointeeType = readType(*Loc.F, Record, Idx);
5851
454
    return Context.getRValueReferenceType(PointeeType);
5852
454
  }
5853
454
5854
30
  case TYPE_MEMBER_POINTER: {
5855
30
    if (
Record.size() != 230
) {
5856
0
      Error("Incorrect encoding of member pointer type");
5857
0
      return QualType();
5858
0
    }
5859
30
    QualType PointeeType = readType(*Loc.F, Record, Idx);
5860
30
    QualType ClassType = readType(*Loc.F, Record, Idx);
5861
30
    if (
PointeeType.isNull() || 30
ClassType.isNull()30
)
5862
0
      return QualType();
5863
30
5864
30
    return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5865
30
  }
5866
30
5867
758
  case TYPE_CONSTANT_ARRAY: {
5868
758
    QualType ElementType = readType(*Loc.F, Record, Idx);
5869
758
    ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5870
758
    unsigned IndexTypeQuals = Record[2];
5871
758
    unsigned Idx = 3;
5872
758
    llvm::APInt Size = ReadAPInt(Record, Idx);
5873
758
    return Context.getConstantArrayType(ElementType, Size,
5874
758
                                         ASM, IndexTypeQuals);
5875
30
  }
5876
30
5877
206
  case TYPE_INCOMPLETE_ARRAY: {
5878
206
    QualType ElementType = readType(*Loc.F, Record, Idx);
5879
206
    ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5880
206
    unsigned IndexTypeQuals = Record[2];
5881
206
    return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5882
30
  }
5883
30
5884
180
  case TYPE_VARIABLE_ARRAY: {
5885
180
    QualType ElementType = readType(*Loc.F, Record, Idx);
5886
180
    ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5887
180
    unsigned IndexTypeQuals = Record[2];
5888
180
    SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5889
180
    SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5890
180
    return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5891
180
                                         ASM, IndexTypeQuals,
5892
180
                                         SourceRange(LBLoc, RBLoc));
5893
30
  }
5894
30
5895
10
  case TYPE_VECTOR: {
5896
10
    if (
Record.size() != 310
) {
5897
0
      Error("incorrect encoding of vector type in AST file");
5898
0
      return QualType();
5899
0
    }
5900
10
5901
10
    QualType ElementType = readType(*Loc.F, Record, Idx);
5902
10
    unsigned NumElements = Record[1];
5903
10
    unsigned VecKind = Record[2];
5904
10
    return Context.getVectorType(ElementType, NumElements,
5905
10
                                  (VectorType::VectorKind)VecKind);
5906
10
  }
5907
10
5908
254
  case TYPE_EXT_VECTOR: {
5909
254
    if (
Record.size() != 3254
) {
5910
0
      Error("incorrect encoding of extended vector type in AST file");
5911
0
      return QualType();
5912
0
    }
5913
254
5914
254
    QualType ElementType = readType(*Loc.F, Record, Idx);
5915
254
    unsigned NumElements = Record[1];
5916
254
    return Context.getExtVectorType(ElementType, NumElements);
5917
254
  }
5918
254
5919
83
  case TYPE_FUNCTION_NO_PROTO: {
5920
83
    if (
Record.size() != 783
) {
5921
0
      Error("incorrect encoding of no-proto function type");
5922
0
      return QualType();
5923
0
    }
5924
83
    QualType ResultType = readType(*Loc.F, Record, Idx);
5925
83
    FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5926
83
                               (CallingConv)Record[4], Record[5], Record[6]);
5927
83
    return Context.getFunctionNoProtoType(ResultType, Info);
5928
83
  }
5929
83
5930
7.74k
  case TYPE_FUNCTION_PROTO: {
5931
7.74k
    QualType ResultType = readType(*Loc.F, Record, Idx);
5932
7.74k
5933
7.74k
    FunctionProtoType::ExtProtoInfo EPI;
5934
7.74k
    EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5935
7.74k
                                        /*hasregparm*/ Record[2],
5936
7.74k
                                        /*regparm*/ Record[3],
5937
7.74k
                                        static_cast<CallingConv>(Record[4]),
5938
7.74k
                                        /*produces*/ Record[5],
5939
7.74k
                                        /*nocallersavedregs*/ Record[6]);
5940
7.74k
5941
7.74k
    unsigned Idx = 7;
5942
7.74k
5943
7.74k
    EPI.Variadic = Record[Idx++];
5944
7.74k
    EPI.HasTrailingReturn = Record[Idx++];
5945
7.74k
    EPI.TypeQuals = Record[Idx++];
5946
7.74k
    EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
5947
7.74k
    SmallVector<QualType, 8> ExceptionStorage;
5948
7.74k
    readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
5949
7.74k
5950
7.74k
    unsigned NumParams = Record[Idx++];
5951
7.74k
    SmallVector<QualType, 16> ParamTypes;
5952
14.8k
    for (unsigned I = 0; 
I != NumParams14.8k
;
++I7.10k
)
5953
7.10k
      ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5954
7.74k
5955
7.74k
    SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
5956
7.74k
    if (
Idx != Record.size()7.74k
) {
5957
2
      for (unsigned I = 0; 
I != NumParams2
;
++I1
)
5958
1
        ExtParameterInfos.push_back(
5959
1
          FunctionProtoType::ExtParameterInfo
5960
1
                           ::getFromOpaqueValue(Record[Idx++]));
5961
1
      EPI.ExtParameterInfos = ExtParameterInfos.data();
5962
1
    }
5963
7.74k
5964
7.74k
    assert(Idx == Record.size());
5965
7.74k
5966
7.74k
    return Context.getFunctionType(ResultType, ParamTypes, EPI);
5967
83
  }
5968
83
5969
0
  case TYPE_UNRESOLVED_USING: {
5970
0
    unsigned Idx = 0;
5971
0
    return Context.getTypeDeclType(
5972
0
                  ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5973
83
  }
5974
83
5975
10.9k
  case TYPE_TYPEDEF: {
5976
10.9k
    if (
Record.size() != 210.9k
) {
5977
0
      Error("incorrect encoding of typedef type");
5978
0
      return QualType();
5979
0
    }
5980
10.9k
    unsigned Idx = 0;
5981
10.9k
    TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5982
10.9k
    QualType Canonical = readType(*Loc.F, Record, Idx);
5983
10.9k
    if (!Canonical.isNull())
5984
10.9k
      Canonical = Context.getCanonicalType(Canonical);
5985
10.9k
    return Context.getTypedefType(Decl, Canonical);
5986
10.9k
  }
5987
10.9k
5988
43
  case TYPE_TYPEOF_EXPR:
5989
43
    return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5990
10.9k
5991
4
  case TYPE_TYPEOF: {
5992
4
    if (
Record.size() != 14
) {
5993
0
      Error("incorrect encoding of typeof(type) in AST file");
5994
0
      return QualType();
5995
0
    }
5996
4
    QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5997
4
    return Context.getTypeOfType(UnderlyingType);
5998
4
  }
5999
4
6000
148
  case TYPE_DECLTYPE: {
6001
148
    QualType UnderlyingType = readType(*Loc.F, Record, Idx);
6002
148
    return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
6003
4
  }
6004
4
6005
1
  case TYPE_UNARY_TRANSFORM: {
6006
1
    QualType BaseType = readType(*Loc.F, Record, Idx);
6007
1
    QualType UnderlyingType = readType(*Loc.F, Record, Idx);
6008
1
    UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
6009
1
    return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
6010
4
  }
6011
4
6012
90
  case TYPE_AUTO: {
6013
90
    QualType Deduced = readType(*Loc.F, Record, Idx);
6014
90
    AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
6015
90
    bool IsDependent = Deduced.isNull() ? 
Record[Idx++]23
:
false67
;
6016
90
    return Context.getAutoType(Deduced, Keyword, IsDependent);
6017
4
  }
6018
4
6019
0
  case TYPE_DEDUCED_TEMPLATE_SPECIALIZATION: {
6020
0
    TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6021
0
    QualType Deduced = readType(*Loc.F, Record, Idx);
6022
0
    bool IsDependent = Deduced.isNull() ? 
Record[Idx++]0
:
false0
;
6023
0
    return Context.getDeducedTemplateSpecializationType(Name, Deduced,
6024
0
                                                        IsDependent);
6025
4
  }
6026
4
6027
14.1k
  case TYPE_RECORD: {
6028
14.1k
    if (
Record.size() != 214.1k
) {
6029
0
      Error("incorrect encoding of record type");
6030
0
      return QualType();
6031
0
    }
6032
14.1k
    unsigned Idx = 0;
6033
14.1k
    bool IsDependent = Record[Idx++];
6034
14.1k
    RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
6035
14.1k
    RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
6036
14.1k
    QualType T = Context.getRecordType(RD);
6037
14.1k
    const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6038
14.1k
    return T;
6039
14.1k
  }
6040
14.1k
6041
322
  case TYPE_ENUM: {
6042
322
    if (
Record.size() != 2322
) {
6043
0
      Error("incorrect encoding of enum type");
6044
0
      return QualType();
6045
0
    }
6046
322
    unsigned Idx = 0;
6047
322
    bool IsDependent = Record[Idx++];
6048
322
    QualType T
6049
322
      = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
6050
322
    const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6051
322
    return T;
6052
322
  }
6053
322
6054
6
  case TYPE_ATTRIBUTED: {
6055
6
    if (
Record.size() != 36
) {
6056
0
      Error("incorrect encoding of attributed type");
6057
0
      return QualType();
6058
0
    }
6059
6
    QualType modifiedType = readType(*Loc.F, Record, Idx);
6060
6
    QualType equivalentType = readType(*Loc.F, Record, Idx);
6061
6
    AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
6062
6
    return Context.getAttributedType(kind, modifiedType, equivalentType);
6063
6
  }
6064
6
6065
58
  case TYPE_PAREN: {
6066
58
    if (
Record.size() != 158
) {
6067
0
      Error("incorrect encoding of paren type");
6068
0
      return QualType();
6069
0
    }
6070
58
    QualType InnerType = readType(*Loc.F, Record, Idx);
6071
58
    return Context.getParenType(InnerType);
6072
58
  }
6073
58
6074
62
  case TYPE_PACK_EXPANSION: {
6075
62
    if (
Record.size() != 262
) {
6076
0
      Error("incorrect encoding of pack expansion type");
6077
0
      return QualType();
6078
0
    }
6079
62
    QualType Pattern = readType(*Loc.F, Record, Idx);
6080
62
    if (Pattern.isNull())
6081
0
      return QualType();
6082
62
    Optional<unsigned> NumExpansions;
6083
62
    if (Record[1])
6084
0
      NumExpansions = Record[1] - 1;
6085
62
    return Context.getPackExpansionType(Pattern, NumExpansions);
6086
62
  }
6087
62
6088
905
  case TYPE_ELABORATED: {
6089
905
    unsigned Idx = 0;
6090
905
    ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
6091
905
    NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
6092
905
    QualType NamedType = readType(*Loc.F, Record, Idx);
6093
905
    return Context.getElaboratedType(Keyword, NNS, NamedType);
6094
62
  }
6095
62
6096
361
  case TYPE_OBJC_INTERFACE: {
6097
361
    unsigned Idx = 0;
6098
361
    ObjCInterfaceDecl *ItfD
6099
361
      = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
6100
361
    return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
6101
62
  }
6102
62
6103
4
  case TYPE_OBJC_TYPE_PARAM: {
6104
4
    unsigned Idx = 0;
6105
4
    ObjCTypeParamDecl *Decl
6106
4
      = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
6107
4
    unsigned NumProtos = Record[Idx++];
6108
4
    SmallVector<ObjCProtocolDecl*, 4> Protos;
6109
4
    for (unsigned I = 0; 
I != NumProtos4
;
++I0
)
6110
0
      Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
6111
4
    return Context.getObjCTypeParamType(Decl, Protos);
6112
62
  }
6113
84
  case TYPE_OBJC_OBJECT: {
6114
84
    unsigned Idx = 0;
6115
84
    QualType Base = readType(*Loc.F, Record, Idx);
6116
84
    unsigned NumTypeArgs = Record[Idx++];
6117
84
    SmallVector<QualType, 4> TypeArgs;
6118
88
    for (unsigned I = 0; 
I != NumTypeArgs88
;
++I4
)
6119
4
      TypeArgs.push_back(readType(*Loc.F, Record, Idx));
6120
84
    unsigned NumProtos = Record[Idx++];
6121
84
    SmallVector<ObjCProtocolDecl*, 4> Protos;
6122
93
    for (unsigned I = 0; 
I != NumProtos93
;
++I9
)
6123
9
      Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
6124
84
    bool IsKindOf = Record[Idx++];
6125
84
    return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
6126
62
  }
6127
62
6128
163
  case TYPE_OBJC_OBJECT_POINTER: {
6129
163
    unsigned Idx = 0;
6130
163
    QualType Pointee = readType(*Loc.F, Record, Idx);
6131
163
    return Context.getObjCObjectPointerType(Pointee);
6132
62
  }
6133
62
6134
674
  case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
6135
674
    unsigned Idx = 0;
6136
674
    QualType Parm = readType(*Loc.F, Record, Idx);
6137
674
    QualType Replacement = readType(*Loc.F, Record, Idx);
6138
674
    return Context.getSubstTemplateTypeParmType(
6139
674
        cast<TemplateTypeParmType>(Parm),
6140
674
        Context.getCanonicalType(Replacement));
6141
62
  }
6142
62
6143
6
  case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
6144
6
    unsigned Idx = 0;
6145
6
    QualType Parm = readType(*Loc.F, Record, Idx);
6146
6
    TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
6147
6
    return Context.getSubstTemplateTypeParmPackType(
6148
6
                                               cast<TemplateTypeParmType>(Parm),
6149
6
                                                     ArgPack);
6150
62
  }
6151
62
6152
753
  case TYPE_INJECTED_CLASS_NAME: {
6153
753
    CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
6154
753
    QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
6155
753
    // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
6156
753
    // for AST reading, too much interdependencies.
6157
753
    const Type *T = nullptr;
6158
904
    for (auto *DI = D; 
DI904
;
DI = DI->getPreviousDecl()151
) {
6159
765
      if (const Type *
Existing765
= DI->getTypeForDecl()) {
6160
614
        T = Existing;
6161
614
        break;
6162
614
      }
6163
765
    }
6164
753
    if (
!T753
) {
6165
139
      T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
6166
278
      for (auto *DI = D; 
DI278
;
DI = DI->getPreviousDecl()139
)
6167
139
        DI->setTypeForDecl(T);
6168
139
    }
6169
753
    return QualType(T, 0);
6170
62
  }
6171
62
6172
3.90k
  case TYPE_TEMPLATE_TYPE_PARM: {
6173
3.90k
    unsigned Idx = 0;
6174
3.90k
    unsigned Depth = Record[Idx++];
6175
3.90k
    unsigned Index = Record[Idx++];
6176
3.90k
    bool Pack = Record[Idx++];
6177
3.90k
    TemplateTypeParmDecl *D
6178
3.90k
      = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
6179
3.90k
    return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
6180
62
  }
6181
62
6182
135
  case TYPE_DEPENDENT_NAME: {
6183
135
    unsigned Idx = 0;
6184
135
    ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
6185
135
    NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
6186
135
    const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
6187
135
    QualType Canon = readType(*Loc.F, Record, Idx);
6188
135
    if (!Canon.isNull())
6189
67
      Canon = Context.getCanonicalType(Canon);
6190
135
    return Context.getDependentNameType(Keyword, NNS, Name, Canon);
6191
62
  }
6192
62
6193
3
  case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
6194
3
    unsigned Idx = 0;
6195
3
    ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
6196
3
    NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
6197
3
    const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
6198
3
    unsigned NumArgs = Record[Idx++];
6199
3
    SmallVector<TemplateArgument, 8> Args;
6200
3
    Args.reserve(NumArgs);
6201
6
    while (NumArgs--)
6202
3
      Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
6203
3
    return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
6204
3
                                                          Args);
6205
62
  }
6206
62
6207
153
  case TYPE_DEPENDENT_SIZED_ARRAY: {
6208
153
    unsigned Idx = 0;
6209
153
6210
153
    // ArrayType
6211
153
    QualType ElementType = readType(*Loc.F, Record, Idx);
6212
153
    ArrayType::ArraySizeModifier ASM
6213
153
      = (ArrayType::ArraySizeModifier)Record[Idx++];
6214
153
    unsigned IndexTypeQuals = Record[Idx++];
6215
153
6216
153
    // DependentSizedArrayType
6217
153
    Expr *NumElts = ReadExpr(*Loc.F);
6218
153
    SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
6219
153
6220
153
    return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
6221
153
                                               IndexTypeQuals, Brackets);
6222
62
  }
6223
62
6224
6.33k
  case TYPE_TEMPLATE_SPECIALIZATION: {
6225
6.33k
    unsigned Idx = 0;
6226
6.33k
    bool IsDependent = Record[Idx++];
6227
6.33k
    TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6228
6.33k
    SmallVector<TemplateArgument, 8> Args;
6229
6.33k
    ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
6230
6.33k
    QualType Underlying = readType(*Loc.F, Record, Idx);
6231
6.33k
    QualType T;
6232
6.33k
    if (Underlying.isNull())
6233
876
      T = Context.getCanonicalTemplateSpecializationType(Name, Args);
6234
6.33k
    else
6235
5.45k
      T = Context.getTemplateSpecializationType(Name, Args, Underlying);
6236
6.33k
    const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6237
6.33k
    return T;
6238
62
  }
6239
62
6240
37
  case TYPE_ATOMIC: {
6241
37
    if (
Record.size() != 137
) {
6242
0
      Error("Incorrect encoding of atomic type");
6243
0
      return QualType();
6244
0
    }
6245
37
    QualType ValueType = readType(*Loc.F, Record, Idx);
6246
37
    return Context.getAtomicType(ValueType);
6247
37
  }
6248
37
6249
2
  case TYPE_PIPE: {
6250
2
    if (
Record.size() != 22
) {
6251
0
      Error("Incorrect encoding of pipe type");
6252
0
      return QualType();
6253
0
    }
6254
2
6255
2
    // Reading the pipe element type.
6256
2
    QualType ElementType = readType(*Loc.F, Record, Idx);
6257
2
    unsigned ReadOnly = Record[1];
6258
2
    return Context.getPipeType(ElementType, ReadOnly);
6259
2
  }
6260
2
6261
1
  case TYPE_DEPENDENT_SIZED_EXT_VECTOR: {
6262
1
    unsigned Idx = 0;
6263
1
6264
1
    // DependentSizedExtVectorType
6265
1
    QualType ElementType = readType(*Loc.F, Record, Idx);
6266
1
    Expr *SizeExpr = ReadExpr(*Loc.F);
6267
1
    SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6268
1
6269
1
    return Context.getDependentSizedExtVectorType(ElementType, SizeExpr,
6270
1
                                                  AttrLoc);
6271
0
  }
6272
0
  }
6273
0
  
llvm_unreachable0
("Invalid TypeCode!");
6274
0
}
6275
6276
void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
6277
                                  SmallVectorImpl<QualType> &Exceptions,
6278
                                  FunctionProtoType::ExceptionSpecInfo &ESI,
6279
7.76k
                                  const RecordData &Record, unsigned &Idx) {
6280
7.76k
  ExceptionSpecificationType EST =
6281
7.76k
      static_cast<ExceptionSpecificationType>(Record[Idx++]);
6282
7.76k
  ESI.Type = EST;
6283
7.76k
  if (
EST == EST_Dynamic7.76k
) {
6284
20
    for (unsigned I = 0, N = Record[Idx++]; 
I != N20
;
++I12
)
6285
12
      Exceptions.push_back(readType(ModuleFile, Record, Idx));
6286
8
    ESI.Exceptions = Exceptions;
6287
7.76k
  } else 
if (7.75k
EST == EST_ComputedNoexcept7.75k
) {
6288
55
    ESI.NoexceptExpr = ReadExpr(ModuleFile);
6289
7.75k
  } else 
if (7.70k
EST == EST_Uninstantiated7.70k
) {
6290
1
    ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
6291
1
    ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
6292
7.70k
  } else 
if (7.70k
EST == EST_Unevaluated7.70k
) {
6293
1.16k
    ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
6294
1.16k
  }
6295
7.76k
}
6296
6297
class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
6298
  ModuleFile *F;
6299
  ASTReader *Reader;
6300
  const ASTReader::RecordData &Record;
6301
  unsigned &Idx;
6302
6303
111k
  SourceLocation ReadSourceLocation() {
6304
111k
    return Reader->ReadSourceLocation(*F, Record, Idx);
6305
111k
  }
6306
6307
21
  TypeSourceInfo *GetTypeSourceInfo() {
6308
21
    return Reader->GetTypeSourceInfo(*F, Record, Idx);
6309
21
  }
6310
6311
1.09k
  NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6312
1.09k
    return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
6313
1.09k
  }
6314
6315
public:
6316
  TypeLocReader(ModuleFile &F, ASTReader &Reader,
6317
                const ASTReader::RecordData &Record, unsigned &Idx)
6318
48.1k
      : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
6319
6320
  // We want compile-time assurance that we've enumerated all of
6321
  // these, so unfortunately we have to declare them first, then
6322
  // define them out-of-line.
6323
#define ABSTRACT_TYPELOC(CLASS, PARENT)
6324
#define TYPELOC(CLASS, PARENT) \
6325
  void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6326
#include "clang/AST/TypeLocNodes.def"
6327
6328
  void VisitFunctionTypeLoc(FunctionTypeLoc);
6329
  void VisitArrayTypeLoc(ArrayTypeLoc);
6330
};
6331
6332
979
void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6333
979
  // nothing to do
6334
979
}
6335
6336
28.4k
void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6337
28.4k
  TL.setBuiltinLoc(ReadSourceLocation());
6338
28.4k
  if (
TL.needsExtraLocalData()28.4k
) {
6339
20.6k
    TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
6340
20.6k
    TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
6341
20.6k
    TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
6342
20.6k
    TL.setModeAttr(Record[Idx++]);
6343
20.6k
  }
6344
28.4k
}
6345
6346
44
void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
6347
44
  TL.setNameLoc(ReadSourceLocation());
6348
44
}
6349
6350
3.13k
void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
6351
3.13k
  TL.setStarLoc(ReadSourceLocation());
6352
3.13k
}
6353
6354
60
void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6355
60
  // nothing to do
6356
60
}
6357
6358
0
void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6359
0
  // nothing to do
6360
0
}
6361
6362
11
void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6363
11
  TL.setCaretLoc(ReadSourceLocation());
6364
11
}
6365
6366
2.46k
void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6367
2.46k
  TL.setAmpLoc(ReadSourceLocation());
6368
2.46k
}
6369
6370
36
void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6371
36
  TL.setAmpAmpLoc(ReadSourceLocation());
6372
36
}
6373
6374
14
void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6375
14
  TL.setStarLoc(ReadSourceLocation());
6376
14
  TL.setClassTInfo(GetTypeSourceInfo());
6377
14
}
6378
6379
1.92k
void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
6380
1.92k
  TL.setLBracketLoc(ReadSourceLocation());
6381
1.92k
  TL.setRBracketLoc(ReadSourceLocation());
6382
1.92k
  if (Record[Idx++])
6383
889
    TL.setSizeExpr(Reader->ReadExpr(*F));
6384
1.92k
  else
6385
1.03k
    TL.setSizeExpr(nullptr);
6386
1.92k
}
6387
6388
1.09k
void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6389
1.09k
  VisitArrayTypeLoc(TL);
6390
1.09k
}
6391
6392
223
void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6393
223
  VisitArrayTypeLoc(TL);
6394
223
}
6395
6396
449
void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6397
449
  VisitArrayTypeLoc(TL);
6398
449
}
6399
6400
void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6401
158
                                            DependentSizedArrayTypeLoc TL) {
6402
158
  VisitArrayTypeLoc(TL);
6403
158
}
6404
6405
void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6406
1
                                        DependentSizedExtVectorTypeLoc TL) {
6407
1
  TL.setNameLoc(ReadSourceLocation());
6408
1
}
6409
6410
10
void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
6411
10
  TL.setNameLoc(ReadSourceLocation());
6412
10
}
6413
6414
174
void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6415
174
  TL.setNameLoc(ReadSourceLocation());
6416
174
}
6417
6418
8.85k
void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
6419
8.85k
  TL.setLocalRangeBegin(ReadSourceLocation());
6420
8.85k
  TL.setLParenLoc(ReadSourceLocation());
6421
8.85k
  TL.setRParenLoc(ReadSourceLocation());
6422
8.85k
  TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx),
6423
8.85k
                                       Reader->ReadSourceLocation(*F, Record, Idx)));
6424
8.85k
  TL.setLocalRangeEnd(ReadSourceLocation());
6425
15.4k
  for (unsigned i = 0, e = TL.getNumParams(); 
i != e15.4k
;
++i6.60k
) {
6426
6.60k
    TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx));
6427
6.60k
  }
6428
8.85k
}
6429
6430
8.73k
void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6431
8.73k
  VisitFunctionTypeLoc(TL);
6432
8.73k
}
6433
6434
117
void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6435
117
  VisitFunctionTypeLoc(TL);
6436
117
}
6437
0
void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
6438
0
  TL.setNameLoc(ReadSourceLocation());
6439
0
}
6440
5.21k
void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
6441
5.21k
  TL.setNameLoc(ReadSourceLocation());
6442
5.21k
}
6443
43
void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6444
43
  TL.setTypeofLoc(ReadSourceLocation());
6445
43
  TL.setLParenLoc(ReadSourceLocation());
6446
43
  TL.setRParenLoc(ReadSourceLocation());
6447
43
}
6448
4
void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6449
4
  TL.setTypeofLoc(ReadSourceLocation());
6450
4
  TL.setLParenLoc(ReadSourceLocation());
6451
4
  TL.setRParenLoc(ReadSourceLocation());
6452
4
  TL.setUnderlyingTInfo(GetTypeSourceInfo());
6453
4
}
6454
133
void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6455
133
  TL.setNameLoc(ReadSourceLocation());
6456
133
}
6457
6458
1
void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6459
1
  TL.setKWLoc(ReadSourceLocation());
6460
1
  TL.setLParenLoc(ReadSourceLocation());
6461
1
  TL.setRParenLoc(ReadSourceLocation());
6462
1
  TL.setUnderlyingTInfo(GetTypeSourceInfo());
6463
1
}
6464
6465
160
void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
6466
160
  TL.setNameLoc(ReadSourceLocation());
6467
160
}
6468
6469
void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6470
0
    DeducedTemplateSpecializationTypeLoc TL) {
6471
0
  TL.setTemplateNameLoc(ReadSourceLocation());
6472
0
}
6473
6474
3.20k
void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
6475
3.20k
  TL.setNameLoc(ReadSourceLocation());
6476
3.20k
}
6477
6478
73
void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
6479
73
  TL.setNameLoc(ReadSourceLocation());
6480
73
}
6481
6482
6
void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6483
6
  TL.setAttrNameLoc(ReadSourceLocation());
6484
6
  if (
TL.hasAttrOperand()6
) {
6485
0
    SourceRange range;
6486
0
    range.setBegin(ReadSourceLocation());
6487
0
    range.setEnd(ReadSourceLocation());
6488
0
    TL.setAttrOperandParensRange(range);
6489
0
  }
6490
6
  if (
TL.hasAttrExprOperand()6
) {
6491
0
    if (Record[Idx++])
6492
0
      TL.setAttrExprOperand(Reader->ReadExpr(*F));
6493
0
    else
6494
0
      TL.setAttrExprOperand(nullptr);
6495
6
  } else 
if (6
TL.hasAttrEnumOperand()6
)
6496
0
    TL.setAttrEnumOperandLoc(ReadSourceLocation());
6497
6
}
6498
6499
3.19k
void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
6500
3.19k
  TL.setNameLoc(ReadSourceLocation());
6501
3.19k
}
6502
6503
void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6504
1.39k
                                            SubstTemplateTypeParmTypeLoc TL) {
6505
1.39k
  TL.setNameLoc(ReadSourceLocation());
6506
1.39k
}
6507
void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6508
0
                                          SubstTemplateTypeParmPackTypeLoc TL) {
6509
0
  TL.setNameLoc(ReadSourceLocation());
6510
0
}
6511
void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6512
5.60k
                                           TemplateSpecializationTypeLoc TL) {
6513
5.60k
  TL.setTemplateKeywordLoc(ReadSourceLocation());
6514
5.60k
  TL.setTemplateNameLoc(ReadSourceLocation());
6515
5.60k
  TL.setLAngleLoc(ReadSourceLocation());
6516
5.60k
  TL.setRAngleLoc(ReadSourceLocation());
6517
11.4k
  for (unsigned i = 0, e = TL.getNumArgs(); 
i != e11.4k
;
++i5.81k
)
6518
5.81k
    TL.setArgLocInfo(
6519
5.81k
        i,
6520
5.81k
        Reader->GetTemplateArgumentLocInfo(
6521
5.81k
            *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx));
6522
5.60k
}
6523
80
void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
6524
80
  TL.setLParenLoc(ReadSourceLocation());
6525
80
  TL.setRParenLoc(ReadSourceLocation());
6526
80
}
6527
6528
1.02k
void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
6529
1.02k
  TL.setElaboratedKeywordLoc(ReadSourceLocation());
6530
1.02k
  TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6531
1.02k
}
6532
6533
229
void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
6534
229
  TL.setNameLoc(ReadSourceLocation());
6535
229
}
6536
6537
70
void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6538
70
  TL.setElaboratedKeywordLoc(ReadSourceLocation());
6539
70
  TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6540
70
  TL.setNameLoc(ReadSourceLocation());
6541
70
}
6542
6543
void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6544
3
       DependentTemplateSpecializationTypeLoc TL) {
6545
3
  TL.setElaboratedKeywordLoc(ReadSourceLocation());
6546
3
  TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6547
3
  TL.setTemplateKeywordLoc(ReadSourceLocation());
6548
3
  TL.setTemplateNameLoc(ReadSourceLocation());
6549
3
  TL.setLAngleLoc(ReadSourceLocation());
6550
3
  TL.setRAngleLoc(ReadSourceLocation());
6551
6
  for (unsigned I = 0, E = TL.getNumArgs(); 
I != E6
;
++I3
)
6552
3
    TL.setArgLocInfo(
6553
3
        I,
6554
3
        Reader->GetTemplateArgumentLocInfo(
6555
3
            *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx));
6556
3
}
6557
6558
56
void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
6559
56
  TL.setEllipsisLoc(ReadSourceLocation());
6560
56
}
6561
6562
125
void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
6563
125
  TL.setNameLoc(ReadSourceLocation());
6564
125
}
6565
6566
0
void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6567
0
  if (
TL.getNumProtocols()0
) {
6568
0
    TL.setProtocolLAngleLoc(ReadSourceLocation());
6569
0
    TL.setProtocolRAngleLoc(ReadSourceLocation());
6570
0
  }
6571
0
  for (unsigned i = 0, e = TL.getNumProtocols(); 
i != e0
;
++i0
)
6572
0
    TL.setProtocolLoc(i, ReadSourceLocation());
6573
0
}
6574
6575
9
void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
6576
9
  TL.setHasBaseTypeAsWritten(Record[Idx++]);
6577
9
  TL.setTypeArgsLAngleLoc(ReadSourceLocation());
6578
9
  TL.setTypeArgsRAngleLoc(ReadSourceLocation());
6579
11
  for (unsigned i = 0, e = TL.getNumTypeArgs(); 
i != e11
;
++i2
)
6580
2
    TL.setTypeArgTInfo(i, GetTypeSourceInfo());
6581
9
  TL.setProtocolLAngleLoc(ReadSourceLocation());
6582
9
  TL.setProtocolRAngleLoc(ReadSourceLocation());
6583
17
  for (unsigned i = 0, e = TL.getNumProtocols(); 
i != e17
;
++i8
)
6584
8
    TL.setProtocolLoc(i, ReadSourceLocation());
6585
9
}
6586
6587
101
void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6588
101
  TL.setStarLoc(ReadSourceLocation());
6589
101
}
6590
6591
58
void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6592
58
  TL.setKWLoc(ReadSourceLocation());
6593
58
  TL.setLParenLoc(ReadSourceLocation());
6594
58
  TL.setRParenLoc(ReadSourceLocation());
6595
58
}
6596
6597
2
void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
6598
2
  TL.setKWLoc(ReadSourceLocation());
6599
2
}
6600
6601
TypeSourceInfo *
6602
ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record,
6603
64.7k
                             unsigned &Idx) {
6604
64.7k
  QualType InfoTy = readType(F, Record, Idx);
6605
64.7k
  if (InfoTy.isNull())
6606
16.5k
    return nullptr;
6607
48.1k
6608
48.1k
  TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
6609
48.1k
  TypeLocReader TLR(F, *this, Record, Idx);
6610
115k
  for (TypeLoc TL = TInfo->getTypeLoc(); 
!TL.isNull()115k
;
TL = TL.getNextTypeLoc()66.9k
)
6611
66.9k
    TLR.Visit(TL);
6612
64.7k
  return TInfo;
6613
64.7k
}
6614
6615
301k
QualType ASTReader::GetType(TypeID ID) {
6616
301k
  assert(ContextObj && "reading type with no AST context");
6617
301k
  ASTContext &Context = *ContextObj;
6618
301k
6619
301k
  unsigned FastQuals = ID & Qualifiers::FastMask;
6620
301k
  unsigned Index = ID >> Qualifiers::FastWidth;
6621
301k
6622
301k
  if (
Index < NUM_PREDEF_TYPE_IDS301k
) {
6623
165k
    QualType T;
6624
165k
    switch ((PredefinedTypeIDs)Index) {
6625
21.8k
    case PREDEF_TYPE_NULL_ID:
6626
21.8k
      return QualType();
6627
6.59k
    case PREDEF_TYPE_VOID_ID:
6628
6.59k
      T = Context.VoidTy;
6629
6.59k
      break;
6630
4.07k
    case PREDEF_TYPE_BOOL_ID:
6631
4.07k
      T = Context.BoolTy;
6632
4.07k
      break;
6633
165k
6634
2.87k
    case PREDEF_TYPE_CHAR_U_ID:
6635
2.87k
    case PREDEF_TYPE_CHAR_S_ID:
6636
2.87k
      // FIXME: Check that the signedness of CharTy is correct!
6637
2.87k
      T = Context.CharTy;
6638
2.87k
      break;
6639
2.87k
6640
258
    case PREDEF_TYPE_UCHAR_ID:
6641
258
      T = Context.UnsignedCharTy;
6642
258
      break;
6643
103
    case PREDEF_TYPE_USHORT_ID:
6644
103
      T = Context.UnsignedShortTy;
6645
103
      break;
6646
3.23k
    case PREDEF_TYPE_UINT_ID:
6647
3.23k
      T = Context.UnsignedIntTy;
6648
3.23k
      break;
6649
2.34k
    case PREDEF_TYPE_ULONG_ID:
6650
2.34k
      T = Context.UnsignedLongTy;
6651
2.34k
      break;
6652
945
    case PREDEF_TYPE_ULONGLONG_ID:
6653
945
      T = Context.UnsignedLongLongTy;
6654
945
      break;
6655
0
    case PREDEF_TYPE_UINT128_ID:
6656
0
      T = Context.UnsignedInt128Ty;
6657
0
      break;
6658
3
    case PREDEF_TYPE_SCHAR_ID:
6659
3
      T = Context.SignedCharTy;
6660
3
      break;
6661
40
    case PREDEF_TYPE_WCHAR_ID:
6662
40
      T = Context.WCharTy;
6663
40
      break;
6664
2.04k
    case PREDEF_TYPE_SHORT_ID:
6665
2.04k
      T = Context.ShortTy;
6666
2.04k
      break;
6667
107k
    case PREDEF_TYPE_INT_ID:
6668
107k
      T = Context.IntTy;
6669
107k
      break;
6670
1.41k
    case PREDEF_TYPE_LONG_ID:
6671
1.41k
      T = Context.LongTy;
6672
1.41k
      break;
6673
1.09k
    case PREDEF_TYPE_LONGLONG_ID:
6674
1.09k
      T = Context.LongLongTy;
6675
1.09k
      break;
6676
0
    case PREDEF_TYPE_INT128_ID:
6677
0
      T = Context.Int128Ty;
6678
0
      break;
6679
12
    case PREDEF_TYPE_HALF_ID:
6680
12
      T = Context.HalfTy;
6681
12
      break;
6682
3.74k
    case PREDEF_TYPE_FLOAT_ID:
6683
3.74k
      T = Context.FloatTy;
6684
3.74k
      break;
6685
3.48k
    case PREDEF_TYPE_DOUBLE_ID:
6686
3.48k
      T = Context.DoubleTy;
6687
3.48k
      break;
6688
301
    case PREDEF_TYPE_LONGDOUBLE_ID:
6689
301
      T = Context.LongDoubleTy;
6690
301
      break;
6691
0
    case PREDEF_TYPE_FLOAT16_ID:
6692
0
      T = Context.Float16Ty;
6693
0
      break;
6694
0
    case PREDEF_TYPE_FLOAT128_ID:
6695
0
      T = Context.Float128Ty;
6696
0
      break;
6697
194
    case PREDEF_TYPE_OVERLOAD_ID:
6698
194
      T = Context.OverloadTy;
6699
194
      break;
6700
299
    case PREDEF_TYPE_BOUND_MEMBER:
6701
299
      T = Context.BoundMemberTy;
6702
299
      break;
6703
80
    case PREDEF_TYPE_PSEUDO_OBJECT:
6704
80
      T = Context.PseudoObjectTy;
6705
80
      break;
6706
2.66k
    case PREDEF_TYPE_DEPENDENT_ID:
6707
2.66k
      T = Context.DependentTy;
6708
2.66k
      break;
6709
0
    case PREDEF_TYPE_UNKNOWN_ANY:
6710
0
      T = Context.UnknownAnyTy;
6711
0
      break;
6712
9
    case PREDEF_TYPE_NULLPTR_ID:
6713
9
      T = Context.NullPtrTy;
6714
9
      break;
6715
4
    case PREDEF_TYPE_CHAR16_ID:
6716
4
      T = Context.Char16Ty;
6717
4
      break;
6718
4
    case PREDEF_TYPE_CHAR32_ID:
6719
4
      T = Context.Char32Ty;
6720
4
      break;
6721
73
    case PREDEF_TYPE_OBJC_ID:
6722
73
      T = Context.ObjCBuiltinIdTy;
6723
73
      break;
6724
5
    case PREDEF_TYPE_OBJC_CLASS:
6725
5
      T = Context.ObjCBuiltinClassTy;
6726
5
      break;
6727
13
    case PREDEF_TYPE_OBJC_SEL:
6728
13
      T = Context.ObjCBuiltinSelTy;
6729
13
      break;
6730
2.87k
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6731
541
    case PREDEF_TYPE_##Id##_ID: \
6732
541
      T = Context.SingletonId; \
6733
541
      break;
6734
13
#include 
"clang/Basic/OpenCLImageTypes.def"13
6735
6
    case PREDEF_TYPE_SAMPLER_ID:
6736
6
      T = Context.OCLSamplerTy;
6737
6
      break;
6738
6
    case PREDEF_TYPE_EVENT_ID:
6739
6
      T = Context.OCLEventTy;
6740
6
      break;
6741
3
    case PREDEF_TYPE_CLK_EVENT_ID:
6742
3
      T = Context.OCLClkEventTy;
6743
3
      break;
6744
3
    case PREDEF_TYPE_QUEUE_ID:
6745
3
      T = Context.OCLQueueTy;
6746
3
      break;
6747
3
    case PREDEF_TYPE_RESERVE_ID_ID:
6748
3
      T = Context.OCLReserveIDTy;
6749
3
      break;
6750
96
    case PREDEF_TYPE_AUTO_DEDUCT:
6751
96
      T = Context.getAutoDeductType();
6752
96
      break;
6753
2.87k
6754
8
    case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6755
8
      T = Context.getAutoRRefDeductType();
6756
8
      break;
6757
2.87k
6758
0
    case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6759
0
      T = Context.ARCUnbridgedCastTy;
6760
0
      break;
6761
2.87k
6762
36
    case PREDEF_TYPE_BUILTIN_FN:
6763
36
      T = Context.BuiltinFnTy;
6764
36
      break;
6765
2.87k
6766
254
    case PREDEF_TYPE_OMP_ARRAY_SECTION:
6767
254
      T = Context.OMPArraySectionTy;
6768
254
      break;
6769
143k
    }
6770
143k
6771
0
    assert(!T.isNull() && "Unknown predefined type");
6772
143k
    return T.withFastQualifiers(FastQuals);
6773
143k
  }
6774
136k
6775
136k
  Index -= NUM_PREDEF_TYPE_IDS;
6776
136k
  assert(Index < TypesLoaded.size() && "Type index out-of-range");
6777
136k
  if (
TypesLoaded[Index].isNull()136k
) {
6778
56.8k
    TypesLoaded[Index] = readTypeRecord(Index);
6779
56.8k
    if (TypesLoaded[Index].isNull())
6780
0
      return QualType();
6781
56.8k
6782
56.8k
    TypesLoaded[Index]->setFromAST();
6783
56.8k
    if (DeserializationListener)
6784
13.7k
      DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6785
13.7k
                                        TypesLoaded[Index]);
6786
56.8k
  }
6787
136k
6788
136k
  return TypesLoaded[Index].withFastQualifiers(FastQuals);
6789
301k
}
6790
6791
277k
QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6792
277k
  return GetType(getGlobalTypeID(F, LocalID));
6793
277k
}
6794
6795
serialization::TypeID
6796
335k
ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6797
335k
  unsigned FastQuals = LocalID & Qualifiers::FastMask;
6798
335k
  unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
6799
335k
6800
335k
  if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6801
195k
    return LocalID;
6802
140k
6803
140k
  
if (140k
!F.ModuleOffsetMap.empty()140k
)
6804
155
    ReadModuleOffsetMap(F);
6805
335k
6806
335k
  ContinuousRangeMap<uint32_t, int, 2>::iterator I
6807
335k
    = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6808
335k
  assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
6809
335k
6810
335k
  unsigned GlobalIndex = LocalIndex + I->second;
6811
335k
  return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6812
335k
}
6813
6814
TemplateArgumentLocInfo
6815
ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6816
                                      TemplateArgument::ArgKind Kind,
6817
                                      const RecordData &Record,
6818
6.34k
                                      unsigned &Index) {
6819
6.34k
  switch (Kind) {
6820
2.96k
  case TemplateArgument::Expression:
6821
2.96k
    return ReadExpr(F);
6822
3.29k
  case TemplateArgument::Type:
6823
3.29k
    return GetTypeSourceInfo(F, Record, Index);
6824
83
  case TemplateArgument::Template: {
6825
83
    NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6826
83
                                                                     Index);
6827
83
    SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6828
83
    return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6829
83
                                   SourceLocation());
6830
6.34k
  }
6831
0
  case TemplateArgument::TemplateExpansion: {
6832
0
    NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6833
0
                                                                     Index);
6834
0
    SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6835
0
    SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6836
0
    return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6837
0
                                   EllipsisLoc);
6838
6.34k
  }
6839
0
  case TemplateArgument::Null:
6840
0
  case TemplateArgument::Integral:
6841
0
  case TemplateArgument::Declaration:
6842
0
  case TemplateArgument::NullPtr:
6843
0
  case TemplateArgument::Pack:
6844
0
    // FIXME: Is this right?
6845
0
    return TemplateArgumentLocInfo();
6846
0
  }
6847
0
  
llvm_unreachable0
("unexpected template argument loc");
6848
0
}
6849
6850
TemplateArgumentLoc
6851
ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6852
643
                                   const RecordData &Record, unsigned &Index) {
6853
643
  TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6854
643
6855
643
  if (
Arg.getKind() == TemplateArgument::Expression643
) {
6856
116
    if (Record[Index++]) // bool InfoHasSameExpr.
6857
116
      return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6858
527
  }
6859
527
  return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6860
527
                                                             Record, Index));
6861
527
}
6862
6863
const ASTTemplateArgumentListInfo*
6864
ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6865
                                           const RecordData &Record,
6866
160
                                           unsigned &Index) {
6867
160
  SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6868
160
  SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6869
160
  unsigned NumArgsAsWritten = Record[Index++];
6870
160
  TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6871
347
  for (unsigned i = 0; 
i != NumArgsAsWritten347
;
++i187
)
6872
187
    TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6873
160
  return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6874
160
}
6875
6876
3.71k
Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6877
3.71k
  return GetDecl(ID);
6878
3.71k
}
6879
6880
39.4k
void ASTReader::CompleteRedeclChain(const Decl *D) {
6881
39.4k
  if (
NumCurrentElementsDeserializing39.4k
) {
6882
3.69k
    // We arrange to not care about the complete redeclaration chain while we're
6883
3.69k
    // deserializing. Just remember that the AST has marked this one as complete
6884
3.69k
    // but that it's not actually complete yet, so we know we still need to
6885
3.69k
    // complete it later.
6886
3.69k
    PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6887
3.69k
    return;
6888
3.69k
  }
6889
35.7k
6890
35.7k
  const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6891
35.7k
6892
35.7k
  // If this is a named declaration, complete it by looking it up
6893
35.7k
  // within its context.
6894
35.7k
  //
6895
35.7k
  // FIXME: Merging a function definition should merge
6896
35.7k
  // all mergeable entities within it.
6897
35.7k
  if (
isa<TranslationUnitDecl>(DC) || 35.7k
isa<NamespaceDecl>(DC)22.0k
||
6898
35.7k
      
isa<CXXRecordDecl>(DC)17.1k
||
isa<EnumDecl>(DC)12.0k
) {
6899
23.6k
    if (DeclarationName 
Name23.6k
= cast<NamedDecl>(D)->getDeclName()) {
6900
22.8k
      if (!getContext().getLangOpts().CPlusPlus &&
6901
22.8k
          
isa<TranslationUnitDecl>(DC)3.71k
) {
6902
3.71k
        // Outside of C++, we don't have a lookup table for the TU, so update
6903
3.71k
        // the identifier instead. (For C++ modules, we don't store decls
6904
3.71k
        // in the serialized identifier table, so we do the lookup in the TU.)
6905
3.71k
        auto *II = Name.getAsIdentifierInfo();
6906
3.71k
        assert(II && "non-identifier name in C?");
6907
3.71k
        if (II->isOutOfDate())
6908
64
          updateOutOfDateIdentifier(*II);
6909
3.71k
      } else
6910
19.1k
        DC->lookup(Name);
6911
23.6k
    } else 
if (795
needsAnonymousDeclarationNumber(cast<NamedDecl>(D))795
) {
6912
128
      // Find all declarations of this kind from the relevant context.
6913
317
      for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6914
317
        auto *DC = cast<DeclContext>(DCDecl);
6915
317
        SmallVector<Decl*, 8> Decls;
6916
317
        FindExternalLexicalDecls(
6917
1.21k
            DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6918
317
      }
6919
795
    }
6920
23.6k
  }
6921
35.7k
6922
35.7k
  if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6923
3.61k
    CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6924
35.7k
  if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6925
65
    VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6926
35.7k
  if (auto *
FD35.7k
= dyn_cast<FunctionDecl>(D)) {
6927
7.55k
    if (auto *Template = FD->getPrimaryTemplate())
6928
761
      Template->LoadLazySpecializations();
6929
7.55k
  }
6930
39.4k
}
6931
6932
CXXCtorInitializer **
6933
435
ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6934
435
  RecordLocation Loc = getLocalBitOffset(Offset);
6935
435
  BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6936
435
  SavedStreamPosition SavedPosition(Cursor);
6937
435
  Cursor.JumpToBit(Loc.Offset);
6938
435
  ReadingKindTracker ReadingKind(Read_Decl, *this);
6939
435
6940
435
  RecordData Record;
6941
435
  unsigned Code = Cursor.ReadCode();
6942
435
  unsigned RecCode = Cursor.readRecord(Code, Record);
6943
435
  if (
RecCode != DECL_CXX_CTOR_INITIALIZERS435
) {
6944
0
    Error("malformed AST file: missing C++ ctor initializers");
6945
0
    return nullptr;
6946
0
  }
6947
435
6948
435
  unsigned Idx = 0;
6949
435
  return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6950
435
}
6951
6952
234
CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6953
234
  assert(ContextObj && "reading base specifiers with no AST context");
6954
234
  ASTContext &Context = *ContextObj;
6955
234
6956
234
  RecordLocation Loc = getLocalBitOffset(Offset);
6957
234
  BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6958
234
  SavedStreamPosition SavedPosition(Cursor);
6959
234
  Cursor.JumpToBit(Loc.Offset);
6960
234
  ReadingKindTracker ReadingKind(Read_Decl, *this);
6961
234
  RecordData Record;
6962
234
  unsigned Code = Cursor.ReadCode();
6963
234
  unsigned RecCode = Cursor.readRecord(Code, Record);
6964
234
  if (
RecCode != DECL_CXX_BASE_SPECIFIERS234
) {
6965
0
    Error("malformed AST file: missing C++ base specifiers");
6966
0
    return nullptr;
6967
0
  }
6968
234
6969
234
  unsigned Idx = 0;
6970
234
  unsigned NumBases = Record[Idx++];
6971
234
  void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6972
234
  CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6973
539
  for (unsigned I = 0; 
I != NumBases539
;
++I305
)
6974
305
    Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6975
234
  return Bases;
6976
234
}
6977
6978
serialization::DeclID
6979
525k
ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6980
525k
  if (LocalID < NUM_PREDEF_DECL_IDS)
6981
199k
    return LocalID;
6982
326k
6983
326k
  
if (326k
!F.ModuleOffsetMap.empty()326k
)
6984
833
    ReadModuleOffsetMap(F);
6985
525k
6986
525k
  ContinuousRangeMap<uint32_t, int, 2>::iterator I
6987
525k
    = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6988
525k
  assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6989
525k
6990
525k
  return LocalID + I->second;
6991
525k
}
6992
6993
bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6994
243
                                   ModuleFile &M) const {
6995
243
  // Predefined decls aren't from any module.
6996
243
  if (ID < NUM_PREDEF_DECL_IDS)
6997
0
    return false;
6998
243
6999
243
  return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
7000
219
         ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
7001
243
}
7002
7003
5.71k
ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
7004
5.71k
  if (!D->isFromASTFile())
7005
1
    return nullptr;
7006
5.71k
  GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
7007
5.71k
  assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7008
5.71k
  return I->second;
7009
5.71k
}
7010
7011
48.7k
SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
7012
48.7k
  if (ID < NUM_PREDEF_DECL_IDS)
7013
0
    return SourceLocation();
7014
48.7k
7015
48.7k
  unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7016
48.7k
7017
48.7k
  if (
Index > DeclsLoaded.size()48.7k
) {
7018
0
    Error("declaration ID out-of-range for AST file");
7019
0
    return SourceLocation();
7020
0
  }
7021
48.7k
7022
48.7k
  
if (Decl *48.7k
D48.7k
= DeclsLoaded[Index])
7023
46.1k
    return D->getLocation();
7024
2.58k
7025
2.58k
  SourceLocation Loc;
7026
2.58k
  DeclCursorForID(ID, Loc);
7027
2.58k
  return Loc;
7028
2.58k
}
7029
7030
118k
static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
7031
118k
  switch (ID) {
7032
81.5k
  case PREDEF_DECL_NULL_ID:
7033
81.5k
    return nullptr;
7034
118k
7035
23.1k
  case PREDEF_DECL_TRANSLATION_UNIT_ID:
7036
23.1k
    return Context.getTranslationUnitDecl();
7037
118k
7038
541
  case PREDEF_DECL_OBJC_ID_ID:
7039
541
    return Context.getObjCIdDecl();
7040
118k
7041
466
  case PREDEF_DECL_OBJC_SEL_ID:
7042
466
    return Context.getObjCSelDecl();
7043
118k
7044
458
  case PREDEF_DECL_OBJC_CLASS_ID:
7045
458
    return Context.getObjCClassDecl();
7046
118k
7047
453
  case PREDEF_DECL_OBJC_PROTOCOL_ID:
7048
453
    return Context.getObjCProtocolDecl();
7049
118k
7050
1.76k
  case PREDEF_DECL_INT_128_ID:
7051
1.76k
    return Context.getInt128Decl();
7052
118k
7053
1.76k
  case PREDEF_DECL_UNSIGNED_INT_128_ID:
7054
1.76k
    return Context.getUInt128Decl();
7055
118k
7056
1
  case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
7057
1
    return Context.getObjCInstanceTypeDecl();
7058
118k
7059
1.91k
  case PREDEF_DECL_BUILTIN_VA_LIST_ID:
7060
1.91k
    return Context.getBuiltinVaListDecl();
7061
118k
7062
37
  case PREDEF_DECL_VA_LIST_TAG:
7063
37
    return Context.getVaListTagDecl();
7064
118k
7065
1.66k
  case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
7066
1.66k
    return Context.getBuiltinMSVaListDecl();
7067
118k
7068
60
  case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
7069
60
    return Context.getExternCContextDecl();
7070
118k
7071
0
  case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
7072
0
    return Context.getMakeIntegerSeqDecl();
7073
118k
7074
3.40k
  case PREDEF_DECL_CF_CONSTANT_STRING_ID:
7075
3.40k
    return Context.getCFConstantStringDecl();
7076
118k
7077
1.46k
  case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
7078
1.46k
    return Context.getCFConstantStringTagDecl();
7079
118k
7080
0
  case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
7081
0
    return Context.getTypePackElementDecl();
7082
0
  }
7083
0
  
llvm_unreachable0
("PredefinedDeclIDs unknown enum value");
7084
0
}
7085
7086
122k
Decl *ASTReader::GetExistingDecl(DeclID ID) {
7087
122k
  assert(ContextObj && "reading decl with no AST context");
7088
122k
  if (
ID < NUM_PREDEF_DECL_IDS122k
) {
7089
118k
    Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
7090
118k
    if (
D118k
) {
7091
37.1k
      // Track that we have merged the declaration with ID \p ID into the
7092
37.1k
      // pre-existing predefined declaration \p D.
7093
37.1k
      auto &Merged = KeyDecls[D->getCanonicalDecl()];
7094
37.1k
      if (Merged.empty())
7095
12.7k
        Merged.push_back(ID);
7096
37.1k
    }
7097
118k
    return D;
7098
118k
  }
7099
3.30k
7100
3.30k
  unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7101
3.30k
7102
3.30k
  if (
Index >= DeclsLoaded.size()3.30k
) {
7103
0
    assert(0 && "declaration ID out-of-range for AST file");
7104
0
    Error("declaration ID out-of-range for AST file");
7105
0
    return nullptr;
7106
0
  }
7107
3.30k
7108
3.30k
  return DeclsLoaded[Index];
7109
3.30k
}
7110
7111
449k
Decl *ASTReader::GetDecl(DeclID ID) {
7112
449k
  if (ID < NUM_PREDEF_DECL_IDS)
7113
116k
    return GetExistingDecl(ID);
7114
333k
7115
333k
  unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7116
333k
7117
333k
  if (
Index >= DeclsLoaded.size()333k
) {
7118
0
    assert(0 && "declaration ID out-of-range for AST file");
7119
0
    Error("declaration ID out-of-range for AST file");
7120
0
    return nullptr;
7121
0
  }
7122
333k
7123
333k
  
if (333k
!DeclsLoaded[Index]333k
) {
7124
75.6k
    ReadDeclRecord(ID);
7125
75.6k
    if (DeserializationListener)
7126
12.6k
      DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7127
75.6k
  }
7128
449k
7129
449k
  return DeclsLoaded[Index];
7130
449k
}
7131
7132
DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
7133
351
                                                  DeclID GlobalID) {
7134
351
  if (GlobalID < NUM_PREDEF_DECL_IDS)
7135
0
    return GlobalID;
7136
351
7137
351
  GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7138
351
  assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7139
351
  ModuleFile *Owner = I->second;
7140
351
7141
351
  llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
7142
351
    = M.GlobalToLocalDeclIDs.find(Owner);
7143
351
  if (Pos == M.GlobalToLocalDeclIDs.end())
7144
52
    return 0;
7145
299
7146
299
  return GlobalID - Owner->BaseDeclID + Pos->second;
7147
299
}
7148
7149
serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
7150
                                            const RecordData &Record,
7151
392k
                                            unsigned &Idx) {
7152
392k
  if (
Idx >= Record.size()392k
) {
7153
0
    Error("Corrupted AST file");
7154
0
    return 0;
7155
0
  }
7156
392k
7157
392k
  return getGlobalDeclID(F, Record[Idx++]);
7158
392k
}
7159
7160
/// \brief Resolve the offset of a statement into a statement.
7161
///
7162
/// This operation will read a new statement from the external
7163
/// source each time it is called, and is meant to be used via a
7164
/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7165
2.73k
Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
7166
2.73k
  // Switch case IDs are per Decl.
7167
2.73k
  ClearSwitchCaseIDs();
7168
2.73k
7169
2.73k
  // Offset here is a global offset across the entire chain.
7170
2.73k
  RecordLocation Loc = getLocalBitOffset(Offset);
7171
2.73k
  Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
7172
2.73k
  assert(NumCurrentElementsDeserializing == 0 &&
7173
2.73k
         "should not be called while already deserializing");
7174
2.73k
  Deserializing D(this);
7175
2.73k
  return ReadStmtFromStream(*Loc.F);
7176
2.73k
}
7177
7178
void ASTReader::FindExternalLexicalDecls(
7179
    const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7180
4.40k
    SmallVectorImpl<Decl *> &Decls) {
7181
4.40k
  bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7182
4.40k
7183
4.23k
  auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
7184
4.23k
    assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7185
22.0k
    for (int I = 0, N = LexicalDecls.size(); 
I != N22.0k
;
I += 217.8k
) {
7186
17.8k
      auto K = (Decl::Kind)+LexicalDecls[I];
7187
17.8k
      if (!IsKindWeWant(K))
7188
4.13k
        continue;
7189
13.6k
7190
13.6k
      auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
7191
13.6k
7192
13.6k
      // Don't add predefined declarations to the lexical context more
7193
13.6k
      // than once.
7194
13.6k
      if (
ID < NUM_PREDEF_DECL_IDS13.6k
) {
7195
1.09k
        if (PredefsVisited[ID])
7196
180
          continue;
7197
912
7198
912
        PredefsVisited[ID] = true;
7199
912
      }
7200
13.6k
7201
13.5k
      
if (Decl *13.5k
D13.5k
= GetLocalDecl(*M, ID)) {
7202
13.5k
        assert(D->getKind() == K && "wrong kind for lexical decl");
7203
13.5k
        if (!DC->isDeclInLexicalTraversal(D))
7204
13.0k
          Decls.push_back(D);
7205
13.5k
      }
7206
17.8k
    }
7207
4.23k
  };
7208
4.40k
7209
4.40k
  if (
isa<TranslationUnitDecl>(DC)4.40k
) {
7210
164
    for (auto Lexical : TULexicalDecls)
7211
191
      Visit(Lexical.first, Lexical.second);
7212
4.40k
  } else {
7213
4.23k
    auto I = LexicalDecls.find(DC);
7214
4.23k
    if (I != LexicalDecls.end())
7215
4.03k
      Visit(I->second.first, I->second.second);
7216
4.23k
  }
7217
4.40k
7218
4.40k
  ++NumLexicalDeclContextsRead;
7219
4.40k
}
7220
7221
namespace {
7222
7223
class DeclIDComp {
7224
  ASTReader &Reader;
7225
  ModuleFile &Mod;
7226
7227
public:
7228
9.15k
  DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7229
7230
0
  bool operator()(LocalDeclID L, LocalDeclID R) const {
7231
0
    SourceLocation LHS = getLocation(L);
7232
0
    SourceLocation RHS = getLocation(R);
7233
0
    return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7234
0
  }
7235
7236
24.3k
  bool operator()(SourceLocation LHS, LocalDeclID R) const {
7237
24.3k
    SourceLocation RHS = getLocation(R);
7238
24.3k
    return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7239
24.3k
  }
7240
7241
24.3k
  bool operator()(LocalDeclID L, SourceLocation RHS) const {
7242
24.3k
    SourceLocation LHS = getLocation(L);
7243
24.3k
    return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7244
24.3k
  }
7245
7246
48.7k
  SourceLocation getLocation(LocalDeclID ID) const {
7247
48.7k
    return Reader.getSourceManager().getFileLoc(
7248
48.7k
            Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7249
48.7k
  }
7250
};
7251
7252
} // end anonymous namespace
7253
7254
void ASTReader::FindFileRegionDecls(FileID File,
7255
                                    unsigned Offset, unsigned Length,
7256
9.16k
                                    SmallVectorImpl<Decl *> &Decls) {
7257
9.16k
  SourceManager &SM = getSourceManager();
7258
9.16k
7259
9.16k
  llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7260
9.16k
  if (I == FileDeclIDs.end())
7261
9
    return;
7262
9.15k
7263
9.15k
  FileDeclsInfo &DInfo = I->second;
7264
9.15k
  if (DInfo.Decls.empty())
7265
0
    return;
7266
9.15k
7267
9.15k
  SourceLocation
7268
9.15k
    BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7269
9.15k
  SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7270
9.15k
7271
9.15k
  DeclIDComp DIDComp(*this, *DInfo.Mod);
7272
9.15k
  ArrayRef<serialization::LocalDeclID>::iterator
7273
9.15k
    BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7274
9.15k
                               BeginLoc, DIDComp);
7275
9.15k
  if (BeginIt != DInfo.Decls.begin())
7276
8.02k
    --BeginIt;
7277
9.15k
7278
9.15k
  // If we are pointing at a top-level decl inside an objc container, we need
7279
9.15k
  // to backtrack until we find it otherwise we will fail to report that the
7280
9.15k
  // region overlaps with an objc container.
7281
9.17k
  while (BeginIt != DInfo.Decls.begin() &&
7282
7.93k
         GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7283
7.93k
             ->isTopLevelDeclInObjCContainer())
7284
23
    --BeginIt;
7285
9.15k
7286
9.15k
  ArrayRef<serialization::LocalDeclID>::iterator
7287
9.15k
    EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7288
9.15k
                             EndLoc, DIDComp);
7289
9.15k
  if (EndIt != DInfo.Decls.end())
7290
1.74k
    ++EndIt;
7291
9.15k
7292
9.15k
  for (ArrayRef<serialization::LocalDeclID>::iterator
7293
19.0k
         DIt = BeginIt; 
DIt != EndIt19.0k
;
++DIt9.89k
)
7294
9.89k
    Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7295
9.16k
}
7296
7297
bool
7298
ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
7299
16.3k
                                          DeclarationName Name) {
7300
16.3k
  assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
7301
16.3k
         "DeclContext has no visible decls in storage");
7302
16.3k
  if (!Name)
7303
0
    return false;
7304
16.3k
7305
16.3k
  auto It = Lookups.find(DC);
7306
16.3k
  if (It == Lookups.end())
7307
0
    return false;
7308
16.3k
7309
16.3k
  Deserializing LookupResults(this);
7310
16.3k
7311
16.3k
  // Load the list of declarations.
7312
16.3k
  SmallVector<NamedDecl *, 64> Decls;
7313
16.0k
  for (DeclID ID : It->second.Table.find(Name)) {
7314
16.0k
    NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7315
16.0k
    if (ND->getDeclName() == Name)
7316
15.9k
      Decls.push_back(ND);
7317
16.0k
  }
7318
16.3k
7319
16.3k
  ++NumVisibleDeclContextsRead;
7320
16.3k
  SetExternalVisibleDeclsForName(DC, Name, Decls);
7321
16.3k
  return !Decls.empty();
7322
16.3k
}
7323
7324
61
void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
7325
61
  if (!DC->hasExternalVisibleStorage())
7326
0
    return;
7327
61
7328
61
  auto It = Lookups.find(DC);
7329
61
  assert(It != Lookups.end() &&
7330
61
         "have external visible storage but no lookup tables");
7331
61
7332
61
  DeclsMap Decls;
7333
61
7334
245
  for (DeclID ID : It->second.Table.findAll()) {
7335
245
    NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7336
245
    Decls[ND->getDeclName()].push_back(ND);
7337
245
  }
7338
61
7339
61
  ++NumVisibleDeclContextsRead;
7340
61
7341
297
  for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); 
I != E297
;
++I236
) {
7342
236
    SetExternalVisibleDeclsForName(DC, I->first, I->second);
7343
236
  }
7344
61
  const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
7345
61
}
7346
7347
const serialization::reader::DeclContextLookupTable *
7348
3.39k
ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
7349
3.39k
  auto I = Lookups.find(Primary);
7350
3.39k
  return I == Lookups.end() ? 
nullptr2.99k
:
&I->second391
;
7351
3.39k
}
7352
7353
/// \brief Under non-PCH compilation the consumer receives the objc methods
7354
/// before receiving the implementation, and codegen depends on this.
7355
/// We simulate this by deserializing and passing to consumer the methods of the
7356
/// implementation before passing the deserialized implementation decl.
7357
static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
7358
8
                                       ASTConsumer *Consumer) {
7359
8
  assert(ImplD && Consumer);
7360
8
7361
8
  for (auto *I : ImplD->methods())
7362
10
    Consumer->HandleInterestingDecl(DeclGroupRef(I));
7363
8
7364
8
  Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
7365
8
}
7366
7367
4.99k
void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
7368
4.99k
  if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
7369
8
    PassObjCImplDeclToConsumer(ImplD, Consumer);
7370
4.99k
  else
7371
4.98k
    Consumer->HandleInterestingDecl(DeclGroupRef(D));
7372
4.99k
}
7373
7374
3.29k
void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7375
3.29k
  this->Consumer = Consumer;
7376
3.29k
7377
3.29k
  if (Consumer)
7378
3.29k
    PassInterestingDeclsToConsumer();
7379
3.29k
7380
3.29k
  if (DeserializationListener)
7381
1.50k
    DeserializationListener->ReaderInitialized(this);
7382
3.29k
}
7383
7384
3
void ASTReader::PrintStats() {
7385
3
  std::fprintf(stderr, "*** AST File Statistics:\n");
7386
3
7387
3
  unsigned NumTypesLoaded
7388
3
    = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
7389
3
                                      QualType());
7390
3
  unsigned NumDeclsLoaded
7391
3
    = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
7392
3
                                      (Decl *)nullptr);
7393
3
  unsigned NumIdentifiersLoaded
7394
3
    = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
7395
3
                                            IdentifiersLoaded.end(),
7396
3
                                            (IdentifierInfo *)nullptr);
7397
3
  unsigned NumMacrosLoaded
7398
3
    = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
7399
3
                                       MacrosLoaded.end(),
7400
3
                                       (MacroInfo *)nullptr);
7401
3
  unsigned NumSelectorsLoaded
7402
3
    = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
7403
3
                                          SelectorsLoaded.end(),
7404
3
                                          Selector());
7405
3
7406
3
  if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7407
3
    std::fprintf(stderr, "  %u/%u source location entries read (%f%%)\n",
7408
3
                 NumSLocEntriesRead, TotalNumSLocEntries,
7409
3
                 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7410
3
  if (!TypesLoaded.empty())
7411
3
    std::fprintf(stderr, "  %u/%u types read (%f%%)\n",
7412
3
                 NumTypesLoaded, (unsigned)TypesLoaded.size(),
7413
3
                 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7414
3
  if (!DeclsLoaded.empty())
7415
3
    std::fprintf(stderr, "  %u/%u declarations read (%f%%)\n",
7416
3
                 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7417
3
                 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7418
3
  if (!IdentifiersLoaded.empty())
7419
3
    std::fprintf(stderr, "  %u/%u identifiers read (%f%%)\n",
7420
3
                 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7421
3
                 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7422
3
  if (!MacrosLoaded.empty())
7423
3
    std::fprintf(stderr, "  %u/%u macros read (%f%%)\n",
7424
3
                 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7425
3
                 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7426
3
  if (!SelectorsLoaded.empty())
7427
1
    std::fprintf(stderr, "  %u/%u selectors read (%f%%)\n",
7428
1
                 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7429
1
                 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7430
3
  if (TotalNumStatements)
7431
1
    std::fprintf(stderr, "  %u/%u statements read (%f%%)\n",
7432
1
                 NumStatementsRead, TotalNumStatements,
7433
1
                 ((float)NumStatementsRead/TotalNumStatements * 100));
7434
3
  if (TotalNumMacros)
7435
3
    std::fprintf(stderr, "  %u/%u macros read (%f%%)\n",
7436
3
                 NumMacrosRead, TotalNumMacros,
7437
3
                 ((float)NumMacrosRead/TotalNumMacros * 100));
7438
3
  if (TotalLexicalDeclContexts)
7439
1
    std::fprintf(stderr, "  %u/%u lexical declcontexts read (%f%%)\n",
7440
1
                 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7441
1
                 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7442
1
                  * 100));
7443
3
  if (TotalVisibleDeclContexts)
7444
1
    std::fprintf(stderr, "  %u/%u visible declcontexts read (%f%%)\n",
7445
1
                 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7446
1
                 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7447
1
                  * 100));
7448
3
  if (
TotalNumMethodPoolEntries3
) {
7449
1
    std::fprintf(stderr, "  %u/%u method pool entries read (%f%%)\n",
7450
1
                 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7451
1
                 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7452
1
                  * 100));
7453
1
  }
7454
3
  if (
NumMethodPoolLookups3
) {
7455
0
    std::fprintf(stderr, "  %u/%u method pool lookups succeeded (%f%%)\n",
7456
0
                 NumMethodPoolHits, NumMethodPoolLookups,
7457
0
                 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
7458
0
  }
7459
3
  if (
NumMethodPoolTableLookups3
) {
7460
0
    std::fprintf(stderr, "  %u/%u method pool table lookups succeeded (%f%%)\n",
7461
0
                 NumMethodPoolTableHits, NumMethodPoolTableLookups,
7462
0
                 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7463
0
                  * 100.0));
7464
0
  }
7465
3
7466
3
  if (
NumIdentifierLookupHits3
) {
7467
3
    std::fprintf(stderr,
7468
3
                 "  %u / %u identifier table lookups succeeded (%f%%)\n",
7469
3
                 NumIdentifierLookupHits, NumIdentifierLookups,
7470
3
                 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
7471
3
  }
7472
3
7473
3
  if (
GlobalIndex3
) {
7474
1
    std::fprintf(stderr, "\n");
7475
1
    GlobalIndex->printStats();
7476
1
  }
7477
3
7478
3
  std::fprintf(stderr, "\n");
7479
3
  dump();
7480
3
  std::fprintf(stderr, "\n");
7481
3
}
7482
7483
template<typename Key, typename ModuleFile, unsigned InitialCapacity>
7484
LLVM_DUMP_METHOD static void
7485
dumpModuleIDMap(StringRef Name,
7486
                const ContinuousRangeMap<Key, ModuleFile *,
7487
27
                                         InitialCapacity> &Map) {
7488
27
  if (Map.begin() == Map.end())
7489
7
    return;
7490
20
7491
20
  typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
7492
20
  llvm::errs() << Name << ":\n";
7493
20
  for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
7494
47
       
I != IEnd47
;
++I27
) {
7495
27
    llvm::errs() << "  " << I->first << " -> " << I->second->FileName
7496
27
      << "\n";
7497
27
  }
7498
27
}
ASTReader.cpp:void dumpModuleIDMap<unsigned long long, clang::serialization::ModuleFile, 4u>(llvm::StringRef, clang::ContinuousRangeMap<unsigned long long, clang::serialization::ModuleFile*, 4u> const&)
Line
Count
Source
7487
3
                                         InitialCapacity> &Map) {
7488
3
  if (Map.begin() == Map.end())
7489
0
    return;
7490
3
7491
3
  typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
7492
3
  llvm::errs() << Name << ":\n";
7493
3
  for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
7494
7
       
I != IEnd7
;
++I4
) {
7495
4
    llvm::errs() << "  " << I->first << " -> " << I->second->FileName
7496
4
      << "\n";
7497
4
  }
7498
3
}
ASTReader.cpp:void dumpModuleIDMap<unsigned int, clang::serialization::ModuleFile, 64u>(llvm::StringRef, clang::ContinuousRangeMap<unsigned int, clang::serialization::ModuleFile*, 64u> const&)
Line
Count
Source
7487
3
                                         InitialCapacity> &Map) {
7488
3
  if (Map.begin() == Map.end())
7489
0
    return;
7490
3
7491
3
  typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
7492
3
  llvm::errs() << Name << ":\n";
7493
3
  for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
7494
7
       
I != IEnd7
;
++I4
) {
7495
4
    llvm::errs() << "  " << I->first << " -> " << I->second->FileName
7496
4
      << "\n";
7497
4
  }
7498
3
}
ASTReader.cpp:void dumpModuleIDMap<unsigned int, clang::serialization::ModuleFile, 4u>(llvm::StringRef, clang::ContinuousRangeMap<unsigned int, clang::serialization::ModuleFile*, 4u> const&)
Line
Count
Source
7487
21
                                         InitialCapacity> &Map) {
7488
21
  if (Map.begin() == Map.end())
7489
7
    return;
7490
14
7491
14
  typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
7492
14
  llvm::errs() << Name << ":\n";
7493
14
  for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
7494
33
       
I != IEnd33
;
++I19
) {
7495
19
    llvm::errs() << "  " << I->first << " -> " << I->second->FileName
7496
19
      << "\n";
7497
19
  }
7498
21
}
7499
7500
3
LLVM_DUMP_METHOD void ASTReader::dump() {
7501
3
  llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7502
3
  dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7503
3
  dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7504
3
  dumpModuleIDMap("Global type map", GlobalTypeMap);
7505
3
  dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7506
3
  dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7507
3
  dumpModuleIDMap("Global macro map", GlobalMacroMap);
7508
3
  dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7509
3
  dumpModuleIDMap("Global selector map", GlobalSelectorMap);
7510
3
  dumpModuleIDMap("Global preprocessed entity map",
7511
3
                  GlobalPreprocessedEntityMap);
7512
3
7513
3
  llvm::errs() << "\n*** PCH/Modules Loaded:";
7514
3
  for (ModuleFile &M : ModuleMgr)
7515
4
    M.dump();
7516
3
}
7517
7518
/// Return the amount of memory used by memory buffers, breaking down
7519
/// by heap-backed versus mmap'ed memory.
7520
0
void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
7521
0
  for (ModuleFile &I : ModuleMgr) {
7522
0
    if (llvm::MemoryBuffer *
buf0
= I.Buffer) {
7523
0
      size_t bytes = buf->getBufferSize();
7524
0
      switch (buf->getBufferKind()) {
7525
0
        case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7526
0
          sizes.malloc_bytes += bytes;
7527
0
          break;
7528
0
        case llvm::MemoryBuffer::MemoryBuffer_MMap:
7529
0
          sizes.mmap_bytes += bytes;
7530
0
          break;
7531
0
      }
7532
0
    }
7533
0
  }
7534
0
}
7535
7536
3.49k
void ASTReader::InitializeSema(Sema &S) {
7537
3.49k
  SemaObj = &S;
7538
3.49k
  S.addExternalSource(this);
7539
3.49k
7540
3.49k
  // Makes sure any declarations that were deserialized "too early"
7541
3.49k
  // still get added to the identifier's declaration chains.
7542
1.29k
  for (uint64_t ID : PreloadedDeclIDs) {
7543
1.29k
    NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7544
1.29k
    pushExternalDeclIntoScope(D, D->getDeclName());
7545
1.29k
  }
7546
3.49k
  PreloadedDeclIDs.clear();
7547
3.49k
7548
3.49k
  // FIXME: What happens if these are changed by a module import?
7549
3.49k
  if (
!FPPragmaOptions.empty()3.49k
) {
7550
1.51k
    assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
7551
1.51k
    SemaObj->FPFeatures = FPOptions(FPPragmaOptions[0]);
7552
1.51k
  }
7553
3.49k
7554
3.49k
  SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
7555
3.49k
  SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
7556
3.49k
  SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
7557
3.49k
7558
3.49k
  UpdateSema();
7559
3.49k
}
7560
7561
4.94k
void ASTReader::UpdateSema() {
7562
4.94k
  assert(SemaObj && "no Sema to update");
7563
4.94k
7564
4.94k
  // Load the offsets of the declarations that Sema references.
7565
4.94k
  // They will be lazily deserialized when needed.
7566
4.94k
  if (
!SemaDeclRefs.empty()4.94k
) {
7567
44
    assert(SemaDeclRefs.size() % 3 == 0);
7568
95
    for (unsigned I = 0; 
I != SemaDeclRefs.size()95
;
I += 351
) {
7569
51
      if (!SemaObj->StdNamespace)
7570
38
        SemaObj->StdNamespace = SemaDeclRefs[I];
7571
51
      if (!SemaObj->StdBadAlloc)
7572
50
        SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
7573
51
      if (!SemaObj->StdAlignValT)
7574
51
        SemaObj->StdAlignValT = SemaDeclRefs[I+2];
7575
51
    }
7576
44
    SemaDeclRefs.clear();
7577
44
  }
7578
4.94k
7579
4.94k
  // Update the state of pragmas. Use the same API as if we had encountered the
7580
4.94k
  // pragma in the source.
7581
4.94k
  if(OptimizeOffPragmaLocation.isValid())
7582
1
    SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
7583
4.94k
  if (PragmaMSStructState != -1)
7584
1.28k
    SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
7585
4.94k
  if (
PointersToMembersPragmaLocation.isValid()4.94k
) {
7586
1
    SemaObj->ActOnPragmaMSPointersToMembers(
7587
1
        (LangOptions::PragmaMSPointersToMembersKind)
7588
1
            PragmaMSPointersToMembersState,
7589
1
        PointersToMembersPragmaLocation);
7590
1
  }
7591
4.94k
  SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
7592
4.94k
7593
4.94k
  if (
PragmaPackCurrentValue4.94k
) {
7594
1.28k
    // The bottom of the stack might have a default value. It must be adjusted
7595
1.28k
    // to the current value to ensure that the packing state is preserved after
7596
1.28k
    // popping entries that were included/imported from a PCH/module.
7597
1.28k
    bool DropFirst = false;
7598
1.28k
    if (!PragmaPackStack.empty() &&
7599
1.28k
        
PragmaPackStack.front().Location.isInvalid()4
) {
7600
3
      assert(PragmaPackStack.front().Value == SemaObj->PackStack.DefaultValue &&
7601
3
             "Expected a default alignment value");
7602
3
      SemaObj->PackStack.Stack.emplace_back(
7603
3
          PragmaPackStack.front().SlotLabel, SemaObj->PackStack.CurrentValue,
7604
3
          SemaObj->PackStack.CurrentPragmaLocation,
7605
3
          PragmaPackStack.front().PushLocation);
7606
3
      DropFirst = true;
7607
3
    }
7608
1.28k
    for (const auto &Entry :
7609
1.28k
         llvm::makeArrayRef(PragmaPackStack).drop_front(DropFirst ? 
13
:
01.28k
))
7610
1
      SemaObj->PackStack.Stack.emplace_back(Entry.SlotLabel, Entry.Value,
7611
1
                                            Entry.Location, Entry.PushLocation);
7612
1.28k
    if (
PragmaPackCurrentLocation.isInvalid()1.28k
) {
7613
1.28k
      assert(*PragmaPackCurrentValue == SemaObj->PackStack.DefaultValue &&
7614
1.28k
             "Expected a default alignment value");
7615
1.28k
      // Keep the current values.
7616
1.28k
    } else {
7617
7
      SemaObj->PackStack.CurrentValue = *PragmaPackCurrentValue;
7618
7
      SemaObj->PackStack.CurrentPragmaLocation = PragmaPackCurrentLocation;
7619
7
    }
7620
1.28k
  }
7621
4.94k
}
7622
7623
492k
IdentifierInfo *ASTReader::get(StringRef Name) {
7624
492k
  // Note that we are loading an identifier.
7625
492k
  Deserializing AnIdentifier(this);
7626
492k
7627
492k
  IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
7628
492k
                                  NumIdentifierLookups,
7629
492k
                                  NumIdentifierLookupHits);
7630
492k
7631
492k
  // We don't need to do identifier table lookups in C++ modules (we preload
7632
492k
  // all interesting declarations, and don't need to use the scope for name
7633
492k
  // lookups). Perform the lookup in PCH files, though, since we don't build
7634
492k
  // a complete initial identifier table if we're carrying on from a PCH.
7635
492k
  if (
PP.getLangOpts().CPlusPlus492k
) {
7636
181k
    for (auto F : ModuleMgr.pch_modules())
7637
106k
      
if (106k
Visitor(*F)106k
)
7638
57.2k
        break;
7639
310k
  } else {
7640
310k
    // If there is a global index, look there first to determine which modules
7641
310k
    // provably do not have any results for this identifier.
7642
310k
    GlobalModuleIndex::HitSet Hits;
7643
310k
    GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7644
310k
    if (
!loadGlobalIndex()310k
) {
7645
115k
      if (
GlobalIndex->lookupIdentifier(Name, Hits)115k
) {
7646
115k
        HitsPtr = &Hits;
7647
115k
      }
7648
115k
    }
7649
310k
7650
310k
    ModuleMgr.visit(Visitor, HitsPtr);
7651
310k
  }
7652
492k
7653
492k
  IdentifierInfo *II = Visitor.getIdentifierInfo();
7654
492k
  markIdentifierUpToDate(II);
7655
492k
  return II;
7656
492k
}
7657
7658
namespace clang {
7659
7660
  /// \brief An identifier-lookup iterator that enumerates all of the
7661
  /// identifiers stored within a set of AST files.
7662
  class ASTIdentifierIterator : public IdentifierIterator {
7663
    /// \brief The AST reader whose identifiers are being enumerated.
7664
    const ASTReader &Reader;
7665
7666
    /// \brief The current index into the chain of AST files stored in
7667
    /// the AST reader.
7668
    unsigned Index;
7669
7670
    /// \brief The current position within the identifier lookup table
7671
    /// of the current AST file.
7672
    ASTIdentifierLookupTable::key_iterator Current;
7673
7674
    /// \brief The end position within the identifier lookup table of
7675
    /// the current AST file.
7676
    ASTIdentifierLookupTable::key_iterator End;
7677
7678
    /// \brief Whether to skip any modules in the ASTReader.
7679
    bool SkipModules;
7680
7681
  public:
7682
    explicit ASTIdentifierIterator(const ASTReader &Reader,
7683
                                   bool SkipModules = false);
7684
7685
    StringRef Next() override;
7686
  };
7687
7688
} // end namespace clang
7689
7690
ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7691
                                             bool SkipModules)
7692
304
    : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
7693
304
}
7694
7695
184k
StringRef ASTIdentifierIterator::Next() {
7696
184k
  while (
Current == End184k
) {
7697
754
    // If we have exhausted all of our AST files, we're done.
7698
754
    if (Index == 0)
7699
304
      return StringRef();
7700
450
7701
450
    --Index;
7702
450
    ModuleFile &F = Reader.ModuleMgr[Index];
7703
450
    if (
SkipModules && 450
F.isModule()35
)
7704
30
      continue;
7705
420
7706
420
    ASTIdentifierLookupTable *IdTable =
7707
420
        (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
7708
420
    Current = IdTable->key_begin();
7709
420
    End = IdTable->key_end();
7710
420
  }
7711
184k
7712
184k
  // We have any identifiers remaining in the current AST file; return
7713
184k
  // the next one.
7714
183k
  StringRef Result = *Current;
7715
183k
  ++Current;
7716
183k
  return Result;
7717
184k
}
7718
7719
namespace {
7720
7721
/// A utility for appending two IdentifierIterators.
7722
class ChainedIdentifierIterator : public IdentifierIterator {
7723
  std::unique_ptr<IdentifierIterator> Current;
7724
  std::unique_ptr<IdentifierIterator> Queued;
7725
7726
public:
7727
  ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7728
                            std::unique_ptr<IdentifierIterator> Second)
7729
14
      : Current(std::move(First)), Queued(std::move(Second)) {}
7730
7731
19.1k
  StringRef Next() override {
7732
19.1k
    if (!Current)
7733
14
      return StringRef();
7734
19.1k
7735
19.1k
    StringRef result = Current->Next();
7736
19.1k
    if (!result.empty())
7737
19.1k
      return result;
7738
28
7739
28
    // Try the queued iterator, which may itself be empty.
7740
28
    Current.reset();
7741
28
    std::swap(Current, Queued);
7742
28
    return Next();
7743
28
  }
7744
};
7745
7746
} // end anonymous namespace.
7747
7748
304
IdentifierIterator *ASTReader::getIdentifiers() {
7749
304
  if (
!loadGlobalIndex()304
) {
7750
14
    std::unique_ptr<IdentifierIterator> ReaderIter(
7751
14
        new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7752
14
    std::unique_ptr<IdentifierIterator> ModulesIter(
7753
14
        GlobalIndex->createIdentifierIterator());
7754
14
    return new ChainedIdentifierIterator(std::move(ReaderIter),
7755
14
                                         std::move(ModulesIter));
7756
14
  }
7757
290
7758
290
  return new ASTIdentifierIterator(*this);
7759
290
}
7760
7761
namespace clang {
7762
namespace serialization {
7763
7764
  class ReadMethodPoolVisitor {
7765
    ASTReader &Reader;
7766
    Selector Sel;
7767
    unsigned PriorGeneration;
7768
    unsigned InstanceBits;
7769
    unsigned FactoryBits;
7770
    bool InstanceHasMoreThanOneDecl;
7771
    bool FactoryHasMoreThanOneDecl;
7772
    SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7773
    SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
7774
7775
  public:
7776
    ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
7777
                          unsigned PriorGeneration)
7778
        : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
7779
          InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7780
1.09k
          FactoryHasMoreThanOneDecl(false) {}
7781
7782
593
    bool operator()(ModuleFile &M) {
7783
593
      if (!M.SelectorLookupTable)
7784
198
        return false;
7785
395
7786
395
      // If we've already searched this module file, skip it now.
7787
395
      
if (395
M.Generation <= PriorGeneration395
)
7788
177
        return true;
7789
218
7790
218
      ++Reader.NumMethodPoolTableLookups;
7791
218
      ASTSelectorLookupTable *PoolTable
7792
218
        = (ASTSelectorLookupTable*)M.SelectorLookupTable;
7793
218
      ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
7794
218
      if (Pos == PoolTable->end())
7795
138
        return false;
7796
80
7797
80
      ++Reader.NumMethodPoolTableHits;
7798
80
      ++Reader.NumSelectorsRead;
7799
80
      // FIXME: Not quite happy with the statistics here. We probably should
7800
80
      // disable this tracking when called via LoadSelector.
7801
80
      // Also, should entries without methods count as misses?
7802
80
      ++Reader.NumMethodPoolEntriesRead;
7803
80
      ASTSelectorLookupTrait::data_type Data = *Pos;
7804
80
      if (Reader.DeserializationListener)
7805
11
        Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
7806
593
7807
593
      InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7808
593
      FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7809
593
      InstanceBits = Data.InstanceBits;
7810
593
      FactoryBits = Data.FactoryBits;
7811
593
      InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7812
593
      FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
7813
593
      return true;
7814
593
    }
7815
7816
    /// \brief Retrieve the instance methods found by this visitor.
7817
1.16k
    ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7818
1.16k
      return InstanceMethods;
7819
1.16k
    }
7820
7821
    /// \brief Retrieve the instance methods found by this visitor.
7822
1.10k
    ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7823
1.10k
      return FactoryMethods;
7824
1.10k
    }
7825
7826
69
    unsigned getInstanceBits() const { return InstanceBits; }
7827
69
    unsigned getFactoryBits() const { return FactoryBits; }
7828
69
    bool instanceHasMoreThanOneDecl() const {
7829
69
      return InstanceHasMoreThanOneDecl;
7830
69
    }
7831
69
    bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
7832
  };
7833
7834
} // end namespace serialization
7835
} // end namespace clang
7836
7837
/// \brief Add the given set of methods to the method list.
7838
static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7839
138
                             ObjCMethodList &List) {
7840
220
  for (unsigned I = 0, N = Methods.size(); 
I != N220
;
++I82
) {
7841
82
    S.addMethodToGlobalList(&List, Methods[I]);
7842
82
  }
7843
138
}
7844
7845
1.09k
void ASTReader::ReadMethodPool(Selector Sel) {
7846
1.09k
  // Get the selector generation and update it to the current generation.
7847
1.09k
  unsigned &Generation = SelectorGeneration[Sel];
7848
1.09k
  unsigned PriorGeneration = Generation;
7849
1.09k
  Generation = getGeneration();
7850
1.09k
  SelectorOutOfDate[Sel] = false;
7851
1.09k
7852
1.09k
  // Search for methods defined with this selector.
7853
1.09k
  ++NumMethodPoolLookups;
7854
1.09k
  ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
7855
1.09k
  ModuleMgr.visit(Visitor);
7856
1.09k
7857
1.09k
  if (Visitor.getInstanceMethods().empty() &&
7858
1.03k
      Visitor.getFactoryMethods().empty())
7859
1.02k
    return;
7860
69
7861
69
  ++NumMethodPoolHits;
7862
69
7863
69
  if (!getSema())
7864
0
    return;
7865
69
7866
69
  Sema &S = *getSema();
7867
69
  Sema::GlobalMethodPool::iterator Pos
7868
69
    = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
7869
69
7870
69
  Pos->second.first.setBits(Visitor.getInstanceBits());
7871
69
  Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
7872
69
  Pos->second.second.setBits(Visitor.getFactoryBits());
7873
69
  Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
7874
69
7875
69
  // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7876
69
  // when building a module we keep every method individually and may need to
7877
69
  // update hasMoreThanOneDecl as we add the methods.
7878
69
  addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7879
69
  addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
7880
69
}
7881
7882
13
void ASTReader::updateOutOfDateSelector(Selector Sel) {
7883
13
  if (SelectorOutOfDate[Sel])
7884
1
    ReadMethodPool(Sel);
7885
13
}
7886
7887
void ASTReader::ReadKnownNamespaces(
7888
81
                          SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7889
81
  Namespaces.clear();
7890
81
7891
182
  for (unsigned I = 0, N = KnownNamespaces.size(); 
I != N182
;
++I101
) {
7892
101
    if (NamespaceDecl *Namespace
7893
101
                = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7894
101
      Namespaces.push_back(Namespace);
7895
101
  }
7896
81
}
7897
7898
void ASTReader::ReadUndefinedButUsed(
7899
2.70k
    llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
7900
3.03k
  for (unsigned Idx = 0, N = UndefinedButUsed.size(); 
Idx != N3.03k
;) {
7901
332
    NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
7902
332
    SourceLocation Loc =
7903
332
        SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
7904
332
    Undefined.insert(std::make_pair(D, Loc));
7905
332
  }
7906
2.70k
}
7907
7908
void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7909
    FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7910
1.77k
                                                     Exprs) {
7911
1.77k
  for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); 
Idx != N1.77k
;) {
7912
1
    FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7913
1
    uint64_t Count = DelayedDeleteExprs[Idx++];
7914
2
    for (uint64_t C = 0; 
C < Count2
;
++C1
) {
7915
1
      SourceLocation DeleteLoc =
7916
1
          SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7917
1
      const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7918
1
      Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7919
1
    }
7920
1
  }
7921
1.77k
}
7922
7923
void ASTReader::ReadTentativeDefinitions(
7924
1.78k
                  SmallVectorImpl<VarDecl *> &TentativeDefs) {
7925
2.47k
  for (unsigned I = 0, N = TentativeDefinitions.size(); 
I != N2.47k
;
++I686
) {
7926
686
    VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7927
686
    if (Var)
7928
686
      TentativeDefs.push_back(Var);
7929
686
  }
7930
1.78k
  TentativeDefinitions.clear();
7931
1.78k
}
7932
7933
void ASTReader::ReadUnusedFileScopedDecls(
7934
1.43k
                               SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7935
1.44k
  for (unsigned I = 0, N = UnusedFileScopedDecls.size(); 
I != N1.44k
;
++I10
) {
7936
10
    DeclaratorDecl *D
7937
10
      = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7938
10
    if (D)
7939
10
      Decls.push_back(D);
7940
10
  }
7941
1.43k
  UnusedFileScopedDecls.clear();
7942
1.43k
}
7943
7944
void ASTReader::ReadDelegatingConstructors(
7945
733
                                 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7946
736
  for (unsigned I = 0, N = DelegatingCtorDecls.size(); 
I != N736
;
++I3
) {
7947
3
    CXXConstructorDecl *D
7948
3
      = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7949
3
    if (D)
7950
3
      Decls.push_back(D);
7951
3
  }
7952
733
  DelegatingCtorDecls.clear();
7953
733
}
7954
7955
2
void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7956
6
  for (unsigned I = 0, N = ExtVectorDecls.size(); 
I != N6
;
++I4
) {
7957
4
    TypedefNameDecl *D
7958
4
      = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7959
4
    if (D)
7960
4
      Decls.push_back(D);
7961
4
  }
7962
2
  ExtVectorDecls.clear();
7963
2
}
7964
7965
void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7966
2.73k
    llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7967
2.73k
  for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7968
2.73k
       
++I3
) {
7969
3
    TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7970
3
        GetDecl(UnusedLocalTypedefNameCandidates[I]));
7971
3
    if (D)
7972
3
      Decls.insert(D);
7973
3
  }
7974
2.73k
  UnusedLocalTypedefNameCandidates.clear();
7975
2.73k
}
7976
7977
void ASTReader::ReadReferencedSelectors(
7978
3.08k
       SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7979
3.08k
  if (ReferencedSelectorsData.empty())
7980
3.07k
    return;
7981
2
7982
2
  // If there are @selector references added them to its pool. This is for
7983
2
  // implementation of -Wselector.
7984
2
  unsigned int DataSize = ReferencedSelectorsData.size()-1;
7985
2
  unsigned I = 0;
7986
4
  while (
I < DataSize4
) {
7987
2
    Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7988
2
    SourceLocation SelLoc
7989
2
      = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7990
2
    Sels.push_back(std::make_pair(Sel, SelLoc));
7991
2
  }
7992
3.08k
  ReferencedSelectorsData.clear();
7993
3.08k
}
7994
7995
void ASTReader::ReadWeakUndeclaredIdentifiers(
7996
82.2k
       SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7997
82.2k
  if (WeakUndeclaredIdentifiers.empty())
7998
82.2k
    return;
7999
9
8000
49
  
for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); 9
I < N49
; /*none*/) {
8001
40
    IdentifierInfo *WeakId
8002
40
      = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8003
40
    IdentifierInfo *AliasId
8004
40
      = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8005
40
    SourceLocation Loc
8006
40
      = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
8007
40
    bool Used = WeakUndeclaredIdentifiers[I++];
8008
40
    WeakInfo WI(AliasId, Loc);
8009
40
    WI.setUsed(Used);
8010
40
    WeakIDs.push_back(std::make_pair(WeakId, WI));
8011
40
  }
8012
82.2k
  WeakUndeclaredIdentifiers.clear();
8013
82.2k
}
8014
8015
4.24k
void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
8016
4.24k
  for (unsigned Idx = 0, N = VTableUses.size(); 
Idx < N4.24k
; /* In loop */) {
8017
4
    ExternalVTableUse VT;
8018
4
    VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
8019
4
    VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
8020
4
    VT.DefinitionRequired = VTableUses[Idx++];
8021
4
    VTables.push_back(VT);
8022
4
  }
8023
4.24k
8024
4.24k
  VTableUses.clear();
8025
4.24k
}
8026
8027
void ASTReader::ReadPendingInstantiations(
8028
3.08k
       SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
8029
3.71k
  for (unsigned Idx = 0, N = PendingInstantiations.size(); 
Idx < N3.71k
;) {
8030
633
    ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
8031
633
    SourceLocation Loc
8032
633
      = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
8033
633
8034
633
    Pending.push_back(std::make_pair(D, Loc));
8035
633
  }
8036
3.08k
  PendingInstantiations.clear();
8037
3.08k
}
8038
8039
void ASTReader::ReadLateParsedTemplates(
8040
    llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
8041
25
        &LPTMap) {
8042
67
  for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
8043
42
       /* In loop */) {
8044
42
    FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
8045
42
8046
42
    auto LT = llvm::make_unique<LateParsedTemplate>();
8047
42
    LT->D = GetDecl(LateParsedTemplates[Idx++]);
8048
42
8049
42
    ModuleFile *F = getOwningModuleFile(LT->D);
8050
42
    assert(F && "No module");
8051
42
8052
42
    unsigned TokN = LateParsedTemplates[Idx++];
8053
42
    LT->Toks.reserve(TokN);
8054
548
    for (unsigned T = 0; 
T < TokN548
;
++T506
)
8055
506
      LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
8056
42
8057
42
    LPTMap.insert(std::make_pair(FD, std::move(LT)));
8058
42
  }
8059
25
8060
25
  LateParsedTemplates.clear();
8061
25
}
8062
8063
265
void ASTReader::LoadSelector(Selector Sel) {
8064
265
  // It would be complicated to avoid reading the methods anyway. So don't.
8065
265
  ReadMethodPool(Sel);
8066
265
}
8067
8068
354k
void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
8069
354k
  assert(ID && "Non-zero identifier ID required");
8070
354k
  assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
8071
354k
  IdentifiersLoaded[ID - 1] = II;
8072
354k
  if (DeserializationListener)
8073
27.2k
    DeserializationListener->IdentifierRead(ID, II);
8074
354k
}
8075
8076
/// \brief Set the globally-visible declarations associated with the given
8077
/// identifier.
8078
///
8079
/// If the AST reader is currently in a state where the given declaration IDs
8080
/// cannot safely be resolved, they are queued until it is safe to resolve
8081
/// them.
8082
///
8083
/// \param II an IdentifierInfo that refers to one or more globally-visible
8084
/// declarations.
8085
///
8086
/// \param DeclIDs the set of declaration IDs with the name @p II that are
8087
/// visible at global scope.
8088
///
8089
/// \param Decls if non-null, this vector will be populated with the set of
8090
/// deserialized declarations. These declarations will not be pushed into
8091
/// scope.
8092
void
8093
ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
8094
                              const SmallVectorImpl<uint32_t> &DeclIDs,
8095
35.2k
                                   SmallVectorImpl<Decl *> *Decls) {
8096
35.2k
  if (
NumCurrentElementsDeserializing && 35.2k
!Decls35.2k
) {
8097
17.7k
    PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
8098
17.7k
    return;
8099
17.7k
  }
8100
17.5k
8101
35.6k
  
for (unsigned I = 0, N = DeclIDs.size(); 17.5k
I != N35.6k
;
++I18.1k
) {
8102
18.1k
    if (
!SemaObj18.1k
) {
8103
1.37k
      // Queue this declaration so that it will be added to the
8104
1.37k
      // translation unit scope and identifier's declaration chain
8105
1.37k
      // once a Sema object is known.
8106
1.37k
      PreloadedDeclIDs.push_back(DeclIDs[I]);
8107
1.37k
      continue;
8108
1.37k
    }
8109
16.7k
8110
16.7k
    NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
8111
16.7k
8112
16.7k
    // If we're simply supposed to record the declarations, do so now.
8113
16.7k
    if (
Decls16.7k
) {
8114
16.7k
      Decls->push_back(D);
8115
16.7k
      continue;
8116
16.7k
    }
8117
0
8118
0
    // Introduce this declaration into the translation-unit scope
8119
0
    // and add it to the declaration chain for this identifier, so
8120
0
    // that (unqualified) name lookup will find it.
8121
0
    pushExternalDeclIntoScope(D, II);
8122
0
  }
8123
35.2k
}
8124
8125
192k
IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
8126
192k
  if (ID == 0)
8127
44.3k
    return nullptr;
8128
148k
8129
148k
  
if (148k
IdentifiersLoaded.empty()148k
) {
8130
0
    Error("no identifier table in AST file");
8131
0
    return nullptr;
8132
0
  }
8133
148k
8134
148k
  ID -= 1;
8135
148k
  if (
!IdentifiersLoaded[ID]148k
) {
8136
42.9k
    GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8137
42.9k
    assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8138
42.9k
    ModuleFile *M = I->second;
8139
42.9k
    unsigned Index = ID - M->BaseIdentifierID;
8140
42.9k
    const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
8141
42.9k
8142
42.9k
    // All of the strings in the AST file are preceded by a 16-bit length.
8143
42.9k
    // Extract that 16-bit length to avoid having to execute strlen().
8144
42.9k
    // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
8145
42.9k
    //  unsigned integers.  This is important to avoid integer overflow when
8146
42.9k
    //  we cast them to 'unsigned'.
8147
42.9k
    const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
8148
42.9k
    unsigned StrLen = (((unsigned) StrLenPtr[0])
8149
42.9k
                       | (((unsigned) StrLenPtr[1]) << 8)) - 1;
8150
42.9k
    auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
8151
42.9k
    IdentifiersLoaded[ID] = &II;
8152
42.9k
    markIdentifierFromAST(*this,  II);
8153
42.9k
    if (DeserializationListener)
8154
7.27k
      DeserializationListener->IdentifierRead(ID + 1, &II);
8155
42.9k
  }
8156
192k
8157
192k
  return IdentifiersLoaded[ID];
8158
192k
}
8159
8160
123k
IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
8161
123k
  return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
8162
123k
}
8163
8164
550k
IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
8165
550k
  if (LocalID < NUM_PREDEF_IDENT_IDS)
8166
47.1k
    return LocalID;
8167
503k
8168
503k
  
if (503k
!M.ModuleOffsetMap.empty()503k
)
8169
0
    ReadModuleOffsetMap(M);
8170
550k
8171
550k
  ContinuousRangeMap<uint32_t, int, 2>::iterator I
8172
550k
    = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
8173
550k
  assert(I != M.IdentifierRemap.end()
8174
550k
         && "Invalid index into identifier index remap");
8175
550k
8176
550k
  return LocalID + I->second;
8177
550k
}
8178
8179
34.8k
MacroInfo *ASTReader::getMacro(MacroID ID) {
8180
34.8k
  if (ID == 0)
8181
66
    return nullptr;
8182
34.7k
8183
34.7k
  
if (34.7k
MacrosLoaded.empty()34.7k
) {
8184
0
    Error("no macro table in AST file");
8185
0
    return nullptr;
8186
0
  }
8187
34.7k
8188
34.7k
  ID -= NUM_PREDEF_MACRO_IDS;
8189
34.7k
  if (
!MacrosLoaded[ID]34.7k
) {
8190
34.7k
    GlobalMacroMapType::iterator I
8191
34.7k
      = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8192
34.7k
    assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8193
34.7k
    ModuleFile *M = I->second;
8194
34.7k
    unsigned Index = ID - M->BaseMacroID;
8195
34.7k
    MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
8196
34.7k
8197
34.7k
    if (DeserializationListener)
8198
434
      DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8199
434
                                         MacrosLoaded[ID]);
8200
34.7k
  }
8201
34.8k
8202
34.8k
  return MacrosLoaded[ID];
8203
34.8k
}
8204
8205
34.8k
MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
8206
34.8k
  if (LocalID < NUM_PREDEF_MACRO_IDS)
8207
66
    return LocalID;
8208
34.7k
8209
34.7k
  
if (34.7k
!M.ModuleOffsetMap.empty()34.7k
)
8210
0
    ReadModuleOffsetMap(M);
8211
34.8k
8212
34.8k
  ContinuousRangeMap<uint32_t, int, 2>::iterator I
8213
34.8k
    = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8214
34.8k
  assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8215
34.8k
8216
34.8k
  return LocalID + I->second;
8217
34.8k
}
8218
8219
serialization::SubmoduleID
8220
101k
ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
8221
101k
  if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8222
50.0k
    return LocalID;
8223
51.8k
8224
51.8k
  
if (51.8k
!M.ModuleOffsetMap.empty()51.8k
)
8225
712
    ReadModuleOffsetMap(M);
8226
101k
8227
101k
  ContinuousRangeMap<uint32_t, int, 2>::iterator I
8228
101k
    = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
8229
101k
  assert(I != M.SubmoduleRemap.end()
8230
101k
         && "Invalid index into submodule index remap");
8231
101k
8232
101k
  return LocalID + I->second;
8233
101k
}
8234
8235
66.9k
Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
8236
66.9k
  if (
GlobalID < NUM_PREDEF_SUBMODULE_IDS66.9k
) {
8237
3.29k
    assert(GlobalID == 0 && "Unhandled global submodule ID");
8238
3.29k
    return nullptr;
8239
3.29k
  }
8240
63.6k
8241
63.6k
  
if (63.6k
GlobalID > SubmodulesLoaded.size()63.6k
) {
8242
0
    Error("submodule ID out of range in AST file");
8243
0
    return nullptr;
8244
0
  }
8245
63.6k
8246
63.6k
  return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8247
63.6k
}
8248
8249
20.9k
Module *ASTReader::getModule(unsigned ID) {
8250
20.9k
  return getSubmodule(ID);
8251
20.9k
}
8252
8253
1.46k
ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
8254
1.46k
  if (
ID & 11.46k
) {
8255
1.46k
    // It's a module, look it up by submodule ID.
8256
1.46k
    auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
8257
1.46k
    return I == GlobalSubmoduleMap.end() ? 
nullptr0
:
I->second1.46k
;
8258
0
  } else {
8259
0
    // It's a prefix (preamble, PCH, ...). Look it up by index.
8260
0
    unsigned IndexFromEnd = ID >> 1;
8261
0
    assert(IndexFromEnd && "got reference to unknown module file");
8262
0
    return getModuleManager().pch_modules().end()[-IndexFromEnd];
8263
0
  }
8264
0
}
8265
8266
102
unsigned ASTReader::getModuleFileID(ModuleFile *F) {
8267
102
  if (!F)
8268
0
    return 1;
8269
102
8270
102
  // For a file representing a module, use the submodule ID of the top-level
8271
102
  // module as the file ID. For any other kind of file, the number of such
8272
102
  // files loaded beforehand will be the same on reload.
8273
102
  // FIXME: Is this true even if we have an explicit module file and a PCH?
8274
102
  
if (102
F->isModule()102
)
8275
102
    return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
8276
0
8277
0
  auto PCHModules = getModuleManager().pch_modules();
8278
0
  auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
8279
0
  assert(I != PCHModules.end() && "emitting reference to unknown file");
8280
0
  return (I - PCHModules.end()) << 1;
8281
0
}
8282
8283
llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
8284
177
ASTReader::getSourceDescriptor(unsigned ID) {
8285
177
  if (const Module *M = getSubmodule(ID))
8286
83
    return ExternalASTSource::ASTSourceDescriptor(*M);
8287
94
8288
94
  // If there is only a single PCH, return it instead.
8289
94
  // Chained PCH are not supported.
8290
94
  const auto &PCHChain = ModuleMgr.pch_modules();
8291
94
  if (
std::distance(std::begin(PCHChain), std::end(PCHChain))94
) {
8292
94
    ModuleFile &MF = ModuleMgr.getPrimaryModule();
8293
94
    StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
8294
94
    StringRef FileName = llvm::sys::path::filename(MF.FileName);
8295
94
    return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
8296
94
                                          MF.Signature);
8297
94
  }
8298
0
  return None;
8299
0
}
8300
8301
72.9k
ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
8302
72.9k
  auto I = DefinitionSource.find(FD);
8303
72.9k
  if (I == DefinitionSource.end())
8304
72.6k
    return EK_ReplyHazy;
8305
280
  
return I->second ? 280
EK_Never132
:
EK_Always148
;
8306
72.9k
}
8307
8308
549
Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
8309
549
  return DecodeSelector(getGlobalSelectorID(M, LocalID));
8310
549
}
8311
8312
561
Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
8313
561
  if (ID == 0)
8314
2
    return Selector();
8315
559
8316
559
  
if (559
ID > SelectorsLoaded.size()559
) {
8317
0
    Error("selector ID out of range in AST file");
8318
0
    return Selector();
8319
0
  }
8320
559
8321
559
  
if (559
SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr559
) {
8322
318
    // Load this selector from the selector table.
8323
318
    GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
8324
318
    assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
8325
318
    ModuleFile &M = *I->second;
8326
318
    ASTSelectorLookupTrait Trait(*this, M);
8327
318
    unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
8328
318
    SelectorsLoaded[ID - 1] =
8329
318
      Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
8330
318
    if (DeserializationListener)
8331
13
      DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
8332
318
  }
8333
561
8334
561
  return SelectorsLoaded[ID - 1];
8335
561
}
8336
8337
10
Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
8338
10
  return DecodeSelector(ID);
8339
10
}
8340
8341
2
uint32_t ASTReader::GetNumExternalSelectors() {
8342
2
  // ID 0 (the null selector) is considered an external selector.
8343
2
  return getTotalNumSelectors() + 1;
8344
2
}
8345
8346
serialization::SelectorID
8347
632
ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
8348
632
  if (LocalID < NUM_PREDEF_SELECTOR_IDS)
8349
0
    return LocalID;
8350
632
8351
632
  
if (632
!M.ModuleOffsetMap.empty()632
)
8352
0
    ReadModuleOffsetMap(M);
8353
632
8354
632
  ContinuousRangeMap<uint32_t, int, 2>::iterator I
8355
632
    = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
8356
632
  assert(I != M.SelectorRemap.end()
8357
632
         && "Invalid index into selector index remap");
8358
632
8359
632
  return LocalID + I->second;
8360
632
}
8361
8362
DeclarationName
8363
ASTReader::ReadDeclarationName(ModuleFile &F,
8364
72.7k
                               const RecordData &Record, unsigned &Idx) {
8365
72.7k
  ASTContext &Context = getContext();
8366
72.7k
  DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
8367
72.7k
  switch (Kind) {
8368
68.0k
  case DeclarationName::Identifier:
8369
68.0k
    return DeclarationName(GetIdentifierInfo(F, Record, Idx));
8370
72.7k
8371
432
  case DeclarationName::ObjCZeroArgSelector:
8372
432
  case DeclarationName::ObjCOneArgSelector:
8373
432
  case DeclarationName::ObjCMultiArgSelector:
8374
432
    return DeclarationName(ReadSelector(F, Record, Idx));
8375
432
8376
2.63k
  case DeclarationName::CXXConstructorName:
8377
2.63k
    return Context.DeclarationNames.getCXXConstructorName(
8378
2.63k
                          Context.getCanonicalType(readType(F, Record, Idx)));
8379
432
8380
530
  case DeclarationName::CXXDestructorName:
8381
530
    return Context.DeclarationNames.getCXXDestructorName(
8382
530
                          Context.getCanonicalType(readType(F, Record, Idx)));
8383
432
8384
0
  case DeclarationName::CXXDeductionGuideName:
8385
0
    return Context.DeclarationNames.getCXXDeductionGuideName(
8386
0
                          ReadDeclAs<TemplateDecl>(F, Record, Idx));
8387
432
8388
160
  case DeclarationName::CXXConversionFunctionName:
8389
160
    return Context.DeclarationNames.getCXXConversionFunctionName(
8390
160
                          Context.getCanonicalType(readType(F, Record, Idx)));
8391
432
8392
886
  case DeclarationName::CXXOperatorName:
8393
886
    return Context.DeclarationNames.getCXXOperatorName(
8394
886
                                       (OverloadedOperatorKind)Record[Idx++]);
8395
432
8396
1
  case DeclarationName::CXXLiteralOperatorName:
8397
1
    return Context.DeclarationNames.getCXXLiteralOperatorName(
8398
1
                                       GetIdentifierInfo(F, Record, Idx));
8399
432
8400
41
  case DeclarationName::CXXUsingDirective:
8401
41
    return DeclarationName::getUsingDirectiveName();
8402
0
  }
8403
0
8404
0
  
llvm_unreachable0
("Invalid NameKind!");
8405
0
}
8406
8407
void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
8408
                                       DeclarationNameLoc &DNLoc,
8409
                                       DeclarationName Name,
8410
41.0k
                                      const RecordData &Record, unsigned &Idx) {
8411
41.0k
  switch (Name.getNameKind()) {
8412
3.24k
  case DeclarationName::CXXConstructorName:
8413
3.24k
  case DeclarationName::CXXDestructorName:
8414
3.24k
  case DeclarationName::CXXConversionFunctionName:
8415
3.24k
    DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
8416
3.24k
    break;
8417
3.24k
8418
1.15k
  case DeclarationName::CXXOperatorName:
8419
1.15k
    DNLoc.CXXOperatorName.BeginOpNameLoc
8420
1.15k
        = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8421
1.15k
    DNLoc.CXXOperatorName.EndOpNameLoc
8422
1.15k
        = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8423
1.15k
    break;
8424
3.24k
8425
2
  case DeclarationName::CXXLiteralOperatorName:
8426
2
    DNLoc.CXXLiteralOperatorName.OpNameLoc
8427
2
        = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8428
2
    break;
8429
3.24k
8430
36.6k
  case DeclarationName::Identifier:
8431
36.6k
  case DeclarationName::ObjCZeroArgSelector:
8432
36.6k
  case DeclarationName::ObjCOneArgSelector:
8433
36.6k
  case DeclarationName::ObjCMultiArgSelector:
8434
36.6k
  case DeclarationName::CXXUsingDirective:
8435
36.6k
  case DeclarationName::CXXDeductionGuideName:
8436
36.6k
    break;
8437
41.0k
  }
8438
41.0k
}
8439
8440
void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
8441
                                        DeclarationNameInfo &NameInfo,
8442
957
                                      const RecordData &Record, unsigned &Idx) {
8443
957
  NameInfo.setName(ReadDeclarationName(F, Record, Idx));
8444
957
  NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
8445
957
  DeclarationNameLoc DNLoc;
8446
957
  ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
8447
957
  NameInfo.setInfo(DNLoc);
8448
957
}
8449
8450
void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
8451
491
                                  const RecordData &Record, unsigned &Idx) {
8452
491
  Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
8453
491
  unsigned NumTPLists = Record[Idx++];
8454
491
  Info.NumTemplParamLists = NumTPLists;
8455
491
  if (
NumTPLists491
) {
8456
382
    Info.TemplParamLists =
8457
382
        new (getContext()) TemplateParameterList *[NumTPLists];
8458
776
    for (unsigned i = 0; 
i != NumTPLists776
;
++i394
)
8459
394
      Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
8460
382
  }
8461
491
}
8462
8463
TemplateName
8464
ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
8465
6.48k
                            unsigned &Idx) {
8466
6.48k
  ASTContext &Context = getContext();
8467
6.48k
  TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
8468
6.48k
  switch (Kind) {
8469
6.47k
  case TemplateName::Template:
8470
6.47k
      return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
8471
6.48k
8472
0
  case TemplateName::OverloadedTemplate: {
8473
0
    unsigned size = Record[Idx++];
8474
0
    UnresolvedSet<8> Decls;
8475
0
    while (size--)
8476
0
      Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
8477
0
8478
0
    return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
8479
6.48k
  }
8480
6.48k
8481
0
  case TemplateName::QualifiedTemplate: {
8482
0
    NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8483
0
    bool hasTemplKeyword = Record[Idx++];
8484
0
    TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
8485
0
    return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
8486
6.48k
  }
8487
6.48k
8488
0
  case TemplateName::DependentTemplate: {
8489
0
    NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8490
0
    if (Record[Idx++])  // isIdentifier
8491
0
      return Context.getDependentTemplateName(NNS,
8492
0
                                               GetIdentifierInfo(F, Record,
8493
0
                                                                 Idx));
8494
0
    return Context.getDependentTemplateName(NNS,
8495
0
                                         (OverloadedOperatorKind)Record[Idx++]);
8496
0
  }
8497
0
8498
8
  case TemplateName::SubstTemplateTemplateParm: {
8499
8
    TemplateTemplateParmDecl *param
8500
8
      = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8501
8
    if (
!param8
)
return TemplateName()0
;
8502
8
    TemplateName replacement = ReadTemplateName(F, Record, Idx);
8503
8
    return Context.getSubstTemplateTemplateParm(param, replacement);
8504
8
  }
8505
8
8506
0
  case TemplateName::SubstTemplateTemplateParmPack: {
8507
0
    TemplateTemplateParmDecl *Param
8508
0
      = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8509
0
    if (!Param)
8510
0
      return TemplateName();
8511
0
8512
0
    TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
8513
0
    if (ArgPack.getKind() != TemplateArgument::Pack)
8514
0
      return TemplateName();
8515
0
8516
0
    return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
8517
0
  }
8518
0
  }
8519
0
8520
0
  
llvm_unreachable0
("Unhandled template name kind!");
8521
0
}
8522
8523
TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
8524
                                                 const RecordData &Record,
8525
                                                 unsigned &Idx,
8526
15.3k
                                                 bool Canonicalize) {
8527
15.3k
  ASTContext &Context = getContext();
8528
15.3k
  if (
Canonicalize15.3k
) {
8529
3.90k
    // The caller wants a canonical template argument. Sometimes the AST only
8530
3.90k
    // wants template arguments in canonical form (particularly as the template
8531
3.90k
    // argument lists of template specializations) so ensure we preserve that
8532
3.90k
    // canonical form across serialization.
8533
3.90k
    TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
8534
3.90k
    return Context.getCanonicalTemplateArgument(Arg);
8535
3.90k
  }
8536
11.4k
8537
11.4k
  TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
8538
11.4k
  switch (Kind) {
8539
0
  case TemplateArgument::Null:
8540
0
    return TemplateArgument();
8541
5.67k
  case TemplateArgument::Type:
8542
5.67k
    return TemplateArgument(readType(F, Record, Idx));
8543
0
  case TemplateArgument::Declaration: {
8544
0
    ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
8545
0
    return TemplateArgument(D, readType(F, Record, Idx));
8546
11.4k
  }
8547
0
  case TemplateArgument::NullPtr:
8548
0
    return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
8549
2.33k
  case TemplateArgument::Integral: {
8550
2.33k
    llvm::APSInt Value = ReadAPSInt(Record, Idx);
8551
2.33k
    QualType T = readType(F, Record, Idx);
8552
2.33k
    return TemplateArgument(Context, Value, T);
8553
11.4k
  }
8554
139
  case TemplateArgument::Template:
8555
139
    return TemplateArgument(ReadTemplateName(F, Record, Idx));
8556
4
  case TemplateArgument::TemplateExpansion: {
8557
4
    TemplateName Name = ReadTemplateName(F, Record, Idx);
8558
4
    Optional<unsigned> NumTemplateExpansions;
8559
4
    if (unsigned NumExpansions = Record[Idx++])
8560
0
      NumTemplateExpansions = NumExpansions - 1;
8561
4
    return TemplateArgument(Name, NumTemplateExpansions);
8562
11.4k
  }
8563
3.26k
  case TemplateArgument::Expression:
8564
3.26k
    return TemplateArgument(ReadExpr(F));
8565
57
  case TemplateArgument::Pack: {
8566
57
    unsigned NumArgs = Record[Idx++];
8567
57
    TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
8568
150
    for (unsigned I = 0; 
I != NumArgs150
;
++I93
)
8569
93
      Args[I] = ReadTemplateArgument(F, Record, Idx);
8570
57
    return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
8571
0
  }
8572
0
  }
8573
0
8574
0
  
llvm_unreachable0
("Unhandled template argument kind!");
8575
0
}
8576
8577
TemplateParameterList *
8578
ASTReader::ReadTemplateParameterList(ModuleFile &F,
8579
3.06k
                                     const RecordData &Record, unsigned &Idx) {
8580
3.06k
  SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
8581
3.06k
  SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
8582
3.06k
  SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
8583
3.06k
8584
3.06k
  unsigned NumParams = Record[Idx++];
8585
3.06k
  SmallVector<NamedDecl *, 16> Params;
8586
3.06k
  Params.reserve(NumParams);
8587
6.40k
  while (NumParams--)
8588
3.33k
    Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
8589
3.06k
8590
3.06k
  // TODO: Concepts
8591
3.06k
  TemplateParameterList *TemplateParams = TemplateParameterList::Create(
8592
3.06k
      getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, nullptr);
8593
3.06k
  return TemplateParams;
8594
3.06k
}
8595
8596
void
8597
ASTReader::
8598
ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
8599
                         ModuleFile &F, const RecordData &Record,
8600
10.0k
                         unsigned &Idx, bool Canonicalize) {
8601
10.0k
  unsigned NumTemplateArgs = Record[Idx++];
8602
10.0k
  TemplArgs.reserve(NumTemplateArgs);
8603
20.8k
  while (NumTemplateArgs--)
8604
10.7k
    TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
8605
10.0k
}
8606
8607
/// \brief Read a UnresolvedSet structure.
8608
void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
8609
13.0k
                                  const RecordData &Record, unsigned &Idx) {
8610
13.0k
  unsigned NumDecls = Record[Idx++];
8611
13.0k
  Set.reserve(getContext(), NumDecls);
8612
13.2k
  while (
NumDecls--13.2k
) {
8613
210
    DeclID ID = ReadDeclID(F, Record, Idx);
8614
210
    AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
8615
210
    Set.addLazyDecl(getContext(), ID, AS);
8616
210
  }
8617
13.0k
}
8618
8619
CXXBaseSpecifier
8620
ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
8621
592
                                const RecordData &Record, unsigned &Idx) {
8622
592
  bool isVirtual = static_cast<bool>(Record[Idx++]);
8623
592
  bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
8624
592
  AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
8625
592
  bool inheritConstructors = static_cast<bool>(Record[Idx++]);
8626
592
  TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
8627
592
  SourceRange Range = ReadSourceRange(F, Record, Idx);
8628
592
  SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
8629
592
  CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
8630
592
                          EllipsisLoc);
8631
592
  Result.setInheritConstructors(inheritConstructors);
8632
592
  return Result;
8633
592
}
8634
8635
CXXCtorInitializer **
8636
ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
8637
435
                                   unsigned &Idx) {
8638
435
  ASTContext &Context = getContext();
8639
435
  unsigned NumInitializers = Record[Idx++];
8640
435
  assert(NumInitializers && "wrote ctor initializers but have no inits");
8641
435
  auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
8642
942
  for (unsigned i = 0; 
i != NumInitializers942
;
++i507
) {
8643
507
    TypeSourceInfo *TInfo = nullptr;
8644
507
    bool IsBaseVirtual = false;
8645
507
    FieldDecl *Member = nullptr;
8646
507
    IndirectFieldDecl *IndirectMember = nullptr;
8647
507
8648
507
    CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
8649
507
    switch (Type) {
8650
56
    case CTOR_INITIALIZER_BASE:
8651
56
      TInfo = GetTypeSourceInfo(F, Record, Idx);
8652
56
      IsBaseVirtual = Record[Idx++];
8653
56
      break;
8654
507
8655
3
    case CTOR_INITIALIZER_DELEGATING:
8656
3
      TInfo = GetTypeSourceInfo(F, Record, Idx);
8657
3
      break;
8658
507
8659
446
     case CTOR_INITIALIZER_MEMBER:
8660
446
      Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
8661
446
      break;
8662
507
8663
2
     case CTOR_INITIALIZER_INDIRECT_MEMBER:
8664
2
      IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
8665
2
      break;
8666
507
    }
8667
507
8668
507
    SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
8669
507
    Expr *Init = ReadExpr(F);
8670
507
    SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
8671
507
    SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
8672
507
8673
507
    CXXCtorInitializer *BOMInit;
8674
507
    if (Type == CTOR_INITIALIZER_BASE)
8675
56
      BOMInit = new (Context)
8676
56
          CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8677
56
                             RParenLoc, MemberOrEllipsisLoc);
8678
451
    else 
if (451
Type == CTOR_INITIALIZER_DELEGATING451
)
8679
3
      BOMInit = new (Context)
8680
3
          CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
8681
448
    else 
if (448
Member448
)
8682
446
      BOMInit = new (Context)
8683
446
          CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8684
446
                             Init, RParenLoc);
8685
448
    else
8686
2
      BOMInit = new (Context)
8687
2
          CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8688
2
                             LParenLoc, Init, RParenLoc);
8689
507
8690
507
    if (/*IsWritten*/
Record[Idx++]507
) {
8691
443
      unsigned SourceOrder = Record[Idx++];
8692
443
      BOMInit->setSourceOrder(SourceOrder);
8693
443
    }
8694
507
8695
507
    CtorInitializers[i] = BOMInit;
8696
507
  }
8697
435
8698
435
  return CtorInitializers;
8699
435
}
8700
8701
NestedNameSpecifier *
8702
ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8703
1.04k
                                   const RecordData &Record, unsigned &Idx) {
8704
1.04k
  ASTContext &Context = getContext();
8705
1.04k
  unsigned N = Record[Idx++];
8706
1.04k
  NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
8707
1.41k
  for (unsigned I = 0; 
I != N1.41k
;
++I372
) {
8708
372
    NestedNameSpecifier::SpecifierKind Kind
8709
372
      = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8710
372
    switch (Kind) {
8711
10
    case NestedNameSpecifier::Identifier: {
8712
10
      IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8713
10
      NNS = NestedNameSpecifier::Create(Context, Prev, II);
8714
10
      break;
8715
372
    }
8716
372
8717
66
    case NestedNameSpecifier::Namespace: {
8718
66
      NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8719
66
      NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8720
66
      break;
8721
372
    }
8722
372
8723
2
    case NestedNameSpecifier::NamespaceAlias: {
8724
2
      NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8725
2
      NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8726
2
      break;
8727
372
    }
8728
372
8729
290
    case NestedNameSpecifier::TypeSpec:
8730
290
    case NestedNameSpecifier::TypeSpecWithTemplate: {
8731
290
      const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8732
290
      if (!T)
8733
0
        return nullptr;
8734
290
8735
290
      bool Template = Record[Idx++];
8736
290
      NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8737
290
      break;
8738
290
    }
8739
290
8740
4
    case NestedNameSpecifier::Global: {
8741
4
      NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8742
4
      // No associated value, and there can't be a prefix.
8743
4
      break;
8744
290
    }
8745
290
8746
0
    case NestedNameSpecifier::Super: {
8747
0
      CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8748
0
      NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8749
0
      break;
8750
372
    }
8751
372
    }
8752
372
    Prev = NNS;
8753
372
  }
8754
1.04k
  return NNS;
8755
1.04k
}
8756
8757
NestedNameSpecifierLoc
8758
ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
8759
3.24k
                                      unsigned &Idx) {
8760
3.24k
  ASTContext &Context = getContext();
8761
3.24k
  unsigned N = Record[Idx++];
8762
3.24k
  NestedNameSpecifierLocBuilder Builder;
8763
4.69k
  for (unsigned I = 0; 
I != N4.69k
;
++I1.44k
) {
8764
1.44k
    NestedNameSpecifier::SpecifierKind Kind
8765
1.44k
      = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8766
1.44k
    switch (Kind) {
8767
19
    case NestedNameSpecifier::Identifier: {
8768
19
      IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8769
19
      SourceRange Range = ReadSourceRange(F, Record, Idx);
8770
19
      Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8771
19
      break;
8772
1.44k
    }
8773
1.44k
8774
158
    case NestedNameSpecifier::Namespace: {
8775
158
      NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8776
158
      SourceRange Range = ReadSourceRange(F, Record, Idx);
8777
158
      Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8778
158
      break;
8779
1.44k
    }
8780
1.44k
8781
2
    case NestedNameSpecifier::NamespaceAlias: {
8782
2
      NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8783
2
      SourceRange Range = ReadSourceRange(F, Record, Idx);
8784
2
      Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8785
2
      break;
8786
1.44k
    }
8787
1.44k
8788
1.21k
    case NestedNameSpecifier::TypeSpec:
8789
1.21k
    case NestedNameSpecifier::TypeSpecWithTemplate: {
8790
1.21k
      bool Template = Record[Idx++];
8791
1.21k
      TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8792
1.21k
      if (!T)
8793
0
        return NestedNameSpecifierLoc();
8794
1.21k
      SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8795
1.21k
8796
1.21k
      // FIXME: 'template' keyword location not saved anywhere, so we fake it.
8797
1.21k
      Builder.Extend(Context,
8798
1.21k
                     Template? 
T->getTypeLoc().getBeginLoc()2
:
SourceLocation()1.21k
,
8799
1.21k
                     T->getTypeLoc(), ColonColonLoc);
8800
1.21k
      break;
8801
1.21k
    }
8802
1.21k
8803
53
    case NestedNameSpecifier::Global: {
8804
53
      SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8805
53
      Builder.MakeGlobal(Context, ColonColonLoc);
8806
53
      break;
8807
1.21k
    }
8808
1.21k
8809
0
    case NestedNameSpecifier::Super: {
8810
0
      CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8811
0
      SourceRange Range = ReadSourceRange(F, Record, Idx);
8812
0
      Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8813
0
      break;
8814
1.21k
    }
8815
1.44k
    }
8816
1.44k
  }
8817
3.24k
8818
3.24k
  return Builder.getWithLocInContext(Context);
8819
3.24k
}
8820
8821
SourceRange
8822
ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8823
21.8k
                           unsigned &Idx) {
8824
21.8k
  SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8825
21.8k
  SourceLocation end = ReadSourceLocation(F, Record, Idx);
8826
21.8k
  return SourceRange(beg, end);
8827
21.8k
}
8828
8829
/// \brief Read an integral value
8830
23.5k
llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8831
23.5k
  unsigned BitWidth = Record[Idx++];
8832
23.5k
  unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8833
23.5k
  llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8834
23.5k
  Idx += NumWords;
8835
23.5k
  return Result;
8836
23.5k
}
8837
8838
/// \brief Read a signed integral value
8839
2.68k
llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8840
2.68k
  bool isUnsigned = Record[Idx++];
8841
2.68k
  return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8842
2.68k
}
8843
8844
/// \brief Read a floating-point value
8845
llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8846
                                     const llvm::fltSemantics &Sem,
8847
319
                                     unsigned &Idx) {
8848
319
  return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
8849
319
}
8850
8851
// \brief Read a string
8852
75.9k
std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8853
75.9k
  unsigned Len = Record[Idx++];
8854
75.9k
  std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8855
75.9k
  Idx += Len;
8856
75.9k
  return Result;
8857
75.9k
}
8858
8859
std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8860
14.6k
                                unsigned &Idx) {
8861
14.6k
  std::string Filename = ReadString(Record, Idx);
8862
14.6k
  ResolveImportedPath(F, Filename);
8863
14.6k
  return Filename;
8864
14.6k
}
8865
8866
VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8867
3.09k
                                         unsigned &Idx) {
8868
3.09k
  unsigned Major = Record[Idx++];
8869
3.09k
  unsigned Minor = Record[Idx++];
8870
3.09k
  unsigned Subminor = Record[Idx++];
8871
3.09k
  if (Minor == 0)
8872
2.88k
    return VersionTuple(Major);
8873
206
  
if (206
Subminor == 0206
)
8874
2
    return VersionTuple(Major, Minor - 1);
8875
204
  return VersionTuple(Major, Minor - 1, Subminor - 1);
8876
204
}
8877
8878
CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8879
                                          const RecordData &Record,
8880
158
                                          unsigned &Idx) {
8881
158
  CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8882
158
  return CXXTemporary::Create(getContext(), Decl);
8883
158
}
8884
8885
55
DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
8886
55
  return Diag(CurrentImportLoc, DiagID);
8887
55
}
8888
8889
379
DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
8890
379
  return Diags.Report(Loc, DiagID);
8891
379
}
8892
8893
/// \brief Retrieve the identifier table associated with the
8894
/// preprocessor.
8895
350k
IdentifierTable &ASTReader::getIdentifierTable() {
8896
350k
  return PP.getIdentifierTable();
8897
350k
}
8898
8899
/// \brief Record that the given ID maps to the given switch-case
8900
/// statement.
8901
23
void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
8902
23
  assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
8903
23
         "Already have a SwitchCase with this ID");
8904
23
  (*CurrSwitchCaseStmts)[ID] = SC;
8905
23
}
8906
8907
/// \brief Retrieve the switch-case statement with the given ID.
8908
23
SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
8909
23
  assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
8910
23
  return (*CurrSwitchCaseStmts)[ID];
8911
23
}
8912
8913
2.73k
void ASTReader::ClearSwitchCaseIDs() {
8914
2.73k
  CurrSwitchCaseStmts->clear();
8915
2.73k
}
8916
8917
117
void ASTReader::ReadComments() {
8918
117
  ASTContext &Context = getContext();
8919
117
  std::vector<RawComment *> Comments;
8920
117
  for (SmallVectorImpl<std::pair<BitstreamCursor,
8921
117
                                 serialization::ModuleFile *> >::iterator
8922
117
       I = CommentsCursors.begin(),
8923
117
       E = CommentsCursors.end();
8924
276
       
I != E276
;
++I159
) {
8925
159
    Comments.clear();
8926
159
    BitstreamCursor &Cursor = I->first;
8927
159
    serialization::ModuleFile &F = *I->second;
8928
159
    SavedStreamPosition SavedPosition(Cursor);
8929
159
8930
159
    RecordData Record;
8931
356
    while (
true356
) {
8932
356
      llvm::BitstreamEntry Entry =
8933
356
        Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
8934
356
8935
356
      switch (Entry.Kind) {
8936
0
      case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8937
0
      case llvm::BitstreamEntry::Error:
8938
0
        Error("malformed block record in AST file");
8939
0
        return;
8940
159
      case llvm::BitstreamEntry::EndBlock:
8941
159
        goto NextCursor;
8942
197
      case llvm::BitstreamEntry::Record:
8943
197
        // The interesting case.
8944
197
        break;
8945
197
      }
8946
197
8947
197
      // Read a record.
8948
197
      Record.clear();
8949
197
      switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
8950
197
      case COMMENTS_RAW_COMMENT: {
8951
197
        unsigned Idx = 0;
8952
197
        SourceRange SR = ReadSourceRange(F, Record, Idx);
8953
197
        RawComment::CommentKind Kind =
8954
197
            (RawComment::CommentKind) Record[Idx++];
8955
197
        bool IsTrailingComment = Record[Idx++];
8956
197
        bool IsAlmostTrailingComment = Record[Idx++];
8957
197
        Comments.push_back(new (Context) RawComment(
8958
197
            SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8959
197
            Context.getLangOpts().CommentOpts.ParseAllComments));
8960
197
        break;
8961
356
      }
8962
356
      }
8963
356
    }
8964
159
  NextCursor:
8965
159
    // De-serialized SourceLocations get negative FileIDs for other modules,
8966
159
    // potentially invalidating the original order. Sort it again.
8967
159
    std::sort(Comments.begin(), Comments.end(),
8968
159
              BeforeThanCompare<RawComment>(SourceMgr));
8969
159
    Context.Comments.addDeserializedComments(Comments);
8970
159
  }
8971
117
}
8972
8973
void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
8974
                                bool IncludeSystem, bool Complain,
8975
                    llvm::function_ref<void(const serialization::InputFile &IF,
8976
1
                                            bool isSystem)> Visitor) {
8977
1
  unsigned NumUserInputs = MF.NumUserInputFiles;
8978
1
  unsigned NumInputs = MF.InputFilesLoaded.size();
8979
1
  assert(NumUserInputs <= NumInputs);
8980
1
  unsigned N = IncludeSystem ? 
NumInputs1
:
NumUserInputs0
;
8981
3
  for (unsigned I = 0; 
I < N3
;
++I2
) {
8982
2
    bool IsSystem = I >= NumUserInputs;
8983
2
    InputFile IF = getInputFile(MF, I+1, Complain);
8984
2
    Visitor(IF, IsSystem);
8985
2
  }
8986
1
}
8987
8988
void ASTReader::visitTopLevelModuleMaps(
8989
    serialization::ModuleFile &MF,
8990
13
    llvm::function_ref<void(const FileEntry *FE)> Visitor) {
8991
13
  unsigned NumInputs = MF.InputFilesLoaded.size();
8992
51
  for (unsigned I = 0; 
I < NumInputs51
;
++I38
) {
8993
38
    InputFileInfo IFI = readInputFileInfo(MF, I + 1);
8994
38
    if (IFI.TopLevelModuleMap)
8995
38
      // FIXME: This unnecessarily re-reads the InputFileInfo.
8996
14
      
if (auto *14
FE14
= getInputFile(MF, I + 1).getFile())
8997
14
        Visitor(FE);
8998
38
  }
8999
13
}
9000
9001
304
std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
9002
304
  // If we know the owning module, use it.
9003
304
  if (Module *M = D->getImportedOwningModule())
9004
303
    return M->getFullModuleName();
9005
1
9006
1
  // Otherwise, use the name of the top-level module the decl is within.
9007
1
  
if (ModuleFile *1
M1
= getOwningModuleFile(D))
9008
0
    return M->ModuleName;
9009
1
9010
1
  // Not from a module.
9011
1
  return "";
9012
1
}
9013
9014
1.07M
void ASTReader::finishPendingActions() {
9015
1.12M
  while (!PendingIdentifierInfos.empty() ||
9016
1.12M
         
!PendingIncompleteDeclChains.empty()1.11M
||
!PendingDeclChains.empty()1.11M
||
9017
1.12M
         
!PendingMacroIDs.empty()1.10M
||
!PendingDeclContextInfos.empty()1.07M
||
9018
1.07M
         
!PendingUpdateRecords.empty()1.07M
) {
9019
52.1k
    // If any identifiers with corresponding top-level declarations have
9020
52.1k
    // been loaded, load those declarations now.
9021
52.1k
    typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
9022
52.1k
      TopLevelDeclsMap;
9023
52.1k
    TopLevelDeclsMap TopLevelDecls;
9024
52.1k
9025
69.6k
    while (
!PendingIdentifierInfos.empty()69.6k
) {
9026
17.5k
      IdentifierInfo *II = PendingIdentifierInfos.back().first;
9027
17.5k
      SmallVector<uint32_t, 4> DeclIDs =
9028
17.5k
          std::move(PendingIdentifierInfos.back().second);
9029
17.5k
      PendingIdentifierInfos.pop_back();
9030
17.5k
9031
17.5k
      SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
9032
17.5k
    }
9033
52.1k
9034
52.1k
    // For each decl chain that we wanted to complete while deserializing, mark
9035
52.1k
    // it as "still needs to be completed".
9036
55.8k
    for (unsigned I = 0; 
I != PendingIncompleteDeclChains.size()55.8k
;
++I3.68k
) {
9037
3.68k
      markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
9038
3.68k
    }
9039
52.1k
    PendingIncompleteDeclChains.clear();
9040
52.1k
9041
52.1k
    // Load pending declaration chains.
9042
110k
    for (unsigned I = 0; 
I != PendingDeclChains.size()110k
;
++I58.1k
)
9043
58.1k
      loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
9044
52.1k
    PendingDeclChains.clear();
9045
52.1k
9046
52.1k
    // Make the most recent of the top-level declarations visible.
9047
52.1k
    for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
9048
69.6k
           TLDEnd = TopLevelDecls.end(); 
TLD != TLDEnd69.6k
;
++TLD17.5k
) {
9049
17.5k
      IdentifierInfo *II = TLD->first;
9050
34.2k
      for (unsigned I = 0, N = TLD->second.size(); 
I != N34.2k
;
++I16.7k
) {
9051
16.7k
        pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
9052
16.7k
      }
9053
17.5k
    }
9054
52.1k
9055
52.1k
    // Load any pending macro definitions.
9056
86.5k
    for (unsigned I = 0; 
I != PendingMacroIDs.size()86.5k
;
++I34.3k
) {
9057
34.3k
      IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
9058
34.3k
      SmallVector<PendingMacroInfo, 2> GlobalIDs;
9059
34.3k
      GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
9060
34.3k
      // Initialize the macro history from chained-PCHs ahead of module imports.
9061
68.9k
      for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
9062
34.5k
           
++IDIdx34.5k
) {
9063
34.5k
        const PendingMacroInfo &Info = GlobalIDs[IDIdx];
9064
34.5k
        if (!Info.M->isModule())
9065
33.7k
          resolvePendingMacro(II, Info);
9066
34.5k
      }
9067
34.3k
      // Handle module imports.
9068
68.9k
      for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
9069
34.5k
           
++IDIdx34.5k
) {
9070
34.5k
        const PendingMacroInfo &Info = GlobalIDs[IDIdx];
9071
34.5k
        if (Info.M->isModule())
9072
783
          resolvePendingMacro(II, Info);
9073
34.5k
      }
9074
34.3k
    }
9075
52.1k
    PendingMacroIDs.clear();
9076
52.1k
9077
52.1k
    // Wire up the DeclContexts for Decls that we delayed setting until
9078
52.1k
    // recursive loading is completed.
9079
63.6k
    while (
!PendingDeclContextInfos.empty()63.6k
) {
9080
11.4k
      PendingDeclContextInfo Info = PendingDeclContextInfos.front();
9081
11.4k
      PendingDeclContextInfos.pop_front();
9082
11.4k
      DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
9083
11.4k
      DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
9084
11.4k
      Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9085
11.4k
    }
9086
52.1k
9087
52.1k
    // Perform any pending declaration updates.
9088
130k
    while (
!PendingUpdateRecords.empty()130k
) {
9089
78.1k
      auto Update = PendingUpdateRecords.pop_back_val();
9090
78.1k
      ReadingKindTracker ReadingKind(Read_Decl, *this);
9091
78.1k
      loadDeclUpdateRecords(Update);
9092
78.1k
    }
9093
52.1k
  }
9094
1.07M
9095
1.07M
  // At this point, all update records for loaded decls are in place, so any
9096
1.07M
  // fake class definitions should have become real.
9097
1.07M
  assert(PendingFakeDefinitionData.empty() &&
9098
1.07M
         "faked up a class definition but never saw the real one");
9099
1.07M
9100
1.07M
  // If we deserialized any C++ or Objective-C class definitions, any
9101
1.07M
  // Objective-C protocol definitions, or any redeclarable templates, make sure
9102
1.07M
  // that all redeclarations point to the definitions. Note that this can only
9103
1.07M
  // happen now, after the redeclaration chains have been fully wired.
9104
2.56k
  for (Decl *D : PendingDefinitions) {
9105
2.56k
    if (TagDecl *
TD2.56k
= dyn_cast<TagDecl>(D)) {
9106
139
      if (const TagType *
TagT139
= dyn_cast<TagType>(TD->getTypeForDecl())) {
9107
88
        // Make sure that the TagType points at the definition.
9108
88
        const_cast<TagType*>(TagT)->decl = TD;
9109
88
      }
9110
139
9111
139
      if (auto 
RD139
= dyn_cast<CXXRecordDecl>(D)) {
9112
446
        for (auto *R = getMostRecentExistingDecl(RD); R;
9113
307
             
R = R->getPreviousDecl()307
) {
9114
307
          assert((R == D) ==
9115
307
                     cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
9116
307
                 "declaration thinks it's the definition but it isn't");
9117
307
          cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
9118
307
        }
9119
139
      }
9120
139
9121
139
      continue;
9122
139
    }
9123
2.42k
9124
2.42k
    
if (auto 2.42k
ID2.42k
= dyn_cast<ObjCInterfaceDecl>(D)) {
9125
273
      // Make sure that the ObjCInterfaceType points at the definition.
9126
273
      const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9127
273
        ->Decl = ID;
9128
273
9129
613
      for (auto *R = getMostRecentExistingDecl(ID); 
R613
;
R = R->getPreviousDecl()340
)
9130
340
        cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9131
273
9132
273
      continue;
9133
273
    }
9134
2.14k
9135
2.14k
    
if (auto 2.14k
PD2.14k
= dyn_cast<ObjCProtocolDecl>(D)) {
9136
118
      for (auto *R = getMostRecentExistingDecl(PD); 
R118
;
R = R->getPreviousDecl()70
)
9137
70
        cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9138
48
9139
48
      continue;
9140
48
    }
9141
2.10k
9142
2.10k
    auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
9143
5.16k
    for (auto *R = getMostRecentExistingDecl(RTD); 
R5.16k
;
R = R->getPreviousDecl()3.06k
)
9144
3.06k
      cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
9145
2.56k
  }
9146
1.07M
  PendingDefinitions.clear();
9147
1.07M
9148
1.07M
  // Load the bodies of any functions or methods we've encountered. We do
9149
1.07M
  // this now (delayed) so that we can be sure that the declaration chains
9150
1.07M
  // have been fully wired up (hasBody relies on this).
9151
1.07M
  // FIXME: We shouldn't require complete redeclaration chains here.
9152
1.07M
  for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9153
1.07M
                               PBEnd = PendingBodies.end();
9154
1.07M
       
PB != PBEnd1.07M
;
++PB4.02k
) {
9155
4.02k
    if (FunctionDecl *
FD4.02k
= dyn_cast<FunctionDecl>(PB->first)) {
9156
3.99k
      // FIXME: Check for =delete/=default?
9157
3.99k
      // FIXME: Complain about ODR violations here?
9158
3.99k
      const FunctionDecl *Defn = nullptr;
9159
3.99k
      if (
!getContext().getLangOpts().Modules || 3.99k
!FD->hasBody(Defn)1.39k
) {
9160
3.61k
        FD->setLazyBody(PB->second);
9161
3.61k
      } else
9162
380
        mergeDefinitionVisibility(const_cast<FunctionDecl*>(Defn), FD);
9163
3.99k
      continue;
9164
3.99k
    }
9165
32
9166
32
    ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
9167
32
    if (
!getContext().getLangOpts().Modules || 32
!MD->hasBody()0
)
9168
32
      MD->setLazyBody(PB->second);
9169
4.02k
  }
9170
1.07M
  PendingBodies.clear();
9171
1.07M
9172
1.07M
  // Do some cleanup.
9173
1.07M
  for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9174
188
    getContext().deduplicateMergedDefinitonsFor(ND);
9175
1.07M
  PendingMergedDefinitionsToDeduplicate.clear();
9176
1.07M
}
9177
9178
1.07M
void ASTReader::diagnoseOdrViolations() {
9179
1.07M
  if (
PendingOdrMergeFailures.empty() && 1.07M
PendingOdrMergeChecks.empty()1.07M
)
9180
1.07M
    return;
9181
267
9182
267
  // Trigger the import of the full definition of each class that had any
9183
267
  // odr-merging problems, so we can produce better diagnostics for them.
9184
267
  // These updates may in turn find and diagnose some ODR failures, so take
9185
267
  // ownership of the set first.
9186
267
  auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
9187
267
  PendingOdrMergeFailures.clear();
9188
107
  for (auto &Merge : OdrMergeFailures) {
9189
107
    Merge.first->buildLookup();
9190
107
    Merge.first->decls_begin();
9191
107
    Merge.first->bases_begin();
9192
107
    Merge.first->vbases_begin();
9193
107
    for (auto *RD : Merge.second) {
9194
107
      RD->decls_begin();
9195
107
      RD->bases_begin();
9196
107
      RD->vbases_begin();
9197
107
    }
9198
107
  }
9199
267
9200
267
  // For each declaration from a merged context, check that the canonical
9201
267
  // definition of that context also contains a declaration of the same
9202
267
  // entity.
9203
267
  //
9204
267
  // Caution: this loop does things that might invalidate iterators into
9205
267
  // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
9206
543
  while (
!PendingOdrMergeChecks.empty()543
) {
9207
276
    NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
9208
276
9209
276
    // FIXME: Skip over implicit declarations for now. This matters for things
9210
276
    // like implicitly-declared special member functions. This isn't entirely
9211
276
    // correct; we can end up with multiple unmerged declarations of the same
9212
276
    // implicit entity.
9213
276
    if (D->isImplicit())
9214
150
      continue;
9215
126
9216
126
    DeclContext *CanonDef = D->getDeclContext();
9217
126
9218
126
    bool Found = false;
9219
126
    const Decl *DCanon = D->getCanonicalDecl();
9220
126
9221
166
    for (auto RI : D->redecls()) {
9222
166
      if (
RI->getLexicalDeclContext() == CanonDef166
) {
9223
35
        Found = true;
9224
35
        break;
9225
35
      }
9226
126
    }
9227
126
    if (Found)
9228
35
      continue;
9229
91
9230
91
    // Quick check failed, time to do the slow thing. Note, we can't just
9231
91
    // look up the name of D in CanonDef here, because the member that is
9232
91
    // in CanonDef might not be found by name lookup (it might have been
9233
91
    // replaced by a more recent declaration in the lookup table), and we
9234
91
    // can't necessarily find it in the redeclaration chain because it might
9235
91
    // be merely mergeable, not redeclarable.
9236
91
    llvm::SmallVector<const NamedDecl*, 4> Candidates;
9237
384
    for (auto *CanonMember : CanonDef->decls()) {
9238
384
      if (
CanonMember->getCanonicalDecl() == DCanon384
) {
9239
19
        // This can happen if the declaration is merely mergeable and not
9240
19
        // actually redeclarable (we looked for redeclarations earlier).
9241
19
        //
9242
19
        // FIXME: We should be able to detect this more efficiently, without
9243
19
        // pulling in all of the members of CanonDef.
9244
19
        Found = true;
9245
19
        break;
9246
19
      }
9247
365
      
if (auto *365
ND365
= dyn_cast<NamedDecl>(CanonMember))
9248
365
        
if (365
ND->getDeclName() == D->getDeclName()365
)
9249
78
          Candidates.push_back(ND);
9250
384
    }
9251
91
9252
91
    if (
!Found91
) {
9253
72
      // The AST doesn't like TagDecls becoming invalid after they've been
9254
72
      // completed. We only really need to mark FieldDecls as invalid here.
9255
72
      if (!isa<TagDecl>(D))
9256
72
        D->setInvalidDecl();
9257
72
9258
72
      // Ensure we don't accidentally recursively enter deserialization while
9259
72
      // we're producing our diagnostic.
9260
72
      Deserializing RecursionGuard(this);
9261
72
9262
72
      std::string CanonDefModule =
9263
72
          getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
9264
72
      Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9265
72
        << D << getOwningModuleNameForDiagnostic(D)
9266
72
        << CanonDef << CanonDefModule.empty() << CanonDefModule;
9267
72
9268
72
      if (Candidates.empty())
9269
10
        Diag(cast<Decl>(CanonDef)->getLocation(),
9270
10
             diag::note_module_odr_violation_no_possible_decls) << D;
9271
62
      else {
9272
140
        for (unsigned I = 0, N = Candidates.size(); 
I != N140
;
++I78
)
9273
78
          Diag(Candidates[I]->getLocation(),
9274
78
               diag::note_module_odr_violation_possible_decl)
9275
78
            << Candidates[I];
9276
62
      }
9277
72
9278
72
      DiagnosedOdrMergeFailures.insert(CanonDef);
9279
72
    }
9280
276
  }
9281
267
9282
267
  if (OdrMergeFailures.empty())
9283
160
    return;
9284
107
9285
107
  // Ensure we don't accidentally recursively enter deserialization while
9286
107
  // we're producing our diagnostics.
9287
107
  Deserializing RecursionGuard(this);
9288
107
9289
107
  // Issue any pending ODR-failure diagnostics.
9290
107
  for (auto &Merge : OdrMergeFailures) {
9291
107
    // If we've already pointed out a specific problem with this class, don't
9292
107
    // bother issuing a general "something's different" diagnostic.
9293
107
    if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
9294
27
      continue;
9295
80
9296
80
    bool Diagnosed = false;
9297
80
    CXXRecordDecl *FirstRecord = Merge.first;
9298
80
    std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
9299
80
    for (CXXRecordDecl *SecondRecord : Merge.second) {
9300
80
      // Multiple different declarations got merged together; tell the user
9301
80
      // where they came from.
9302
80
      if (FirstRecord == SecondRecord)
9303
0
        continue;
9304
80
9305
80
      std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
9306
80
      using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
9307
80
9308
80
      const ClassTemplateDecl *FirstTemplate =
9309
80
          FirstRecord->getDescribedClassTemplate();
9310
80
      const ClassTemplateDecl *SecondTemplate =
9311
80
          SecondRecord->getDescribedClassTemplate();
9312
80
9313
80
      assert(!FirstTemplate == !SecondTemplate &&
9314
80
             "Both pointers should be null or non-null");
9315
80
9316
80
      enum ODRTemplateDifference {
9317
80
        ParamEmptyName,
9318
80
        ParamName,
9319
80
        ParamSingleDefaultArgument,
9320
80
        ParamDifferentDefaultArgument,
9321
80
      };
9322
80
9323
80
      if (
FirstTemplate && 80
SecondTemplate12
) {
9324
12
        DeclHashes FirstTemplateHashes;
9325
12
        DeclHashes SecondTemplateHashes;
9326
12
        ODRHash Hash;
9327
12
9328
12
        auto PopulateTemplateParameterHashs =
9329
24
            [&Hash](DeclHashes &Hashes, const ClassTemplateDecl *TD) {
9330
26
              for (auto *D : TD->getTemplateParameters()->asArray()) {
9331
26
                Hash.clear();
9332
26
                Hash.AddSubDecl(D);
9333
26
                Hashes.emplace_back(D, Hash.CalculateHash());
9334
26
              }
9335
24
            };
9336
12
9337
12
        PopulateTemplateParameterHashs(FirstTemplateHashes, FirstTemplate);
9338
12
        PopulateTemplateParameterHashs(SecondTemplateHashes, SecondTemplate);
9339
12
9340
12
        assert(FirstTemplateHashes.size() == SecondTemplateHashes.size() &&
9341
12
               "Number of template parameters should be equal.");
9342
12
9343
12
        auto FirstIt = FirstTemplateHashes.begin();
9344
12
        auto FirstEnd = FirstTemplateHashes.end();
9345
12
        auto SecondIt = SecondTemplateHashes.begin();
9346
19
        for (; 
FirstIt != FirstEnd19
;
++FirstIt, ++SecondIt7
) {
9347
13
          if (FirstIt->second == SecondIt->second)
9348
7
            continue;
9349
6
9350
6
          auto ODRDiagError = [FirstRecord, &FirstModule,
9351
6
                               this](SourceLocation Loc, SourceRange Range,
9352
6
                                     ODRTemplateDifference DiffType) {
9353
6
            return Diag(Loc, diag::err_module_odr_violation_template_parameter)
9354
6
                   << FirstRecord << FirstModule.empty() << FirstModule << Range
9355
6
                   << DiffType;
9356
6
          };
9357
6
          auto ODRDiagNote = [&SecondModule,
9358
6
                              this](SourceLocation Loc, SourceRange Range,
9359
6
                                    ODRTemplateDifference DiffType) {
9360
6
            return Diag(Loc, diag::note_module_odr_violation_template_parameter)
9361
6
                   << SecondModule << Range << DiffType;
9362
6
          };
9363
6
9364
6
          const NamedDecl* FirstDecl = cast<NamedDecl>(FirstIt->first);
9365
6
          const NamedDecl* SecondDecl = cast<NamedDecl>(SecondIt->first);
9366
6
9367
6
          assert(FirstDecl->getKind() == SecondDecl->getKind() &&
9368
6
                 "Parameter Decl's should be the same kind.");
9369
6
9370
6
          DeclarationName FirstName = FirstDecl->getDeclName();
9371
6
          DeclarationName SecondName = SecondDecl->getDeclName();
9372
6
9373
6
          if (
FirstName != SecondName6
) {
9374
2
            const bool FirstNameEmpty =
9375
2
                FirstName.isIdentifier() && !FirstName.getAsIdentifierInfo();
9376
2
            const bool SecondNameEmpty =
9377
2
                SecondName.isIdentifier() && !SecondName.getAsIdentifierInfo();
9378
2
            assert((!FirstNameEmpty || !SecondNameEmpty) &&
9379
2
                   "Both template parameters cannot be unnamed.");
9380
2
            ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9381
2
                         FirstNameEmpty ? 
ParamEmptyName1
:
ParamName1
)
9382
2
                << FirstName;
9383
2
            ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9384
2
                        SecondNameEmpty ? 
ParamEmptyName0
:
ParamName2
)
9385
2
                << SecondName;
9386
2
            break;
9387
2
          }
9388
4
9389
4
          switch (FirstDecl->getKind()) {
9390
0
          default:
9391
0
            llvm_unreachable("Invalid template parameter type.");
9392
2
          case Decl::TemplateTypeParm: {
9393
2
            const auto *FirstParam = cast<TemplateTypeParmDecl>(FirstDecl);
9394
2
            const auto *SecondParam = cast<TemplateTypeParmDecl>(SecondDecl);
9395
2
            const bool HasFirstDefaultArgument =
9396
2
                FirstParam->hasDefaultArgument() &&
9397
1
                !FirstParam->defaultArgumentWasInherited();
9398
2
            const bool HasSecondDefaultArgument =
9399
2
                SecondParam->hasDefaultArgument() &&
9400
2
                !SecondParam->defaultArgumentWasInherited();
9401
2
9402
2
            if (
HasFirstDefaultArgument != HasSecondDefaultArgument2
) {
9403
1
              ODRDiagError(FirstDecl->getLocation(),
9404
1
                           FirstDecl->getSourceRange(),
9405
1
                           ParamSingleDefaultArgument)
9406
1
                  << HasFirstDefaultArgument;
9407
1
              ODRDiagNote(SecondDecl->getLocation(),
9408
1
                          SecondDecl->getSourceRange(),
9409
1
                          ParamSingleDefaultArgument)
9410
1
                  << HasSecondDefaultArgument;
9411
1
              break;
9412
1
            }
9413
1
9414
2
            assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9415
1
                   "Expecting default arguments.");
9416
1
9417
1
            ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9418
1
                         ParamDifferentDefaultArgument);
9419
1
            ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9420
1
                        ParamDifferentDefaultArgument);
9421
1
9422
1
            break;
9423
1
          }
9424
1
          case Decl::NonTypeTemplateParm: {
9425
1
            const auto *FirstParam = cast<NonTypeTemplateParmDecl>(FirstDecl);
9426
1
            const auto *SecondParam = cast<NonTypeTemplateParmDecl>(SecondDecl);
9427
1
            const bool HasFirstDefaultArgument =
9428
1
                FirstParam->hasDefaultArgument() &&
9429
1
                !FirstParam->defaultArgumentWasInherited();
9430
1
            const bool HasSecondDefaultArgument =
9431
1
                SecondParam->hasDefaultArgument() &&
9432
1
                !SecondParam->defaultArgumentWasInherited();
9433
1
9434
1
            if (
HasFirstDefaultArgument != HasSecondDefaultArgument1
) {
9435
1
              ODRDiagError(FirstDecl->getLocation(),
9436
1
                           FirstDecl->getSourceRange(),
9437
1
                           ParamSingleDefaultArgument)
9438
1
                  << HasFirstDefaultArgument;
9439
1
              ODRDiagNote(SecondDecl->getLocation(),
9440
1
                          SecondDecl->getSourceRange(),
9441
1
                          ParamSingleDefaultArgument)
9442
1
                  << HasSecondDefaultArgument;
9443
1
              break;
9444
1
            }
9445
0
9446
1
            assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9447
0
                   "Expecting default arguments.");
9448
0
9449
0
            ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9450
0
                         ParamDifferentDefaultArgument);
9451
0
            ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9452
0
                        ParamDifferentDefaultArgument);
9453
0
9454
0
            break;
9455
0
          }
9456
1
          case Decl::TemplateTemplateParm: {
9457
1
            const auto *FirstParam = cast<TemplateTemplateParmDecl>(FirstDecl);
9458
1
            const auto *SecondParam =
9459
1
                cast<TemplateTemplateParmDecl>(SecondDecl);
9460
1
            const bool HasFirstDefaultArgument =
9461
1
                FirstParam->hasDefaultArgument() &&
9462
1
                !FirstParam->defaultArgumentWasInherited();
9463
1
            const bool HasSecondDefaultArgument =
9464
1
                SecondParam->hasDefaultArgument() &&
9465
1
                !SecondParam->defaultArgumentWasInherited();
9466
1
9467
1
            if (
HasFirstDefaultArgument != HasSecondDefaultArgument1
) {
9468
0
              ODRDiagError(FirstDecl->getLocation(),
9469
0
                           FirstDecl->getSourceRange(),
9470
0
                           ParamSingleDefaultArgument)
9471
0
                  << HasFirstDefaultArgument;
9472
0
              ODRDiagNote(SecondDecl->getLocation(),
9473
0
                          SecondDecl->getSourceRange(),
9474
0
                          ParamSingleDefaultArgument)
9475
0
                  << HasSecondDefaultArgument;
9476
0
              break;
9477
0
            }
9478
1
9479
0
            assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9480
1
                   "Expecting default arguments.");
9481
1
9482
1
            ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9483
1
                         ParamDifferentDefaultArgument);
9484
1
            ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9485
1
                        ParamDifferentDefaultArgument);
9486
1
9487
1
            break;
9488
1
          }
9489
4
          }
9490
4
9491
4
          break;
9492
4
        }
9493
12
9494
12
        
if (12
FirstIt != FirstEnd12
) {
9495
6
          Diagnosed = true;
9496
6
          break;
9497
6
        }
9498
74
      }
9499
74
9500
74
      DeclHashes FirstHashes;
9501
74
      DeclHashes SecondHashes;
9502
74
      ODRHash Hash;
9503
74
9504
74
      auto PopulateHashes = [&Hash, FirstRecord](DeclHashes &Hashes,
9505
148
                                                 CXXRecordDecl *Record) {
9506
438
        for (auto *D : Record->decls()) {
9507
438
          // Due to decl merging, the first CXXRecordDecl is the parent of
9508
438
          // Decls in both records.
9509
438
          if (!ODRHash::isWhitelistedDecl(D, FirstRecord))
9510
177
            continue;
9511
261
          Hash.clear();
9512
261
          Hash.AddSubDecl(D);
9513
261
          Hashes.emplace_back(D, Hash.CalculateHash());
9514
261
        }
9515
148
      };
9516
74
      PopulateHashes(FirstHashes, FirstRecord);
9517
74
      PopulateHashes(SecondHashes, SecondRecord);
9518
74
9519
74
      // Used with err_module_odr_violation_mismatch_decl and
9520
74
      // note_module_odr_violation_mismatch_decl
9521
74
      // This list should be the same Decl's as in ODRHash::isWhiteListedDecl
9522
74
      enum {
9523
74
        EndOfClass,
9524
74
        PublicSpecifer,
9525
74
        PrivateSpecifer,
9526
74
        ProtectedSpecifer,
9527
74
        StaticAssert,
9528
74
        Field,
9529
74
        CXXMethod,
9530
74
        TypeAlias,
9531
74
        TypeDef,
9532
74
        Var,
9533
74
        Friend,
9534
74
        Other
9535
74
      } FirstDiffType = Other,
9536
74
        SecondDiffType = Other;
9537
74
9538
147
      auto DifferenceSelector = [](Decl *D) {
9539
147
        assert(D && "valid Decl required");
9540
147
        switch (D->getKind()) {
9541
0
        default:
9542
0
          return Other;
9543
25
        case Decl::AccessSpec:
9544
25
          switch (D->getAccess()) {
9545
12
          case AS_public:
9546
12
            return PublicSpecifer;
9547
12
          case AS_private:
9548
12
            return PrivateSpecifer;
9549
1
          case AS_protected:
9550
1
            return ProtectedSpecifer;
9551
0
          case AS_none:
9552
0
            break;
9553
0
          }
9554
0
          
llvm_unreachable0
("Invalid access specifier");
9555
7
        case Decl::StaticAssert:
9556
7
          return StaticAssert;
9557
41
        case Decl::Field:
9558
41
          return Field;
9559
39
        case Decl::CXXMethod:
9560
39
        case Decl::CXXConstructor:
9561
39
        case Decl::CXXDestructor:
9562
39
          return CXXMethod;
9563
9
        case Decl::TypeAlias:
9564
9
          return TypeAlias;
9565
5
        case Decl::Typedef:
9566
5
          return TypeDef;
9567
11
        case Decl::Var:
9568
11
          return Var;
9569
10
        case Decl::Friend:
9570
10
          return Friend;
9571
0
        }
9572
0
      };
9573
74
9574
74
      Decl *FirstDecl = nullptr;
9575
74
      Decl *SecondDecl = nullptr;
9576
74
      auto FirstIt = FirstHashes.begin();
9577
74
      auto SecondIt = SecondHashes.begin();
9578
74
9579
74
      // If there is a diagnoseable difference, FirstDiffType and
9580
74
      // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
9581
74
      // filled in if not EndOfClass.
9582
108
      while (
FirstIt != FirstHashes.end() || 108
SecondIt != SecondHashes.end()0
) {
9583
108
        if (
FirstIt != FirstHashes.end() && 108
SecondIt != SecondHashes.end()108
&&
9584
108
            
FirstIt->second == SecondIt->second107
) {
9585
34
          ++FirstIt;
9586
34
          ++SecondIt;
9587
34
          continue;
9588
34
        }
9589
74
9590
74
        
FirstDecl = FirstIt == FirstHashes.end() ? 74
nullptr0
:
FirstIt->first74
;
9591
74
        SecondDecl = SecondIt == SecondHashes.end() ? 
nullptr1
:
SecondIt->first73
;
9592
74
9593
74
        FirstDiffType = FirstDecl ? 
DifferenceSelector(FirstDecl)74
:
EndOfClass0
;
9594
74
        SecondDiffType =
9595
74
            SecondDecl ? 
DifferenceSelector(SecondDecl)73
:
EndOfClass1
;
9596
108
9597
108
        break;
9598
108
      }
9599
74
9600
74
      if (
FirstDiffType == Other || 74
SecondDiffType == Other74
) {
9601
0
        // Reaching this point means an unexpected Decl was encountered
9602
0
        // or no difference was detected.  This causes a generic error
9603
0
        // message to be emitted.
9604
0
        Diag(FirstRecord->getLocation(),
9605
0
             diag::err_module_odr_violation_different_definitions)
9606
0
            << FirstRecord << FirstModule.empty() << FirstModule;
9607
0
9608
0
        if (
FirstDecl0
) {
9609
0
          Diag(FirstDecl->getLocation(), diag::note_first_module_difference)
9610
0
              << FirstRecord << FirstDecl->getSourceRange();
9611
0
        }
9612
0
9613
0
        Diag(SecondRecord->getLocation(),
9614
0
             diag::note_module_odr_violation_different_definitions)
9615
0
            << SecondModule;
9616
0
9617
0
        if (
SecondDecl0
) {
9618
0
          Diag(SecondDecl->getLocation(), diag::note_second_module_difference)
9619
0
              << SecondDecl->getSourceRange();
9620
0
        }
9621
0
9622
0
        Diagnosed = true;
9623
0
        break;
9624
0
      }
9625
74
9626
74
      
if (74
FirstDiffType != SecondDiffType74
) {
9627
17
        SourceLocation FirstLoc;
9628
17
        SourceRange FirstRange;
9629
17
        if (
FirstDiffType == EndOfClass17
) {
9630
0
          FirstLoc = FirstRecord->getBraceRange().getEnd();
9631
17
        } else {
9632
17
          FirstLoc = FirstIt->first->getLocation();
9633
17
          FirstRange = FirstIt->first->getSourceRange();
9634
17
        }
9635
17
        Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
9636
17
            << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
9637
17
            << FirstDiffType;
9638
17
9639
17
        SourceLocation SecondLoc;
9640
17
        SourceRange SecondRange;
9641
17
        if (
SecondDiffType == EndOfClass17
) {
9642
1
          SecondLoc = SecondRecord->getBraceRange().getEnd();
9643
17
        } else {
9644
16
          SecondLoc = SecondDecl->getLocation();
9645
16
          SecondRange = SecondDecl->getSourceRange();
9646
16
        }
9647
17
        Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
9648
17
            << SecondModule << SecondRange << SecondDiffType;
9649
17
        Diagnosed = true;
9650
17
        break;
9651
17
      }
9652
57
9653
74
      assert(FirstDiffType == SecondDiffType);
9654
57
9655
57
      // Used with err_module_odr_violation_mismatch_decl_diff and
9656
57
      // note_module_odr_violation_mismatch_decl_diff
9657
57
      enum ODRDeclDifference{
9658
57
        StaticAssertCondition,
9659
57
        StaticAssertMessage,
9660
57
        StaticAssertOnlyMessage,
9661
57
        FieldName,
9662
57
        FieldTypeName,
9663
57
        FieldSingleBitField,
9664
57
        FieldDifferentWidthBitField,
9665
57
        FieldSingleMutable,
9666
57
        FieldSingleInitializer,
9667
57
        FieldDifferentInitializers,
9668
57
        MethodName,
9669
57
        MethodDeleted,
9670
57
        MethodVirtual,
9671
57
        MethodStatic,
9672
57
        MethodVolatile,
9673
57
        MethodConst,
9674
57
        MethodInline,
9675
57
        MethodNumberParameters,
9676
57
        MethodParameterType,
9677
57
        MethodParameterName,
9678
57
        MethodParameterSingleDefaultArgument,
9679
57
        MethodParameterDifferentDefaultArgument,
9680
57
        TypedefName,
9681
57
        TypedefType,
9682
57
        VarName,
9683
57
        VarType,
9684
57
        VarSingleInitializer,
9685
57
        VarDifferentInitializer,
9686
57
        VarConstexpr,
9687
57
        FriendTypeFunction,
9688
57
        FriendType,
9689
57
        FriendFunction,
9690
57
      };
9691
57
9692
57
      // These lambdas have the common portions of the ODR diagnostics.  This
9693
57
      // has the same return as Diag(), so addition parameters can be passed
9694
57
      // in with operator<<
9695
57
      auto ODRDiagError = [FirstRecord, &FirstModule, this](
9696
57
          SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9697
57
        return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
9698
57
               << FirstRecord << FirstModule.empty() << FirstModule << Range
9699
57
               << DiffType;
9700
57
      };
9701
57
      auto ODRDiagNote = [&SecondModule, this](
9702
57
          SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9703
57
        return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
9704
57
               << SecondModule << Range << DiffType;
9705
57
      };
9706
57
9707
22
      auto ComputeODRHash = [&Hash](const Stmt* S) {
9708
22
        assert(S);
9709
22
        Hash.clear();
9710
22
        Hash.AddStmt(S);
9711
22
        return Hash.CalculateHash();
9712
22
      };
9713
57
9714
56
      auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
9715
56
        Hash.clear();
9716
56
        Hash.AddQualType(Ty);
9717
56
        return Hash.CalculateHash();
9718
56
      };
9719
57
9720
57
      switch (FirstDiffType) {
9721
0
      case Other:
9722
0
      case EndOfClass:
9723
0
      case PublicSpecifer:
9724
0
      case PrivateSpecifer:
9725
0
      case ProtectedSpecifer:
9726
0
        llvm_unreachable("Invalid diff type");
9727
0
9728
3
      case StaticAssert: {
9729
3
        StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
9730
3
        StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
9731
3
9732
3
        Expr *FirstExpr = FirstSA->getAssertExpr();
9733
3
        Expr *SecondExpr = SecondSA->getAssertExpr();
9734
3
        unsigned FirstODRHash = ComputeODRHash(FirstExpr);
9735
3
        unsigned SecondODRHash = ComputeODRHash(SecondExpr);
9736
3
        if (
FirstODRHash != SecondODRHash3
) {
9737
1
          ODRDiagError(FirstExpr->getLocStart(), FirstExpr->getSourceRange(),
9738
1
                       StaticAssertCondition);
9739
1
          ODRDiagNote(SecondExpr->getLocStart(),
9740
1
                      SecondExpr->getSourceRange(), StaticAssertCondition);
9741
1
          Diagnosed = true;
9742
1
          break;
9743
1
        }
9744
2
9745
2
        StringLiteral *FirstStr = FirstSA->getMessage();
9746
2
        StringLiteral *SecondStr = SecondSA->getMessage();
9747
2
        assert((FirstStr || SecondStr) && "Both messages cannot be empty");
9748
2
        if (
(FirstStr && 2
!SecondStr1
) ||
(!FirstStr && 2
SecondStr1
)) {
9749
1
          SourceLocation FirstLoc, SecondLoc;
9750
1
          SourceRange FirstRange, SecondRange;
9751
1
          if (
FirstStr1
) {
9752
0
            FirstLoc = FirstStr->getLocStart();
9753
0
            FirstRange = FirstStr->getSourceRange();
9754
1
          } else {
9755
1
            FirstLoc = FirstSA->getLocStart();
9756
1
            FirstRange = FirstSA->getSourceRange();
9757
1
          }
9758
1
          if (
SecondStr1
) {
9759
1
            SecondLoc = SecondStr->getLocStart();
9760
1
            SecondRange = SecondStr->getSourceRange();
9761
1
          } else {
9762
0
            SecondLoc = SecondSA->getLocStart();
9763
0
            SecondRange = SecondSA->getSourceRange();
9764
0
          }
9765
1
          ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage)
9766
1
              << (FirstStr == nullptr);
9767
1
          ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage)
9768
1
              << (SecondStr == nullptr);
9769
1
          Diagnosed = true;
9770
1
          break;
9771
1
        }
9772
1
9773
1
        
if (1
FirstStr && 1
SecondStr1
&&
9774
1
            
FirstStr->getString() != SecondStr->getString()1
) {
9775
1
          ODRDiagError(FirstStr->getLocStart(), FirstStr->getSourceRange(),
9776
1
                       StaticAssertMessage);
9777
1
          ODRDiagNote(SecondStr->getLocStart(), SecondStr->getSourceRange(),
9778
1
                      StaticAssertMessage);
9779
1
          Diagnosed = true;
9780
1
          break;
9781
1
        }
9782
0
        break;
9783
0
      }
9784
19
      case Field: {
9785
19
        FieldDecl *FirstField = cast<FieldDecl>(FirstDecl);
9786
19
        FieldDecl *SecondField = cast<FieldDecl>(SecondDecl);
9787
19
        IdentifierInfo *FirstII = FirstField->getIdentifier();
9788
19
        IdentifierInfo *SecondII = SecondField->getIdentifier();
9789
19
        if (
FirstII->getName() != SecondII->getName()19
) {
9790
2
          ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9791
2
                       FieldName)
9792
2
              << FirstII;
9793
2
          ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9794
2
                      FieldName)
9795
2
              << SecondII;
9796
2
9797
2
          Diagnosed = true;
9798
2
          break;
9799
2
        }
9800
17
9801
19
        assert(getContext().hasSameType(FirstField->getType(),
9802
17
                                        SecondField->getType()));
9803
17
9804
17
        QualType FirstType = FirstField->getType();
9805
17
        QualType SecondType = SecondField->getType();
9806
17
        if (ComputeQualTypeODRHash(FirstType) !=
9807
17
            ComputeQualTypeODRHash(SecondType)) {
9808
9
          ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9809
9
                       FieldTypeName)
9810
9
              << FirstII << FirstType;
9811
9
          ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9812
9
                      FieldTypeName)
9813
9
              << SecondII << SecondType;
9814
9
9815
9
          Diagnosed = true;
9816
9
          break;
9817
9
        }
9818
8
9819
8
        const bool IsFirstBitField = FirstField->isBitField();
9820
8
        const bool IsSecondBitField = SecondField->isBitField();
9821
8
        if (
IsFirstBitField != IsSecondBitField8
) {
9822
1
          ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9823
1
                       FieldSingleBitField)
9824
1
              << FirstII << IsFirstBitField;
9825
1
          ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9826
1
                      FieldSingleBitField)
9827
1
              << SecondII << IsSecondBitField;
9828
1
          Diagnosed = true;
9829
1
          break;
9830
1
        }
9831
7
9832
7
        
if (7
IsFirstBitField && 7
IsSecondBitField2
) {
9833
2
          ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9834
2
                       FieldDifferentWidthBitField)
9835
2
              << FirstII << FirstField->getBitWidth()->getSourceRange();
9836
2
          ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9837
2
                      FieldDifferentWidthBitField)
9838
2
              << SecondII << SecondField->getBitWidth()->getSourceRange();
9839
2
          Diagnosed = true;
9840
2
          break;
9841
2
        }
9842
5
9843
5
        const bool IsFirstMutable = FirstField->isMutable();
9844
5
        const bool IsSecondMutable = SecondField->isMutable();
9845
5
        if (
IsFirstMutable != IsSecondMutable5
) {
9846
1
          ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9847
1
                       FieldSingleMutable)
9848
1
              << FirstII << IsFirstMutable;
9849
1
          ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9850
1
                      FieldSingleMutable)
9851
1
              << SecondII << IsSecondMutable;
9852
1
          Diagnosed = true;
9853
1
          break;
9854
1
        }
9855
4
9856
4
        const Expr *FirstInitializer = FirstField->getInClassInitializer();
9857
4
        const Expr *SecondInitializer = SecondField->getInClassInitializer();
9858
4
        if (
(!FirstInitializer && 4
SecondInitializer1
) ||
9859
4
            
(FirstInitializer && 3
!SecondInitializer3
)) {
9860
1
          ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9861
1
                       FieldSingleInitializer)
9862
1
              << FirstII << (FirstInitializer != nullptr);
9863
1
          ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9864
1
                      FieldSingleInitializer)
9865
1
              << SecondII << (SecondInitializer != nullptr);
9866
1
          Diagnosed = true;
9867
1
          break;
9868
1
        }
9869
3
9870
3
        
if (3
FirstInitializer && 3
SecondInitializer3
) {
9871
3
          unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
9872
3
          unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
9873
3
          if (
FirstInitHash != SecondInitHash3
) {
9874
3
            ODRDiagError(FirstField->getLocation(),
9875
3
                         FirstField->getSourceRange(),
9876
3
                         FieldDifferentInitializers)
9877
3
                << FirstII << FirstInitializer->getSourceRange();
9878
3
            ODRDiagNote(SecondField->getLocation(),
9879
3
                        SecondField->getSourceRange(),
9880
3
                        FieldDifferentInitializers)
9881
3
                << SecondII << SecondInitializer->getSourceRange();
9882
3
            Diagnosed = true;
9883
3
            break;
9884
3
          }
9885
0
        }
9886
0
9887
0
        break;
9888
0
      }
9889
19
      case CXXMethod: {
9890
19
        enum {
9891
19
          DiagMethod,
9892
19
          DiagConstructor,
9893
19
          DiagDestructor,
9894
19
        } FirstMethodType,
9895
19
            SecondMethodType;
9896
38
        auto GetMethodTypeForDiagnostics = [](const CXXMethodDecl* D) {
9897
38
          if (
isa<CXXConstructorDecl>(D)38
)
return DiagConstructor4
;
9898
34
          
if (34
isa<CXXDestructorDecl>(D)34
)
return DiagDestructor3
;
9899
31
          return DiagMethod;
9900
31
        };
9901
19
        const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
9902
19
        const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
9903
19
        FirstMethodType = GetMethodTypeForDiagnostics(FirstMethod);
9904
19
        SecondMethodType = GetMethodTypeForDiagnostics(SecondMethod);
9905
19
        auto FirstName = FirstMethod->getDeclName();
9906
19
        auto SecondName = SecondMethod->getDeclName();
9907
19
        if (
FirstMethodType != SecondMethodType || 19
FirstName != SecondName17
) {
9908
3
          ODRDiagError(FirstMethod->getLocation(),
9909
3
                       FirstMethod->getSourceRange(), MethodName)
9910
3
              << FirstMethodType << FirstName;
9911
3
          ODRDiagNote(SecondMethod->getLocation(),
9912
3
                      SecondMethod->getSourceRange(), MethodName)
9913
3
              << SecondMethodType << SecondName;
9914
3
9915
3
          Diagnosed = true;
9916
3
          break;
9917
3
        }
9918
16
9919
16
        const bool FirstDeleted = FirstMethod->isDeleted();
9920
16
        const bool SecondDeleted = SecondMethod->isDeleted();
9921
16
        if (
FirstDeleted != SecondDeleted16
) {
9922
0
          ODRDiagError(FirstMethod->getLocation(),
9923
0
                       FirstMethod->getSourceRange(), MethodDeleted)
9924
0
              << FirstMethodType << FirstName << FirstDeleted;
9925
0
9926
0
          ODRDiagNote(SecondMethod->getLocation(),
9927
0
                      SecondMethod->getSourceRange(), MethodDeleted)
9928
0
              << SecondMethodType << SecondName << SecondDeleted;
9929
0
          Diagnosed = true;
9930
0
          break;
9931
0
        }
9932
16
9933
16
        const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
9934
16
        const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
9935
16
        const bool FirstPure = FirstMethod->isPure();
9936
16
        const bool SecondPure = SecondMethod->isPure();
9937
16
        if (
(FirstVirtual || 16
SecondVirtual15
) &&
9938
16
            
(FirstVirtual != SecondVirtual || 3
FirstPure != SecondPure1
)) {
9939
3
          ODRDiagError(FirstMethod->getLocation(),
9940
3
                       FirstMethod->getSourceRange(), MethodVirtual)
9941
3
              << FirstMethodType << FirstName << FirstPure << FirstVirtual;
9942
3
          ODRDiagNote(SecondMethod->getLocation(),
9943
3
                      SecondMethod->getSourceRange(), MethodVirtual)
9944
3
              << SecondMethodType << SecondName << SecondPure << SecondVirtual;
9945
3
          Diagnosed = true;
9946
3
          break;
9947
3
        }
9948
13
9949
13
        // CXXMethodDecl::isStatic uses the canonical Decl.  With Decl merging,
9950
13
        // FirstDecl is the canonical Decl of SecondDecl, so the storage
9951
13
        // class needs to be checked instead.
9952
13
        const auto FirstStorage = FirstMethod->getStorageClass();
9953
13
        const auto SecondStorage = SecondMethod->getStorageClass();
9954
13
        const bool FirstStatic = FirstStorage == SC_Static;
9955
13
        const bool SecondStatic = SecondStorage == SC_Static;
9956
13
        if (
FirstStatic != SecondStatic13
) {
9957
1
          ODRDiagError(FirstMethod->getLocation(),
9958
1
                       FirstMethod->getSourceRange(), MethodStatic)
9959
1
              << FirstMethodType << FirstName << FirstStatic;
9960
1
          ODRDiagNote(SecondMethod->getLocation(),
9961
1
                      SecondMethod->getSourceRange(), MethodStatic)
9962
1
              << SecondMethodType << SecondName << SecondStatic;
9963
1
          Diagnosed = true;
9964
1
          break;
9965
1
        }
9966
12
9967
12
        const bool FirstVolatile = FirstMethod->isVolatile();
9968
12
        const bool SecondVolatile = SecondMethod->isVolatile();
9969
12
        if (
FirstVolatile != SecondVolatile12
) {
9970
1
          ODRDiagError(FirstMethod->getLocation(),
9971
1
                       FirstMethod->getSourceRange(), MethodVolatile)
9972
1
              << FirstMethodType << FirstName << FirstVolatile;
9973
1
          ODRDiagNote(SecondMethod->getLocation(),
9974
1
                      SecondMethod->getSourceRange(), MethodVolatile)
9975
1
              << SecondMethodType << SecondName << SecondVolatile;
9976
1
          Diagnosed = true;
9977
1
          break;
9978
1
        }
9979
11
9980
11
        const bool FirstConst = FirstMethod->isConst();
9981
11
        const bool SecondConst = SecondMethod->isConst();
9982
11
        if (
FirstConst != SecondConst11
) {
9983
1
          ODRDiagError(FirstMethod->getLocation(),
9984
1
                       FirstMethod->getSourceRange(), MethodConst)
9985
1
              << FirstMethodType << FirstName << FirstConst;
9986
1
          ODRDiagNote(SecondMethod->getLocation(),
9987
1
                      SecondMethod->getSourceRange(), MethodConst)
9988
1
              << SecondMethodType << SecondName << SecondConst;
9989
1
          Diagnosed = true;
9990
1
          break;
9991
1
        }
9992
10
9993
10
        const bool FirstInline = FirstMethod->isInlineSpecified();
9994
10
        const bool SecondInline = SecondMethod->isInlineSpecified();
9995
10
        if (
FirstInline != SecondInline10
) {
9996
1
          ODRDiagError(FirstMethod->getLocation(),
9997
1
                       FirstMethod->getSourceRange(), MethodInline)
9998
1
              << FirstMethodType << FirstName << FirstInline;
9999
1
          ODRDiagNote(SecondMethod->getLocation(),
10000
1
                      SecondMethod->getSourceRange(), MethodInline)
10001
1
              << SecondMethodType << SecondName << SecondInline;
10002
1
          Diagnosed = true;
10003
1
          break;
10004
1
        }
10005
9
10006
9
        const unsigned FirstNumParameters = FirstMethod->param_size();
10007
9
        const unsigned SecondNumParameters = SecondMethod->param_size();
10008
9
        if (
FirstNumParameters != SecondNumParameters9
) {
10009
2
          ODRDiagError(FirstMethod->getLocation(),
10010
2
                       FirstMethod->getSourceRange(), MethodNumberParameters)
10011
2
              << FirstMethodType << FirstName << FirstNumParameters;
10012
2
          ODRDiagNote(SecondMethod->getLocation(),
10013
2
                      SecondMethod->getSourceRange(), MethodNumberParameters)
10014
2
              << SecondMethodType << SecondName << SecondNumParameters;
10015
2
          Diagnosed = true;
10016
2
          break;
10017
2
        }
10018
7
10019
7
        // Need this status boolean to know when break out of the switch.
10020
7
        bool ParameterMismatch = false;
10021
7
        for (unsigned I = 0; 
I < FirstNumParameters7
;
++I0
) {
10022
7
          const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I);
10023
7
          const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I);
10024
7
10025
7
          QualType FirstParamType = FirstParam->getType();
10026
7
          QualType SecondParamType = SecondParam->getType();
10027
7
          if (FirstParamType != SecondParamType &&
10028
3
              ComputeQualTypeODRHash(FirstParamType) !=
10029
7
                  ComputeQualTypeODRHash(SecondParamType)) {
10030
2
            if (const DecayedType *ParamDecayedType =
10031
1
                    FirstParamType->getAs<DecayedType>()) {
10032
1
              ODRDiagError(FirstMethod->getLocation(),
10033
1
                           FirstMethod->getSourceRange(), MethodParameterType)
10034
1
                  << FirstMethodType << FirstName << (I + 1) << FirstParamType
10035
1
                  << true << ParamDecayedType->getOriginalType();
10036
2
            } else {
10037
1
              ODRDiagError(FirstMethod->getLocation(),
10038
1
                           FirstMethod->getSourceRange(), MethodParameterType)
10039
1
                  << FirstMethodType << FirstName << (I + 1) << FirstParamType
10040
1
                  << false;
10041
1
            }
10042
2
10043
2
            if (const DecayedType *ParamDecayedType =
10044
1
                    SecondParamType->getAs<DecayedType>()) {
10045
1
              ODRDiagNote(SecondMethod->getLocation(),
10046
1
                          SecondMethod->getSourceRange(), MethodParameterType)
10047
1
                  << SecondMethodType << SecondName << (I + 1)
10048
1
                  << SecondParamType << true
10049
1
                  << ParamDecayedType->getOriginalType();
10050
2
            } else {
10051
1
              ODRDiagNote(SecondMethod->getLocation(),
10052
1
                          SecondMethod->getSourceRange(), MethodParameterType)
10053
1
                  << SecondMethodType << SecondName << (I + 1)
10054
1
                  << SecondParamType << false;
10055
1
            }
10056
2
            ParameterMismatch = true;
10057
2
            break;
10058
2
          }
10059
5
10060
5
          DeclarationName FirstParamName = FirstParam->getDeclName();
10061
5
          DeclarationName SecondParamName = SecondParam->getDeclName();
10062
5
          if (
FirstParamName != SecondParamName5
) {
10063
1
            ODRDiagError(FirstMethod->getLocation(),
10064
1
                         FirstMethod->getSourceRange(), MethodParameterName)
10065
1
                << FirstMethodType << FirstName << (I + 1) << FirstParamName;
10066
1
            ODRDiagNote(SecondMethod->getLocation(),
10067
1
                        SecondMethod->getSourceRange(), MethodParameterName)
10068
1
                << SecondMethodType << SecondName << (I + 1) << SecondParamName;
10069
1
            ParameterMismatch = true;
10070
1
            break;
10071
1
          }
10072
4
10073
4
          const Expr *FirstInit = FirstParam->getInit();
10074
4
          const Expr *SecondInit = SecondParam->getInit();
10075
4
          if (
(FirstInit == nullptr) != (SecondInit == nullptr)4
) {
10076
1
            ODRDiagError(FirstMethod->getLocation(),
10077
1
                         FirstMethod->getSourceRange(),
10078
1
                         MethodParameterSingleDefaultArgument)
10079
1
                << FirstMethodType << FirstName << (I + 1)
10080
1
                << (FirstInit == nullptr)
10081
1
                << (FirstInit ? 
FirstInit->getSourceRange()1
:
SourceRange()0
);
10082
1
            ODRDiagNote(SecondMethod->getLocation(),
10083
1
                        SecondMethod->getSourceRange(),
10084
1
                        MethodParameterSingleDefaultArgument)
10085
1
                << SecondMethodType << SecondName << (I + 1)
10086
1
                << (SecondInit == nullptr)
10087
1
                << (SecondInit ? 
SecondInit->getSourceRange()0
:
SourceRange()1
);
10088
1
            ParameterMismatch = true;
10089
1
            break;
10090
1
          }
10091
3
10092
3
          
if (3
FirstInit && 3
SecondInit3
&&
10093
3
              
ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)3
) {
10094
3
            ODRDiagError(FirstMethod->getLocation(),
10095
3
                         FirstMethod->getSourceRange(),
10096
3
                         MethodParameterDifferentDefaultArgument)
10097
3
                << FirstMethodType << FirstName << (I + 1)
10098
3
                << FirstInit->getSourceRange();
10099
3
            ODRDiagNote(SecondMethod->getLocation(),
10100
3
                        SecondMethod->getSourceRange(),
10101
3
                        MethodParameterDifferentDefaultArgument)
10102
3
                << SecondMethodType << SecondName << (I + 1)
10103
3
                << SecondInit->getSourceRange();
10104
3
            ParameterMismatch = true;
10105
3
            break;
10106
3
10107
3
          }
10108
7
        }
10109
7
10110
7
        if (
ParameterMismatch7
) {
10111
7
          Diagnosed = true;
10112
7
          break;
10113
7
        }
10114
0
10115
0
        break;
10116
0
      }
10117
6
      case TypeAlias:
10118
6
      case TypeDef: {
10119
6
        TypedefNameDecl *FirstTD = cast<TypedefNameDecl>(FirstDecl);
10120
6
        TypedefNameDecl *SecondTD = cast<TypedefNameDecl>(SecondDecl);
10121
6
        auto FirstName = FirstTD->getDeclName();
10122
6
        auto SecondName = SecondTD->getDeclName();
10123
6
        if (
FirstName != SecondName6
) {
10124
2
          ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
10125
2
                       TypedefName)
10126
2
              << (FirstDiffType == TypeAlias) << FirstName;
10127
2
          ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
10128
2
                      TypedefName)
10129
2
              << (FirstDiffType == TypeAlias) << SecondName;
10130
2
          Diagnosed = true;
10131
2
          break;
10132
2
        }
10133
4
10134
4
        QualType FirstType = FirstTD->getUnderlyingType();
10135
4
        QualType SecondType = SecondTD->getUnderlyingType();
10136
4
        if (ComputeQualTypeODRHash(FirstType) !=
10137
4
            ComputeQualTypeODRHash(SecondType)) {
10138
4
          ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
10139
4
                       TypedefType)
10140
4
              << (FirstDiffType == TypeAlias) << FirstName << FirstType;
10141
4
          ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
10142
4
                      TypedefType)
10143
4
              << (FirstDiffType == TypeAlias) << SecondName << SecondType;
10144
4
          Diagnosed = true;
10145
4
          break;
10146
4
        }
10147
0
        break;
10148
0
      }
10149
5
      case Var: {
10150
5
        VarDecl *FirstVD = cast<VarDecl>(FirstDecl);
10151
5
        VarDecl *SecondVD = cast<VarDecl>(SecondDecl);
10152
5
        auto FirstName = FirstVD->getDeclName();
10153
5
        auto SecondName = SecondVD->getDeclName();
10154
5
        if (
FirstName != SecondName5
) {
10155
1
          ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10156
1
                       VarName)
10157
1
              << FirstName;
10158
1
          ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10159
1
                      VarName)
10160
1
              << SecondName;
10161
1
          Diagnosed = true;
10162
1
          break;
10163
1
        }
10164
4
10165
4
        QualType FirstType = FirstVD->getType();
10166
4
        QualType SecondType = SecondVD->getType();
10167
4
        if (ComputeQualTypeODRHash(FirstType) !=
10168
4
                        ComputeQualTypeODRHash(SecondType)) {
10169
1
          ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10170
1
                       VarType)
10171
1
              << FirstName << FirstType;
10172
1
          ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10173
1
                      VarType)
10174
1
              << SecondName << SecondType;
10175
1
          Diagnosed = true;
10176
1
          break;
10177
1
        }
10178
3
10179
3
        const Expr *FirstInit = FirstVD->getInit();
10180
3
        const Expr *SecondInit = SecondVD->getInit();
10181
3
        if (
(FirstInit == nullptr) != (SecondInit == nullptr)3
) {
10182
1
          ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10183
1
                       VarSingleInitializer)
10184
1
              << FirstName << (FirstInit == nullptr)
10185
1
              << (FirstInit ? 
FirstInit->getSourceRange()0
:
SourceRange()1
);
10186
1
          ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10187
1
                      VarSingleInitializer)
10188
1
              << SecondName << (SecondInit == nullptr)
10189
1
              << (SecondInit ? 
SecondInit->getSourceRange()1
:
SourceRange()0
);
10190
1
          Diagnosed = true;
10191
1
          break;
10192
1
        }
10193
2
10194
2
        
if (2
FirstInit && 2
SecondInit2
&&
10195
2
            
ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)2
) {
10196
1
          ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10197
1
                       VarDifferentInitializer)
10198
1
              << FirstName << FirstInit->getSourceRange();
10199
1
          ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10200
1
                      VarDifferentInitializer)
10201
1
              << SecondName << SecondInit->getSourceRange();
10202
1
          Diagnosed = true;
10203
1
          break;
10204
1
        }
10205
1
10206
1
        const bool FirstIsConstexpr = FirstVD->isConstexpr();
10207
1
        const bool SecondIsConstexpr = SecondVD->isConstexpr();
10208
1
        if (
FirstIsConstexpr != SecondIsConstexpr1
) {
10209
1
          ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10210
1
                       VarConstexpr)
10211
1
              << FirstName << FirstIsConstexpr;
10212
1
          ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10213
1
                      VarConstexpr)
10214
1
              << SecondName << SecondIsConstexpr;
10215
1
          Diagnosed = true;
10216
1
          break;
10217
1
        }
10218
0
        break;
10219
0
      }
10220
5
      case Friend: {
10221
5
        FriendDecl *FirstFriend = cast<FriendDecl>(FirstDecl);
10222
5
        FriendDecl *SecondFriend = cast<FriendDecl>(SecondDecl);
10223
5
10224
5
        NamedDecl *FirstND = FirstFriend->getFriendDecl();
10225
5
        NamedDecl *SecondND = SecondFriend->getFriendDecl();
10226
5
10227
5
        TypeSourceInfo *FirstTSI = FirstFriend->getFriendType();
10228
5
        TypeSourceInfo *SecondTSI = SecondFriend->getFriendType();
10229
5
10230
5
        if (
FirstND && 5
SecondND2
) {
10231
1
          ODRDiagError(FirstFriend->getFriendLoc(),
10232
1
                       FirstFriend->getSourceRange(), FriendFunction)
10233
1
              << FirstND;
10234
1
          ODRDiagNote(SecondFriend->getFriendLoc(),
10235
1
                      SecondFriend->getSourceRange(), FriendFunction)
10236
1
              << SecondND;
10237
1
10238
1
          Diagnosed = true;
10239
1
          break;
10240
1
        }
10241
4
10242
4
        
if (4
FirstTSI && 4
SecondTSI3
) {
10243
3
          QualType FirstFriendType = FirstTSI->getType();
10244
3
          QualType SecondFriendType = SecondTSI->getType();
10245
3
          assert(ComputeQualTypeODRHash(FirstFriendType) !=
10246
3
                 ComputeQualTypeODRHash(SecondFriendType));
10247
3
          ODRDiagError(FirstFriend->getFriendLoc(),
10248
3
                       FirstFriend->getSourceRange(), FriendType)
10249
3
              << FirstFriendType;
10250
3
          ODRDiagNote(SecondFriend->getFriendLoc(),
10251
3
                      SecondFriend->getSourceRange(), FriendType)
10252
3
              << SecondFriendType;
10253
3
          Diagnosed = true;
10254
3
          break;
10255
3
        }
10256
1
10257
1
        ODRDiagError(FirstFriend->getFriendLoc(), FirstFriend->getSourceRange(),
10258
1
                     FriendTypeFunction)
10259
1
            << (FirstTSI == nullptr);
10260
1
        ODRDiagNote(SecondFriend->getFriendLoc(),
10261
1
                    SecondFriend->getSourceRange(), FriendTypeFunction)
10262
1
            << (SecondTSI == nullptr);
10263
1
10264
1
        Diagnosed = true;
10265
1
        break;
10266
1
      }
10267
57
      }
10268
57
10269
57
      
if (57
Diagnosed == true57
)
10270
57
        continue;
10271
0
10272
0
      Diag(FirstDecl->getLocation(),
10273
0
           diag::err_module_odr_violation_mismatch_decl_unknown)
10274
0
          << FirstRecord << FirstModule.empty() << FirstModule << FirstDiffType
10275
0
          << FirstDecl->getSourceRange();
10276
0
      Diag(SecondDecl->getLocation(),
10277
0
           diag::note_module_odr_violation_mismatch_decl_unknown)
10278
0
          << SecondModule << FirstDiffType << SecondDecl->getSourceRange();
10279
0
      Diagnosed = true;
10280
0
    }
10281
80
10282
80
    
if (80
!Diagnosed80
) {
10283
0
      // All definitions are updates to the same declaration. This happens if a
10284
0
      // module instantiates the declaration of a class template specialization
10285
0
      // and two or more other modules instantiate its definition.
10286
0
      //
10287
0
      // FIXME: Indicate which modules had instantiations of this definition.
10288
0
      // FIXME: How can this even happen?
10289
0
      Diag(Merge.first->getLocation(),
10290
0
           diag::err_module_odr_violation_different_instantiations)
10291
0
        << Merge.first;
10292
0
    }
10293
107
  }
10294
1.07M
}
10295
10296
1.23M
void ASTReader::StartedDeserializing() {
10297
1.23M
  if (
++NumCurrentElementsDeserializing == 1 && 1.23M
ReadTimer.get()1.07M
)
10298
120
    ReadTimer->startTimer();
10299
1.23M
}
10300
10301
1.23M
void ASTReader::FinishedDeserializing() {
10302
1.23M
  assert(NumCurrentElementsDeserializing &&
10303
1.23M
         "FinishedDeserializing not paired with StartedDeserializing");
10304
1.23M
  if (
NumCurrentElementsDeserializing == 11.23M
) {
10305
1.07M
    // We decrease NumCurrentElementsDeserializing only after pending actions
10306
1.07M
    // are finished, to avoid recursively re-calling finishPendingActions().
10307
1.07M
    finishPendingActions();
10308
1.07M
  }
10309
1.23M
  --NumCurrentElementsDeserializing;
10310
1.23M
10311
1.23M
  if (
NumCurrentElementsDeserializing == 01.23M
) {
10312
1.07M
    // Propagate exception specification updates along redeclaration chains.
10313
1.07M
    while (
!PendingExceptionSpecUpdates.empty()1.07M
) {
10314
27
      auto Updates = std::move(PendingExceptionSpecUpdates);
10315
27
      PendingExceptionSpecUpdates.clear();
10316
29
      for (auto Update : Updates) {
10317
29
        ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
10318
29
        auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
10319
29
        auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
10320
29
        if (auto *Listener = getContext().getASTMutationListener())
10321
4
          Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
10322
29
        for (auto *Redecl : Update.second->redecls())
10323
56
          getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
10324
29
      }
10325
27
    }
10326
1.07M
10327
1.07M
    if (ReadTimer)
10328
120
      ReadTimer->stopTimer();
10329
1.07M
10330
1.07M
    diagnoseOdrViolations();
10331
1.07M
10332
1.07M
    // We are not in recursive loading, so it's safe to pass the "interesting"
10333
1.07M
    // decls to the consumer.
10334
1.07M
    if (Consumer)
10335
758k
      PassInterestingDeclsToConsumer();
10336
1.07M
  }
10337
1.23M
}
10338
10339
18.0k
void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
10340
18.0k
  if (IdentifierInfo *
II18.0k
= Name.getAsIdentifierInfo()) {
10341
18.0k
    // Remove any fake results before adding any real ones.
10342
18.0k
    auto It = PendingFakeLookupResults.find(II);
10343
18.0k
    if (
It != PendingFakeLookupResults.end()18.0k
) {
10344
5.89k
      for (auto *ND : It->second)
10345
5.84k
        SemaObj->IdResolver.RemoveDecl(ND);
10346
5.89k
      // FIXME: this works around module+PCH performance issue.
10347
5.89k
      // Rather than erase the result from the map, which is O(n), just clear
10348
5.89k
      // the vector of NamedDecls.
10349
5.89k
      It->second.clear();
10350
5.89k
    }
10351
18.0k
  }
10352
18.0k
10353
18.0k
  if (
SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && 18.0k
SemaObj->TUScope16.3k
) {
10354
10.7k
    SemaObj->TUScope->AddDecl(D);
10355
18.0k
  } else 
if (7.33k
SemaObj->TUScope7.33k
) {
10356
74
    // Adding the decl to IdResolver may have failed because it was already in
10357
74
    // (even though it was not added in scope). If it is already in, make sure
10358
74
    // it gets in the scope as well.
10359
74
    if (std::find(SemaObj->IdResolver.begin(Name),
10360
74
                  SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
10361
74
      SemaObj->TUScope->AddDecl(D);
10362
7.33k
  }
10363
18.0k
}
10364
10365
ASTReader::ASTReader(Preprocessor &PP, ASTContext *Context,
10366
                     const PCHContainerReader &PCHContainerRdr,
10367
                     ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
10368
                     StringRef isysroot, bool DisableValidation,
10369
                     bool AllowASTWithCompilerErrors,
10370
                     bool AllowConfigurationMismatch, bool ValidateSystemInputs,
10371
                     bool UseGlobalIndex,
10372
                     std::unique_ptr<llvm::Timer> ReadTimer)
10373
    : Listener(DisableValidation
10374
                   ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
10375
                   : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
10376
      SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
10377
      PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
10378
      ContextObj(Context),
10379
      ModuleMgr(PP.getFileManager(), PP.getPCMCache(), PCHContainerRdr,
10380
                PP.getHeaderSearchInfo()),
10381
      PCMCache(PP.getPCMCache()), DummyIdResolver(PP),
10382
      ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
10383
      DisableValidation(DisableValidation),
10384
      AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
10385
      AllowConfigurationMismatch(AllowConfigurationMismatch),
10386
      ValidateSystemInputs(ValidateSystemInputs),
10387
3.48k
      UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
10388
3.48k
  SourceMgr.setExternalSLocEntrySource(this);
10389
3.48k
10390
28
  for (const auto &Ext : Extensions) {
10391
28
    auto BlockName = Ext->getExtensionMetadata().BlockName;
10392
28
    auto Known = ModuleFileExtensions.find(BlockName);
10393
28
    if (
Known != ModuleFileExtensions.end()28
) {
10394
1
      Diags.Report(diag::warn_duplicate_module_file_extension)
10395
1
        << BlockName;
10396
1
      continue;
10397
1
    }
10398
27
10399
27
    ModuleFileExtensions.insert({BlockName, Ext});
10400
27
  }
10401
3.48k
}
10402
10403
3.42k
ASTReader::~ASTReader() {
10404
3.42k
  if (OwnsDeserializationListener)
10405
103
    delete DeserializationListener;
10406
3.42k
}
10407
10408
11.8k
IdentifierResolver &ASTReader::getIdResolver() {
10409
11.8k
  return SemaObj ? 
SemaObj->IdResolver11.7k
:
DummyIdResolver94
;
10410
11.8k
}
10411
10412
unsigned ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
10413
264k
                                     unsigned AbbrevID) {
10414
264k
  Idx = 0;
10415
264k
  Record.clear();
10416
264k
  return Cursor.readRecord(AbbrevID, Record);
10417
264k
}