clang 19.0.0git
ASTReader.cpp
Go to the documentation of this file.
1//===- ASTReader.cpp - AST File Reader ------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the ASTReader class, which reads AST files.
10//
11//===----------------------------------------------------------------------===//
12
13#include "ASTCommon.h"
14#include "ASTReaderInternals.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclBase.h"
23#include "clang/AST/DeclCXX.h"
25#include "clang/AST/DeclGroup.h"
26#include "clang/AST/DeclObjC.h"
29#include "clang/AST/Expr.h"
30#include "clang/AST/ExprCXX.h"
39#include "clang/AST/Type.h"
40#include "clang/AST/TypeLoc.h"
52#include "clang/Basic/LLVM.h"
54#include "clang/Basic/Module.h"
68#include "clang/Basic/Version.h"
71#include "clang/Lex/MacroInfo.h"
72#include "clang/Lex/ModuleMap.h"
76#include "clang/Lex/Token.h"
78#include "clang/Sema/Scope.h"
79#include "clang/Sema/Sema.h"
80#include "clang/Sema/SemaCUDA.h"
81#include "clang/Sema/Weak.h"
93#include "llvm/ADT/APFloat.h"
94#include "llvm/ADT/APInt.h"
95#include "llvm/ADT/APSInt.h"
96#include "llvm/ADT/ArrayRef.h"
97#include "llvm/ADT/DenseMap.h"
98#include "llvm/ADT/FloatingPointMode.h"
99#include "llvm/ADT/FoldingSet.h"
100#include "llvm/ADT/Hashing.h"
101#include "llvm/ADT/IntrusiveRefCntPtr.h"
102#include "llvm/ADT/STLExtras.h"
103#include "llvm/ADT/ScopeExit.h"
104#include "llvm/ADT/SmallPtrSet.h"
105#include "llvm/ADT/SmallString.h"
106#include "llvm/ADT/SmallVector.h"
107#include "llvm/ADT/StringExtras.h"
108#include "llvm/ADT/StringMap.h"
109#include "llvm/ADT/StringRef.h"
110#include "llvm/ADT/iterator_range.h"
111#include "llvm/Bitstream/BitstreamReader.h"
112#include "llvm/Support/Casting.h"
113#include "llvm/Support/Compiler.h"
114#include "llvm/Support/Compression.h"
115#include "llvm/Support/DJB.h"
116#include "llvm/Support/Endian.h"
117#include "llvm/Support/Error.h"
118#include "llvm/Support/ErrorHandling.h"
119#include "llvm/Support/FileSystem.h"
120#include "llvm/Support/LEB128.h"
121#include "llvm/Support/MemoryBuffer.h"
122#include "llvm/Support/Path.h"
123#include "llvm/Support/SaveAndRestore.h"
124#include "llvm/Support/TimeProfiler.h"
125#include "llvm/Support/Timer.h"
126#include "llvm/Support/VersionTuple.h"
127#include "llvm/Support/raw_ostream.h"
128#include "llvm/TargetParser/Triple.h"
129#include <algorithm>
130#include <cassert>
131#include <cstddef>
132#include <cstdint>
133#include <cstdio>
134#include <ctime>
135#include <iterator>
136#include <limits>
137#include <map>
138#include <memory>
139#include <optional>
140#include <string>
141#include <system_error>
142#include <tuple>
143#include <utility>
144#include <vector>
145
146using namespace clang;
147using namespace clang::serialization;
148using namespace clang::serialization::reader;
149using llvm::BitstreamCursor;
150
151//===----------------------------------------------------------------------===//
152// ChainedASTReaderListener implementation
153//===----------------------------------------------------------------------===//
154
155bool
157 return First->ReadFullVersionInformation(FullVersion) ||
158 Second->ReadFullVersionInformation(FullVersion);
159}
160
162 First->ReadModuleName(ModuleName);
163 Second->ReadModuleName(ModuleName);
164}
165
166void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
167 First->ReadModuleMapFile(ModuleMapPath);
168 Second->ReadModuleMapFile(ModuleMapPath);
169}
170
171bool
173 bool Complain,
174 bool AllowCompatibleDifferences) {
175 return First->ReadLanguageOptions(LangOpts, Complain,
176 AllowCompatibleDifferences) ||
177 Second->ReadLanguageOptions(LangOpts, Complain,
178 AllowCompatibleDifferences);
179}
180
182 const TargetOptions &TargetOpts, bool Complain,
183 bool AllowCompatibleDifferences) {
184 return First->ReadTargetOptions(TargetOpts, Complain,
185 AllowCompatibleDifferences) ||
186 Second->ReadTargetOptions(TargetOpts, Complain,
187 AllowCompatibleDifferences);
188}
189
191 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
192 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
193 Second->ReadDiagnosticOptions(DiagOpts, Complain);
194}
195
196bool
198 bool Complain) {
199 return First->ReadFileSystemOptions(FSOpts, Complain) ||
200 Second->ReadFileSystemOptions(FSOpts, Complain);
201}
202
204 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
205 bool Complain) {
206 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
207 Complain) ||
208 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
209 Complain);
210}
211
213 const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain,
214 std::string &SuggestedPredefines) {
215 return First->ReadPreprocessorOptions(PPOpts, ReadMacros, Complain,
216 SuggestedPredefines) ||
217 Second->ReadPreprocessorOptions(PPOpts, ReadMacros, Complain,
218 SuggestedPredefines);
219}
220
222 unsigned Value) {
223 First->ReadCounter(M, Value);
224 Second->ReadCounter(M, Value);
225}
226
228 return First->needsInputFileVisitation() ||
229 Second->needsInputFileVisitation();
230}
231
233 return First->needsSystemInputFileVisitation() ||
234 Second->needsSystemInputFileVisitation();
235}
236
238 ModuleKind Kind) {
239 First->visitModuleFile(Filename, Kind);
240 Second->visitModuleFile(Filename, Kind);
241}
242
244 bool isSystem,
245 bool isOverridden,
246 bool isExplicitModule) {
247 bool Continue = false;
248 if (First->needsInputFileVisitation() &&
249 (!isSystem || First->needsSystemInputFileVisitation()))
250 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
251 isExplicitModule);
252 if (Second->needsInputFileVisitation() &&
253 (!isSystem || Second->needsSystemInputFileVisitation()))
254 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
255 isExplicitModule);
256 return Continue;
257}
258
260 const ModuleFileExtensionMetadata &Metadata) {
261 First->readModuleFileExtension(Metadata);
262 Second->readModuleFileExtension(Metadata);
263}
264
265//===----------------------------------------------------------------------===//
266// PCH validator implementation
267//===----------------------------------------------------------------------===//
268
270
271/// Compare the given set of language options against an existing set of
272/// language options.
273///
274/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
275/// \param AllowCompatibleDifferences If true, differences between compatible
276/// language options will be permitted.
277///
278/// \returns true if the languagae options mis-match, false otherwise.
279static bool checkLanguageOptions(const LangOptions &LangOpts,
280 const LangOptions &ExistingLangOpts,
281 DiagnosticsEngine *Diags,
282 bool AllowCompatibleDifferences = true) {
283#define LANGOPT(Name, Bits, Default, Description) \
284 if (ExistingLangOpts.Name != LangOpts.Name) { \
285 if (Diags) { \
286 if (Bits == 1) \
287 Diags->Report(diag::err_pch_langopt_mismatch) \
288 << Description << LangOpts.Name << ExistingLangOpts.Name; \
289 else \
290 Diags->Report(diag::err_pch_langopt_value_mismatch) \
291 << Description; \
292 } \
293 return true; \
294 }
295
296#define VALUE_LANGOPT(Name, Bits, Default, Description) \
297 if (ExistingLangOpts.Name != LangOpts.Name) { \
298 if (Diags) \
299 Diags->Report(diag::err_pch_langopt_value_mismatch) \
300 << Description; \
301 return true; \
302 }
303
304#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
305 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
306 if (Diags) \
307 Diags->Report(diag::err_pch_langopt_value_mismatch) \
308 << Description; \
309 return true; \
310 }
311
312#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
313 if (!AllowCompatibleDifferences) \
314 LANGOPT(Name, Bits, Default, Description)
315
316#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
317 if (!AllowCompatibleDifferences) \
318 ENUM_LANGOPT(Name, Bits, Default, Description)
319
320#define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
321 if (!AllowCompatibleDifferences) \
322 VALUE_LANGOPT(Name, Bits, Default, Description)
323
324#define BENIGN_LANGOPT(Name, Bits, Default, Description)
325#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
326#define BENIGN_VALUE_LANGOPT(Name, Bits, Default, Description)
327#include "clang/Basic/LangOptions.def"
328
329 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
330 if (Diags)
331 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
332 return true;
333 }
334
335 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
336 if (Diags)
337 Diags->Report(diag::err_pch_langopt_value_mismatch)
338 << "target Objective-C runtime";
339 return true;
340 }
341
342 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
344 if (Diags)
345 Diags->Report(diag::err_pch_langopt_value_mismatch)
346 << "block command names";
347 return true;
348 }
349
350 // Sanitizer feature mismatches are treated as compatible differences. If
351 // compatible differences aren't allowed, we still only want to check for
352 // mismatches of non-modular sanitizers (the only ones which can affect AST
353 // generation).
354 if (!AllowCompatibleDifferences) {
355 SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
356 SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
357 SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
358 ExistingSanitizers.clear(ModularSanitizers);
359 ImportedSanitizers.clear(ModularSanitizers);
360 if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
361 const std::string Flag = "-fsanitize=";
362 if (Diags) {
363#define SANITIZER(NAME, ID) \
364 { \
365 bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \
366 bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \
367 if (InExistingModule != InImportedModule) \
368 Diags->Report(diag::err_pch_targetopt_feature_mismatch) \
369 << InExistingModule << (Flag + NAME); \
370 }
371#include "clang/Basic/Sanitizers.def"
372 }
373 return true;
374 }
375 }
376
377 return false;
378}
379
380/// Compare the given set of target options against an existing set of
381/// target options.
382///
383/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
384///
385/// \returns true if the target options mis-match, false otherwise.
386static bool checkTargetOptions(const TargetOptions &TargetOpts,
387 const TargetOptions &ExistingTargetOpts,
388 DiagnosticsEngine *Diags,
389 bool AllowCompatibleDifferences = true) {
390#define CHECK_TARGET_OPT(Field, Name) \
391 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
392 if (Diags) \
393 Diags->Report(diag::err_pch_targetopt_mismatch) \
394 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
395 return true; \
396 }
397
398 // The triple and ABI must match exactly.
399 CHECK_TARGET_OPT(Triple, "target");
400 CHECK_TARGET_OPT(ABI, "target ABI");
401
402 // We can tolerate different CPUs in many cases, notably when one CPU
403 // supports a strict superset of another. When allowing compatible
404 // differences skip this check.
405 if (!AllowCompatibleDifferences) {
406 CHECK_TARGET_OPT(CPU, "target CPU");
407 CHECK_TARGET_OPT(TuneCPU, "tune CPU");
408 }
409
410#undef CHECK_TARGET_OPT
411
412 // Compare feature sets.
413 SmallVector<StringRef, 4> ExistingFeatures(
414 ExistingTargetOpts.FeaturesAsWritten.begin(),
415 ExistingTargetOpts.FeaturesAsWritten.end());
416 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
417 TargetOpts.FeaturesAsWritten.end());
418 llvm::sort(ExistingFeatures);
419 llvm::sort(ReadFeatures);
420
421 // We compute the set difference in both directions explicitly so that we can
422 // diagnose the differences differently.
423 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
424 std::set_difference(
425 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
426 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
427 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
428 ExistingFeatures.begin(), ExistingFeatures.end(),
429 std::back_inserter(UnmatchedReadFeatures));
430
431 // If we are allowing compatible differences and the read feature set is
432 // a strict subset of the existing feature set, there is nothing to diagnose.
433 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
434 return false;
435
436 if (Diags) {
437 for (StringRef Feature : UnmatchedReadFeatures)
438 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
439 << /* is-existing-feature */ false << Feature;
440 for (StringRef Feature : UnmatchedExistingFeatures)
441 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
442 << /* is-existing-feature */ true << Feature;
443 }
444
445 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
446}
447
448bool
450 bool Complain,
451 bool AllowCompatibleDifferences) {
452 const LangOptions &ExistingLangOpts = PP.getLangOpts();
453 return checkLanguageOptions(LangOpts, ExistingLangOpts,
454 Complain ? &Reader.Diags : nullptr,
455 AllowCompatibleDifferences);
456}
457
459 bool Complain,
460 bool AllowCompatibleDifferences) {
461 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
462 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
463 Complain ? &Reader.Diags : nullptr,
464 AllowCompatibleDifferences);
465}
466
467namespace {
468
469using MacroDefinitionsMap =
470 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
471using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>;
472
473} // namespace
474
476 DiagnosticsEngine &Diags,
477 bool Complain) {
478 using Level = DiagnosticsEngine::Level;
479
480 // Check current mappings for new -Werror mappings, and the stored mappings
481 // for cases that were explicitly mapped to *not* be errors that are now
482 // errors because of options like -Werror.
483 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
484
485 for (DiagnosticsEngine *MappingSource : MappingSources) {
486 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
487 diag::kind DiagID = DiagIDMappingPair.first;
488 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
489 if (CurLevel < DiagnosticsEngine::Error)
490 continue; // not significant
491 Level StoredLevel =
492 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
493 if (StoredLevel < DiagnosticsEngine::Error) {
494 if (Complain)
495 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
496 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
497 return true;
498 }
499 }
500 }
501
502 return false;
503}
504
507 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
508 return true;
509 return Ext >= diag::Severity::Error;
510}
511
513 DiagnosticsEngine &Diags, bool IsSystem,
514 bool SystemHeaderWarningsInModule,
515 bool Complain) {
516 // Top-level options
517 if (IsSystem) {
518 if (Diags.getSuppressSystemWarnings())
519 return false;
520 // If -Wsystem-headers was not enabled before, and it was not explicit,
521 // be conservative
522 if (StoredDiags.getSuppressSystemWarnings() &&
523 !SystemHeaderWarningsInModule) {
524 if (Complain)
525 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
526 return true;
527 }
528 }
529
530 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
531 if (Complain)
532 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
533 return true;
534 }
535
536 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
537 !StoredDiags.getEnableAllWarnings()) {
538 if (Complain)
539 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
540 return true;
541 }
542
543 if (isExtHandlingFromDiagsError(Diags) &&
544 !isExtHandlingFromDiagsError(StoredDiags)) {
545 if (Complain)
546 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
547 return true;
548 }
549
550 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
551}
552
553/// Return the top import module if it is implicit, nullptr otherwise.
555 Preprocessor &PP) {
556 // If the original import came from a file explicitly generated by the user,
557 // don't check the diagnostic mappings.
558 // FIXME: currently this is approximated by checking whether this is not a
559 // module import of an implicitly-loaded module file.
560 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
561 // the transitive closure of its imports, since unrelated modules cannot be
562 // imported until after this module finishes validation.
563 ModuleFile *TopImport = &*ModuleMgr.rbegin();
564 while (!TopImport->ImportedBy.empty())
565 TopImport = TopImport->ImportedBy[0];
566 if (TopImport->Kind != MK_ImplicitModule)
567 return nullptr;
568
569 StringRef ModuleName = TopImport->ModuleName;
570 assert(!ModuleName.empty() && "diagnostic options read before module name");
571
572 Module *M =
573 PP.getHeaderSearchInfo().lookupModule(ModuleName, TopImport->ImportLoc);
574 assert(M && "missing module");
575 return M;
576}
577
579 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
580 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
583 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
584 // This should never fail, because we would have processed these options
585 // before writing them to an ASTFile.
586 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
587
588 ModuleManager &ModuleMgr = Reader.getModuleManager();
589 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
590
591 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
592 if (!TopM)
593 return false;
594
595 Module *Importer = PP.getCurrentModule();
596
597 DiagnosticOptions &ExistingOpts = ExistingDiags.getDiagnosticOptions();
598 bool SystemHeaderWarningsInModule =
599 Importer && llvm::is_contained(ExistingOpts.SystemHeaderWarningsModules,
600 Importer->Name);
601
602 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
603 // contains the union of their flags.
604 return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
605 SystemHeaderWarningsInModule, Complain);
606}
607
608/// Collect the macro definitions provided by the given preprocessor
609/// options.
610static void
612 MacroDefinitionsMap &Macros,
613 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
614 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
615 StringRef Macro = PPOpts.Macros[I].first;
616 bool IsUndef = PPOpts.Macros[I].second;
617
618 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
619 StringRef MacroName = MacroPair.first;
620 StringRef MacroBody = MacroPair.second;
621
622 // For an #undef'd macro, we only care about the name.
623 if (IsUndef) {
624 if (MacroNames && !Macros.count(MacroName))
625 MacroNames->push_back(MacroName);
626
627 Macros[MacroName] = std::make_pair("", true);
628 continue;
629 }
630
631 // For a #define'd macro, figure out the actual definition.
632 if (MacroName.size() == Macro.size())
633 MacroBody = "1";
634 else {
635 // Note: GCC drops anything following an end-of-line character.
636 StringRef::size_type End = MacroBody.find_first_of("\n\r");
637 MacroBody = MacroBody.substr(0, End);
638 }
639
640 if (MacroNames && !Macros.count(MacroName))
641 MacroNames->push_back(MacroName);
642 Macros[MacroName] = std::make_pair(MacroBody, false);
643 }
644}
645
650};
651
652/// Check the preprocessor options deserialized from the control block
653/// against the preprocessor options in an existing preprocessor.
654///
655/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
656/// \param Validation If set to OptionValidateNone, ignore differences in
657/// preprocessor options. If set to OptionValidateContradictions,
658/// require that options passed both in the AST file and on the command
659/// line (-D or -U) match, but tolerate options missing in one or the
660/// other. If set to OptionValidateContradictions, require that there
661/// are no differences in the options between the two.
663 const PreprocessorOptions &PPOpts,
664 const PreprocessorOptions &ExistingPPOpts, bool ReadMacros,
665 DiagnosticsEngine *Diags, FileManager &FileMgr,
666 std::string &SuggestedPredefines, const LangOptions &LangOpts,
668 if (ReadMacros) {
669 // Check macro definitions.
670 MacroDefinitionsMap ASTFileMacros;
671 collectMacroDefinitions(PPOpts, ASTFileMacros);
672 MacroDefinitionsMap ExistingMacros;
673 SmallVector<StringRef, 4> ExistingMacroNames;
674 collectMacroDefinitions(ExistingPPOpts, ExistingMacros,
675 &ExistingMacroNames);
676
677 // Use a line marker to enter the <command line> file, as the defines and
678 // undefines here will have come from the command line.
679 SuggestedPredefines += "# 1 \"<command line>\" 1\n";
680
681 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
682 // Dig out the macro definition in the existing preprocessor options.
683 StringRef MacroName = ExistingMacroNames[I];
684 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
685
686 // Check whether we know anything about this macro name or not.
687 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
688 ASTFileMacros.find(MacroName);
689 if (Validation == OptionValidateNone || Known == ASTFileMacros.end()) {
690 if (Validation == OptionValidateStrictMatches) {
691 // If strict matches are requested, don't tolerate any extra defines
692 // on the command line that are missing in the AST file.
693 if (Diags) {
694 Diags->Report(diag::err_pch_macro_def_undef) << MacroName << true;
695 }
696 return true;
697 }
698 // FIXME: Check whether this identifier was referenced anywhere in the
699 // AST file. If so, we should reject the AST file. Unfortunately, this
700 // information isn't in the control block. What shall we do about it?
701
702 if (Existing.second) {
703 SuggestedPredefines += "#undef ";
704 SuggestedPredefines += MacroName.str();
705 SuggestedPredefines += '\n';
706 } else {
707 SuggestedPredefines += "#define ";
708 SuggestedPredefines += MacroName.str();
709 SuggestedPredefines += ' ';
710 SuggestedPredefines += Existing.first.str();
711 SuggestedPredefines += '\n';
712 }
713 continue;
714 }
715
716 // If the macro was defined in one but undef'd in the other, we have a
717 // conflict.
718 if (Existing.second != Known->second.second) {
719 if (Diags) {
720 Diags->Report(diag::err_pch_macro_def_undef)
721 << MacroName << Known->second.second;
722 }
723 return true;
724 }
725
726 // If the macro was #undef'd in both, or if the macro bodies are
727 // identical, it's fine.
728 if (Existing.second || Existing.first == Known->second.first) {
729 ASTFileMacros.erase(Known);
730 continue;
731 }
732
733 // The macro bodies differ; complain.
734 if (Diags) {
735 Diags->Report(diag::err_pch_macro_def_conflict)
736 << MacroName << Known->second.first << Existing.first;
737 }
738 return true;
739 }
740
741 // Leave the <command line> file and return to <built-in>.
742 SuggestedPredefines += "# 1 \"<built-in>\" 2\n";
743
744 if (Validation == OptionValidateStrictMatches) {
745 // If strict matches are requested, don't tolerate any extra defines in
746 // the AST file that are missing on the command line.
747 for (const auto &MacroName : ASTFileMacros.keys()) {
748 if (Diags) {
749 Diags->Report(diag::err_pch_macro_def_undef) << MacroName << false;
750 }
751 return true;
752 }
753 }
754 }
755
756 // Check whether we're using predefines.
757 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines &&
758 Validation != OptionValidateNone) {
759 if (Diags) {
760 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
761 }
762 return true;
763 }
764
765 // Detailed record is important since it is used for the module cache hash.
766 if (LangOpts.Modules &&
767 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord &&
768 Validation != OptionValidateNone) {
769 if (Diags) {
770 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
771 }
772 return true;
773 }
774
775 // Compute the #include and #include_macros lines we need.
776 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
777 StringRef File = ExistingPPOpts.Includes[I];
778
779 if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&
780 !ExistingPPOpts.PCHThroughHeader.empty()) {
781 // In case the through header is an include, we must add all the includes
782 // to the predefines so the start point can be determined.
783 SuggestedPredefines += "#include \"";
784 SuggestedPredefines += File;
785 SuggestedPredefines += "\"\n";
786 continue;
787 }
788
789 if (File == ExistingPPOpts.ImplicitPCHInclude)
790 continue;
791
792 if (llvm::is_contained(PPOpts.Includes, File))
793 continue;
794
795 SuggestedPredefines += "#include \"";
796 SuggestedPredefines += File;
797 SuggestedPredefines += "\"\n";
798 }
799
800 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
801 StringRef File = ExistingPPOpts.MacroIncludes[I];
802 if (llvm::is_contained(PPOpts.MacroIncludes, File))
803 continue;
804
805 SuggestedPredefines += "#__include_macros \"";
806 SuggestedPredefines += File;
807 SuggestedPredefines += "\"\n##\n";
808 }
809
810 return false;
811}
812
814 bool ReadMacros, bool Complain,
815 std::string &SuggestedPredefines) {
816 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
817
819 PPOpts, ExistingPPOpts, ReadMacros, Complain ? &Reader.Diags : nullptr,
820 PP.getFileManager(), SuggestedPredefines, PP.getLangOpts());
821}
822
824 const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain,
825 std::string &SuggestedPredefines) {
826 return checkPreprocessorOptions(PPOpts, PP.getPreprocessorOpts(), ReadMacros,
827 nullptr, PP.getFileManager(),
828 SuggestedPredefines, PP.getLangOpts(),
830}
831
832/// Check the header search options deserialized from the control block
833/// against the header search options in an existing preprocessor.
834///
835/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
837 StringRef SpecificModuleCachePath,
838 StringRef ExistingModuleCachePath,
839 DiagnosticsEngine *Diags,
840 const LangOptions &LangOpts,
841 const PreprocessorOptions &PPOpts) {
842 if (LangOpts.Modules) {
843 if (SpecificModuleCachePath != ExistingModuleCachePath &&
845 if (Diags)
846 Diags->Report(diag::err_pch_modulecache_mismatch)
847 << SpecificModuleCachePath << ExistingModuleCachePath;
848 return true;
849 }
850 }
851
852 return false;
853}
854
856 StringRef SpecificModuleCachePath,
857 bool Complain) {
858 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
860 Complain ? &Reader.Diags : nullptr,
862}
863
866}
867
868//===----------------------------------------------------------------------===//
869// AST reader implementation
870//===----------------------------------------------------------------------===//
871
872static uint64_t readULEB(const unsigned char *&P) {
873 unsigned Length = 0;
874 const char *Error = nullptr;
875
876 uint64_t Val = llvm::decodeULEB128(P, &Length, nullptr, &Error);
877 if (Error)
878 llvm::report_fatal_error(Error);
879 P += Length;
880 return Val;
881}
882
883/// Read ULEB-encoded key length and data length.
884static std::pair<unsigned, unsigned>
885readULEBKeyDataLength(const unsigned char *&P) {
886 unsigned KeyLen = readULEB(P);
887 if ((unsigned)KeyLen != KeyLen)
888 llvm::report_fatal_error("key too large");
889
890 unsigned DataLen = readULEB(P);
891 if ((unsigned)DataLen != DataLen)
892 llvm::report_fatal_error("data too large");
893
894 return std::make_pair(KeyLen, DataLen);
895}
896
898 bool TakeOwnership) {
899 DeserializationListener = Listener;
900 OwnsDeserializationListener = TakeOwnership;
901}
902
904 return serialization::ComputeHash(Sel);
905}
906
907std::pair<unsigned, unsigned>
909 return readULEBKeyDataLength(d);
910}
911
913ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
914 using namespace llvm::support;
915
916 SelectorTable &SelTable = Reader.getContext().Selectors;
917 unsigned N = endian::readNext<uint16_t, llvm::endianness::little>(d);
918 const IdentifierInfo *FirstII = Reader.getLocalIdentifier(
919 F, endian::readNext<uint32_t, llvm::endianness::little>(d));
920 if (N == 0)
921 return SelTable.getNullarySelector(FirstII);
922 else if (N == 1)
923 return SelTable.getUnarySelector(FirstII);
924
926 Args.push_back(FirstII);
927 for (unsigned I = 1; I != N; ++I)
928 Args.push_back(Reader.getLocalIdentifier(
929 F, endian::readNext<uint32_t, llvm::endianness::little>(d)));
930
931 return SelTable.getSelector(N, Args.data());
932}
933
936 unsigned DataLen) {
937 using namespace llvm::support;
938
940
941 Result.ID = Reader.getGlobalSelectorID(
942 F, endian::readNext<uint32_t, llvm::endianness::little>(d));
943 unsigned FullInstanceBits =
944 endian::readNext<uint16_t, llvm::endianness::little>(d);
945 unsigned FullFactoryBits =
946 endian::readNext<uint16_t, llvm::endianness::little>(d);
947 Result.InstanceBits = FullInstanceBits & 0x3;
948 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
949 Result.FactoryBits = FullFactoryBits & 0x3;
950 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
951 unsigned NumInstanceMethods = FullInstanceBits >> 3;
952 unsigned NumFactoryMethods = FullFactoryBits >> 3;
953
954 // Load instance methods
955 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
956 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
957 F,
958 LocalDeclID(endian::readNext<DeclID, llvm::endianness::little>(d))))
959 Result.Instance.push_back(Method);
960 }
961
962 // Load factory methods
963 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
964 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
965 F,
966 LocalDeclID(endian::readNext<DeclID, llvm::endianness::little>(d))))
967 Result.Factory.push_back(Method);
968 }
969
970 return Result;
971}
972
974 return llvm::djbHash(a);
975}
976
977std::pair<unsigned, unsigned>
979 return readULEBKeyDataLength(d);
980}
981
983ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
984 assert(n >= 2 && d[n-1] == '\0');
985 return StringRef((const char*) d, n-1);
986}
987
988/// Whether the given identifier is "interesting".
989static bool isInterestingIdentifier(ASTReader &Reader, const IdentifierInfo &II,
990 bool IsModule) {
991 bool IsInteresting =
992 II.getNotableIdentifierID() != tok::NotableIdentifierKind::not_notable ||
994 II.getObjCKeywordID() != tok::ObjCKeywordKind::objc_not_keyword;
995 return II.hadMacroDefinition() || II.isPoisoned() ||
996 (!IsModule && IsInteresting) || II.hasRevertedTokenIDToIdentifier() ||
997 (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
998 II.getFETokenInfo());
999}
1000
1001static bool readBit(unsigned &Bits) {
1002 bool Value = Bits & 0x1;
1003 Bits >>= 1;
1004 return Value;
1005}
1006
1008 using namespace llvm::support;
1009
1010 unsigned RawID = endian::readNext<uint32_t, llvm::endianness::little>(d);
1011 return Reader.getGlobalIdentifierID(F, RawID >> 1);
1012}
1013
1015 if (!II.isFromAST()) {
1016 II.setIsFromAST();
1017 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
1018 if (isInterestingIdentifier(Reader, II, IsModule))
1020 }
1021}
1022
1024 const unsigned char* d,
1025 unsigned DataLen) {
1026 using namespace llvm::support;
1027
1028 unsigned RawID = endian::readNext<uint32_t, llvm::endianness::little>(d);
1029 bool IsInteresting = RawID & 0x01;
1030
1031 // Wipe out the "is interesting" bit.
1032 RawID = RawID >> 1;
1033
1034 // Build the IdentifierInfo and link the identifier ID with it.
1035 IdentifierInfo *II = KnownII;
1036 if (!II) {
1037 II = &Reader.getIdentifierTable().getOwn(k);
1038 KnownII = II;
1039 }
1040 markIdentifierFromAST(Reader, *II);
1041 Reader.markIdentifierUpToDate(II);
1042
1043 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
1044 if (!IsInteresting) {
1045 // For uninteresting identifiers, there's nothing else to do. Just notify
1046 // the reader that we've finished loading this identifier.
1047 Reader.SetIdentifierInfo(ID, II);
1048 return II;
1049 }
1050
1051 unsigned ObjCOrBuiltinID =
1052 endian::readNext<uint16_t, llvm::endianness::little>(d);
1053 unsigned Bits = endian::readNext<uint16_t, llvm::endianness::little>(d);
1054 bool CPlusPlusOperatorKeyword = readBit(Bits);
1055 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
1056 bool Poisoned = readBit(Bits);
1057 bool ExtensionToken = readBit(Bits);
1058 bool HadMacroDefinition = readBit(Bits);
1059
1060 assert(Bits == 0 && "Extra bits in the identifier?");
1061 DataLen -= 8;
1062
1063 // Set or check the various bits in the IdentifierInfo structure.
1064 // Token IDs are read-only.
1065 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
1067 if (!F.isModule())
1068 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
1069 assert(II->isExtensionToken() == ExtensionToken &&
1070 "Incorrect extension token flag");
1071 (void)ExtensionToken;
1072 if (Poisoned)
1073 II->setIsPoisoned(true);
1074 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
1075 "Incorrect C++ operator keyword flag");
1076 (void)CPlusPlusOperatorKeyword;
1077
1078 // If this identifier is a macro, deserialize the macro
1079 // definition.
1080 if (HadMacroDefinition) {
1081 uint32_t MacroDirectivesOffset =
1082 endian::readNext<uint32_t, llvm::endianness::little>(d);
1083 DataLen -= 4;
1084
1085 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
1086 }
1087
1088 Reader.SetIdentifierInfo(ID, II);
1089
1090 // Read all of the declarations visible at global scope with this
1091 // name.
1092 if (DataLen > 0) {
1094 for (; DataLen > 0; DataLen -= sizeof(DeclID))
1095 DeclIDs.push_back(Reader.getGlobalDeclID(
1096 F,
1097 LocalDeclID(endian::readNext<DeclID, llvm::endianness::little>(d))));
1098 Reader.SetGloballyVisibleDecls(II, DeclIDs);
1099 }
1100
1101 return II;
1102}
1103
1105 : Kind(Name.getNameKind()) {
1106 switch (Kind) {
1108 Data = (uint64_t)Name.getAsIdentifierInfo();
1109 break;
1113 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
1114 break;
1116 Data = Name.getCXXOverloadedOperator();
1117 break;
1119 Data = (uint64_t)Name.getCXXLiteralIdentifier();
1120 break;
1122 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1123 ->getDeclName().getAsIdentifierInfo();
1124 break;
1129 Data = 0;
1130 break;
1131 }
1132}
1133
1135 llvm::FoldingSetNodeID ID;
1136 ID.AddInteger(Kind);
1137
1138 switch (Kind) {
1142 ID.AddString(((IdentifierInfo*)Data)->getName());
1143 break;
1147 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1148 break;
1150 ID.AddInteger((OverloadedOperatorKind)Data);
1151 break;
1156 break;
1157 }
1158
1159 return ID.ComputeHash();
1160}
1161
1162ModuleFile *
1163ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
1164 using namespace llvm::support;
1165
1166 uint32_t ModuleFileID =
1167 endian::readNext<uint32_t, llvm::endianness::little>(d);
1168 return Reader.getLocalModuleFile(F, ModuleFileID);
1169}
1170
1171std::pair<unsigned, unsigned>
1172ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
1173 return readULEBKeyDataLength(d);
1174}
1175
1177ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1178 using namespace llvm::support;
1179
1180 auto Kind = (DeclarationName::NameKind)*d++;
1181 uint64_t Data;
1182 switch (Kind) {
1186 Data = (uint64_t)Reader.getLocalIdentifier(
1187 F, endian::readNext<uint32_t, llvm::endianness::little>(d));
1188 break;
1192 Data = (uint64_t)Reader
1193 .getLocalSelector(
1194 F, endian::readNext<uint32_t, llvm::endianness::little>(d))
1195 .getAsOpaquePtr();
1196 break;
1198 Data = *d++; // OverloadedOperatorKind
1199 break;
1204 Data = 0;
1205 break;
1206 }
1207
1208 return DeclarationNameKey(Kind, Data);
1209}
1210
1211void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1212 const unsigned char *d,
1213 unsigned DataLen,
1214 data_type_builder &Val) {
1215 using namespace llvm::support;
1216
1217 for (unsigned NumDecls = DataLen / sizeof(DeclID); NumDecls; --NumDecls) {
1218 LocalDeclID LocalID(endian::readNext<DeclID, llvm::endianness::little>(d));
1219 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1220 }
1221}
1222
1223bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1224 BitstreamCursor &Cursor,
1225 uint64_t Offset,
1226 DeclContext *DC) {
1227 assert(Offset != 0);
1228
1229 SavedStreamPosition SavedPosition(Cursor);
1230 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1231 Error(std::move(Err));
1232 return true;
1233 }
1234
1235 RecordData Record;
1236 StringRef Blob;
1237 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1238 if (!MaybeCode) {
1239 Error(MaybeCode.takeError());
1240 return true;
1241 }
1242 unsigned Code = MaybeCode.get();
1243
1244 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1245 if (!MaybeRecCode) {
1246 Error(MaybeRecCode.takeError());
1247 return true;
1248 }
1249 unsigned RecCode = MaybeRecCode.get();
1250 if (RecCode != DECL_CONTEXT_LEXICAL) {
1251 Error("Expected lexical block");
1252 return true;
1253 }
1254
1255 assert(!isa<TranslationUnitDecl>(DC) &&
1256 "expected a TU_UPDATE_LEXICAL record for TU");
1257 // If we are handling a C++ class template instantiation, we can see multiple
1258 // lexical updates for the same record. It's important that we select only one
1259 // of them, so that field numbering works properly. Just pick the first one we
1260 // see.
1261 auto &Lex = LexicalDecls[DC];
1262 if (!Lex.first) {
1263 Lex = std::make_pair(
1264 &M, llvm::ArrayRef(
1265 reinterpret_cast<const unalighed_decl_id_t *>(Blob.data()),
1266 Blob.size() / sizeof(DeclID)));
1267 }
1269 return false;
1270}
1271
1272bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1273 BitstreamCursor &Cursor,
1274 uint64_t Offset,
1275 GlobalDeclID ID) {
1276 assert(Offset != 0);
1277
1278 SavedStreamPosition SavedPosition(Cursor);
1279 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1280 Error(std::move(Err));
1281 return true;
1282 }
1283
1284 RecordData Record;
1285 StringRef Blob;
1286 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1287 if (!MaybeCode) {
1288 Error(MaybeCode.takeError());
1289 return true;
1290 }
1291 unsigned Code = MaybeCode.get();
1292
1293 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1294 if (!MaybeRecCode) {
1295 Error(MaybeRecCode.takeError());
1296 return true;
1297 }
1298 unsigned RecCode = MaybeRecCode.get();
1299 if (RecCode != DECL_CONTEXT_VISIBLE) {
1300 Error("Expected visible lookup table block");
1301 return true;
1302 }
1303
1304 // We can't safely determine the primary context yet, so delay attaching the
1305 // lookup table until we're done with recursive deserialization.
1306 auto *Data = (const unsigned char*)Blob.data();
1307 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
1308 return false;
1309}
1310
1311void ASTReader::Error(StringRef Msg) const {
1312 Error(diag::err_fe_pch_malformed, Msg);
1313 if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1314 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
1315 Diag(diag::note_module_cache_path)
1316 << PP.getHeaderSearchInfo().getModuleCachePath();
1317 }
1318}
1319
1320void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1321 StringRef Arg3) const {
1322 if (Diags.isDiagnosticInFlight())
1323 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2, Arg3);
1324 else
1325 Diag(DiagID) << Arg1 << Arg2 << Arg3;
1326}
1327
1328void ASTReader::Error(llvm::Error &&Err) const {
1329 llvm::Error RemainingErr =
1330 handleErrors(std::move(Err), [this](const DiagnosticError &E) {
1331 auto Diag = E.getDiagnostic().second;
1332
1333 // Ideally we'd just emit it, but have to handle a possible in-flight
1334 // diagnostic. Note that the location is currently ignored as well.
1335 auto NumArgs = Diag.getStorage()->NumDiagArgs;
1336 assert(NumArgs <= 3 && "Can only have up to 3 arguments");
1337 StringRef Arg1, Arg2, Arg3;
1338 switch (NumArgs) {
1339 case 3:
1340 Arg3 = Diag.getStringArg(2);
1341 [[fallthrough]];
1342 case 2:
1343 Arg2 = Diag.getStringArg(1);
1344 [[fallthrough]];
1345 case 1:
1346 Arg1 = Diag.getStringArg(0);
1347 }
1348 Error(Diag.getDiagID(), Arg1, Arg2, Arg3);
1349 });
1350 if (RemainingErr)
1351 Error(toString(std::move(RemainingErr)));
1352}
1353
1354//===----------------------------------------------------------------------===//
1355// Source Manager Deserialization
1356//===----------------------------------------------------------------------===//
1357
1358/// Read the line table in the source manager block.
1359void ASTReader::ParseLineTable(ModuleFile &F, const RecordData &Record) {
1360 unsigned Idx = 0;
1361 LineTableInfo &LineTable = SourceMgr.getLineTable();
1362
1363 // Parse the file names
1364 std::map<int, int> FileIDs;
1365 FileIDs[-1] = -1; // For unspecified filenames.
1366 for (unsigned I = 0; Record[Idx]; ++I) {
1367 // Extract the file name
1368 auto Filename = ReadPath(F, Record, Idx);
1369 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1370 }
1371 ++Idx;
1372
1373 // Parse the line entries
1374 std::vector<LineEntry> Entries;
1375 while (Idx < Record.size()) {
1376 FileID FID = ReadFileID(F, Record, Idx);
1377
1378 // Extract the line entries
1379 unsigned NumEntries = Record[Idx++];
1380 assert(NumEntries && "no line entries for file ID");
1381 Entries.clear();
1382 Entries.reserve(NumEntries);
1383 for (unsigned I = 0; I != NumEntries; ++I) {
1384 unsigned FileOffset = Record[Idx++];
1385 unsigned LineNo = Record[Idx++];
1386 int FilenameID = FileIDs[Record[Idx++]];
1389 unsigned IncludeOffset = Record[Idx++];
1390 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1391 FileKind, IncludeOffset));
1392 }
1393 LineTable.AddEntry(FID, Entries);
1394 }
1395}
1396
1397/// Read a source manager block
1398llvm::Error ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1399 using namespace SrcMgr;
1400
1401 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1402
1403 // Set the source-location entry cursor to the current position in
1404 // the stream. This cursor will be used to read the contents of the
1405 // source manager block initially, and then lazily read
1406 // source-location entries as needed.
1407 SLocEntryCursor = F.Stream;
1408
1409 // The stream itself is going to skip over the source manager block.
1410 if (llvm::Error Err = F.Stream.SkipBlock())
1411 return Err;
1412
1413 // Enter the source manager block.
1414 if (llvm::Error Err = SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID))
1415 return Err;
1416 F.SourceManagerBlockStartOffset = SLocEntryCursor.GetCurrentBitNo();
1417
1418 RecordData Record;
1419 while (true) {
1421 SLocEntryCursor.advanceSkippingSubblocks();
1422 if (!MaybeE)
1423 return MaybeE.takeError();
1424 llvm::BitstreamEntry E = MaybeE.get();
1425
1426 switch (E.Kind) {
1427 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1428 case llvm::BitstreamEntry::Error:
1429 return llvm::createStringError(std::errc::illegal_byte_sequence,
1430 "malformed block record in AST file");
1431 case llvm::BitstreamEntry::EndBlock:
1432 return llvm::Error::success();
1433 case llvm::BitstreamEntry::Record:
1434 // The interesting case.
1435 break;
1436 }
1437
1438 // Read a record.
1439 Record.clear();
1440 StringRef Blob;
1441 Expected<unsigned> MaybeRecord =
1442 SLocEntryCursor.readRecord(E.ID, Record, &Blob);
1443 if (!MaybeRecord)
1444 return MaybeRecord.takeError();
1445 switch (MaybeRecord.get()) {
1446 default: // Default behavior: ignore.
1447 break;
1448
1449 case SM_SLOC_FILE_ENTRY:
1452 // Once we hit one of the source location entries, we're done.
1453 return llvm::Error::success();
1454 }
1455 }
1456}
1457
1460 BitstreamCursor &Cursor = F->SLocEntryCursor;
1461 SavedStreamPosition SavedPosition(Cursor);
1462 if (llvm::Error Err = Cursor.JumpToBit(F->SLocEntryOffsetsBase +
1463 F->SLocEntryOffsets[Index]))
1464 return std::move(Err);
1465
1466 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
1467 if (!MaybeEntry)
1468 return MaybeEntry.takeError();
1469
1470 llvm::BitstreamEntry Entry = MaybeEntry.get();
1471 if (Entry.Kind != llvm::BitstreamEntry::Record)
1472 return llvm::createStringError(
1473 std::errc::illegal_byte_sequence,
1474 "incorrectly-formatted source location entry in AST file");
1475
1477 StringRef Blob;
1478 Expected<unsigned> MaybeSLOC = Cursor.readRecord(Entry.ID, Record, &Blob);
1479 if (!MaybeSLOC)
1480 return MaybeSLOC.takeError();
1481
1482 switch (MaybeSLOC.get()) {
1483 default:
1484 return llvm::createStringError(
1485 std::errc::illegal_byte_sequence,
1486 "incorrectly-formatted source location entry in AST file");
1487 case SM_SLOC_FILE_ENTRY:
1490 return F->SLocEntryBaseOffset + Record[0];
1491 }
1492}
1493
1495 auto SLocMapI =
1496 GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset - SLocOffset - 1);
1497 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
1498 "Corrupted global sloc offset map");
1499 ModuleFile *F = SLocMapI->second;
1500
1501 bool Invalid = false;
1502
1503 auto It = llvm::upper_bound(
1504 llvm::index_range(0, F->LocalNumSLocEntries), SLocOffset,
1505 [&](SourceLocation::UIntTy Offset, std::size_t LocalIndex) {
1506 int ID = F->SLocEntryBaseID + LocalIndex;
1507 std::size_t Index = -ID - 2;
1508 if (!SourceMgr.SLocEntryOffsetLoaded[Index]) {
1509 assert(!SourceMgr.SLocEntryLoaded[Index]);
1510 auto MaybeEntryOffset = readSLocOffset(F, LocalIndex);
1511 if (!MaybeEntryOffset) {
1512 Error(MaybeEntryOffset.takeError());
1513 Invalid = true;
1514 return true;
1515 }
1516 SourceMgr.LoadedSLocEntryTable[Index] =
1517 SrcMgr::SLocEntry::getOffsetOnly(*MaybeEntryOffset);
1518 SourceMgr.SLocEntryOffsetLoaded[Index] = true;
1519 }
1520 return Offset < SourceMgr.LoadedSLocEntryTable[Index].getOffset();
1521 });
1522
1523 if (Invalid)
1524 return 0;
1525
1526 // The iterator points to the first entry with start offset greater than the
1527 // offset of interest. The previous entry must contain the offset of interest.
1528 return F->SLocEntryBaseID + *std::prev(It);
1529}
1530
1532 if (ID == 0)
1533 return false;
1534
1535 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1536 Error("source location entry ID out-of-range for AST file");
1537 return true;
1538 }
1539
1540 // Local helper to read the (possibly-compressed) buffer data following the
1541 // entry record.
1542 auto ReadBuffer = [this](
1543 BitstreamCursor &SLocEntryCursor,
1544 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1546 StringRef Blob;
1547 Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();
1548 if (!MaybeCode) {
1549 Error(MaybeCode.takeError());
1550 return nullptr;
1551 }
1552 unsigned Code = MaybeCode.get();
1553
1554 Expected<unsigned> MaybeRecCode =
1555 SLocEntryCursor.readRecord(Code, Record, &Blob);
1556 if (!MaybeRecCode) {
1557 Error(MaybeRecCode.takeError());
1558 return nullptr;
1559 }
1560 unsigned RecCode = MaybeRecCode.get();
1561
1562 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1563 // Inspect the first byte to differentiate zlib (\x78) and zstd
1564 // (little-endian 0xFD2FB528).
1565 const llvm::compression::Format F =
1566 Blob.size() > 0 && Blob.data()[0] == 0x78
1567 ? llvm::compression::Format::Zlib
1568 : llvm::compression::Format::Zstd;
1569 if (const char *Reason = llvm::compression::getReasonIfUnsupported(F)) {
1570 Error(Reason);
1571 return nullptr;
1572 }
1573 SmallVector<uint8_t, 0> Decompressed;
1574 if (llvm::Error E = llvm::compression::decompress(
1575 F, llvm::arrayRefFromStringRef(Blob), Decompressed, Record[0])) {
1576 Error("could not decompress embedded file contents: " +
1577 llvm::toString(std::move(E)));
1578 return nullptr;
1579 }
1580 return llvm::MemoryBuffer::getMemBufferCopy(
1581 llvm::toStringRef(Decompressed), Name);
1582 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1583 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1584 } else {
1585 Error("AST record has invalid code");
1586 return nullptr;
1587 }
1588 };
1589
1590 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1591 if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(
1593 F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {
1594 Error(std::move(Err));
1595 return true;
1596 }
1597
1598 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1600
1601 ++NumSLocEntriesRead;
1602 Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();
1603 if (!MaybeEntry) {
1604 Error(MaybeEntry.takeError());
1605 return true;
1606 }
1607 llvm::BitstreamEntry Entry = MaybeEntry.get();
1608
1609 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1610 Error("incorrectly-formatted source location entry in AST file");
1611 return true;
1612 }
1613
1615 StringRef Blob;
1616 Expected<unsigned> MaybeSLOC =
1617 SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);
1618 if (!MaybeSLOC) {
1619 Error(MaybeSLOC.takeError());
1620 return true;
1621 }
1622 switch (MaybeSLOC.get()) {
1623 default:
1624 Error("incorrectly-formatted source location entry in AST file");
1625 return true;
1626
1627 case SM_SLOC_FILE_ENTRY: {
1628 // We will detect whether a file changed and return 'Failure' for it, but
1629 // we will also try to fail gracefully by setting up the SLocEntry.
1630 unsigned InputID = Record[4];
1631 InputFile IF = getInputFile(*F, InputID);
1633 bool OverriddenBuffer = IF.isOverridden();
1634
1635 // Note that we only check if a File was returned. If it was out-of-date
1636 // we have complained but we will continue creating a FileID to recover
1637 // gracefully.
1638 if (!File)
1639 return true;
1640
1641 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1642 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1643 // This is the module's main file.
1644 IncludeLoc = getImportLocation(F);
1645 }
1647 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1648 FileID FID = SourceMgr.createFileID(*File, IncludeLoc, FileCharacter, ID,
1649 BaseOffset + Record[0]);
1650 SrcMgr::FileInfo &FileInfo =
1651 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1652 FileInfo.NumCreatedFIDs = Record[5];
1653 if (Record[3])
1654 FileInfo.setHasLineDirectives();
1655
1656 unsigned NumFileDecls = Record[7];
1657 if (NumFileDecls && ContextObj) {
1658 const LocalDeclID *FirstDecl = F->FileSortedDecls + Record[6];
1659 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1660 FileDeclIDs[FID] =
1661 FileDeclsInfo(F, llvm::ArrayRef(FirstDecl, NumFileDecls));
1662 }
1663
1664 const SrcMgr::ContentCache &ContentCache =
1665 SourceMgr.getOrCreateContentCache(*File, isSystem(FileCharacter));
1666 if (OverriddenBuffer && !ContentCache.BufferOverridden &&
1667 ContentCache.ContentsEntry == ContentCache.OrigEntry &&
1668 !ContentCache.getBufferIfLoaded()) {
1669 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1670 if (!Buffer)
1671 return true;
1672 SourceMgr.overrideFileContents(*File, std::move(Buffer));
1673 }
1674
1675 break;
1676 }
1677
1678 case SM_SLOC_BUFFER_ENTRY: {
1679 const char *Name = Blob.data();
1680 unsigned Offset = Record[0];
1682 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1683 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1684 if (IncludeLoc.isInvalid() && F->isModule()) {
1685 IncludeLoc = getImportLocation(F);
1686 }
1687
1688 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1689 if (!Buffer)
1690 return true;
1691 FileID FID = SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
1692 BaseOffset + Offset, IncludeLoc);
1693 if (Record[3]) {
1694 auto &FileInfo =
1695 const_cast<SrcMgr::FileInfo &>(SourceMgr.getSLocEntry(FID).getFile());
1696 FileInfo.setHasLineDirectives();
1697 }
1698 break;
1699 }
1700
1703 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1], Seq);
1704 SourceLocation ExpansionBegin = ReadSourceLocation(*F, Record[2], Seq);
1705 SourceLocation ExpansionEnd = ReadSourceLocation(*F, Record[3], Seq);
1706 SourceMgr.createExpansionLoc(SpellingLoc, ExpansionBegin, ExpansionEnd,
1707 Record[5], Record[4], ID,
1708 BaseOffset + Record[0]);
1709 break;
1710 }
1711 }
1712
1713 return false;
1714}
1715
1716std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1717 if (ID == 0)
1718 return std::make_pair(SourceLocation(), "");
1719
1720 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1721 Error("source location entry ID out-of-range for AST file");
1722 return std::make_pair(SourceLocation(), "");
1723 }
1724
1725 // Find which module file this entry lands in.
1726 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1727 if (!M->isModule())
1728 return std::make_pair(SourceLocation(), "");
1729
1730 // FIXME: Can we map this down to a particular submodule? That would be
1731 // ideal.
1732 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
1733}
1734
1735/// Find the location where the module F is imported.
1736SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1737 if (F->ImportLoc.isValid())
1738 return F->ImportLoc;
1739
1740 // Otherwise we have a PCH. It's considered to be "imported" at the first
1741 // location of its includer.
1742 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1743 // Main file is the importer.
1744 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
1745 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
1746 }
1747 return F->ImportedBy[0]->FirstLoc;
1748}
1749
1750/// Enter a subblock of the specified BlockID with the specified cursor. Read
1751/// the abbreviations that are at the top of the block and then leave the cursor
1752/// pointing into the block.
1753llvm::Error ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor,
1754 unsigned BlockID,
1755 uint64_t *StartOfBlockOffset) {
1756 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID))
1757 return Err;
1758
1759 if (StartOfBlockOffset)
1760 *StartOfBlockOffset = Cursor.GetCurrentBitNo();
1761
1762 while (true) {
1763 uint64_t Offset = Cursor.GetCurrentBitNo();
1764 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1765 if (!MaybeCode)
1766 return MaybeCode.takeError();
1767 unsigned Code = MaybeCode.get();
1768
1769 // We expect all abbrevs to be at the start of the block.
1770 if (Code != llvm::bitc::DEFINE_ABBREV) {
1771 if (llvm::Error Err = Cursor.JumpToBit(Offset))
1772 return Err;
1773 return llvm::Error::success();
1774 }
1775 if (llvm::Error Err = Cursor.ReadAbbrevRecord())
1776 return Err;
1777 }
1778}
1779
1781 unsigned &Idx) {
1782 Token Tok;
1783 Tok.startToken();
1784 Tok.setLocation(ReadSourceLocation(M, Record, Idx));
1785 Tok.setKind((tok::TokenKind)Record[Idx++]);
1786 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1787
1788 if (Tok.isAnnotation()) {
1789 Tok.setAnnotationEndLoc(ReadSourceLocation(M, Record, Idx));
1790 switch (Tok.getKind()) {
1791 case tok::annot_pragma_loop_hint: {
1792 auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
1793 Info->PragmaName = ReadToken(M, Record, Idx);
1794 Info->Option = ReadToken(M, Record, Idx);
1795 unsigned NumTokens = Record[Idx++];
1797 Toks.reserve(NumTokens);
1798 for (unsigned I = 0; I < NumTokens; ++I)
1799 Toks.push_back(ReadToken(M, Record, Idx));
1800 Info->Toks = llvm::ArrayRef(Toks).copy(PP.getPreprocessorAllocator());
1801 Tok.setAnnotationValue(static_cast<void *>(Info));
1802 break;
1803 }
1804 case tok::annot_pragma_pack: {
1805 auto *Info = new (PP.getPreprocessorAllocator()) Sema::PragmaPackInfo;
1806 Info->Action = static_cast<Sema::PragmaMsStackAction>(Record[Idx++]);
1807 auto SlotLabel = ReadString(Record, Idx);
1808 Info->SlotLabel =
1809 llvm::StringRef(SlotLabel).copy(PP.getPreprocessorAllocator());
1810 Info->Alignment = ReadToken(M, Record, Idx);
1811 Tok.setAnnotationValue(static_cast<void *>(Info));
1812 break;
1813 }
1814 // Some annotation tokens do not use the PtrData field.
1815 case tok::annot_pragma_openmp:
1816 case tok::annot_pragma_openmp_end:
1817 case tok::annot_pragma_unused:
1818 case tok::annot_pragma_openacc:
1819 case tok::annot_pragma_openacc_end:
1820 break;
1821 default:
1822 llvm_unreachable("missing deserialization code for annotation token");
1823 }
1824 } else {
1825 Tok.setLength(Record[Idx++]);
1826 if (IdentifierInfo *II = getLocalIdentifier(M, Record[Idx++]))
1827 Tok.setIdentifierInfo(II);
1828 }
1829 return Tok;
1830}
1831
1833 BitstreamCursor &Stream = F.MacroCursor;
1834
1835 // Keep track of where we are in the stream, then jump back there
1836 // after reading this macro.
1837 SavedStreamPosition SavedPosition(Stream);
1838
1839 if (llvm::Error Err = Stream.JumpToBit(Offset)) {
1840 // FIXME this drops errors on the floor.
1841 consumeError(std::move(Err));
1842 return nullptr;
1843 }
1846 MacroInfo *Macro = nullptr;
1847 llvm::MutableArrayRef<Token> MacroTokens;
1848
1849 while (true) {
1850 // Advance to the next record, but if we get to the end of the block, don't
1851 // pop it (removing all the abbreviations from the cursor) since we want to
1852 // be able to reseek within the block and read entries.
1853 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
1855 Stream.advanceSkippingSubblocks(Flags);
1856 if (!MaybeEntry) {
1857 Error(MaybeEntry.takeError());
1858 return Macro;
1859 }
1860 llvm::BitstreamEntry Entry = MaybeEntry.get();
1861
1862 switch (Entry.Kind) {
1863 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1864 case llvm::BitstreamEntry::Error:
1865 Error("malformed block record in AST file");
1866 return Macro;
1867 case llvm::BitstreamEntry::EndBlock:
1868 return Macro;
1869 case llvm::BitstreamEntry::Record:
1870 // The interesting case.
1871 break;
1872 }
1873
1874 // Read a record.
1875 Record.clear();
1877 if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
1878 RecType = (PreprocessorRecordTypes)MaybeRecType.get();
1879 else {
1880 Error(MaybeRecType.takeError());
1881 return Macro;
1882 }
1883 switch (RecType) {
1884 case PP_MODULE_MACRO:
1886 return Macro;
1887
1890 // If we already have a macro, that means that we've hit the end
1891 // of the definition of the macro we were looking for. We're
1892 // done.
1893 if (Macro)
1894 return Macro;
1895
1896 unsigned NextIndex = 1; // Skip identifier ID.
1897 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
1898 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
1899 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
1900 MI->setIsUsed(Record[NextIndex++]);
1901 MI->setUsedForHeaderGuard(Record[NextIndex++]);
1902 MacroTokens = MI->allocateTokens(Record[NextIndex++],
1903 PP.getPreprocessorAllocator());
1904 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1905 // Decode function-like macro info.
1906 bool isC99VarArgs = Record[NextIndex++];
1907 bool isGNUVarArgs = Record[NextIndex++];
1908 bool hasCommaPasting = Record[NextIndex++];
1909 MacroParams.clear();
1910 unsigned NumArgs = Record[NextIndex++];
1911 for (unsigned i = 0; i != NumArgs; ++i)
1912 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1913
1914 // Install function-like macro info.
1915 MI->setIsFunctionLike();
1916 if (isC99VarArgs) MI->setIsC99Varargs();
1917 if (isGNUVarArgs) MI->setIsGNUVarargs();
1918 if (hasCommaPasting) MI->setHasCommaPasting();
1919 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
1920 }
1921
1922 // Remember that we saw this macro last so that we add the tokens that
1923 // form its body to it.
1924 Macro = MI;
1925
1926 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1927 Record[NextIndex]) {
1928 // We have a macro definition. Register the association
1930 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1931 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
1932 PreprocessingRecord::PPEntityID PPID =
1933 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1934 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1935 PPRec.getPreprocessedEntity(PPID));
1936 if (PPDef)
1937 PPRec.RegisterMacroDefinition(Macro, PPDef);
1938 }
1939
1940 ++NumMacrosRead;
1941 break;
1942 }
1943
1944 case PP_TOKEN: {
1945 // If we see a TOKEN before a PP_MACRO_*, then the file is
1946 // erroneous, just pretend we didn't see this.
1947 if (!Macro) break;
1948 if (MacroTokens.empty()) {
1949 Error("unexpected number of macro tokens for a macro in AST file");
1950 return Macro;
1951 }
1952
1953 unsigned Idx = 0;
1954 MacroTokens[0] = ReadToken(F, Record, Idx);
1955 MacroTokens = MacroTokens.drop_front();
1956 break;
1957 }
1958 }
1959 }
1960}
1961
1964 unsigned LocalID) const {
1965 if (!M.ModuleOffsetMap.empty())
1966 ReadModuleOffsetMap(M);
1967
1970 assert(I != M.PreprocessedEntityRemap.end()
1971 && "Invalid index into preprocessed entity index remap");
1972
1973 return LocalID + I->second;
1974}
1975
1976const FileEntry *HeaderFileInfoTrait::getFile(const internal_key_type &Key) {
1977 FileManager &FileMgr = Reader.getFileManager();
1978 if (!Key.Imported) {
1979 if (auto File = FileMgr.getFile(Key.Filename))
1980 return *File;
1981 return nullptr;
1982 }
1983
1984 std::string Resolved = std::string(Key.Filename);
1985 Reader.ResolveImportedPath(M, Resolved);
1986 if (auto File = FileMgr.getFile(Resolved))
1987 return *File;
1988 return nullptr;
1989}
1990
1991unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1992 return llvm::hash_combine(ikey.Size, ikey.ModTime);
1993}
1994
1996HeaderFileInfoTrait::GetInternalKey(external_key_type ekey) {
1997 internal_key_type ikey = {ekey.getSize(),
1998 M.HasTimestamps ? ekey.getModificationTime() : 0,
1999 ekey.getName(), /*Imported*/ false};
2000 return ikey;
2001}
2002
2003bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
2004 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
2005 return false;
2006
2007 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
2008 return true;
2009
2010 // Determine whether the actual files are equivalent.
2011 const FileEntry *FEA = getFile(a);
2012 const FileEntry *FEB = getFile(b);
2013 return FEA && FEA == FEB;
2014}
2015
2016std::pair<unsigned, unsigned>
2017HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
2018 return readULEBKeyDataLength(d);
2019}
2020
2022HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
2023 using namespace llvm::support;
2024
2025 internal_key_type ikey;
2026 ikey.Size = off_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2027 ikey.ModTime =
2028 time_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2029 ikey.Filename = (const char *)d;
2030 ikey.Imported = true;
2031 return ikey;
2032}
2033
2035HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
2036 unsigned DataLen) {
2037 using namespace llvm::support;
2038
2039 const unsigned char *End = d + DataLen;
2040 HeaderFileInfo HFI;
2041 unsigned Flags = *d++;
2042
2043 bool Included = (Flags >> 6) & 0x01;
2044 if (Included)
2045 if (const FileEntry *FE = getFile(key))
2046 // Not using \c Preprocessor::markIncluded(), since that would attempt to
2047 // deserialize this header file info again.
2048 Reader.getPreprocessor().getIncludedFiles().insert(FE);
2049
2050 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
2051 HFI.isImport |= (Flags >> 5) & 0x01;
2052 HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
2053 HFI.DirInfo = (Flags >> 1) & 0x07;
2054 HFI.IndexHeaderMapHeader = Flags & 0x01;
2055 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
2056 M, endian::readNext<uint32_t, llvm::endianness::little>(d));
2057 if (unsigned FrameworkOffset =
2058 endian::readNext<uint32_t, llvm::endianness::little>(d)) {
2059 // The framework offset is 1 greater than the actual offset,
2060 // since 0 is used as an indicator for "no framework name".
2061 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
2062 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
2063 }
2064
2065 assert((End - d) % 4 == 0 &&
2066 "Wrong data length in HeaderFileInfo deserialization");
2067 while (d != End) {
2068 uint32_t LocalSMID =
2069 endian::readNext<uint32_t, llvm::endianness::little>(d);
2070 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 7);
2071 LocalSMID >>= 3;
2072
2073 // This header is part of a module. Associate it with the module to enable
2074 // implicit module import.
2075 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
2076 Module *Mod = Reader.getSubmodule(GlobalSMID);
2077 FileManager &FileMgr = Reader.getFileManager();
2078 ModuleMap &ModMap =
2079 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
2080
2081 std::string Filename = std::string(key.Filename);
2082 if (key.Imported)
2083 Reader.ResolveImportedPath(M, Filename);
2084 if (auto FE = FileMgr.getOptionalFileRef(Filename)) {
2085 // FIXME: NameAsWritten
2086 Module::Header H = {std::string(key.Filename), "", *FE};
2087 ModMap.addHeader(Mod, H, HeaderRole, /*Imported=*/true);
2088 }
2089 HFI.mergeModuleMembership(HeaderRole);
2090 }
2091
2092 // This HeaderFileInfo was externally loaded.
2093 HFI.External = true;
2094 HFI.IsValid = true;
2095 return HFI;
2096}
2097
2099 uint32_t MacroDirectivesOffset) {
2100 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
2101 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
2102}
2103
2105 // Note that we are loading defined macros.
2106 Deserializing Macros(this);
2107
2108 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
2109 BitstreamCursor &MacroCursor = I.MacroCursor;
2110
2111 // If there was no preprocessor block, skip this file.
2112 if (MacroCursor.getBitcodeBytes().empty())
2113 continue;
2114
2115 BitstreamCursor Cursor = MacroCursor;
2116 if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
2117 Error(std::move(Err));
2118 return;
2119 }
2120
2122 while (true) {
2123 Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
2124 if (!MaybeE) {
2125 Error(MaybeE.takeError());
2126 return;
2127 }
2128 llvm::BitstreamEntry E = MaybeE.get();
2129
2130 switch (E.Kind) {
2131 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
2132 case llvm::BitstreamEntry::Error:
2133 Error("malformed block record in AST file");
2134 return;
2135 case llvm::BitstreamEntry::EndBlock:
2136 goto NextCursor;
2137
2138 case llvm::BitstreamEntry::Record: {
2139 Record.clear();
2140 Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
2141 if (!MaybeRecord) {
2142 Error(MaybeRecord.takeError());
2143 return;
2144 }
2145 switch (MaybeRecord.get()) {
2146 default: // Default behavior: ignore.
2147 break;
2148
2151 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
2152 if (II->isOutOfDate())
2153 updateOutOfDateIdentifier(*II);
2154 break;
2155 }
2156
2157 case PP_TOKEN:
2158 // Ignore tokens.
2159 break;
2160 }
2161 break;
2162 }
2163 }
2164 }
2165 NextCursor: ;
2166 }
2167}
2168
2169namespace {
2170
2171 /// Visitor class used to look up identifirs in an AST file.
2172 class IdentifierLookupVisitor {
2173 StringRef Name;
2174 unsigned NameHash;
2175 unsigned PriorGeneration;
2176 unsigned &NumIdentifierLookups;
2177 unsigned &NumIdentifierLookupHits;
2178 IdentifierInfo *Found = nullptr;
2179
2180 public:
2181 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
2182 unsigned &NumIdentifierLookups,
2183 unsigned &NumIdentifierLookupHits)
2184 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
2185 PriorGeneration(PriorGeneration),
2186 NumIdentifierLookups(NumIdentifierLookups),
2187 NumIdentifierLookupHits(NumIdentifierLookupHits) {}
2188
2189 bool operator()(ModuleFile &M) {
2190 // If we've already searched this module file, skip it now.
2191 if (M.Generation <= PriorGeneration)
2192 return true;
2193
2196 if (!IdTable)
2197 return false;
2198
2199 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
2200 Found);
2201 ++NumIdentifierLookups;
2202 ASTIdentifierLookupTable::iterator Pos =
2203 IdTable->find_hashed(Name, NameHash, &Trait);
2204 if (Pos == IdTable->end())
2205 return false;
2206
2207 // Dereferencing the iterator has the effect of building the
2208 // IdentifierInfo node and populating it with the various
2209 // declarations it needs.
2210 ++NumIdentifierLookupHits;
2211 Found = *Pos;
2212 return true;
2213 }
2214
2215 // Retrieve the identifier info found within the module
2216 // files.
2217 IdentifierInfo *getIdentifierInfo() const { return Found; }
2218 };
2219
2220} // namespace
2221
2223 // Note that we are loading an identifier.
2224 Deserializing AnIdentifier(this);
2225
2226 unsigned PriorGeneration = 0;
2227 if (getContext().getLangOpts().Modules)
2228 PriorGeneration = IdentifierGeneration[&II];
2229
2230 // If there is a global index, look there first to determine which modules
2231 // provably do not have any results for this identifier.
2233 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
2234 if (!loadGlobalIndex()) {
2235 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
2236 HitsPtr = &Hits;
2237 }
2238 }
2239
2240 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
2241 NumIdentifierLookups,
2242 NumIdentifierLookupHits);
2243 ModuleMgr.visit(Visitor, HitsPtr);
2244 markIdentifierUpToDate(&II);
2245}
2246
2248 if (!II)
2249 return;
2250
2251 const_cast<IdentifierInfo *>(II)->setOutOfDate(false);
2252
2253 // Update the generation for this identifier.
2254 if (getContext().getLangOpts().Modules)
2255 IdentifierGeneration[II] = getGeneration();
2256}
2257
2259 const PendingMacroInfo &PMInfo) {
2260 ModuleFile &M = *PMInfo.M;
2261
2262 BitstreamCursor &Cursor = M.MacroCursor;
2263 SavedStreamPosition SavedPosition(Cursor);
2264 if (llvm::Error Err =
2265 Cursor.JumpToBit(M.MacroOffsetsBase + PMInfo.MacroDirectivesOffset)) {
2266 Error(std::move(Err));
2267 return;
2268 }
2269
2270 struct ModuleMacroRecord {
2271 SubmoduleID SubModID;
2272 MacroInfo *MI;
2274 };
2276
2277 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
2278 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
2279 // macro histroy.
2281 while (true) {
2283 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
2284 if (!MaybeEntry) {
2285 Error(MaybeEntry.takeError());
2286 return;
2287 }
2288 llvm::BitstreamEntry Entry = MaybeEntry.get();
2289
2290 if (Entry.Kind != llvm::BitstreamEntry::Record) {
2291 Error("malformed block record in AST file");
2292 return;
2293 }
2294
2295 Record.clear();
2296 Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
2297 if (!MaybePP) {
2298 Error(MaybePP.takeError());
2299 return;
2300 }
2301 switch ((PreprocessorRecordTypes)MaybePP.get()) {
2303 break;
2304
2305 case PP_MODULE_MACRO: {
2306 ModuleMacros.push_back(ModuleMacroRecord());
2307 auto &Info = ModuleMacros.back();
2308 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
2309 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
2310 for (int I = 2, N = Record.size(); I != N; ++I)
2311 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
2312 continue;
2313 }
2314
2315 default:
2316 Error("malformed block record in AST file");
2317 return;
2318 }
2319
2320 // We found the macro directive history; that's the last record
2321 // for this macro.
2322 break;
2323 }
2324
2325 // Module macros are listed in reverse dependency order.
2326 {
2327 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
2329 for (auto &MMR : ModuleMacros) {
2330 Overrides.clear();
2331 for (unsigned ModID : MMR.Overrides) {
2332 Module *Mod = getSubmodule(ModID);
2333 auto *Macro = PP.getModuleMacro(Mod, II);
2334 assert(Macro && "missing definition for overridden macro");
2335 Overrides.push_back(Macro);
2336 }
2337
2338 bool Inserted = false;
2339 Module *Owner = getSubmodule(MMR.SubModID);
2340 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
2341 }
2342 }
2343
2344 // Don't read the directive history for a module; we don't have anywhere
2345 // to put it.
2346 if (M.isModule())
2347 return;
2348
2349 // Deserialize the macro directives history in reverse source-order.
2350 MacroDirective *Latest = nullptr, *Earliest = nullptr;
2351 unsigned Idx = 0, N = Record.size();
2352 while (Idx < N) {
2353 MacroDirective *MD = nullptr;
2354 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
2356 switch (K) {
2358 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
2359 MD = PP.AllocateDefMacroDirective(MI, Loc);
2360 break;
2361 }
2363 MD = PP.AllocateUndefMacroDirective(Loc);
2364 break;
2366 bool isPublic = Record[Idx++];
2367 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2368 break;
2369 }
2370
2371 if (!Latest)
2372 Latest = MD;
2373 if (Earliest)
2374 Earliest->setPrevious(MD);
2375 Earliest = MD;
2376 }
2377
2378 if (Latest)
2379 PP.setLoadedMacroDirective(II, Earliest, Latest);
2380}
2381
2382bool ASTReader::shouldDisableValidationForFile(
2383 const serialization::ModuleFile &M) const {
2384 if (DisableValidationKind == DisableValidationForModuleKind::None)
2385 return false;
2386
2387 // If a PCH is loaded and validation is disabled for PCH then disable
2388 // validation for the PCH and the modules it loads.
2389 ModuleKind K = CurrentDeserializingModuleKind.value_or(M.Kind);
2390
2391 switch (K) {
2392 case MK_MainFile:
2393 case MK_Preamble:
2394 case MK_PCH:
2395 return bool(DisableValidationKind & DisableValidationForModuleKind::PCH);
2396 case MK_ImplicitModule:
2397 case MK_ExplicitModule:
2398 case MK_PrebuiltModule:
2399 return bool(DisableValidationKind & DisableValidationForModuleKind::Module);
2400 }
2401
2402 return false;
2403}
2404
2405InputFileInfo ASTReader::getInputFileInfo(ModuleFile &F, unsigned ID) {
2406 // If this ID is bogus, just return an empty input file.
2407 if (ID == 0 || ID > F.InputFileInfosLoaded.size())
2408 return InputFileInfo();
2409
2410 // If we've already loaded this input file, return it.
2411 if (!F.InputFileInfosLoaded[ID - 1].Filename.empty())
2412 return F.InputFileInfosLoaded[ID - 1];
2413
2414 // Go find this input file.
2415 BitstreamCursor &Cursor = F.InputFilesCursor;
2416 SavedStreamPosition SavedPosition(Cursor);
2417 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2418 F.InputFileOffsets[ID - 1])) {
2419 // FIXME this drops errors on the floor.
2420 consumeError(std::move(Err));
2421 }
2422
2423 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2424 if (!MaybeCode) {
2425 // FIXME this drops errors on the floor.
2426 consumeError(MaybeCode.takeError());
2427 }
2428 unsigned Code = MaybeCode.get();
2429 RecordData Record;
2430 StringRef Blob;
2431
2432 if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
2433 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
2434 "invalid record type for input file");
2435 else {
2436 // FIXME this drops errors on the floor.
2437 consumeError(Maybe.takeError());
2438 }
2439
2440 assert(Record[0] == ID && "Bogus stored ID or offset");
2441 InputFileInfo R;
2442 R.StoredSize = static_cast<off_t>(Record[1]);
2443 R.StoredTime = static_cast<time_t>(Record[2]);
2444 R.Overridden = static_cast<bool>(Record[3]);
2445 R.Transient = static_cast<bool>(Record[4]);
2446 R.TopLevel = static_cast<bool>(Record[5]);
2447 R.ModuleMap = static_cast<bool>(Record[6]);
2448 std::tie(R.FilenameAsRequested, R.Filename) = [&]() {
2449 uint16_t AsRequestedLength = Record[7];
2450
2451 std::string NameAsRequested = Blob.substr(0, AsRequestedLength).str();
2452 std::string Name = Blob.substr(AsRequestedLength).str();
2453
2454 ResolveImportedPath(F, NameAsRequested);
2455 ResolveImportedPath(F, Name);
2456
2457 if (Name.empty())
2458 Name = NameAsRequested;
2459
2460 return std::make_pair(std::move(NameAsRequested), std::move(Name));
2461 }();
2462
2463 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
2464 if (!MaybeEntry) // FIXME this drops errors on the floor.
2465 consumeError(MaybeEntry.takeError());
2466 llvm::BitstreamEntry Entry = MaybeEntry.get();
2467 assert(Entry.Kind == llvm::BitstreamEntry::Record &&
2468 "expected record type for input file hash");
2469
2470 Record.clear();
2471 if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record))
2472 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH &&
2473 "invalid record type for input file hash");
2474 else {
2475 // FIXME this drops errors on the floor.
2476 consumeError(Maybe.takeError());
2477 }
2478 R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) |
2479 static_cast<uint64_t>(Record[0]);
2480
2481 // Note that we've loaded this input file info.
2482 F.InputFileInfosLoaded[ID - 1] = R;
2483 return R;
2484}
2485
2486static unsigned moduleKindForDiagnostic(ModuleKind Kind);
2487InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
2488 // If this ID is bogus, just return an empty input file.
2489 if (ID == 0 || ID > F.InputFilesLoaded.size())
2490 return InputFile();
2491
2492 // If we've already loaded this input file, return it.
2493 if (F.InputFilesLoaded[ID-1].getFile())
2494 return F.InputFilesLoaded[ID-1];
2495
2496 if (F.InputFilesLoaded[ID-1].isNotFound())
2497 return InputFile();
2498
2499 // Go find this input file.
2500 BitstreamCursor &Cursor = F.InputFilesCursor;
2501 SavedStreamPosition SavedPosition(Cursor);
2502 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2503 F.InputFileOffsets[ID - 1])) {
2504 // FIXME this drops errors on the floor.
2505 consumeError(std::move(Err));
2506 }
2507
2508 InputFileInfo FI = getInputFileInfo(F, ID);
2509 off_t StoredSize = FI.StoredSize;
2510 time_t StoredTime = FI.StoredTime;
2511 bool Overridden = FI.Overridden;
2512 bool Transient = FI.Transient;
2513 StringRef Filename = FI.FilenameAsRequested;
2514 uint64_t StoredContentHash = FI.ContentHash;
2515
2516 // For standard C++ modules, we don't need to check the inputs.
2517 bool SkipChecks = F.StandardCXXModule;
2518
2519 const HeaderSearchOptions &HSOpts =
2520 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2521
2522 // The option ForceCheckCXX20ModulesInputFiles is only meaningful for C++20
2523 // modules.
2525 SkipChecks = false;
2526 Overridden = false;
2527 }
2528
2529 auto File = FileMgr.getOptionalFileRef(Filename, /*OpenFile=*/false);
2530
2531 // For an overridden file, create a virtual file with the stored
2532 // size/timestamp.
2533 if ((Overridden || Transient || SkipChecks) && !File)
2534 File = FileMgr.getVirtualFileRef(Filename, StoredSize, StoredTime);
2535
2536 if (!File) {
2537 if (Complain) {
2538 std::string ErrorStr = "could not find file '";
2539 ErrorStr += Filename;
2540 ErrorStr += "' referenced by AST file '";
2541 ErrorStr += F.FileName;
2542 ErrorStr += "'";
2543 Error(ErrorStr);
2544 }
2545 // Record that we didn't find the file.
2547 return InputFile();
2548 }
2549
2550 // Check if there was a request to override the contents of the file
2551 // that was part of the precompiled header. Overriding such a file
2552 // can lead to problems when lexing using the source locations from the
2553 // PCH.
2554 SourceManager &SM = getSourceManager();
2555 // FIXME: Reject if the overrides are different.
2556 if ((!Overridden && !Transient) && !SkipChecks &&
2557 SM.isFileOverridden(*File)) {
2558 if (Complain)
2559 Error(diag::err_fe_pch_file_overridden, Filename);
2560
2561 // After emitting the diagnostic, bypass the overriding file to recover
2562 // (this creates a separate FileEntry).
2563 File = SM.bypassFileContentsOverride(*File);
2564 if (!File) {
2566 return InputFile();
2567 }
2568 }
2569
2570 struct Change {
2571 enum ModificationKind {
2572 Size,
2573 ModTime,
2574 Content,
2575 None,
2576 } Kind;
2577 std::optional<int64_t> Old = std::nullopt;
2578 std::optional<int64_t> New = std::nullopt;
2579 };
2580 auto HasInputContentChanged = [&](Change OriginalChange) {
2581 assert(ValidateASTInputFilesContent &&
2582 "We should only check the content of the inputs with "
2583 "ValidateASTInputFilesContent enabled.");
2584
2585 if (StoredContentHash == static_cast<uint64_t>(llvm::hash_code(-1)))
2586 return OriginalChange;
2587
2588 auto MemBuffOrError = FileMgr.getBufferForFile(*File);
2589 if (!MemBuffOrError) {
2590 if (!Complain)
2591 return OriginalChange;
2592 std::string ErrorStr = "could not get buffer for file '";
2593 ErrorStr += File->getName();
2594 ErrorStr += "'";
2595 Error(ErrorStr);
2596 return OriginalChange;
2597 }
2598
2599 // FIXME: hash_value is not guaranteed to be stable!
2600 auto ContentHash = hash_value(MemBuffOrError.get()->getBuffer());
2601 if (StoredContentHash == static_cast<uint64_t>(ContentHash))
2602 return Change{Change::None};
2603
2604 return Change{Change::Content};
2605 };
2606 auto HasInputFileChanged = [&]() {
2607 if (StoredSize != File->getSize())
2608 return Change{Change::Size, StoredSize, File->getSize()};
2609 if (!shouldDisableValidationForFile(F) && StoredTime &&
2610 StoredTime != File->getModificationTime()) {
2611 Change MTimeChange = {Change::ModTime, StoredTime,
2612 File->getModificationTime()};
2613
2614 // In case the modification time changes but not the content,
2615 // accept the cached file as legit.
2616 if (ValidateASTInputFilesContent)
2617 return HasInputContentChanged(MTimeChange);
2618
2619 return MTimeChange;
2620 }
2621 return Change{Change::None};
2622 };
2623
2624 bool IsOutOfDate = false;
2625 auto FileChange = SkipChecks ? Change{Change::None} : HasInputFileChanged();
2626 // When ForceCheckCXX20ModulesInputFiles and ValidateASTInputFilesContent
2627 // enabled, it is better to check the contents of the inputs. Since we can't
2628 // get correct modified time information for inputs from overriden inputs.
2629 if (HSOpts.ForceCheckCXX20ModulesInputFiles && ValidateASTInputFilesContent &&
2630 F.StandardCXXModule && FileChange.Kind == Change::None)
2631 FileChange = HasInputContentChanged(FileChange);
2632
2633 // For an overridden file, there is nothing to validate.
2634 if (!Overridden && FileChange.Kind != Change::None) {
2635 if (Complain && !Diags.isDiagnosticInFlight()) {
2636 // Build a list of the PCH imports that got us here (in reverse).
2637 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2638 while (!ImportStack.back()->ImportedBy.empty())
2639 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
2640
2641 // The top-level PCH is stale.
2642 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2643 Diag(diag::err_fe_ast_file_modified)
2644 << Filename << moduleKindForDiagnostic(ImportStack.back()->Kind)
2645 << TopLevelPCHName << FileChange.Kind
2646 << (FileChange.Old && FileChange.New)
2647 << llvm::itostr(FileChange.Old.value_or(0))
2648 << llvm::itostr(FileChange.New.value_or(0));
2649
2650 // Print the import stack.
2651 if (ImportStack.size() > 1) {
2652 Diag(diag::note_pch_required_by)
2653 << Filename << ImportStack[0]->FileName;
2654 for (unsigned I = 1; I < ImportStack.size(); ++I)
2655 Diag(diag::note_pch_required_by)
2656 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
2657 }
2658
2659 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
2660 }
2661
2662 IsOutOfDate = true;
2663 }
2664 // FIXME: If the file is overridden and we've already opened it,
2665 // issue an error (or split it into a separate FileEntry).
2666
2667 InputFile IF = InputFile(*File, Overridden || Transient, IsOutOfDate);
2668
2669 // Note that we've loaded this input file.
2670 F.InputFilesLoaded[ID-1] = IF;
2671 return IF;
2672}
2673
2674/// If we are loading a relocatable PCH or module file, and the filename
2675/// is not an absolute path, add the system or module root to the beginning of
2676/// the file name.
2678 // Resolve relative to the base directory, if we have one.
2679 if (!M.BaseDirectory.empty())
2680 return ResolveImportedPath(Filename, M.BaseDirectory);
2681}
2682
2683void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
2684 if (Filename.empty() || llvm::sys::path::is_absolute(Filename) ||
2685 Filename == "<built-in>" || Filename == "<command line>")
2686 return;
2687
2688 SmallString<128> Buffer;
2689 llvm::sys::path::append(Buffer, Prefix, Filename);
2690 Filename.assign(Buffer.begin(), Buffer.end());
2691}
2692
2693static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2694 switch (ARR) {
2695 case ASTReader::Failure: return true;
2696 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2697 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2700 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2701 case ASTReader::HadErrors: return true;
2702 case ASTReader::Success: return false;
2703 }
2704
2705 llvm_unreachable("unknown ASTReadResult");
2706}
2707
2708ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2709 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2710 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
2711 std::string &SuggestedPredefines) {
2712 if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
2713 // FIXME this drops errors on the floor.
2714 consumeError(std::move(Err));
2715 return Failure;
2716 }
2717
2718 // Read all of the records in the options block.
2719 RecordData Record;
2720 ASTReadResult Result = Success;
2721 while (true) {
2722 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2723 if (!MaybeEntry) {
2724 // FIXME this drops errors on the floor.
2725 consumeError(MaybeEntry.takeError());
2726 return Failure;
2727 }
2728 llvm::BitstreamEntry Entry = MaybeEntry.get();
2729
2730 switch (Entry.Kind) {
2731 case llvm::BitstreamEntry::Error:
2732 case llvm::BitstreamEntry::SubBlock:
2733 return Failure;
2734
2735 case llvm::BitstreamEntry::EndBlock:
2736 return Result;
2737
2738 case llvm::BitstreamEntry::Record:
2739 // The interesting case.
2740 break;
2741 }
2742
2743 // Read and process a record.
2744 Record.clear();
2745 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
2746 if (!MaybeRecordType) {
2747 // FIXME this drops errors on the floor.
2748 consumeError(MaybeRecordType.takeError());
2749 return Failure;
2750 }
2751 switch ((OptionsRecordTypes)MaybeRecordType.get()) {
2752 case LANGUAGE_OPTIONS: {
2753 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2754 if (ParseLanguageOptions(Record, Complain, Listener,
2755 AllowCompatibleConfigurationMismatch))
2756 Result = ConfigurationMismatch;
2757 break;
2758 }
2759
2760 case TARGET_OPTIONS: {
2761 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2762 if (ParseTargetOptions(Record, Complain, Listener,
2763 AllowCompatibleConfigurationMismatch))
2764 Result = ConfigurationMismatch;
2765 break;
2766 }
2767
2768 case FILE_SYSTEM_OPTIONS: {
2769 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2770 if (!AllowCompatibleConfigurationMismatch &&
2771 ParseFileSystemOptions(Record, Complain, Listener))
2772 Result = ConfigurationMismatch;
2773 break;
2774 }
2775
2776 case HEADER_SEARCH_OPTIONS: {
2777 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2778 if (!AllowCompatibleConfigurationMismatch &&
2779 ParseHeaderSearchOptions(Record, Complain, Listener))
2780 Result = ConfigurationMismatch;
2781 break;
2782 }
2783
2785 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2786 if (!AllowCompatibleConfigurationMismatch &&
2787 ParsePreprocessorOptions(Record, Complain, Listener,
2788 SuggestedPredefines))
2789 Result = ConfigurationMismatch;
2790 break;
2791 }
2792 }
2793}
2794
2796ASTReader::ReadControlBlock(ModuleFile &F,
2798 const ModuleFile *ImportedBy,
2799 unsigned ClientLoadCapabilities) {
2800 BitstreamCursor &Stream = F.Stream;
2801
2802 if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2803 Error(std::move(Err));
2804 return Failure;
2805 }
2806
2807 // Lambda to read the unhashed control block the first time it's called.
2808 //
2809 // For PCM files, the unhashed control block cannot be read until after the
2810 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
2811 // need to look ahead before reading the IMPORTS record. For consistency,
2812 // this block is always read somehow (see BitstreamEntry::EndBlock).
2813 bool HasReadUnhashedControlBlock = false;
2814 auto readUnhashedControlBlockOnce = [&]() {
2815 if (!HasReadUnhashedControlBlock) {
2816 HasReadUnhashedControlBlock = true;
2817 if (ASTReadResult Result =
2818 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2819 return Result;
2820 }
2821 return Success;
2822 };
2823
2824 bool DisableValidation = shouldDisableValidationForFile(F);
2825
2826 // Read all of the records and blocks in the control block.
2827 RecordData Record;
2828 unsigned NumInputs = 0;
2829 unsigned NumUserInputs = 0;
2830 StringRef BaseDirectoryAsWritten;
2831 while (true) {
2832 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2833 if (!MaybeEntry) {
2834 Error(MaybeEntry.takeError());
2835 return Failure;
2836 }
2837 llvm::BitstreamEntry Entry = MaybeEntry.get();
2838
2839 switch (Entry.Kind) {
2840 case llvm::BitstreamEntry::Error:
2841 Error("malformed block record in AST file");
2842 return Failure;
2843 case llvm::BitstreamEntry::EndBlock: {
2844 // Validate the module before returning. This call catches an AST with
2845 // no module name and no imports.
2846 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2847 return Result;
2848
2849 // Validate input files.
2850 const HeaderSearchOptions &HSOpts =
2851 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2852
2853 // All user input files reside at the index range [0, NumUserInputs), and
2854 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2855 // loaded module files, ignore missing inputs.
2856 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2857 F.Kind != MK_PrebuiltModule) {
2858 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2859
2860 // If we are reading a module, we will create a verification timestamp,
2861 // so we verify all input files. Otherwise, verify only user input
2862 // files.
2863
2864 unsigned N = ValidateSystemInputs ? NumInputs : NumUserInputs;
2868 N = NumUserInputs;
2869
2870 for (unsigned I = 0; I < N; ++I) {
2871 InputFile IF = getInputFile(F, I+1, Complain);
2872 if (!IF.getFile() || IF.isOutOfDate())
2873 return OutOfDate;
2874 }
2875 }
2876
2877 if (Listener)
2878 Listener->visitModuleFile(F.FileName, F.Kind);
2879
2880 if (Listener && Listener->needsInputFileVisitation()) {
2881 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2882 : NumUserInputs;
2883 for (unsigned I = 0; I < N; ++I) {
2884 bool IsSystem = I >= NumUserInputs;
2885 InputFileInfo FI = getInputFileInfo(F, I + 1);
2886 Listener->visitInputFile(
2887 FI.FilenameAsRequested, IsSystem, FI.Overridden,
2889 }
2890 }
2891
2892 return Success;
2893 }
2894
2895 case llvm::BitstreamEntry::SubBlock:
2896 switch (Entry.ID) {
2898 F.InputFilesCursor = Stream;
2899 if (llvm::Error Err = Stream.SkipBlock()) {
2900 Error(std::move(Err));
2901 return Failure;
2902 }
2903 if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2904 Error("malformed block record in AST file");
2905 return Failure;
2906 }
2907 F.InputFilesOffsetBase = F.InputFilesCursor.GetCurrentBitNo();
2908 continue;
2909
2910 case OPTIONS_BLOCK_ID:
2911 // If we're reading the first module for this group, check its options
2912 // are compatible with ours. For modules it imports, no further checking
2913 // is required, because we checked them when we built it.
2914 if (Listener && !ImportedBy) {
2915 // Should we allow the configuration of the module file to differ from
2916 // the configuration of the current translation unit in a compatible
2917 // way?
2918 //
2919 // FIXME: Allow this for files explicitly specified with -include-pch.
2920 bool AllowCompatibleConfigurationMismatch =
2922
2923 ASTReadResult Result =
2924 ReadOptionsBlock(Stream, ClientLoadCapabilities,
2925 AllowCompatibleConfigurationMismatch, *Listener,
2926 SuggestedPredefines);
2927 if (Result == Failure) {
2928 Error("malformed block record in AST file");
2929 return Result;
2930 }
2931
2932 if (DisableValidation ||
2933 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2934 Result = Success;
2935
2936 // If we can't load the module, exit early since we likely
2937 // will rebuild the module anyway. The stream may be in the
2938 // middle of a block.
2939 if (Result != Success)
2940 return Result;
2941 } else if (llvm::Error Err = Stream.SkipBlock()) {
2942 Error(std::move(Err));
2943 return Failure;
2944 }
2945 continue;
2946
2947 default:
2948 if (llvm::Error Err = Stream.SkipBlock()) {
2949 Error(std::move(Err));
2950 return Failure;
2951 }
2952 continue;
2953 }
2954
2955 case llvm::BitstreamEntry::Record:
2956 // The interesting case.
2957 break;
2958 }
2959
2960 // Read and process a record.
2961 Record.clear();
2962 StringRef Blob;
2963 Expected<unsigned> MaybeRecordType =
2964 Stream.readRecord(Entry.ID, Record, &Blob);
2965 if (!MaybeRecordType) {
2966 Error(MaybeRecordType.takeError());
2967 return Failure;
2968 }
2969 switch ((ControlRecordTypes)MaybeRecordType.get()) {
2970 case METADATA: {
2971 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2972 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2973 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2974 : diag::err_pch_version_too_new);
2975 return VersionMismatch;
2976 }
2977
2978 bool hasErrors = Record[7];
2979 if (hasErrors && !DisableValidation) {
2980 // If requested by the caller and the module hasn't already been read
2981 // or compiled, mark modules on error as out-of-date.
2982 if ((ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate) &&
2983 canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
2984 return OutOfDate;
2985
2986 if (!AllowASTWithCompilerErrors) {
2987 Diag(diag::err_pch_with_compiler_errors);
2988 return HadErrors;
2989 }
2990 }
2991 if (hasErrors) {
2992 Diags.ErrorOccurred = true;
2993 Diags.UncompilableErrorOccurred = true;
2994 Diags.UnrecoverableErrorOccurred = true;
2995 }
2996
2997 F.RelocatablePCH = Record[4];
2998 // Relative paths in a relocatable PCH are relative to our sysroot.
2999 if (F.RelocatablePCH)
3000 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
3001
3003
3004 F.HasTimestamps = Record[6];
3005
3006 const std::string &CurBranch = getClangFullRepositoryVersion();
3007 StringRef ASTBranch = Blob;
3008 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
3009 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3010 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
3011 return VersionMismatch;
3012 }
3013 break;
3014 }
3015
3016 case IMPORTS: {
3017 // Validate the AST before processing any imports (otherwise, untangling
3018 // them can be error-prone and expensive). A module will have a name and
3019 // will already have been validated, but this catches the PCH case.
3020 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3021 return Result;
3022
3023 // Load each of the imported PCH files.
3024 unsigned Idx = 0, N = Record.size();
3025 while (Idx < N) {
3026 // Read information about the AST file.
3027 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
3028 // Whether we're importing a standard c++ module.
3029 bool IsImportingStdCXXModule = Record[Idx++];
3030 // The import location will be the local one for now; we will adjust
3031 // all import locations of module imports after the global source
3032 // location info are setup, in ReadAST.
3033 SourceLocation ImportLoc =
3034 ReadUntranslatedSourceLocation(Record[Idx++]);
3035 off_t StoredSize = !IsImportingStdCXXModule ? (off_t)Record[Idx++] : 0;
3036 time_t StoredModTime =
3037 !IsImportingStdCXXModule ? (time_t)Record[Idx++] : 0;
3038
3039 ASTFileSignature StoredSignature;
3040 if (!IsImportingStdCXXModule) {
3041 auto FirstSignatureByte = Record.begin() + Idx;
3042 StoredSignature = ASTFileSignature::create(
3043 FirstSignatureByte, FirstSignatureByte + ASTFileSignature::size);
3045 }
3046
3047 std::string ImportedName = ReadString(Record, Idx);
3048 std::string ImportedFile;
3049
3050 // For prebuilt and explicit modules first consult the file map for
3051 // an override. Note that here we don't search prebuilt module
3052 // directories if we're not importing standard c++ module, only the
3053 // explicit name to file mappings. Also, we will still verify the
3054 // size/signature making sure it is essentially the same file but
3055 // perhaps in a different location.
3056 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
3057 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
3058 ImportedName, /*FileMapOnly*/ !IsImportingStdCXXModule);
3059
3060 // For C++20 Modules, we won't record the path to the imported modules
3061 // in the BMI
3062 if (!IsImportingStdCXXModule) {
3063 if (ImportedFile.empty()) {
3064 // Use BaseDirectoryAsWritten to ensure we use the same path in the
3065 // ModuleCache as when writing.
3066 ImportedFile = ReadPath(BaseDirectoryAsWritten, Record, Idx);
3067 } else
3068 SkipPath(Record, Idx);
3069 } else if (ImportedFile.empty()) {
3070 Diag(clang::diag::err_failed_to_find_module_file) << ImportedName;
3071 return Missing;
3072 }
3073
3074 // If our client can't cope with us being out of date, we can't cope with
3075 // our dependency being missing.
3076 unsigned Capabilities = ClientLoadCapabilities;
3077 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3078 Capabilities &= ~ARR_Missing;
3079
3080 // Load the AST file.
3081 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
3082 Loaded, StoredSize, StoredModTime,
3083 StoredSignature, Capabilities);
3084
3085 // If we diagnosed a problem, produce a backtrace.
3086 bool recompilingFinalized =
3087 Result == OutOfDate && (Capabilities & ARR_OutOfDate) &&
3088 getModuleManager().getModuleCache().isPCMFinal(F.FileName);
3089 if (isDiagnosedResult(Result, Capabilities) || recompilingFinalized)
3090 Diag(diag::note_module_file_imported_by)
3091 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
3092 if (recompilingFinalized)
3093 Diag(diag::note_module_file_conflict);
3094
3095 switch (Result) {
3096 case Failure: return Failure;
3097 // If we have to ignore the dependency, we'll have to ignore this too.
3098 case Missing:
3099 case OutOfDate: return OutOfDate;
3100 case VersionMismatch: return VersionMismatch;
3101 case ConfigurationMismatch: return ConfigurationMismatch;
3102 case HadErrors: return HadErrors;
3103 case Success: break;
3104 }
3105 }
3106 break;
3107 }
3108
3109 case ORIGINAL_FILE:
3110 F.OriginalSourceFileID = FileID::get(Record[0]);
3111 F.ActualOriginalSourceFileName = std::string(Blob);
3113 ResolveImportedPath(F, F.OriginalSourceFileName);
3114 break;
3115
3116 case ORIGINAL_FILE_ID:
3117 F.OriginalSourceFileID = FileID::get(Record[0]);
3118 break;
3119
3120 case MODULE_NAME:
3121 F.ModuleName = std::string(Blob);
3122 Diag(diag::remark_module_import)
3123 << F.ModuleName << F.FileName << (ImportedBy ? true : false)
3124 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
3125 if (Listener)
3126 Listener->ReadModuleName(F.ModuleName);
3127
3128 // Validate the AST as soon as we have a name so we can exit early on
3129 // failure.
3130 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3131 return Result;
3132
3133 break;
3134
3135 case MODULE_DIRECTORY: {
3136 // Save the BaseDirectory as written in the PCM for computing the module
3137 // filename for the ModuleCache.
3138 BaseDirectoryAsWritten = Blob;
3139 assert(!F.ModuleName.empty() &&
3140 "MODULE_DIRECTORY found before MODULE_NAME");
3141 F.BaseDirectory = std::string(Blob);
3142 if (!PP.getPreprocessorOpts().ModulesCheckRelocated)
3143 break;
3144 // If we've already loaded a module map file covering this module, we may
3145 // have a better path for it (relative to the current build).
3146 Module *M = PP.getHeaderSearchInfo().lookupModule(
3147 F.ModuleName, SourceLocation(), /*AllowSearch*/ true,
3148 /*AllowExtraModuleMapSearch*/ true);
3149 if (M && M->Directory) {
3150 // If we're implicitly loading a module, the base directory can't
3151 // change between the build and use.
3152 // Don't emit module relocation error if we have -fno-validate-pch
3153 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
3156 auto BuildDir = PP.getFileManager().getOptionalDirectoryRef(Blob);
3157 if (!BuildDir || *BuildDir != M->Directory) {
3158 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3159 Diag(diag::err_imported_module_relocated)
3160 << F.ModuleName << Blob << M->Directory->getName();
3161 return OutOfDate;
3162 }
3163 }
3164 F.BaseDirectory = std::string(M->Directory->getName());
3165 }
3166 break;
3167 }
3168
3169 case MODULE_MAP_FILE:
3170 if (ASTReadResult Result =
3171 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
3172 return Result;
3173 break;
3174
3175 case INPUT_FILE_OFFSETS:
3176 NumInputs = Record[0];
3177 NumUserInputs = Record[1];
3179 (const llvm::support::unaligned_uint64_t *)Blob.data();
3180 F.InputFilesLoaded.resize(NumInputs);
3181 F.InputFileInfosLoaded.resize(NumInputs);
3182 F.NumUserInputFiles = NumUserInputs;
3183 break;
3184 }
3185 }
3186}
3187
3188llvm::Error ASTReader::ReadASTBlock(ModuleFile &F,
3189 unsigned ClientLoadCapabilities) {
3190 BitstreamCursor &Stream = F.Stream;
3191
3192 if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID))
3193 return Err;
3194 F.ASTBlockStartOffset = Stream.GetCurrentBitNo();
3195
3196 // Read all of the records and blocks for the AST file.
3197 RecordData Record;
3198 while (true) {
3199 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3200 if (!MaybeEntry)
3201 return MaybeEntry.takeError();
3202 llvm::BitstreamEntry Entry = MaybeEntry.get();
3203
3204 switch (Entry.Kind) {
3205 case llvm::BitstreamEntry::Error:
3206 return llvm::createStringError(
3207 std::errc::illegal_byte_sequence,
3208 "error at end of module block in AST file");
3209 case llvm::BitstreamEntry::EndBlock:
3210 // Outside of C++, we do not store a lookup map for the translation unit.
3211 // Instead, mark it as needing a lookup map to be built if this module
3212 // contains any declarations lexically within it (which it always does!).
3213 // This usually has no cost, since we very rarely need the lookup map for
3214 // the translation unit outside C++.
3215 if (ASTContext *Ctx = ContextObj) {
3216 DeclContext *DC = Ctx->getTranslationUnitDecl();
3217 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
3219 }
3220
3221 return llvm::Error::success();
3222 case llvm::BitstreamEntry::SubBlock:
3223 switch (Entry.ID) {
3224 case DECLTYPES_BLOCK_ID:
3225 // We lazily load the decls block, but we want to set up the
3226 // DeclsCursor cursor to point into it. Clone our current bitcode
3227 // cursor to it, enter the block and read the abbrevs in that block.
3228 // With the main cursor, we just skip over it.
3229 F.DeclsCursor = Stream;
3230 if (llvm::Error Err = Stream.SkipBlock())
3231 return Err;
3232 if (llvm::Error Err = ReadBlockAbbrevs(
3234 return Err;
3235 break;
3236
3238 F.MacroCursor = Stream;
3239 if (!PP.getExternalSource())
3240 PP.setExternalSource(this);
3241
3242 if (llvm::Error Err = Stream.SkipBlock())
3243 return Err;
3244 if (llvm::Error Err =
3245 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID))
3246 return Err;
3247 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
3248 break;
3249
3251 F.PreprocessorDetailCursor = Stream;
3252
3253 if (llvm::Error Err = Stream.SkipBlock()) {
3254 return Err;
3255 }
3256 if (llvm::Error Err = ReadBlockAbbrevs(F.PreprocessorDetailCursor,
3258 return Err;
3260 = F.PreprocessorDetailCursor.GetCurrentBitNo();
3261
3262 if (!PP.getPreprocessingRecord())
3263 PP.createPreprocessingRecord();
3264 if (!PP.getPreprocessingRecord()->getExternalSource())
3265 PP.getPreprocessingRecord()->SetExternalSource(*this);
3266 break;
3267
3269 if (llvm::Error Err = ReadSourceManagerBlock(F))
3270 return Err;
3271 break;
3272
3273 case SUBMODULE_BLOCK_ID:
3274 if (llvm::Error Err = ReadSubmoduleBlock(F, ClientLoadCapabilities))
3275 return Err;
3276 break;
3277
3278 case COMMENTS_BLOCK_ID: {
3279 BitstreamCursor C = Stream;
3280
3281 if (llvm::Error Err = Stream.SkipBlock())
3282 return Err;
3283 if (llvm::Error Err = ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID))
3284 return Err;
3285 CommentsCursors.push_back(std::make_pair(C, &F));
3286 break;
3287 }
3288
3289 default:
3290 if (llvm::Error Err = Stream.SkipBlock())
3291 return Err;
3292 break;
3293 }
3294 continue;
3295
3296 case llvm::BitstreamEntry::Record:
3297 // The interesting case.
3298 break;
3299 }
3300
3301 // Read and process a record.
3302 Record.clear();
3303 StringRef Blob;
3304 Expected<unsigned> MaybeRecordType =
3305 Stream.readRecord(Entry.ID, Record, &Blob);
3306 if (!MaybeRecordType)
3307 return MaybeRecordType.takeError();
3308 ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
3309
3310 // If we're not loading an AST context, we don't care about most records.
3311 if (!ContextObj) {
3312 switch (RecordType) {
3313 case IDENTIFIER_TABLE:
3314 case IDENTIFIER_OFFSET:
3316 case STATISTICS:
3319 case PP_COUNTER_VALUE:
3321 case MODULE_OFFSET_MAP:
3325 case IMPORTED_MODULES:
3326 case MACRO_OFFSET:
3327 break;
3328 default:
3329 continue;
3330 }
3331 }
3332
3333 switch (RecordType) {
3334 default: // Default behavior: ignore.
3335 break;
3336
3337 case TYPE_OFFSET: {
3338 if (F.LocalNumTypes != 0)
3339 return llvm::createStringError(
3340 std::errc::illegal_byte_sequence,
3341 "duplicate TYPE_OFFSET record in AST file");
3342 F.TypeOffsets = reinterpret_cast<const UnderalignedInt64 *>(Blob.data());
3343 F.LocalNumTypes = Record[0];
3344 unsigned LocalBaseTypeIndex = Record[1];
3345 F.BaseTypeIndex = getTotalNumTypes();
3346
3347 if (F.LocalNumTypes > 0) {
3348 // Introduce the global -> local mapping for types within this module.
3349 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
3350
3351 // Introduce the local -> global mapping for types within this module.
3353 std::make_pair(LocalBaseTypeIndex,
3354 F.BaseTypeIndex - LocalBaseTypeIndex));
3355
3356 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
3357 }
3358 break;
3359 }
3360
3361 case DECL_OFFSET: {
3362 if (F.LocalNumDecls != 0)
3363 return llvm::createStringError(
3364 std::errc::illegal_byte_sequence,
3365 "duplicate DECL_OFFSET record in AST file");
3366 F.DeclOffsets = (const DeclOffset *)Blob.data();
3367 F.LocalNumDecls = Record[0];
3368 unsigned LocalBaseDeclID = Record[1];
3369 F.BaseDeclID = getTotalNumDecls();
3370
3371 if (F.LocalNumDecls > 0) {
3372 // Introduce the global -> local mapping for declarations within this
3373 // module.
3374 GlobalDeclMap.insert(std::make_pair(
3375 GlobalDeclID(getTotalNumDecls() + NUM_PREDEF_DECL_IDS), &F));
3376
3377 // Introduce the local -> global mapping for declarations within this
3378 // module.
3380 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
3381
3382 // Introduce the global -> local mapping for declarations within this
3383 // module.
3384 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
3385
3386 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
3387 }
3388 break;
3389 }
3390
3391 case TU_UPDATE_LEXICAL: {
3392 DeclContext *TU = ContextObj->getTranslationUnitDecl();
3393 LexicalContents Contents(
3394 reinterpret_cast<const unalighed_decl_id_t *>(Blob.data()),
3395 static_cast<unsigned int>(Blob.size() / sizeof(DeclID)));
3396 TULexicalDecls.push_back(std::make_pair(&F, Contents));
3398 break;
3399 }
3400
3401 case UPDATE_VISIBLE: {
3402 unsigned Idx = 0;
3403 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3404 auto *Data = (const unsigned char*)Blob.data();
3405 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
3406 // If we've already loaded the decl, perform the updates when we finish
3407 // loading this block.
3408 if (Decl *D = GetExistingDecl(ID))
3409 PendingUpdateRecords.push_back(
3410 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3411 break;
3412 }
3413
3414 case IDENTIFIER_TABLE:
3416 reinterpret_cast<const unsigned char *>(Blob.data());
3417 if (Record[0]) {
3418 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
3420 F.IdentifierTableData + sizeof(uint32_t),
3422 ASTIdentifierLookupTrait(*this, F));
3423
3424 PP.getIdentifierTable().setExternalIdentifierLookup(this);
3425 }
3426 break;
3427
3428 case IDENTIFIER_OFFSET: {
3429 if (F.LocalNumIdentifiers != 0)
3430 return llvm::createStringError(
3431 std::errc::illegal_byte_sequence,
3432 "duplicate IDENTIFIER_OFFSET record in AST file");
3433 F.IdentifierOffsets = (const uint32_t *)Blob.data();
3435 unsigned LocalBaseIdentifierID = Record[1];
3436 F.BaseIdentifierID = getTotalNumIdentifiers();
3437
3438 if (F.LocalNumIdentifiers > 0) {
3439 // Introduce the global -> local mapping for identifiers within this
3440 // module.
3441 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
3442 &F));
3443
3444 // Introduce the local -> global mapping for identifiers within this
3445 // module.
3447 std::make_pair(LocalBaseIdentifierID,
3448 F.BaseIdentifierID - LocalBaseIdentifierID));
3449
3450 IdentifiersLoaded.resize(IdentifiersLoaded.size()
3452 }
3453 break;
3454 }
3455
3457 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
3458 break;
3459
3461 // FIXME: Skip reading this record if our ASTConsumer doesn't care
3462 // about "interesting" decls (for instance, if we're building a module).
3463 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3464 EagerlyDeserializedDecls.push_back(
3465 getGlobalDeclID(F, LocalDeclID(Record[I])));
3466 break;
3467
3469 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
3470 // them (ie: if we're not codegenerating this module).
3471 if (F.Kind == MK_MainFile ||
3472 getContext().getLangOpts().BuildingPCHWithObjectFile)
3473 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3474 EagerlyDeserializedDecls.push_back(
3475 getGlobalDeclID(F, LocalDeclID(Record[I])));
3476 break;
3477
3478 case SPECIAL_TYPES:
3479 if (SpecialTypes.empty()) {
3480 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3481 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
3482 break;
3483 }
3484
3485 if (SpecialTypes.size() != Record.size())
3486 return llvm::createStringError(std::errc::illegal_byte_sequence,
3487 "invalid special-types record");
3488
3489 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3490 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
3491 if (!SpecialTypes[I])
3492 SpecialTypes[I] = ID;
3493 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
3494 // merge step?
3495 }
3496 break;
3497
3498 case STATISTICS:
3499 TotalNumStatements += Record[0];
3500 TotalNumMacros += Record[1];
3501 TotalLexicalDeclContexts += Record[2];
3502 TotalVisibleDeclContexts += Record[3];
3503 break;
3504
3506 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3507 UnusedFileScopedDecls.push_back(
3508 getGlobalDeclID(F, LocalDeclID(Record[I])));
3509 break;
3510
3511 case DELEGATING_CTORS:
3512 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3513 DelegatingCtorDecls.push_back(
3514 getGlobalDeclID(F, LocalDeclID(Record[I])));
3515 break;
3516
3518 if (Record.size() % 3 != 0)
3519 return llvm::createStringError(std::errc::illegal_byte_sequence,
3520 "invalid weak identifiers record");
3521
3522 // FIXME: Ignore weak undeclared identifiers from non-original PCH
3523 // files. This isn't the way to do it :)
3524 WeakUndeclaredIdentifiers.clear();
3525
3526 // Translate the weak, undeclared identifiers into global IDs.
3527 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
3528 WeakUndeclaredIdentifiers.push_back(
3529 getGlobalIdentifierID(F, Record[I++]));
3530 WeakUndeclaredIdentifiers.push_back(
3531 getGlobalIdentifierID(F, Record[I++]));
3532 WeakUndeclaredIdentifiers.push_back(
3533 ReadSourceLocation(F, Record, I).getRawEncoding());
3534 }
3535 break;
3536
3537 case SELECTOR_OFFSETS: {
3538 F.SelectorOffsets = (const uint32_t *)Blob.data();
3540 unsigned LocalBaseSelectorID = Record[1];
3541 F.BaseSelectorID = getTotalNumSelectors();
3542
3543 if (F.LocalNumSelectors > 0) {
3544 // Introduce the global -> local mapping for selectors within this
3545 // module.
3546 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
3547
3548 // Introduce the local -> global mapping for selectors within this
3549 // module.
3551 std::make_pair(LocalBaseSelectorID,
3552 F.BaseSelectorID - LocalBaseSelectorID));
3553
3554 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
3555 }
3556 break;
3557 }
3558
3559 case METHOD_POOL:
3560 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
3561 if (Record[0])
3563 = ASTSelectorLookupTable::Create(
3566 ASTSelectorLookupTrait(*this, F));
3567 TotalNumMethodPoolEntries += Record[1];
3568 break;
3569
3571 if (!Record.empty()) {
3572 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
3573 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
3574 Record[Idx++]));
3575 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
3576 getRawEncoding());
3577 }
3578 }
3579 break;
3580
3581 case PP_ASSUME_NONNULL_LOC: {
3582 unsigned Idx = 0;
3583 if (!Record.empty())
3584 PP.setPreambleRecordedPragmaAssumeNonNullLoc(
3585 ReadSourceLocation(F, Record, Idx));
3586 break;
3587 }
3588
3590 if (!Record.empty()) {
3591 unsigned Idx = 0, End = Record.size() - 1;
3592 bool ReachedEOFWhileSkipping = Record[Idx++];
3593 std::optional<Preprocessor::PreambleSkipInfo> SkipInfo;
3594 if (ReachedEOFWhileSkipping) {
3595 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
3596 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
3597 bool FoundNonSkipPortion = Record[Idx++];
3598 bool FoundElse = Record[Idx++];
3599 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
3600 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
3601 FoundElse, ElseLoc);
3602 }
3603 SmallVector<PPConditionalInfo, 4> ConditionalStack;
3604 while (Idx < End) {
3605 auto Loc = ReadSourceLocation(F, Record, Idx);
3606 bool WasSkipping = Record[Idx++];
3607 bool FoundNonSkip = Record[Idx++];
3608 bool FoundElse = Record[Idx++];
3609 ConditionalStack.push_back(
3610 {Loc, WasSkipping, FoundNonSkip, FoundElse});
3611 }
3612 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
3613 }
3614 break;
3615
3616 case PP_COUNTER_VALUE:
3617 if (!Record.empty() && Listener)
3618 Listener->ReadCounter(F, Record[0]);
3619 break;
3620
3621 case FILE_SORTED_DECLS:
3622 F.FileSortedDecls = (const LocalDeclID *)Blob.data();
3624 break;
3625
3627 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
3629 SourceLocation::UIntTy SLocSpaceSize = Record[1];
3631 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
3632 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
3633 SLocSpaceSize);
3634 if (!F.SLocEntryBaseID) {
3635 if (!Diags.isDiagnosticInFlight()) {
3636 Diags.Report(SourceLocation(), diag::remark_sloc_usage);
3637 SourceMgr.noteSLocAddressSpaceUsage(Diags);
3638 }
3639 return llvm::createStringError(std::errc::invalid_argument,
3640 "ran out of source locations");
3641 }
3642 // Make our entry in the range map. BaseID is negative and growing, so
3643 // we invert it. Because we invert it, though, we need the other end of
3644 // the range.
3645 unsigned RangeStart =
3647 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
3649
3650 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3651 assert((F.SLocEntryBaseOffset & SourceLocation::MacroIDBit) == 0);
3652 GlobalSLocOffsetMap.insert(
3653 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
3654 - SLocSpaceSize,&F));
3655
3656 // Initialize the remapping table.
3657 // Invalid stays invalid.
3658 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
3659 // This module. Base was 2 when being compiled.
3660 F.SLocRemap.insertOrReplace(std::make_pair(
3661 2U, static_cast<SourceLocation::IntTy>(F.SLocEntryBaseOffset - 2)));
3662
3663 TotalNumSLocEntries += F.LocalNumSLocEntries;
3664 break;
3665 }
3666
3667 case MODULE_OFFSET_MAP:
3668 F.ModuleOffsetMap = Blob;
3669 break;
3670
3672 ParseLineTable(F, Record);
3673 break;
3674
3675 case EXT_VECTOR_DECLS:
3676 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3677 ExtVectorDecls.push_back(getGlobalDeclID(F, LocalDeclID(Record[I])));
3678 break;
3679
3680 case VTABLE_USES:
3681 if (Record.size() % 3 != 0)
3682 return llvm::createStringError(std::errc::illegal_byte_sequence,
3683 "Invalid VTABLE_USES record");
3684
3685 // Later tables overwrite earlier ones.
3686 // FIXME: Modules will have some trouble with this. This is clearly not
3687 // the right way to do this.
3688 VTableUses.clear();
3689
3690 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3691 VTableUses.push_back(
3692 {getGlobalDeclID(F, LocalDeclID(Record[Idx++])),
3693 ReadSourceLocation(F, Record, Idx).getRawEncoding(),
3694 (bool)Record[Idx++]});
3695 }
3696 break;
3697
3699
3700 if (Record.size() % 2 != 0)
3701 return llvm::createStringError(
3702 std::errc::illegal_byte_sequence,
3703 "Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
3704
3705 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3706 PendingInstantiations.push_back(
3707 {getGlobalDeclID(F, LocalDeclID(Record[I++])),
3708 ReadSourceLocation(F, Record, I).getRawEncoding()});
3709 }
3710 break;
3711
3712 case SEMA_DECL_REFS:
3713 if (Record.size() != 3)
3714 return llvm::createStringError(std::errc::illegal_byte_sequence,
3715 "Invalid SEMA_DECL_REFS block");
3716 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3717 SemaDeclRefs.push_back(getGlobalDeclID(F, LocalDeclID(Record[I])));
3718 break;
3719
3720 case PPD_ENTITIES_OFFSETS: {
3721 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3722 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3723 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
3724
3725 unsigned LocalBasePreprocessedEntityID = Record[0];
3726
3727 unsigned StartingID;
3728 if (!PP.getPreprocessingRecord())
3729 PP.createPreprocessingRecord();
3730 if (!PP.getPreprocessingRecord()->getExternalSource())
3731 PP.getPreprocessingRecord()->SetExternalSource(*this);
3732 StartingID
3733 = PP.getPreprocessingRecord()
3734 ->allocateLoadedEntities(F.NumPreprocessedEntities);
3735 F.BasePreprocessedEntityID = StartingID;
3736
3737 if (F.NumPreprocessedEntities > 0) {
3738 // Introduce the global -> local mapping for preprocessed entities in
3739 // this module.
3740 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3741
3742 // Introduce the local -> global mapping for preprocessed entities in
3743 // this module.
3745 std::make_pair(LocalBasePreprocessedEntityID,
3746 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3747 }
3748
3749 break;
3750 }
3751
3752 case PPD_SKIPPED_RANGES: {
3753 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
3754 assert(Blob.size() % sizeof(PPSkippedRange) == 0);
3755 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
3756
3757 if (!PP.getPreprocessingRecord())
3758 PP.createPreprocessingRecord();
3759 if (!PP.getPreprocessingRecord()->getExternalSource())
3760 PP.getPreprocessingRecord()->SetExternalSource(*this);
3761 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
3762 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
3763
3765 GlobalSkippedRangeMap.insert(
3766 std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
3767 break;
3768 }
3769
3771 if (Record.size() % 2 != 0)
3772 return llvm::createStringError(
3773 std::errc::illegal_byte_sequence,
3774 "invalid DECL_UPDATE_OFFSETS block in AST file");
3775 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3776 GlobalDeclID ID = getGlobalDeclID(F, LocalDeclID(Record[I]));
3777 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3778
3779 // If we've already loaded the decl, perform the updates when we finish
3780 // loading this block.
3781 if (Decl *D = GetExistingDecl(ID))
3782 PendingUpdateRecords.push_back(
3783 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3784 }
3785 break;
3786
3788 if (Record.size() % 3 != 0)
3789 return llvm::createStringError(
3790 std::errc::illegal_byte_sequence,
3791 "invalid DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD block in AST "
3792 "file");
3793 for (unsigned I = 0, N = Record.size(); I != N; I += 3) {
3794 GlobalDeclID ID = getGlobalDeclID(F, LocalDeclID(Record[I]));
3795
3796 uint64_t BaseOffset = F.DeclsBlockStartOffset;
3797 assert(BaseOffset && "Invalid DeclsBlockStartOffset for module file!");
3798 uint64_t LexicalOffset = Record[I + 1] ? BaseOffset + Record[I + 1] : 0;
3799 uint64_t VisibleOffset = Record[I + 2] ? BaseOffset + Record[I + 2] : 0;
3800
3801 DelayedNamespaceOffsetMap[ID] = {LexicalOffset, VisibleOffset};
3802
3803 assert(!GetExistingDecl(ID) &&
3804 "We shouldn't load the namespace in the front of delayed "
3805 "namespace lexical and visible block");
3806 }
3807 break;
3808 }
3809
3811 if (F.LocalNumObjCCategoriesInMap != 0)
3812 return llvm::createStringError(
3813 std::errc::illegal_byte_sequence,
3814 "duplicate OBJC_CATEGORIES_MAP record in AST file");
3815
3817 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
3818 break;
3819
3820 case OBJC_CATEGORIES:
3821 F.ObjCCategories.swap(Record);
3822 break;
3823
3825 // Later tables overwrite earlier ones.
3826 // FIXME: Modules will have trouble with this.
3827 CUDASpecialDeclRefs.clear();
3828 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3829 CUDASpecialDeclRefs.push_back(
3830 getGlobalDeclID(F, LocalDeclID(Record[I])));
3831 break;
3832
3834 F.HeaderFileInfoTableData = Blob.data();
3836 if (Record[0]) {
3838 = HeaderFileInfoLookupTable::Create(
3839 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3840 (const unsigned char *)F.HeaderFileInfoTableData,
3841 HeaderFileInfoTrait(*this, F,
3842 &PP.getHeaderSearchInfo(),
3843 Blob.data() + Record[2]));
3844
3845 PP.getHeaderSearchInfo().SetExternalSource(this);
3846 if (!PP.getHeaderSearchInfo().getExternalLookup())
3847 PP.getHeaderSearchInfo().SetExternalLookup(this);
3848 }
3849 break;
3850
3851 case FP_PRAGMA_OPTIONS:
3852 // Later tables overwrite earlier ones.
3853 FPPragmaOptions.swap(Record);
3854 break;
3855
3856 case OPENCL_EXTENSIONS:
3857 for (unsigned I = 0, E = Record.size(); I != E; ) {
3858 auto Name = ReadString(Record, I);
3859 auto &OptInfo = OpenCLExtensions.OptMap[Name];
3860 OptInfo.Supported = Record[I++] != 0;
3861 OptInfo.Enabled = Record[I++] != 0;
3862 OptInfo.WithPragma = Record[I++] != 0;
3863 OptInfo.Avail = Record[I++];
3864 OptInfo.Core = Record[I++];
3865 OptInfo.Opt = Record[I++];
3866 }
3867 break;
3868
3870 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3871 TentativeDefinitions.push_back(
3872 getGlobalDeclID(F, LocalDeclID(Record[I])));
3873 break;
3874
3875 case KNOWN_NAMESPACES:
3876 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3877 KnownNamespaces.push_back(getGlobalDeclID(F, LocalDeclID(Record[I])));
3878 break;
3879
3880 case UNDEFINED_BUT_USED:
3881 if (Record.size() % 2 != 0)
3882 return llvm::createStringError(std::errc::illegal_byte_sequence,
3883 "invalid undefined-but-used record");
3884 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3885 UndefinedButUsed.push_back(
3886 {getGlobalDeclID(F, LocalDeclID(Record[I++])),
3887 ReadSourceLocation(F, Record, I).getRawEncoding()});
3888 }
3889 break;
3890
3892 for (unsigned I = 0, N = Record.size(); I != N;) {
3893 DelayedDeleteExprs.push_back(
3894 getGlobalDeclID(F, LocalDeclID(Record[I++])).get());
3895 const uint64_t Count = Record[I++];
3896 DelayedDeleteExprs.push_back(Count);
3897 for (uint64_t C = 0; C < Count; ++C) {
3898 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3899 bool IsArrayForm = Record[I++] == 1;
3900 DelayedDeleteExprs.push_back(IsArrayForm);
3901 }
3902 }
3903 break;
3904
3905 case IMPORTED_MODULES:
3906 if (!F.isModule()) {
3907 // If we aren't loading a module (which has its own exports), make
3908 // all of the imported modules visible.
3909 // FIXME: Deal with macros-only imports.
3910 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3911 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3912 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3913 if (GlobalID) {
3914 PendingImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
3915 if (DeserializationListener)
3916 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3917 }
3918 }
3919 }
3920 break;
3921
3922 case MACRO_OFFSET: {
3923 if (F.LocalNumMacros != 0)
3924 return llvm::createStringError(
3925 std::errc::illegal_byte_sequence,
3926 "duplicate MACRO_OFFSET record in AST file");
3927 F.MacroOffsets = (const uint32_t *)Blob.data();
3928 F.LocalNumMacros = Record[0];
3929 unsigned LocalBaseMacroID = Record[1];
3931 F.BaseMacroID = getTotalNumMacros();
3932
3933 if (F.LocalNumMacros > 0) {
3934 // Introduce the global -> local mapping for macros within this module.
3935 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3936
3937 // Introduce the local -> global mapping for macros within this module.
3939 std::make_pair(LocalBaseMacroID,
3940 F.BaseMacroID - LocalBaseMacroID));
3941
3942 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3943 }
3944 break;
3945 }
3946
3948 LateParsedTemplates.emplace_back(
3949 std::piecewise_construct, std::forward_as_tuple(&F),
3950 std::forward_as_tuple(Record.begin(), Record.end()));
3951 break;
3952
3954 if (Record.size() != 1)
3955 return llvm::createStringError(std::errc::illegal_byte_sequence,
3956 "invalid pragma optimize record");
3957 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3958 break;
3959
3961 if (Record.size() != 1)
3962 return llvm::createStringError(std::errc::illegal_byte_sequence,
3963 "invalid pragma ms_struct record");
3964 PragmaMSStructState = Record[0];
3965 break;
3966
3968 if (Record.size() != 2)
3969 return llvm::createStringError(
3970 std::errc::illegal_byte_sequence,
3971 "invalid pragma pointers to members record");
3972 PragmaMSPointersToMembersState = Record[0];
3973 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3974 break;
3975
3977 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3978 UnusedLocalTypedefNameCandidates.push_back(
3979 getGlobalDeclID(F, LocalDeclID(Record[I])));
3980 break;
3981
3983 if (Record.size() != 1)
3984 return llvm::createStringError(std::errc::illegal_byte_sequence,
3985 "invalid cuda pragma options record");
3986 ForceHostDeviceDepth = Record[0];
3987 break;
3988
3990 if (Record.size() < 3)
3991 return llvm::createStringError(std::errc::illegal_byte_sequence,
3992 "invalid pragma pack record");
3993 PragmaAlignPackCurrentValue = ReadAlignPackInfo(Record[0]);
3994 PragmaAlignPackCurrentLocation = ReadSourceLocation(F, Record[1]);
3995 unsigned NumStackEntries = Record[2];
3996 unsigned Idx = 3;
3997 // Reset the stack when importing a new module.
3998 PragmaAlignPackStack.clear();
3999 for (unsigned I = 0; I < NumStackEntries; ++I) {
4000 PragmaAlignPackStackEntry Entry;
4001 Entry.Value = ReadAlignPackInfo(Record[Idx++]);
4002 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
4003 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
4004 PragmaAlignPackStrings.push_back(ReadString(Record, Idx));
4005 Entry.SlotLabel = PragmaAlignPackStrings.back();
4006 PragmaAlignPackStack.push_back(Entry);
4007 }
4008 break;
4009 }
4010
4012 if (Record.size() < 3)
4013 return llvm::createStringError(std::errc::illegal_byte_sequence,
4014 "invalid pragma float control record");
4015 FpPragmaCurrentValue = FPOptionsOverride::getFromOpaqueInt(Record[0]);
4016 FpPragmaCurrentLocation = ReadSourceLocation(F, Record[1]);
4017 unsigned NumStackEntries = Record[2];
4018 unsigned Idx = 3;
4019 // Reset the stack when importing a new module.
4020 FpPragmaStack.clear();
4021 for (unsigned I = 0; I < NumStackEntries; ++I) {
4022 FpPragmaStackEntry Entry;
4023 Entry.Value = FPOptionsOverride::getFromOpaqueInt(Record[Idx++]);
4024 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
4025 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
4026 FpPragmaStrings.push_back(ReadString(Record, Idx));
4027 Entry.SlotLabel = FpPragmaStrings.back();
4028 FpPragmaStack.push_back(Entry);
4029 }
4030 break;
4031 }
4032
4034 for (unsigned I = 0, N = Record.size(); I != N; ++I)
4035 DeclsToCheckForDeferredDiags.insert(
4036 getGlobalDeclID(F, LocalDeclID(Record[I])));
4037 break;
4038 }
4039 }
4040}
4041
4042void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
4043 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
4044
4045 // Additional remapping information.
4046 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
4047 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
4048 F.ModuleOffsetMap = StringRef();
4049
4050 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
4051 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
4052 F.SLocRemap.insert(std::make_pair(0U, 0));
4053 F.SLocRemap.insert(std::make_pair(2U, 1));
4054 }
4055
4056 // Continuous range maps we may be updating in our module.
4057 using SLocRemapBuilder =
4059 2>::Builder;
4061 SLocRemapBuilder SLocRemap(F.SLocRemap);
4062 RemapBuilder IdentifierRemap(F.IdentifierRemap);
4063 RemapBuilder MacroRemap(F.MacroRemap);
4064 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
4065 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
4066 RemapBuilder SelectorRemap(F.SelectorRemap);
4067 RemapBuilder DeclRemap(F.DeclRemap);
4068 RemapBuilder TypeRemap(F.TypeRemap);
4069
4070 while (Data < DataEnd) {
4071 // FIXME: Looking up dependency modules by filename is horrible. Let's
4072 // start fixing this with prebuilt, explicit and implicit modules and see
4073 // how it goes...
4074 using namespace llvm::support;
4075 ModuleKind Kind = static_cast<ModuleKind>(
4076 endian::readNext<uint8_t, llvm::endianness::little>(Data));
4077 uint16_t Len = endian::readNext<uint16_t, llvm::endianness::little>(Data);
4078 StringRef Name = StringRef((const char*)Data, Len);
4079 Data += Len;
4082 ? ModuleMgr.lookupByModuleName(Name)
4083 : ModuleMgr.lookupByFileName(Name));
4084 if (!OM) {
4085 std::string Msg =
4086 "SourceLocation remap refers to unknown module, cannot find ";
4087 Msg.append(std::string(Name));
4088 Error(Msg);
4089 return;
4090 }
4091
4092 SourceLocation::UIntTy SLocOffset =
4093 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4094 uint32_t IdentifierIDOffset =
4095 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4096 uint32_t MacroIDOffset =
4097 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4098 uint32_t PreprocessedEntityIDOffset =
4099 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4100 uint32_t SubmoduleIDOffset =
4101 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4102 uint32_t SelectorIDOffset =
4103 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4104 uint32_t DeclIDOffset =
4105 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4106 uint32_t TypeIndexOffset =
4107 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4108
4109 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
4110 RemapBuilder &Remap) {
4111 constexpr uint32_t None = std::numeric_limits<uint32_t>::max();
4112 if (Offset != None)
4113 Remap.insert(std::make_pair(Offset,
4114 static_cast<int>(BaseOffset - Offset)));
4115 };
4116
4117 constexpr SourceLocation::UIntTy SLocNone =
4118 std::numeric_limits<SourceLocation::UIntTy>::max();
4119 if (SLocOffset != SLocNone)
4120 SLocRemap.insert(std::make_pair(
4121 SLocOffset, static_cast<SourceLocation::IntTy>(
4122 OM->SLocEntryBaseOffset - SLocOffset)));
4123
4124 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
4125 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
4126 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
4127 PreprocessedEntityRemap);
4128 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
4129 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
4130 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
4131 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
4132
4133 // Global -> local mappings.
4134 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
4135 }
4136}
4137
4139ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
4140 const ModuleFile *ImportedBy,
4141 unsigned ClientLoadCapabilities) {
4142 unsigned Idx = 0;
4143 F.ModuleMapPath = ReadPath(F, Record, Idx);
4144
4145 // Try to resolve ModuleName in the current header search context and
4146 // verify that it is found in the same module map file as we saved. If the
4147 // top-level AST file is a main file, skip this check because there is no
4148 // usable header search context.
4149 assert(!F.ModuleName.empty() &&
4150 "MODULE_NAME should come before MODULE_MAP_FILE");
4151 if (PP.getPreprocessorOpts().ModulesCheckRelocated &&
4152 F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
4153 // An implicitly-loaded module file should have its module listed in some
4154 // module map file that we've already loaded.
4155 Module *M =
4156 PP.getHeaderSearchInfo().lookupModule(F.ModuleName, F.ImportLoc);
4157 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
4158 OptionalFileEntryRef ModMap =
4159 M ? Map.getModuleMapFileForUniquing(M) : std::nullopt;
4160 // Don't emit module relocation error if we have -fno-validate-pch
4161 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
4163 !ModMap) {
4164 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) {
4165 if (auto ASTFE = M ? M->getASTFile() : std::nullopt) {
4166 // This module was defined by an imported (explicit) module.
4167 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
4168 << ASTFE->getName();
4169 } else {
4170 // This module was built with a different module map.
4171 Diag(diag::err_imported_module_not_found)
4172 << F.ModuleName << F.FileName
4173 << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath
4174 << !ImportedBy;
4175 // In case it was imported by a PCH, there's a chance the user is
4176 // just missing to include the search path to the directory containing
4177 // the modulemap.
4178 if (ImportedBy && ImportedBy->Kind == MK_PCH)
4179 Diag(diag::note_imported_by_pch_module_not_found)
4180 << llvm::sys::path::parent_path(F.ModuleMapPath);
4181 }
4182 }
4183 return OutOfDate;
4184 }
4185
4186 assert(M && M->Name == F.ModuleName && "found module with different name");
4187
4188 // Check the primary module map file.
4189 auto StoredModMap = FileMgr.getFile(F.ModuleMapPath);
4190 if (!StoredModMap || *StoredModMap != ModMap) {
4191 assert(ModMap && "found module is missing module map file");
4192 assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
4193 "top-level import should be verified");
4194 bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
4195 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4196 Diag(diag::err_imported_module_modmap_changed)
4197 << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
4198 << ModMap->getName() << F.ModuleMapPath << NotImported;
4199 return OutOfDate;
4200 }
4201
4202 ModuleMap::AdditionalModMapsSet AdditionalStoredMaps;
4203 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
4204 // FIXME: we should use input files rather than storing names.
4205 std::string Filename = ReadPath(F, Record, Idx);
4206 auto SF = FileMgr.getOptionalFileRef(Filename, false, false);
4207 if (!SF) {
4208 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4209 Error("could not find file '" + Filename +"' referenced by AST file");
4210 return OutOfDate;
4211 }
4212 AdditionalStoredMaps.insert(*SF);
4213 }
4214
4215 // Check any additional module map files (e.g. module.private.modulemap)
4216 // that are not in the pcm.
4217 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
4218 for (FileEntryRef ModMap : *AdditionalModuleMaps) {
4219 // Remove files that match
4220 // Note: SmallPtrSet::erase is really remove
4221 if (!AdditionalStoredMaps.erase(ModMap)) {
4222 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4223 Diag(diag::err_module_different_modmap)
4224 << F.ModuleName << /*new*/0 << ModMap.getName();
4225 return OutOfDate;
4226 }
4227 }
4228 }
4229
4230 // Check any additional module map files that are in the pcm, but not
4231 // found in header search. Cases that match are already removed.
4232 for (FileEntryRef ModMap : AdditionalStoredMaps) {
4233 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4234 Diag(diag::err_module_different_modmap)
4235 << F.ModuleName << /*not new*/1 << ModMap.getName();
4236 return OutOfDate;
4237 }
4238 }
4239
4240 if (Listener)
4241 Listener->ReadModuleMapFile(F.ModuleMapPath);
4242 return Success;
4243}
4244
4245/// Move the given method to the back of the global list of methods.
4247 // Find the entry for this selector in the method pool.
4249 = S.MethodPool.find(Method->getSelector());
4250 if (Known == S.MethodPool.end())
4251 return;
4252
4253 // Retrieve the appropriate method list.
4254 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
4255 : Known->second.second;
4256 bool Found = false;
4257 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
4258 if (!Found) {
4259 if (List->getMethod() == Method) {
4260 Found = true;
4261 } else {
4262 // Keep searching.
4263 continue;
4264 }
4265 }
4266
4267 if (List->getNext())
4268 List->setMethod(List->getNext()->getMethod());
4269 else
4270 List->setMethod(Method);
4271 }
4272}
4273
4275 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
4276 for (Decl *D : Names) {
4277 bool wasHidden = !D->isUnconditionallyVisible();
4278 D->setVisibleDespiteOwningModule();
4279
4280 if (wasHidden && SemaObj) {
4281 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
4282 moveMethodToBackOfGlobalList(*SemaObj, Method);
4283 }
4284 }
4285 }
4286}
4287
4289 Module::NameVisibilityKind NameVisibility,
4290 SourceLocation ImportLoc) {
4293 Stack.push_back(Mod);
4294 while (!Stack.empty()) {
4295 Mod = Stack.pop_back_val();
4296
4297 if (NameVisibility <= Mod->NameVisibility) {
4298 // This module already has this level of visibility (or greater), so
4299 // there is nothing more to do.
4300 continue;
4301 }
4302
4303 if (Mod->isUnimportable()) {
4304 // Modules that aren't importable cannot be made visible.
4305 continue;
4306 }
4307
4308 // Update the module's name visibility.
4309 Mod->NameVisibility = NameVisibility;
4310
4311 // If we've already deserialized any names from this module,
4312 // mark them as visible.
4313 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
4314 if (Hidden != HiddenNamesMap.end()) {
4315 auto HiddenNames = std::move(*Hidden);
4316 HiddenNamesMap.erase(Hidden);
4317 makeNamesVisible(HiddenNames.second, HiddenNames.first);
4318 assert(!HiddenNamesMap.contains(Mod) &&
4319 "making names visible added hidden names");
4320 }
4321
4322 // Push any exported modules onto the stack to be marked as visible.
4324 Mod->getExportedModules(Exports);
4326 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
4327 Module *Exported = *I;
4328 if (Visited.insert(Exported).second)
4329 Stack.push_back(Exported);
4330 }
4331 }
4332}
4333
4334/// We've merged the definition \p MergedDef into the existing definition
4335/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
4336/// visible.
4338 NamedDecl *MergedDef) {
4339 if (!Def->isUnconditionallyVisible()) {
4340 // If MergedDef is visible or becomes visible, make the definition visible.
4341 if (MergedDef->isUnconditionallyVisible())
4343 else {
4344 getContext().mergeDefinitionIntoModule(
4345 Def, MergedDef->getImportedOwningModule(),
4346 /*NotifyListeners*/ false);
4347 PendingMergedDefinitionsToDeduplicate.insert(Def);
4348 }
4349 }
4350}
4351
4353 if (GlobalIndex)
4354 return false;
4355
4356 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
4357 !PP.getLangOpts().Modules)
4358 return true;
4359
4360 // Try to load the global index.
4361 TriedLoadingGlobalIndex = true;
4362 StringRef ModuleCachePath
4363 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
4364 std::pair<GlobalModuleIndex *, llvm::Error> Result =
4365 GlobalModuleIndex::readIndex(ModuleCachePath);
4366 if (llvm::Error Err = std::move(Result.second)) {
4367 assert(!Result.first);
4368 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
4369 return true;
4370 }
4371
4372 GlobalIndex.reset(Result.first);
4373 ModuleMgr.setGlobalIndex(GlobalIndex.get());
4374 return false;
4375}
4376
4378 return PP.getLangOpts().Modules && UseGlobalIndex &&
4379 !hasGlobalIndex() && TriedLoadingGlobalIndex;
4380}
4381
4383 // Overwrite the timestamp file contents so that file's mtime changes.
4384 std::string TimestampFilename = MF.getTimestampFilename();
4385 std::error_code EC;
4386 llvm::raw_fd_ostream OS(TimestampFilename, EC,
4387 llvm::sys::fs::OF_TextWithCRLF);
4388 if (EC)
4389 return;
4390 OS << "Timestamp file\n";
4391 OS.close();
4392 OS.clear_error(); // Avoid triggering a fatal error.
4393}
4394
4395/// Given a cursor at the start of an AST file, scan ahead and drop the
4396/// cursor into the start of the given block ID, returning false on success and
4397/// true on failure.
4398static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
4399 while (true) {
4400 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
4401 if (!MaybeEntry) {
4402 // FIXME this drops errors on the floor.
4403 consumeError(MaybeEntry.takeError());
4404 return true;
4405 }
4406 llvm::BitstreamEntry Entry = MaybeEntry.get();
4407
4408 switch (Entry.Kind) {
4409 case llvm::BitstreamEntry::Error:
4410 case llvm::BitstreamEntry::EndBlock:
4411 return true;
4412
4413 case llvm::BitstreamEntry::Record:
4414 // Ignore top-level records.
4415 if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
4416 break;
4417 else {
4418 // FIXME this drops errors on the floor.
4419 consumeError(Skipped.takeError());
4420 return true;
4421 }
4422
4423 case llvm::BitstreamEntry::SubBlock:
4424 if (Entry.ID == BlockID) {
4425 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
4426 // FIXME this drops the error on the floor.
4427 consumeError(std::move(Err));
4428 return true;
4429 }
4430 // Found it!
4431 return false;
4432 }
4433
4434 if (llvm::Error Err = Cursor.SkipBlock()) {
4435 // FIXME this drops the error on the floor.
4436 consumeError(std::move(Err));
4437 return true;
4438 }
4439 }
4440 }
4441}
4442
4444 SourceLocation ImportLoc,
4445 unsigned ClientLoadCapabilities,
4446 ModuleFile **NewLoadedModuleFile) {
4447 llvm::TimeTraceScope scope("ReadAST", FileName);
4448
4449 llvm::SaveAndRestore SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
4451 CurrentDeserializingModuleKind, Type);
4452
4453 // Defer any pending actions until we get to the end of reading the AST file.
4454 Deserializing AnASTFile(this);
4455
4456 // Bump the generation number.
4457 unsigned PreviousGeneration = 0;
4458 if (ContextObj)
4459 PreviousGeneration = incrementGeneration(*ContextObj);
4460
4461 unsigned NumModules = ModuleMgr.size();
4463 if (ASTReadResult ReadResult =
4464 ReadASTCore(FileName, Type, ImportLoc,
4465 /*ImportedBy=*/nullptr, Loaded, 0, 0, ASTFileSignature(),
4466 ClientLoadCapabilities)) {
4467 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules);
4468
4469 // If we find that any modules are unusable, the global index is going
4470 // to be out-of-date. Just remove it.
4471 GlobalIndex.reset();
4472 ModuleMgr.setGlobalIndex(nullptr);
4473 return ReadResult;
4474 }
4475
4476 if (NewLoadedModuleFile && !Loaded.empty())
4477 *NewLoadedModuleFile = Loaded.back().Mod;
4478
4479 // Here comes stuff that we only do once the entire chain is loaded. Do *not*
4480 // remove modules from this point. Various fields are updated during reading
4481 // the AST block and removing the modules would result in dangling pointers.
4482 // They are generally only incidentally dereferenced, ie. a binary search
4483 // runs over `GlobalSLocEntryMap`, which could cause an invalid module to
4484 // be dereferenced but it wouldn't actually be used.
4485
4486 // Load the AST blocks of all of the modules that we loaded. We can still
4487 // hit errors parsing the ASTs at this point.
4488 for (ImportedModule &M : Loaded) {
4489 ModuleFile &F = *M.Mod;
4490 llvm::TimeTraceScope Scope2("Read Loaded AST", F.ModuleName);
4491
4492 // Read the AST block.
4493 if (llvm::Error Err = ReadASTBlock(F, ClientLoadCapabilities)) {
4494 Error(std::move(Err));
4495 return Failure;
4496 }
4497
4498 // The AST block should always have a definition for the main module.
4499 if (F.isModule() && !F.DidReadTopLevelSubmodule) {
4500 Error(diag::err_module_file_missing_top_level_submodule, F.FileName);
4501 return Failure;
4502 }
4503
4504 // Read the extension blocks.
4506 if (llvm::Error Err = ReadExtensionBlock(F)) {
4507 Error(std::move(Err));
4508 return Failure;
4509 }
4510 }
4511
4512 // Once read, set the ModuleFile bit base offset and update the size in
4513 // bits of all files we've seen.
4514 F.GlobalBitOffset = TotalModulesSizeInBits;
4515 TotalModulesSizeInBits += F.SizeInBits;
4516 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
4517 }
4518
4519 // Preload source locations and interesting indentifiers.
4520 for (ImportedModule &M : Loaded) {
4521 ModuleFile &F = *M.Mod;
4522
4523 // Map the original source file ID into the ID space of the current
4524 // compilation.
4526 F.OriginalSourceFileID = TranslateFileID(F, F.OriginalSourceFileID);
4527
4528 for (auto Offset : F.PreloadIdentifierOffsets) {
4529 const unsigned char *Data = F.IdentifierTableData + Offset;
4530
4531 ASTIdentifierLookupTrait Trait(*this, F);
4532 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
4533 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
4534
4535 IdentifierInfo *II;
4536 if (!PP.getLangOpts().CPlusPlus) {
4537 // Identifiers present in both the module file and the importing
4538 // instance are marked out-of-date so that they can be deserialized
4539 // on next use via ASTReader::updateOutOfDateIdentifier().
4540 // Identifiers present in the module file but not in the importing
4541 // instance are ignored for now, preventing growth of the identifier
4542 // table. They will be deserialized on first use via ASTReader::get().
4543 auto It = PP.getIdentifierTable().find(Key);
4544 if (It == PP.getIdentifierTable().end())
4545 continue;
4546 II = It->second;
4547 } else {
4548 // With C++ modules, not many identifiers are considered interesting.
4549 // All identifiers in the module file can be placed into the identifier
4550 // table of the importing instance and marked as out-of-date. This makes
4551 // ASTReader::get() a no-op, and deserialization will take place on
4552 // first/next use via ASTReader::updateOutOfDateIdentifier().
4553 II = &PP.getIdentifierTable().getOwn(Key);
4554 }
4555
4556 II->setOutOfDate(true);
4557
4558 // Mark this identifier as being from an AST file so that we can track
4559 // whether we need to serialize it.
4560 markIdentifierFromAST(*this, *II);
4561
4562 // Associate the ID with the identifier so that the writer can reuse it.
4563 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
4564 SetIdentifierInfo(ID, II);
4565 }
4566 }
4567
4568 // Builtins and library builtins have already been initialized. Mark all
4569 // identifiers as out-of-date, so that they are deserialized on first use.
4570 if (Type == MK_PCH || Type == MK_Preamble || Type == MK_MainFile)
4571 for (auto &Id : PP.getIdentifierTable())
4572 Id.second->setOutOfDate(true);
4573
4574 // Mark selectors as out of date.
4575 for (const auto &Sel : SelectorGeneration)
4576 SelectorOutOfDate[Sel.first] = true;
4577
4578 // Setup the import locations and notify the module manager that we've
4579 // committed to these module files.
4580 for (ImportedModule &M : Loaded) {
4581 ModuleFile &F = *M.Mod;
4582
4583 ModuleMgr.moduleFileAccepted(&F);
4584
4585 // Set the import location.
4586 F.DirectImportLoc = ImportLoc;
4587 // FIXME: We assume that locations from PCH / preamble do not need
4588 // any translation.
4589 if (!M.ImportedBy)
4590 F.ImportLoc = M.ImportLoc;
4591 else
4592 F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
4593 }
4594
4595 // Resolve any unresolved module exports.
4596 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4597 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
4598 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
4599 Module *ResolvedMod = getSubmodule(GlobalID);
4600
4601 switch (Unresolved.Kind) {
4602 case UnresolvedModuleRef::Conflict:
4603 if (ResolvedMod) {
4604 Module::Conflict Conflict;
4605 Conflict.Other = ResolvedMod;
4606 Conflict.Message = Unresolved.String.str();
4607 Unresolved.Mod->Conflicts.push_back(Conflict);
4608 }
4609 continue;
4610
4611 case UnresolvedModuleRef::Import:
4612 if (ResolvedMod)
4613 Unresolved.Mod->Imports.insert(ResolvedMod);
4614 continue;
4615
4616 case UnresolvedModuleRef::Affecting:
4617 if (ResolvedMod)
4618 Unresolved.Mod->AffectingClangModules.insert(ResolvedMod);
4619 continue;
4620
4621 case UnresolvedModuleRef::Export:
4622 if (ResolvedMod || Unresolved.IsWildcard)
4623 Unresolved.Mod->Exports.push_back(
4624 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
4625 continue;
4626 }
4627 }
4628 UnresolvedModuleRefs.clear();
4629
4630 // FIXME: How do we load the 'use'd modules? They may not be submodules.
4631 // Might be unnecessary as use declarations are only used to build the
4632 // module itself.
4633
4634 if (ContextObj)
4635 InitializeContext();
4636
4637 if (SemaObj)
4638 UpdateSema();
4639
4640 if (DeserializationListener)
4641 DeserializationListener->ReaderInitialized(this);
4642
4643 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
4644 if (PrimaryModule.OriginalSourceFileID.isValid()) {
4645 // If this AST file is a precompiled preamble, then set the
4646 // preamble file ID of the source manager to the file source file
4647 // from which the preamble was built.
4648 if (Type == MK_Preamble) {
4649 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
4650 } else if (Type == MK_MainFile) {
4651 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
4652 }
4653 }
4654
4655 // For any Objective-C class definitions we have already loaded, make sure
4656 // that we load any additional categories.
4657 if (ContextObj) {
4658 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
4659 loadObjCCategories(GlobalDeclID(ObjCClassesLoaded[I]->getGlobalID()),
4660 ObjCClassesLoaded[I], PreviousGeneration);
4661 }
4662 }
4663
4664 HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
4666 // Now we are certain that the module and all modules it depends on are
4667 // up-to-date. For implicitly-built module files, ensure the corresponding
4668 // timestamp files are up-to-date in this build session.
4669 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
4670 ImportedModule &M = Loaded[I];
4671 if (M.Mod->Kind == MK_ImplicitModule &&
4672 M.Mod->InputFilesValidationTimestamp < HSOpts.BuildSessionTimestamp)
4673 updateModuleTimestamp(*M.Mod);
4674 }
4675 }
4676
4677 return Success;
4678}
4679
4680static ASTFileSignature readASTFileSignature(StringRef PCH);
4681
4682/// Whether \p Stream doesn't start with the AST/PCH file magic number 'CPCH'.
4683static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
4684 // FIXME checking magic headers is done in other places such as
4685 // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
4686 // always done the same. Unify it all with a helper.
4687 if (!Stream.canSkipToPos(4))
4688 return llvm::createStringError(std::errc::illegal_byte_sequence,
4689 "file too small to contain AST file magic");
4690 for (unsigned C : {'C', 'P', 'C', 'H'})
4691 if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
4692 if (Res.get() != C)
4693 return llvm::createStringError(
4694 std::errc::illegal_byte_sequence,
4695 "file doesn't start with AST file magic");
4696 } else
4697 return Res.takeError();
4698 return llvm::Error::success();
4699}
4700
4702 switch (Kind) {
4703 case MK_PCH:
4704 return 0; // PCH
4705 case MK_ImplicitModule:
4706 case MK_ExplicitModule:
4707 case MK_PrebuiltModule:
4708 return 1; // module
4709 case MK_MainFile:
4710 case MK_Preamble:
4711 return 2; // main source file
4712 }
4713 llvm_unreachable("unknown module kind");
4714}
4715
4717ASTReader::ReadASTCore(StringRef FileName,
4719 SourceLocation ImportLoc,
4720 ModuleFile *ImportedBy,
4722 off_t ExpectedSize, time_t ExpectedModTime,
4723 ASTFileSignature ExpectedSignature,
4724 unsigned ClientLoadCapabilities) {
4725 ModuleFile *M;
4726 std::string ErrorStr;
4728 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
4729 getGeneration(), ExpectedSize, ExpectedModTime,
4730 ExpectedSignature, readASTFileSignature,
4731 M, ErrorStr);
4732
4733 switch (AddResult) {
4735 Diag(diag::remark_module_import)
4736 << M->ModuleName << M->FileName << (ImportedBy ? true : false)
4737 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
4738 return Success;
4739
4741 // Load module file below.
4742 break;
4743
4745 // The module file was missing; if the client can handle that, return
4746 // it.
4747 if (ClientLoadCapabilities & ARR_Missing)
4748 return Missing;
4749
4750 // Otherwise, return an error.
4751 Diag(diag::err_ast_file_not_found)
4752 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
4753 << ErrorStr;
4754 return Failure;
4755
4757 // We couldn't load the module file because it is out-of-date. If the
4758 // client can handle out-of-date, return it.
4759 if (ClientLoadCapabilities & ARR_OutOfDate)
4760 return OutOfDate;
4761
4762 // Otherwise, return an error.
4763 Diag(diag::err_ast_file_out_of_date)
4764 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
4765 << ErrorStr;
4766 return Failure;
4767 }
4768
4769 assert(M && "Missing module file");
4770
4771 bool ShouldFinalizePCM = false;
4772 auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() {
4773 auto &MC = getModuleManager().getModuleCache();
4774 if (ShouldFinalizePCM)
4775 MC.finalizePCM(FileName);
4776 else
4777 MC.tryToDropPCM(FileName);
4778 });
4779 ModuleFile &F = *M;
4780 BitstreamCursor &Stream = F.Stream;
4781 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
4782 F.SizeInBits = F.Buffer->getBufferSize() * 8;
4783
4784 // Sniff for the signature.
4785 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4786 Diag(diag::err_ast_file_invalid)
4787 << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
4788 return Failure;
4789 }
4790
4791 // This is used for compatibility with older PCH formats.
4792 bool HaveReadControlBlock = false;
4793 while (true) {
4794 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4795 if (!MaybeEntry) {
4796 Error(MaybeEntry.takeError());
4797 return Failure;
4798 }
4799 llvm::BitstreamEntry Entry = MaybeEntry.get();
4800
4801 switch (Entry.Kind) {
4802 case llvm::BitstreamEntry::Error:
4803 case llvm::BitstreamEntry::Record:
4804 case llvm::BitstreamEntry::EndBlock:
4805 Error("invalid record at top-level of AST file");
4806 return Failure;
4807
4808 case llvm::BitstreamEntry::SubBlock:
4809 break;
4810 }
4811
4812 switch (Entry.ID) {
4813 case CONTROL_BLOCK_ID:
4814 HaveReadControlBlock = true;
4815 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
4816 case Success:
4817 // Check that we didn't try to load a non-module AST file as a module.
4818 //
4819 // FIXME: Should we also perform the converse check? Loading a module as
4820 // a PCH file sort of works, but it's a bit wonky.
4822 Type == MK_PrebuiltModule) &&
4823 F.ModuleName.empty()) {
4824 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4825 if (Result != OutOfDate ||
4826 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4827 Diag(diag::err_module_file_not_module) << FileName;
4828 return Result;
4829 }
4830 break;
4831
4832 case Failure: return Failure;
4833 case Missing: return Missing;
4834 case OutOfDate: return OutOfDate;
4835 case VersionMismatch: return VersionMismatch;
4836 case ConfigurationMismatch: return ConfigurationMismatch;
4837 case HadErrors: return HadErrors;
4838 }
4839 break;
4840
4841 case AST_BLOCK_ID:
4842 if (!HaveReadControlBlock) {
4843 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
4844 Diag(diag::err_pch_version_too_old);
4845 return VersionMismatch;
4846 }
4847
4848 // Record that we've loaded this module.
4849 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4850 ShouldFinalizePCM = true;
4851 return Success;
4852
4853 default:
4854 if (llvm::Error Err = Stream.SkipBlock()) {
4855 Error(std::move(Err));
4856 return Failure;
4857 }
4858 break;
4859 }
4860 }
4861
4862 llvm_unreachable("unexpected break; expected return");
4863}
4864
4866ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4867 unsigned ClientLoadCapabilities) {
4868 const HeaderSearchOptions &HSOpts =
4869 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4870 bool AllowCompatibleConfigurationMismatch =
4872 bool DisableValidation = shouldDisableValidationForFile(F);
4873
4874 ASTReadResult Result = readUnhashedControlBlockImpl(
4875 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4876 Listener.get(),
4877 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4878
4879 // If F was directly imported by another module, it's implicitly validated by
4880 // the importing module.
4881 if (DisableValidation || WasImportedBy ||
4882 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4883 return Success;
4884
4885 if (Result == Failure) {
4886 Error("malformed block record in AST file");
4887 return Failure;
4888 }
4889
4890 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
4891 // If this module has already been finalized in the ModuleCache, we're stuck
4892 // with it; we can only load a single version of each module.
4893 //
4894 // This can happen when a module is imported in two contexts: in one, as a
4895 // user module; in another, as a system module (due to an import from
4896 // another module marked with the [system] flag). It usually indicates a
4897 // bug in the module map: this module should also be marked with [system].
4898 //
4899 // If -Wno-system-headers (the default), and the first import is as a
4900 // system module, then validation will fail during the as-user import,
4901 // since -Werror flags won't have been validated. However, it's reasonable
4902 // to treat this consistently as a system module.
4903 //
4904 // If -Wsystem-headers, the PCM on disk was built with
4905 // -Wno-system-headers, and the first import is as a user module, then
4906 // validation will fail during the as-system import since the PCM on disk
4907 // doesn't guarantee that -Werror was respected. However, the -Werror
4908 // flags were checked during the initial as-user import.
4909 if (getModuleManager().getModuleCache().isPCMFinal(F.FileName)) {
4910 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4911 return Success;
4912 }
4913 }
4914
4915 return Result;
4916}
4917
4918ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4919 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4920 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4921 bool ValidateDiagnosticOptions) {
4922 // Initialize a stream.
4923 BitstreamCursor Stream(StreamData);
4924
4925 // Sniff for the signature.
4926 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4927 // FIXME this drops the error on the floor.
4928 consumeError(std::move(Err));
4929 return Failure;
4930 }
4931
4932 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4934 return Failure;
4935
4936 // Read all of the records in the options block.
4937 RecordData Record;
4938 ASTReadResult Result = Success;
4939 while (true) {
4940 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4941 if (!MaybeEntry) {
4942 // FIXME this drops the error on the floor.
4943 consumeError(MaybeEntry.takeError());
4944 return Failure;
4945 }
4946 llvm::BitstreamEntry Entry = MaybeEntry.get();
4947
4948 switch (Entry.Kind) {
4949 case llvm::BitstreamEntry::Error:
4950 case llvm::BitstreamEntry::SubBlock:
4951 return Failure;
4952
4953 case llvm::BitstreamEntry::EndBlock:
4954 return Result;
4955
4956 case llvm::BitstreamEntry::Record:
4957 // The interesting case.
4958 break;
4959 }
4960
4961 // Read and process a record.
4962 Record.clear();
4963 StringRef Blob;
4964 Expected<unsigned> MaybeRecordType =
4965 Stream.readRecord(Entry.ID, Record, &Blob);
4966 if (!MaybeRecordType) {
4967 // FIXME this drops the error.
4968 return Failure;
4969 }
4970 switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
4971 case SIGNATURE:
4972 if (F) {
4973 F->Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
4975 "Dummy AST file signature not backpatched in ASTWriter.");
4976 }
4977 break;
4978 case AST_BLOCK_HASH:
4979 if (F) {
4980 F->ASTBlockHash = ASTFileSignature::create(Blob.begin(), Blob.end());
4982 "Dummy AST block hash not backpatched in ASTWriter.");
4983 }
4984 break;
4985 case DIAGNOSTIC_OPTIONS: {
4986 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4987 if (Listener && ValidateDiagnosticOptions &&
4988 !AllowCompatibleConfigurationMismatch &&
4989 ParseDiagnosticOptions(Record, Complain, *Listener))
4990 Result = OutOfDate; // Don't return early. Read the signature.
4991 break;
4992 }
4993 case HEADER_SEARCH_PATHS: {
4994 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
4995 if (Listener && !AllowCompatibleConfigurationMismatch &&
4996 ParseHeaderSearchPaths(Record, Complain, *Listener))
4997 Result = ConfigurationMismatch;
4998 break;
4999 }
5001 if (!F)
5002 break;
5003 if (F->PragmaDiagMappings.empty())
5004 F->PragmaDiagMappings.swap(Record);
5005 else
5006 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
5007 Record.begin(), Record.end());
5008 break;
5010 if (F)
5011 F->SearchPathUsage = ReadBitVector(Record, Blob);
5012 break;
5013 case VFS_USAGE:
5014 if (F)
5015 F->VFSUsage = ReadBitVector(Record, Blob);
5016 break;
5017 }
5018 }
5019}
5020
5021/// Parse a record and blob containing module file extension metadata.
5024 StringRef Blob,
5025 ModuleFileExtensionMetadata &Metadata) {
5026 if (Record.size() < 4) return true;
5027
5028 Metadata.MajorVersion = Record[0];
5029 Metadata.MinorVersion = Record[1];
5030
5031 unsigned BlockNameLen = Record[2];
5032 unsigned UserInfoLen = Record[3];
5033
5034 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
5035
5036 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
5037 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
5038 Blob.data() + BlockNameLen + UserInfoLen);
5039 return false;
5040}
5041
5042llvm::Error ASTReader::ReadExtensionBlock(ModuleFile &F) {
5043 BitstreamCursor &Stream = F.Stream;
5044
5045 RecordData Record;
5046 while (true) {
5047 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5048 if (!MaybeEntry)
5049 return MaybeEntry.takeError();
5050 llvm::BitstreamEntry Entry = MaybeEntry.get();
5051
5052 switch (Entry.Kind) {
5053 case llvm::BitstreamEntry::SubBlock:
5054 if (llvm::Error Err = Stream.SkipBlock())
5055 return Err;
5056 continue;
5057 case llvm::BitstreamEntry::EndBlock:
5058 return llvm::Error::success();
5059 case llvm::BitstreamEntry::Error:
5060 return llvm::createStringError(std::errc::illegal_byte_sequence,
5061 "malformed block record in AST file");
5062 case llvm::BitstreamEntry::Record:
5063 break;
5064 }
5065
5066 Record.clear();
5067 StringRef Blob;
5068 Expected<unsigned> MaybeRecCode =
5069 Stream.readRecord(Entry.ID, Record, &Blob);
5070 if (!MaybeRecCode)
5071 return MaybeRecCode.takeError();
5072 switch (MaybeRecCode.get()) {
5073 case EXTENSION_METADATA: {
5075 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5076 return llvm::createStringError(
5077 std::errc::illegal_byte_sequence,
5078 "malformed EXTENSION_METADATA in AST file");
5079
5080 // Find a module file extension with this block name.
5081 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
5082 if (Known == ModuleFileExtensions.end()) break;
5083
5084 // Form a reader.
5085 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
5086 F, Stream)) {
5087 F.ExtensionReaders.push_back(std::move(Reader));
5088 }
5089
5090 break;
5091 }
5092 }
5093 }
5094
5095 return llvm::Error::success();
5096}
5097
5099 assert(ContextObj && "no context to initialize");
5100 ASTContext &Context = *ContextObj;
5101
5102 // If there's a listener, notify them that we "read" the translation unit.
5103 if (DeserializationListener)
5104 DeserializationListener->DeclRead(
5106 Context.getTranslationUnitDecl());
5107
5108 // FIXME: Find a better way to deal with collisions between these
5109 // built-in types. Right now, we just ignore the problem.
5110
5111 // Load the special types.
5112 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
5113 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
5114 if (!Context.CFConstantStringTypeDecl)
5115 Context.setCFConstantStringType(GetType(String));
5116 }
5117
5118 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
5119 QualType FileType = GetType(File);
5120 if (FileType.isNull()) {
5121 Error("FILE type is NULL");
5122 return;
5123 }
5124
5125 if (!Context.FILEDecl) {
5126 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
5127 Context.setFILEDecl(Typedef->getDecl());
5128 else {
5129 const TagType *Tag = FileType->getAs<TagType>();
5130 if (!Tag) {
5131 Error("Invalid FILE type in AST file");
5132 return;
5133 }
5134 Context.setFILEDecl(Tag->getDecl());
5135 }
5136 }
5137 }
5138
5139 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
5140 QualType Jmp_bufType = GetType(Jmp_buf);
5141 if (Jmp_bufType.isNull()) {
5142 Error("jmp_buf type is NULL");
5143 return;
5144 }
5145
5146 if (!Context.jmp_bufDecl) {
5147 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
5148 Context.setjmp_bufDecl(Typedef->getDecl());
5149 else {
5150 const TagType *Tag = Jmp_bufType->getAs<TagType>();
5151 if (!Tag) {
5152 Error("Invalid jmp_buf type in AST file");
5153 return;
5154 }
5155 Context.setjmp_bufDecl(Tag->getDecl());
5156 }
5157 }
5158 }
5159
5160 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
5161 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
5162 if (Sigjmp_bufType.isNull()) {
5163 Error("sigjmp_buf type is NULL");
5164 return;
5165 }
5166
5167 if (!Context.sigjmp_bufDecl) {
5168 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
5169 Context.setsigjmp_bufDecl(Typedef->getDecl());
5170 else {
5171 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
5172 assert(Tag && "Invalid sigjmp_buf type in AST file");
5173 Context.setsigjmp_bufDecl(Tag->getDecl());
5174 }
5175 }
5176 }
5177
5178 if (unsigned ObjCIdRedef
5179 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
5180 if (Context.ObjCIdRedefinitionType.isNull())
5181 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
5182 }
5183
5184 if (unsigned ObjCClassRedef
5185 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
5186 if (Context.ObjCClassRedefinitionType.isNull())
5187 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
5188 }
5189
5190 if (unsigned ObjCSelRedef
5191 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
5192 if (Context.ObjCSelRedefinitionType.isNull())
5193 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
5194 }
5195
5196 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
5197 QualType Ucontext_tType = GetType(Ucontext_t);
5198 if (Ucontext_tType.isNull()) {
5199 Error("ucontext_t type is NULL");
5200 return;
5201 }
5202
5203 if (!Context.ucontext_tDecl) {
5204 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
5205 Context.setucontext_tDecl(Typedef->getDecl());
5206 else {
5207 const TagType *Tag = Ucontext_tType->getAs<TagType>();
5208 assert(Tag && "Invalid ucontext_t type in AST file");
5209 Context.setucontext_tDecl(Tag->getDecl());
5210 }
5211 }
5212 }
5213 }
5214
5215 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
5216
5217 // If there were any CUDA special declarations, deserialize them.
5218 if (!CUDASpecialDeclRefs.empty()) {
5219 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
5221 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
5222 }
5223
5224 // Re-export any modules that were imported by a non-module AST file.
5225 // FIXME: This does not make macro-only imports visible again.
5226 for (auto &Import : PendingImportedModules) {
5227 if (Module *Imported = getSubmodule(Import.ID)) {
5228 makeModuleVisible(Imported, Module::AllVisible,
5229 /*ImportLoc=*/Import.ImportLoc);
5230 if (Import.ImportLoc.isValid())
5231 PP.makeModuleVisible(Imported, Import.ImportLoc);
5232 // This updates visibility for Preprocessor only. For Sema, which can be
5233 // nullptr here, we do the same later, in UpdateSema().
5234 }
5235 }
5236
5237 // Hand off these modules to Sema.
5238 PendingImportedModulesSema.append(PendingImportedModules);
5239 PendingImportedModules.clear();
5240}
5241
5243 // Nothing to do for now.
5244}
5245
5246/// Reads and return the signature record from \p PCH's control block, or
5247/// else returns 0.
5249 BitstreamCursor Stream(PCH);
5250 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5251 // FIXME this drops the error on the floor.
5252 consumeError(std::move(Err));
5253 return ASTFileSignature();
5254 }
5255
5256 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5258 return ASTFileSignature();
5259
5260 // Scan for SIGNATURE inside the diagnostic options block.
5262 while (true) {
5264 Stream.advanceSkippingSubblocks();
5265 if (!MaybeEntry) {
5266 // FIXME this drops the error on the floor.
5267 consumeError(MaybeEntry.takeError());
5268 return ASTFileSignature();
5269 }
5270 llvm::BitstreamEntry Entry = MaybeEntry.get();
5271
5272 if (Entry.Kind != llvm::BitstreamEntry::Record)
5273 return ASTFileSignature();
5274
5275 Record.clear();
5276 StringRef Blob;
5277 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5278 if (!MaybeRecord) {
5279 // FIXME this drops the error on the floor.
5280 consumeError(MaybeRecord.takeError());
5281 return ASTFileSignature();
5282 }
5283 if (SIGNATURE == MaybeRecord.get()) {
5284 auto Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
5285 assert(Signature != ASTFileSignature::createDummy() &&
5286 "Dummy AST file signature not backpatched in ASTWriter.");
5287 return Signature;
5288 }
5289 }
5290}
5291
5292/// Retrieve the name of the original source file name
5293/// directly from the AST file, without actually loading the AST
5294/// file.
5296 const std::string &ASTFileName, FileManager &FileMgr,
5297 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
5298 // Open the AST file.
5299 auto Buffer = FileMgr.getBufferForFile(ASTFileName, /*IsVolatile=*/false,
5300 /*RequiresNullTerminator=*/false);
5301 if (!Buffer) {
5302 Diags.Report(diag::err_fe_unable_to_read_pch_file)
5303 << ASTFileName << Buffer.getError().message();
5304 return std::string();
5305 }
5306
5307 // Initialize the stream
5308 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
5309
5310 // Sniff for the signature.
5311 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5312 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
5313 return std::string();
5314 }
5315
5316 // Scan for the CONTROL_BLOCK_ID block.
5317 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
5318 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5319 return std::string();
5320 }
5321
5322 // Scan for ORIGINAL_FILE inside the control block.
5324 while (true) {
5326 Stream.advanceSkippingSubblocks();
5327 if (!MaybeEntry) {
5328 // FIXME this drops errors on the floor.
5329 consumeError(MaybeEntry.takeError());
5330 return std::string();
5331 }
5332 llvm::BitstreamEntry Entry = MaybeEntry.get();
5333
5334 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
5335 return std::string();
5336
5337 if (Entry.Kind != llvm::BitstreamEntry::Record) {
5338 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5339 return std::string();
5340 }
5341
5342 Record.clear();
5343 StringRef Blob;
5344 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5345 if (!MaybeRecord) {
5346 // FIXME this drops the errors on the floor.
5347 consumeError(MaybeRecord.takeError());
5348 return std::string();
5349 }
5350 if (ORIGINAL_FILE == MaybeRecord.get())
5351 return Blob.str();
5352 }
5353}
5354
5355namespace {
5356
5357 class SimplePCHValidator : public ASTReaderListener {
5358 const LangOptions &ExistingLangOpts;
5359 const TargetOptions &ExistingTargetOpts;
5360 const PreprocessorOptions &ExistingPPOpts;
5361 std::string ExistingModuleCachePath;
5362 FileManager &FileMgr;
5363 bool StrictOptionMatches;
5364
5365 public:
5366 SimplePCHValidator(const LangOptions &ExistingLangOpts,
5367 const TargetOptions &ExistingTargetOpts,
5368 const PreprocessorOptions &ExistingPPOpts,
5369 StringRef ExistingModuleCachePath, FileManager &FileMgr,
5370 bool StrictOptionMatches)
5371 : ExistingLangOpts(ExistingLangOpts),
5372 ExistingTargetOpts(ExistingTargetOpts),
5373 ExistingPPOpts(ExistingPPOpts),
5374 ExistingModuleCachePath(ExistingModuleCachePath), FileMgr(FileMgr),
5375 StrictOptionMatches(StrictOptionMatches) {}
5376
5377 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
5378 bool AllowCompatibleDifferences) override {
5379 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
5380 AllowCompatibleDifferences);
5381 }
5382
5383 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
5384 bool AllowCompatibleDifferences) override {
5385 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
5386 AllowCompatibleDifferences);
5387 }
5388
5389 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
5390 StringRef SpecificModuleCachePath,
5391 bool Complain) override {
5392 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5393 ExistingModuleCachePath, nullptr,
5394 ExistingLangOpts, ExistingPPOpts);
5395 }
5396
5397 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
5398 bool ReadMacros, bool Complain,
5399 std::string &SuggestedPredefines) override {
5401 PPOpts, ExistingPPOpts, ReadMacros, /*Diags=*/nullptr, FileMgr,
5402 SuggestedPredefines, ExistingLangOpts,
5403 StrictOptionMatches ? OptionValidateStrictMatches
5405 }
5406 };
5407
5408} // namespace
5409
5411 StringRef Filename, FileManager &FileMgr,
5412 const InMemoryModuleCache &ModuleCache,
5413 const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions,
5414 ASTReaderListener &Listener, bool ValidateDiagnosticOptions,
5415 unsigned ClientLoadCapabilities) {
5416 // Open the AST file.
5417 std::unique_ptr<llvm::MemoryBuffer> OwnedBuffer;
5418 llvm::MemoryBuffer *Buffer = ModuleCache.lookupPCM(Filename);
5419 if (!Buffer) {
5420 // FIXME: We should add the pcm to the InMemoryModuleCache if it could be
5421 // read again later, but we do not have the context here to determine if it
5422 // is safe to change the result of InMemoryModuleCache::getPCMState().
5423
5424 // FIXME: This allows use of the VFS; we do not allow use of the
5425 // VFS when actually loading a module.
5426 auto BufferOrErr = FileMgr.getBufferForFile(Filename);
5427 if (!BufferOrErr)
5428 return true;
5429 OwnedBuffer = std::move(*BufferOrErr);
5430 Buffer = OwnedBuffer.get();
5431 }
5432
5433 // Initialize the stream
5434 StringRef Bytes = PCHContainerRdr.ExtractPCH(*Buffer);
5435 BitstreamCursor Stream(Bytes);
5436
5437 // Sniff for the signature.
5438 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5439 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
5440 return true;
5441 }
5442
5443 // Scan for the CONTROL_BLOCK_ID block.
5445 return true;
5446
5447 bool NeedsInputFiles = Listener.needsInputFileVisitation();
5448 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
5449 bool NeedsImports = Listener.needsImportVisitation();
5450 BitstreamCursor InputFilesCursor;
5451 uint64_t InputFilesOffsetBase = 0;
5452
5454 std::string ModuleDir;
5455 bool DoneWithControlBlock = false;
5456 while (!DoneWithControlBlock) {
5457 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5458 if (!MaybeEntry) {
5459 // FIXME this drops the error on the floor.
5460 consumeError(MaybeEntry.takeError());
5461 return true;
5462 }
5463 llvm::BitstreamEntry Entry = MaybeEntry.get();
5464
5465 switch (Entry.Kind) {
5466 case llvm::BitstreamEntry::SubBlock: {
5467 switch (Entry.ID) {
5468 case OPTIONS_BLOCK_ID: {
5469 std::string IgnoredSuggestedPredefines;
5470 if (ReadOptionsBlock(Stream, ClientLoadCapabilities,
5471 /*AllowCompatibleConfigurationMismatch*/ false,
5472 Listener, IgnoredSuggestedPredefines) != Success)
5473 return true;
5474 break;
5475 }
5476
5478 InputFilesCursor = Stream;
5479 if (llvm::Error Err = Stream.SkipBlock()) {
5480 // FIXME this drops the error on the floor.
5481 consumeError(std::move(Err));
5482 return true;
5483 }
5484 if (NeedsInputFiles &&
5485 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
5486 return true;
5487 InputFilesOffsetBase = InputFilesCursor.GetCurrentBitNo();
5488 break;
5489
5490 default:
5491 if (llvm::Error Err = Stream.SkipBlock()) {
5492 // FIXME this drops the error on the floor.
5493 consumeError(std::move(Err));
5494 return true;
5495 }
5496 break;
5497 }
5498
5499 continue;
5500 }
5501
5502 case llvm::BitstreamEntry::EndBlock:
5503 DoneWithControlBlock = true;
5504 break;
5505
5506 case llvm::BitstreamEntry::Error:
5507 return true;
5508
5509 case llvm::BitstreamEntry::Record:
5510 break;
5511 }
5512
5513 if (DoneWithControlBlock) break;
5514
5515 Record.clear();
5516 StringRef Blob;
5517 Expected<unsigned> MaybeRecCode =
5518 Stream.readRecord(Entry.ID, Record, &Blob);
5519 if (!MaybeRecCode) {
5520 // FIXME this drops the error.
5521 return Failure;
5522 }
5523 switch ((ControlRecordTypes)MaybeRecCode.get()) {
5524 case METADATA:
5525 if (Record[0] != VERSION_MAJOR)
5526 return true;
5527 if (Listener.ReadFullVersionInformation(Blob))
5528 return true;
5529 break;
5530 case MODULE_NAME:
5531 Listener.ReadModuleName(Blob);
5532 break;
5533 case MODULE_DIRECTORY:
5534 ModuleDir = std::string(Blob);
5535 break;
5536 case MODULE_MAP_FILE: {
5537 unsigned Idx = 0;
5538 auto Path = ReadString(Record, Idx);
5539 ResolveImportedPath(Path, ModuleDir);
5540 Listener.ReadModuleMapFile(Path);
5541 break;
5542 }
5543 case INPUT_FILE_OFFSETS: {
5544 if (!NeedsInputFiles)
5545 break;
5546
5547 unsigned NumInputFiles = Record[0];
5548 unsigned NumUserFiles = Record[1];
5549 const llvm::support::unaligned_uint64_t *InputFileOffs =
5550 (const llvm::support::unaligned_uint64_t *)Blob.data();
5551 for (unsigned I = 0; I != NumInputFiles; ++I) {
5552 // Go find this input file.
5553 bool isSystemFile = I >= NumUserFiles;
5554
5555 if (isSystemFile && !NeedsSystemInputFiles)
5556 break; // the rest are system input files
5557
5558 BitstreamCursor &Cursor = InputFilesCursor;
5559 SavedStreamPosition SavedPosition(Cursor);
5560 if (llvm::Error Err =
5561 Cursor.JumpToBit(InputFilesOffsetBase + InputFileOffs[I])) {
5562 // FIXME this drops errors on the floor.
5563 consumeError(std::move(Err));
5564 }
5565
5566 Expected<unsigned> MaybeCode = Cursor.ReadCode();
5567 if (!MaybeCode) {
5568 // FIXME this drops errors on the floor.
5569 consumeError(MaybeCode.takeError());
5570 }
5571 unsigned Code = MaybeCode.get();
5572
5574 StringRef Blob;
5575 bool shouldContinue = false;
5576 Expected<unsigned> MaybeRecordType =
5577 Cursor.readRecord(Code, Record, &Blob);
5578 if (!MaybeRecordType) {
5579 // FIXME this drops errors on the floor.
5580 consumeError(MaybeRecordType.takeError());
5581 }
5582 switch ((InputFileRecordTypes)MaybeRecordType.get()) {
5583 case INPUT_FILE_HASH:
5584 break;
5585 case INPUT_FILE:
5586 bool Overridden = static_cast<bool>(Record[3]);
5587 std::string Filename = std::string(Blob);
5588 ResolveImportedPath(Filename, ModuleDir);
5589 shouldContinue = Listener.visitInputFile(
5590 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
5591 break;
5592 }
5593 if (!shouldContinue)
5594 break;
5595 }
5596 break;
5597 }
5598
5599 case IMPORTS: {
5600 if (!NeedsImports)
5601 break;
5602
5603 unsigned Idx = 0, N = Record.size();
5604 while (Idx < N) {
5605 // Read information about the AST file.
5606
5607 // Skip Kind
5608 Idx++;
5609 bool IsStandardCXXModule = Record[Idx++];
5610
5611 // Skip ImportLoc
5612 Idx++;
5613
5614 // In C++20 Modules, we don't record the path to imported
5615 // modules in the BMI files.
5616 if (IsStandardCXXModule) {
5617 std::string ModuleName = ReadString(Record, Idx);
5618 Listener.visitImport(ModuleName, /*Filename=*/"");
5619 continue;
5620 }
5621
5622 // Skip Size, ModTime and Signature
5623 Idx += 1 + 1 + ASTFileSignature::size;
5624 std::string ModuleName = ReadString(Record, Idx);
5625 std::string Filename = ReadString(Record, Idx);
5626 ResolveImportedPath(Filename, ModuleDir);
5627 Listener.visitImport(ModuleName, Filename);
5628 }
5629 break;
5630 }
5631
5632 default:
5633 // No other validation to perform.
5634 break;
5635 }
5636 }
5637
5638 // Look for module file extension blocks, if requested.
5639 if (FindModuleFileExtensions) {
5640 BitstreamCursor SavedStream = Stream;
5641 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
5642 bool DoneWithExtensionBlock = false;
5643 while (!DoneWithExtensionBlock) {
5644 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5645 if (!MaybeEntry) {
5646 // FIXME this drops the error.
5647 return true;
5648 }
5649 llvm::BitstreamEntry Entry = MaybeEntry.get();
5650
5651 switch (Entry.Kind) {
5652 case llvm::BitstreamEntry::SubBlock:
5653 if (llvm::Error Err = Stream.SkipBlock()) {
5654 // FIXME this drops the error on the floor.
5655 consumeError(std::move(Err));
5656 return true;
5657 }
5658 continue;
5659
5660 case llvm::BitstreamEntry::EndBlock:
5661 DoneWithExtensionBlock = true;
5662 continue;
5663
5664 case llvm::BitstreamEntry::Error:
5665 return true;
5666
5667 case llvm::BitstreamEntry::Record:
5668 break;
5669 }
5670
5671 Record.clear();
5672 StringRef Blob;
5673 Expected<unsigned> MaybeRecCode =
5674 Stream.readRecord(Entry.ID, Record, &Blob);
5675 if (!MaybeRecCode) {
5676 // FIXME this drops the error.
5677 return true;
5678 }
5679 switch (MaybeRecCode.get()) {
5680 case EXTENSION_METADATA: {
5682 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5683 return true;
5684
5685 Listener.readModuleFileExtension(Metadata);
5686 break;
5687 }
5688 }
5689 }
5690 }
5691 Stream = SavedStream;
5692 }
5693
5694 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5695 if (readUnhashedControlBlockImpl(
5696 nullptr, Bytes, ClientLoadCapabilities,
5697 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
5698 ValidateDiagnosticOptions) != Success)
5699 return true;
5700
5701 return false;
5702}
5703
5705 const InMemoryModuleCache &ModuleCache,
5706 const PCHContainerReader &PCHContainerRdr,
5707 const LangOptions &LangOpts,
5708 const TargetOptions &TargetOpts,
5709 const PreprocessorOptions &PPOpts,
5710 StringRef ExistingModuleCachePath,
5711 bool RequireStrictOptionMatches) {
5712 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
5713 ExistingModuleCachePath, FileMgr,
5714 RequireStrictOptionMatches);
5715 return !readASTFileControlBlock(Filename, FileMgr, ModuleCache,
5716 PCHContainerRdr,
5717 /*FindModuleFileExtensions=*/false, validator,
5718 /*ValidateDiagnosticOptions=*/true);
5719}
5720
5721llvm::Error ASTReader::ReadSubmoduleBlock(ModuleFile &F,
5722 unsigned ClientLoadCapabilities) {
5723 // Enter the submodule block.
5724 if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID))
5725 return Err;
5726
5727 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
5728 bool First = true;
5729 Module *CurrentModule = nullptr;
5730 RecordData Record;
5731 while (true) {
5733 F.Stream.advanceSkippingSubblocks();
5734 if (!MaybeEntry)
5735 return MaybeEntry.takeError();
5736 llvm::BitstreamEntry Entry = MaybeEntry.get();
5737
5738 switch (Entry.Kind) {
5739 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
5740 case llvm::BitstreamEntry::Error:
5741 return llvm::createStringError(std::errc::illegal_byte_sequence,
5742 "malformed block record in AST file");
5743 case llvm::BitstreamEntry::EndBlock:
5744 return llvm::Error::success();
5745 case llvm::BitstreamEntry::Record:
5746 // The interesting case.
5747 break;
5748 }
5749
5750 // Read a record.
5751 StringRef Blob;
5752 Record.clear();
5753 Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
5754 if (!MaybeKind)
5755 return MaybeKind.takeError();
5756 unsigned Kind = MaybeKind.get();
5757
5758 if ((Kind == SUBMODULE_METADATA) != First)
5759 return llvm::createStringError(
5760 std::errc::illegal_byte_sequence,
5761 "submodule metadata record should be at beginning of block");
5762 First = false;
5763
5764 // Submodule information is only valid if we have a current module.
5765 // FIXME: Should we error on these cases?
5766 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
5767 Kind != SUBMODULE_DEFINITION)
5768 continue;
5769
5770 switch (Kind) {
5771 default: // Default behavior: ignore.
5772 break;
5773
5774 case SUBMODULE_DEFINITION: {
5775 if (Record.size() < 13)
5776 return llvm::createStringError(std::errc::illegal_byte_sequence,
5777 "malformed module definition");
5778
5779 StringRef Name = Blob;
5780 unsigned Idx = 0;
5781 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
5782 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
5784 SourceLocation DefinitionLoc = ReadSourceLocation(F, Record[Idx++]);
5785 bool IsFramework = Record[Idx++];
5786 bool IsExplicit = Record[Idx++];
5787 bool IsSystem = Record[Idx++];
5788 bool IsExternC = Record[Idx++];
5789 bool InferSubmodules = Record[Idx++];
5790 bool InferExplicitSubmodules = Record[Idx++];
5791 bool InferExportWildcard = Record[Idx++];
5792 bool ConfigMacrosExhaustive = Record[Idx++];
5793 bool ModuleMapIsPrivate = Record[Idx++];
5794 bool NamedModuleHasInit = Record[Idx++];
5795
5796 Module *ParentModule = nullptr;
5797 if (Parent)
5798 ParentModule = getSubmodule(Parent);
5799
5800 // Retrieve this (sub)module from the module map, creating it if
5801 // necessary.
5802 CurrentModule =
5803 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
5804 .first;
5805
5806 // FIXME: Call ModMap.setInferredModuleAllowedBy()
5807
5808 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
5809 if (GlobalIndex >= SubmodulesLoaded.size() ||
5810 SubmodulesLoaded[GlobalIndex])
5811 return llvm::createStringError(std::errc::invalid_argument,
5812 "too many submodules");
5813
5814 if (!ParentModule) {
5815 if (OptionalFileEntryRef CurFile = CurrentModule->getASTFile()) {
5816 // Don't emit module relocation error if we have -fno-validate-pch
5817 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
5819 CurFile != F.File) {
5820 auto ConflictError =
5821 PartialDiagnostic(diag::err_module_file_conflict,
5822 ContextObj->DiagAllocator)
5823 << CurrentModule->getTopLevelModuleName() << CurFile->getName()
5824 << F.File.getName();
5825 return DiagnosticError::create(CurrentImportLoc, ConflictError);
5826 }
5827 }
5828
5829 F.DidReadTopLevelSubmodule = true;
5830 CurrentModule->setASTFile(F.File);
5831 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
5832 }
5833
5834 CurrentModule->Kind = Kind;
5835 CurrentModule->DefinitionLoc = DefinitionLoc;
5836 CurrentModule->Signature = F.Signature;
5837 CurrentModule->IsFromModuleFile = true;
5838 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
5839 CurrentModule->IsExternC = IsExternC;
5840 CurrentModule->InferSubmodules = InferSubmodules;
5841 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
5842 CurrentModule->InferExportWildcard = InferExportWildcard;
5843 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
5844 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
5845 CurrentModule->NamedModuleHasInit = NamedModuleHasInit;
5846 if (DeserializationListener)
5847 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
5848
5849 SubmodulesLoaded[GlobalIndex] = CurrentModule;
5850
5851 // Clear out data that will be replaced by what is in the module file.
5852 CurrentModule->LinkLibraries.clear();
5853 CurrentModule->ConfigMacros.clear();
5854 CurrentModule->UnresolvedConflicts.clear();
5855 CurrentModule->Conflicts.clear();
5856
5857 // The module is available unless it's missing a requirement; relevant
5858 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
5859 // Missing headers that were present when the module was built do not
5860 // make it unavailable -- if we got this far, this must be an explicitly
5861 // imported module file.
5862 CurrentModule->Requirements.clear();
5863 CurrentModule->MissingHeaders.clear();
5864 CurrentModule->IsUnimportable =
5865 ParentModule && ParentModule->IsUnimportable;
5866 CurrentModule->IsAvailable = !CurrentModule->IsUnimportable;
5867 break;
5868 }
5869
5871 // FIXME: This doesn't work for framework modules as `Filename` is the
5872 // name as written in the module file and does not include
5873 // `Headers/`, so this path will never exist.
5874 std::string Filename = std::string(Blob);
5875 ResolveImportedPath(F, Filename);
5876 if (auto Umbrella = PP.getFileManager().getOptionalFileRef(Filename)) {
5877 if (!CurrentModule->getUmbrellaHeaderAsWritten()) {
5878 // FIXME: NameAsWritten
5879 ModMap.setUmbrellaHeaderAsWritten(CurrentModule, *Umbrella, Blob, "");
5880 }
5881 // Note that it's too late at this point to return out of date if the
5882 // name from the PCM doesn't match up with the one in the module map,
5883 // but also quite unlikely since we will have already checked the
5884 // modification time and size of the module map file itself.
5885 }
5886 break;
5887 }
5888
5889 case SUBMODULE_HEADER:
5892 // We lazily associate headers with their modules via the HeaderInfo table.
5893 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
5894 // of complete filenames or remove it entirely.
5895 break;
5896
5899 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
5900 // them here.
5901 break;
5902
5903 case SUBMODULE_TOPHEADER: {
5904 std::string HeaderName(Blob);
5905 ResolveImportedPath(F, HeaderName);
5906 CurrentModule->addTopHeaderFilename(HeaderName);
5907 break;
5908 }
5909
5911 // See comments in SUBMODULE_UMBRELLA_HEADER
5912 std::string Dirname = std::string(Blob);
5913 ResolveImportedPath(F, Dirname);
5914 if (auto Umbrella =
5915 PP.getFileManager().getOptionalDirectoryRef(Dirname)) {
5916 if (!CurrentModule->getUmbrellaDirAsWritten()) {
5917 // FIXME: NameAsWritten
5918 ModMap.setUmbrellaDirAsWritten(CurrentModule, *Umbrella, Blob, "");
5919 }
5920 }
5921 break;
5922 }
5923
5924 case SUBMODULE_METADATA: {
5925 F.BaseSubmoduleID = getTotalNumSubmodules();
5927 unsigned LocalBaseSubmoduleID = Record[1];
5928 if (F.LocalNumSubmodules > 0) {
5929 // Introduce the global -> local mapping for submodules within this
5930 // module.
5931 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
5932
5933 // Introduce the local -> global mapping for submodules within this
5934 // module.
5936 std::make_pair(LocalBaseSubmoduleID,
5937 F.BaseSubmoduleID - LocalBaseSubmoduleID));
5938
5939 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5940 }
5941 break;
5942 }
5943
5944 case SUBMODULE_IMPORTS:
5945 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
5946 UnresolvedModuleRef Unresolved;
5947 Unresolved.File = &F;
5948 Unresolved.Mod = CurrentModule;
5949 Unresolved.ID = Record[Idx];
5950 Unresolved.Kind = UnresolvedModuleRef::Import;
5951 Unresolved.IsWildcard = false;
5952 UnresolvedModuleRefs.push_back(Unresolved);
5953 }
5954 break;
5955
5957 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
5958 UnresolvedModuleRef Unresolved;
5959 Unresolved.File = &F;
5960 Unresolved.Mod = CurrentModule;
5961 Unresolved.ID = Record[Idx];
5962 Unresolved.Kind = UnresolvedModuleRef::Affecting;
5963 Unresolved.IsWildcard = false;
5964 UnresolvedModuleRefs.push_back(Unresolved);
5965 }
5966 break;
5967
5968 case SUBMODULE_EXPORTS:
5969 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
5970 UnresolvedModuleRef Unresolved;
5971 Unresolved.File = &F;
5972 Unresolved.Mod = CurrentModule;
5973 Unresolved.ID = Record[Idx];
5974 Unresolved.Kind = UnresolvedModuleRef::Export;
5975 Unresolved.IsWildcard = Record[Idx + 1];
5976 UnresolvedModuleRefs.push_back(Unresolved);
5977 }
5978
5979 // Once we've loaded the set of exports, there's no reason to keep
5980 // the parsed, unresolved exports around.
5981 CurrentModule->UnresolvedExports.clear();
5982 break;
5983
5984 case SUBMODULE_REQUIRES:
5985 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
5986 PP.getTargetInfo());
5987 break;
5988
5990 ModMap.resolveLinkAsDependencies(CurrentModule);
5991 CurrentModule->LinkLibraries.push_back(
5992 Module::LinkLibrary(std::string(Blob), Record[0]));
5993 break;
5994
5996 CurrentModule->ConfigMacros.push_back(Blob.str());
5997 break;
5998
5999 case SUBMODULE_CONFLICT: {
6000 UnresolvedModuleRef Unresolved;
6001 Unresolved.File = &F;
6002 Unresolved.Mod = CurrentModule;
6003 Unresolved.ID = Record[0];
6004 Unresolved.Kind = UnresolvedModuleRef::Conflict;
6005 Unresolved.IsWildcard = false;
6006 Unresolved.String = Blob;
6007 UnresolvedModuleRefs.push_back(Unresolved);
6008 break;
6009 }
6010
6012 if (!ContextObj)
6013 break;
6015 for (auto &ID : Record)
6016 Inits.push_back(getGlobalDeclID(F, LocalDeclID(ID)));
6017 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
6018 break;
6019 }
6020
6022 CurrentModule->ExportAsModule = Blob.str();
6023 ModMap.addLinkAsDependency(CurrentModule);
6024 break;
6025 }
6026 }
6027}
6028
6029/// Parse the record that corresponds to a LangOptions data
6030/// structure.
6031///
6032/// This routine parses the language options from the AST file and then gives
6033/// them to the AST listener if one is set.
6034///
6035/// \returns true if the listener deems the file unacceptable, false otherwise.
6036bool ASTReader::ParseLanguageOptions(const RecordData &Record,
6037 bool Complain,
6038 ASTReaderListener &Listener,
6039 bool AllowCompatibleDifferences) {
6040 LangOptions LangOpts;
6041 unsigned Idx = 0;
6042#define LANGOPT(Name, Bits, Default, Description) \
6043 LangOpts.Name = Record[Idx++];
6044#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
6045 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
6046#include "clang/Basic/LangOptions.def"
6047#define SANITIZER(NAME, ID) \
6048 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
6049#include "clang/Basic/Sanitizers.def"
6050
6051 for (unsigned N = Record[Idx++]; N; --N)
6052 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
6053
6054 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
6055 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
6056 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
6057
6058 LangOpts.CurrentModule = ReadString(Record, Idx);
6059
6060 // Comment options.
6061 for (unsigned N = Record[Idx++]; N; --N) {
6062 LangOpts.CommentOpts.BlockCommandNames.push_back(
6063 ReadString(Record, Idx));
6064 }
6065 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
6066
6067 // OpenMP offloading options.
6068 for (unsigned N = Record[Idx++]; N; --N) {
6069 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
6070 }
6071
6072 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
6073
6074 return Listener.ReadLanguageOptions(LangOpts, Complain,
6075 AllowCompatibleDifferences);
6076}
6077
6078bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
6079 ASTReaderListener &Listener,
6080 bool AllowCompatibleDifferences) {
6081 unsigned Idx = 0;
6082 TargetOptions TargetOpts;
6083 TargetOpts.Triple = ReadString(Record, Idx);
6084 TargetOpts.CPU = ReadString(Record, Idx);
6085 TargetOpts.TuneCPU = ReadString(Record, Idx);
6086 TargetOpts.ABI = ReadString(Record, Idx);
6087 for (unsigned N = Record[Idx++]; N; --N) {
6088 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
6089 }
6090 for (unsigned N = Record[Idx++]; N; --N) {
6091 TargetOpts.Features.push_back(ReadString(Record, Idx));
6092 }
6093
6094 return Listener.ReadTargetOptions(TargetOpts, Complain,
6095 AllowCompatibleDifferences);
6096}
6097
6098bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
6099 ASTReaderListener &Listener) {
6101 unsigned Idx = 0;
6102#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
6103#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
6104 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
6105#include "clang/Basic/DiagnosticOptions.def"
6106
6107 for (unsigned N = Record[Idx++]; N; --N)
6108 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
6109 for (unsigned N = Record[Idx++]; N; --N)
6110 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
6111
6112 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
6113}
6114
6115bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
6116 ASTReaderListener &Listener) {
6117 FileSystemOptions FSOpts;
6118 unsigned Idx = 0;
6119 FSOpts.WorkingDir = ReadString(Record, Idx);
6120 return Listener.ReadFileSystemOptions(FSOpts, Complain);
6121}
6122
6123bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
6124 bool Complain,
6125 ASTReaderListener &Listener) {
6126 HeaderSearchOptions HSOpts;
6127 unsigned Idx = 0;
6128 HSOpts.Sysroot = ReadString(Record, Idx);
6129
6130 HSOpts.ResourceDir = ReadString(Record, Idx);
6131 HSOpts.ModuleCachePath = ReadString(Record, Idx);
6132 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
6133 HSOpts.DisableModuleHash = Record[Idx++];
6134 HSOpts.ImplicitModuleMaps = Record[Idx++];
6135 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
6136 HSOpts.EnablePrebuiltImplicitModules = Record[Idx++];
6137 HSOpts.UseBuiltinIncludes = Record[Idx++];
6138 HSOpts.UseStandardSystemIncludes = Record[Idx++];
6139 HSOpts.UseStandardCXXIncludes = Record[Idx++];
6140 HSOpts.UseLibcxx = Record[Idx++];
6141 std::string SpecificModuleCachePath = ReadString(Record, Idx);
6142
6143 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
6144 Complain);
6145}
6146
6147bool ASTReader::ParseHeaderSearchPaths(const RecordData &Record, bool Complain,
6148 ASTReaderListener &Listener) {
6149 HeaderSearchOptions HSOpts;
6150 unsigned Idx = 0;
6151
6152 // Include entries.
6153 for (unsigned N = Record[Idx++]; N; --N) {
6154 std::string Path = ReadString(Record, Idx);
6156 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
6157 bool IsFramework = Record[Idx++];
6158 bool IgnoreSysRoot = Record[Idx++];
6159 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
6160 IgnoreSysRoot);
6161 }
6162
6163 // System header prefixes.
6164 for (unsigned N = Record[Idx++]; N; --N) {
6165 std::string Prefix = ReadString(Record, Idx);
6166 bool IsSystemHeader = Record[Idx++];
6167 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
6168 }
6169
6170 // VFS overlay files.
6171 for (unsigned N = Record[Idx++]; N; --N) {
6172 std::string VFSOverlayFile = ReadString(Record, Idx);
6173 HSOpts.VFSOverlayFiles.emplace_back(std::move(VFSOverlayFile));
6174 }
6175
6176 return Listener.ReadHeaderSearchPaths(HSOpts, Complain);
6177}
6178
6179bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
6180 bool Complain,
6181 ASTReaderListener &Listener,
6182 std::string &SuggestedPredefines) {
6183 PreprocessorOptions PPOpts;
6184 unsigned Idx = 0;
6185
6186 // Macro definitions/undefs
6187 bool ReadMacros = Record[Idx++];
6188 if (ReadMacros) {
6189 for (unsigned N = Record[Idx++]; N; --N) {
6190 std::string Macro = ReadString(Record, Idx);
6191 bool IsUndef = Record[Idx++];
6192 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
6193 }
6194 }
6195
6196 // Includes
6197 for (unsigned N = Record[Idx++]; N; --N) {
6198 PPOpts.Includes.push_back(ReadString(Record, Idx));
6199 }
6200
6201 // Macro Includes
6202 for (unsigned N = Record[Idx++]; N; --N) {
6203 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
6204 }
6205
6206 PPOpts.UsePredefines = Record[Idx++];
6207 PPOpts.DetailedRecord = Record[Idx++];
6208 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
6210 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
6211 SuggestedPredefines.clear();
6212 return Listener.ReadPreprocessorOptions(PPOpts, ReadMacros, Complain,
6213 SuggestedPredefines);
6214}
6215
6216std::pair<ModuleFile *, unsigned>
6217ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
6218 GlobalPreprocessedEntityMapType::iterator
6219 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
6220 assert(I != GlobalPreprocessedEntityMap.end() &&
6221 "Corrupted global preprocessed entity map");
6222 ModuleFile *M = I->second;
6223 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
6224 return std::make_pair(M, LocalIndex);
6225}
6226
6227llvm::iterator_range<PreprocessingRecord::iterator>
6228ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
6229 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
6230 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
6232
6233 return llvm::make_range(PreprocessingRecord::iterator(),
6235}
6236
6237bool ASTReader::canRecoverFromOutOfDate(StringRef ModuleFileName,
6238 unsigned int ClientLoadCapabilities) {
6239 return ClientLoadCapabilities & ARR_OutOfDate &&
6240 !getModuleManager().getModuleCache().isPCMFinal(ModuleFileName);
6241}
6242
6243llvm::iterator_range<ASTReader::ModuleDeclIterator>
6245 return llvm::make_range(
6246 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
6247 ModuleDeclIterator(this, &Mod,
6249}
6250
6252 auto I = GlobalSkippedRangeMap.find(GlobalIndex);
6253 assert(I != GlobalSkippedRangeMap.end() &&
6254 "Corrupted global skipped range map");
6255 ModuleFile *M = I->second;
6256 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
6257 assert(LocalIndex < M->NumPreprocessedSkippedRanges);
6258 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
6259 SourceRange Range(TranslateSourceLocation(*M, RawRange.getBegin()),
6260 TranslateSourceLocation(*M, RawRange.getEnd()));
6261 assert(Range.isValid());
6262 return Range;
6263}
6264
6266 PreprocessedEntityID PPID = Index+1;
6267 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6268 ModuleFile &M = *PPInfo.first;
6269 unsigned LocalIndex = PPInfo.second;
6270 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6271
6272 if (!PP.getPreprocessingRecord()) {
6273 Error("no preprocessing record");
6274 return nullptr;
6275 }
6276
6278 if (llvm::Error Err = M.PreprocessorDetailCursor.JumpToBit(
6279 M.MacroOffsetsBase + PPOffs.BitOffset)) {
6280 Error(std::move(Err));
6281 return nullptr;
6282 }
6283
6285 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
6286 if (!MaybeEntry) {
6287 Error(MaybeEntry.takeError());
6288 return nullptr;
6289 }
6290 llvm::BitstreamEntry Entry = MaybeEntry.get();
6291
6292 if (Entry.Kind != llvm::BitstreamEntry::Record)
6293 return nullptr;
6294
6295 // Read the record.
6296 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
6297 TranslateSourceLocation(M, PPOffs.getEnd()));
6298 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
6299 StringRef Blob;
6301 Expected<unsigned> MaybeRecType =
6302 M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
6303 if (!MaybeRecType) {
6304 Error(MaybeRecType.takeError());
6305 return nullptr;
6306 }
6307 switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
6308 case PPD_MACRO_EXPANSION: {
6309 bool isBuiltin = Record[0];
6310 IdentifierInfo *Name = nullptr;
6311 MacroDefinitionRecord *Def = nullptr;
6312 if (isBuiltin)
6313 Name = getLocalIdentifier(M, Record[1]);
6314 else {
6315 PreprocessedEntityID GlobalID =
6316 getGlobalPreprocessedEntityID(M, Record[1]);
6317 Def = cast<MacroDefinitionRecord>(
6318 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
6319 }
6320
6321 MacroExpansion *ME;
6322 if (isBuiltin)
6323 ME = new (PPRec) MacroExpansion(Name, Range);
6324 else
6325 ME = new (PPRec) MacroExpansion(Def, Range);
6326
6327 return ME;
6328 }
6329
6330 case PPD_MACRO_DEFINITION: {
6331 // Decode the identifier info and then check again; if the macro is
6332 // still defined and associated with the identifier,
6333 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
6334 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
6335
6336 if (DeserializationListener)
6337 DeserializationListener->MacroDefinitionRead(PPID, MD);
6338
6339 return MD;
6340 }
6341
6343 const char *FullFileNameStart = Blob.data() + Record[0];
6344 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
6346 if (!FullFileName.empty())
6347 File = PP.getFileManager().getOptionalFileRef(FullFileName);
6348
6349 // FIXME: Stable encoding
6351 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
6353 = new (PPRec) InclusionDirective(PPRec, Kind,
6354 StringRef(Blob.data(), Record[0]),
6355 Record[1], Record[3],
6356 File,
6357 Range);
6358 return ID;
6359 }
6360 }
6361
6362 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
6363}
6364
6365/// Find the next module that contains entities and return the ID
6366/// of the first entry.
6367///
6368/// \param SLocMapI points at a chunk of a module that contains no
6369/// preprocessed entities or the entities it contains are not the ones we are
6370/// looking for.
6371PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
6372 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
6373 ++SLocMapI;
6374 for (GlobalSLocOffsetMapType::const_iterator
6375 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
6376 ModuleFile &M = *SLocMapI->second;
6378 return M.BasePreprocessedEntityID;
6379 }
6380
6381 return getTotalNumPreprocessedEntities();
6382}
6383
6384namespace {
6385
6386struct PPEntityComp {
6387 const ASTReader &Reader;
6388 ModuleFile &M;
6389
6390 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
6391
6392 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
6393 SourceLocation LHS = getLoc(L);
6394 SourceLocation RHS = getLoc(R);
6395 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6396 }
6397
6398 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
6399 SourceLocation LHS = getLoc(L);
6400 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6401 }
6402
6403 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
6404 SourceLocation RHS = getLoc(R);
6405 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6406 }
6407
6408 SourceLocation getLoc(const PPEntityOffset &PPE) const {
6409 return Reader.TranslateSourceLocation(M, PPE.getBegin());
6410 }
6411};
6412
6413} // namespace
6414
6415PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
6416 bool EndsAfter) const {
6417 if (SourceMgr.isLocalSourceLocation(Loc))
6418 return getTotalNumPreprocessedEntities();
6419
6420 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
6421 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
6422 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
6423 "Corrupted global sloc offset map");
6424
6425 if (SLocMapI->second->NumPreprocessedEntities == 0)
6426 return findNextPreprocessedEntity(SLocMapI);
6427
6428 ModuleFile &M = *SLocMapI->second;
6429
6430 using pp_iterator = const PPEntityOffset *;
6431
6432 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
6433 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
6434
6435 size_t Count = M.NumPreprocessedEntities;
6436 size_t Half;
6437 pp_iterator First = pp_begin;
6438 pp_iterator PPI;
6439
6440 if (EndsAfter) {
6441 PPI = std::upper_bound(pp_begin, pp_end, Loc,
6442 PPEntityComp(*this, M));
6443 } else {
6444 // Do a binary search manually instead of using std::lower_bound because
6445 // The end locations of entities may be unordered (when a macro expansion
6446 // is inside another macro argument), but for this case it is not important
6447 // whether we get the first macro expansion or its containing macro.
6448 while (Count > 0) {
6449 Half = Count / 2;
6450 PPI = First;
6451 std::advance(PPI, Half);
6452 if (SourceMgr.isBeforeInTranslationUnit(
6453 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
6454 First = PPI;
6455 ++First;
6456 Count = Count - Half - 1;
6457 } else
6458 Count = Half;
6459 }
6460 }
6461
6462 if (PPI == pp_end)
6463 return findNextPreprocessedEntity(SLocMapI);
6464
6465 return M.BasePreprocessedEntityID + (PPI - pp_begin);
6466}
6467
6468/// Returns a pair of [Begin, End) indices of preallocated
6469/// preprocessed entities that \arg Range encompasses.
6470std::pair<unsigned, unsigned>
6472 if (Range.isInvalid())
6473 return std::make_pair(0,0);
6474 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
6475
6476 PreprocessedEntityID BeginID =
6477 findPreprocessedEntity(Range.getBegin(), false);
6478 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
6479 return std::make_pair(BeginID, EndID);
6480}
6481
6482/// Optionally returns true or false if the preallocated preprocessed
6483/// entity with index \arg Index came from file \arg FID.
6484std::optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
6485 FileID FID) {
6486 if (FID.isInvalid())
6487 return false;
6488
6489 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6490 ModuleFile &M = *PPInfo.first;
6491 unsigned LocalIndex = PPInfo.second;
6492 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6493
6494 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
6495 if (Loc.isInvalid())
6496 return false;
6497
6498 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
6499 return true;
6500 else
6501 return false;
6502}
6503
6504namespace {
6505
6506 /// Visitor used to search for information about a header file.
6507 class HeaderFileInfoVisitor {
6508 FileEntryRef FE;
6509 std::optional<HeaderFileInfo> HFI;
6510
6511 public:
6512 explicit HeaderFileInfoVisitor(FileEntryRef FE) : FE(FE) {}
6513
6514 bool operator()(ModuleFile &M) {
6517 if (!Table)
6518 return false;
6519
6520 // Look in the on-disk hash table for an entry for this file name.
6521 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
6522 if (Pos == Table->end())
6523 return false;
6524
6525 HFI = *Pos;
6526 return true;
6527 }
6528
6529 std::optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
6530 };
6531
6532} // namespace
6533
6535 HeaderFileInfoVisitor Visitor(FE);
6536 ModuleMgr.visit(Visitor);
6537 if (std::optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
6538 return *HFI;
6539
6540 return HeaderFileInfo();
6541}
6542
6544 using DiagState = DiagnosticsEngine::DiagState;
6546
6547 for (ModuleFile &F : ModuleMgr) {
6548 unsigned Idx = 0;
6549 auto &Record = F.PragmaDiagMappings;
6550 if (Record.empty())
6551 continue;
6552
6553 DiagStates.clear();
6554
6555 auto ReadDiagState = [&](const DiagState &BasedOn,
6556 bool IncludeNonPragmaStates) {
6557 unsigned BackrefID = Record[Idx++];
6558 if (BackrefID != 0)
6559 return DiagStates[BackrefID - 1];
6560
6561 // A new DiagState was created here.
6562 Diag.DiagStates.push_back(BasedOn);
6563 DiagState *NewState = &Diag.DiagStates.back();
6564 DiagStates.push_back(NewState);
6565 unsigned Size = Record[Idx++];
6566 assert(Idx + Size * 2 <= Record.size() &&
6567 "Invalid data, not enough diag/map pairs");
6568 while (Size--) {
6569 unsigned DiagID = Record[Idx++];
6570 DiagnosticMapping NewMapping =
6572 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
6573 continue;
6574
6575 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
6576
6577 // If this mapping was specified as a warning but the severity was
6578 // upgraded due to diagnostic settings, simulate the current diagnostic
6579 // settings (and use a warning).
6580 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
6582 NewMapping.setUpgradedFromWarning(false);
6583 }
6584
6585 Mapping = NewMapping;
6586 }
6587 return NewState;
6588 };
6589
6590 // Read the first state.
6591 DiagState *FirstState;
6592 if (F.Kind == MK_ImplicitModule) {
6593 // Implicitly-built modules are reused with different diagnostic
6594 // settings. Use the initial diagnostic state from Diag to simulate this
6595 // compilation's diagnostic settings.
6596 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
6597 DiagStates.push_back(FirstState);
6598
6599 // Skip the initial diagnostic state from the serialized module.
6600 assert(Record[1] == 0 &&
6601 "Invalid data, unexpected backref in initial state");
6602 Idx = 3 + Record[2] * 2;
6603 assert(Idx < Record.size() &&
6604 "Invalid data, not enough state change pairs in initial state");
6605 } else if (F.isModule()) {
6606 // For an explicit module, preserve the flags from the module build
6607 // command line (-w, -Weverything, -Werror, ...) along with any explicit
6608 // -Wblah flags.
6609 unsigned Flags = Record[Idx++];
6610 DiagState Initial;
6611 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
6612 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
6613 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
6614 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
6615 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
6616 Initial.ExtBehavior = (diag::Severity)Flags;
6617 FirstState = ReadDiagState(Initial, true);
6618
6619 assert(F.OriginalSourceFileID.isValid());
6620
6621 // Set up the root buffer of the module to start with the initial
6622 // diagnostic state of the module itself, to cover files that contain no
6623 // explicit transitions (for which we did not serialize anything).
6624 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
6625 .StateTransitions.push_back({FirstState, 0});
6626 } else {
6627 // For prefix ASTs, start with whatever the user configured on the
6628 // command line.
6629 Idx++; // Skip flags.
6630 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState, false);
6631 }
6632
6633 // Read the state transitions.
6634 unsigned NumLocations = Record[Idx++];
6635 while (NumLocations--) {
6636 assert(Idx < Record.size() &&
6637 "Invalid data, missing pragma diagnostic states");
6638 FileID FID = ReadFileID(F, Record, Idx);
6639 assert(FID.isValid() && "invalid FileID for transition");
6640 unsigned Transitions = Record[Idx++];
6641
6642 // Note that we don't need to set up Parent/ParentOffset here, because
6643 // we won't be changing the diagnostic state within imported FileIDs
6644 // (other than perhaps appending to the main source file, which has no
6645 // parent).
6646 auto &F = Diag.DiagStatesByLoc.Files[FID];
6647 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
6648 for (unsigned I = 0; I != Transitions; ++I) {
6649 unsigned Offset = Record[Idx++];
6650 auto *State = ReadDiagState(*FirstState, false);
6651 F.StateTransitions.push_back({State, Offset});
6652 }
6653 }
6654
6655 // Read the final state.
6656 assert(Idx < Record.size() &&
6657 "Invalid data, missing final pragma diagnostic state");
6658 SourceLocation CurStateLoc = ReadSourceLocation(F, Record[Idx++]);
6659 auto *CurState = ReadDiagState(*FirstState, false);
6660
6661 if (!F.isModule()) {
6662 Diag.DiagStatesByLoc.CurDiagState = CurState;
6663 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
6664
6665 // Preserve the property that the imaginary root file describes the
6666 // current state.
6667 FileID NullFile;
6668 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
6669 if (T.empty())
6670 T.push_back({CurState, 0});
6671 else
6672 T[0].State = CurState;
6673 }
6674
6675 // Don't try to read these mappings again.
6676 Record.clear();
6677 }
6678}
6679
6680/// Get the correct cursor and offset for loading a type.
6681ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
6682 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
6683 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
6684 ModuleFile *M = I->second;
6685 return RecordLocation(
6686 M, M->TypeOffsets[Index - M->BaseTypeIndex].getBitOffset() +
6688}
6689
6690static std::optional<Type::TypeClass> getTypeClassForCode(TypeCode code) {
6691 switch (code) {
6692#define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
6693 case TYPE_##CODE_ID: return Type::CLASS_ID;
6694#include "clang/Serialization/TypeBitCodes.def"
6695 default:
6696 return std::nullopt;
6697 }
6698}
6699
6700/// Read and return the type with the given index..
6701///
6702/// The index is the type ID, shifted and minus the number of predefs. This
6703/// routine actually reads the record corresponding to the type at the given
6704/// location. It is a helper routine for GetType, which deals with reading type
6705/// IDs.
6706QualType ASTReader::readTypeRecord(unsigned Index) {
6707 assert(ContextObj && "reading type with no AST context");
6708 ASTContext &Context = *ContextObj;
6709 RecordLocation Loc = TypeCursorForIndex(Index);
6710 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
6711
6712 // Keep track of where we are in the stream, then jump back there
6713 // after reading this type.
6714 SavedStreamPosition SavedPosition(DeclsCursor);
6715
6716 ReadingKindTracker ReadingKind(Read_Type, *this);
6717
6718 // Note that we are loading a type record.
6719 Deserializing AType(this);
6720
6721 if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
6722 Error(std::move(Err));
6723 return QualType();
6724 }
6725 Expected<unsigned> RawCode = DeclsCursor.ReadCode();
6726 if (!RawCode) {
6727 Error(RawCode.takeError());
6728 return QualType();
6729 }
6730
6731 ASTRecordReader Record(*this, *Loc.F);
6732 Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get());
6733 if (!Code) {
6734 Error(Code.takeError());
6735 return QualType();
6736 }
6737 if (Code.get() == TYPE_EXT_QUAL) {
6738 QualType baseType = Record.readQualType();
6739 Qualifiers quals = Record.readQualifiers();
6740 return Context.getQualifiedType(baseType, quals);
6741 }
6742
6743 auto maybeClass = getTypeClassForCode((TypeCode) Code.get());
6744 if (!maybeClass) {
6745 Error("Unexpected code for type");
6746 return QualType();
6747 }
6748
6750 return TypeReader.read(*maybeClass);
6751}
6752
6753namespace clang {
6754
6755class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
6757
6758 ASTRecordReader &Reader;
6759 LocSeq *Seq;
6760
6761 SourceLocation readSourceLocation() { return Reader.readSourceLocation(Seq); }
6762 SourceRange readSourceRange() { return Reader.readSourceRange(Seq); }
6763
6764 TypeSourceInfo *GetTypeSourceInfo() {
6765 return Reader.readTypeSourceInfo();
6766 }
6767
6768 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6769 return Reader.readNestedNameSpecifierLoc();
6770 }
6771
6772 Attr *ReadAttr() {
6773 return Reader.readAttr();
6774 }
6775
6776public:
6778 : Reader(Reader), Seq(Seq) {}
6779
6780 // We want compile-time assurance that we've enumerated all of
6781 // these, so unfortunately we have to declare them first, then
6782 // define them out-of-line.
6783#define ABSTRACT_TYPELOC(CLASS, PARENT)
6784#define TYPELOC(CLASS, PARENT) \
6785 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6786#include "clang/AST/TypeLocNodes.def"
6787
6788 void VisitFunctionTypeLoc(FunctionTypeLoc);
6789 void VisitArrayTypeLoc(ArrayTypeLoc);
6790};
6791
6792} // namespace clang
6793
6794void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6795 // nothing to do
6796}
6797
6798void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6799 TL.setBuiltinLoc(readSourceLocation());
6800 if (TL.needsExtraLocalData()) {
6801 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt()));
6802 TL.setWrittenSignSpec(static_cast<TypeSpecifierSign>(Reader.readInt()));
6803 TL.setWrittenWidthSpec(static_cast<TypeSpecifierWidth>(Reader.readInt()));
6804 TL.setModeAttr(Reader.readInt());
6805 }
6806}
6807
6808void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
6809 TL.setNameLoc(readSourceLocation());
6810}
6811
6812void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
6813 TL.setStarLoc(readSourceLocation());
6814}
6815
6816void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6817 // nothing to do
6818}
6819
6820void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6821 // nothing to do
6822}
6823
6824void TypeLocReader::VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) {
6825 // nothing to do
6826}
6827
6828void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6829 TL.setExpansionLoc(readSourceLocation());
6830}
6831
6832void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6833 TL.setCaretLoc(readSourceLocation());
6834}
6835
6836void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6837 TL.setAmpLoc(readSourceLocation());
6838}
6839
6840void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6841 TL.setAmpAmpLoc(readSourceLocation());
6842}
6843
6844void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6845 TL.setStarLoc(readSourceLocation());
6846 TL.setClassTInfo(GetTypeSourceInfo());
6847}
6848
6850 TL.setLBracketLoc(readSourceLocation());
6851 TL.setRBracketLoc(readSourceLocation());
6852 if (Reader.readBool())
6853 TL.setSizeExpr(Reader.readExpr());
6854 else
6855 TL.setSizeExpr(nullptr);
6856}
6857
6858void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6859 VisitArrayTypeLoc(TL);
6860}
6861
6862void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6863 VisitArrayTypeLoc(TL);
6864}
6865
6866void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6867 VisitArrayTypeLoc(TL);
6868}
6869
6870void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6872 VisitArrayTypeLoc(TL);
6873}
6874
6875void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
6877
6878 TL.setAttrNameLoc(readSourceLocation());
6879 TL.setAttrOperandParensRange(readSourceRange());
6880 TL.setAttrExprOperand(Reader.readExpr());
6881}
6882
6883void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6885 TL.setNameLoc(readSourceLocation());
6886}
6887
6888void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
6889 TL.setNameLoc(readSourceLocation());
6890}
6891
6892void TypeLocReader::VisitDependentVectorTypeLoc(
6894 TL.setNameLoc(readSourceLocation());
6895}
6896
6897void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6898 TL.setNameLoc(readSourceLocation());
6899}
6900
6901void TypeLocReader::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
6902 TL.setAttrNameLoc(readSourceLocation());
6903 TL.setAttrOperandParensRange(readSourceRange());
6904 TL.setAttrRowOperand(Reader.readExpr());
6905 TL.setAttrColumnOperand(Reader.readExpr());
6906}
6907
6908void TypeLocReader::VisitDependentSizedMatrixTypeLoc(
6910 TL.setAttrNameLoc(readSourceLocation());
6911 TL.setAttrOperandParensRange(readSourceRange());
6912 TL.setAttrRowOperand(Reader.readExpr());
6913 TL.setAttrColumnOperand(Reader.readExpr());
6914}
6915
6917 TL.setLocalRangeBegin(readSourceLocation());
6918 TL.setLParenLoc(readSourceLocation());
6919 TL.setRParenLoc(readSourceLocation());
6920 TL.setExceptionSpecRange(readSourceRange());
6921 TL.setLocalRangeEnd(readSourceLocation());
6922 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
6923 TL.setParam(i, Reader.readDeclAs<ParmVarDecl>());
6924 }
6925}
6926
6927void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6928 VisitFunctionTypeLoc(TL);
6929}
6930
6931void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6932 VisitFunctionTypeLoc(TL);
6933}
6934
6935void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
6936 TL.setNameLoc(readSourceLocation());
6937}
6938
6939void TypeLocReader::VisitUsingTypeLoc(UsingTypeLoc TL) {
6940 TL.setNameLoc(readSourceLocation());
6941}
6942
6943void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
6944 TL.setNameLoc(readSourceLocation());
6945}
6946
6947void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6948 TL.setTypeofLoc(readSourceLocation());
6949 TL.setLParenLoc(readSourceLocation());
6950 TL.setRParenLoc(readSourceLocation());
6951}
6952
6953void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6954 TL.setTypeofLoc(readSourceLocation());
6955 TL.setLParenLoc(readSourceLocation());
6956 TL.setRParenLoc(readSourceLocation());
6957 TL.setUnmodifiedTInfo(GetTypeSourceInfo());
6958}
6959
6960void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6961 TL.setDecltypeLoc(readSourceLocation());
6962 TL.setRParenLoc(readSourceLocation());
6963}
6964
6965void TypeLocReader::VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {
6966 TL.setEllipsisLoc(readSourceLocation());
6967}
6968
6969void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6970 TL.setKWLoc(readSourceLocation());
6971 TL.setLParenLoc(readSourceLocation());
6972 TL.setRParenLoc(readSourceLocation());
6973 TL.setUnderlyingTInfo(GetTypeSourceInfo());
6974}
6975
6977 auto NNS = readNestedNameSpecifierLoc();
6978 auto TemplateKWLoc = readSourceLocation();
6979 auto ConceptNameLoc = readDeclarationNameInfo();
6980 auto FoundDecl = readDeclAs<NamedDecl>();
6981 auto NamedConcept = readDeclAs<ConceptDecl>();
6982 auto *CR = ConceptReference::Create(
6983 getContext(), NNS, TemplateKWLoc, ConceptNameLoc, FoundDecl, NamedConcept,
6984 (readBool() ? readASTTemplateArgumentListInfo() : nullptr));
6985 return CR;
6986}
6987
6988void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
6989 TL.setNameLoc(readSourceLocation());
6990 if (Reader.readBool())
6991 TL.setConceptReference(Reader.readConceptReference());
6992 if (Reader.readBool())
6993 TL.setRParenLoc(readSourceLocation());
6994}
6995
6996void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6998 TL.setTemplateNameLoc(readSourceLocation());
6999}
7000
7001void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
7002 TL.setNameLoc(readSourceLocation());
7003}
7004
7005void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
7006 TL.setNameLoc(readSourceLocation());
7007}
7008
7009void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
7010 TL.setAttr(ReadAttr());
7011}
7012
7013void TypeLocReader::VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
7014 // Nothing to do
7015}
7016
7017void TypeLocReader::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
7018 // Nothing to do.
7019}
7020
7021void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
7022 TL.setNameLoc(readSourceLocation());
7023}
7024
7025void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
7027 TL.setNameLoc(readSourceLocation());
7028}
7029
7030void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
7032 TL.setNameLoc(readSourceLocation());
7033}
7034
7035void TypeLocReader::VisitTemplateSpecializationTypeLoc(
7037 TL.setTemplateKeywordLoc(readSourceLocation());
7038 TL.setTemplateNameLoc(readSourceLocation());
7039 TL.setLAngleLoc(readSourceLocation());
7040 TL.setRAngleLoc(readSourceLocation());
7041 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
7042 TL.setArgLocInfo(i,
7043 Reader.readTemplateArgumentLocInfo(
7044 TL.getTypePtr()->template_arguments()[i].getKind()));
7045}
7046
7047void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
7048 TL.setLParenLoc(readSourceLocation());
7049 TL.setRParenLoc(readSourceLocation());
7050}
7051
7052void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
7053 TL.setElaboratedKeywordLoc(readSourceLocation());
7054 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7055}
7056
7057void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
7058 TL.setNameLoc(readSourceLocation());
7059}
7060
7061void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
7062 TL.setElaboratedKeywordLoc(readSourceLocation());
7063 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7064 TL.setNameLoc(readSourceLocation());
7065}
7066
7067void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
7069 TL.setElaboratedKeywordLoc(readSourceLocation());
7070 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7071 TL.setTemplateKeywordLoc(readSourceLocation());
7072 TL.setTemplateNameLoc(readSourceLocation());
7073 TL.setLAngleLoc(readSourceLocation());
7074 TL.setRAngleLoc(readSourceLocation());
7075 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
7076 TL.setArgLocInfo(I,
7077 Reader.readTemplateArgumentLocInfo(
7078 TL.getTypePtr()->template_arguments()[I].getKind()));
7079}
7080
7081void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
7082 TL.setEllipsisLoc(readSourceLocation());
7083}
7084
7085void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
7086 TL.setNameLoc(readSourceLocation());
7087 TL.setNameEndLoc(readSourceLocation());
7088}
7089
7090void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
7091 if (TL.getNumProtocols()) {
7092 TL.setProtocolLAngleLoc(readSourceLocation());
7093 TL.setProtocolRAngleLoc(readSourceLocation());
7094 }
7095 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7096 TL.setProtocolLoc(i, readSourceLocation());
7097}
7098
7099void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
7100 TL.setHasBaseTypeAsWritten(Reader.readBool());
7101 TL.setTypeArgsLAngleLoc(readSourceLocation());
7102 TL.setTypeArgsRAngleLoc(readSourceLocation());
7103 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
7104 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
7105 TL.setProtocolLAngleLoc(readSourceLocation());
7106 TL.setProtocolRAngleLoc(readSourceLocation());
7107 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7108 TL.setProtocolLoc(i, readSourceLocation());
7109}
7110
7111void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
7112 TL.setStarLoc(readSourceLocation());
7113}
7114
7115void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
7116 TL.setKWLoc(readSourceLocation());
7117 TL.setLParenLoc(readSourceLocation());
7118 TL.setRParenLoc(readSourceLocation());
7119}
7120
7121void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
7122 TL.setKWLoc(readSourceLocation());
7123}
7124
7125void TypeLocReader::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
7126 TL.setNameLoc(readSourceLocation());
7127}
7128void TypeLocReader::VisitDependentBitIntTypeLoc(
7130 TL.setNameLoc(readSourceLocation());
7131}
7132
7134 LocSeq::State Seq(ParentSeq);
7135 TypeLocReader TLR(*this, Seq);
7136 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
7137 TLR.Visit(TL);
7138}
7139
7141 QualType InfoTy = readType();
7142 if (InfoTy.isNull())
7143 return nullptr;
7144
7145 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
7146 readTypeLoc(TInfo->getTypeLoc());
7147 return TInfo;
7148}
7149
7151 assert(ContextObj && "reading type with no AST context");
7152 ASTContext &Context = *ContextObj;
7153
7154 unsigned FastQuals = ID & Qualifiers::FastMask;
7155 unsigned Index = ID >> Qualifiers::FastWidth;
7156
7157 if (Index < NUM_PREDEF_TYPE_IDS) {
7158 QualType T;
7159 switch ((PredefinedTypeIDs)Index) {
7161 // We should never use this one.
7162 llvm_unreachable("Invalid predefined type");
7163 break;
7165 return QualType();
7167 T = Context.VoidTy;
7168 break;
7170 T = Context.BoolTy;
7171 break;
7174 // FIXME: Check that the signedness of CharTy is correct!
7175 T = Context.CharTy;
7176 break;
7178 T = Context.UnsignedCharTy;
7179 break;
7181 T = Context.UnsignedShortTy;
7182 break;
7184 T = Context.UnsignedIntTy;
7185 break;
7187 T = Context.UnsignedLongTy;
7188 break;
7190 T = Context.UnsignedLongLongTy;
7191 break;
7193 T = Context.UnsignedInt128Ty;
7194 break;
7196 T = Context.SignedCharTy;
7197 break;
7199 T = Context.WCharTy;
7200 break;
7202 T = Context.ShortTy;
7203 break;
7204 case PREDEF_TYPE_INT_ID:
7205 T = Context.IntTy;
7206 break;
7208 T = Context.LongTy;
7209 break;
7211 T = Context.LongLongTy;
7212 break;
7214 T = Context.Int128Ty;
7215 break;
7217 T = Context.BFloat16Ty;
7218 break;
7220 T = Context.HalfTy;
7221 break;
7223 T = Context.FloatTy;
7224 break;
7226 T = Context.DoubleTy;
7227 break;
7229 T = Context.LongDoubleTy;
7230 break;
7232 T = Context.ShortAccumTy;
7233 break;
7235 T = Context.AccumTy;
7236 break;
7238 T = Context.LongAccumTy;
7239 break;
7241 T = Context.UnsignedShortAccumTy;
7242 break;
7244 T = Context.UnsignedAccumTy;
7245 break;
7247 T = Context.UnsignedLongAccumTy;
7248 break;
7250 T = Context.ShortFractTy;
7251 break;
7253 T = Context.FractTy;
7254 break;
7256 T = Context.LongFractTy;
7257 break;
7259 T = Context.UnsignedShortFractTy;
7260 break;
7262 T = Context.UnsignedFractTy;
7263 break;
7265 T = Context.UnsignedLongFractTy;
7266 break;
7268 T = Context.SatShortAccumTy;
7269 break;
7271 T = Context.SatAccumTy;
7272 break;
7274 T = Context.SatLongAccumTy;
7275 break;
7277 T = Context.SatUnsignedShortAccumTy;
7278 break;
7280 T = Context.SatUnsignedAccumTy;
7281 break;
7283 T = Context.SatUnsignedLongAccumTy;
7284 break;
7286 T = Context.SatShortFractTy;
7287 break;
7289 T = Context.SatFractTy;
7290 break;
7292 T = Context.SatLongFractTy;
7293 break;
7295 T = Context.SatUnsignedShortFractTy;
7296 break;
7298 T = Context.SatUnsignedFractTy;
7299 break;
7301 T = Context.SatUnsignedLongFractTy;
7302 break;
7304 T = Context.Float16Ty;
7305 break;
7307 T = Context.Float128Ty;
7308 break;
7310 T = Context.Ibm128Ty;
7311 break;
7313 T = Context.OverloadTy;
7314 break;
7316 T = Context.BoundMemberTy;
7317 break;
7319 T = Context.PseudoObjectTy;
7320 break;
7322 T = Context.DependentTy;
7323 break;
7325 T = Context.UnknownAnyTy;
7326 break;
7328 T = Context.NullPtrTy;
7329 break;
7331 T = Context.Char8Ty;
7332 break;
7334 T = Context.Char16Ty;
7335 break;
7337 T = Context.Char32Ty;
7338 break;
7340 T = Context.ObjCBuiltinIdTy;
7341 break;
7343 T = Context.ObjCBuiltinClassTy;
7344 break;
7346 T = Context.ObjCBuiltinSelTy;
7347 break;
7348#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7349 case PREDEF_TYPE_##Id##_ID: \
7350 T = Context.SingletonId; \
7351 break;
7352#include "clang/Basic/OpenCLImageTypes.def"
7353#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7354 case PREDEF_TYPE_##Id##_ID: \
7355 T = Context.Id##Ty; \
7356 break;
7357#include "clang/Basic/OpenCLExtensionTypes.def"
7359 T = Context.OCLSamplerTy;
7360 break;
7362 T = Context.OCLEventTy;
7363 break;
7365 T = Context.OCLClkEventTy;
7366 break;
7368 T = Context.OCLQueueTy;
7369 break;
7371 T = Context.OCLReserveIDTy;
7372 break;
7374 T = Context.getAutoDeductType();
7375 break;
7377 T = Context.getAutoRRefDeductType();
7378 break;
7380 T = Context.ARCUnbridgedCastTy;
7381 break;
7383 T = Context.BuiltinFnTy;
7384 break;
7386 T = Context.IncompleteMatrixIdxTy;
7387 break;
7389 T = Context.ArraySectionTy;
7390 break;
7392 T = Context.OMPArrayShapingTy;
7393 break;
7395 T = Context.OMPIteratorTy;
7396 break;
7397#define SVE_TYPE(Name, Id, SingletonId) \
7398 case PREDEF_TYPE_##Id##_ID: \
7399 T = Context.SingletonId; \
7400 break;
7401#include "clang/Basic/AArch64SVEACLETypes.def"
7402#define PPC_VECTOR_TYPE(Name, Id, Size) \
7403 case PREDEF_TYPE_##Id##_ID: \
7404 T = Context.Id##Ty; \
7405 break;
7406#include "clang/Basic/PPCTypes.def"
7407#define RVV_TYPE(Name, Id, SingletonId) \
7408 case PREDEF_TYPE_##Id##_ID: \
7409 T = Context.SingletonId; \
7410 break;
7411#include "clang/Basic/RISCVVTypes.def"
7412#define WASM_TYPE(Name, Id, SingletonId) \
7413 case PREDEF_TYPE_##Id##_ID: \
7414 T = Context.SingletonId; \
7415 break;
7416#include "clang/Basic/WebAssemblyReferenceTypes.def"
7417 }
7418
7419 assert(!T.isNull() && "Unknown predefined type");
7420 return T.withFastQualifiers(FastQuals);
7421 }
7422
7423 Index -= NUM_PREDEF_TYPE_IDS;
7424 assert(Index < TypesLoaded.size() && "Type index out-of-range");
7425 if (TypesLoaded[Index].isNull()) {
7426 TypesLoaded[Index] = readTypeRecord(Index);
7427 if (TypesLoaded[Index].isNull())
7428 return QualType();
7429
7430 TypesLoaded[Index]->setFromAST();
7431 if (DeserializationListener)
7432 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
7433 TypesLoaded[Index]);
7434 }
7435
7436 return TypesLoaded[Index].withFastQualifiers(FastQuals);
7437}
7438
7440 return GetType(getGlobalTypeID(F, LocalID));
7441}
7442
7444ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
7445 unsigned FastQuals = LocalID & Qualifiers::FastMask;
7446 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
7447
7448 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
7449 return LocalID;
7450
7451 if (!F.ModuleOffsetMap.empty())
7452 ReadModuleOffsetMap(F);
7453
7455 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
7456 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
7457
7458 unsigned GlobalIndex = LocalIndex + I->second;
7459 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
7460}
7461
7464 switch (Kind) {
7466 return readExpr();
7468 return readTypeSourceInfo();
7470 NestedNameSpecifierLoc QualifierLoc =
7471 readNestedNameSpecifierLoc();
7472 SourceLocation TemplateNameLoc = readSourceLocation();
7473 return TemplateArgumentLocInfo(getASTContext(), QualifierLoc,
7474 TemplateNameLoc, SourceLocation());
7475 }
7477 NestedNameSpecifierLoc QualifierLoc = readNestedNameSpecifierLoc();
7478 SourceLocation TemplateNameLoc = readSourceLocation();
7479 SourceLocation EllipsisLoc = readSourceLocation();
7480 return TemplateArgumentLocInfo(getASTContext(), QualifierLoc,
7481 TemplateNameLoc, EllipsisLoc);
7482 }
7489 // FIXME: Is this right?
7490 return TemplateArgumentLocInfo();
7491 }
7492 llvm_unreachable("unexpected template argument loc");
7493}
7494
7496 TemplateArgument Arg = readTemplateArgument();
7497
7499 if (readBool()) // bool InfoHasSameExpr.
7501 }
7502 return TemplateArgumentLoc(Arg, readTemplateArgumentLocInfo(Arg.getKind()));
7503}
7504
7507 Result.setLAngleLoc(readSourceLocation());
7508 Result.setRAngleLoc(readSourceLocation());
7509 unsigned NumArgsAsWritten = readInt();
7510 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
7511 Result.addArgument(readTemplateArgumentLoc());
7512}
7513
7517 readTemplateArgumentListInfo(Result);
7518 return ASTTemplateArgumentListInfo::Create(getContext(), Result);
7519}
7520
7522
7524 if (NumCurrentElementsDeserializing) {
7525 // We arrange to not care about the complete redeclaration chain while we're
7526 // deserializing. Just remember that the AST has marked this one as complete
7527 // but that it's not actually complete yet, so we know we still need to
7528 // complete it later.
7529 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
7530 return;
7531 }
7532
7533 if (!D->getDeclContext()) {
7534 assert(isa<TranslationUnitDecl>(D) && "Not a TU?");
7535 return;
7536 }
7537
7538 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
7539
7540 // If this is a named declaration, complete it by looking it up
7541 // within its context.
7542 //
7543 // FIXME: Merging a function definition should merge
7544 // all mergeable entities within it.
7545 if (isa<TranslationUnitDecl, NamespaceDecl, RecordDecl, EnumDecl>(DC)) {
7546 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
7547 if (!getContext().getLangOpts().CPlusPlus &&
7548 isa<TranslationUnitDecl>(DC)) {
7549 // Outside of C++, we don't have a lookup table for the TU, so update
7550 // the identifier instead. (For C++ modules, we don't store decls
7551 // in the serialized identifier table, so we do the lookup in the TU.)
7552 auto *II = Name.getAsIdentifierInfo();
7553 assert(II && "non-identifier name in C?");
7554 if (II->isOutOfDate())
7555 updateOutOfDateIdentifier(*II);
7556 } else
7557 DC->lookup(Name);
7558 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
7559 // Find all declarations of this kind from the relevant context.
7560 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
7561 auto *DC = cast<DeclContext>(DCDecl);
7563 FindExternalLexicalDecls(
7564 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
7565 }
7566 }
7567 }
7568
7569 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
7570 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
7571 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
7572 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
7573 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7574 if (auto *Template = FD->getPrimaryTemplate())
7575 Template->LoadLazySpecializations();
7576 }
7577}
7578
7581 RecordLocation Loc = getLocalBitOffset(Offset);
7582 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7583 SavedStreamPosition SavedPosition(Cursor);
7584 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7585 Error(std::move(Err));
7586 return nullptr;
7587 }
7588 ReadingKindTracker ReadingKind(Read_Decl, *this);
7589 Deserializing D(this);
7590
7591 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7592 if (!MaybeCode) {
7593 Error(MaybeCode.takeError());
7594 return nullptr;
7595 }
7596 unsigned Code = MaybeCode.get();
7597
7598 ASTRecordReader Record(*this, *Loc.F);
7599 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
7600 if (!MaybeRecCode) {
7601 Error(MaybeRecCode.takeError());
7602 return nullptr;
7603 }
7604 if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
7605 Error("malformed AST file: missing C++ ctor initializers");
7606 return nullptr;
7607 }
7608
7609 return Record.readCXXCtorInitializers();
7610}
7611
7613 assert(ContextObj && "reading base specifiers with no AST context");
7614 ASTContext &Context = *ContextObj;
7615
7616 RecordLocation Loc = getLocalBitOffset(Offset);
7617 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7618 SavedStreamPosition SavedPosition(Cursor);
7619 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7620 Error(std::move(Err));
7621 return nullptr;
7622 }
7623 ReadingKindTracker ReadingKind(Read_Decl, *this);
7624 Deserializing D(this);
7625
7626 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7627 if (!MaybeCode) {
7628 Error(MaybeCode.takeError());
7629 return nullptr;
7630 }
7631 unsigned Code = MaybeCode.get();
7632
7633 ASTRecordReader Record(*this, *Loc.F);
7634 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
7635 if (!MaybeRecCode) {
7636 Error(MaybeCode.takeError());
7637 return nullptr;
7638 }
7639 unsigned RecCode = MaybeRecCode.get();
7640
7641 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
7642 Error("malformed AST file: missing C++ base specifiers");
7643 return nullptr;
7644 }
7645
7646 unsigned NumBases = Record.readInt();
7647 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
7648 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
7649 for (unsigned I = 0; I != NumBases; ++I)
7650 Bases[I] = Record.readCXXBaseSpecifier();
7651 return Bases;
7652}
7653
7655 LocalDeclID LocalID) const {
7656 DeclID ID = LocalID.get();
7657 if (ID < NUM_PREDEF_DECL_IDS)
7658 return GlobalDeclID(ID);
7659
7660 if (!F.ModuleOffsetMap.empty())
7661 ReadModuleOffsetMap(F);
7662
7665 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
7666
7667 return GlobalDeclID(ID + I->second);
7668}
7669
7671 // Predefined decls aren't from any module.
7672 if (ID.get() < NUM_PREDEF_DECL_IDS)
7673 return false;
7674
7675 return ID.get() - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
7676 ID.get() - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
7677}
7678
7680 if (!D->isFromASTFile())
7681 return nullptr;
7683 GlobalDeclMap.find(GlobalDeclID(D->getGlobalID()));
7684 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7685 return I->second;
7686}
7687
7689 if (ID.get() < NUM_PREDEF_DECL_IDS)
7690 return SourceLocation();
7691
7692 unsigned Index = ID.get() - NUM_PREDEF_DECL_IDS;
7693
7694 if (Index > DeclsLoaded.size()) {
7695 Error("declaration ID out-of-range for AST file");
7696 return SourceLocation();
7697 }
7698
7699 if (Decl *D = DeclsLoaded[Index])
7700 return D->getLocation();
7701
7702 SourceLocation Loc;
7703 DeclCursorForID(ID, Loc);
7704 return Loc;
7705}
7706
7708 switch (ID) {
7710 return nullptr;
7711
7713 return Context.getTranslationUnitDecl();
7714
7716 return Context.getObjCIdDecl();
7717
7719 return Context.getObjCSelDecl();
7720
7722 return Context.getObjCClassDecl();
7723
7725 return Context.getObjCProtocolDecl();
7726
7728 return Context.getInt128Decl();
7729
7731 return Context.getUInt128Decl();
7732
7734 return Context.getObjCInstanceTypeDecl();
7735
7737 return Context.getBuiltinVaListDecl();
7738
7740 return Context.getVaListTagDecl();
7741
7743 return Context.getBuiltinMSVaListDecl();
7744
7746 return Context.getMSGuidTagDecl();
7747
7749 return Context.getExternCContextDecl();
7750
7752 return Context.getMakeIntegerSeqDecl();
7753
7755 return Context.getCFConstantStringDecl();
7756
7758 return Context.getCFConstantStringTagDecl();
7759
7761 return Context.getTypePackElementDecl();
7762 }
7763 llvm_unreachable("PredefinedDeclIDs unknown enum value");
7764}
7765
7767 assert(ContextObj && "reading decl with no AST context");
7768 if (ID.get() < NUM_PREDEF_DECL_IDS) {
7769 Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
7770 if (D) {
7771 // Track that we have merged the declaration with ID \p ID into the
7772 // pre-existing predefined declaration \p D.
7773 auto &Merged = KeyDecls[D->getCanonicalDecl()];
7774 if (Merged.empty())
7775 Merged.push_back(ID);
7776 }
7777 return D;
7778 }
7779
7780 unsigned Index = ID.get() - NUM_PREDEF_DECL_IDS;
7781
7782 if (Index >= DeclsLoaded.size()) {
7783 assert(0 && "declaration ID out-of-range for AST file");
7784 Error("declaration ID out-of-range for AST file");
7785 return nullptr;
7786 }
7787
7788 return DeclsLoaded[Index];
7789}
7790
7792 if (ID.get() < NUM_PREDEF_DECL_IDS)
7793 return GetExistingDecl(ID);
7794
7795 unsigned Index = ID.get() - NUM_PREDEF_DECL_IDS;
7796
7797 if (Index >= DeclsLoaded.size()) {
7798 assert(0 && "declaration ID out-of-range for AST file");
7799 Error("declaration ID out-of-range for AST file");
7800 return nullptr;
7801 }
7802
7803 if (!DeclsLoaded[Index]) {
7804 ReadDeclRecord(ID);
7805 if (DeserializationListener)
7806 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7807 }
7808
7809 return DeclsLoaded[Index];
7810}
7811
7813 GlobalDeclID GlobalID) {
7814 DeclID ID = GlobalID.get();
7815 if (ID < NUM_PREDEF_DECL_IDS)
7816 return LocalDeclID(ID);
7817
7818 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7819 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7820 ModuleFile *Owner = I->second;
7821
7822 llvm::DenseMap<ModuleFile *, DeclID>::iterator Pos =
7823 M.GlobalToLocalDeclIDs.find(Owner);
7824 if (Pos == M.GlobalToLocalDeclIDs.end())
7825 return LocalDeclID();
7826
7827 return LocalDeclID(ID - Owner->BaseDeclID + Pos->second);
7828}
7829
7831 unsigned &Idx) {
7832 if (Idx >= Record.size()) {
7833 Error("Corrupted AST file");
7834 return GlobalDeclID(0);
7835 }
7836
7837 return getGlobalDeclID(F, LocalDeclID(Record[Idx++]));
7838}
7839
7840/// Resolve the offset of a statement into a statement.
7841///
7842/// This operation will read a new statement from the external
7843/// source each time it is called, and is meant to be used via a
7844/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7846 // Switch case IDs are per Decl.
7847 ClearSwitchCaseIDs();
7848
7849 // Offset here is a global offset across the entire chain.
7850 RecordLocation Loc = getLocalBitOffset(Offset);
7851 if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
7852 Error(std::move(Err));
7853 return nullptr;
7854 }
7855 assert(NumCurrentElementsDeserializing == 0 &&
7856 "should not be called while already deserializing");
7857 Deserializing D(this);
7858 return ReadStmtFromStream(*Loc.F);
7859}
7860
7862 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7863 SmallVectorImpl<Decl *> &Decls) {
7864 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7865
7866 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
7867 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7868 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7869 auto K = (Decl::Kind)+LexicalDecls[I];
7870 if (!IsKindWeWant(K))
7871 continue;
7872
7873 auto ID = (DeclID) + LexicalDecls[I + 1];
7874
7875 // Don't add predefined declarations to the lexical context more
7876 // than once.
7877 if (ID < NUM_PREDEF_DECL_IDS) {
7878 if (PredefsVisited[ID])
7879 continue;
7880
7881 PredefsVisited[ID] = true;
7882 }
7883
7884 if (Decl *D = GetLocalDecl(*M, LocalDeclID(ID))) {
7885 assert(D->getKind() == K && "wrong kind for lexical decl");
7886 if (!DC->isDeclInLexicalTraversal(D))
7887 Decls.push_back(D);
7888 }
7889 }
7890 };
7891
7892 if (isa<TranslationUnitDecl>(DC)) {
7893 for (const auto &Lexical : TULexicalDecls)
7894 Visit(Lexical.first, Lexical.second);
7895 } else {
7896 auto I = LexicalDecls.find(DC);
7897 if (I != LexicalDecls.end())
7898 Visit(I->second.first, I->second.second);
7899 }
7900
7901 ++NumLexicalDeclContextsRead;
7902}
7903
7904namespace {
7905
7906class DeclIDComp {
7907 ASTReader &Reader;
7908 ModuleFile &Mod;
7909
7910public:
7911 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7912
7913 bool operator()(LocalDeclID L, LocalDeclID R) const {
7914 SourceLocation LHS = getLocation(L);
7915 SourceLocation RHS = getLocation(R);
7916 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7917 }
7918
7919 bool operator()(SourceLocation LHS, LocalDeclID R) const {
7920 SourceLocation RHS = getLocation(R);
7921 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7922 }
7923
7924 bool operator()(LocalDeclID L, SourceLocation RHS) const {
7925 SourceLocation LHS = getLocation(L);
7926 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7927 }
7928
7929 SourceLocation getLocation(LocalDeclID ID) const {
7930 return Reader.getSourceManager().getFileLoc(
7931 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7932 }
7933};
7934
7935} // namespace
7936
7938 unsigned Offset, unsigned Length,
7939 SmallVectorImpl<Decl *> &Decls) {
7940 SourceManager &SM = getSourceManager();
7941
7942 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7943 if (I == FileDeclIDs.end())
7944 return;
7945
7946 FileDeclsInfo &DInfo = I->second;
7947 if (DInfo.Decls.empty())
7948 return;
7949
7951 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7952 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7953
7954 DeclIDComp DIDComp(*this, *DInfo.Mod);
7956 llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
7957 if (BeginIt != DInfo.Decls.begin())
7958 --BeginIt;
7959
7960 // If we are pointing at a top-level decl inside an objc container, we need
7961 // to backtrack until we find it otherwise we will fail to report that the
7962 // region overlaps with an objc container.
7963 while (BeginIt != DInfo.Decls.begin() &&
7964 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7965 ->isTopLevelDeclInObjCContainer())
7966 --BeginIt;
7967
7969 llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
7970 if (EndIt != DInfo.Decls.end())
7971 ++EndIt;
7972
7973 for (ArrayRef<LocalDeclID>::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
7974 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7975}
7976
7977bool
7979 DeclarationName Name) {
7980 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
7981 "DeclContext has no visible decls in storage");
7982 if (!Name)
7983 return false;
7984
7985 auto It = Lookups.find(DC);
7986 if (It == Lookups.end())
7987 return false;
7988
7989 Deserializing LookupResults(this);
7990
7991 // Load the list of declarations.
7994
7995 for (GlobalDeclID ID : It->second.Table.find(Name)) {
7996 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7997 if (ND->getDeclName() == Name && Found.insert(ND).second)
7998 Decls.push_back(ND);
7999 }
8000
8001 ++NumVisibleDeclContextsRead;
8002 SetExternalVisibleDeclsForName(DC, Name, Decls);
8003 return !Decls.empty();
8004}
8005
8007 if (!DC->hasExternalVisibleStorage())
8008 return;
8009
8010 auto It = Lookups.find(DC);
8011 assert(It != Lookups.end() &&
8012 "have external visible storage but no lookup tables");
8013
8014 DeclsMap Decls;
8015
8016 for (GlobalDeclID ID : It->second.Table.findAll()) {
8017 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
8018 Decls[ND->getDeclName()].push_back(ND);
8019 }
8020
8021 ++NumVisibleDeclContextsRead;
8022
8023 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
8024 SetExternalVisibleDeclsForName(DC, I->first, I->second);
8025 }
8026 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
8027}
8028
8031 auto I = Lookups.find(Primary);
8032 return I == Lookups.end() ? nullptr : &I->second;
8033}
8034
8035/// Under non-PCH compilation the consumer receives the objc methods
8036/// before receiving the implementation, and codegen depends on this.
8037/// We simulate this by deserializing and passing to consumer the methods of the
8038/// implementation before passing the deserialized implementation decl.
8040 ASTConsumer *Consumer) {
8041 assert(ImplD && Consumer);
8042
8043 for (auto *I : ImplD->methods())
8044 Consumer->HandleInterestingDecl(DeclGroupRef(I));
8045
8046 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
8047}
8048
8049void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
8050 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
8051 PassObjCImplDeclToConsumer(ImplD, Consumer);
8052 else
8053 Consumer->HandleInterestingDecl(DeclGroupRef(D));
8054}
8055
8057 this->Consumer = Consumer;
8058
8059 if (Consumer)
8060 PassInterestingDeclsToConsumer();
8061
8062 if (DeserializationListener)
8063 DeserializationListener->ReaderInitialized(this);
8064}
8065
8067 std::fprintf(stderr, "*** AST File Statistics:\n");
8068
8069 unsigned NumTypesLoaded =
8070 TypesLoaded.size() - llvm::count(TypesLoaded.materialized(), QualType());
8071 unsigned NumDeclsLoaded =
8072 DeclsLoaded.size() -
8073 llvm::count(DeclsLoaded.materialized(), (Decl *)nullptr);
8074 unsigned NumIdentifiersLoaded =
8075 IdentifiersLoaded.size() -
8076 llvm::count(IdentifiersLoaded, (IdentifierInfo *)nullptr);
8077 unsigned NumMacrosLoaded =
8078 MacrosLoaded.size() - llvm::count(MacrosLoaded, (MacroInfo *)nullptr);
8079 unsigned NumSelectorsLoaded =
8080 SelectorsLoaded.size() - llvm::count(SelectorsLoaded, Selector());
8081
8082 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
8083 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
8084 NumSLocEntriesRead, TotalNumSLocEntries,
8085 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
8086 if (!TypesLoaded.empty())
8087 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
8088 NumTypesLoaded, (unsigned)TypesLoaded.size(),
8089 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
8090 if (!DeclsLoaded.empty())
8091 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
8092 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
8093 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
8094 if (!IdentifiersLoaded.empty())
8095 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
8096 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
8097 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
8098 if (!MacrosLoaded.empty())
8099 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
8100 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
8101 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
8102 if (!SelectorsLoaded.empty())
8103 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
8104 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
8105 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
8106 if (TotalNumStatements)
8107 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
8108 NumStatementsRead, TotalNumStatements,
8109 ((float)NumStatementsRead/TotalNumStatements * 100));
8110 if (TotalNumMacros)
8111 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
8112 NumMacrosRead, TotalNumMacros,
8113 ((float)NumMacrosRead/TotalNumMacros * 100));
8114 if (TotalLexicalDeclContexts)
8115 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
8116 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
8117 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
8118 * 100));
8119 if (TotalVisibleDeclContexts)
8120 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
8121 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
8122 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
8123 * 100));
8124 if (TotalNumMethodPoolEntries)
8125 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
8126 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
8127 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
8128 * 100));
8129 if (NumMethodPoolLookups)
8130 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
8131 NumMethodPoolHits, NumMethodPoolLookups,
8132 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
8133 if (NumMethodPoolTableLookups)
8134 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
8135 NumMethodPoolTableHits, NumMethodPoolTableLookups,
8136 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
8137 * 100.0));
8138 if (NumIdentifierLookupHits)
8139 std::fprintf(stderr,
8140 " %u / %u identifier table lookups succeeded (%f%%)\n",
8141 NumIdentifierLookupHits, NumIdentifierLookups,
8142 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
8143
8144 if (GlobalIndex) {
8145 std::fprintf(stderr, "\n");
8146 GlobalIndex->printStats();
8147 }
8148
8149 std::fprintf(stderr, "\n");
8150 dump();
8151 std::fprintf(stderr, "\n");
8152}
8153
8154template<typename Key, typename ModuleFile, unsigned InitialCapacity>
8155LLVM_DUMP_METHOD static void
8156dumpModuleIDMap(StringRef Name,
8157 const ContinuousRangeMap<Key, ModuleFile *,
8158 InitialCapacity> &Map) {
8159 if (Map.begin() == Map.end())
8160 return;
8161
8163
8164 llvm::errs() << Name << ":\n";
8165 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
8166 I != IEnd; ++I) {
8167 uint64_t ID = 0;
8168 if constexpr (std::is_integral_v<Key>)
8169 ID = I->first;
8170 else /*GlobalDeclID*/
8171 ID = I->first.get();
8172 llvm::errs() << " " << ID << " -> " << I->second->FileName << "\n";
8173 }
8174}
8175
8176LLVM_DUMP_METHOD void ASTReader::dump() {
8177 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
8178 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
8179 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
8180 dumpModuleIDMap("Global type map", GlobalTypeMap);
8181 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
8182 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
8183 dumpModuleIDMap("Global macro map", GlobalMacroMap);
8184 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
8185 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
8186 dumpModuleIDMap("Global preprocessed entity map",
8187 GlobalPreprocessedEntityMap);
8188
8189 llvm::errs() << "\n*** PCH/Modules Loaded:";
8190 for (ModuleFile &M : ModuleMgr)
8191 M.dump();
8192}
8193
8194/// Return the amount of memory used by memory buffers, breaking down
8195/// by heap-backed versus mmap'ed memory.
8197 for (ModuleFile &I : ModuleMgr) {
8198 if (llvm::MemoryBuffer *buf = I.Buffer) {
8199 size_t bytes = buf->getBufferSize();
8200 switch (buf->getBufferKind()) {
8201 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
8202 sizes.malloc_bytes += bytes;
8203 break;
8204 case llvm::MemoryBuffer::MemoryBuffer_MMap:
8205 sizes.mmap_bytes += bytes;
8206 break;
8207 }
8208 }
8209 }
8210}
8211
8213 SemaObj = &S;
8214 S.addExternalSource(this);
8215
8216 // Makes sure any declarations that were deserialized "too early"
8217 // still get added to the identifier's declaration chains.
8218 for (GlobalDeclID ID : PreloadedDeclIDs) {
8219 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
8220 pushExternalDeclIntoScope(D, D->getDeclName());
8221 }
8222 PreloadedDeclIDs.clear();
8223
8224 // FIXME: What happens if these are changed by a module import?
8225 if (!FPPragmaOptions.empty()) {
8226 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
8227 FPOptionsOverride NewOverrides =
8228 FPOptionsOverride::getFromOpaqueInt(FPPragmaOptions[0]);
8229 SemaObj->CurFPFeatures =
8230 NewOverrides.applyOverrides(SemaObj->getLangOpts());
8231 }
8232
8233 SemaObj->OpenCLFeatures = OpenCLExtensions;
8234
8235 UpdateSema();
8236}
8237
8239 assert(SemaObj && "no Sema to update");
8240
8241 // Load the offsets of the declarations that Sema references.
8242 // They will be lazily deserialized when needed.
8243 if (!SemaDeclRefs.empty()) {
8244 assert(SemaDeclRefs.size() % 3 == 0);
8245 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
8246 if (!SemaObj->StdNamespace)
8247 SemaObj->StdNamespace = SemaDeclRefs[I].get();
8248 if (!SemaObj->StdBadAlloc)
8249 SemaObj->StdBadAlloc = SemaDeclRefs[I + 1].get();
8250 if (!SemaObj->StdAlignValT)
8251 SemaObj->StdAlignValT = SemaDeclRefs[I + 2].get();
8252 }
8253 SemaDeclRefs.clear();
8254 }
8255
8256 // Update the state of pragmas. Use the same API as if we had encountered the
8257 // pragma in the source.
8258 if(OptimizeOffPragmaLocation.isValid())
8259 SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
8260 if (PragmaMSStructState != -1)
8261 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
8262 if (PointersToMembersPragmaLocation.isValid()) {
8263 SemaObj->ActOnPragmaMSPointersToMembers(
8265 PragmaMSPointersToMembersState,
8266 PointersToMembersPragmaLocation);
8267 }
8268 SemaObj->CUDA().ForceHostDeviceDepth = ForceHostDeviceDepth;
8269
8270 if (PragmaAlignPackCurrentValue) {
8271 // The bottom of the stack might have a default value. It must be adjusted
8272 // to the current value to ensure that the packing state is preserved after
8273 // popping entries that were included/imported from a PCH/module.
8274 bool DropFirst = false;
8275 if (!PragmaAlignPackStack.empty() &&
8276 PragmaAlignPackStack.front().Location.isInvalid()) {
8277 assert(PragmaAlignPackStack.front().Value ==
8278 SemaObj->AlignPackStack.DefaultValue &&
8279 "Expected a default alignment value");
8280 SemaObj->AlignPackStack.Stack.emplace_back(
8281 PragmaAlignPackStack.front().SlotLabel,
8282 SemaObj->AlignPackStack.CurrentValue,
8283 SemaObj->AlignPackStack.CurrentPragmaLocation,
8284 PragmaAlignPackStack.front().PushLocation);
8285 DropFirst = true;
8286 }
8287 for (const auto &Entry :
8288 llvm::ArrayRef(PragmaAlignPackStack).drop_front(DropFirst ? 1 : 0)) {
8289 SemaObj->AlignPackStack.Stack.emplace_back(
8290 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
8291 }
8292 if (PragmaAlignPackCurrentLocation.isInvalid()) {
8293 assert(*PragmaAlignPackCurrentValue ==
8294 SemaObj->AlignPackStack.DefaultValue &&
8295 "Expected a default align and pack value");
8296 // Keep the current values.
8297 } else {
8298 SemaObj->AlignPackStack.CurrentValue = *PragmaAlignPackCurrentValue;
8299 SemaObj->AlignPackStack.CurrentPragmaLocation =
8300 PragmaAlignPackCurrentLocation;
8301 }
8302 }
8303 if (FpPragmaCurrentValue) {
8304 // The bottom of the stack might have a default value. It must be adjusted
8305 // to the current value to ensure that fp-pragma state is preserved after
8306 // popping entries that were included/imported from a PCH/module.
8307 bool DropFirst = false;
8308 if (!FpPragmaStack.empty() && FpPragmaStack.front().Location.isInvalid()) {
8309 assert(FpPragmaStack.front().Value ==
8310 SemaObj->FpPragmaStack.DefaultValue &&
8311 "Expected a default pragma float_control value");
8312 SemaObj->FpPragmaStack.Stack.emplace_back(
8313 FpPragmaStack.front().SlotLabel, SemaObj->FpPragmaStack.CurrentValue,
8314 SemaObj->FpPragmaStack.CurrentPragmaLocation,
8315 FpPragmaStack.front().PushLocation);
8316 DropFirst = true;
8317 }
8318 for (const auto &Entry :
8319 llvm::ArrayRef(FpPragmaStack).drop_front(DropFirst ? 1 : 0))
8320 SemaObj->FpPragmaStack.Stack.emplace_back(
8321 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
8322 if (FpPragmaCurrentLocation.isInvalid()) {
8323 assert(*FpPragmaCurrentValue == SemaObj->FpPragmaStack.DefaultValue &&
8324 "Expected a default pragma float_control value");
8325 // Keep the current values.
8326 } else {
8327 SemaObj->FpPragmaStack.CurrentValue = *FpPragmaCurrentValue;
8328 SemaObj->FpPragmaStack.CurrentPragmaLocation = FpPragmaCurrentLocation;
8329 }
8330 }
8331
8332 // For non-modular AST files, restore visiblity of modules.
8333 for (auto &Import : PendingImportedModulesSema) {
8334 if (Import.ImportLoc.isInvalid())
8335 continue;
8336 if (Module *Imported = getSubmodule(Import.ID)) {
8337 SemaObj->makeModuleVisible(Imported, Import.ImportLoc);
8338 }
8339 }
8340 PendingImportedModulesSema.clear();
8341}
8342
8344 // Note that we are loading an identifier.
8345 Deserializing AnIdentifier(this);
8346
8347 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
8348 NumIdentifierLookups,
8349 NumIdentifierLookupHits);
8350
8351 // We don't need to do identifier table lookups in C++ modules (we preload
8352 // all interesting declarations, and don't need to use the scope for name
8353 // lookups). Perform the lookup in PCH files, though, since we don't build
8354 // a complete initial identifier table if we're carrying on from a PCH.
8355 if (PP.getLangOpts().CPlusPlus) {
8356 for (auto *F : ModuleMgr.pch_modules())
8357 if (Visitor(*F))
8358 break;
8359 } else {
8360 // If there is a global index, look there first to determine which modules
8361 // provably do not have any results for this identifier.
8363 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
8364 if (!loadGlobalIndex()) {
8365 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
8366 HitsPtr = &Hits;
8367 }
8368 }
8369
8370 ModuleMgr.visit(Visitor, HitsPtr);
8371 }
8372
8373 IdentifierInfo *II = Visitor.getIdentifierInfo();
8374 markIdentifierUpToDate(II);
8375 return II;
8376}
8377
8378namespace clang {
8379
8380 /// An identifier-lookup iterator that enumerates all of the
8381 /// identifiers stored within a set of AST files.
8383 /// The AST reader whose identifiers are being enumerated.
8384 const ASTReader &Reader;
8385
8386 /// The current index into the chain of AST files stored in
8387 /// the AST reader.
8388 unsigned Index;
8389
8390 /// The current position within the identifier lookup table
8391 /// of the current AST file.
8392 ASTIdentifierLookupTable::key_iterator Current;
8393
8394 /// The end position within the identifier lookup table of
8395 /// the current AST file.
8396 ASTIdentifierLookupTable::key_iterator End;
8397
8398 /// Whether to skip any modules in the ASTReader.
8399 bool SkipModules;
8400
8401 public:
8402 explicit ASTIdentifierIterator(const ASTReader &Reader,
8403 bool SkipModules = false);
8404
8405 StringRef Next() override;
8406 };
8407
8408} // namespace clang
8409
8411 bool SkipModules)
8412 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
8413}
8414
8416 while (Current == End) {
8417 // If we have exhausted all of our AST files, we're done.
8418 if (Index == 0)
8419 return StringRef();
8420
8421 --Index;
8422 ModuleFile &F = Reader.ModuleMgr[Index];
8423 if (SkipModules && F.isModule())
8424 continue;
8425
8426 ASTIdentifierLookupTable *IdTable =
8428 Current = IdTable->key_begin();
8429 End = IdTable->key_end();
8430 }
8431
8432 // We have any identifiers remaining in the current AST file; return
8433 // the next one.
8434 StringRef Result = *Current;
8435 ++Current;
8436 return Result;
8437}
8438
8439namespace {
8440
8441/// A utility for appending two IdentifierIterators.
8442class ChainedIdentifierIterator : public IdentifierIterator {
8443 std::unique_ptr<IdentifierIterator> Current;
8444 std::unique_ptr<IdentifierIterator> Queued;
8445
8446public:
8447 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
8448 std::unique_ptr<IdentifierIterator> Second)
8449 : Current(std::move(First)), Queued(std::move(Second)) {}
8450
8451 StringRef Next() override {
8452 if (!Current)
8453 return StringRef();
8454
8455 StringRef result = Current->Next();
8456 if (!result.empty())
8457 return result;
8458
8459 // Try the queued iterator, which may itself be empty.
8460 Current.reset();
8461 std::swap(Current, Queued);
8462 return Next();
8463 }
8464};
8465
8466} // namespace
8467
8469 if (!loadGlobalIndex()) {
8470 std::unique_ptr<IdentifierIterator> ReaderIter(
8471 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
8472 std::unique_ptr<IdentifierIterator> ModulesIter(
8473 GlobalIndex->createIdentifierIterator());
8474 return new ChainedIdentifierIterator(std::move(ReaderIter),
8475 std::move(ModulesIter));
8476 }
8477
8478 return new ASTIdentifierIterator(*this);
8479}
8480
8481namespace clang {
8482namespace serialization {
8483
8485 ASTReader &Reader;
8486 Selector Sel;
8487 unsigned PriorGeneration;
8488 unsigned InstanceBits = 0;
8489 unsigned FactoryBits = 0;
8490 bool InstanceHasMoreThanOneDecl = false;
8491 bool FactoryHasMoreThanOneDecl = false;
8492 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
8493 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
8494
8495 public:
8497 unsigned PriorGeneration)
8498 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
8499
8501 if (!M.SelectorLookupTable)
8502 return false;
8503
8504 // If we've already searched this module file, skip it now.
8505 if (M.Generation <= PriorGeneration)
8506 return true;
8507
8508 ++Reader.NumMethodPoolTableLookups;
8509 ASTSelectorLookupTable *PoolTable
8511 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
8512 if (Pos == PoolTable->end())
8513 return false;
8514
8515 ++Reader.NumMethodPoolTableHits;
8516 ++Reader.NumSelectorsRead;
8517 // FIXME: Not quite happy with the statistics here. We probably should
8518 // disable this tracking when called via LoadSelector.
8519 // Also, should entries without methods count as misses?
8520 ++Reader.NumMethodPoolEntriesRead;
8522 if (Reader.DeserializationListener)
8523 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
8524
8525 // Append methods in the reverse order, so that later we can process them
8526 // in the order they appear in the source code by iterating through
8527 // the vector in the reverse order.
8528 InstanceMethods.append(Data.Instance.rbegin(), Data.Instance.rend());
8529 FactoryMethods.append(Data.Factory.rbegin(), Data.Factory.rend());
8530 InstanceBits = Data.InstanceBits;
8531 FactoryBits = Data.FactoryBits;
8532 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
8533 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
8534 return false;
8535 }
8536
8537 /// Retrieve the instance methods found by this visitor.
8539 return InstanceMethods;
8540 }
8541
8542 /// Retrieve the instance methods found by this visitor.
8544 return FactoryMethods;
8545 }
8546
8547 unsigned getInstanceBits() const { return InstanceBits; }
8548 unsigned getFactoryBits() const { return FactoryBits; }
8549
8551 return InstanceHasMoreThanOneDecl;
8552 }
8553
8554 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
8555 };
8556
8557} // namespace serialization
8558} // namespace clang
8559
8560/// Add the given set of methods to the method list.
8562 ObjCMethodList &List) {
8563 for (ObjCMethodDecl *M : llvm::reverse(Methods))
8564 S.addMethodToGlobalList(&List, M);
8565}
8566
8568 // Get the selector generation and update it to the current generation.
8569 unsigned &Generation = SelectorGeneration[Sel];
8570 unsigned PriorGeneration = Generation;
8571 Generation = getGeneration();
8572 SelectorOutOfDate[Sel] = false;
8573
8574 // Search for methods defined with this selector.
8575 ++NumMethodPoolLookups;
8576 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
8577 ModuleMgr.visit(Visitor);
8578
8579 if (Visitor.getInstanceMethods().empty() &&
8580 Visitor.getFactoryMethods().empty())
8581 return;
8582
8583 ++NumMethodPoolHits;
8584
8585 if (!getSema())
8586 return;
8587
8588 Sema &S = *getSema();
8590 S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethodPool::Lists()))
8591 .first;
8592
8593 Pos->second.first.setBits(Visitor.getInstanceBits());
8594 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
8595 Pos->second.second.setBits(Visitor.getFactoryBits());
8596 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
8597
8598 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
8599 // when building a module we keep every method individually and may need to
8600 // update hasMoreThanOneDecl as we add the methods.
8601 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
8602 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
8603}
8604
8606 if (SelectorOutOfDate[Sel])
8607 ReadMethodPool(Sel);
8608}
8609
8612 Namespaces.clear();
8613
8614 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
8615 if (NamespaceDecl *Namespace
8616 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
8617 Namespaces.push_back(Namespace);
8618 }
8619}
8620
8622 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
8623 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
8624 UndefinedButUsedDecl &U = UndefinedButUsed[Idx++];
8625 NamedDecl *D = cast<NamedDecl>(GetDecl(U.ID));
8627 Undefined.insert(std::make_pair(D, Loc));
8628 }
8629 UndefinedButUsed.clear();
8630}
8631
8633 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
8634 Exprs) {
8635 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
8636 FieldDecl *FD =
8637 cast<FieldDecl>(GetDecl(GlobalDeclID(DelayedDeleteExprs[Idx++])));
8638 uint64_t Count = DelayedDeleteExprs[Idx++];
8639 for (uint64_t C = 0; C < Count; ++C) {
8640 SourceLocation DeleteLoc =
8641 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
8642 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
8643 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
8644 }
8645 }
8646}
8647
8649 SmallVectorImpl<VarDecl *> &TentativeDefs) {
8650 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
8651 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
8652 if (Var)
8653 TentativeDefs.push_back(Var);
8654 }
8655 TentativeDefinitions.clear();
8656}
8657
8660 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
8662 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
8663 if (D)
8664 Decls.push_back(D);
8665 }
8666 UnusedFileScopedDecls.clear();
8667}
8668
8671 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
8673 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
8674 if (D)
8675 Decls.push_back(D);
8676 }
8677 DelegatingCtorDecls.clear();
8678}
8679
8681 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
8683 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
8684 if (D)
8685 Decls.push_back(D);
8686 }
8687 ExtVectorDecls.clear();
8688}
8689
8692 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
8693 ++I) {
8694 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
8695 GetDecl(UnusedLocalTypedefNameCandidates[I]));
8696 if (D)
8697 Decls.insert(D);
8698 }
8699 UnusedLocalTypedefNameCandidates.clear();
8700}
8701
8704 for (auto I : DeclsToCheckForDeferredDiags) {
8705 auto *D = dyn_cast_or_null<Decl>(GetDecl(I));
8706 if (D)
8707 Decls.insert(D);
8708 }
8709 DeclsToCheckForDeferredDiags.clear();
8710}
8711
8713 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
8714 if (ReferencedSelectorsData.empty())
8715 return;
8716
8717 // If there are @selector references added them to its pool. This is for
8718 // implementation of -Wselector.
8719 unsigned int DataSize = ReferencedSelectorsData.size()-1;
8720 unsigned I = 0;
8721 while (I < DataSize) {
8722 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
8723 SourceLocation SelLoc
8724 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
8725 Sels.push_back(std::make_pair(Sel, SelLoc));
8726 }
8727 ReferencedSelectorsData.clear();
8728}
8729
8731 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
8732 if (WeakUndeclaredIdentifiers.empty())
8733 return;
8734
8735 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
8736 IdentifierInfo *WeakId
8737 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8738 IdentifierInfo *AliasId
8739 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8740 SourceLocation Loc =
8741 SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
8742 WeakInfo WI(AliasId, Loc);
8743 WeakIDs.push_back(std::make_pair(WeakId, WI));
8744 }
8745 WeakUndeclaredIdentifiers.clear();
8746}
8747
8749 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
8751 VTableUse &TableInfo = VTableUses[Idx++];
8752 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(TableInfo.ID));
8753 VT.Location = SourceLocation::getFromRawEncoding(TableInfo.RawLoc);
8754 VT.DefinitionRequired = TableInfo.Used;
8755 VTables.push_back(VT);
8756 }
8757
8758 VTableUses.clear();
8759}
8760
8762 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
8763 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
8764 PendingInstantiation &Inst = PendingInstantiations[Idx++];
8765 ValueDecl *D = cast<ValueDecl>(GetDecl(Inst.ID));
8767
8768 Pending.push_back(std::make_pair(D, Loc));
8769 }
8770 PendingInstantiations.clear();
8771}
8772
8774 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
8775 &LPTMap) {
8776 for (auto &LPT : LateParsedTemplates) {
8777 ModuleFile *FMod = LPT.first;
8778 RecordDataImpl &LateParsed = LPT.second;
8779 for (unsigned Idx = 0, N = LateParsed.size(); Idx < N;
8780 /* In loop */) {
8781 FunctionDecl *FD = cast<FunctionDecl>(
8782 GetLocalDecl(*FMod, LocalDeclID(LateParsed[Idx++])));
8783
8784 auto LT = std::make_unique<LateParsedTemplate>();
8785 LT->D = GetLocalDecl(*FMod, LocalDeclID(LateParsed[Idx++]));
8786 LT->FPO = FPOptions::getFromOpaqueInt(LateParsed[Idx++]);
8787
8789 assert(F && "No module");
8790
8791 unsigned TokN = LateParsed[Idx++];
8792 LT->Toks.reserve(TokN);
8793 for (unsigned T = 0; T < TokN; ++T)
8794 LT->Toks.push_back(ReadToken(*F, LateParsed, Idx));
8795
8796 LPTMap.insert(std::make_pair(FD, std::move(LT)));
8797 }
8798 }
8799
8800 LateParsedTemplates.clear();
8801}
8802
8804 if (Lambda->getLambdaContextDecl()) {
8805 // Keep track of this lambda so it can be merged with another lambda that
8806 // is loaded later.
8807 LambdaDeclarationsForMerging.insert(
8809 Lambda->getLambdaIndexInContext()},
8810 const_cast<CXXRecordDecl *>(Lambda)});
8811 }
8812}
8813
8815 // It would be complicated to avoid reading the methods anyway. So don't.
8816 ReadMethodPool(Sel);
8817}
8818
8820 assert(ID && "Non-zero identifier ID required");
8821 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
8822 IdentifiersLoaded[ID - 1] = II;
8823 if (DeserializationListener)
8824 DeserializationListener->IdentifierRead(ID, II);
8825}
8826
8827/// Set the globally-visible declarations associated with the given
8828/// identifier.
8829///
8830/// If the AST reader is currently in a state where the given declaration IDs
8831/// cannot safely be resolved, they are queued until it is safe to resolve
8832/// them.
8833///
8834/// \param II an IdentifierInfo that refers to one or more globally-visible
8835/// declarations.
8836///
8837/// \param DeclIDs the set of declaration IDs with the name @p II that are
8838/// visible at global scope.
8839///
8840/// \param Decls if non-null, this vector will be populated with the set of
8841/// deserialized declarations. These declarations will not be pushed into
8842/// scope.
8845 SmallVectorImpl<Decl *> *Decls) {
8846 if (NumCurrentElementsDeserializing && !Decls) {
8847 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
8848 return;
8849 }
8850
8851 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
8852 if (!SemaObj) {
8853 // Queue this declaration so that it will be added to the
8854 // translation unit scope and identifier's declaration chain
8855 // once a Sema object is known.
8856 PreloadedDeclIDs.push_back(DeclIDs[I]);
8857 continue;
8858 }
8859
8860 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
8861
8862 // If we're simply supposed to record the declarations, do so now.
8863 if (Decls) {
8864 Decls->push_back(D);
8865 continue;
8866 }
8867
8868 // Introduce this declaration into the translation-unit scope
8869 // and add it to the declaration chain for this identifier, so
8870 // that (unqualified) name lookup will find it.
8871 pushExternalDeclIntoScope(D, II);
8872 }
8873}
8874
8876 if (ID == 0)
8877 return nullptr;
8878
8879 if (IdentifiersLoaded.empty()) {
8880 Error("no identifier table in AST file");
8881 return nullptr;
8882 }
8883
8884 ID -= 1;
8885 if (!IdentifiersLoaded[ID]) {
8886 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8887 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8888 ModuleFile *M = I->second;
8889 unsigned Index = ID - M->BaseIdentifierID;
8890 const unsigned char *Data =
8892
8893 ASTIdentifierLookupTrait Trait(*this, *M);
8894 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
8895 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
8896 auto &II = PP.getIdentifierTable().get(Key);
8897 IdentifiersLoaded[ID] = &II;
8898 markIdentifierFromAST(*this, II);
8899 if (DeserializationListener)
8900 DeserializationListener->IdentifierRead(ID + 1, &II);
8901 }
8902
8903 return IdentifiersLoaded[ID];
8904}
8905
8907 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
8908}
8909
8911 if (LocalID < NUM_PREDEF_IDENT_IDS)
8912 return LocalID;
8913
8914 if (!M.ModuleOffsetMap.empty())
8915 ReadModuleOffsetMap(M);
8916
8919 assert(I != M.IdentifierRemap.end()
8920 && "Invalid index into identifier index remap");
8921
8922 return LocalID + I->second;
8923}
8924
8926 if (ID == 0)
8927 return nullptr;
8928
8929 if (MacrosLoaded.empty()) {
8930 Error("no macro table in AST file");
8931 return nullptr;
8932 }
8933
8935 if (!MacrosLoaded[ID]) {
8937 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8938 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8939 ModuleFile *M = I->second;
8940 unsigned Index = ID - M->BaseMacroID;
8941 MacrosLoaded[ID] =
8942 ReadMacroRecord(*M, M->MacroOffsetsBase + M->MacroOffsets[Index]);
8943
8944 if (DeserializationListener)
8945 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8946 MacrosLoaded[ID]);
8947 }
8948
8949 return MacrosLoaded[ID];
8950}
8951
8953 if (LocalID < NUM_PREDEF_MACRO_IDS)
8954 return LocalID;
8955
8956 if (!M.ModuleOffsetMap.empty())
8957 ReadModuleOffsetMap(M);
8958
8960 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8961 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8962
8963 return LocalID + I->second;
8964}
8965
8968 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8969 return LocalID;
8970
8971 if (!M.ModuleOffsetMap.empty())
8972 ReadModuleOffsetMap(M);
8973
8976 assert(I != M.SubmoduleRemap.end()
8977 && "Invalid index into submodule index remap");
8978
8979 return LocalID + I->second;
8980}
8981
8983 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8984 assert(GlobalID == 0 && "Unhandled global submodule ID");
8985 return nullptr;
8986 }
8987
8988 if (GlobalID > SubmodulesLoaded.size()) {
8989 Error("submodule ID out of range in AST file");
8990 return nullptr;
8991 }
8992
8993 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8994}
8995
8997 return getSubmodule(ID);
8998}
8999
9001 if (ID & 1) {
9002 // It's a module, look it up by submodule ID.
9003 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(M, ID >> 1));
9004 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
9005 } else {
9006 // It's a prefix (preamble, PCH, ...). Look it up by index.
9007 unsigned IndexFromEnd = ID >> 1;
9008 assert(IndexFromEnd && "got reference to unknown module file");
9009 return getModuleManager().pch_modules().end()[-IndexFromEnd];
9010 }
9011}
9012
9014 if (!M)
9015 return 1;
9016
9017 // For a file representing a module, use the submodule ID of the top-level
9018 // module as the file ID. For any other kind of file, the number of such
9019 // files loaded beforehand will be the same on reload.
9020 // FIXME: Is this true even if we have an explicit module file and a PCH?
9021 if (M->isModule())
9022 return ((M->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
9023
9024 auto PCHModules = getModuleManager().pch_modules();
9025 auto I = llvm::find(PCHModules, M);
9026 assert(I != PCHModules.end() && "emitting reference to unknown file");
9027 return (I - PCHModules.end()) << 1;
9028}
9029
9030std::optional<ASTSourceDescriptor> ASTReader::getSourceDescriptor(unsigned ID) {
9031 if (Module *M = getSubmodule(ID))
9032 return ASTSourceDescriptor(*M);
9033
9034 // If there is only a single PCH, return it instead.
9035 // Chained PCH are not supported.
9036 const auto &PCHChain = ModuleMgr.pch_modules();
9037 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
9038 ModuleFile &MF = ModuleMgr.getPrimaryModule();
9039 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
9040 StringRef FileName = llvm::sys::path::filename(MF.FileName);
9041 return ASTSourceDescriptor(ModuleName,
9042 llvm::sys::path::parent_path(MF.FileName),
9043 FileName, MF.Signature);
9044 }
9045 return std::nullopt;
9046}
9047
9049 auto I = DefinitionSource.find(FD);
9050 if (I == DefinitionSource.end())
9051 return EK_ReplyHazy;
9052 return I->second ? EK_Never : EK_Always;
9053}
9054
9056 return DecodeSelector(getGlobalSelectorID(M, LocalID));
9057}
9058
9060 if (ID == 0)
9061 return Selector();
9062
9063 if (ID > SelectorsLoaded.size()) {
9064 Error("selector ID out of range in AST file");
9065 return Selector();
9066 }
9067
9068 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
9069 // Load this selector from the selector table.
9070 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
9071 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
9072 ModuleFile &M = *I->second;
9073 ASTSelectorLookupTrait Trait(*this, M);
9074 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
9075 SelectorsLoaded[ID - 1] =
9076 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
9077 if (DeserializationListener)
9078 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
9079 }
9080
9081 return SelectorsLoaded[ID - 1];
9082}
9083
9085 return DecodeSelector(ID);
9086}
9087
9089 // ID 0 (the null selector) is considered an external selector.
9090 return getTotalNumSelectors() + 1;
9091}
9092
9094ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
9095 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
9096 return LocalID;
9097
9098 if (!M.ModuleOffsetMap.empty())
9099 ReadModuleOffsetMap(M);
9100
9103 assert(I != M.SelectorRemap.end()
9104 && "Invalid index into selector index remap");
9105
9106 return LocalID + I->second;
9107}
9108
9111 switch (Name.getNameKind()) {
9116
9119
9123
9130 break;
9131 }
9132 return DeclarationNameLoc();
9133}
9134
9136 DeclarationNameInfo NameInfo;
9137 NameInfo.setName(readDeclarationName());
9138 NameInfo.setLoc(readSourceLocation());
9139 NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName()));
9140 return NameInfo;
9141}
9142
9144 return TypeCoupledDeclRefInfo(readDeclAs<ValueDecl>(), readBool());
9145}
9146
9149 unsigned NumTPLists = readInt();
9150 Info.NumTemplParamLists = NumTPLists;
9151 if (NumTPLists) {
9152 Info.TemplParamLists =
9153 new (getContext()) TemplateParameterList *[NumTPLists];
9154 for (unsigned i = 0; i != NumTPLists; ++i)
9156 }
9157}
9158
9161 SourceLocation TemplateLoc = readSourceLocation();
9162 SourceLocation LAngleLoc = readSourceLocation();
9163 SourceLocation RAngleLoc = readSourceLocation();
9164
9165 unsigned NumParams = readInt();
9167 Params.reserve(NumParams);
9168 while (NumParams--)
9169 Params.push_back(readDeclAs<NamedDecl>());
9170
9171 bool HasRequiresClause = readBool();
9172 Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr;
9173
9175 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
9176 return TemplateParams;
9177}
9178
9181 bool Canonicalize) {
9182 unsigned NumTemplateArgs = readInt();
9183 TemplArgs.reserve(NumTemplateArgs);
9184 while (NumTemplateArgs--)
9185 TemplArgs.push_back(readTemplateArgument(Canonicalize));
9186}
9187
9188/// Read a UnresolvedSet structure.
9190 unsigned NumDecls = readInt();
9191 Set.reserve(getContext(), NumDecls);
9192 while (NumDecls--) {
9193 GlobalDeclID ID = readDeclID();
9195 Set.addLazyDecl(getContext(), ID.get(), AS);
9196 }
9197}
9198
9201 bool isVirtual = readBool();
9202 bool isBaseOfClass = readBool();
9203 AccessSpecifier AS = static_cast<AccessSpecifier>(readInt());
9204 bool inheritConstructors = readBool();
9206 SourceRange Range = readSourceRange();
9207 SourceLocation EllipsisLoc = readSourceLocation();
9208 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
9209 EllipsisLoc);
9210 Result.setInheritConstructors(inheritConstructors);
9211 return Result;
9212}
9213
9216 ASTContext &Context = getContext();
9217 unsigned NumInitializers = readInt();
9218 assert(NumInitializers && "wrote ctor initializers but have no inits");
9219 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
9220 for (unsigned i = 0; i != NumInitializers; ++i) {
9221 TypeSourceInfo *TInfo = nullptr;
9222 bool IsBaseVirtual = false;
9223 FieldDecl *Member = nullptr;
9224 IndirectFieldDecl *IndirectMember = nullptr;
9225
9227 switch (Type) {
9229 TInfo = readTypeSourceInfo();
9230 IsBaseVirtual = readBool();
9231 break;
9232
9234 TInfo = readTypeSourceInfo();
9235 break;
9236
9238 Member = readDeclAs<FieldDecl>();
9239 break;
9240
9242 IndirectMember = readDeclAs<IndirectFieldDecl>();
9243 break;
9244 }
9245
9246 SourceLocation MemberOrEllipsisLoc = readSourceLocation();
9247 Expr *Init = readExpr();
9248 SourceLocation LParenLoc = readSourceLocation();
9249 SourceLocation RParenLoc = readSourceLocation();
9250
9251 CXXCtorInitializer *BOMInit;
9253 BOMInit = new (Context)
9254 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
9255 RParenLoc, MemberOrEllipsisLoc);
9257 BOMInit = new (Context)
9258 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
9259 else if (Member)
9260 BOMInit = new (Context)
9261 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
9262 Init, RParenLoc);
9263 else
9264 BOMInit = new (Context)
9265 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
9266 LParenLoc, Init, RParenLoc);
9267
9268 if (/*IsWritten*/readBool()) {
9269 unsigned SourceOrder = readInt();
9270 BOMInit->setSourceOrder(SourceOrder);
9271 }
9272
9273 CtorInitializers[i] = BOMInit;
9274 }
9275
9276 return CtorInitializers;
9277}
9278
9281 ASTContext &Context = getContext();
9282 unsigned N = readInt();
9284 for (unsigned I = 0; I != N; ++I) {
9285 auto Kind = readNestedNameSpecifierKind();
9286 switch (Kind) {
9289 SourceRange Range = readSourceRange();
9290 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
9291 break;
9292 }
9293
9295 NamespaceDecl *NS = readDeclAs<NamespaceDecl>();
9296 SourceRange Range = readSourceRange();
9297 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
9298 break;
9299 }
9300
9302 NamespaceAliasDecl *Alias = readDeclAs<NamespaceAliasDecl>();
9303 SourceRange Range = readSourceRange();
9304 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
9305 break;
9306 }
9307
9310 bool Template = readBool();
9312 if (!T)
9313 return NestedNameSpecifierLoc();
9314 SourceLocation ColonColonLoc = readSourceLocation();
9315
9316 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
9317 Builder.Extend(Context,
9318 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
9319 T->getTypeLoc(), ColonColonLoc);
9320 break;
9321 }
9322
9324 SourceLocation ColonColonLoc = readSourceLocation();
9325 Builder.MakeGlobal(Context, ColonColonLoc);
9326 break;
9327 }
9328
9330 CXXRecordDecl *RD = readDeclAs<CXXRecordDecl>();
9331 SourceRange Range = readSourceRange();
9332 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
9333 break;
9334 }
9335 }
9336 }
9337
9338 return Builder.getWithLocInContext(Context);
9339}
9340
9342 unsigned &Idx, LocSeq *Seq) {
9345 return SourceRange(beg, end);
9346}
9347
9349 const StringRef Blob) {
9350 unsigned Count = Record[0];
9351 const char *Byte = Blob.data();
9352 llvm::BitVector Ret = llvm::BitVector(Count, false);
9353 for (unsigned I = 0; I < Count; ++Byte)
9354 for (unsigned Bit = 0; Bit < 8 && I < Count; ++Bit, ++I)
9355 if (*Byte & (1 << Bit))
9356 Ret[I] = true;
9357 return Ret;
9358}
9359
9360/// Read a floating-point value
9361llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) {
9362 return llvm::APFloat(Sem, readAPInt());
9363}
9364
9365// Read a string
9366std::string ASTReader::ReadString(const RecordDataImpl &Record, unsigned &Idx) {
9367 unsigned Len = Record[Idx++];
9368 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
9369 Idx += Len;
9370 return Result;
9371}
9372
9374 unsigned &Idx) {
9375 std::string Filename = ReadString(Record, Idx);
9377 return Filename;
9378}
9379
9380std::string ASTReader::ReadPath(StringRef BaseDirectory,
9381 const RecordData &Record, unsigned &Idx) {
9382 std::string Filename = ReadString(Record, Idx);
9383 if (!BaseDirectory.empty())
9384 ResolveImportedPath(Filename, BaseDirectory);
9385 return Filename;
9386}
9387
9389 unsigned &Idx) {
9390 unsigned Major = Record[Idx++];
9391 unsigned Minor = Record[Idx++];
9392 unsigned Subminor = Record[Idx++];
9393 if (Minor == 0)
9394 return VersionTuple(Major);
9395 if (Subminor == 0)
9396 return VersionTuple(Major, Minor - 1);
9397 return VersionTuple(Major, Minor - 1, Subminor - 1);
9398}
9399
9401 const RecordData &Record,
9402 unsigned &Idx) {
9403 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
9405}
9406
9407DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
9408 return Diag(CurrentImportLoc, DiagID);
9409}
9410
9412 return Diags.Report(Loc, DiagID);
9413}
9414
9415/// Retrieve the identifier table associated with the
9416/// preprocessor.
9418 return PP.getIdentifierTable();
9419}
9420
9421/// Record that the given ID maps to the given switch-case
9422/// statement.
9424 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
9425 "Already have a SwitchCase with this ID");
9426 (*CurrSwitchCaseStmts)[ID] = SC;
9427}
9428
9429/// Retrieve the switch-case statement with the given ID.
9431 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
9432 return (*CurrSwitchCaseStmts)[ID];
9433}
9434
9436 CurrSwitchCaseStmts->clear();
9437}
9438
9440 ASTContext &Context = getContext();
9441 std::vector<RawComment *> Comments;
9442 for (SmallVectorImpl<std::pair<BitstreamCursor,
9443 serialization::ModuleFile *>>::iterator
9444 I = CommentsCursors.begin(),
9445 E = CommentsCursors.end();
9446 I != E; ++I) {
9447 Comments.clear();
9448 BitstreamCursor &Cursor = I->first;
9449 serialization::ModuleFile &F = *I->second;
9450 SavedStreamPosition SavedPosition(Cursor);
9451
9453 while (true) {
9455 Cursor.advanceSkippingSubblocks(
9456 BitstreamCursor::AF_DontPopBlockAtEnd);
9457 if (!MaybeEntry) {
9458 Error(MaybeEntry.takeError());
9459 return;
9460 }
9461 llvm::BitstreamEntry Entry = MaybeEntry.get();
9462
9463 switch (Entry.Kind) {
9464 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
9465 case llvm::BitstreamEntry::Error:
9466 Error("malformed block record in AST file");
9467 return;
9468 case llvm::BitstreamEntry::EndBlock:
9469 goto NextCursor;
9470 case llvm::BitstreamEntry::Record:
9471 // The interesting case.
9472 break;
9473 }
9474
9475 // Read a record.
9476 Record.clear();
9477 Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
9478 if (!MaybeComment) {
9479 Error(MaybeComment.takeError());
9480 return;
9481 }
9482 switch ((CommentRecordTypes)MaybeComment.get()) {
9483 case COMMENTS_RAW_COMMENT: {
9484 unsigned Idx = 0;
9485 SourceRange SR = ReadSourceRange(F, Record, Idx);
9488 bool IsTrailingComment = Record[Idx++];
9489 bool IsAlmostTrailingComment = Record[Idx++];
9490 Comments.push_back(new (Context) RawComment(
9491 SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
9492 break;
9493 }
9494 }
9495 }
9496 NextCursor:
9497 llvm::DenseMap<FileID, std::map<unsigned, RawComment *>>
9498 FileToOffsetToComment;
9499 for (RawComment *C : Comments) {
9500 SourceLocation CommentLoc = C->getBeginLoc();
9501 if (CommentLoc.isValid()) {
9502 std::pair<FileID, unsigned> Loc =
9503 SourceMgr.getDecomposedLoc(CommentLoc);
9504 if (Loc.first.isValid())
9505 Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
9506 }
9507 }
9508 }
9509}
9510
9512 serialization::ModuleFile &MF, bool IncludeSystem,
9513 llvm::function_ref<void(const serialization::InputFileInfo &IFI,
9514 bool IsSystem)>
9515 Visitor) {
9516 unsigned NumUserInputs = MF.NumUserInputFiles;
9517 unsigned NumInputs = MF.InputFilesLoaded.size();
9518 assert(NumUserInputs <= NumInputs);
9519 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9520 for (unsigned I = 0; I < N; ++I) {
9521 bool IsSystem = I >= NumUserInputs;
9522 InputFileInfo IFI = getInputFileInfo(MF, I+1);
9523 Visitor(IFI, IsSystem);
9524 }
9525}
9526
9528 bool IncludeSystem, bool Complain,
9529 llvm::function_ref<void(const serialization::InputFile &IF,
9530 bool isSystem)> Visitor) {
9531 unsigned NumUserInputs = MF.NumUserInputFiles;
9532 unsigned NumInputs = MF.InputFilesLoaded.size();
9533 assert(NumUserInputs <= NumInputs);
9534 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9535 for (unsigned I = 0; I < N; ++I) {
9536 bool IsSystem = I >= NumUserInputs;
9537 InputFile IF = getInputFile(MF, I+1, Complain);
9538 Visitor(IF, IsSystem);
9539 }
9540}
9541
9544 llvm::function_ref<void(FileEntryRef FE)> Visitor) {
9545 unsigned NumInputs = MF.InputFilesLoaded.size();
9546 for (unsigned I = 0; I < NumInputs; ++I) {
9547 InputFileInfo IFI = getInputFileInfo(MF, I + 1);
9548 if (IFI.TopLevel && IFI.ModuleMap)
9549 if (auto FE = getInputFile(MF, I + 1).getFile())
9550 Visitor(*FE);
9551 }
9552}
9553
9554void ASTReader::finishPendingActions() {
9555 while (
9556 !PendingIdentifierInfos.empty() || !PendingDeducedFunctionTypes.empty() ||
9557 !PendingDeducedVarTypes.empty() || !PendingIncompleteDeclChains.empty() ||
9558 !PendingDeclChains.empty() || !PendingMacroIDs.empty() ||
9559 !PendingDeclContextInfos.empty() || !PendingUpdateRecords.empty() ||
9560 !PendingObjCExtensionIvarRedeclarations.empty()) {
9561 // If any identifiers with corresponding top-level declarations have
9562 // been loaded, load those declarations now.
9563 using TopLevelDeclsMap =
9564 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
9565 TopLevelDeclsMap TopLevelDecls;
9566
9567 while (!PendingIdentifierInfos.empty()) {
9568 IdentifierInfo *II = PendingIdentifierInfos.back().first;
9570 std::move(PendingIdentifierInfos.back().second);
9571 PendingIdentifierInfos.pop_back();
9572
9573 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
9574 }
9575
9576 // Load each function type that we deferred loading because it was a
9577 // deduced type that might refer to a local type declared within itself.
9578 for (unsigned I = 0; I != PendingDeducedFunctionTypes.size(); ++I) {
9579 auto *FD = PendingDeducedFunctionTypes[I].first;
9580 FD->setType(GetType(PendingDeducedFunctionTypes[I].second));
9581
9582 if (auto *DT = FD->getReturnType()->getContainedDeducedType()) {
9583 // If we gave a function a deduced return type, remember that we need to
9584 // propagate that along the redeclaration chain.
9585 if (DT->isDeduced()) {
9586 PendingDeducedTypeUpdates.insert(
9587 {FD->getCanonicalDecl(), FD->getReturnType()});
9588 continue;
9589 }
9590
9591 // The function has undeduced DeduceType return type. We hope we can
9592 // find the deduced type by iterating the redecls in other modules
9593 // later.
9594 PendingUndeducedFunctionDecls.push_back(FD);
9595 continue;
9596 }
9597 }
9598 PendingDeducedFunctionTypes.clear();
9599
9600 // Load each variable type that we deferred loading because it was a
9601 // deduced type that might refer to a local type declared within itself.
9602 for (unsigned I = 0; I != PendingDeducedVarTypes.size(); ++I) {
9603 auto *VD = PendingDeducedVarTypes[I].first;
9604 VD->setType(GetType(PendingDeducedVarTypes[I].second));
9605 }
9606 PendingDeducedVarTypes.clear();
9607
9608 // For each decl chain that we wanted to complete while deserializing, mark
9609 // it as "still needs to be completed".
9610 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
9611 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
9612 }
9613 PendingIncompleteDeclChains.clear();
9614
9615 // Load pending declaration chains.
9616 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
9617 loadPendingDeclChain(PendingDeclChains[I].first,
9618 PendingDeclChains[I].second);
9619 PendingDeclChains.clear();
9620
9621 // Make the most recent of the top-level declarations visible.
9622 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
9623 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
9624 IdentifierInfo *II = TLD->first;
9625 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
9626 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
9627 }
9628 }
9629
9630 // Load any pending macro definitions.
9631 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
9632 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
9634 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
9635 // Initialize the macro history from chained-PCHs ahead of module imports.
9636 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
9637 ++IDIdx) {
9638 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
9639 if (!Info.M->isModule())
9640 resolvePendingMacro(II, Info);
9641 }
9642 // Handle module imports.
9643 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
9644 ++IDIdx) {
9645 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
9646 if (Info.M->isModule())
9647 resolvePendingMacro(II, Info);
9648 }
9649 }
9650 PendingMacroIDs.clear();
9651
9652 // Wire up the DeclContexts for Decls that we delayed setting until
9653 // recursive loading is completed.
9654 while (!PendingDeclContextInfos.empty()) {
9655 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
9656 PendingDeclContextInfos.pop_front();
9657 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
9658 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
9659 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9660 }
9661
9662 // Perform any pending declaration updates.
9663 while (!PendingUpdateRecords.empty()) {
9664 auto Update = PendingUpdateRecords.pop_back_val();
9665 ReadingKindTracker ReadingKind(Read_Decl, *this);
9666 loadDeclUpdateRecords(Update);
9667 }
9668
9669 while (!PendingObjCExtensionIvarRedeclarations.empty()) {
9670 auto ExtensionsPair = PendingObjCExtensionIvarRedeclarations.back().first;
9671 auto DuplicateIvars =
9672 PendingObjCExtensionIvarRedeclarations.back().second;
9673 llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls;
9675 ExtensionsPair.first->getASTContext(),
9676 ExtensionsPair.second->getASTContext(), NonEquivalentDecls,
9677 StructuralEquivalenceKind::Default, /*StrictTypeSpelling =*/false,
9678 /*Complain =*/false,
9679 /*ErrorOnTagTypeMismatch =*/true);
9680 if (Ctx.IsEquivalent(ExtensionsPair.first, ExtensionsPair.second)) {
9681 // Merge redeclared ivars with their predecessors.
9682 for (auto IvarPair : DuplicateIvars) {
9683 ObjCIvarDecl *Ivar = IvarPair.first, *PrevIvar = IvarPair.second;
9684 // Change semantic DeclContext but keep the lexical one.
9685 Ivar->setDeclContextsImpl(PrevIvar->getDeclContext(),
9686 Ivar->getLexicalDeclContext(),
9687 getContext());
9688 getContext().setPrimaryMergedDecl(Ivar, PrevIvar->getCanonicalDecl());
9689 }
9690 // Invalidate duplicate extension and the cached ivar list.
9691 ExtensionsPair.first->setInvalidDecl();
9692 ExtensionsPair.second->getClassInterface()
9693 ->getDefinition()
9694 ->setIvarList(nullptr);
9695 } else {
9696 for (auto IvarPair : DuplicateIvars) {
9697 Diag(IvarPair.first->getLocation(),
9698 diag::err_duplicate_ivar_declaration)
9699 << IvarPair.first->getIdentifier();
9700 Diag(IvarPair.second->getLocation(), diag::note_previous_definition);
9701 }
9702 }
9703 PendingObjCExtensionIvarRedeclarations.pop_back();
9704 }
9705 }
9706
9707 // At this point, all update records for loaded decls are in place, so any
9708 // fake class definitions should have become real.
9709 assert(PendingFakeDefinitionData.empty() &&
9710 "faked up a class definition but never saw the real one");
9711
9712 // If we deserialized any C++ or Objective-C class definitions, any
9713 // Objective-C protocol definitions, or any redeclarable templates, make sure
9714 // that all redeclarations point to the definitions. Note that this can only
9715 // happen now, after the redeclaration chains have been fully wired.
9716 for (Decl *D : PendingDefinitions) {
9717 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9718 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
9719 // Make sure that the TagType points at the definition.
9720 const_cast<TagType*>(TagT)->decl = TD;
9721 }
9722
9723 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
9724 for (auto *R = getMostRecentExistingDecl(RD); R;
9725 R = R->getPreviousDecl()) {
9726 assert((R == D) ==
9727 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
9728 "declaration thinks it's the definition but it isn't");
9729 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
9730 }
9731 }
9732
9733 continue;
9734 }
9735
9736 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
9737 // Make sure that the ObjCInterfaceType points at the definition.
9738 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9739 ->Decl = ID;
9740
9741 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9742 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9743
9744 continue;
9745 }
9746
9747 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
9748 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9749 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9750
9751 continue;
9752 }
9753
9754 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
9755 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9756 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
9757 }
9758 PendingDefinitions.clear();
9759
9760 // Load the bodies of any functions or methods we've encountered. We do
9761 // this now (delayed) so that we can be sure that the declaration chains
9762 // have been fully wired up (hasBody relies on this).
9763 // FIXME: We shouldn't require complete redeclaration chains here.
9764 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9765 PBEnd = PendingBodies.end();
9766 PB != PBEnd; ++PB) {
9767 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
9768 // For a function defined inline within a class template, force the
9769 // canonical definition to be the one inside the canonical definition of
9770 // the template. This ensures that we instantiate from a correct view
9771 // of the template.
9772 //
9773 // Sadly we can't do this more generally: we can't be sure that all
9774 // copies of an arbitrary class definition will have the same members
9775 // defined (eg, some member functions may not be instantiated, and some
9776 // special members may or may not have been implicitly defined).
9777 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent()))
9778 if (RD->isDependentContext() && !RD->isThisDeclarationADefinition())
9779 continue;
9780
9781 // FIXME: Check for =delete/=default?
9782 const FunctionDecl *Defn = nullptr;
9783 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
9784 FD->setLazyBody(PB->second);
9785 } else {
9786 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
9787 mergeDefinitionVisibility(NonConstDefn, FD);
9788
9789 if (!FD->isLateTemplateParsed() &&
9790 !NonConstDefn->isLateTemplateParsed() &&
9791 // We only perform ODR checks for decls not in the explicit
9792 // global module fragment.
9793 !shouldSkipCheckingODR(FD) &&
9794 FD->getODRHash() != NonConstDefn->getODRHash()) {
9795 if (!isa<CXXMethodDecl>(FD)) {
9796 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9797 } else if (FD->getLexicalParent()->isFileContext() &&
9798 NonConstDefn->getLexicalParent()->isFileContext()) {
9799 // Only diagnose out-of-line method definitions. If they are
9800 // in class definitions, then an error will be generated when
9801 // processing the class bodies.
9802 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9803 }
9804 }
9805 }
9806 continue;
9807 }
9808
9809 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
9810 if (!getContext().getLangOpts().Modules || !MD->hasBody())
9811 MD->setLazyBody(PB->second);
9812 }
9813 PendingBodies.clear();
9814
9815 // Inform any classes that had members added that they now have more members.
9816 for (auto [RD, MD] : PendingAddedClassMembers) {
9817 RD->addedMember(MD);
9818 }
9819 PendingAddedClassMembers.clear();
9820
9821 // Do some cleanup.
9822 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9824 PendingMergedDefinitionsToDeduplicate.clear();
9825}
9826
9827void ASTReader::diagnoseOdrViolations() {
9828 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
9829 PendingRecordOdrMergeFailures.empty() &&
9830 PendingFunctionOdrMergeFailures.empty() &&
9831 PendingEnumOdrMergeFailures.empty() &&
9832 PendingObjCInterfaceOdrMergeFailures.empty() &&
9833 PendingObjCProtocolOdrMergeFailures.empty())
9834 return;
9835
9836 // Trigger the import of the full definition of each class that had any
9837 // odr-merging problems, so we can produce better diagnostics for them.
9838 // These updates may in turn find and diagnose some ODR failures, so take
9839 // ownership of the set first.
9840 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
9841 PendingOdrMergeFailures.clear();
9842 for (auto &Merge : OdrMergeFailures) {
9843 Merge.first->buildLookup();
9844 Merge.first->decls_begin();
9845 Merge.first->bases_begin();
9846 Merge.first->vbases_begin();
9847 for (auto &RecordPair : Merge.second) {
9848 auto *RD = RecordPair.first;
9849 RD->decls_begin();
9850 RD->bases_begin();
9851 RD->vbases_begin();
9852 }
9853 }
9854
9855 // Trigger the import of the full definition of each record in C/ObjC.
9856 auto RecordOdrMergeFailures = std::move(PendingRecordOdrMergeFailures);
9857 PendingRecordOdrMergeFailures.clear();
9858 for (auto &Merge : RecordOdrMergeFailures) {
9859 Merge.first->decls_begin();
9860 for (auto &D : Merge.second)
9861 D->decls_begin();
9862 }
9863
9864 // Trigger the import of the full interface definition.
9865 auto ObjCInterfaceOdrMergeFailures =
9866 std::move(PendingObjCInterfaceOdrMergeFailures);
9867 PendingObjCInterfaceOdrMergeFailures.clear();
9868 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
9869 Merge.first->decls_begin();
9870 for (auto &InterfacePair : Merge.second)
9871 InterfacePair.first->decls_begin();
9872 }
9873
9874 // Trigger the import of functions.
9875 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
9876 PendingFunctionOdrMergeFailures.clear();
9877 for (auto &Merge : FunctionOdrMergeFailures) {
9878 Merge.first->buildLookup();
9879 Merge.first->decls_begin();
9880 Merge.first->getBody();
9881 for (auto &FD : Merge.second) {
9882 FD->buildLookup();
9883 FD->decls_begin();
9884 FD->getBody();
9885 }
9886 }
9887
9888 // Trigger the import of enums.
9889 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
9890 PendingEnumOdrMergeFailures.clear();
9891 for (auto &Merge : EnumOdrMergeFailures) {
9892 Merge.first->decls_begin();
9893 for (auto &Enum : Merge.second) {
9894 Enum->decls_begin();
9895 }
9896 }
9897
9898 // Trigger the import of the full protocol definition.
9899 auto ObjCProtocolOdrMergeFailures =
9900 std::move(PendingObjCProtocolOdrMergeFailures);
9901 PendingObjCProtocolOdrMergeFailures.clear();
9902 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
9903 Merge.first->decls_begin();
9904 for (auto &ProtocolPair : Merge.second)
9905 ProtocolPair.first->decls_begin();
9906 }
9907
9908 // For each declaration from a merged context, check that the canonical
9909 // definition of that context also contains a declaration of the same
9910 // entity.
9911 //
9912 // Caution: this loop does things that might invalidate iterators into
9913 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
9914 while (!PendingOdrMergeChecks.empty()) {
9915 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
9916
9917 // FIXME: Skip over implicit declarations for now. This matters for things
9918 // like implicitly-declared special member functions. This isn't entirely
9919 // correct; we can end up with multiple unmerged declarations of the same
9920 // implicit entity.
9921 if (D->isImplicit())
9922 continue;
9923
9924 DeclContext *CanonDef = D->getDeclContext();
9925
9926 bool Found = false;
9927 const Decl *DCanon = D->getCanonicalDecl();
9928
9929 for (auto *RI : D->redecls()) {
9930 if (RI->getLexicalDeclContext() == CanonDef) {
9931 Found = true;
9932 break;
9933 }
9934 }
9935 if (Found)
9936 continue;
9937
9938 // Quick check failed, time to do the slow thing. Note, we can't just
9939 // look up the name of D in CanonDef here, because the member that is
9940 // in CanonDef might not be found by name lookup (it might have been
9941 // replaced by a more recent declaration in the lookup table), and we
9942 // can't necessarily find it in the redeclaration chain because it might
9943 // be merely mergeable, not redeclarable.
9945 for (auto *CanonMember : CanonDef->decls()) {
9946 if (CanonMember->getCanonicalDecl() == DCanon) {
9947 // This can happen if the declaration is merely mergeable and not
9948 // actually redeclarable (we looked for redeclarations earlier).
9949 //
9950 // FIXME: We should be able to detect this more efficiently, without
9951 // pulling in all of the members of CanonDef.
9952 Found = true;
9953 break;
9954 }
9955 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
9956 if (ND->getDeclName() == D->getDeclName())
9957 Candidates.push_back(ND);
9958 }
9959
9960 if (!Found) {
9961 // The AST doesn't like TagDecls becoming invalid after they've been
9962 // completed. We only really need to mark FieldDecls as invalid here.
9963 if (!isa<TagDecl>(D))
9964 D->setInvalidDecl();
9965
9966 // Ensure we don't accidentally recursively enter deserialization while
9967 // we're producing our diagnostic.
9968 Deserializing RecursionGuard(this);
9969
9970 std::string CanonDefModule =
9972 cast<Decl>(CanonDef));
9973 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9975 << CanonDef << CanonDefModule.empty() << CanonDefModule;
9976
9977 if (Candidates.empty())
9978 Diag(cast<Decl>(CanonDef)->getLocation(),
9979 diag::note_module_odr_violation_no_possible_decls) << D;
9980 else {
9981 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
9982 Diag(Candidates[I]->getLocation(),
9983 diag::note_module_odr_violation_possible_decl)
9984 << Candidates[I];
9985 }
9986
9987 DiagnosedOdrMergeFailures.insert(CanonDef);
9988 }
9989 }
9990
9991 if (OdrMergeFailures.empty() && RecordOdrMergeFailures.empty() &&
9992 FunctionOdrMergeFailures.empty() && EnumOdrMergeFailures.empty() &&
9993 ObjCInterfaceOdrMergeFailures.empty() &&
9994 ObjCProtocolOdrMergeFailures.empty())
9995 return;
9996
9997 ODRDiagsEmitter DiagsEmitter(Diags, getContext(),
9998 getPreprocessor().getLangOpts());
9999
10000 // Issue any pending ODR-failure diagnostics.
10001 for (auto &Merge : OdrMergeFailures) {
10002 // If we've already pointed out a specific problem with this class, don't
10003 // bother issuing a general "something's different" diagnostic.
10004 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10005 continue;
10006
10007 bool Diagnosed = false;
10008 CXXRecordDecl *FirstRecord = Merge.first;
10009 for (auto &RecordPair : Merge.second) {
10010 if (DiagsEmitter.diagnoseMismatch(FirstRecord, RecordPair.first,
10011 RecordPair.second)) {
10012 Diagnosed = true;
10013 break;
10014 }
10015 }
10016
10017 if (!Diagnosed) {
10018 // All definitions are updates to the same declaration. This happens if a
10019 // module instantiates the declaration of a class template specialization
10020 // and two or more other modules instantiate its definition.
10021 //
10022 // FIXME: Indicate which modules had instantiations of this definition.
10023 // FIXME: How can this even happen?
10024 Diag(Merge.first->getLocation(),
10025 diag::err_module_odr_violation_different_instantiations)
10026 << Merge.first;
10027 }
10028 }
10029
10030 // Issue any pending ODR-failure diagnostics for RecordDecl in C/ObjC. Note
10031 // that in C++ this is done as a part of CXXRecordDecl ODR checking.
10032 for (auto &Merge : RecordOdrMergeFailures) {
10033 // If we've already pointed out a specific problem with this class, don't
10034 // bother issuing a general "something's different" diagnostic.
10035 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10036 continue;
10037
10038 RecordDecl *FirstRecord = Merge.first;
10039 bool Diagnosed = false;
10040 for (auto *SecondRecord : Merge.second) {
10041 if (DiagsEmitter.diagnoseMismatch(FirstRecord, SecondRecord)) {
10042 Diagnosed = true;
10043 break;
10044 }
10045 }
10046 (void)Diagnosed;
10047 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10048 }
10049
10050 // Issue ODR failures diagnostics for functions.
10051 for (auto &Merge : FunctionOdrMergeFailures) {
10052 FunctionDecl *FirstFunction = Merge.first;
10053 bool Diagnosed = false;
10054 for (auto &SecondFunction : Merge.second) {
10055 if (DiagsEmitter.diagnoseMismatch(FirstFunction, SecondFunction)) {
10056 Diagnosed = true;
10057 break;
10058 }
10059 }
10060 (void)Diagnosed;
10061 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10062 }
10063
10064 // Issue ODR failures diagnostics for enums.
10065 for (auto &Merge : EnumOdrMergeFailures) {
10066 // If we've already pointed out a specific problem with this enum, don't
10067 // bother issuing a general "something's different" diagnostic.
10068 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10069 continue;
10070
10071 EnumDecl *FirstEnum = Merge.first;
10072 bool Diagnosed = false;
10073 for (auto &SecondEnum : Merge.second) {
10074 if (DiagsEmitter.diagnoseMismatch(FirstEnum, SecondEnum)) {
10075 Diagnosed = true;
10076 break;
10077 }
10078 }
10079 (void)Diagnosed;
10080 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10081 }
10082
10083 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
10084 // If we've already pointed out a specific problem with this interface,
10085 // don't bother issuing a general "something's different" diagnostic.
10086 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10087 continue;
10088
10089 bool Diagnosed = false;
10090 ObjCInterfaceDecl *FirstID = Merge.first;
10091 for (auto &InterfacePair : Merge.second) {
10092 if (DiagsEmitter.diagnoseMismatch(FirstID, InterfacePair.first,
10093 InterfacePair.second)) {
10094 Diagnosed = true;
10095 break;
10096 }
10097 }
10098 (void)Diagnosed;
10099 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10100 }
10101
10102 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
10103 // If we've already pointed out a specific problem with this protocol,
10104 // don't bother issuing a general "something's different" diagnostic.
10105 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10106 continue;
10107
10108 ObjCProtocolDecl *FirstProtocol = Merge.first;
10109 bool Diagnosed = false;
10110 for (auto &ProtocolPair : Merge.second) {
10111 if (DiagsEmitter.diagnoseMismatch(FirstProtocol, ProtocolPair.first,
10112 ProtocolPair.second)) {
10113 Diagnosed = true;
10114 break;
10115 }
10116 }
10117 (void)Diagnosed;
10118 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10119 }
10120}
10121
10123 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
10124 ReadTimer->startTimer();
10125}
10126
10128 assert(NumCurrentElementsDeserializing &&
10129 "FinishedDeserializing not paired with StartedDeserializing");
10130 if (NumCurrentElementsDeserializing == 1) {
10131 // We decrease NumCurrentElementsDeserializing only after pending actions
10132 // are finished, to avoid recursively re-calling finishPendingActions().
10133 finishPendingActions();
10134 }
10135 --NumCurrentElementsDeserializing;
10136
10137 if (NumCurrentElementsDeserializing == 0) {
10138 // Propagate exception specification and deduced type updates along
10139 // redeclaration chains.
10140 //
10141 // We do this now rather than in finishPendingActions because we want to
10142 // be able to walk the complete redeclaration chains of the updated decls.
10143 while (!PendingExceptionSpecUpdates.empty() ||
10144 !PendingDeducedTypeUpdates.empty()) {
10145 auto ESUpdates = std::move(PendingExceptionSpecUpdates);
10146 PendingExceptionSpecUpdates.clear();
10147 for (auto Update : ESUpdates) {
10148 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
10149 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
10150 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
10151 if (auto *Listener = getContext().getASTMutationListener())
10152 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
10153 for (auto *Redecl : Update.second->redecls())
10154 getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
10155 }
10156
10157 auto DTUpdates = std::move(PendingDeducedTypeUpdates);
10158 PendingDeducedTypeUpdates.clear();
10159 for (auto Update : DTUpdates) {
10160 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
10161 // FIXME: If the return type is already deduced, check that it matches.
10163 Update.second);
10164 }
10165
10166 auto UDTUpdates = std::move(PendingUndeducedFunctionDecls);
10167 PendingUndeducedFunctionDecls.clear();
10168 // We hope we can find the deduced type for the functions by iterating
10169 // redeclarations in other modules.
10170 for (FunctionDecl *UndeducedFD : UDTUpdates)
10171 (void)UndeducedFD->getMostRecentDecl();
10172 }
10173
10174 if (ReadTimer)
10175 ReadTimer->stopTimer();
10176
10177 diagnoseOdrViolations();
10178
10179 // We are not in recursive loading, so it's safe to pass the "interesting"
10180 // decls to the consumer.
10181 if (Consumer)
10182 PassInterestingDeclsToConsumer();
10183 }
10184}
10185
10186void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
10187 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
10188 // Remove any fake results before adding any real ones.
10189 auto It = PendingFakeLookupResults.find(II);
10190 if (It != PendingFakeLookupResults.end()) {
10191 for (auto *ND : It->second)
10192 SemaObj->IdResolver.RemoveDecl(ND);
10193 // FIXME: this works around module+PCH performance issue.
10194 // Rather than erase the result from the map, which is O(n), just clear
10195 // the vector of NamedDecls.
10196 It->second.clear();
10197 }
10198 }
10199
10200 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
10201 SemaObj->TUScope->AddDecl(D);
10202 } else if (SemaObj->TUScope) {
10203 // Adding the decl to IdResolver may have failed because it was already in
10204 // (even though it was not added in scope). If it is already in, make sure
10205 // it gets in the scope as well.
10206 if (llvm::is_contained(SemaObj->IdResolver.decls(Name), D))
10207 SemaObj->TUScope->AddDecl(D);
10208 }
10209}
10210
10212 ASTContext *Context,
10213 const PCHContainerReader &PCHContainerRdr,
10214 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
10215 StringRef isysroot,
10216 DisableValidationForModuleKind DisableValidationKind,
10217 bool AllowASTWithCompilerErrors,
10218 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
10219 bool ValidateASTInputFilesContent, bool UseGlobalIndex,
10220 std::unique_ptr<llvm::Timer> ReadTimer)
10221 : Listener(bool(DisableValidationKind &DisableValidationForModuleKind::PCH)
10223 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
10224 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
10225 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
10226 ContextObj(Context), ModuleMgr(PP.getFileManager(), ModuleCache,
10227 PCHContainerRdr, PP.getHeaderSearchInfo()),
10228 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
10229 DisableValidationKind(DisableValidationKind),
10230 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
10231 AllowConfigurationMismatch(AllowConfigurationMismatch),
10232 ValidateSystemInputs(ValidateSystemInputs),
10233 ValidateASTInputFilesContent(ValidateASTInputFilesContent),
10234 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
10235 SourceMgr.setExternalSLocEntrySource(this);
10236
10237 for (const auto &Ext : Extensions) {
10238 auto BlockName = Ext->getExtensionMetadata().BlockName;
10239 auto Known = ModuleFileExtensions.find(BlockName);
10240 if (Known != ModuleFileExtensions.end()) {
10241 Diags.Report(diag::warn_duplicate_module_file_extension)
10242 << BlockName;
10243 continue;
10244 }
10245
10246 ModuleFileExtensions.insert({BlockName, Ext});
10247 }
10248}
10249
10251 if (OwnsDeserializationListener)
10252 delete DeserializationListener;
10253}
10254
10256 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
10257}
10258
10260 unsigned AbbrevID) {
10261 Idx = 0;
10262 Record.clear();
10263 return Cursor.readRecord(AbbrevID, Record);
10264}
10265//===----------------------------------------------------------------------===//
10266//// OMPClauseReader implementation
10267////===----------------------------------------------------------------------===//
10268
10269// This has to be in namespace clang because it's friended by all
10270// of the OMP clauses.
10271namespace clang {
10272
10273class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> {
10275 ASTContext &Context;
10276
10277public:
10279 : Record(Record), Context(Record.getContext()) {}
10280#define GEN_CLANG_CLAUSE_CLASS
10281#define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *C);
10282#include "llvm/Frontend/OpenMP/OMP.inc"
10286};
10287
10288} // end namespace clang
10289
10291 return OMPClauseReader(*this).readClause();
10292}
10293
10295 OMPClause *C = nullptr;
10296 switch (llvm::omp::Clause(Record.readInt())) {
10297 case llvm::omp::OMPC_if:
10298 C = new (Context) OMPIfClause();
10299 break;
10300 case llvm::omp::OMPC_final:
10301 C = new (Context) OMPFinalClause();
10302 break;
10303 case llvm::omp::OMPC_num_threads:
10304 C = new (Context) OMPNumThreadsClause();
10305 break;
10306 case llvm::omp::OMPC_safelen:
10307 C = new (Context) OMPSafelenClause();
10308 break;
10309 case llvm::omp::OMPC_simdlen:
10310 C = new (Context) OMPSimdlenClause();
10311 break;
10312 case llvm::omp::OMPC_sizes: {
10313 unsigned NumSizes = Record.readInt();
10314 C = OMPSizesClause::CreateEmpty(Context, NumSizes);
10315 break;
10316 }
10317 case llvm::omp::OMPC_full:
10318 C = OMPFullClause::CreateEmpty(Context);
10319 break;
10320 case llvm::omp::OMPC_partial:
10322 break;
10323 case llvm::omp::OMPC_allocator:
10324 C = new (Context) OMPAllocatorClause();
10325 break;
10326 case llvm::omp::OMPC_collapse:
10327 C = new (Context) OMPCollapseClause();
10328 break;
10329 case llvm::omp::OMPC_default:
10330 C = new (Context) OMPDefaultClause();
10331 break;
10332 case llvm::omp::OMPC_proc_bind:
10333 C = new (Context) OMPProcBindClause();
10334 break;
10335 case llvm::omp::OMPC_schedule:
10336 C = new (Context) OMPScheduleClause();
10337 break;
10338 case llvm::omp::OMPC_ordered:
10339 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
10340 break;
10341 case llvm::omp::OMPC_nowait:
10342 C = new (Context) OMPNowaitClause();
10343 break;
10344 case llvm::omp::OMPC_untied:
10345 C = new (Context) OMPUntiedClause();
10346 break;
10347 case llvm::omp::OMPC_mergeable:
10348 C = new (Context) OMPMergeableClause();
10349 break;
10350 case llvm::omp::OMPC_read:
10351 C = new (Context) OMPReadClause();
10352 break;
10353 case llvm::omp::OMPC_write:
10354 C = new (Context) OMPWriteClause();
10355 break;
10356 case llvm::omp::OMPC_update:
10357 C = OMPUpdateClause::CreateEmpty(Context, Record.readInt());
10358 break;
10359 case llvm::omp::OMPC_capture:
10360 C = new (Context) OMPCaptureClause();
10361 break;
10362 case llvm::omp::OMPC_compare:
10363 C = new (Context) OMPCompareClause();
10364 break;
10365 case llvm::omp::OMPC_fail:
10366 C = new (Context) OMPFailClause();
10367 break;
10368 case llvm::omp::OMPC_seq_cst:
10369 C = new (Context) OMPSeqCstClause();
10370 break;
10371 case llvm::omp::OMPC_acq_rel:
10372 C = new (Context) OMPAcqRelClause();
10373 break;
10374 case llvm::omp::OMPC_acquire:
10375 C = new (Context) OMPAcquireClause();
10376 break;
10377 case llvm::omp::OMPC_release:
10378 C = new (Context) OMPReleaseClause();
10379 break;
10380 case llvm::omp::OMPC_relaxed:
10381 C = new (Context) OMPRelaxedClause();
10382 break;
10383 case llvm::omp::OMPC_weak:
10384 C = new (Context) OMPWeakClause();
10385 break;
10386 case llvm::omp::OMPC_threads:
10387 C = new (Context) OMPThreadsClause();
10388 break;
10389 case llvm::omp::OMPC_simd:
10390 C = new (Context) OMPSIMDClause();
10391 break;
10392 case llvm::omp::OMPC_nogroup:
10393 C = new (Context) OMPNogroupClause();
10394 break;
10395 case llvm::omp::OMPC_unified_address:
10396 C = new (Context) OMPUnifiedAddressClause();
10397 break;
10398 case llvm::omp::OMPC_unified_shared_memory:
10399 C = new (Context) OMPUnifiedSharedMemoryClause();
10400 break;
10401 case llvm::omp::OMPC_reverse_offload:
10402 C = new (Context) OMPReverseOffloadClause();
10403 break;
10404 case llvm::omp::OMPC_dynamic_allocators:
10405 C = new (Context) OMPDynamicAllocatorsClause();
10406 break;
10407 case llvm::omp::OMPC_atomic_default_mem_order:
10408 C = new (Context) OMPAtomicDefaultMemOrderClause();
10409 break;
10410 case llvm::omp::OMPC_at:
10411 C = new (Context) OMPAtClause();
10412 break;
10413 case llvm::omp::OMPC_severity:
10414 C = new (Context) OMPSeverityClause();
10415 break;
10416 case llvm::omp::OMPC_message:
10417 C = new (Context) OMPMessageClause();
10418 break;
10419 case llvm::omp::OMPC_private:
10420 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
10421 break;
10422 case llvm::omp::OMPC_firstprivate:
10423 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
10424 break;
10425 case llvm::omp::OMPC_lastprivate:
10426 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
10427 break;
10428 case llvm::omp::OMPC_shared:
10429 C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
10430 break;
10431 case llvm::omp::OMPC_reduction: {
10432 unsigned N = Record.readInt();
10433 auto Modifier = Record.readEnum<OpenMPReductionClauseModifier>();
10434 C = OMPReductionClause::CreateEmpty(Context, N, Modifier);
10435 break;
10436 }
10437 case llvm::omp::OMPC_task_reduction:
10438 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
10439 break;
10440 case llvm::omp::OMPC_in_reduction:
10441 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
10442 break;
10443 case llvm::omp::OMPC_linear:
10444 C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
10445 break;
10446 case llvm::omp::OMPC_aligned:
10447 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
10448 break;
10449 case llvm::omp::OMPC_copyin:
10450 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
10451 break;
10452 case llvm::omp::OMPC_copyprivate:
10453 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
10454 break;
10455 case llvm::omp::OMPC_flush:
10456 C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
10457 break;
10458 case llvm::omp::OMPC_depobj:
10460 break;
10461 case llvm::omp::OMPC_depend: {
10462 unsigned NumVars = Record.readInt();
10463 unsigned NumLoops = Record.readInt();
10464 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
10465 break;
10466 }
10467 case llvm::omp::OMPC_device:
10468 C = new (Context) OMPDeviceClause();
10469 break;
10470 case llvm::omp::OMPC_map: {
10472 Sizes.NumVars = Record.readInt();
10473 Sizes.NumUniqueDeclarations = Record.readInt();
10474 Sizes.NumComponentLists = Record.readInt();
10475 Sizes.NumComponents = Record.readInt();
10476 C = OMPMapClause::CreateEmpty(Context, Sizes);
10477 break;
10478 }
10479 case llvm::omp::OMPC_num_teams:
10480 C = new (Context) OMPNumTeamsClause();
10481 break;
10482 case llvm::omp::OMPC_thread_limit:
10483 C = new (Context) OMPThreadLimitClause();
10484 break;
10485 case llvm::omp::OMPC_priority:
10486 C = new (Context) OMPPriorityClause();
10487 break;
10488 case llvm::omp::OMPC_grainsize:
10489 C = new (Context) OMPGrainsizeClause();
10490 break;
10491 case llvm::omp::OMPC_num_tasks:
10492 C = new (Context) OMPNumTasksClause();
10493 break;
10494 case llvm::omp::OMPC_hint:
10495 C = new (Context) OMPHintClause();
10496 break;
10497 case llvm::omp::OMPC_dist_schedule:
10498 C = new (Context) OMPDistScheduleClause();
10499 break;
10500 case llvm::omp::OMPC_defaultmap:
10501 C = new (Context) OMPDefaultmapClause();
10502 break;
10503 case llvm::omp::OMPC_to: {
10505 Sizes.NumVars = Record.readInt();
10506 Sizes.NumUniqueDeclarations = Record.readInt();
10507 Sizes.NumComponentLists = Record.readInt();
10508 Sizes.NumComponents = Record.readInt();
10509 C = OMPToClause::CreateEmpty(Context, Sizes);
10510 break;
10511 }
10512 case llvm::omp::OMPC_from: {
10514 Sizes.NumVars = Record.readInt();
10515 Sizes.NumUniqueDeclarations = Record.readInt();
10516 Sizes.NumComponentLists = Record.readInt();
10517 Sizes.NumComponents = Record.readInt();
10518 C = OMPFromClause::CreateEmpty(Context, Sizes);
10519 break;
10520 }
10521 case llvm::omp::OMPC_use_device_ptr: {
10523 Sizes.NumVars = Record.readInt();
10524 Sizes.NumUniqueDeclarations = Record.readInt();
10525 Sizes.NumComponentLists = Record.readInt();
10526 Sizes.NumComponents = Record.readInt();
10527 C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
10528 break;
10529 }
10530 case llvm::omp::OMPC_use_device_addr: {
10532 Sizes.NumVars = Record.readInt();
10533 Sizes.NumUniqueDeclarations = Record.readInt();
10534 Sizes.NumComponentLists = Record.readInt();
10535 Sizes.NumComponents = Record.readInt();
10536 C = OMPUseDeviceAddrClause::CreateEmpty(Context, Sizes);
10537 break;
10538 }
10539 case llvm::omp::OMPC_is_device_ptr: {
10541 Sizes.NumVars = Record.readInt();
10542 Sizes.NumUniqueDeclarations = Record.readInt();
10543 Sizes.NumComponentLists = Record.readInt();
10544 Sizes.NumComponents = Record.readInt();
10545 C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
10546 break;
10547 }
10548 case llvm::omp::OMPC_has_device_addr: {
10550 Sizes.NumVars = Record.readInt();
10551 Sizes.NumUniqueDeclarations = Record.readInt();
10552 Sizes.NumComponentLists = Record.readInt();
10553 Sizes.NumComponents = Record.readInt();
10554 C = OMPHasDeviceAddrClause::CreateEmpty(Context, Sizes);
10555 break;
10556 }
10557 case llvm::omp::OMPC_allocate:
10558 C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
10559 break;
10560 case llvm::omp::OMPC_nontemporal:
10561 C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt());
10562 break;
10563 case llvm::omp::OMPC_inclusive:
10564 C = OMPInclusiveClause::CreateEmpty(Context, Record.readInt());
10565 break;
10566 case llvm::omp::OMPC_exclusive:
10567 C = OMPExclusiveClause::CreateEmpty(Context, Record.readInt());
10568 break;
10569 case llvm::omp::OMPC_order:
10570 C = new (Context) OMPOrderClause();
10571 break;
10572 case llvm::omp::OMPC_init:
10573 C = OMPInitClause::CreateEmpty(Context, Record.readInt());
10574 break;
10575 case llvm::omp::OMPC_use:
10576 C = new (Context) OMPUseClause();
10577 break;
10578 case llvm::omp::OMPC_destroy:
10579 C = new (Context) OMPDestroyClause();
10580 break;
10581 case llvm::omp::OMPC_novariants:
10582 C = new (Context) OMPNovariantsClause();
10583 break;
10584 case llvm::omp::OMPC_nocontext:
10585 C = new (Context) OMPNocontextClause();
10586 break;
10587 case llvm::omp::OMPC_detach:
10588 C = new (Context) OMPDetachClause();
10589 break;
10590 case llvm::omp::OMPC_uses_allocators:
10591 C = OMPUsesAllocatorsClause::CreateEmpty(Context, Record.readInt());
10592 break;
10593 case llvm::omp::OMPC_affinity:
10594 C = OMPAffinityClause::CreateEmpty(Context, Record.readInt());
10595 break;
10596 case llvm::omp::OMPC_filter:
10597 C = new (Context) OMPFilterClause();
10598 break;
10599 case llvm::omp::OMPC_bind:
10600 C = OMPBindClause::CreateEmpty(Context);
10601 break;
10602 case llvm::omp::OMPC_align:
10603 C = new (Context) OMPAlignClause();
10604 break;
10605 case llvm::omp::OMPC_ompx_dyn_cgroup_mem:
10606 C = new (Context) OMPXDynCGroupMemClause();
10607 break;
10608 case llvm::omp::OMPC_doacross: {
10609 unsigned NumVars = Record.readInt();
10610 unsigned NumLoops = Record.readInt();
10611 C = OMPDoacrossClause::CreateEmpty(Context, NumVars, NumLoops);
10612 break;
10613 }
10614 case llvm::omp::OMPC_ompx_attribute:
10615 C = new (Context) OMPXAttributeClause();
10616 break;
10617 case llvm::omp::OMPC_ompx_bare:
10618 C = new (Context) OMPXBareClause();
10619 break;
10620#define OMP_CLAUSE_NO_CLASS(Enum, Str) \
10621 case llvm::omp::Enum: \
10622 break;
10623#include "llvm/Frontend/OpenMP/OMPKinds.def"
10624 default:
10625 break;
10626 }
10627 assert(C && "Unknown OMPClause type");
10628
10629 Visit(C);
10630 C->setLocStart(Record.readSourceLocation());
10631 C->setLocEnd(Record.readSourceLocation());
10632
10633 return C;
10634}
10635
10637 C->setPreInitStmt(Record.readSubStmt(),
10638 static_cast<OpenMPDirectiveKind>(Record.readInt()));
10639}
10640
10643 C->setPostUpdateExpr(Record.readSubExpr());
10644}
10645
10646void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
10648 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
10649 C->setNameModifierLoc(Record.readSourceLocation());
10650 C->setColonLoc(Record.readSourceLocation());
10651 C->setCondition(Record.readSubExpr());
10652 C->setLParenLoc(Record.readSourceLocation());
10653}
10654
10655void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
10657 C->setCondition(Record.readSubExpr());
10658 C->setLParenLoc(Record.readSourceLocation());
10659}
10660
10661void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
10663 C->setNumThreads(Record.readSubExpr());
10664 C->setLParenLoc(Record.readSourceLocation());
10665}
10666
10667void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
10668 C->setSafelen(Record.readSubExpr());
10669 C->setLParenLoc(Record.readSourceLocation());
10670}
10671
10672void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
10673 C->setSimdlen(Record.readSubExpr());
10674 C->setLParenLoc(Record.readSourceLocation());
10675}
10676
10677void OMPClauseReader::VisitOMPSizesClause(OMPSizesClause *C) {
10678 for (Expr *&E : C->getSizesRefs())
10679 E = Record.readSubExpr();
10680 C->setLParenLoc(Record.readSourceLocation());
10681}
10682
10683void OMPClauseReader::VisitOMPFullClause(OMPFullClause *C) {}
10684
10685void OMPClauseReader::VisitOMPPartialClause(OMPPartialClause *C) {
10686 C->setFactor(Record.readSubExpr());
10687 C->setLParenLoc(Record.readSourceLocation());
10688}
10689
10690void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
10691 C->setAllocator(Record.readExpr());
10692 C->setLParenLoc(Record.readSourceLocation());
10693}
10694
10695void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
10696 C->setNumForLoops(Record.readSubExpr());
10697 C->setLParenLoc(Record.readSourceLocation());
10698}
10699
10700void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
10701 C->setDefaultKind(static_cast<llvm::omp::DefaultKind>(Record.readInt()));
10702 C->setLParenLoc(Record.readSourceLocation());
10703 C->setDefaultKindKwLoc(Record.readSourceLocation());
10704}
10705
10706void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
10707 C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt()));
10708 C->setLParenLoc(Record.readSourceLocation());
10709 C->setProcBindKindKwLoc(Record.readSourceLocation());
10710}
10711
10712void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
10714 C->setScheduleKind(
10715 static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
10716 C->setFirstScheduleModifier(
10717 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
10718 C->setSecondScheduleModifier(
10719 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
10720 C->setChunkSize(Record.readSubExpr());
10721 C->setLParenLoc(Record.readSourceLocation());
10722 C->setFirstScheduleModifierLoc(Record.readSourceLocation());
10723 C->setSecondScheduleModifierLoc(Record.readSourceLocation());
10724 C->setScheduleKindLoc(Record.readSourceLocation());
10725 C->setCommaLoc(Record.readSourceLocation());
10726}
10727
10728void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
10729 C->setNumForLoops(Record.readSubExpr());
10730 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
10731 C->setLoopNumIterations(I, Record.readSubExpr());
10732 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
10733 C->setLoopCounter(I, Record.readSubExpr());
10734 C->setLParenLoc(Record.readSourceLocation());
10735}
10736
10737void OMPClauseReader::VisitOMPDetachClause(OMPDetachClause *C) {
10738 C->setEventHandler(Record.readSubExpr());
10739 C->setLParenLoc(Record.readSourceLocation());
10740}
10741
10742void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {}
10743
10744void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
10745
10746void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
10747
10748void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
10749
10750void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
10751
10752void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *C) {
10753 if (C->isExtended()) {
10754 C->setLParenLoc(Record.readSourceLocation());
10755 C->setArgumentLoc(Record.readSourceLocation());
10756 C->setDependencyKind(Record.readEnum<OpenMPDependClauseKind>());
10757 }
10758}
10759
10760void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
10761
10762void OMPClauseReader::VisitOMPCompareClause(OMPCompareClause *) {}
10763
10764// Read the parameter of fail clause. This will have been saved when
10765// OMPClauseWriter is called.
10766void OMPClauseReader::VisitOMPFailClause(OMPFailClause *C) {
10767 C->setLParenLoc(Record.readSourceLocation());
10768 SourceLocation FailParameterLoc = Record.readSourceLocation();
10769 C->setFailParameterLoc(FailParameterLoc);
10770 OpenMPClauseKind CKind = Record.readEnum<OpenMPClauseKind>();
10771 C->setFailParameter(CKind);
10772}
10773
10774void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
10775
10776void OMPClauseReader::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
10777
10778void OMPClauseReader::VisitOMPAcquireClause(OMPAcquireClause *) {}
10779
10780void OMPClauseReader::VisitOMPReleaseClause(OMPReleaseClause *) {}
10781
10782void OMPClauseReader::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
10783
10784void OMPClauseReader::VisitOMPWeakClause(OMPWeakClause *) {}
10785
10786void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
10787
10788void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
10789
10790void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
10791
10792void OMPClauseReader::VisitOMPInitClause(OMPInitClause *C) {
10793 unsigned NumVars = C->varlist_size();
10795 Vars.reserve(NumVars);
10796 for (unsigned I = 0; I != NumVars; ++I)
10797 Vars.push_back(Record.readSubExpr());
10798 C->setVarRefs(Vars);
10799 C->setIsTarget(Record.readBool());
10800 C->setIsTargetSync(Record.readBool());
10801 C->setLParenLoc(Record.readSourceLocation());
10802 C->setVarLoc(Record.readSourceLocation());
10803}
10804
10805void OMPClauseReader::VisitOMPUseClause(OMPUseClause *C) {
10806 C->setInteropVar(Record.readSubExpr());
10807 C->setLParenLoc(Record.readSourceLocation());
10808 C->setVarLoc(Record.readSourceLocation());
10809}
10810
10811void OMPClauseReader::VisitOMPDestroyClause(OMPDestroyClause *C) {
10812 C->setInteropVar(Record.readSubExpr());
10813 C->setLParenLoc(Record.readSourceLocation());
10814 C->setVarLoc(Record.readSourceLocation());
10815}
10816
10817void OMPClauseReader::VisitOMPNovariantsClause(OMPNovariantsClause *C) {
10819 C->setCondition(Record.readSubExpr());
10820 C->setLParenLoc(Record.readSourceLocation());
10821}
10822
10823void OMPClauseReader::VisitOMPNocontextClause(OMPNocontextClause *C) {
10825 C->setCondition(Record.readSubExpr());
10826 C->setLParenLoc(Record.readSourceLocation());
10827}
10828
10829void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
10830
10831void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
10833
10834void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
10835
10836void
10837OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
10838}
10839
10840void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
10842 C->setAtomicDefaultMemOrderKind(
10843 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
10844 C->setLParenLoc(Record.readSourceLocation());
10845 C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
10846}
10847
10848void OMPClauseReader::VisitOMPAtClause(OMPAtClause *C) {
10849 C->setAtKind(static_cast<OpenMPAtClauseKind>(Record.readInt()));
10850 C->setLParenLoc(Record.readSourceLocation());
10851 C->setAtKindKwLoc(Record.readSourceLocation());
10852}
10853
10854void OMPClauseReader::VisitOMPSeverityClause(OMPSeverityClause *C) {
10855 C->setSeverityKind(static_cast<OpenMPSeverityClauseKind>(Record.readInt()));
10856 C->setLParenLoc(Record.readSourceLocation());
10857 C->setSeverityKindKwLoc(Record.readSourceLocation());
10858}
10859
10860void OMPClauseReader::VisitOMPMessageClause(OMPMessageClause *C) {
10861 C->setMessageString(Record.readSubExpr());
10862 C->setLParenLoc(Record.readSourceLocation());
10863}
10864
10865void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
10866 C->setLParenLoc(Record.readSourceLocation());
10867 unsigned NumVars = C->varlist_size();
10869 Vars.reserve(NumVars);
10870 for (unsigned i = 0; i != NumVars; ++i)
10871 Vars.push_back(Record.readSubExpr());
10872 C->setVarRefs(Vars);
10873 Vars.clear();
10874 for (unsigned i = 0; i != NumVars; ++i)
10875 Vars.push_back(Record.readSubExpr());
10876 C->setPrivateCopies(Vars);
10877}
10878
10879void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
10881 C->setLParenLoc(Record.readSourceLocation());
10882 unsigned NumVars = C->varlist_size();
10884 Vars.reserve(NumVars);
10885 for (unsigned i = 0; i != NumVars; ++i)
10886 Vars.push_back(Record.readSubExpr());
10887 C->setVarRefs(Vars);
10888 Vars.clear();
10889 for (unsigned i = 0; i != NumVars; ++i)
10890 Vars.push_back(Record.readSubExpr());
10891 C->setPrivateCopies(Vars);
10892 Vars.clear();
10893 for (unsigned i = 0; i != NumVars; ++i)
10894 Vars.push_back(Record.readSubExpr());
10895 C->setInits(Vars);
10896}
10897
10898void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
10900 C->setLParenLoc(Record.readSourceLocation());
10901 C->setKind(Record.readEnum<OpenMPLastprivateModifier>());
10902 C->setKindLoc(Record.readSourceLocation());
10903 C->setColonLoc(Record.readSourceLocation());
10904 unsigned NumVars = C->varlist_size();
10906 Vars.reserve(NumVars);
10907 for (unsigned i = 0; i != NumVars; ++i)
10908 Vars.push_back(Record.readSubExpr());
10909 C->setVarRefs(Vars);
10910 Vars.clear();
10911 for (unsigned i = 0; i != NumVars; ++i)
10912 Vars.push_back(Record.readSubExpr());
10913 C->setPrivateCopies(Vars);
10914 Vars.clear();
10915 for (unsigned i = 0; i != NumVars; ++i)
10916 Vars.push_back(Record.readSubExpr());
10917 C->setSourceExprs(Vars);
10918 Vars.clear();
10919 for (unsigned i = 0; i != NumVars; ++i)
10920 Vars.push_back(Record.readSubExpr());
10921 C->setDestinationExprs(Vars);
10922 Vars.clear();
10923 for (unsigned i = 0; i != NumVars; ++i)
10924 Vars.push_back(Record.readSubExpr());
10925 C->setAssignmentOps(Vars);
10926}
10927
10928void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
10929 C->setLParenLoc(Record.readSourceLocation());
10930 unsigned NumVars = C->varlist_size();
10932 Vars.reserve(NumVars);
10933 for (unsigned i = 0; i != NumVars; ++i)
10934 Vars.push_back(Record.readSubExpr());
10935 C->setVarRefs(Vars);
10936}
10937
10938void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
10940 C->setLParenLoc(Record.readSourceLocation());
10941 C->setModifierLoc(Record.readSourceLocation());
10942 C->setColonLoc(Record.readSourceLocation());
10943 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
10944 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
10945 C->setQualifierLoc(NNSL);
10946 C->setNameInfo(DNI);
10947
10948 unsigned NumVars = C->varlist_size();
10950 Vars.reserve(NumVars);
10951 for (unsigned i = 0; i != NumVars; ++i)
10952 Vars.push_back(Record.readSubExpr());
10953 C->setVarRefs(Vars);
10954 Vars.clear();
10955 for (unsigned i = 0; i != NumVars; ++i)
10956 Vars.push_back(Record.readSubExpr());
10957 C->setPrivates(Vars);
10958 Vars.clear();
10959 for (unsigned i = 0; i != NumVars; ++i)
10960 Vars.push_back(Record.readSubExpr());
10961 C->setLHSExprs(Vars);
10962 Vars.clear();
10963 for (unsigned i = 0; i != NumVars; ++i)
10964 Vars.push_back(Record.readSubExpr());
10965 C->setRHSExprs(Vars);
10966 Vars.clear();
10967 for (unsigned i = 0; i != NumVars; ++i)
10968 Vars.push_back(Record.readSubExpr());
10969 C->setReductionOps(Vars);
10970 if (C->getModifier() == OMPC_REDUCTION_inscan) {
10971 Vars.clear();
10972 for (unsigned i = 0; i != NumVars; ++i)
10973 Vars.push_back(Record.readSubExpr());
10974 C->setInscanCopyOps(Vars);
10975 Vars.clear();
10976 for (unsigned i = 0; i != NumVars; ++i)
10977 Vars.push_back(Record.readSubExpr());
10978 C->setInscanCopyArrayTemps(Vars);
10979 Vars.clear();
10980 for (unsigned i = 0; i != NumVars; ++i)
10981 Vars.push_back(Record.readSubExpr());
10982 C->setInscanCopyArrayElems(Vars);
10983 }
10984}
10985
10986void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
10988 C->setLParenLoc(Record.readSourceLocation());
10989 C->setColonLoc(Record.readSourceLocation());
10990 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
10991 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
10992 C->setQualifierLoc(NNSL);
10993 C->setNameInfo(DNI);
10994
10995 unsigned NumVars = C->varlist_size();
10997 Vars.reserve(NumVars);
10998 for (unsigned I = 0; I != NumVars; ++I)
10999 Vars.push_back(Record.readSubExpr());
11000 C->setVarRefs(Vars);
11001 Vars.clear();
11002 for (unsigned I = 0; I != NumVars; ++I)
11003 Vars.push_back(Record.readSubExpr());
11004 C->setPrivates(Vars);
11005 Vars.clear();
11006 for (unsigned I = 0; I != NumVars; ++I)
11007 Vars.push_back(Record.readSubExpr());
11008 C->setLHSExprs(Vars);
11009 Vars.clear();
11010 for (unsigned I = 0; I != NumVars; ++I)
11011 Vars.push_back(Record.readSubExpr());
11012 C->setRHSExprs(Vars);
11013 Vars.clear();
11014 for (unsigned I = 0; I != NumVars; ++I)
11015 Vars.push_back(Record.readSubExpr());
11016 C->setReductionOps(Vars);
11017}
11018
11019void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
11021 C->setLParenLoc(Record.readSourceLocation());
11022 C->setColonLoc(Record.readSourceLocation());
11023 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
11024 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
11025 C->setQualifierLoc(NNSL);
11026 C->setNameInfo(DNI);
11027
11028 unsigned NumVars = C->varlist_size();
11030 Vars.reserve(NumVars);
11031 for (unsigned I = 0; I != NumVars; ++I)
11032 Vars.push_back(Record.readSubExpr());
11033 C->setVarRefs(Vars);
11034 Vars.clear();
11035 for (unsigned I = 0; I != NumVars; ++I)
11036 Vars.push_back(Record.readSubExpr());
11037 C->setPrivates(Vars);
11038 Vars.clear();
11039 for (unsigned I = 0; I != NumVars; ++I)
11040 Vars.push_back(Record.readSubExpr());
11041 C->setLHSExprs(Vars);
11042 Vars.clear();
11043 for (unsigned I = 0; I != NumVars; ++I)
11044 Vars.push_back(Record.readSubExpr());
11045 C->setRHSExprs(Vars);
11046 Vars.clear();
11047 for (unsigned I = 0; I != NumVars; ++I)
11048 Vars.push_back(Record.readSubExpr());
11049 C->setReductionOps(Vars);
11050 Vars.clear();
11051 for (unsigned I = 0; I != NumVars; ++I)
11052 Vars.push_back(Record.readSubExpr());
11053 C->setTaskgroupDescriptors(Vars);
11054}
11055
11056void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
11058 C->setLParenLoc(Record.readSourceLocation());
11059 C->setColonLoc(Record.readSourceLocation());
11060 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
11061 C->setModifierLoc(Record.readSourceLocation());
11062 unsigned NumVars = C->varlist_size();
11064 Vars.reserve(NumVars);
11065 for (unsigned i = 0; i != NumVars; ++i)
11066 Vars.push_back(Record.readSubExpr());
11067 C->setVarRefs(Vars);
11068 Vars.clear();
11069 for (unsigned i = 0; i != NumVars; ++i)
11070 Vars.push_back(Record.readSubExpr());
11071 C->setPrivates(Vars);
11072 Vars.clear();
11073 for (unsigned i = 0; i != NumVars; ++i)
11074 Vars.push_back(Record.readSubExpr());
11075 C->setInits(Vars);
11076 Vars.clear();
11077 for (unsigned i = 0; i != NumVars; ++i)
11078 Vars.push_back(Record.readSubExpr());
11079 C->setUpdates(Vars);
11080 Vars.clear();
11081 for (unsigned i = 0; i != NumVars; ++i)
11082 Vars.push_back(Record.readSubExpr());
11083 C->setFinals(Vars);
11084 C->setStep(Record.readSubExpr());
11085 C->setCalcStep(Record.readSubExpr());
11086 Vars.clear();
11087 for (unsigned I = 0; I != NumVars + 1; ++I)
11088 Vars.push_back(Record.readSubExpr());
11089 C->setUsedExprs(Vars);
11090}
11091
11092void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
11093 C->setLParenLoc(Record.readSourceLocation());
11094 C->setColonLoc(Record.readSourceLocation());
11095 unsigned NumVars = C->varlist_size();
11097 Vars.reserve(NumVars);
11098 for (unsigned i = 0; i != NumVars; ++i)
11099 Vars.push_back(Record.readSubExpr());
11100 C->setVarRefs(Vars);
11101 C->setAlignment(Record.readSubExpr());
11102}
11103
11104void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
11105 C->setLParenLoc(Record.readSourceLocation());
11106 unsigned NumVars = C->varlist_size();
11108 Exprs.reserve(NumVars);
11109 for (unsigned i = 0; i != NumVars; ++i)
11110 Exprs.push_back(Record.readSubExpr());
11111 C->setVarRefs(Exprs);
11112 Exprs.clear();
11113 for (unsigned i = 0; i != NumVars; ++i)
11114 Exprs.push_back(Record.readSubExpr());
11115 C->setSourceExprs(Exprs);
11116 Exprs.clear();
11117 for (unsigned i = 0; i != NumVars; ++i)
11118 Exprs.push_back(Record.readSubExpr());
11119 C->setDestinationExprs(Exprs);
11120 Exprs.clear();
11121 for (unsigned i = 0; i != NumVars; ++i)
11122 Exprs.push_back(Record.readSubExpr());
11123 C->setAssignmentOps(Exprs);
11124}
11125
11126void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
11127 C->setLParenLoc(Record.readSourceLocation());
11128 unsigned NumVars = C->varlist_size();
11130 Exprs.reserve(NumVars);
11131 for (unsigned i = 0; i != NumVars; ++i)
11132 Exprs.push_back(Record.readSubExpr());
11133 C->setVarRefs(Exprs);
11134 Exprs.clear();
11135 for (unsigned i = 0; i != NumVars; ++i)
11136 Exprs.push_back(Record.readSubExpr());
11137 C->setSourceExprs(Exprs);
11138 Exprs.clear();
11139 for (unsigned i = 0; i != NumVars; ++i)
11140 Exprs.push_back(Record.readSubExpr());
11141 C->setDestinationExprs(Exprs);
11142 Exprs.clear();
11143 for (unsigned i = 0; i != NumVars; ++i)
11144 Exprs.push_back(Record.readSubExpr());
11145 C->setAssignmentOps(Exprs);
11146}
11147
11148void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
11149 C->setLParenLoc(Record.readSourceLocation());
11150 unsigned NumVars = C->varlist_size();
11152 Vars.reserve(NumVars);
11153 for (unsigned i = 0; i != NumVars; ++i)
11154 Vars.push_back(Record.readSubExpr());
11155 C->setVarRefs(Vars);
11156}
11157
11158void OMPClauseReader::VisitOMPDepobjClause(OMPDepobjClause *C) {
11159 C->setDepobj(Record.readSubExpr());
11160 C->setLParenLoc(Record.readSourceLocation());
11161}
11162
11163void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
11164 C->setLParenLoc(Record.readSourceLocation());
11165 C->setModifier(Record.readSubExpr());
11166 C->setDependencyKind(
11167 static_cast<OpenMPDependClauseKind>(Record.readInt()));
11168 C->setDependencyLoc(Record.readSourceLocation());
11169 C->setColonLoc(Record.readSourceLocation());
11170 C->setOmpAllMemoryLoc(Record.readSourceLocation());
11171 unsigned NumVars = C->varlist_size();
11173 Vars.reserve(NumVars);
11174 for (unsigned I = 0; I != NumVars; ++I)
11175 Vars.push_back(Record.readSubExpr());
11176 C->setVarRefs(Vars);
11177 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
11178 C->setLoopData(I, Record.readSubExpr());
11179}
11180
11181void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
11183 C->setModifier(Record.readEnum<OpenMPDeviceClauseModifier>());
11184 C->setDevice(Record.readSubExpr());
11185 C->setModifierLoc(Record.readSourceLocation());
11186 C->setLParenLoc(Record.readSourceLocation());
11187}
11188
11189void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
11190 C->setLParenLoc(Record.readSourceLocation());
11191 bool HasIteratorModifier = false;
11192 for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
11193 C->setMapTypeModifier(
11194 I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
11195 C->setMapTypeModifierLoc(I, Record.readSourceLocation());
11196 if (C->getMapTypeModifier(I) == OMPC_MAP_MODIFIER_iterator)
11197 HasIteratorModifier = true;
11198 }
11199 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
11200 C->setMapperIdInfo(Record.readDeclarationNameInfo());
11201 C->setMapType(
11202 static_cast<OpenMPMapClauseKind>(Record.readInt()));
11203 C->setMapLoc(Record.readSourceLocation());
11204 C->setColonLoc(Record.readSourceLocation());
11205 auto NumVars = C->varlist_size();
11206 auto UniqueDecls = C->getUniqueDeclarationsNum();
11207 auto TotalLists = C->getTotalComponentListNum();
11208 auto TotalComponents = C->getTotalComponentsNum();
11209
11211 Vars.reserve(NumVars);
11212 for (unsigned i = 0; i != NumVars; ++i)
11213 Vars.push_back(Record.readExpr());
11214 C->setVarRefs(Vars);
11215
11216 SmallVector<Expr *, 16> UDMappers;
11217 UDMappers.reserve(NumVars);
11218 for (unsigned I = 0; I < NumVars; ++I)
11219 UDMappers.push_back(Record.readExpr());
11220 C->setUDMapperRefs(UDMappers);
11221
11222 if (HasIteratorModifier)
11223 C->setIteratorModifier(Record.readExpr());
11224
11226 Decls.reserve(UniqueDecls);
11227 for (unsigned i = 0; i < UniqueDecls; ++i)
11228 Decls.push_back(Record.readDeclAs<ValueDecl>());
11229 C->setUniqueDecls(Decls);
11230
11231 SmallVector<unsigned, 16> ListsPerDecl;
11232 ListsPerDecl.reserve(UniqueDecls);
11233 for (unsigned i = 0; i < UniqueDecls; ++i)
11234 ListsPerDecl.push_back(Record.readInt());
11235 C->setDeclNumLists(ListsPerDecl);
11236
11237 SmallVector<unsigned, 32> ListSizes;
11238 ListSizes.reserve(TotalLists);
11239 for (unsigned i = 0; i < TotalLists; ++i)
11240 ListSizes.push_back(Record.readInt());
11241 C->setComponentListSizes(ListSizes);
11242
11244 Components.reserve(TotalComponents);
11245 for (unsigned i = 0; i < TotalComponents; ++i) {
11246 Expr *AssociatedExprPr = Record.readExpr();
11247 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11248 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
11249 /*IsNonContiguous=*/false);
11250 }
11251 C->setComponents(Components, ListSizes);
11252}
11253
11254void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
11255 C->setLParenLoc(Record.readSourceLocation());
11256 C->setColonLoc(Record.readSourceLocation());
11257 C->setAllocator(Record.readSubExpr());
11258 unsigned NumVars = C->varlist_size();
11260 Vars.reserve(NumVars);
11261 for (unsigned i = 0; i != NumVars; ++i)
11262 Vars.push_back(Record.readSubExpr());
11263 C->setVarRefs(Vars);
11264}
11265
11266void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
11268 C->setNumTeams(Record.readSubExpr());
11269 C->setLParenLoc(Record.readSourceLocation());
11270}
11271
11272void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
11274 C->setThreadLimit(Record.readSubExpr());
11275 C->setLParenLoc(Record.readSourceLocation());
11276}
11277
11278void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
11280 C->setPriority(Record.readSubExpr());
11281 C->setLParenLoc(Record.readSourceLocation());
11282}
11283
11284void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
11286 C->setModifier(Record.readEnum<OpenMPGrainsizeClauseModifier>());
11287 C->setGrainsize(Record.readSubExpr());
11288 C->setModifierLoc(Record.readSourceLocation());
11289 C->setLParenLoc(Record.readSourceLocation());
11290}
11291
11292void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
11294 C->setModifier(Record.readEnum<OpenMPNumTasksClauseModifier>());
11295 C->setNumTasks(Record.readSubExpr());
11296 C->setModifierLoc(Record.readSourceLocation());
11297 C->setLParenLoc(Record.readSourceLocation());
11298}
11299
11300void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
11301 C->setHint(Record.readSubExpr());
11302 C->setLParenLoc(Record.readSourceLocation());
11303}
11304
11305void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
11307 C->setDistScheduleKind(
11308 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
11309 C->setChunkSize(Record.readSubExpr());
11310 C->setLParenLoc(Record.readSourceLocation());
11311 C->setDistScheduleKindLoc(Record.readSourceLocation());
11312 C->setCommaLoc(Record.readSourceLocation());
11313}
11314
11315void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
11316 C->setDefaultmapKind(
11317 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
11318 C->setDefaultmapModifier(
11319 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
11320 C->setLParenLoc(Record.readSourceLocation());
11321 C->setDefaultmapModifierLoc(Record.readSourceLocation());
11322 C->setDefaultmapKindLoc(Record.readSourceLocation());
11323}
11324
11325void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
11326 C->setLParenLoc(Record.readSourceLocation());
11327 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
11328 C->setMotionModifier(
11329 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
11330 C->setMotionModifierLoc(I, Record.readSourceLocation());
11331 }
11332 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
11333 C->setMapperIdInfo(Record.readDeclarationNameInfo());
11334 C->setColonLoc(Record.readSourceLocation());
11335 auto NumVars = C->varlist_size();
11336 auto UniqueDecls = C->getUniqueDeclarationsNum();
11337 auto TotalLists = C->getTotalComponentListNum();
11338 auto TotalComponents = C->getTotalComponentsNum();
11339
11341 Vars.reserve(NumVars);
11342 for (unsigned i = 0; i != NumVars; ++i)
11343 Vars.push_back(Record.readSubExpr());
11344 C->setVarRefs(Vars);
11345
11346 SmallVector<Expr *, 16> UDMappers;
11347 UDMappers.reserve(NumVars);
11348 for (unsigned I = 0; I < NumVars; ++I)
11349 UDMappers.push_back(Record.readSubExpr());
11350 C->setUDMapperRefs(UDMappers);
11351
11353 Decls.reserve(UniqueDecls);
11354 for (unsigned i = 0; i < UniqueDecls; ++i)
11355 Decls.push_back(Record.readDeclAs<ValueDecl>());
11356 C->setUniqueDecls(Decls);
11357
11358 SmallVector<unsigned, 16> ListsPerDecl;
11359 ListsPerDecl.reserve(UniqueDecls);
11360 for (unsigned i = 0; i < UniqueDecls; ++i)
11361 ListsPerDecl.push_back(Record.readInt());
11362 C->setDeclNumLists(ListsPerDecl);
11363
11364 SmallVector<unsigned, 32> ListSizes;
11365 ListSizes.reserve(TotalLists);
11366 for (unsigned i = 0; i < TotalLists; ++i)
11367 ListSizes.push_back(Record.readInt());
11368 C->setComponentListSizes(ListSizes);
11369
11371 Components.reserve(TotalComponents);
11372 for (unsigned i = 0; i < TotalComponents; ++i) {
11373 Expr *AssociatedExprPr = Record.readSubExpr();
11374 bool IsNonContiguous = Record.readBool();
11375 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11376 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
11377 }
11378 C->setComponents(Components, ListSizes);
11379}
11380
11381void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
11382 C->setLParenLoc(Record.readSourceLocation());
11383 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
11384 C->setMotionModifier(
11385 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
11386 C->setMotionModifierLoc(I, Record.readSourceLocation());
11387 }
11388 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
11389 C->setMapperIdInfo(Record.readDeclarationNameInfo());
11390 C->setColonLoc(Record.readSourceLocation());
11391 auto NumVars = C->varlist_size();
11392 auto UniqueDecls = C->getUniqueDeclarationsNum();
11393 auto TotalLists = C->getTotalComponentListNum();
11394 auto TotalComponents = C->getTotalComponentsNum();
11395
11397 Vars.reserve(NumVars);
11398 for (unsigned i = 0; i != NumVars; ++i)
11399 Vars.push_back(Record.readSubExpr());
11400 C->setVarRefs(Vars);
11401
11402 SmallVector<Expr *, 16> UDMappers;
11403 UDMappers.reserve(NumVars);
11404 for (unsigned I = 0; I < NumVars; ++I)
11405 UDMappers.push_back(Record.readSubExpr());
11406 C->setUDMapperRefs(UDMappers);
11407
11409 Decls.reserve(UniqueDecls);
11410 for (unsigned i = 0; i < UniqueDecls; ++i)
11411 Decls.push_back(Record.readDeclAs<ValueDecl>());
11412 C->setUniqueDecls(Decls);
11413
11414 SmallVector<unsigned, 16> ListsPerDecl;
11415 ListsPerDecl.reserve(UniqueDecls);
11416 for (unsigned i = 0; i < UniqueDecls; ++i)
11417 ListsPerDecl.push_back(Record.readInt());
11418 C->setDeclNumLists(ListsPerDecl);
11419
11420 SmallVector<unsigned, 32> ListSizes;
11421 ListSizes.reserve(TotalLists);
11422 for (unsigned i = 0; i < TotalLists; ++i)
11423 ListSizes.push_back(Record.readInt());
11424 C->setComponentListSizes(ListSizes);
11425
11427 Components.reserve(TotalComponents);
11428 for (unsigned i = 0; i < TotalComponents; ++i) {
11429 Expr *AssociatedExprPr = Record.readSubExpr();
11430 bool IsNonContiguous = Record.readBool();
11431 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11432 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
11433 }
11434 C->setComponents(Components, ListSizes);
11435}
11436
11437void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
11438 C->setLParenLoc(Record.readSourceLocation());
11439 auto NumVars = C->varlist_size();
11440 auto UniqueDecls = C->getUniqueDeclarationsNum();
11441 auto TotalLists = C->getTotalComponentListNum();
11442 auto TotalComponents = C->getTotalComponentsNum();
11443
11445 Vars.reserve(NumVars);
11446 for (unsigned i = 0; i != NumVars; ++i)
11447 Vars.push_back(Record.readSubExpr());
11448 C->setVarRefs(Vars);
11449 Vars.clear();
11450 for (unsigned i = 0; i != NumVars; ++i)
11451 Vars.push_back(Record.readSubExpr());
11452 C->setPrivateCopies(Vars);
11453 Vars.clear();
11454 for (unsigned i = 0; i != NumVars; ++i)
11455 Vars.push_back(Record.readSubExpr());
11456 C->setInits(Vars);
11457
11459 Decls.reserve(UniqueDecls);
11460 for (unsigned i = 0; i < UniqueDecls; ++i)
11461 Decls.push_back(Record.readDeclAs<ValueDecl>());
11462 C->setUniqueDecls(Decls);
11463
11464 SmallVector<unsigned, 16> ListsPerDecl;
11465 ListsPerDecl.reserve(UniqueDecls);
11466 for (unsigned i = 0; i < UniqueDecls; ++i)
11467 ListsPerDecl.push_back(Record.readInt());
11468 C->setDeclNumLists(ListsPerDecl);
11469
11470 SmallVector<unsigned, 32> ListSizes;
11471 ListSizes.reserve(TotalLists);
11472 for (unsigned i = 0; i < TotalLists; ++i)
11473 ListSizes.push_back(Record.readInt());
11474 C->setComponentListSizes(ListSizes);
11475
11477 Components.reserve(TotalComponents);
11478 for (unsigned i = 0; i < TotalComponents; ++i) {
11479 auto *AssociatedExprPr = Record.readSubExpr();
11480 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11481 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
11482 /*IsNonContiguous=*/false);
11483 }
11484 C->setComponents(Components, ListSizes);
11485}
11486
11487void OMPClauseReader::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
11488 C->setLParenLoc(Record.readSourceLocation());
11489 auto NumVars = C->varlist_size();
11490 auto UniqueDecls = C->getUniqueDeclarationsNum();
11491 auto TotalLists = C->getTotalComponentListNum();
11492 auto TotalComponents = C->getTotalComponentsNum();
11493
11495 Vars.reserve(NumVars);
11496 for (unsigned i = 0; i != NumVars; ++i)
11497 Vars.push_back(Record.readSubExpr());
11498 C->setVarRefs(Vars);
11499
11501 Decls.reserve(UniqueDecls);
11502 for (unsigned i = 0; i < UniqueDecls; ++i)
11503 Decls.push_back(Record.readDeclAs<ValueDecl>());
11504 C->setUniqueDecls(Decls);
11505
11506 SmallVector<unsigned, 16> ListsPerDecl;
11507 ListsPerDecl.reserve(UniqueDecls);
11508 for (unsigned i = 0; i < UniqueDecls; ++i)
11509 ListsPerDecl.push_back(Record.readInt());
11510 C->setDeclNumLists(ListsPerDecl);
11511
11512 SmallVector<unsigned, 32> ListSizes;
11513 ListSizes.reserve(TotalLists);
11514 for (unsigned i = 0; i < TotalLists; ++i)
11515 ListSizes.push_back(Record.readInt());
11516 C->setComponentListSizes(ListSizes);
11517
11519 Components.reserve(TotalComponents);
11520 for (unsigned i = 0; i < TotalComponents; ++i) {
11521 Expr *AssociatedExpr = Record.readSubExpr();
11522 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11523 Components.emplace_back(AssociatedExpr, AssociatedDecl,
11524 /*IsNonContiguous*/ false);
11525 }
11526 C->setComponents(Components, ListSizes);
11527}
11528
11529void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
11530 C->setLParenLoc(Record.readSourceLocation());
11531 auto NumVars = C->varlist_size();
11532 auto UniqueDecls = C->getUniqueDeclarationsNum();
11533 auto TotalLists = C->getTotalComponentListNum();
11534 auto TotalComponents = C->getTotalComponentsNum();
11535
11537 Vars.reserve(NumVars);
11538 for (unsigned i = 0; i != NumVars; ++i)
11539 Vars.push_back(Record.readSubExpr());
11540 C->setVarRefs(Vars);
11541 Vars.clear();
11542
11544 Decls.reserve(UniqueDecls);
11545 for (unsigned i = 0; i < UniqueDecls; ++i)
11546 Decls.push_back(Record.readDeclAs<ValueDecl>());
11547 C->setUniqueDecls(Decls);
11548
11549 SmallVector<unsigned, 16> ListsPerDecl;
11550 ListsPerDecl.reserve(UniqueDecls);
11551 for (unsigned i = 0; i < UniqueDecls; ++i)
11552 ListsPerDecl.push_back(Record.readInt());
11553 C->setDeclNumLists(ListsPerDecl);
11554
11555 SmallVector<unsigned, 32> ListSizes;
11556 ListSizes.reserve(TotalLists);
11557 for (unsigned i = 0; i < TotalLists; ++i)
11558 ListSizes.push_back(Record.readInt());
11559 C->setComponentListSizes(ListSizes);
11560
11562 Components.reserve(TotalComponents);
11563 for (unsigned i = 0; i < TotalComponents; ++i) {
11564 Expr *AssociatedExpr = Record.readSubExpr();
11565 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11566 Components.emplace_back(AssociatedExpr, AssociatedDecl,
11567 /*IsNonContiguous=*/false);
11568 }
11569 C->setComponents(Components, ListSizes);
11570}
11571
11572void OMPClauseReader::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) {
11573 C->setLParenLoc(Record.readSourceLocation());
11574 auto NumVars = C->varlist_size();
11575 auto UniqueDecls = C->getUniqueDeclarationsNum();
11576 auto TotalLists = C->getTotalComponentListNum();
11577 auto TotalComponents = C->getTotalComponentsNum();
11578
11580 Vars.reserve(NumVars);
11581 for (unsigned I = 0; I != NumVars; ++I)
11582 Vars.push_back(Record.readSubExpr());
11583 C->setVarRefs(Vars);
11584 Vars.clear();
11585
11587 Decls.reserve(UniqueDecls);
11588 for (unsigned I = 0; I < UniqueDecls; ++I)
11589 Decls.push_back(Record.readDeclAs<ValueDecl>());
11590 C->setUniqueDecls(Decls);
11591
11592 SmallVector<unsigned, 16> ListsPerDecl;
11593 ListsPerDecl.reserve(UniqueDecls);
11594 for (unsigned I = 0; I < UniqueDecls; ++I)
11595 ListsPerDecl.push_back(Record.readInt());
11596 C->setDeclNumLists(ListsPerDecl);
11597
11598 SmallVector<unsigned, 32> ListSizes;
11599 ListSizes.reserve(TotalLists);
11600 for (unsigned i = 0; i < TotalLists; ++i)
11601 ListSizes.push_back(Record.readInt());
11602 C->setComponentListSizes(ListSizes);
11603
11605 Components.reserve(TotalComponents);
11606 for (unsigned I = 0; I < TotalComponents; ++I) {
11607 Expr *AssociatedExpr = Record.readSubExpr();
11608 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11609 Components.emplace_back(AssociatedExpr, AssociatedDecl,
11610 /*IsNonContiguous=*/false);
11611 }
11612 C->setComponents(Components, ListSizes);
11613}
11614
11615void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
11616 C->setLParenLoc(Record.readSourceLocation());
11617 unsigned NumVars = C->varlist_size();
11619 Vars.reserve(NumVars);
11620 for (unsigned i = 0; i != NumVars; ++i)
11621 Vars.push_back(Record.readSubExpr());
11622 C->setVarRefs(Vars);
11623 Vars.clear();
11624 Vars.reserve(NumVars);
11625 for (unsigned i = 0; i != NumVars; ++i)
11626 Vars.push_back(Record.readSubExpr());
11627 C->setPrivateRefs(Vars);
11628}
11629
11630void OMPClauseReader::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
11631 C->setLParenLoc(Record.readSourceLocation());
11632 unsigned NumVars = C->varlist_size();
11634 Vars.reserve(NumVars);
11635 for (unsigned i = 0; i != NumVars; ++i)
11636 Vars.push_back(Record.readSubExpr());
11637 C->setVarRefs(Vars);
11638}
11639
11640void OMPClauseReader::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
11641 C->setLParenLoc(Record.readSourceLocation());
11642 unsigned NumVars = C->varlist_size();
11644 Vars.reserve(NumVars);
11645 for (unsigned i = 0; i != NumVars; ++i)
11646 Vars.push_back(Record.readSubExpr());
11647 C->setVarRefs(Vars);
11648}
11649
11650void OMPClauseReader::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
11651 C->setLParenLoc(Record.readSourceLocation());
11652 unsigned NumOfAllocators = C->getNumberOfAllocators();
11654 Data.reserve(NumOfAllocators);
11655 for (unsigned I = 0; I != NumOfAllocators; ++I) {
11656 OMPUsesAllocatorsClause::Data &D = Data.emplace_back();
11657 D.Allocator = Record.readSubExpr();
11658 D.AllocatorTraits = Record.readSubExpr();
11659 D.LParenLoc = Record.readSourceLocation();
11660 D.RParenLoc = Record.readSourceLocation();
11661 }
11662 C->setAllocatorsData(Data);
11663}
11664
11665void OMPClauseReader::VisitOMPAffinityClause(OMPAffinityClause *C) {
11666 C->setLParenLoc(Record.readSourceLocation());
11667 C->setModifier(Record.readSubExpr());
11668 C->setColonLoc(Record.readSourceLocation());
11669 unsigned NumOfLocators = C->varlist_size();
11670 SmallVector<Expr *, 4> Locators;
11671 Locators.reserve(NumOfLocators);
11672 for (unsigned I = 0; I != NumOfLocators; ++I)
11673 Locators.push_back(Record.readSubExpr());
11674 C->setVarRefs(Locators);
11675}
11676
11677void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) {
11678 C->setKind(Record.readEnum<OpenMPOrderClauseKind>());
11679 C->setModifier(Record.readEnum<OpenMPOrderClauseModifier>());
11680 C->setLParenLoc(Record.readSourceLocation());
11681 C->setKindKwLoc(Record.readSourceLocation());
11682 C->setModifierKwLoc(Record.readSourceLocation());
11683}
11684
11685void OMPClauseReader::VisitOMPFilterClause(OMPFilterClause *C) {
11687 C->setThreadID(Record.readSubExpr());
11688 C->setLParenLoc(Record.readSourceLocation());
11689}
11690
11691void OMPClauseReader::VisitOMPBindClause(OMPBindClause *C) {
11692 C->setBindKind(Record.readEnum<OpenMPBindClauseKind>());
11693 C->setLParenLoc(Record.readSourceLocation());
11694 C->setBindKindLoc(Record.readSourceLocation());
11695}
11696
11697void OMPClauseReader::VisitOMPAlignClause(OMPAlignClause *C) {
11698 C->setAlignment(Record.readExpr());
11699 C->setLParenLoc(Record.readSourceLocation());
11700}
11701
11702void OMPClauseReader::VisitOMPXDynCGroupMemClause(OMPXDynCGroupMemClause *C) {
11704 C->setSize(Record.readSubExpr());
11705 C->setLParenLoc(Record.readSourceLocation());
11706}
11707
11708void OMPClauseReader::VisitOMPDoacrossClause(OMPDoacrossClause *C) {
11709 C->setLParenLoc(Record.readSourceLocation());
11710 C->setDependenceType(
11711 static_cast<OpenMPDoacrossClauseModifier>(Record.readInt()));
11712 C->setDependenceLoc(Record.readSourceLocation());
11713 C->setColonLoc(Record.readSourceLocation());
11714 unsigned NumVars = C->varlist_size();
11716 Vars.reserve(NumVars);
11717 for (unsigned I = 0; I != NumVars; ++I)
11718 Vars.push_back(Record.readSubExpr());
11719 C->setVarRefs(Vars);
11720 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
11721 C->setLoopData(I, Record.readSubExpr());
11722}
11723
11724void OMPClauseReader::VisitOMPXAttributeClause(OMPXAttributeClause *C) {
11725 AttrVec Attrs;
11726 Record.readAttributes(Attrs);
11727 C->setAttrs(Attrs);
11728 C->setLocStart(Record.readSourceLocation());
11729 C->setLParenLoc(Record.readSourceLocation());
11730 C->setLocEnd(Record.readSourceLocation());
11731}
11732
11733void OMPClauseReader::VisitOMPXBareClause(OMPXBareClause *C) {}
11734
11737 TI.Sets.resize(readUInt32());
11738 for (auto &Set : TI.Sets) {
11739 Set.Kind = readEnum<llvm::omp::TraitSet>();
11740 Set.Selectors.resize(readUInt32());
11741 for (auto &Selector : Set.Selectors) {
11742 Selector.Kind = readEnum<llvm::omp::TraitSelector>();
11743 Selector.ScoreOrCondition = nullptr;
11744 if (readBool())
11745 Selector.ScoreOrCondition = readExprRef();
11746 Selector.Properties.resize(readUInt32());
11747 for (auto &Property : Selector.Properties)
11748 Property.Kind = readEnum<llvm::omp::TraitProperty>();
11749 }
11750 }
11751 return &TI;
11752}
11753
11755 if (!Data)
11756 return;
11757 if (Reader->ReadingKind == ASTReader::Read_Stmt) {
11758 // Skip NumClauses, NumChildren and HasAssociatedStmt fields.
11759 skipInts(3);
11760 }
11761 SmallVector<OMPClause *, 4> Clauses(Data->getNumClauses());
11762 for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)
11763 Clauses[I] = readOMPClause();
11764 Data->setClauses(Clauses);
11765 if (Data->hasAssociatedStmt())
11766 Data->setAssociatedStmt(readStmt());
11767 for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
11768 Data->getChildren()[I] = readStmt();
11769}
11770
11772 OpenACCClauseKind ClauseKind = readEnum<OpenACCClauseKind>();
11775
11776 switch (ClauseKind) {
11778 SourceLocation LParenLoc = readSourceLocation();
11779 OpenACCDefaultClauseKind DCK = readEnum<OpenACCDefaultClauseKind>();
11780 return OpenACCDefaultClause::Create(getContext(), DCK, BeginLoc, LParenLoc,
11781 EndLoc);
11782 }
11783 case OpenACCClauseKind::If: {
11784 SourceLocation LParenLoc = readSourceLocation();
11785 Expr *CondExpr = readSubExpr();
11786 return OpenACCIfClause::Create(getContext(), BeginLoc, LParenLoc, CondExpr,
11787 EndLoc);
11788 }
11790 SourceLocation LParenLoc = readSourceLocation();
11791 Expr *CondExpr = readBool() ? readSubExpr() : nullptr;
11792 return OpenACCSelfClause::Create(getContext(), BeginLoc, LParenLoc,
11793 CondExpr, EndLoc);
11794 }
11796 SourceLocation LParenLoc = readSourceLocation();
11797 unsigned NumClauses = readInt();
11799 for (unsigned I = 0; I < NumClauses; ++I)
11800 IntExprs.push_back(readSubExpr());
11801 return OpenACCNumGangsClause::Create(getContext(), BeginLoc, LParenLoc,
11802 IntExprs, EndLoc);
11803 }
11805 SourceLocation LParenLoc = readSourceLocation();
11806 Expr *IntExpr = readSubExpr();
11807 return OpenACCNumWorkersClause::Create(getContext(), BeginLoc, LParenLoc,
11808 IntExpr, EndLoc);
11809 }
11811 SourceLocation LParenLoc = readSourceLocation();
11812 Expr *IntExpr = readSubExpr();
11813 return OpenACCVectorLengthClause::Create(getContext(), BeginLoc, LParenLoc,
11814 IntExpr, EndLoc);
11815 }
11853 llvm_unreachable("Clause serialization not yet implemented");
11854 }
11855 llvm_unreachable("Invalid Clause Kind");
11856}
11857
11860 for (unsigned I = 0; I < Clauses.size(); ++I)
11861 Clauses[I] = readOpenACCClause();
11862}
Defines the clang::ASTContext interface.
NodeId Parent
Definition: ASTDiff.cpp:191
int Id
Definition: ASTDiff.cpp:190
ASTImporterLookupTable & LT
StringRef P
static unsigned moduleKindForDiagnostic(ModuleKind Kind)
Definition: ASTReader.cpp:4701
static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD, ASTConsumer *Consumer)
Under non-PCH compilation the consumer receives the objc methods before receiving the implementation,...
Definition: ASTReader.cpp:8039
static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream)
Whether Stream doesn't start with the AST/PCH file magic number 'CPCH'.
Definition: ASTReader.cpp:4683
static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags)
Definition: ASTReader.cpp:505
static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags, DiagnosticsEngine &Diags, bool IsSystem, bool SystemHeaderWarningsInModule, bool Complain)
Definition: ASTReader.cpp:512
static void updateModuleTimestamp(ModuleFile &MF)
Definition: ASTReader.cpp:4382
static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, StringRef ExistingModuleCachePath, DiagnosticsEngine *Diags, const LangOptions &LangOpts, const PreprocessorOptions &PPOpts)
Check the header search options deserialized from the control block against the header search options...
Definition: ASTReader.cpp:836
static void collectMacroDefinitions(const PreprocessorOptions &PPOpts, MacroDefinitionsMap &Macros, SmallVectorImpl< StringRef > *MacroNames=nullptr)
Collect the macro definitions provided by the given preprocessor options.
Definition: ASTReader.cpp:611
static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts, const PreprocessorOptions &ExistingPPOpts, bool ReadMacros, DiagnosticsEngine *Diags, FileManager &FileMgr, std::string &SuggestedPredefines, const LangOptions &LangOpts, OptionValidation Validation=OptionValidateContradictions)
Check the preprocessor options deserialized from the control block against the preprocessor options i...
Definition: ASTReader.cpp:662
static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags, DiagnosticsEngine &Diags, bool Complain)
Definition: ASTReader.cpp:475
static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method)
Move the given method to the back of the global list of methods.
Definition: ASTReader.cpp:4246
static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps)
Definition: ASTReader.cpp:2693
static bool isInterestingIdentifier(ASTReader &Reader, const IdentifierInfo &II, bool IsModule)
Whether the given identifier is "interesting".
Definition: ASTReader.cpp:989
static bool parseModuleFileExtensionMetadata(const SmallVectorImpl< uint64_t > &Record, StringRef Blob, ModuleFileExtensionMetadata &Metadata)
Parse a record and blob containing module file extension metadata.
Definition: ASTReader.cpp:5022
static Module * getTopImportImplicitModule(ModuleManager &ModuleMgr, Preprocessor &PP)
Return the top import module if it is implicit, nullptr otherwise.
Definition: ASTReader.cpp:554
static Decl * getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID)
Definition: ASTReader.cpp:7707
static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II)
Definition: ASTReader.cpp:1014
static void addMethodsToPool(Sema &S, ArrayRef< ObjCMethodDecl * > Methods, ObjCMethodList &List)
Add the given set of methods to the method list.
Definition: ASTReader.cpp:8561
static bool readBit(unsigned &Bits)
Definition: ASTReader.cpp:1001
static std::optional< Type::TypeClass > getTypeClassForCode(TypeCode code)
Definition: ASTReader.cpp:6690
static std::pair< unsigned, unsigned > readULEBKeyDataLength(const unsigned char *&P)
Read ULEB-encoded key length and data length.
Definition: ASTReader.cpp:885
static LLVM_DUMP_METHOD void dumpModuleIDMap(StringRef Name, const ContinuousRangeMap< Key, ModuleFile *, InitialCapacity > &Map)
Definition: ASTReader.cpp:8156
OptionValidation
Definition: ASTReader.cpp:646
@ OptionValidateStrictMatches
Definition: ASTReader.cpp:649
@ OptionValidateNone
Definition: ASTReader.cpp:647
@ OptionValidateContradictions
Definition: ASTReader.cpp:648
static bool checkTargetOptions(const TargetOptions &TargetOpts, const TargetOptions &ExistingTargetOpts, DiagnosticsEngine *Diags, bool AllowCompatibleDifferences=true)
Compare the given set of target options against an existing set of target options.
Definition: ASTReader.cpp:386
#define CHECK_TARGET_OPT(Field, Name)
static bool checkLanguageOptions(const LangOptions &LangOpts, const LangOptions &ExistingLangOpts, DiagnosticsEngine *Diags, bool AllowCompatibleDifferences=true)
Compare the given set of language options against an existing set of language options.
Definition: ASTReader.cpp:279
static ASTFileSignature readASTFileSignature(StringRef PCH)
Reads and return the signature record from PCH's control block, or else returns 0.
Definition: ASTReader.cpp:5248
static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID)
Given a cursor at the start of an AST file, scan ahead and drop the cursor into the start of the give...
Definition: ASTReader.cpp:4398
static uint64_t readULEB(const unsigned char *&P)
Definition: ASTReader.cpp:872
ContinuousRangeMap< unsigned, int, 2 > SLocRemap
Definition: ASTUnit.cpp:2377
static StringRef bytes(const std::vector< T, Allocator > &v)
Definition: ASTWriter.cpp:126
static char ID
Definition: Arena.cpp:183
#define SM(sm)
Definition: Cuda.cpp:82
Defines the Diagnostic-related interfaces.
Defines the clang::CommentOptions interface.
static void dump(llvm::raw_ostream &OS, StringRef FunctionName, ArrayRef< CounterExpression > Expressions, ArrayRef< CounterMappingRegion > Regions)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the ExceptionSpecificationType enumeration and various utility functions.
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines the clang::FileManager interface and associated types.
Defines the clang::FileSystemOptions interface.
StringRef Filename
Definition: Format.cpp:2971
llvm::DenseSet< const void * > Visited
Definition: HTMLLogger.cpp:146
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
static const Decl * getCanonicalDecl(const Decl *D)
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::FileType FileType
Definition: MachO.h:45
llvm::MachO::Record Record
Definition: MachO.h:31
Defines the clang::MacroInfo and clang::MacroDirective classes.
Defines the clang::Module class, which describes a module in the source code.
Defines types useful for describing an Objective-C runtime.
Defines some OpenACC-specific enums and functions.
This file defines OpenMP AST classes for clauses.
Defines some OpenMP-specific enums and functions.
Defines an enumeration for C++ overloaded operators.
Defines the clang::Preprocessor interface.
static std::string getName(const CallEvent &Call)
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
Defines the clang::SanitizerKind enum.
This file declares semantic analysis for CUDA constructs.
Defines the clang::SourceLocation class and associated facilities.
Defines implementation details of the clang::SourceManager class.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
const char * Data
Defines the clang::TargetOptions class.
Defines the clang::TokenKind enum and support functions.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
Defines version macros and version-related utility functions for Clang.
__device__ __2f16 b
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Definition: ASTConsumer.h:33
virtual void HandleInterestingDecl(DeclGroupRef D)
HandleInterestingDecl - Handle the specified interesting declaration.
Definition: ASTConsumer.cpp:22
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
CanQualType AccumTy
Definition: ASTContext.h:1104
CanQualType ObjCBuiltinSelTy
Definition: ASTContext.h:1122
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1073
CanQualType ARCUnbridgedCastTy
Definition: ASTContext.h:1121
CanQualType LongTy
Definition: ASTContext.h:1100
TypedefDecl * getObjCClassDecl() const
Retrieve the typedef declaration corresponding to the predefined Objective-C 'Class' type.
TypedefDecl * getCFConstantStringDecl() const
CanQualType Int128Ty
Definition: ASTContext.h:1100
CanQualType SatUnsignedFractTy
Definition: ASTContext.h:1113
BuiltinTemplateDecl * getMakeIntegerSeqDecl() const
ExternCContextDecl * getExternCContextDecl() const
TypedefDecl * getObjCSelDecl() const
Retrieve the typedef corresponding to the predefined 'SEL' type in Objective-C.
CanQualType UnsignedShortAccumTy
Definition: ASTContext.h:1106
TypedefDecl * getObjCInstanceTypeDecl()
Retrieve the typedef declaration corresponding to the Objective-C "instancetype" type.
QualType getAutoRRefDeductType() const
C++11 deduction pattern for 'auto &&' type.
TypedefDecl * getBuiltinMSVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_ms_va_list type.
TypedefDecl * getObjCIdDecl() const
Retrieve the typedef corresponding to the predefined id type in Objective-C.
CanQualType SatAccumTy
Definition: ASTContext.h:1109
CanQualType ShortAccumTy
Definition: ASTContext.h:1104
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any.
Definition: ASTContext.h:1203
CanQualType FloatTy
Definition: ASTContext.h:1103
CanQualType DoubleTy
Definition: ASTContext.h:1103
CanQualType SatLongAccumTy
Definition: ASTContext.h:1109
void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl)
Set the type for the C sigjmp_buf type.
Definition: ASTContext.h:1975
CanQualType LongDoubleTy
Definition: ASTContext.h:1103
CanQualType OMPArrayShapingTy
Definition: ASTContext.h:1131
CanQualType Char16Ty
Definition: ASTContext.h:1098
void setFILEDecl(TypeDecl *FILEDecl)
Set the type for the C FILE type.
Definition: ASTContext.h:1953
CanQualType UnsignedLongFractTy
Definition: ASTContext.h:1108
CanQualType DependentTy
Definition: ASTContext.h:1119
CanQualType NullPtrTy
Definition: ASTContext.h:1118
CanQualType OMPIteratorTy
Definition: ASTContext.h:1131
RawCommentList Comments
All comments in this translation unit.
Definition: ASTContext.h:805
CanQualType SatShortFractTy
Definition: ASTContext.h:1112
CanQualType Ibm128Ty
Definition: ASTContext.h:1103
CanQualType SatUnsignedAccumTy
Definition: ASTContext.h:1110
CanQualType ArraySectionTy
Definition: ASTContext.h:1130
CanQualType ObjCBuiltinIdTy
Definition: ASTContext.h:1122
CanQualType BoolTy
Definition: ASTContext.h:1092
RecordDecl * getCFConstantStringTagDecl() const
CanQualType UnsignedFractTy
Definition: ASTContext.h:1108
CanQualType Float128Ty
Definition: ASTContext.h:1103
CanQualType ObjCBuiltinClassTy
Definition: ASTContext.h:1122
void setucontext_tDecl(TypeDecl *ucontext_tDecl)
Set the type for the C ucontext_t type.
Definition: ASTContext.h:1987
OMPTraitInfo & getNewOMPTraitInfo()
Return a new OMPTraitInfo object owned by this context.
CanQualType UnsignedLongTy
Definition: ASTContext.h:1101
CanQualType UnsignedLongAccumTy
Definition: ASTContext.h:1106
CanQualType ShortFractTy
Definition: ASTContext.h:1107
CanQualType BoundMemberTy
Definition: ASTContext.h:1119
CanQualType SatUnsignedShortFractTy
Definition: ASTContext.h:1113
CanQualType CharTy
Definition: ASTContext.h:1093
TypedefDecl * getInt128Decl() const
Retrieve the declaration for the 128-bit signed integer type.
CanQualType IntTy
Definition: ASTContext.h:1100
CanQualType PseudoObjectTy
Definition: ASTContext.h:1121
CanQualType Float16Ty
Definition: ASTContext.h:1117
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2156
CanQualType SignedCharTy
Definition: ASTContext.h:1100
CanQualType OverloadTy
Definition: ASTContext.h:1119
CanQualType OCLClkEventTy
Definition: ASTContext.h:1127
void adjustExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, bool AsWritten=false)
Change the exception specification on a function once it is delay-parsed, instantiated,...
TypedefDecl * getUInt128Decl() const
Retrieve the declaration for the 128-bit unsigned integer type.
CanQualType SatUnsignedShortAccumTy
Definition: ASTContext.h:1110
Decl * getVaListTagDecl() const
Retrieve the C type declaration corresponding to the predefined __va_list_tag type used to help defin...
CanQualType UnsignedInt128Ty
Definition: ASTContext.h:1102
CanQualType BuiltinFnTy
Definition: ASTContext.h:1120
ObjCInterfaceDecl * getObjCProtocolDecl() const
Retrieve the Objective-C class declaration corresponding to the predefined Protocol class.
CanQualType OCLSamplerTy
Definition: ASTContext.h:1127
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type.
CanQualType VoidTy
Definition: ASTContext.h:1091
CanQualType UnsignedCharTy
Definition: ASTContext.h:1101
CanQualType UnsignedShortFractTy
Definition: ASTContext.h:1108
void * Allocate(size_t Size, unsigned Align=8) const
Definition: ASTContext.h:718
CanQualType UnsignedIntTy
Definition: ASTContext.h:1101
TagDecl * getMSGuidTagDecl() const
Retrieve the implicitly-predeclared 'struct _GUID' declaration.
Definition: ASTContext.h:2137
CanQualType UnknownAnyTy
Definition: ASTContext.h:1119
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1102
CanQualType OCLReserveIDTy
Definition: ASTContext.h:1128
CanQualType UnsignedShortTy
Definition: ASTContext.h:1101
CanQualType SatUnsignedLongFractTy
Definition: ASTContext.h:1114
void setcudaConfigureCallDecl(FunctionDecl *FD)
Definition: ASTContext.h:1420
CanQualType ShortTy
Definition: ASTContext.h:1100
CanQualType FractTy
Definition: ASTContext.h:1107
DiagnosticsEngine & getDiagnostics() const
CanQualType LongAccumTy
Definition: ASTContext.h:1105
CanQualType Char32Ty
Definition: ASTContext.h:1099
CanQualType SatFractTy
Definition: ASTContext.h:1112
CanQualType SatLongFractTy
Definition: ASTContext.h:1112
CanQualType OCLQueueTy
Definition: ASTContext.h:1128
CanQualType LongFractTy
Definition: ASTContext.h:1107
CanQualType SatShortAccumTy
Definition: ASTContext.h:1109
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CanQualType BFloat16Ty
Definition: ASTContext.h:1116
CanQualType IncompleteMatrixIdxTy
Definition: ASTContext.h:1129
void setjmp_bufDecl(TypeDecl *jmp_bufDecl)
Set the type for the C jmp_buf type.
Definition: ASTContext.h:1963
BuiltinTemplateDecl * getTypePackElementDecl() const
CanQualType SatUnsignedLongAccumTy
Definition: ASTContext.h:1111
CanQualType LongLongTy
Definition: ASTContext.h:1100
void deduplicateMergedDefinitonsFor(NamedDecl *ND)
Clean up the merged definition list.
CanQualType WCharTy
Definition: ASTContext.h:1094
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
void setPrimaryMergedDecl(Decl *D, Decl *Primary)
Definition: ASTContext.h:1039
CanQualType Char8Ty
Definition: ASTContext.h:1097
CanQualType HalfTy
Definition: ASTContext.h:1115
CanQualType UnsignedAccumTy
Definition: ASTContext.h:1106
void setCFConstantStringType(QualType T)
CanQualType OCLEventTy
Definition: ASTContext.h:1127
virtual void MacroRead(serialization::MacroID ID, MacroInfo *MI)
A macro was read from the AST file.
virtual void IdentifierRead(serialization::IdentID ID, IdentifierInfo *II)
An identifier was deserialized from the AST file.
virtual void SelectorRead(serialization::SelectorID iD, Selector Sel)
A selector was read from the AST file.
An identifier-lookup iterator that enumerates all of the identifiers stored within a set of AST files...
Definition: ASTReader.cpp:8382
ASTIdentifierIterator(const ASTReader &Reader, bool SkipModules=false)
Definition: ASTReader.cpp:8410
StringRef Next() override
Retrieve the next string in the identifier table and advances the iterator for the following string.
Definition: ASTReader.cpp:8415
Abstract interface for callback invocations by the ASTReader.
Definition: ASTReader.h:114
virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool Complain)
Receives the header search options.
Definition: ASTReader.h:174
virtual void ReadModuleMapFile(StringRef ModuleMapPath)
Definition: ASTReader.h:127
virtual bool needsInputFileVisitation()
Returns true if this ASTReaderListener wants to receive the input files of the AST file via visitInpu...
Definition: ASTReader.h:218
virtual bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, bool AllowCompatibleDifferences)
Receives the target options.
Definition: ASTReader.h:142
virtual bool visitInputFile(StringRef Filename, bool isSystem, bool isOverridden, bool isExplicitModule)
if needsInputFileVisitation returns true, this is called for each non-system input file of the AST Fi...
Definition: ASTReader.h:230
virtual bool ReadHeaderSearchPaths(const HeaderSearchOptions &HSOpts, bool Complain)
Receives the header search paths.
Definition: ASTReader.h:189
virtual bool ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain)
Receives the file system options.
Definition: ASTReader.h:161
virtual bool ReadDiagnosticOptions(IntrusiveRefCntPtr< DiagnosticOptions > DiagOpts, bool Complain)
Receives the diagnostic options.
Definition: ASTReader.h:152
virtual void readModuleFileExtension(const ModuleFileExtensionMetadata &Metadata)
Indicates that a particular module file extension has been read.
Definition: ASTReader.h:244
virtual bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, bool AllowCompatibleDifferences)
Receives the language options.
Definition: ASTReader.h:132
virtual void visitImport(StringRef ModuleName, StringRef Filename)
If needsImportVisitation returns true, this is called for each AST file imported by this AST file.
Definition: ASTReader.h:241
virtual void visitModuleFile(StringRef Filename, serialization::ModuleKind Kind)
This is called for each AST file loaded.
Definition: ASTReader.h:213
virtual bool needsImportVisitation() const
Returns true if this ASTReaderListener wants to receive the imports of the AST file via visitImport,...
Definition: ASTReader.h:237
virtual bool ReadFullVersionInformation(StringRef FullVersion)
Receives the full Clang version information.
Definition: ASTReader.h:122
virtual void ReadCounter(const serialization::ModuleFile &M, unsigned Value)
Receives COUNTER value.
Definition: ASTReader.h:209
virtual void ReadModuleName(StringRef ModuleName)
Definition: ASTReader.h:126
virtual bool needsSystemInputFileVisitation()
Returns true if this ASTReaderListener wants to receive the system input files of the AST file via vi...
Definition: ASTReader.h:222
virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain, std::string &SuggestedPredefines)
Receives the preprocessor options.
Definition: ASTReader.h:202
Reads an AST files chain containing the contents of a translation unit.
Definition: ASTReader.h:366
std::optional< bool > isPreprocessedEntityInFileID(unsigned Index, FileID FID) override
Optionally returns true or false if the preallocated preprocessed entity with index Index came from f...
Definition: ASTReader.cpp:6484
PreprocessedEntity * ReadPreprocessedEntity(unsigned Index) override
Read a preallocated preprocessed entity from the external source.
Definition: ASTReader.cpp:6265
void markIdentifierUpToDate(const IdentifierInfo *II)
Note that this identifier is up-to-date.
Definition: ASTReader.cpp:2247
void visitTopLevelModuleMaps(serialization::ModuleFile &MF, llvm::function_ref< void(FileEntryRef)> Visitor)
Visit all the top-level module maps loaded when building the given module file.
Definition: ASTReader.cpp:9542
void setDeserializationListener(ASTDeserializationListener *Listener, bool TakeOwnership=false)
Set the AST deserialization listener.
Definition: ASTReader.cpp:897
ExtKind hasExternalDefinitions(const Decl *D) override
Definition: ASTReader.cpp:9048
IdentifierTable & getIdentifierTable()
Retrieve the identifier table associated with the preprocessor.
Definition: ASTReader.cpp:9417
ModuleManager & getModuleManager()
Retrieve the module manager.
Definition: ASTReader.h:1773
bool isDeclIDFromModule(GlobalDeclID ID, ModuleFile &M) const
Returns true if global DeclID ID originated from module M.
Definition: ASTReader.cpp:7670
friend class ASTIdentifierIterator
Definition: ASTReader.h:370
bool ReadSLocEntry(int ID) override
Read the source location entry with index ID.
Definition: ASTReader.cpp:1531
void RecordSwitchCaseID(SwitchCase *SC, unsigned ID)
Record that the given ID maps to the given switch-case statement.
Definition: ASTReader.cpp:9423
DiagnosticBuilder Diag(unsigned DiagID) const
Report a diagnostic.
Definition: ASTReader.cpp:9407
ASTContext & getContext()
Retrieve the AST context that this AST reader supplements.
Definition: ASTReader.h:2363
static std::string ReadString(const RecordDataImpl &Record, unsigned &Idx)
Definition: ASTReader.cpp:9366
void ReadDeclsToCheckForDeferredDiags(llvm::SmallSetVector< Decl *, 4 > &Decls) override
Read the set of decls to be checked for deferred diags.
Definition: ASTReader.cpp:8702
void InitializeSema(Sema &S) override
Initialize the semantic source with the Sema instance being used to perform semantic analysis on the ...
Definition: ASTReader.cpp:8212
@ ARR_Missing
The client can handle an AST file that cannot load because it is missing.
Definition: ASTReader.h:1615
@ ARR_ConfigurationMismatch
The client can handle an AST file that cannot load because it's compiled configuration doesn't match ...
Definition: ASTReader.h:1628
@ ARR_OutOfDate
The client can handle an AST file that cannot load because it is out-of-date relative to its input fi...
Definition: ASTReader.h:1619
@ ARR_VersionMismatch
The client can handle an AST file that cannot load because it was built with a different version of C...
Definition: ASTReader.h:1623
void ReadMismatchingDeleteExpressions(llvm::MapVector< FieldDecl *, llvm::SmallVector< std::pair< SourceLocation, bool >, 4 > > &Exprs) override
Definition: ASTReader.cpp:8632
void FindFileRegionDecls(FileID File, unsigned Offset, unsigned Length, SmallVectorImpl< Decl * > &Decls) override
Get the decls that are contained in a file in the Offset/Length range.
Definition: ASTReader.cpp:7937
SourceRange ReadSkippedRange(unsigned Index) override
Read a preallocated skipped range from the external source.
Definition: ASTReader.cpp:6251
void dump()
Dump information about the AST reader to standard error.
Definition: ASTReader.cpp:8176
serialization::IdentifierID getGlobalIdentifierID(ModuleFile &M, unsigned LocalID)
Definition: ASTReader.cpp:8910
void AssignedLambdaNumbering(const CXXRecordDecl *Lambda) override
Notify the external source that a lambda was assigned a mangling number.
Definition: ASTReader.cpp:8803
MacroInfo * ReadMacroRecord(ModuleFile &F, uint64_t Offset)
Reads the macro record located at the given offset.
Definition: ASTReader.cpp:1832
SmallVector< std::pair< llvm::BitstreamCursor, serialization::ModuleFile * >, 8 > CommentsCursors
Cursors for comments blocks.
Definition: ASTReader.h:2397
Selector getLocalSelector(ModuleFile &M, unsigned LocalID)
Retrieve a selector from the given module with its local ID number.
Definition: ASTReader.cpp:9055
void FindExternalLexicalDecls(const DeclContext *DC, llvm::function_ref< bool(Decl::Kind)> IsKindWeWant, SmallVectorImpl< Decl * > &Decls) override
Read all of the declarations lexically stored in a declaration context.
Definition: ASTReader.cpp:7861
std::optional< ASTSourceDescriptor > getSourceDescriptor(unsigned ID) override
Return a descriptor for the corresponding module.
Definition: ASTReader.cpp:9030
const serialization::reader::DeclContextLookupTable * getLoadedLookupTables(DeclContext *Primary) const
Get the loaded lookup tables for Primary, if any.
Definition: ASTReader.cpp:8030
void ClearSwitchCaseIDs()
Definition: ASTReader.cpp:9435
void SetGloballyVisibleDecls(IdentifierInfo *II, const SmallVectorImpl< GlobalDeclID > &DeclIDs, SmallVectorImpl< Decl * > *Decls=nullptr)
Set the globally-visible declarations associated with the given identifier.
Definition: ASTReader.cpp:8843
void SetIdentifierInfo(unsigned ID, IdentifierInfo *II)
Definition: ASTReader.cpp:8819
bool loadGlobalIndex()
Attempts to load the global index.
Definition: ASTReader.cpp:4352
void ReadComments() override
Loads comments ranges.
Definition: ASTReader.cpp:9439
SourceManager & getSourceManager() const
Definition: ASTReader.h:1600
SourceLocation getSourceLocationForDeclID(GlobalDeclID ID)
Returns the source location for the decl ID.
Definition: ASTReader.cpp:7688
void makeModuleVisible(Module *Mod, Module::NameVisibilityKind NameVisibility, SourceLocation ImportLoc)
Make the entities in the given module and any of its (non-explicit) submodules visible to name lookup...
Definition: ASTReader.cpp:4288
void finalizeForWriting()
Finalizes the AST reader's state before writing an AST file to disk.
Definition: ASTReader.cpp:5242
Sema * getSema()
Retrieve the semantic analysis object used to analyze the translation unit in which the precompiled h...
Definition: ASTReader.h:2375
CXXCtorInitializer ** GetExternalCXXCtorInitializers(uint64_t Offset) override
Read the contents of a CXXCtorInitializer array.
Definition: ASTReader.cpp:7580
void visitInputFileInfos(serialization::ModuleFile &MF, bool IncludeSystem, llvm::function_ref< void(const serialization::InputFileInfo &IFI, bool IsSystem)> Visitor)
Visit all the input file infos of the given module file.
Definition: ASTReader.cpp:9511
void StartTranslationUnit(ASTConsumer *Consumer) override
Function that will be invoked when we begin parsing a new translation unit involving this external AS...
Definition: ASTReader.cpp:8056
LocalDeclID mapGlobalIDToModuleFileGlobalID(ModuleFile &M, GlobalDeclID GlobalID)
Map a global declaration ID into the declaration ID used to refer to this declaration within the give...
Definition: ASTReader.cpp:7812
void resolvePendingMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo)
Definition: ASTReader.cpp:2258
bool FindExternalVisibleDeclsByName(const DeclContext *DC, DeclarationName Name) override
Finds all the visible declarations with a given name.
Definition: ASTReader.cpp:7978
void ReadTentativeDefinitions(SmallVectorImpl< VarDecl * > &TentativeDefs) override
Read the set of tentative definitions known to the external Sema source.
Definition: ASTReader.cpp:8648
Decl * GetExternalDecl(GlobalDeclID ID) override
Resolve a declaration ID into a declaration, potentially building a new declaration.
Definition: ASTReader.cpp:7521
llvm::Expected< SourceLocation::UIntTy > readSLocOffset(ModuleFile *F, unsigned Index)
Try to read the offset of the SLocEntry at the given index in the given module file.
Definition: ASTReader.cpp:1459
~ASTReader() override
void CompleteRedeclChain(const Decl *D) override
If any redeclarations of D have been imported since it was last checked, this digs out those redeclar...
Definition: ASTReader.cpp:7523
SourceLocation TranslateSourceLocation(ModuleFile &ModuleFile, SourceLocation Loc) const
Translate a source location from another module file's source location space into ours.
Definition: ASTReader.h:2247
static llvm::Error ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor, unsigned BlockID, uint64_t *StartOfBlockOffset=nullptr)
ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the specified cursor.
Definition: ASTReader.cpp:1753
serialization::PreprocessedEntityID getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const
Determine the global preprocessed entity ID that corresponds to the given local ID within the given m...
Definition: ASTReader.cpp:1963
std::pair< unsigned, unsigned > findPreprocessedEntitiesInRange(SourceRange Range) override
Returns a pair of [Begin, End) indices of preallocated preprocessed entities that Range encompasses.
Definition: ASTReader.cpp:6471
IdentifierInfo * get(StringRef Name) override
Retrieve the IdentifierInfo for the named identifier.
Definition: ASTReader.cpp:8343
void visitInputFiles(serialization::ModuleFile &MF, bool IncludeSystem, bool Complain, llvm::function_ref< void(const serialization::InputFile &IF, bool isSystem)> Visitor)
Visit all the input files of the given module file.
Definition: ASTReader.cpp:9527
Module * getModule(unsigned ID) override
Retrieve the module that corresponds to the given module ID.
Definition: ASTReader.cpp:8996
llvm::iterator_range< ModuleDeclIterator > getModuleFileLevelDecls(ModuleFile &Mod)
Definition: ASTReader.cpp:6244
GlobalDeclID ReadDeclID(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Reads a declaration ID from the given position in a record in the given module.
Definition: ASTReader.cpp:7830
Stmt * GetExternalDeclStmt(uint64_t Offset) override
Resolve the offset of a statement into a statement.
Definition: ASTReader.cpp:7845
Selector GetExternalSelector(serialization::SelectorID ID) override
Resolve a selector ID into a selector.
Definition: ASTReader.cpp:9084
unsigned getTotalNumSelectors() const
Returns the number of selectors found in the chain.
Definition: ASTReader.h:1873
MacroInfo * getMacro(serialization::MacroID ID)
Retrieve the macro with the given ID.
Definition: ASTReader.cpp:8925
void ReadUndefinedButUsed(llvm::MapVector< NamedDecl *, SourceLocation > &Undefined) override
Load the set of used but not defined functions or variables with internal linkage,...
Definition: ASTReader.cpp:8621
void ReadDelegatingConstructors(SmallVectorImpl< CXXConstructorDecl * > &Decls) override
Read the set of delegating constructors known to the external Sema source.
Definition: ASTReader.cpp:8669
SourceLocation ReadSourceLocation(ModuleFile &ModuleFile, SourceLocation::UIntTy Raw, LocSeq *Seq=nullptr) const
Read a source location from raw form.
Definition: ASTReader.h:2238
QualType GetType(serialization::TypeID ID)
Resolve a type ID into a type, potentially building a new type.
Definition: ASTReader.cpp:7150
void addPendingMacro(IdentifierInfo *II, ModuleFile *M, uint32_t MacroDirectivesOffset)
Add a macro to deserialize its macro directive history.
Definition: ASTReader.cpp:2098
SourceRange ReadSourceRange(ModuleFile &F, const RecordData &Record, unsigned &Idx, LocSeq *Seq=nullptr)
Read a source range.
Definition: ASTReader.cpp:9341
GlobalDeclID getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const
Map from a local declaration ID within a given module to a global declaration ID.
Definition: ASTReader.cpp:7654
void ReadWeakUndeclaredIdentifiers(SmallVectorImpl< std::pair< IdentifierInfo *, WeakInfo > > &WeakIDs) override
Read the set of weak, undeclared identifiers known to the external Sema source.
Definition: ASTReader.cpp:8730
void completeVisibleDeclsMap(const DeclContext *DC) override
Load all external visible decls in the given DeclContext.
Definition: ASTReader.cpp:8006
void ReadUnusedLocalTypedefNameCandidates(llvm::SmallSetVector< const TypedefNameDecl *, 4 > &Decls) override
Read the set of potentially unused typedefs known to the source.
Definition: ASTReader.cpp:8690
IdentifierResolver & getIdResolver()
Get the identifier resolver used for name lookup / updates in the translation unit scope.
static bool readASTFileControlBlock(StringRef Filename, FileManager &FileMgr, const InMemoryModuleCache &ModuleCache, const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions, ASTReaderListener &Listener, bool ValidateDiagnosticOptions, unsigned ClientLoadCapabilities=ARR_ConfigurationMismatch|ARR_OutOfDate)
Read the control block for the named AST file.
Definition: ASTReader.cpp:5410
void ReadExtVectorDecls(SmallVectorImpl< TypedefNameDecl * > &Decls) override
Read the set of ext_vector type declarations known to the external Sema source.
Definition: ASTReader.cpp:8680
void ResolveImportedPath(ModuleFile &M, std::string &Filename)
If we are loading a relocatable PCH or module file, and the filename is not an absolute path,...
Definition: ASTReader.cpp:2677
ModuleFile * getOwningModuleFile(const Decl *D)
Retrieve the module file that owns the given declaration, or NULL if the declaration is not from a mo...
Definition: ASTReader.cpp:7679
SmallVector< GlobalDeclID, 16 > PreloadedDeclIDs
Definition: ASTReader.h:2370
std::pair< SourceLocation, StringRef > getModuleImportLoc(int ID) override
Retrieve the module import location and module name for the given source manager entry ID.
Definition: ASTReader.cpp:1716
void ReadUnusedFileScopedDecls(SmallVectorImpl< const DeclaratorDecl * > &Decls) override
Read the set of unused file-scope declarations known to the external Sema source.
Definition: ASTReader.cpp:8658
void ReadReferencedSelectors(SmallVectorImpl< std::pair< Selector, SourceLocation > > &Sels) override
Read the set of referenced selectors known to the external Sema source.
Definition: ASTReader.cpp:8712
Selector DecodeSelector(serialization::SelectorID Idx)
Definition: ASTReader.cpp:9059
ASTReadResult ReadAST(StringRef FileName, ModuleKind Type, SourceLocation ImportLoc, unsigned ClientLoadCapabilities, ModuleFile **NewLoadedModuleFile=nullptr)
Load the AST file designated by the given file name.
Definition: ASTReader.cpp:4443
StringRef getOriginalSourceFile()
Retrieve the name of the original source file name for the primary module file.
Definition: ASTReader.h:1780
std::string ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Definition: ASTReader.cpp:9373
unsigned getModuleFileID(ModuleFile *M)
Get an ID for the given module file.
Definition: ASTReader.cpp:9013
IdentifierInfo * DecodeIdentifierInfo(serialization::IdentifierID ID)
Definition: ASTReader.cpp:8875
ASTReadResult
The result of reading the control block of an AST file, which can fail for various reasons.
Definition: ASTReader.h:384
@ Success
The control block was read successfully.
Definition: ASTReader.h:387
@ ConfigurationMismatch
The AST file was written with a different language/target configuration.
Definition: ASTReader.h:404
@ OutOfDate
The AST file is out-of-date relative to its input files, and needs to be regenerated.
Definition: ASTReader.h:397
@ Failure
The AST file itself appears corrupted.
Definition: ASTReader.h:390
@ VersionMismatch
The AST file was written by a different version of Clang.
Definition: ASTReader.h:400
@ HadErrors
The AST file has errors.
Definition: ASTReader.h:407
@ Missing
The AST file was missing.
Definition: ASTReader.h:393
static VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx)
Read a version tuple.
Definition: ASTReader.cpp:9388
Token ReadToken(ModuleFile &M, const RecordDataImpl &Record, unsigned &Idx)
Reads a token out of a record.
Definition: ASTReader.cpp:1780
SwitchCase * getSwitchCaseWithID(unsigned ID)
Retrieve the switch-case statement with the given ID.
Definition: ASTReader.cpp:9430
ModuleFile * getLocalModuleFile(ModuleFile &M, unsigned ID)
Retrieve the module file with a given local ID within the specified ModuleFile.
Definition: ASTReader.cpp:9000
void ReadLateParsedTemplates(llvm::MapVector< const FunctionDecl *, std::unique_ptr< LateParsedTemplate > > &LPTMap) override
Read the set of late parsed template functions for this source.
Definition: ASTReader.cpp:8773
IdentifierIterator * getIdentifiers() override
Retrieve an iterator into the set of all identifiers in all loaded AST files.
Definition: ASTReader.cpp:8468
void ReadUsedVTables(SmallVectorImpl< ExternalVTableUse > &VTables) override
Read the set of used vtables known to the external Sema source.
Definition: ASTReader.cpp:8748
bool isGlobalIndexUnavailable() const
Determine whether we tried to load the global index, but failed, e.g., because it is out-of-date or d...
Definition: ASTReader.cpp:4377
uint32_t GetNumExternalSelectors() override
Returns the number of selectors known to the external AST source.
Definition: ASTReader.cpp:9088
void updateOutOfDateSelector(Selector Sel) override
Load the contents of the global method pool for a given selector if necessary.
Definition: ASTReader.cpp:8605
Decl * GetExistingDecl(GlobalDeclID ID)
Resolve a declaration ID into a declaration.
Definition: ASTReader.cpp:7766
static llvm::BitVector ReadBitVector(const RecordData &Record, const StringRef Blob)
Definition: ASTReader.cpp:9348
void LoadSelector(Selector Sel)
Load a selector from disk, registering its ID if it exists.
Definition: ASTReader.cpp:8814
IdentifierInfo * getLocalIdentifier(ModuleFile &M, unsigned LocalID)
Definition: ASTReader.cpp:8906
void ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag)
Definition: ASTReader.cpp:6543
void makeNamesVisible(const HiddenNames &Names, Module *Owner)
Make the names within this set of hidden names visible.
Definition: ASTReader.cpp:4274
void UpdateSema()
Update the state of Sema after loading some additional modules.
Definition: ASTReader.cpp:8238
Decl * GetDecl(GlobalDeclID ID)
Resolve a declaration ID into a declaration, potentially building a new declaration.
Definition: ASTReader.cpp:7791
Decl * GetLocalDecl(ModuleFile &F, LocalDeclID LocalID)
Reads a declaration with the given local ID in the given module.
Definition: ASTReader.h:1929
ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache, ASTContext *Context, const PCHContainerReader &PCHContainerRdr, ArrayRef< std::shared_ptr< ModuleFileExtension > > Extensions, StringRef isysroot="", DisableValidationForModuleKind DisableValidationKind=DisableValidationForModuleKind::None, bool AllowASTWithCompilerErrors=false, bool AllowConfigurationMismatch=false, bool ValidateSystemInputs=false, bool ValidateASTInputFilesContent=false, bool UseGlobalIndex=true, std::unique_ptr< llvm::Timer > ReadTimer={})
Load the AST file and validate its contents against the given Preprocessor.
int getSLocEntryID(SourceLocation::UIntTy SLocOffset) override
Get the index ID for the loaded SourceLocation offset.
Definition: ASTReader.cpp:1494
void ReadPendingInstantiations(SmallVectorImpl< std::pair< ValueDecl *, SourceLocation > > &Pending) override
Read the set of pending instantiations known to the external Sema source.
Definition: ASTReader.cpp:8761
serialization::SubmoduleID getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID)
Retrieve the global submodule ID given a module and its local ID number.
Definition: ASTReader.cpp:8967
Preprocessor & getPreprocessor() const
Retrieve the preprocessor.
Definition: ASTReader.h:1776
CXXTemporary * ReadCXXTemporary(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Definition: ASTReader.cpp:9400
void ReadKnownNamespaces(SmallVectorImpl< NamespaceDecl * > &Namespaces) override
Load the set of namespaces that are known to the external source, which will be used during typo corr...
Definition: ASTReader.cpp:8610
QualType getLocalType(ModuleFile &F, unsigned LocalID)
Resolve a local type ID within a given AST file into a type.
Definition: ASTReader.cpp:7439
Module * getSubmodule(serialization::SubmoduleID GlobalID)
Retrieve the submodule that corresponds to a global submodule ID.
Definition: ASTReader.cpp:8982
void PrintStats() override
Print some statistics about AST usage.
Definition: ASTReader.cpp:8066
void mergeDefinitionVisibility(NamedDecl *Def, NamedDecl *MergedDef)
Note that MergedDef is a redefinition of the canonical definition Def, so Def should be visible whene...
Definition: ASTReader.cpp:4337
serialization::SelectorID getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const
Retrieve the global selector ID that corresponds to this the local selector ID in a given module.
Definition: ASTReader.cpp:9094
void StartedDeserializing() override
Notify ASTReader that we started deserialization of a decl or type so until FinishedDeserializing is ...
void ReadMethodPool(Selector Sel) override
Load the contents of the global method pool for a given selector.
Definition: ASTReader.cpp:8567
void InitializeContext()
Initializes the ASTContext.
Definition: ASTReader.cpp:5098
CXXBaseSpecifier * GetExternalCXXBaseSpecifiers(uint64_t Offset) override
Resolve the offset of a set of C++ base specifiers in the decl stream into an array of specifiers.
Definition: ASTReader.cpp:7612
serialization::TypeID getGlobalTypeID(ModuleFile &F, unsigned LocalID) const
Map a local type ID within a given AST file into a global type ID.
Definition: ASTReader.cpp:7444
static bool isAcceptableASTFile(StringRef Filename, FileManager &FileMgr, const InMemoryModuleCache &ModuleCache, const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts, const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts, StringRef ExistingModuleCachePath, bool RequireStrictOptionMatches=false)
Determine whether the given AST file is acceptable to load into a translation unit with the given lan...
Definition: ASTReader.cpp:5704
void FinishedDeserializing() override
Notify ASTReader that we finished the deserialization of a decl or type.
void updateOutOfDateIdentifier(const IdentifierInfo &II) override
Update an out-of-date identifier.
Definition: ASTReader.cpp:2222
void ReadDefinedMacros() override
Read the set of macros defined by this external macro source.
Definition: ASTReader.cpp:2104
HeaderFileInfo GetHeaderFileInfo(FileEntryRef FE) override
Read the header file information for the given file entry.
Definition: ASTReader.cpp:6534
serialization::MacroID getGlobalMacroID(ModuleFile &M, unsigned LocalID)
Retrieve the global macro ID corresponding to the given local ID within the given module file.
Definition: ASTReader.cpp:8952
An object for streaming information from a record.
bool readBool()
Read a boolean value, advancing Idx.
uint32_t readUInt32()
Read a 32-bit unsigned value; required to satisfy BasicReader.
llvm::APFloat readAPFloat(const llvm::fltSemantics &Sem)
Read an arbitrary constant value, advancing Idx.
Definition: ASTReader.cpp:9361
TemplateArgumentLoc readTemplateArgumentLoc()
Reads a TemplateArgumentLoc, advancing Idx.
Definition: ASTReader.cpp:7495
void readTypeLoc(TypeLoc TL, LocSeq *Seq=nullptr)
Reads the location information for a type.
Definition: ASTReader.cpp:7133
void readUnresolvedSet(LazyASTUnresolvedSet &Set)
Read a UnresolvedSet structure, advancing Idx.
Definition: ASTReader.cpp:9189
void readTemplateArgumentList(SmallVectorImpl< TemplateArgument > &TemplArgs, bool Canonicalize=false)
Read a template argument array, advancing Idx.
Definition: ASTReader.cpp:9179
void readQualifierInfo(QualifierInfo &Info)
Definition: ASTReader.cpp:9147
DeclarationNameLoc readDeclarationNameLoc(DeclarationName Name)
Read a declaration name, advancing Idx.
Definition: ASTReader.cpp:9110
CXXBaseSpecifier readCXXBaseSpecifier()
Read a C++ base specifier, advancing Idx.
Definition: ASTReader.cpp:9200
Expected< unsigned > readRecord(llvm::BitstreamCursor &Cursor, unsigned AbbrevID)
Reads a record with id AbbrevID from Cursor, resetting the internal state.
DeclarationNameInfo readDeclarationNameInfo()
Definition: ASTReader.cpp:9135
IdentifierInfo * readIdentifier()
TemplateArgumentLocInfo readTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind)
Reads a TemplateArgumentLocInfo appropriate for the given TemplateArgument kind, advancing Idx.
Definition: ASTReader.cpp:7463
TemplateArgument readTemplateArgument(bool Canonicalize)
ASTContext & getContext()
Retrieve the AST context that this AST reader supplements.
TypeSourceInfo * readTypeSourceInfo()
Reads a declarator info from the given record, advancing Idx.
Definition: ASTReader.cpp:7140
void readTemplateArgumentListInfo(TemplateArgumentListInfo &Result)
Definition: ASTReader.cpp:7505
TypeCoupledDeclRefInfo readTypeCoupledDeclRefInfo()
Definition: ASTReader.cpp:9143
void skipInts(unsigned N)
Skips the specified number of values.
GlobalDeclID readDeclID()
Reads a declaration ID from the given position in this record.
SourceRange readSourceRange(LocSeq *Seq=nullptr)
Read a source range, advancing Idx.
NestedNameSpecifierLoc readNestedNameSpecifierLoc()
Return a nested name specifier, advancing Idx.
Definition: ASTReader.cpp:9280
ConceptReference * readConceptReference()
Definition: ASTReader.cpp:6976
void readOMPChildren(OMPChildren *Data)
Read an OpenMP children, advancing Idx.
OMPClause * readOMPClause()
Read an OpenMP clause, advancing Idx.
void readOpenACCClauseList(MutableArrayRef< const OpenACCClause * > Clauses)
Read a list of OpenACC clauses into the passed SmallVector.
OMPTraitInfo * readOMPTraitInfo()
Read an OMPTraitInfo object, advancing Idx.
TemplateParameterList * readTemplateParameterList()
Read a template parameter list, advancing Idx.
Definition: ASTReader.cpp:9160
OpenACCClause * readOpenACCClause()
Read an OpenACC clause, advancing Idx.
CXXCtorInitializer ** readCXXCtorInitializers()
Read a CXXCtorInitializer array, advancing Idx.
Definition: ASTReader.cpp:9215
Stmt * readStmt()
Reads a statement.
const ASTTemplateArgumentListInfo * readASTTemplateArgumentListInfo()
Definition: ASTReader.cpp:7515
uint64_t readInt()
Returns the current value in this record, and advances to the next value.
Attr * readAttr()
Reads one attribute from the current stream position, advancing Idx.
Expr * readExpr()
Reads an expression.
SourceLocation readSourceLocation(LocSeq *Seq=nullptr)
Read a source location, advancing Idx.
Expr * readSubExpr()
Reads a sub-expression operand during statement reading.
Abstracts clang modules and precompiled header files and holds everything needed to generate debug in...
Definition: Module.h:873
Wrapper for source info for array parameter types.
Definition: TypeLoc.h:1617
Wrapper for source info for arrays.
Definition: TypeLoc.h:1561
void setLBracketLoc(SourceLocation Loc)
Definition: TypeLoc.h:1567
void setRBracketLoc(SourceLocation Loc)
Definition: TypeLoc.h:1575
void setSizeExpr(Expr *Size)
Definition: TypeLoc.h:1587
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2638
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2630
void setKWLoc(SourceLocation Loc)
Definition: TypeLoc.h:2622
Attr - This represents one attribute.
Definition: Attr.h:42
Type source information for an attributed type.
Definition: TypeLoc.h:875
void setAttr(const Attr *A)
Definition: TypeLoc.h:901
void setConceptReference(ConceptReference *CR)
Definition: TypeLoc.h:2201
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2195
Type source information for an btf_tag attributed type.
Definition: TypeLoc.h:925
Wrapper for source info for block pointers.
Definition: TypeLoc.h:1314
void setCaretLoc(SourceLocation Loc)
Definition: TypeLoc.h:1320
Wrapper for source info for builtin types.
Definition: TypeLoc.h:565
void setWrittenTypeSpec(TypeSpecifierType written)
Definition: TypeLoc.h:651
bool needsExtraLocalData() const
Definition: TypeLoc.h:594
void setModeAttr(bool written)
Definition: TypeLoc.h:663
void setBuiltinLoc(SourceLocation Loc)
Definition: TypeLoc.h:571
void setWrittenWidthSpec(TypeSpecifierWidth written)
Definition: TypeLoc.h:640
void setWrittenSignSpec(TypeSpecifierSign written)
Definition: TypeLoc.h:624
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2535
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2300
void setSourceOrder(int Pos)
Set the source order of this initializer.
Definition: DeclCXX.h:2487
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2799
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
Decl * getLambdaContextDecl() const
Retrieve the declaration that provides additional context for a lambda, when the normal declaration c...
Definition: DeclCXX.cpp:1685
unsigned getLambdaIndexInContext() const
Retrieve the index of this lambda within the context declaration returned by getLambdaContextDecl().
Definition: DeclCXX.h:1792
Represents a C++ temporary.
Definition: ExprCXX.h:1453
static CXXTemporary * Create(const ASTContext &C, const CXXDestructorDecl *Destructor)
Definition: ExprCXX.cpp:1043
bool visitInputFile(StringRef Filename, bool isSystem, bool isOverridden, bool isExplicitModule) override
if needsInputFileVisitation returns true, this is called for each non-system input file of the AST Fi...
Definition: ASTReader.cpp:243
bool ReadFullVersionInformation(StringRef FullVersion) override
Receives the full Clang version information.
Definition: ASTReader.cpp:156
bool ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain) override
Receives the file system options.
Definition: ASTReader.cpp:197
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
Definition: ASTReader.cpp:212
void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override
Receives COUNTER value.
Definition: ASTReader.cpp:221
void ReadModuleMapFile(StringRef ModuleMapPath) override
Definition: ASTReader.cpp:166
bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool Complain) override
Receives the header search options.
Definition: ASTReader.cpp:203
bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, bool AllowCompatibleDifferences) override
Receives the target options.
Definition: ASTReader.cpp:181
void ReadModuleName(StringRef ModuleName) override
Definition: ASTReader.cpp:161
bool needsInputFileVisitation() override
Returns true if this ASTReaderListener wants to receive the input files of the AST file via visitInpu...
Definition: ASTReader.cpp:227
bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, bool AllowCompatibleDifferences) override
Receives the language options.
Definition: ASTReader.cpp:172
void readModuleFileExtension(const ModuleFileExtensionMetadata &Metadata) override
Indicates that a particular module file extension has been read.
Definition: ASTReader.cpp:259
bool ReadDiagnosticOptions(IntrusiveRefCntPtr< DiagnosticOptions > DiagOpts, bool Complain) override
Receives the diagnostic options.
Definition: ASTReader.cpp:190
void visitModuleFile(StringRef Filename, serialization::ModuleKind Kind) override
This is called for each AST file loaded.
Definition: ASTReader.cpp:237
bool needsSystemInputFileVisitation() override
Returns true if this ASTReaderListener wants to receive the system input files of the AST file via vi...
Definition: ASTReader.cpp:232
A reference to a concept and its template args, as it appears in the code.
Definition: ASTConcept.h:128
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
Definition: ASTConcept.cpp:93
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:421
An object that helps properly build a continuous range map from a set of values.
A map from continuous integer ranges to some value, with a very specialized interface.
void insertOrReplace(const value_type &Val)
typename Representation::const_iterator const_iterator
typename Representation::iterator iterator
void insert(const value_type &Val)
Wrapper for source info for pointers decayed from arrays and functions.
Definition: TypeLoc.h:1262
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1784
bool hasExternalVisibleStorage() const
Whether this DeclContext has external storage containing additional declarations that are visible in ...
Definition: DeclBase.h:2649
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1920
void setMustBuildLookupTable()
Mark that there are external lexical declarations that we need to include in our lookup table (and th...
Definition: DeclBase.h:2622
bool hasExternalLexicalStorage() const
Whether this DeclContext has external storage containing additional declarations that are lexically i...
Definition: DeclBase.h:2637
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1354
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2322
void setHasExternalLexicalStorage(bool ES=true) const
State whether this DeclContext has external storage for declarations lexically in this context.
Definition: DeclBase.h:2643
bool isDeclInLexicalTraversal(const Decl *D) const
Determine whether the given declaration is stored in the list of declarations lexically within this c...
Definition: DeclBase.h:2663
DeclID get() const
Definition: DeclID.h:117
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:599
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
bool isUnconditionallyVisible() const
Determine whether this declaration is definitely visible to name lookup, independent of whether the o...
Definition: DeclBase.h:849
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:89
GlobalDeclID getGlobalID() const
Retrieve the global declaration ID associated with this declaration, which specifies where this Decl ...
Definition: DeclBase.h:780
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition: DeclBase.h:803
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition: DeclBase.h:776
SourceLocation getLocation() const
Definition: DeclBase.h:445
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: DeclBase.h:1039
DeclContext * getDeclContext()
Definition: DeclBase.h:454
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
Kind getKind() const
Definition: DeclBase.h:448
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition: DeclBase.h:860
DeclarationNameLoc - Additional source/type location info for a declaration name.
static DeclarationNameLoc makeNamedTypeLoc(TypeSourceInfo *TInfo)
Construct location information for a constructor, destructor or conversion operator.
static DeclarationNameLoc makeCXXLiteralOperatorNameLoc(SourceLocation Loc)
Construct location information for a literal C++ operator.
static DeclarationNameLoc makeCXXOperatorNameLoc(SourceLocation BeginLoc, SourceLocation EndLoc)
Construct location information for a non-literal C++ operator.
The name of a declaration.
NameKind
The kind of the name stored in this DeclarationName.
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:770
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2087
void setDecltypeLoc(SourceLocation Loc)
Definition: TypeLoc.h:2084
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2302
void setAttrNameLoc(SourceLocation loc)
Definition: TypeLoc.h:1773
void setAttrOperandParensRange(SourceRange range)
Definition: TypeLoc.h:1794
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2423
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2403
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2412
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1892
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2472
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2492
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2460
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:2516
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:2508
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:2524
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2500
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:6519
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1864
A little helper class used to produce diagnostics.
Definition: Diagnostic.h:1271
Carries a Clang diagnostic in an llvm::Error.
static llvm::Error create(SourceLocation Loc, PartialDiagnostic Diag)
Creates a new DiagnosticError that contains the given diagnostic at the given location.
PartialDiagnosticAt & getDiagnostic()
bool wasUpgradedFromWarning() const
Whether this mapping attempted to map the diagnostic to a warning, but was overruled because the diag...
void setSeverity(diag::Severity Value)
static DiagnosticMapping deserialize(unsigned Bits)
Deserialize a mapping.
void setUpgradedFromWarning(bool Value)
Options for controlling the compiler diagnostics engine.
std::vector< std::string > SystemHeaderWarningsModules
The list of -Wsystem-header-in-module=... options used to override whether -Wsystem-headers is enable...
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1547
DiagnosticOptions & getDiagnosticOptions() const
Retrieve the diagnostic options.
Definition: Diagnostic.h:562
bool getEnableAllWarnings() const
Definition: Diagnostic.h:664
Level
The level of the diagnostic, after it has been through mapping.
Definition: Diagnostic.h:195
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
Definition: Diagnostic.h:931
bool getSuppressSystemWarnings() const
Definition: Diagnostic.h:690
bool getWarningsAsErrors() const
Definition: Diagnostic.h:672
diag::Severity getExtensionHandlingBehavior() const
Definition: Diagnostic.h:781
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition: Diagnostic.h:557
StringRef getName() const
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2323
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2337
Represents an enum.
Definition: Decl.h:3868
Wrapper for source info for enum types.
Definition: TypeLoc.h:749
This represents one expression.
Definition: Expr.h:110
RAII class for safely pairing a StartedDeserializing call with FinishedDeserializing.
MemoryBufferSizes getMemoryBufferSizes() const
Return the amount of memory used by memory buffers, breaking down by heap-backed versus mmap'ed memor...
uint32_t getGeneration() const
Get the current generation of this AST source.
Represents difference between two FPOptions values.
Definition: LangOptions.h:915
static FPOptionsOverride getFromOpaqueInt(storage_type I)
Definition: LangOptions.h:981
FPOptions applyOverrides(FPOptions Base)
Definition: LangOptions.h:988
static FPOptions getFromOpaqueInt(storage_type Value)
Definition: LangOptions.h:879
Represents a member of a struct/union/class.
Definition: Decl.h:3058
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
Definition: FileEntry.h:57
time_t getModificationTime() const
Definition: FileEntry.h:348
off_t getSize() const
Definition: FileEntry.h:340
StringRef getName() const
The name of this FileEntry.
Definition: FileEntry.h:61
Cached information about one file (either on disk or in the virtual file system).
Definition: FileEntry.h:300
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
bool isValid() const
bool isInvalid() const
Implements support for file system lookup, file system caching, and directory search management.
Definition: FileManager.h:53
OptionalFileEntryRef getOptionalFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Get a FileEntryRef if it exists, without doing anything on error.
Definition: FileManager.h:240
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(FileEntryRef Entry, bool isVolatile=false, bool RequiresNullTerminator=true)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
FileEntryRef getVirtualFileRef(StringRef Filename, off_t Size, time_t ModificationTime)
Retrieve a file entry for a "virtual" file that acts as if there were a file with the given name on d...
llvm::ErrorOr< const FileEntry * > getFile(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).
Keeps track of options that affect how file operations are performed.
std::string WorkingDir
If set, paths are resolved as if the working directory was set to the value of WorkingDir.
Represents a function declaration or definition.
Definition: Decl.h:1971
void setLazyBody(uint64_t Offset)
Definition: Decl.h:2302
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4652
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4896
Wrapper for source info for functions.
Definition: TypeLoc.h:1428
unsigned getNumParams() const
Definition: TypeLoc.h:1500
void setLocalRangeBegin(SourceLocation L)
Definition: TypeLoc.h:1448
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1464
void setParam(unsigned i, ParmVarDecl *VD)
Definition: TypeLoc.h:1507
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1472
void setLocalRangeEnd(SourceLocation L)
Definition: TypeLoc.h:1456
void setExceptionSpecRange(SourceRange R)
Definition: TypeLoc.h:1486
static std::pair< GlobalModuleIndex *, llvm::Error > readIndex(llvm::StringRef Path)
Read a global index file for the given directory.
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
uint64_t BuildSessionTimestamp
The time in seconds when the build session started.
unsigned ImplicitModuleMaps
Implicit module maps.
std::vector< SystemHeaderPrefix > SystemHeaderPrefixes
User-specified system header prefixes.
unsigned EnablePrebuiltImplicitModules
Also search for prebuilt implicit modules in the prebuilt module cache path.
unsigned ModuleMapFileHomeIsCwd
Set the 'home directory' of a module map file to the current working directory (or the home directory...
std::string Sysroot
If non-empty, the directory to use as a "virtual system root" for include paths.
std::string ModuleCachePath
The directory used for the module cache.
std::string ModuleUserBuildPath
The directory used for a user build.
std::vector< std::string > VFSOverlayFiles
The set of user-provided virtual filesystem overlay files.
unsigned UseLibcxx
Use libc++ instead of the default libstdc++.
unsigned UseBuiltinIncludes
Include the compiler builtin includes.
unsigned UseStandardCXXIncludes
Include the system standard C++ library include search directories.
std::vector< Entry > UserEntries
User specified include entries.
std::string ResourceDir
The directory which holds the compiler resource files (builtin includes, etc.).
unsigned UseStandardSystemIncludes
Include the system standard include search directories.
unsigned ModulesValidateOncePerBuildSession
If true, skip verifying input files used by modules if the module was already verified during this bu...
unsigned DisableModuleHash
Whether we should disable the use of the hash string within the module cache.
Module * lookupModule(StringRef ModuleName, SourceLocation ImportLoc=SourceLocation(), bool AllowSearch=true, bool AllowExtraModuleMapSearch=false)
Lookup a module Search for a module with the given name.
StringRef getModuleCachePath() const
Retrieve the path to the module cache.
Definition: HeaderSearch.h:450
One of these records is kept for each identifier that is lexed.
unsigned getBuiltinID() const
Return a value indicating whether this is a builtin function.
bool isCPlusPlusOperatorKeyword() const
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
bool hadMacroDefinition() const
Returns true if this identifier was #defined to some value at any moment.
void setIsPoisoned(bool Value=true)
setIsPoisoned - Mark this identifier as poisoned.
bool isFromAST() const
Return true if the identifier in its current state was loaded from an AST file.
bool isPoisoned() const
Return true if this token has been poisoned.
bool hasRevertedTokenIDToIdentifier() const
True if revertTokenIDToIdentifier() was called.
tok::NotableIdentifierKind getNotableIdentifierID() const
void setOutOfDate(bool OOD)
Set whether the information for this identifier is out of date with respect to the external source.
tok::ObjCKeywordKind getObjCKeywordID() const
Return the Objective-C keyword ID for the this identifier.
void setObjCOrBuiltinID(unsigned ID)
void revertTokenIDToIdentifier()
Revert TokenID to tok::identifier; used for GNU libstdc++ 4.2 compatibility.
bool isOutOfDate() const
Determine whether the information for this identifier is out of date with respect to the external sou...
void setChangedSinceDeserialization()
Note that this identifier has changed since it was loaded from an AST file.
void * getFETokenInfo() const
Get and set FETokenInfo.
StringRef getName() const
Return the actual identifier string.
bool isExtensionToken() const
get/setExtension - Initialize information about whether or not this language token is an extension.
An iterator that walks over all of the known identifiers in the lookup table.
IdentifierResolver - Keeps track of shadowed decls on enclosing scopes.
void RemoveDecl(NamedDecl *D)
RemoveDecl - Unlink the decl from its shadowed decl chain.
bool tryAddTopLevelDecl(NamedDecl *D, DeclarationName Name)
Try to add the given declaration to the top level scope, if it (or a redeclaration of it) hasn't alre...
llvm::iterator_range< iterator > decls(DeclarationName Name)
Returns a range of decls with the name 'Name'.
Implements an efficient mapping from strings to IdentifierInfo nodes.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
In-memory cache for modules.
llvm::MemoryBuffer * lookupPCM(llvm::StringRef Filename) const
Get a pointer to the pCM if it exists; else nullptr.
Record the location of an inclusion directive, such as an #include or #import statement.
InclusionKind
The kind of inclusion directives known to the preprocessor.
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3342
Wrapper for source info for injected class names of class templates.
Definition: TypeLoc.h:705
void setAmpLoc(SourceLocation Loc)
Definition: TypeLoc.h:1398
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:461
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:496
SanitizerSet Sanitize
Set of enabled sanitizers.
Definition: LangOptions.h:467
CommentOptions CommentOpts
Options for parsing comments.
Definition: LangOptions.h:525
std::string OMPHostIRFile
Name of the IR file that contains the result of the OpenMP target host code generation.
Definition: LangOptions.h:539
std::vector< llvm::Triple > OMPTargetTriples
Triples of the OpenMP targets that the host code codegen should take into account in order to generat...
Definition: LangOptions.h:535
std::string CurrentModule
The name of the current module, of which the main source file is a part.
Definition: LangOptions.h:516
std::vector< std::string > ModuleFeatures
The names of any features to enable in module 'requires' decls in addition to the hard-coded list in ...
Definition: LangOptions.h:522
An UnresolvedSet-like class that might not have been loaded from the external AST source yet.
Used to hold and unique data used to represent #line information.
unsigned getLineTableFilenameID(StringRef Str)
void AddEntry(FileID FID, const std::vector< LineEntry > &Entries)
Add a new line entry that has already been encoded into the internal representation of the line table...
Record the location of a macro definition.
Encapsulates changes to the "macros namespace" (the location where the macro name became active,...
Definition: MacroInfo.h:313
void setPrevious(MacroDirective *Prev)
Set previous definition of the macro with the same name.
Definition: MacroInfo.h:351
Records the location of a macro expansion.
Encapsulates the data about a macro definition (e.g.
Definition: MacroInfo.h:39
void setUsedForHeaderGuard(bool Val)
Definition: MacroInfo.h:296
void setHasCommaPasting()
Definition: MacroInfo.h:220
void setDefinitionEndLoc(SourceLocation EndLoc)
Set the location of the last token in the macro.
Definition: MacroInfo.h:128
void setParameterList(ArrayRef< IdentifierInfo * > List, llvm::BumpPtrAllocator &PPAllocator)
Set the specified list of identifiers as the parameter list for this macro.
Definition: MacroInfo.h:166
llvm::MutableArrayRef< Token > allocateTokens(unsigned NumTokens, llvm::BumpPtrAllocator &PPAllocator)
Definition: MacroInfo.h:254
void setIsFunctionLike()
Function/Object-likeness.
Definition: MacroInfo.h:200
void setIsGNUVarargs()
Definition: MacroInfo.h:206
void setIsC99Varargs()
Varargs querying methods. This can only be set for function-like macros.
Definition: MacroInfo.h:205
void setIsUsed(bool Val)
Set the value of the IsUsed flag.
Definition: MacroInfo.h:154
void setExpansionLoc(SourceLocation Loc)
Definition: TypeLoc.h:1171
void setAttrRowOperand(Expr *e)
Definition: TypeLoc.h:1927
void setAttrColumnOperand(Expr *e)
Definition: TypeLoc.h:1933
void setAttrOperandParensRange(SourceRange range)
Definition: TypeLoc.h:1942
void setAttrNameLoc(SourceLocation loc)
Definition: TypeLoc.h:1921
Wrapper for source info for member pointers.
Definition: TypeLoc.h:1332
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1338
void setClassTInfo(TypeSourceInfo *TI)
Definition: TypeLoc.h:1350
void addLinkAsDependency(Module *Mod)
Make module to use export_as as the link dependency name if enough information is available or add it...
Definition: ModuleMap.cpp:69
std::pair< Module *, bool > findOrCreateModule(StringRef Name, Module *Parent, bool IsFramework, bool IsExplicit)
Find a new module or submodule, or create it if it does not already exist.
Definition: ModuleMap.cpp:851
void setUmbrellaDirAsWritten(Module *Mod, DirectoryEntryRef UmbrellaDir, const Twine &NameAsWritten, const Twine &PathRelativeToRootModuleDirectory)
Sets the umbrella directory of the given module to the given directory.
Definition: ModuleMap.cpp:1201
void setUmbrellaHeaderAsWritten(Module *Mod, FileEntryRef UmbrellaHeader, const Twine &NameAsWritten, const Twine &PathRelativeToRootModuleDirectory)
Sets the umbrella header of the given module to the given header.
Definition: ModuleMap.cpp:1186
void resolveLinkAsDependencies(Module *Mod)
Use PendingLinkAsModule information to mark top level link names that are going to be replaced by exp...
Definition: ModuleMap.cpp:58
ModuleHeaderRole
Flags describing the role of a module header.
Definition: ModuleMap.h:127
void addHeader(Module *Mod, Module::Header Header, ModuleHeaderRole Role, bool Imported=false)
Adds this header to the given module.
Definition: ModuleMap.cpp:1282
Describes a module or submodule.
Definition: Module.h:105
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition: Module.h:675
void addRequirement(StringRef Feature, bool RequiredState, const LangOptions &LangOpts, const TargetInfo &Target)
Add the given feature requirement to the list of features required by this module.
Definition: Module.cpp:319
unsigned InferSubmodules
Whether we should infer submodules for this module based on the headers.
Definition: Module.h:349
std::vector< std::string > ConfigMacros
The set of "configuration macros", which are macros that (intentionally) change how this module is bu...
Definition: Module.h:471
unsigned IsUnimportable
Whether this module has declared itself unimportable, either because it's missing a requirement from ...
Definition: Module.h:304
NameVisibilityKind NameVisibility
The visibility of names within this particular module.
Definition: Module.h:394
NameVisibilityKind
Describes the visibility of the various names within a particular module.
Definition: Module.h:386
@ Hidden
All of the names in this module are hidden.
Definition: Module.h:388
@ AllVisible
All of the names in this module are visible.
Definition: Module.h:390
SourceLocation DefinitionLoc
The location of the module definition.
Definition: Module.h:111
SmallVector< UnresolvedHeaderDirective, 1 > MissingHeaders
Headers that are mentioned in the module map file but could not be found on the file system.
Definition: Module.h:285
ModuleKind Kind
The kind of this module.
Definition: Module.h:150
void addTopHeaderFilename(StringRef Filename)
Add a top-level header filename associated with this module.
Definition: Module.h:715
bool isUnimportable() const
Determine whether this module has been declared unimportable.
Definition: Module.h:505
void setASTFile(OptionalFileEntryRef File)
Set the serialized AST file for the top-level module of this module.
Definition: Module.h:685
unsigned IsSystem
Whether this is a "system" module (which assumes that all headers in it are system headers).
Definition: Module.h:332
std::string Name
The name of this module.
Definition: Module.h:108
unsigned IsExternC
Whether this is an 'extern "C"' module (which implicitly puts all headers in it within an 'extern "C"...
Definition: Module.h:338
unsigned ModuleMapIsPrivate
Whether this module came from a "private" module map, found next to a regular (public) module map.
Definition: Module.h:377
llvm::SmallVector< LinkLibrary, 2 > LinkLibraries
The set of libraries or frameworks to link against when an entity from this module is used.
Definition: Module.h:463
SmallVector< UnresolvedExportDecl, 2 > UnresolvedExports
The set of export declarations that have yet to be resolved.
Definition: Module.h:432
std::optional< Header > getUmbrellaHeaderAsWritten() const
Retrieve the umbrella header as written.
Definition: Module.h:699
SmallVector< Requirement, 2 > Requirements
The set of language features required to use this module.
Definition: Module.h:295
OptionalDirectoryEntryRef Directory
The build directory of this module.
Definition: Module.h:159
unsigned NamedModuleHasInit
Whether this C++20 named modules doesn't need an initializer.
Definition: Module.h:382
unsigned ConfigMacrosExhaustive
Whether the set of configuration macros is exhaustive.
Definition: Module.h:367
std::string PresumedModuleMapFile
The presumed file name for the module map defining this module.
Definition: Module.h:163
ASTFileSignature Signature
The module signature.
Definition: Module.h:169
unsigned InferExportWildcard
Whether, when inferring submodules, the inferr submodules should export all modules they import (e....
Definition: Module.h:359
void getExportedModules(SmallVectorImpl< Module * > &Exported) const
Appends this module's list of exported modules to Exported.
Definition: Module.cpp:402
std::vector< UnresolvedConflict > UnresolvedConflicts
The list of conflicts for which the module-id has not yet been resolved.
Definition: Module.h:484
unsigned IsFromModuleFile
Whether this module was loaded from a module file.
Definition: Module.h:319
llvm::PointerIntPair< Module *, 1, bool > ExportDecl
Describes an exported module.
Definition: Module.h:411
std::optional< DirectoryName > getUmbrellaDirAsWritten() const
Retrieve the umbrella directory as written.
Definition: Module.h:691
std::string ExportAsModule
The module through which entities defined in this module will eventually be exposed,...
Definition: Module.h:179
unsigned IsAvailable
Whether this module is available in the current translation unit.
Definition: Module.h:315
unsigned InferExplicitSubmodules
Whether, when inferring submodules, the inferred submodules should be explicit.
Definition: Module.h:354
OptionalFileEntryRef getASTFile() const
The serialized AST file for this module, if one was created.
Definition: Module.h:680
std::vector< Conflict > Conflicts
The list of conflicts.
Definition: Module.h:496
This represents a decl that may have a name.
Definition: Decl.h:249
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
Represents a C++ namespace alias.
Definition: DeclCXX.h:3120
Represent a C++ namespace.
Definition: Decl.h:547
Class that aids in the construction of nested-name-specifiers along with source-location information ...
A C++ nested-name-specifier augmented with source location information.
@ NamespaceAlias
A namespace alias, stored as a NamespaceAliasDecl*.
@ TypeSpec
A type, stored as a Type*.
@ TypeSpecWithTemplate
A type that was preceded by the 'template' keyword, stored as a Type*.
@ Super
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Identifier
An identifier, stored as an IdentifierInfo*.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace, stored as a NamespaceDecl*.
static std::string getOwningModuleNameForDiagnostic(const Decl *D)
Get the best name we know for the module that owns the given declaration, or an empty string if the d...
This represents 'acq_rel' clause in the '#pragma omp atomic|flush' directives.
This represents 'acquire' clause in the '#pragma omp atomic|flush' directives.
This represents clause 'affinity' in the '#pragma omp task'-based directives.
static OMPAffinityClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N locator items.
This represents the 'align' clause in the '#pragma omp allocate' directive.
Definition: OpenMPClause.h:388
This represents clause 'aligned' in the '#pragma omp ...' directives.
static OMPAlignedClause * CreateEmpty(const ASTContext &C, unsigned NumVars)
Creates an empty clause with the place for NumVars variables.
This represents clause 'allocate' in the '#pragma omp ...' directives.
Definition: OpenMPClause.h:432
static OMPAllocateClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents 'allocator' clause in the '#pragma omp ...' directive.
Definition: OpenMPClause.h:354
This represents 'at' clause in the '#pragma omp error' directive.
This represents 'atomic_default_mem_order' clause in the '#pragma omp requires' directive.
This represents 'bind' clause in the '#pragma omp ...' directives.
static OMPBindClause * CreateEmpty(const ASTContext &C)
Build an empty 'bind' clause.
This represents 'capture' clause in the '#pragma omp atomic' directive.
Contains data for OpenMP directives: clauses, children expressions/statements (helpers for codegen) a...
void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C)
OMPClauseReader(ASTRecordReader &Record)
OMPClause * readClause()
void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C)
RetTy Visit(PTR(OMPClause) S)
Class that handles post-update expression for some clauses, like 'lastprivate', 'reduction' etc.
Definition: OpenMPClause.h:233
Class that handles pre-initialization statement for some clauses, like 'shedule', 'firstprivate' etc.
Definition: OpenMPClause.h:195
This is a basic class for representing single OpenMP clause.
Definition: OpenMPClause.h:55
This represents 'collapse' clause in the '#pragma omp ...' directive.
Definition: OpenMPClause.h:977
This represents 'compare' clause in the '#pragma omp atomic' directive.
This represents clause 'copyin' in the '#pragma omp ...' directives.
static OMPCopyinClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
This represents clause 'copyprivate' in the '#pragma omp ...' directives.
static OMPCopyprivateClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
This represents 'default' clause in the '#pragma omp ...' directive.
This represents 'defaultmap' clause in the '#pragma omp ...' directive.
This represents implicit clause 'depend' for the '#pragma omp task' directive.
static OMPDependClause * CreateEmpty(const ASTContext &C, unsigned N, unsigned NumLoops)
Creates an empty clause with N variables.
This represents implicit clause 'depobj' for the '#pragma omp depobj' directive.
static OMPDepobjClause * CreateEmpty(const ASTContext &C)
Creates an empty clause.
This represents 'destroy' clause in the '#pragma omp depobj' directive or the '#pragma omp interop' d...
This represents 'detach' clause in the '#pragma omp task' directive.
This represents 'device' clause in the '#pragma omp ...' directive.
This represents 'dist_schedule' clause in the '#pragma omp ...' directive.
This represents the 'doacross' clause for the '#pragma omp ordered' directive.
static OMPDoacrossClause * CreateEmpty(const ASTContext &C, unsigned N, unsigned NumLoops)
Creates an empty clause with N expressions.
This represents 'dynamic_allocators' clause in the '#pragma omp requires' directive.
This represents clause 'exclusive' in the '#pragma omp scan' directive.
static OMPExclusiveClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents 'fail' clause in the '#pragma omp atomic' directive.
This represents 'filter' clause in the '#pragma omp ...' directive.
This represents 'final' clause in the '#pragma omp ...' directive.
Definition: OpenMPClause.h:630
This represents clause 'firstprivate' in the '#pragma omp ...' directives.
static OMPFirstprivateClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents implicit clause 'flush' for the '#pragma omp flush' directive.
static OMPFlushClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
This represents clause 'from' in the '#pragma omp ...' directives.
static OMPFromClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
Representation of the 'full' clause of the '#pragma omp unroll' directive.
Definition: OpenMPClause.h:879
static OMPFullClause * CreateEmpty(const ASTContext &C)
Build an empty 'full' AST node for deserialization.
This represents 'grainsize' clause in the '#pragma omp ...' directive.
This represents clause 'has_device_ptr' in the '#pragma omp ...' directives.
static OMPHasDeviceAddrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
This represents 'hint' clause in the '#pragma omp ...' directive.
This represents 'if' clause in the '#pragma omp ...' directive.
Definition: OpenMPClause.h:527
This represents clause 'in_reduction' in the '#pragma omp task' directives.
static OMPInReductionClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents clause 'inclusive' in the '#pragma omp scan' directive.
static OMPInclusiveClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents the 'init' clause in '#pragma omp ...' directives.
static OMPInitClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N expressions.
This represents clause 'is_device_ptr' in the '#pragma omp ...' directives.
static OMPIsDevicePtrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
This represents clause 'lastprivate' in the '#pragma omp ...' directives.
static OMPLastprivateClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents clause 'linear' in the '#pragma omp ...' directives.
static OMPLinearClause * CreateEmpty(const ASTContext &C, unsigned NumVars)
Creates an empty clause with the place for NumVars variables.
This represents clause 'map' in the '#pragma omp ...' directives.
static OMPMapClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars original expressions, NumUniqueDeclarations declar...
This represents 'mergeable' clause in the '#pragma omp ...' directive.
This represents 'message' clause in the '#pragma omp error' directive.
This represents 'nocontext' clause in the '#pragma omp ...' directive.
This represents 'nogroup' clause in the '#pragma omp ...' directive.
This represents clause 'nontemporal' in the '#pragma omp ...' directives.
static OMPNontemporalClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents 'novariants' clause in the '#pragma omp ...' directive.
This represents 'nowait' clause in the '#pragma omp ...' directive.
This represents 'num_tasks' clause in the '#pragma omp ...' directive.
This represents 'num_teams' clause in the '#pragma omp ...' directive.
This represents 'num_threads' clause in the '#pragma omp ...' directive.
Definition: OpenMPClause.h:676
This represents 'order' clause in the '#pragma omp ...' directive.
This represents 'ordered' clause in the '#pragma omp ...' directive.
static OMPOrderedClause * CreateEmpty(const ASTContext &C, unsigned NumLoops)
Build an empty clause.
Representation of the 'partial' clause of the '#pragma omp unroll' directive.
Definition: OpenMPClause.h:907
static OMPPartialClause * CreateEmpty(const ASTContext &C)
Build an empty 'partial' AST node for deserialization.
This represents 'priority' clause in the '#pragma omp ...' directive.
This represents clause 'private' in the '#pragma omp ...' directives.
static OMPPrivateClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents 'proc_bind' clause in the '#pragma omp ...' directive.
This represents 'read' clause in the '#pragma omp atomic' directive.
This represents clause 'reduction' in the '#pragma omp ...' directives.
static OMPReductionClause * CreateEmpty(const ASTContext &C, unsigned N, OpenMPReductionClauseModifier Modifier)
Creates an empty clause with the place for N variables.
This represents 'relaxed' clause in the '#pragma omp atomic' directives.
This represents 'release' clause in the '#pragma omp atomic|flush' directives.
This represents 'reverse_offload' clause in the '#pragma omp requires' directive.
This represents 'simd' clause in the '#pragma omp ...' directive.
This represents 'safelen' clause in the '#pragma omp ...' directive.
Definition: OpenMPClause.h:721
This represents 'schedule' clause in the '#pragma omp ...' directive.
This represents 'seq_cst' clause in the '#pragma omp atomic' directive.
This represents 'severity' clause in the '#pragma omp error' directive.
This represents clause 'shared' in the '#pragma omp ...' directives.
static OMPSharedClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
This represents 'simdlen' clause in the '#pragma omp ...' directive.
Definition: OpenMPClause.h:756
This represents the 'sizes' clause in the '#pragma omp tile' directive.
Definition: OpenMPClause.h:788
static OMPSizesClause * CreateEmpty(const ASTContext &C, unsigned NumSizes)
Build an empty 'sizes' AST node for deserialization.
This represents clause 'task_reduction' in the '#pragma omp taskgroup' directives.
static OMPTaskReductionClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents 'thread_limit' clause in the '#pragma omp ...' directive.
This represents 'threads' clause in the '#pragma omp ...' directive.
This represents clause 'to' in the '#pragma omp ...' directives.
static OMPToClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
Helper data structure representing the traits in a match clause of an declare variant or metadirectiv...
llvm::SmallVector< OMPTraitSet, 2 > Sets
The outermost level of selector sets.
This represents 'unified_address' clause in the '#pragma omp requires' directive.
This represents 'unified_shared_memory' clause in the '#pragma omp requires' directive.
This represents 'untied' clause in the '#pragma omp ...' directive.
This represents 'update' clause in the '#pragma omp atomic' directive.
static OMPUpdateClause * CreateEmpty(const ASTContext &C, bool IsExtended)
Creates an empty clause with the place for N variables.
This represents the 'use' clause in '#pragma omp ...' directives.
This represents clause 'use_device_addr' in the '#pragma omp ...' directives.
static OMPUseDeviceAddrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
This represents clause 'use_device_ptr' in the '#pragma omp ...' directives.
static OMPUseDevicePtrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
This represents clause 'uses_allocators' in the '#pragma omp target'-based directives.
static OMPUsesAllocatorsClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N allocators.
This represents 'weak' clause in the '#pragma omp atomic' directives.
This represents 'write' clause in the '#pragma omp atomic' directive.
This represents 'ompx_attribute' clause in a directive that might generate an outlined function.
This represents 'ompx_bare' clause in the '#pragma omp target teams ...' directive.
This represents 'ompx_dyn_cgroup_mem' clause in the '#pragma omp target ...' directive.
method_range methods() const
Definition: DeclObjC.h:1015
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
Wrapper for source info for ObjC interfaces.
Definition: TypeLoc.h:1091
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1101
void setNameEndLoc(SourceLocation Loc)
Definition: TypeLoc.h:1113
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:6948
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1950
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
bool hasBody() const override
Determine whether this method has a body.
Definition: DeclObjC.h:523
Selector getSelector() const
Definition: DeclObjC.h:327
bool isInstanceMethod() const
Definition: DeclObjC.h:426
void setLazyBody(uint64_t Offset)
Definition: DeclObjC.h:528
Wraps an ObjCPointerType with source location information.
Definition: TypeLoc.h:1370
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1376
void setTypeArgsRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:984
unsigned getNumTypeArgs() const
Definition: TypeLoc.h:988
unsigned getNumProtocols() const
Definition: TypeLoc.h:1018
void setTypeArgsLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:976
void setTypeArgTInfo(unsigned i, TypeSourceInfo *TInfo)
Definition: TypeLoc.h:997
void setProtocolLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1006
void setProtocolRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1014
void setHasBaseTypeAsWritten(bool HasBaseType)
Definition: TypeLoc.h:1046
void setProtocolLoc(unsigned i, SourceLocation Loc)
Definition: TypeLoc.h:1027
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2082
The basic abstraction for the target Objective-C runtime.
Definition: ObjCRuntime.h:28
Kind
The basic Objective-C runtimes that we know about.
Definition: ObjCRuntime.h:31
ProtocolLAngleLoc, ProtocolRAngleLoc, and the source locations for protocol qualifiers are stored aft...
Definition: TypeLoc.h:772
unsigned getNumProtocols() const
Definition: TypeLoc.h:809
void setProtocolLoc(unsigned i, SourceLocation Loc)
Definition: TypeLoc.h:818
void setProtocolLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:795
void setProtocolRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:805
This is the base type for all OpenACC Clauses.
Definition: OpenACCClause.h:22
static OpenACCDefaultClause * Create(const ASTContext &C, OpenACCDefaultClauseKind K, SourceLocation BeginLoc, SourceLocation LParenLoc, SourceLocation EndLoc)
static OpenACCIfClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *ConditionExpr, SourceLocation EndLoc)
static OpenACCNumGangsClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > IntExprs, SourceLocation EndLoc)
static OpenACCNumWorkersClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
static OpenACCSelfClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *ConditionExpr, SourceLocation EndLoc)
static OpenACCVectorLengthClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
This abstract interface provides operations for unwrapping containers for serialized ASTs (precompile...
virtual llvm::StringRef ExtractPCH(llvm::MemoryBufferRef Buffer) const =0
Returns the serialized AST inside the PCH container Buffer.
ASTReaderListener implementation to validate the information of the PCH file against an initialized P...
Definition: ASTReader.h:294
bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, bool AllowCompatibleDifferences) override
Receives the target options.
Definition: ASTReader.cpp:458
void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override
Receives COUNTER value.
Definition: ASTReader.cpp:864
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
Definition: ASTReader.cpp:813
bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool Complain) override
Receives the header search options.
Definition: ASTReader.cpp:855
bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, bool AllowCompatibleDifferences) override
Receives the language options.
Definition: ASTReader.cpp:449
bool ReadDiagnosticOptions(IntrusiveRefCntPtr< DiagnosticOptions > DiagOpts, bool Complain) override
Receives the diagnostic options.
Definition: ASTReader.cpp:578
void setEllipsisLoc(SourceLocation Loc)
Definition: TypeLoc.h:2582
void setEllipsisLoc(SourceLocation Loc)
Definition: TypeLoc.h:2112
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1203
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1199
Represents a parameter to a function.
Definition: Decl.h:1761
void setKWLoc(SourceLocation Loc)
Definition: TypeLoc.h:2674
Wrapper for source info for pointers.
Definition: TypeLoc.h:1301
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1307
Base class that describes a preprocessed entity, which may be a preprocessor directive or macro expan...
Iteration over the preprocessed entities.
A record of the steps taken while preprocessing a source file, including the various preprocessing di...
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
std::vector< std::string > MacroIncludes
std::vector< std::string > Includes
ObjCXXARCStandardLibraryKind ObjCXXARCStandardLibrary
The Objective-C++ ARC standard library that we should support, by providing appropriate definitions t...
std::string PCHThroughHeader
If non-empty, the filename used in an #include directive in the primary source file (or command-line ...
bool DetailedRecord
Whether we should maintain a detailed record of all macro definitions and expansions.
std::string ImplicitPCHInclude
The implicit PCH included at the start of the translation unit, or empty.
bool AllowPCHWithDifferentModulesCachePath
When true, a PCH with modules cache path different to the current compilation will not be rejected.
bool UsePredefines
Initialize the preprocessor with the compiler and target specific predefines.
std::vector< std::pair< std::string, bool > > Macros
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:128
Module * getCurrentModule()
Retrieves the module that we're currently building, if any.
const TargetInfo & getTargetInfo() const
FileManager & getFileManager() const
PreprocessorOptions & getPreprocessorOpts() const
Retrieve the preprocessor options used to initialize this preprocessor.
HeaderSearch & getHeaderSearchInfo() const
IdentifierTable & getIdentifierTable()
const LangOptions & getLangOpts() const
void setCounterValue(unsigned V)
DiagnosticsEngine & getDiagnostics() const
A (possibly-)qualified type.
Definition: Type.h:940
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1007
Wrapper of type source information for a type with non-trivial direct qualifiers.
Definition: TypeLoc.h:289
The collection of all-type qualifiers we support.
Definition: Type.h:318
@ FastWidth
The width of the "fast" qualifier mask.
Definition: Type.h:362
@ FastMask
The fast qualifier mask.
Definition: Type.h:365
void setAmpAmpLoc(SourceLocation Loc)
Definition: TypeLoc.h:1412
Represents a struct/union/class.
Definition: Decl.h:4169
Wrapper for source info for record types.
Definition: TypeLoc.h:741
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5545
void AddDecl(Decl *D)
Definition: Scope.h:342
This table allows us to fully hide how we implement multi-keyword caching.
Selector getNullarySelector(const IdentifierInfo *ID)
Selector getSelector(unsigned NumArgs, const IdentifierInfo **IIV)
Can create any sort of selector.
Selector getUnarySelector(const IdentifierInfo *ID)
Smart pointer class that efficiently represents Objective-C method names.
llvm::DenseMap< Selector, Lists >::iterator iterator
Definition: Sema.h:11820
iterator find(Selector Sel)
Definition: Sema.h:11823
std::pair< ObjCMethodList, ObjCMethodList > Lists
Definition: Sema.h:11819
std::pair< iterator, bool > insert(std::pair< Selector, Lists > &&Val)
Definition: Sema.h:11824
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:457
GlobalMethodPool MethodPool
Method Pool - allows efficient lookup when typechecking messages to "id".
Definition: Sema.h:11840
void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method)
Add the given method to the list of globally-known methods.
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:830
void addExternalSource(ExternalSemaSource *E)
Registers an external source.
Definition: Sema.cpp:559
IdentifierResolver IdResolver
Definition: Sema.h:2537
PragmaMsStackAction
Definition: Sema.h:1192
ASTReaderListenter implementation to set SuggestedPredefines of ASTReader which is required to use a ...
Definition: ASTReader.h:321
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
Definition: ASTReader.cpp:823
This object establishes a SourceLocationSequence.
Serialized encoding of a sequence of SourceLocations.
Encodes a location in the source.
static SourceLocation getFromRawEncoding(UIntTy Encoding)
Turn a raw encoding of a SourceLocation object into a real SourceLocation.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
SourceLocation getFileLoc(SourceLocation Loc) const
Given Loc, if it is a macro location return the expansion location or the spelling location,...
void setExternalSLocEntrySource(ExternalSLocEntrySource *Source)
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
A trivial tuple used to represent a source range.
One instance of this struct is kept for every file loaded or used.
OptionalFileEntryRef ContentsEntry
References the file which the contents were actually loaded from.
std::optional< llvm::MemoryBufferRef > getBufferIfLoaded() const
Return the buffer, only if it has been loaded.
unsigned BufferOverridden
Indicates whether the buffer itself was provided to override the actual file contents.
OptionalFileEntryRef OrigEntry
Reference to the file entry representing this ContentCache.
Information about a FileID, basically just the logical file that it represents and include stack info...
void setHasLineDirectives()
Set the flag that indicates that this FileID has line table entries associated with it.
Stmt - This represents one statement.
Definition: Stmt.h:84
DiagnosticStorage * getStorage() const
Retrieve storage for this particular diagnostic.
Definition: Diagnostic.h:1160
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:864
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:857
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3585
TagDecl * getDecl() const
Definition: Type.cpp:3993
TargetOptions & getTargetOpts() const
Retrieve the target options.
Definition: TargetInfo.h:307
Options for controlling the target.
Definition: TargetOptions.h:26
std::string Triple
The name of the target triple to compile for.
Definition: TargetOptions.h:29
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
Definition: TargetOptions.h:58
std::string ABI
If given, the name of the target ABI to use.
Definition: TargetOptions.h:45
std::string TuneCPU
If given, the name of the target CPU to tune code for.
Definition: TargetOptions.h:39
std::string CPU
If given, the name of the target CPU to generate code for.
Definition: TargetOptions.h:36
std::vector< std::string > FeaturesAsWritten
The list of target specific features to enable or disable, as written on the command line.
Definition: TargetOptions.h:54
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
Represents a template argument.
Definition: TemplateBase.h:61
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:408
ArgKind
The kind of template argument we're storing.
Definition: TemplateBase.h:64
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
Definition: TemplateBase.h:89
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:97
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:78
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:67
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:82
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:1687
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1663
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1704
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1671
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1679
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:6153
Wrapper for template type parameters.
Definition: TypeLoc.h:758
Token - This structure provides full information about a lexed token.
Definition: Token.h:36
void setAnnotationEndLoc(SourceLocation L)
Definition: Token.h:150
void setLength(unsigned Len)
Definition: Token.h:141
void setKind(tok::TokenKind K)
Definition: Token.h:95
tok::TokenKind getKind() const
Definition: Token.h:94
void setLocation(SourceLocation L)
Definition: Token.h:140
bool isAnnotation() const
Return true if this is any of tok::annot_* kind tokens.
Definition: Token.h:121
void setAnnotationValue(void *val)
Definition: Token.h:238
void startToken()
Reset all flags to cleared.
Definition: Token.h:177
void setIdentifierInfo(IdentifierInfo *II)
Definition: Token.h:196
void setFlag(TokenFlags Flag)
Set the specified flag.
Definition: Token.h:244
[BoundsSafety] Represents information of declarations referenced by the arguments of the counted_by a...
Definition: Type.h:3163
void VisitArrayTypeLoc(ArrayTypeLoc)
Definition: ASTReader.cpp:6849
void VisitFunctionTypeLoc(FunctionTypeLoc)
Definition: ASTReader.cpp:6916
TypeLocReader(ASTRecordReader &Reader, LocSeq *Seq)
Definition: ASTReader.cpp:6777
RetTy Visit(TypeLoc TyLoc)
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
TypeLoc getNextTypeLoc() const
Get the next TypeLoc pointed by this TypeLoc, e.g for "int*" the TypeLoc is a PointerLoc and next Typ...
Definition: TypeLoc.h:170
bool isNull() const
Definition: TypeLoc.h:121
void setUnmodifiedTInfo(TypeSourceInfo *TI) const
Definition: TypeLoc.h:2061
A container of type source information.
Definition: Type.h:7326
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:539
The base class of the type hierarchy.
Definition: Type.h:1813
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8119
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3433
Wrapper for source info for typedefs.
Definition: TypeLoc.h:693
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2004
void setTypeofLoc(SourceLocation Loc)
Definition: TypeLoc.h:1996
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2012
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2146
void setKWLoc(SourceLocation Loc)
Definition: TypeLoc.h:2140
void setUnderlyingTInfo(TypeSourceInfo *TInfo)
Definition: TypeLoc.h:2152
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2143
Wrapper for source info for unresolved typename using decls.
Definition: TypeLoc.h:716
Wrapper for source info for types used via transparent aliases.
Definition: TypeLoc.h:682
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:706
Represents a variable declaration or definition.
Definition: Decl.h:918
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1841
Captures information about a #pragma weak directive.
Definition: Weak.h:25
A key used when looking up entities by DeclarationName.
Definition: ASTBitCodes.h:2017
unsigned getHash() const
Compute a fingerprint of this key for use in on-disk hash table.
Definition: ASTReader.cpp:1134
The input file that has been loaded from this AST file, along with bools indicating whether this was ...
Definition: ModuleFile.h:78
OptionalFileEntryRef getFile() const
Definition: ModuleFile.h:107
static InputFile getNotFound()
Definition: ModuleFile.h:101
Information about a module that has been loaded by the ASTReader.
Definition: ModuleFile.h:124
const PPEntityOffset * PreprocessedEntityOffsets
Definition: ModuleFile.h:379
serialization::IdentID BaseIdentifierID
Base identifier ID for identifiers local to this module.
Definition: ModuleFile.h:315
void * IdentifierLookupTable
A pointer to an on-disk hash table of opaque type IdentifierHashTable.
Definition: ModuleFile.h:328
serialization::DeclID BaseDeclID
Base declaration ID for declarations local to this module.
Definition: ModuleFile.h:462
void * SelectorLookupTable
A pointer to an on-disk hash table of opaque type ASTSelectorLookupTable.
Definition: ModuleFile.h:442
const UnderalignedInt64 * TypeOffsets
Offset of each type within the bitstream, indexed by the type ID, or the representation of a Type*.
Definition: ModuleFile.h:498
std::vector< std::unique_ptr< ModuleFileExtensionReader > > ExtensionReaders
The list of extension readers that are attached to this module file.
Definition: ModuleFile.h:240
SourceLocation DirectImportLoc
The source location where the module was explicitly or implicitly imported in the local translation u...
Definition: ModuleFile.h:230
StringRef Data
The serialized bitstream data for this file.
Definition: ModuleFile.h:216
const serialization::ObjCCategoriesInfo * ObjCCategoriesMap
Array of category list location information within this module file, sorted by the definition ID.
Definition: ModuleFile.h:482
ContinuousRangeMap< uint32_t, int, 2 > PreprocessedEntityRemap
Remapping table for preprocessed entity IDs in this module.
Definition: ModuleFile.h:377
int SLocEntryBaseID
The base ID in the source manager's view of this module.
Definition: ModuleFile.h:285
serialization::PreprocessedEntityID BasePreprocessedEntityID
Base preprocessed entity ID for preprocessed entities local to this module.
Definition: ModuleFile.h:374
serialization::TypeID BaseTypeIndex
Base type ID for types local to this module as represented in the global type ID space.
Definition: ModuleFile.h:502
unsigned LocalNumObjCCategoriesInMap
The number of redeclaration info entries in ObjCCategoriesMap.
Definition: ModuleFile.h:485
uint64_t MacroOffsetsBase
Base file offset for the offsets in MacroOffsets.
Definition: ModuleFile.h:345
const llvm::support::unaligned_uint64_t * InputFileOffsets
Relative offsets for all of the input file entries in the AST file.
Definition: ModuleFile.h:255
std::vector< unsigned > PreloadIdentifierOffsets
Offsets of identifiers that we're going to preload within IdentifierTableData.
Definition: ModuleFile.h:332
unsigned LocalNumIdentifiers
The number of identifiers in this AST file.
Definition: ModuleFile.h:305
llvm::BitstreamCursor DeclsCursor
DeclsCursor - This is a cursor to the start of the DECLTYPES_BLOCK block.
Definition: ModuleFile.h:449
const unsigned char * IdentifierTableData
Actual data for the on-disk hash table of identifiers.
Definition: ModuleFile.h:324
uint64_t SLocEntryOffsetsBase
Base file offset for the offsets in SLocEntryOffsets.
Definition: ModuleFile.h:292
llvm::BitstreamCursor InputFilesCursor
The cursor to the start of the input-files block.
Definition: ModuleFile.h:249
std::vector< InputFile > InputFilesLoaded
The input files that have been loaded from this AST file.
Definition: ModuleFile.h:258
serialization::SelectorID BaseSelectorID
Base selector ID for selectors local to this module.
Definition: ModuleFile.h:427
llvm::SetVector< ModuleFile * > ImportedBy
List of modules which depend on this module.
Definition: ModuleFile.h:513
const char * HeaderFileInfoTableData
Actual data for the on-disk hash table of header file information.
Definition: ModuleFile.h:398
SourceLocation ImportLoc
The source location where this module was first imported.
Definition: ModuleFile.h:233
ContinuousRangeMap< uint32_t, int, 2 > TypeRemap
Remapping table for type IDs in this module.
Definition: ModuleFile.h:505
const uint32_t * SLocEntryOffsets
Offsets for all of the source location entries in the AST file.
Definition: ModuleFile.h:296
llvm::BitstreamCursor MacroCursor
The cursor to the start of the preprocessor block, which stores all of the macro definitions.
Definition: ModuleFile.h:338
FileID OriginalSourceFileID
The file ID for the original source file that was used to build this AST file.
Definition: ModuleFile.h:162
FileEntryRef File
The file entry for the module file.
Definition: ModuleFile.h:179
std::string ActualOriginalSourceFileName
The actual original source file name that was used to build this AST file.
Definition: ModuleFile.h:158
ContinuousRangeMap< uint32_t, int, 2 > IdentifierRemap
Remapping table for identifier IDs in this module.
Definition: ModuleFile.h:318
const LocalDeclID * FileSortedDecls
Array of file-level DeclIDs sorted by file.
Definition: ModuleFile.h:477
uint64_t PreprocessorDetailStartOffset
The offset of the start of the preprocessor detail cursor.
Definition: ModuleFile.h:370
std::vector< InputFileInfo > InputFileInfosLoaded
The input file infos that have been loaded from this AST file.
Definition: ModuleFile.h:261
unsigned LocalNumSubmodules
The number of submodules in this module.
Definition: ModuleFile.h:407
SourceLocation FirstLoc
The first source location in this module.
Definition: ModuleFile.h:236
ASTFileSignature ASTBlockHash
The signature of the AST block of the module file, this can be used to unique module files based on A...
Definition: ModuleFile.h:187
uint64_t SourceManagerBlockStartOffset
The bit offset to the start of the SOURCE_MANAGER_BLOCK.
Definition: ModuleFile.h:279
bool DidReadTopLevelSubmodule
Whether the top-level module has been read from the AST file.
Definition: ModuleFile.h:176
std::string OriginalSourceFileName
The original source file name that was used to build the primary AST file, which may have been modifi...
Definition: ModuleFile.h:154
bool isModule() const
Is this a module file for a module (rather than a PCH or similar).
Definition: ModuleFile.h:523
bool HasTimestamps
Whether timestamps are included in this module file.
Definition: ModuleFile.h:173
uint64_t InputFilesOffsetBase
Absolute offset of the start of the input-files block.
Definition: ModuleFile.h:252
llvm::BitstreamCursor SLocEntryCursor
Cursor used to read source location entries.
Definition: ModuleFile.h:276
bool RelocatablePCH
Whether this precompiled header is a relocatable PCH file.
Definition: ModuleFile.h:167
const uint32_t * SelectorOffsets
Offsets into the selector lookup table's data array where each selector resides.
Definition: ModuleFile.h:424
unsigned LocalNumSLocEntries
The number of source location entries in this AST file.
Definition: ModuleFile.h:282
void * HeaderFileInfoTable
The on-disk hash table that contains information about each of the header files.
Definition: ModuleFile.h:402
llvm::BitstreamCursor Stream
The main bitstream cursor for the main block.
Definition: ModuleFile.h:219
serialization::SubmoduleID BaseSubmoduleID
Base submodule ID for submodules local to this module.
Definition: ModuleFile.h:410
uint64_t SizeInBits
The size of this file, in bits.
Definition: ModuleFile.h:207
uint64_t GlobalBitOffset
The global bit offset (or base) of this module.
Definition: ModuleFile.h:210
bool StandardCXXModule
Whether this module file is a standard C++ module.
Definition: ModuleFile.h:170
unsigned LocalNumTypes
The number of types in this AST file.
Definition: ModuleFile.h:494
StringRef ModuleOffsetMap
The module offset map data for this file.
Definition: ModuleFile.h:244
const PPSkippedRange * PreprocessedSkippedRangeOffsets
Definition: ModuleFile.h:385
std::string FileName
The file name of the module file.
Definition: ModuleFile.h:139
uint64_t InputFilesValidationTimestamp
If non-zero, specifies the time when we last validated input files.
Definition: ModuleFile.h:271
llvm::BitstreamCursor PreprocessorDetailCursor
The cursor to the start of the (optional) detailed preprocessing record block.
Definition: ModuleFile.h:367
SourceLocation::UIntTy SLocEntryBaseOffset
The base offset in the source manager's view of this module.
Definition: ModuleFile.h:288
const DeclOffset * DeclOffsets
Offset of each declaration within the bitstream, indexed by the declaration ID (-1).
Definition: ModuleFile.h:459
std::string getTimestampFilename() const
Definition: ModuleFile.h:147
uint64_t MacroStartOffset
The offset of the start of the set of defined macros.
Definition: ModuleFile.h:361
ASTFileSignature Signature
The signature of the module file, which may be used instead of the size and modification time to iden...
Definition: ModuleFile.h:183
unsigned LocalNumMacros
The number of macros in this AST file.
Definition: ModuleFile.h:341
ContinuousRangeMap< serialization::DeclID, int, 2 > DeclRemap
Remapping table for declaration IDs in this module.
Definition: ModuleFile.h:465
const unsigned char * SelectorLookupTableData
A pointer to the character data that comprises the selector table.
Definition: ModuleFile.h:435
void dump()
Dump debugging output for this module.
Definition: ModuleFile.cpp:47
unsigned LocalNumDecls
The number of declarations in this AST file.
Definition: ModuleFile.h:455
unsigned LocalNumHeaderFileInfos
The number of local HeaderFileInfo structures.
Definition: ModuleFile.h:391
llvm::BitVector SearchPathUsage
The bit vector denoting usage of each header search entry (true = used).
Definition: ModuleFile.h:190
ContinuousRangeMap< SourceLocation::UIntTy, SourceLocation::IntTy, 2 > SLocRemap
Remapping table for source locations in this module.
Definition: ModuleFile.h:300
unsigned Generation
The generation of which this module file is a part.
Definition: ModuleFile.h:200
const uint32_t * IdentifierOffsets
Offsets into the identifier table data.
Definition: ModuleFile.h:312
ContinuousRangeMap< uint32_t, int, 2 > SelectorRemap
Remapping table for selector IDs in this module.
Definition: ModuleFile.h:430
llvm::DenseMap< ModuleFile *, serialization::DeclID > GlobalToLocalDeclIDs
Mapping from the module files that this module file depends on to the base declaration ID for that mo...
Definition: ModuleFile.h:474
ContinuousRangeMap< uint32_t, int, 2 > MacroRemap
Remapping table for macro IDs in this module.
Definition: ModuleFile.h:358
const uint32_t * MacroOffsets
Offsets of macros in the preprocessor block.
Definition: ModuleFile.h:352
uint64_t ASTBlockStartOffset
The bit offset of the AST block of this module.
Definition: ModuleFile.h:213
ContinuousRangeMap< uint32_t, int, 2 > SubmoduleRemap
Remapping table for submodule IDs in this module.
Definition: ModuleFile.h:413
llvm::BitVector VFSUsage
The bit vector denoting usage of each VFS entry (true = used).
Definition: ModuleFile.h:193
uint64_t DeclsBlockStartOffset
The offset to the start of the DECLTYPES_BLOCK block.
Definition: ModuleFile.h:452
SmallVector< uint64_t, 8 > PragmaDiagMappings
Diagnostic IDs and their mappings that the user changed.
Definition: ModuleFile.h:510
unsigned BasePreprocessedSkippedRangeID
Base ID for preprocessed skipped ranges local to this module.
Definition: ModuleFile.h:383
unsigned LocalNumSelectors
The number of selectors new to this file.
Definition: ModuleFile.h:420
ModuleKind Kind
The type of this module.
Definition: ModuleFile.h:136
std::string ModuleName
The name of the module.
Definition: ModuleFile.h:142
serialization::MacroID BaseMacroID
Base macro ID for macros local to this module.
Definition: ModuleFile.h:355
SmallVector< uint64_t, 1 > ObjCCategories
The Objective-C category lists for categories known to this module.
Definition: ModuleFile.h:489
std::string BaseDirectory
The base directory of the module.
Definition: ModuleFile.h:145
Manages the set of modules loaded by an AST reader.
Definition: ModuleManager.h:47
ModuleFile & getPrimaryModule()
Returns the primary module associated with the manager, that is, the first module loaded.
AddModuleResult
The result of attempting to add a new module.
@ Missing
The module file is missing.
@ OutOfDate
The module file is out-of-date.
@ NewlyLoaded
The module file was just loaded in response to this call.
@ AlreadyLoaded
The module file had already been loaded.
llvm::iterator_range< SmallVectorImpl< ModuleFile * >::const_iterator > pch_modules() const
A range covering the PCH and preamble module files loaded.
ModuleReverseIterator rbegin()
Reverse iterator to traverse all loaded modules.
void visit(llvm::function_ref< bool(ModuleFile &M)> Visitor, llvm::SmallPtrSetImpl< ModuleFile * > *ModuleFilesHit=nullptr)
Visit each of the modules.
unsigned size() const
Number of modules loaded.
ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel, unsigned PriorGeneration)
Definition: ASTReader.cpp:8496
ArrayRef< ObjCMethodDecl * > getInstanceMethods() const
Retrieve the instance methods found by this visitor.
Definition: ASTReader.cpp:8538
ArrayRef< ObjCMethodDecl * > getFactoryMethods() const
Retrieve the instance methods found by this visitor.
Definition: ASTReader.cpp:8543
static TypeIdx fromTypeID(TypeID ID)
Definition: ASTBitCodes.h:96
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
Definition: ASTReader.cpp:978
static hash_value_type ComputeHash(const internal_key_type &a)
Definition: ASTReader.cpp:973
static internal_key_type ReadKey(const unsigned char *d, unsigned n)
Definition: ASTReader.cpp:983
Class that performs lookup for an identifier stored in an AST file.
IdentID ReadIdentifierID(const unsigned char *d)
Definition: ASTReader.cpp:1007
data_type ReadData(const internal_key_type &k, const unsigned char *d, unsigned DataLen)
Definition: ASTReader.cpp:1023
Class that performs lookup for a selector's entries in the global method pool stored in an AST file.
internal_key_type ReadKey(const unsigned char *d, unsigned)
Definition: ASTReader.cpp:913
data_type ReadData(Selector, const unsigned char *d, unsigned DataLen)
Definition: ASTReader.cpp:935
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
Definition: ASTReader.cpp:908
static hash_value_type ComputeHash(Selector Sel)
Definition: ASTReader.cpp:903
Trait class used to search the on-disk hash table containing all of the header search information.
PredefinedTypeIDs
Predefined type IDs.
Definition: ASTBitCodes.h:849
CtorInitializerType
The different kinds of data that can occur in a CtorInitializer.
Definition: ASTBitCodes.h:1973
const unsigned NUM_PREDEF_TYPE_IDS
The number of predefined type IDs that are reserved for the PREDEF_TYPE_* constants.
Definition: ASTBitCodes.h:1103
const unsigned NumSpecialTypeIDs
The number of special type IDs.
Definition: ASTBitCodes.h:1158
TypeCode
Record codes for each kind of type.
Definition: ASTBitCodes.h:1117
@ PREDEF_TYPE_LONG_ACCUM_ID
The 'long _Accum' type.
Definition: ASTBitCodes.h:995
@ PREDEF_TYPE_SAMPLER_ID
OpenCL sampler type.
Definition: ASTBitCodes.h:968
@ PREDEF_TYPE_INT128_ID
The '__int128_t' type.
Definition: ASTBitCodes.h:917
@ PREDEF_TYPE_CHAR32_ID
The C++ 'char32_t' type.
Definition: ASTBitCodes.h:926
@ PREDEF_TYPE_SAT_SHORT_ACCUM_ID
The '_Sat short _Accum' type.
Definition: ASTBitCodes.h:1025
@ PREDEF_TYPE_IBM128_ID
The '__ibm128' type.
Definition: ASTBitCodes.h:1073
@ PREDEF_TYPE_SHORT_FRACT_ID
The 'short _Fract' type.
Definition: ASTBitCodes.h:1007
@ PREDEF_TYPE_AUTO_RREF_DEDUCT
The "auto &&" deduction type.
Definition: ASTBitCodes.h:947
@ PREDEF_TYPE_BOUND_MEMBER
The placeholder type for bound member functions.
Definition: ASTBitCodes.h:941
@ PREDEF_TYPE_LONGLONG_ID
The (signed) 'long long' type.
Definition: ASTBitCodes.h:896
@ PREDEF_TYPE_FRACT_ID
The '_Fract' type.
Definition: ASTBitCodes.h:1010
@ PREDEF_TYPE_ARC_UNBRIDGED_CAST
ARC's unbridged-cast placeholder type.
Definition: ASTBitCodes.h:953
@ PREDEF_TYPE_USHORT_FRACT_ID
The 'unsigned short _Fract' type.
Definition: ASTBitCodes.h:1016
@ PREDEF_TYPE_SAT_ULONG_FRACT_ID
The '_Sat unsigned long _Fract' type.
Definition: ASTBitCodes.h:1058
@ PREDEF_TYPE_BOOL_ID
The 'bool' or '_Bool' type.
Definition: ASTBitCodes.h:857
@ PREDEF_TYPE_SAT_LONG_ACCUM_ID
The '_Sat long _Accum' type.
Definition: ASTBitCodes.h:1031
@ PREDEF_TYPE_SAT_LONG_FRACT_ID
The '_Sat long _Fract' type.
Definition: ASTBitCodes.h:1049
@ PREDEF_TYPE_SAT_SHORT_FRACT_ID
The '_Sat short _Fract' type.
Definition: ASTBitCodes.h:1043
@ PREDEF_TYPE_CHAR_U_ID
The 'char' type, when it is unsigned.
Definition: ASTBitCodes.h:860
@ PREDEF_TYPE_RESERVE_ID_ID
OpenCL reserve_id type.
Definition: ASTBitCodes.h:974
@ PREDEF_TYPE_SAT_ACCUM_ID
The '_Sat _Accum' type.
Definition: ASTBitCodes.h:1028
@ PREDEF_TYPE_BUILTIN_FN
The placeholder type for builtin functions.
Definition: ASTBitCodes.h:959
@ PREDEF_TYPE_SHORT_ACCUM_ID
The 'short _Accum' type.
Definition: ASTBitCodes.h:989
@ PREDEF_TYPE_FLOAT_ID
The 'float' type.
Definition: ASTBitCodes.h:899
@ PREDEF_TYPE_QUEUE_ID
OpenCL queue type.
Definition: ASTBitCodes.h:971
@ PREDEF_TYPE_INT_ID
The (signed) 'int' type.
Definition: ASTBitCodes.h:890
@ PREDEF_TYPE_OBJC_SEL
The ObjC 'SEL' type.
Definition: ASTBitCodes.h:935
@ PREDEF_TYPE_BFLOAT16_ID
The '__bf16' type.
Definition: ASTBitCodes.h:1070
@ PREDEF_TYPE_WCHAR_ID
The C++ 'wchar_t' type.
Definition: ASTBitCodes.h:884
@ PREDEF_TYPE_UCHAR_ID
The 'unsigned char' type.
Definition: ASTBitCodes.h:863
@ PREDEF_TYPE_UACCUM_ID
The 'unsigned _Accum' type.
Definition: ASTBitCodes.h:1001
@ PREDEF_TYPE_SCHAR_ID
The 'signed char' type.
Definition: ASTBitCodes.h:881
@ PREDEF_TYPE_CHAR_S_ID
The 'char' type, when it is signed.
Definition: ASTBitCodes.h:878
@ PREDEF_TYPE_NULLPTR_ID
The type of 'nullptr'.
Definition: ASTBitCodes.h:920
@ PREDEF_TYPE_ULONG_FRACT_ID
The 'unsigned long _Fract' type.
Definition: ASTBitCodes.h:1022
@ PREDEF_TYPE_FLOAT16_ID
The '_Float16' type.
Definition: ASTBitCodes.h:983
@ PREDEF_TYPE_UINT_ID
The 'unsigned int' type.
Definition: ASTBitCodes.h:869
@ PREDEF_TYPE_FLOAT128_ID
The '__float128' type.
Definition: ASTBitCodes.h:980
@ PREDEF_TYPE_OBJC_ID
The ObjC 'id' type.
Definition: ASTBitCodes.h:929
@ PREDEF_TYPE_CHAR16_ID
The C++ 'char16_t' type.
Definition: ASTBitCodes.h:923
@ PREDEF_TYPE_ARRAY_SECTION
The placeholder type for an array section.
Definition: ASTBitCodes.h:977
@ PREDEF_TYPE_ULONGLONG_ID
The 'unsigned long long' type.
Definition: ASTBitCodes.h:875
@ PREDEF_TYPE_SAT_UFRACT_ID
The '_Sat unsigned _Fract' type.
Definition: ASTBitCodes.h:1055
@ PREDEF_TYPE_USHORT_ID
The 'unsigned short' type.
Definition: ASTBitCodes.h:866
@ PREDEF_TYPE_SHORT_ID
The (signed) 'short' type.
Definition: ASTBitCodes.h:887
@ PREDEF_TYPE_OMP_ARRAY_SHAPING
The placeholder type for OpenMP array shaping operation.
Definition: ASTBitCodes.h:1061
@ PREDEF_TYPE_DEPENDENT_ID
The placeholder type for dependent types.
Definition: ASTBitCodes.h:911
@ PREDEF_TYPE_LONGDOUBLE_ID
The 'long double' type.
Definition: ASTBitCodes.h:905
@ PREDEF_TYPE_DOUBLE_ID
The 'double' type.
Definition: ASTBitCodes.h:902
@ PREDEF_TYPE_UINT128_ID
The '__uint128_t' type.
Definition: ASTBitCodes.h:914
@ PREDEF_TYPE_HALF_ID
The OpenCL 'half' / ARM NEON __fp16 type.
Definition: ASTBitCodes.h:950
@ PREDEF_TYPE_VOID_ID
The void type.
Definition: ASTBitCodes.h:854
@ PREDEF_TYPE_SAT_USHORT_FRACT_ID
The '_Sat unsigned short _Fract' type.
Definition: ASTBitCodes.h:1052
@ PREDEF_TYPE_ACCUM_ID
The '_Accum' type.
Definition: ASTBitCodes.h:992
@ PREDEF_TYPE_SAT_FRACT_ID
The '_Sat _Fract' type.
Definition: ASTBitCodes.h:1046
@ PREDEF_TYPE_NULL_ID
The NULL type.
Definition: ASTBitCodes.h:851
@ PREDEF_TYPE_USHORT_ACCUM_ID
The 'unsigned short _Accum' type.
Definition: ASTBitCodes.h:998
@ PREDEF_TYPE_CHAR8_ID
The C++ 'char8_t' type.
Definition: ASTBitCodes.h:986
@ PREDEF_TYPE_UFRACT_ID
The 'unsigned _Fract' type.
Definition: ASTBitCodes.h:1019
@ PREDEF_TYPE_OVERLOAD_ID
The placeholder type for overloaded function sets.
Definition: ASTBitCodes.h:908
@ PREDEF_TYPE_INCOMPLETE_MATRIX_IDX
A placeholder type for incomplete matrix index operations.
Definition: ASTBitCodes.h:1067
@ PREDEF_TYPE_SAT_USHORT_ACCUM_ID
The '_Sat unsigned short _Accum' type.
Definition: ASTBitCodes.h:1034
@ PREDEF_TYPE_LONG_ID
The (signed) 'long' type.
Definition: ASTBitCodes.h:893
@ PREDEF_TYPE_SAT_ULONG_ACCUM_ID
The '_Sat unsigned long _Accum' type.
Definition: ASTBitCodes.h:1040
@ PREDEF_TYPE_LONG_FRACT_ID
The 'long _Fract' type.
Definition: ASTBitCodes.h:1013
@ PREDEF_TYPE_UNKNOWN_ANY
The 'unknown any' placeholder type.
Definition: ASTBitCodes.h:938
@ PREDEF_TYPE_OMP_ITERATOR
The placeholder type for OpenMP iterator expression.
Definition: ASTBitCodes.h:1064
@ PREDEF_TYPE_PSEUDO_OBJECT
The pseudo-object placeholder type.
Definition: ASTBitCodes.h:956
@ PREDEF_TYPE_OBJC_CLASS
The ObjC 'Class' type.
Definition: ASTBitCodes.h:932
@ PREDEF_TYPE_ULONG_ID
The 'unsigned long' type.
Definition: ASTBitCodes.h:872
@ PREDEF_TYPE_SAT_UACCUM_ID
The '_Sat unsigned _Accum' type.
Definition: ASTBitCodes.h:1037
@ PREDEF_TYPE_CLK_EVENT_ID
OpenCL clk event type.
Definition: ASTBitCodes.h:965
@ PREDEF_TYPE_EVENT_ID
OpenCL event type.
Definition: ASTBitCodes.h:962
@ PREDEF_TYPE_ULONG_ACCUM_ID
The 'unsigned long _Accum' type.
Definition: ASTBitCodes.h:1004
@ PREDEF_TYPE_AUTO_DEDUCT
The "auto" deduction type.
Definition: ASTBitCodes.h:944
@ DECL_CXX_BASE_SPECIFIERS
A record containing CXXBaseSpecifiers.
Definition: ASTBitCodes.h:1393
@ DECL_CONTEXT_LEXICAL
A record that stores the set of declarations that are lexically stored within a given DeclContext.
Definition: ASTBitCodes.h:1273
@ DECL_CXX_CTOR_INITIALIZERS
A record containing CXXCtorInitializers.
Definition: ASTBitCodes.h:1396
@ DECL_CONTEXT_VISIBLE
A record that stores the set of declarations that are visible from a given DeclContext.
Definition: ASTBitCodes.h:1282
@ TYPE_EXT_QUAL
An ExtQualType record.
Definition: ASTBitCodes.h:1123
@ SPECIAL_TYPE_OBJC_SEL_REDEFINITION
Objective-C "SEL" redefinition type.
Definition: ASTBitCodes.h:1151
@ SPECIAL_TYPE_UCONTEXT_T
C ucontext_t typedef type.
Definition: ASTBitCodes.h:1154
@ SPECIAL_TYPE_JMP_BUF
C jmp_buf typedef type.
Definition: ASTBitCodes.h:1139
@ SPECIAL_TYPE_FILE
C FILE typedef type.
Definition: ASTBitCodes.h:1136
@ SPECIAL_TYPE_SIGJMP_BUF
C sigjmp_buf typedef type.
Definition: ASTBitCodes.h:1142
@ SPECIAL_TYPE_OBJC_CLASS_REDEFINITION
Objective-C "Class" redefinition type.
Definition: ASTBitCodes.h:1148
@ SPECIAL_TYPE_CF_CONSTANT_STRING
CFConstantString type.
Definition: ASTBitCodes.h:1133
@ SPECIAL_TYPE_OBJC_ID_REDEFINITION
Objective-C "id" redefinition type.
Definition: ASTBitCodes.h:1145
Defines the clang::TargetInfo interface.
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
Definition: SourceManager.h:81
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
Severity
Enum values that allow the client to map NOTEs, WARNINGs, and EXTENSIONs to either Ignore (nothing),...
Definition: DiagnosticIDs.h:85
@ Warning
Present this diagnostic as a warning.
@ Error
Present this diagnostic as an error.
IncludeDirGroup
IncludeDirGroup - Identifies the group an include Entry belongs to, representing its relative positiv...
llvm::OnDiskChainedHashTable< HeaderFileInfoTrait > HeaderFileInfoLookupTable
The on-disk hash table used for known header files.
llvm::OnDiskIterableChainedHashTable< ASTIdentifierLookupTrait > ASTIdentifierLookupTable
The on-disk hash table used to contain information about all of the identifiers in the program.
llvm::OnDiskChainedHashTable< ASTSelectorLookupTrait > ASTSelectorLookupTable
The on-disk hash table used for the global method pool.
@ EXTENSION_METADATA
Metadata describing this particular extension.
Definition: ASTBitCodes.h:408
uint32_t TypeID
An ID number that refers to a type in an AST file.
Definition: ASTBitCodes.h:77
@ SUBMODULE_EXCLUDED_HEADER
Specifies a header that has been explicitly excluded from this submodule.
Definition: ASTBitCodes.h:798
@ SUBMODULE_TOPHEADER
Specifies a top-level header that falls into this (sub)module.
Definition: ASTBitCodes.h:780
@ SUBMODULE_PRIVATE_TEXTUAL_HEADER
Specifies a header that is private to this submodule but must be textually included.
Definition: ASTBitCodes.h:818
@ SUBMODULE_HEADER
Specifies a header that falls into this (sub)module.
Definition: ASTBitCodes.h:777
@ SUBMODULE_EXPORT_AS
Specifies the name of the module that will eventually re-export the entities in this module.
Definition: ASTBitCodes.h:826
@ SUBMODULE_UMBRELLA_DIR
Specifies an umbrella directory.
Definition: ASTBitCodes.h:783
@ SUBMODULE_UMBRELLA_HEADER
Specifies the umbrella header used to create this module, if any.
Definition: ASTBitCodes.h:774
@ SUBMODULE_METADATA
Metadata for submodules as a whole.
Definition: ASTBitCodes.h:766
@ SUBMODULE_REQUIRES
Specifies a required feature.
Definition: ASTBitCodes.h:794
@ SUBMODULE_PRIVATE_HEADER
Specifies a header that is private to this submodule.
Definition: ASTBitCodes.h:810
@ SUBMODULE_IMPORTS
Specifies the submodules that are imported by this submodule.
Definition: ASTBitCodes.h:787
@ SUBMODULE_CONFLICT
Specifies a conflict with another module.
Definition: ASTBitCodes.h:807
@ SUBMODULE_INITIALIZERS
Specifies some declarations with initializers that must be emitted to initialize the module.
Definition: ASTBitCodes.h:822
@ SUBMODULE_DEFINITION
Defines the major attributes of a submodule, including its name and parent.
Definition: ASTBitCodes.h:770
@ SUBMODULE_LINK_LIBRARY
Specifies a library or framework to link against.
Definition: ASTBitCodes.h:801
@ SUBMODULE_CONFIG_MACRO
Specifies a configuration macro for this module.
Definition: ASTBitCodes.h:804
@ SUBMODULE_EXPORTS
Specifies the submodules that are re-exported from this submodule.
Definition: ASTBitCodes.h:791
@ SUBMODULE_TEXTUAL_HEADER
Specifies a header that is part of the module but must be textually included.
Definition: ASTBitCodes.h:814
@ SUBMODULE_AFFECTING_MODULES
Specifies affecting modules that were not imported.
Definition: ASTBitCodes.h:829
const unsigned int NUM_PREDEF_IDENT_IDS
The number of predefined identifier IDs.
Definition: ASTBitCodes.h:129
uint32_t SubmoduleID
An ID number that refers to a submodule in a module file.
Definition: ASTBitCodes.h:163
OptionsRecordTypes
Record types that occur within the options block inside the control block.
Definition: ASTBitCodes.h:359
@ FILE_SYSTEM_OPTIONS
Record code for the filesystem options table.
Definition: ASTBitCodes.h:372
@ TARGET_OPTIONS
Record code for the target options table.
Definition: ASTBitCodes.h:369
@ PREPROCESSOR_OPTIONS
Record code for the preprocessor options table.
Definition: ASTBitCodes.h:378
@ HEADER_SEARCH_OPTIONS
Record code for the headers search options table.
Definition: ASTBitCodes.h:375
@ LANGUAGE_OPTIONS
Record code for the language options table.
Definition: ASTBitCodes.h:366
uint32_t SelectorID
An ID number that refers to an ObjC selector in an AST file.
Definition: ASTBitCodes.h:145
const unsigned int NUM_PREDEF_PP_ENTITY_IDS
The number of predefined preprocessed entity IDs.
Definition: ASTBitCodes.h:265
uint32_t PreprocessedEntityID
An ID number that refers to an entity in the detailed preprocessing record.
Definition: ASTBitCodes.h:160
const unsigned int NUM_PREDEF_SUBMODULE_IDS
The number of predefined submodule IDs.
Definition: ASTBitCodes.h:166
@ SUBMODULE_BLOCK_ID
The block containing the submodule structure.
Definition: ASTBitCodes.h:290
@ PREPROCESSOR_DETAIL_BLOCK_ID
The block containing the detailed preprocessing record.
Definition: ASTBitCodes.h:287
@ AST_BLOCK_ID
The AST block, which acts as a container around the full AST block.
Definition: ASTBitCodes.h:272
@ SOURCE_MANAGER_BLOCK_ID
The block containing information about the source manager.
Definition: ASTBitCodes.h:276
@ CONTROL_BLOCK_ID
The control block, which contains all of the information that needs to be validated prior to committi...
Definition: ASTBitCodes.h:298
@ DECLTYPES_BLOCK_ID
The block containing the definitions of all of the types and decls used within the AST file.
Definition: ASTBitCodes.h:284
@ PREPROCESSOR_BLOCK_ID
The block containing information about the preprocessor.
Definition: ASTBitCodes.h:280
@ COMMENTS_BLOCK_ID
The block containing comments.
Definition: ASTBitCodes.h:293
@ UNHASHED_CONTROL_BLOCK_ID
A block with unhashed content.
Definition: ASTBitCodes.h:320
@ EXTENSION_BLOCK_ID
A block containing a module file extension.
Definition: ASTBitCodes.h:314
@ OPTIONS_BLOCK_ID
The block of configuration options, used to check that a module is being used in a configuration comp...
Definition: ASTBitCodes.h:311
@ INPUT_FILES_BLOCK_ID
The block of input files, which were used as inputs to create this AST file.
Definition: ASTBitCodes.h:304
uint32_t IdentID
An ID number that refers to an identifier in an AST file.
Definition: ASTBitCodes.h:126
CommentRecordTypes
Record types used within a comments block.
Definition: ASTBitCodes.h:833
@ SM_SLOC_FILE_ENTRY
Describes a source location entry (SLocEntry) for a file.
Definition: ASTBitCodes.h:703
@ SM_SLOC_BUFFER_BLOB_COMPRESSED
Describes a zlib-compressed blob that contains the data for a buffer entry.
Definition: ASTBitCodes.h:717
@ SM_SLOC_BUFFER_ENTRY
Describes a source location entry (SLocEntry) for a buffer.
Definition: ASTBitCodes.h:707
@ SM_SLOC_BUFFER_BLOB
Describes a blob that contains the data for a buffer entry.
Definition: ASTBitCodes.h:713
@ SM_SLOC_EXPANSION_ENTRY
Describes a source location entry (SLocEntry) for a macro expansion.
Definition: ASTBitCodes.h:721
const unsigned int NUM_PREDEF_SELECTOR_IDS
The number of predefined selector IDs.
Definition: ASTBitCodes.h:148
bool needsAnonymousDeclarationNumber(const NamedDecl *D)
Determine whether the given declaration needs an anonymous declaration number.
Definition: ASTCommon.cpp:456
const unsigned VERSION_MAJOR
AST file major version number supported by this version of Clang.
Definition: ASTBitCodes.h:45
DeclIDBase::DeclID DeclID
An ID number that refers to a declaration in an AST file.
Definition: ASTBitCodes.h:65
PreprocessorRecordTypes
Record types used within a preprocessor block.
Definition: ASTBitCodes.h:725
@ PP_TOKEN
Describes one token.
Definition: ASTBitCodes.h:740
@ PP_MACRO_FUNCTION_LIKE
A function-like macro definition.
Definition: ASTBitCodes.h:736
@ PP_MACRO_OBJECT_LIKE
An object-like macro definition.
Definition: ASTBitCodes.h:731
@ PP_MACRO_DIRECTIVE_HISTORY
The macro directives history for a particular identifier.
Definition: ASTBitCodes.h:743
@ PP_MODULE_MACRO
A macro directive exported by a module.
Definition: ASTBitCodes.h:747
ControlRecordTypes
Record types that occur within the control block.
Definition: ASTBitCodes.h:324
@ MODULE_MAP_FILE
Record code for the module map file that was used to build this AST file.
Definition: ASTBitCodes.h:351
@ MODULE_DIRECTORY
Record code for the module build directory.
Definition: ASTBitCodes.h:354
@ IMPORTS
Record code for the list of other AST files imported by this AST file.
Definition: ASTBitCodes.h:331
@ ORIGINAL_FILE_ID
Record code for file ID of the file or buffer that was used to generate the AST file.
Definition: ASTBitCodes.h:340
@ MODULE_NAME
Record code for the module name.
Definition: ASTBitCodes.h:347
@ ORIGINAL_FILE
Record code for the original file that was used to generate the AST file, including both its file ID ...
Definition: ASTBitCodes.h:336
@ INPUT_FILE_OFFSETS
Offsets into the input-files block where input files reside.
Definition: ASTBitCodes.h:344
@ METADATA
AST file metadata, including the AST file version number and information about the compiler used to b...
Definition: ASTBitCodes.h:327
UnhashedControlBlockRecordTypes
Record codes for the unhashed control block.
Definition: ASTBitCodes.h:382
@ DIAGNOSTIC_OPTIONS
Record code for the diagnostic options table.
Definition: ASTBitCodes.h:390
@ HEADER_SEARCH_ENTRY_USAGE
Record code for the indices of used header search entries.
Definition: ASTBitCodes.h:399
@ AST_BLOCK_HASH
Record code for the content hash of the AST block.
Definition: ASTBitCodes.h:387
@ DIAG_PRAGMA_MAPPINGS
Record code for #pragma diagnostic mappings.
Definition: ASTBitCodes.h:396
@ SIGNATURE
Record code for the signature that identifiers this AST file.
Definition: ASTBitCodes.h:384
@ HEADER_SEARCH_PATHS
Record code for the headers search paths.
Definition: ASTBitCodes.h:393
@ VFS_USAGE
Record code for the indices of used VFSs.
Definition: ASTBitCodes.h:402
InputFileRecordTypes
Record types that occur within the input-files block inside the control block.
Definition: ASTBitCodes.h:416
@ INPUT_FILE_HASH
The input file content hash.
Definition: ASTBitCodes.h:421
@ INPUT_FILE
An input file.
Definition: ASTBitCodes.h:418
PreprocessorDetailRecordTypes
Record types used within a preprocessor detail block.
Definition: ASTBitCodes.h:751
@ PPD_INCLUSION_DIRECTIVE
Describes an inclusion directive within the preprocessing record.
Definition: ASTBitCodes.h:760
@ PPD_MACRO_EXPANSION
Describes a macro expansion within the preprocessing record.
Definition: ASTBitCodes.h:753
@ PPD_MACRO_DEFINITION
Describes a macro definition within the preprocessing record.
Definition: ASTBitCodes.h:756
ModuleKind
Specifies the kind of module that has been loaded.
Definition: ModuleFile.h:42
@ MK_PCH
File is a PCH file treated as such.
Definition: ModuleFile.h:50
@ MK_Preamble
File is a PCH file treated as the preamble.
Definition: ModuleFile.h:53
@ MK_MainFile
File is a PCH file treated as the actual main file.
Definition: ModuleFile.h:56
@ MK_ExplicitModule
File is an explicitly-loaded module.
Definition: ModuleFile.h:47
@ MK_ImplicitModule
File is an implicitly-loaded module.
Definition: ModuleFile.h:44
@ MK_PrebuiltModule
File is from a prebuilt module path.
Definition: ModuleFile.h:59
const unsigned int NUM_PREDEF_MACRO_IDS
The number of predefined macro IDs.
Definition: ASTBitCodes.h:142
ASTRecordTypes
Record types that occur within the AST block itself.
Definition: ASTBitCodes.h:425
@ DECL_UPDATE_OFFSETS
Record for offsets of DECL_UPDATES records for declarations that were modified after being deserializ...
Definition: ASTBitCodes.h:566
@ STATISTICS
Record code for the extra statistics we gather while generating an AST file.
Definition: ASTBitCodes.h:500
@ FLOAT_CONTROL_PRAGMA_OPTIONS
Record code for #pragma float_control options.
Definition: ASTBitCodes.h:686
@ KNOWN_NAMESPACES
Record code for the set of known namespaces, which are used for typo correction.
Definition: ASTBitCodes.h:592
@ SPECIAL_TYPES
Record code for the set of non-builtin, special types.
Definition: ASTBitCodes.h:496
@ PENDING_IMPLICIT_INSTANTIATIONS
Record code for pending implicit instantiations.
Definition: ASTBitCodes.h:555
@ TYPE_OFFSET
Record code for the offsets of each type.
Definition: ASTBitCodes.h:438
@ DELEGATING_CTORS
The list of delegating constructor declarations.
Definition: ASTBitCodes.h:588
@ PP_ASSUME_NONNULL_LOC
ID 66 used to be the list of included files.
Definition: ASTBitCodes.h:692
@ EXT_VECTOR_DECLS
Record code for the set of ext_vector type names.
Definition: ASTBitCodes.h:525
@ OPENCL_EXTENSIONS
Record code for enabled OpenCL extensions.
Definition: ASTBitCodes.h:585
@ FP_PRAGMA_OPTIONS
Record code for floating point #pragma options.
Definition: ASTBitCodes.h:582
@ VTABLE_USES
Record code for the array of VTable uses.
Definition: ASTBitCodes.h:535
@ LATE_PARSED_TEMPLATE
Record code for late parsed template functions.
Definition: ASTBitCodes.h:642
@ DECLS_TO_CHECK_FOR_DEFERRED_DIAGS
Record code for the Decls to be checked for deferred diags.
Definition: ASTBitCodes.h:683
@ DECL_OFFSET
Record code for the offsets of each decl.
Definition: ASTBitCodes.h:450
@ SOURCE_MANAGER_LINE_TABLE
Record code for the source manager line table information, which stores information about #line direc...
Definition: ASTBitCodes.h:602
@ PP_COUNTER_VALUE
The value of the next COUNTER to dispense.
Definition: ASTBitCodes.h:516
@ DELETE_EXPRS_TO_ANALYZE
Delete expressions that will be analyzed later.
Definition: ASTBitCodes.h:653
@ UPDATE_VISIBLE
Record code for an update to a decl context's lookup table.
Definition: ASTBitCodes.h:562
@ CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH
Number of unmatched #pragma clang cuda_force_host_device begin directives we've seen.
Definition: ASTBitCodes.h:663
@ MACRO_OFFSET
Record code for the table of offsets of each macro ID.
Definition: ASTBitCodes.h:630
@ PPD_ENTITIES_OFFSETS
Record code for the table of offsets to entries in the preprocessing record.
Definition: ASTBitCodes.h:532
@ IDENTIFIER_OFFSET
Record code for the table of offsets of each identifier ID.
Definition: ASTBitCodes.h:458
@ OBJC_CATEGORIES
Record code for the array of Objective-C categories (including extensions).
Definition: ASTBitCodes.h:623
@ METHOD_POOL
Record code for the Objective-C method pool,.
Definition: ASTBitCodes.h:512
@ DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD
Record code for lexical and visible block for delayed namespace in reduced BMI.
Definition: ASTBitCodes.h:696
@ PP_CONDITIONAL_STACK
The stack of open #ifs/#ifdefs recorded in a preamble.
Definition: ASTBitCodes.h:677
@ REFERENCED_SELECTOR_POOL
Record code for referenced selector pool.
Definition: ASTBitCodes.h:540
@ SOURCE_LOCATION_OFFSETS
Record code for the table of offsets into the block of source-location information.
Definition: ASTBitCodes.h:520
@ WEAK_UNDECLARED_IDENTIFIERS
Record code for weak undeclared identifiers.
Definition: ASTBitCodes.h:552
@ UNDEFINED_BUT_USED
Record code for undefined but used functions and variables that need a definition in this TU.
Definition: ASTBitCodes.h:639
@ FILE_SORTED_DECLS
Record code for a file sorted array of DeclIDs in a module.
Definition: ASTBitCodes.h:609
@ MSSTRUCT_PRAGMA_OPTIONS
Record code for #pragma ms_struct options.
Definition: ASTBitCodes.h:656
@ TENTATIVE_DEFINITIONS
Record code for the array of tentative definitions.
Definition: ASTBitCodes.h:503
@ UNUSED_FILESCOPED_DECLS
Record code for the array of unused file scoped decls.
Definition: ASTBitCodes.h:528
@ ALIGN_PACK_PRAGMA_OPTIONS
Record code for #pragma align/pack options.
Definition: ASTBitCodes.h:674
@ IMPORTED_MODULES
Record code for an array of all of the (sub)modules that were imported by the AST file.
Definition: ASTBitCodes.h:613
@ SELECTOR_OFFSETS
Record code for the table of offsets into the Objective-C method pool.
Definition: ASTBitCodes.h:509
@ UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES
Record code for potentially unused local typedef names.
Definition: ASTBitCodes.h:648
@ EAGERLY_DESERIALIZED_DECLS
Record code for the array of eagerly deserialized decls.
Definition: ASTBitCodes.h:487
@ INTERESTING_IDENTIFIERS
A list of "interesting" identifiers.
Definition: ASTBitCodes.h:635
@ HEADER_SEARCH_TABLE
Record code for header search information.
Definition: ASTBitCodes.h:579
@ OBJC_CATEGORIES_MAP
Record code for map of Objective-C class definition IDs to the ObjC categories in a module that are a...
Definition: ASTBitCodes.h:606
@ CUDA_SPECIAL_DECL_REFS
Record code for special CUDA declarations.
Definition: ASTBitCodes.h:576
@ TU_UPDATE_LEXICAL
Record code for an update to the TU's lexically contained declarations.
Definition: ASTBitCodes.h:544
@ PPD_SKIPPED_RANGES
A table of skipped ranges within the preprocessing record.
Definition: ASTBitCodes.h:680
@ IDENTIFIER_TABLE
Record code for the identifier table.
Definition: ASTBitCodes.h:477
@ SEMA_DECL_REFS
Record code for declarations that Sema keeps references of.
Definition: ASTBitCodes.h:549
@ OPTIMIZE_PRAGMA_OPTIONS
Record code for #pragma optimize options.
Definition: ASTBitCodes.h:645
@ MODULE_OFFSET_MAP
Record code for the remapping information used to relate loaded modules to the various offsets and ID...
Definition: ASTBitCodes.h:598
@ POINTERS_TO_MEMBERS_PRAGMA_OPTIONS
Record code for #pragma ms_struct options.
Definition: ASTBitCodes.h:659
uint32_t MacroID
An ID number that refers to a macro in an AST file.
Definition: ASTBitCodes.h:132
uint32_t IdentifierID
An ID number that refers to an identifier in an AST file.
Definition: ASTBitCodes.h:61
unsigned ComputeHash(Selector Sel)
Definition: ASTCommon.cpp:281
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
The JSON file list parser is used to communicate input to InstallAPI.
OpenACCClauseKind
Represents the kind of an OpenACC clause.
Definition: OpenACCKinds.h:164
@ Auto
'auto' clause, allowed on 'loop' directives.
@ Bind
'bind' clause, allowed on routine constructs.
@ Gang
'gang' clause, allowed on 'loop' and Combined constructs.
@ Wait
'wait' clause, allowed on Compute, Data, 'update', and Combined constructs.
@ DevicePtr
'deviceptr' clause, allowed on Compute and Combined Constructs, plus 'data' and 'declare'.
@ VectorLength
'vector_length' clause, allowed on 'parallel', 'kernels', 'parallel loop', and 'kernels loop' constru...
@ Async
'async' clause, allowed on Compute, Data, 'update', 'wait', and Combined constructs.
@ Collapse
'collapse' clause, allowed on 'loop' and Combined constructs.
@ NoHost
'nohost' clause, allowed on 'routine' directives.
@ DeviceNum
'device_num' clause, allowed on 'init', 'shutdown', and 'set' constructs.
@ Private
'private' clause, allowed on 'parallel', 'serial', 'loop', 'parallel loop', and 'serial loop' constru...
@ Invalid
Represents an invalid clause, for the purposes of parsing.
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Copy
'copy' clause, allowed on Compute and Combined Constructs, plus 'data' and 'declare'.
@ Worker
'worker' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Create
'copyin' clause, allowed on Compute and Combined constructs, plus 'data', 'enter data',...
@ DeviceType
'device_type' clause, allowed on Compute, 'data', 'init', 'shutdown', 'set', update',...
@ DefaultAsync
'default_async' clause, allowed on 'set' construct.
@ Attach
'attach' clause, allowed on Compute and Combined constructs, plus 'data' and 'enter data'.
@ NumGangs
'num_gangs' clause, allowed on 'parallel', 'kernels', parallel loop', and 'kernels loop' constructs.
@ If
'if' clause, allowed on all the Compute Constructs, Data Constructs, Executable Constructs,...
@ Default
'default' clause, allowed on parallel, serial, kernel (and compound) constructs.
@ UseDevice
'use_device' clause, allowed on 'host_data' construct.
@ NoCreate
'no_create' clause, allowed on allowed on Compute and Combined constructs, plus 'data'.
@ Link
'link' clause, allowed on 'declare' construct.
@ Reduction
'reduction' clause, allowed on Parallel, Serial, Loop, and the combined constructs.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ CopyOut
'copyout' clause, allowed on Compute and Combined constructs, plus 'data', 'exit data',...
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ FirstPrivate
'firstprivate' clause, allowed on 'parallel', 'serial', 'parallel loop', and 'serial loop' constructs...
@ Host
'host' clause, allowed on 'update' construct.
@ Tile
'tile' clause, allowed on 'loop' and Combined constructs.
@ DeviceResident
'device_resident' clause, allowed on the 'declare' construct.
@ Present
'present' clause, allowed on Compute and Combined constructs, plus 'data' and 'declare'.
@ DType
'dtype' clause, an alias for 'device_type', stored separately for diagnostic purposes.
@ CopyIn
'copyin' clause, allowed on Compute and Combined constructs, plus 'data', 'enter data',...
@ Device
'device' clause, allowed on the 'update' construct.
@ Independent
'independent' clause, allowed on 'loop' directives.
@ NumWorkers
'num_workers' clause, allowed on 'parallel', 'kernels', parallel loop', and 'kernels loop' constructs...
@ IfPresent
'if_present' clause, allowed on 'host_data' and 'update' directives.
@ Detach
'detach' clause, allowed on the 'exit data' construct.
@ Delete
'delete' clause, allowed on the 'exit data' construct.
@ Finalize
'finalize' clause, allowed on 'exit data' directive.
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:55
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
SanitizerMask getPPTransparentSanitizers()
Return the sanitizers which do not affect preprocessing.
Definition: Sanitizers.h:198
@ CPlusPlus
Definition: LangStandard.h:55
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
llvm::omp::Directive OpenMPDirectiveKind
OpenMP directives.
Definition: OpenMPKinds.h:24
OpenMPDefaultmapClauseModifier
OpenMP modifiers for 'defaultmap' clause.
Definition: OpenMPKinds.h:118
OpenMPOrderClauseModifier
OpenMP modifiers for 'order' clause.
Definition: OpenMPKinds.h:171
void ProcessWarningOptions(DiagnosticsEngine &Diags, const DiagnosticOptions &Opts, bool ReportDiags=true)
ProcessWarningOptions - Initialize the diagnostic client and process the warning options specified on...
Definition: Warnings.cpp:44
OpenMPAtClauseKind
OpenMP attributes for 'at' clause.
Definition: OpenMPKinds.h:135
OpenMPReductionClauseModifier
OpenMP modifiers for 'reduction' clause.
Definition: OpenMPKinds.h:186
OpenMPScheduleClauseModifier
OpenMP modifiers for 'schedule' clause.
Definition: OpenMPKinds.h:38
llvm::omp::Clause OpenMPClauseKind
OpenMP clauses.
Definition: OpenMPKinds.h:27
OpenMPDistScheduleClauseKind
OpenMP attributes for 'dist_schedule' clause.
Definition: OpenMPKinds.h:103
OpenMPDoacrossClauseModifier
OpenMP dependence types for 'doacross' clause.
Definition: OpenMPKinds.h:219
static constexpr unsigned NumberOfOMPMapClauseModifiers
Number of allowed map-type-modifiers.
Definition: OpenMPKinds.h:87
const unsigned int NUM_PREDEF_DECL_IDS
The number of declaration IDs that are predefined.
Definition: DeclID.h:90
ObjCXXARCStandardLibraryKind
Enumerate the kinds of standard library that.
PredefinedDeclIDs
Predefined declaration IDs.
Definition: DeclID.h:30
@ PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID
The internal '__NSConstantString' tag type.
Definition: DeclID.h:80
@ PREDEF_DECL_TRANSLATION_UNIT_ID
The translation unit.
Definition: DeclID.h:35
@ PREDEF_DECL_TYPE_PACK_ELEMENT_ID
The internal '__type_pack_element' template.
Definition: DeclID.h:83
@ PREDEF_DECL_OBJC_CLASS_ID
The Objective-C 'Class' type.
Definition: DeclID.h:44
@ PREDEF_DECL_BUILTIN_MS_GUID_ID
The predeclared '_GUID' struct.
Definition: DeclID.h:68
@ PREDEF_DECL_OBJC_INSTANCETYPE_ID
The internal 'instancetype' typedef.
Definition: DeclID.h:56
@ PREDEF_DECL_OBJC_PROTOCOL_ID
The Objective-C 'Protocol' type.
Definition: DeclID.h:47
@ PREDEF_DECL_UNSIGNED_INT_128_ID
The unsigned 128-bit integer type.
Definition: DeclID.h:53
@ PREDEF_DECL_OBJC_SEL_ID
The Objective-C 'SEL' type.
Definition: DeclID.h:41
@ PREDEF_DECL_INT_128_ID
The signed 128-bit integer type.
Definition: DeclID.h:50
@ PREDEF_DECL_VA_LIST_TAG
The internal '__va_list_tag' struct, if any.
Definition: DeclID.h:62
@ PREDEF_DECL_BUILTIN_MS_VA_LIST_ID
The internal '__builtin_ms_va_list' typedef.
Definition: DeclID.h:65
@ PREDEF_DECL_CF_CONSTANT_STRING_ID
The internal '__NSConstantString' typedef.
Definition: DeclID.h:77
@ PREDEF_DECL_NULL_ID
The NULL declaration.
Definition: DeclID.h:32
@ PREDEF_DECL_BUILTIN_VA_LIST_ID
The internal '__builtin_va_list' typedef.
Definition: DeclID.h:59
@ PREDEF_DECL_EXTERN_C_CONTEXT_ID
The extern "C" context.
Definition: DeclID.h:71
@ PREDEF_DECL_OBJC_ID_ID
The Objective-C 'id' type.
Definition: DeclID.h:38
@ PREDEF_DECL_MAKE_INTEGER_SEQ_ID
The internal '__make_integer_seq' template.
Definition: DeclID.h:74
@ Property
The type of a property.
@ Result
The result type of a method or function.
OpenMPBindClauseKind
OpenMP bindings for the 'bind' clause.
Definition: OpenMPKinds.h:200
OpenACCDefaultClauseKind
Definition: OpenACCKinds.h:419
OpenMPLastprivateModifier
OpenMP 'lastprivate' clause modifier.
Definition: OpenMPKinds.h:157
OpenMPDependClauseKind
OpenMP attributes for 'depend' clause.
Definition: OpenMPKinds.h:54
OpenMPGrainsizeClauseModifier
Definition: OpenMPKinds.h:206
OpenMPNumTasksClauseModifier
Definition: OpenMPKinds.h:212
OpenMPSeverityClauseKind
OpenMP attributes for 'severity' clause.
Definition: OpenMPKinds.h:142
static constexpr unsigned NumberOfOMPMotionModifiers
Number of allowed motion-modifiers.
Definition: OpenMPKinds.h:99
TypeSpecifierWidth
Specifies the width of a type, e.g., short, long, or long long.
Definition: Specifiers.h:47
OpenMPMotionModifierKind
OpenMP modifier kind for 'to' or 'from' clause.
Definition: OpenMPKinds.h:91
PragmaMSStructKind
Definition: PragmaKinds.h:23
OpenMPDefaultmapClauseKind
OpenMP attributes for 'defaultmap' clause.
Definition: OpenMPKinds.h:110
OpenMPLinearClauseKind
OpenMP attributes for 'linear' clause.
Definition: OpenMPKinds.h:62
TypeSpecifierSign
Specifies the signedness of a type, e.g., signed or unsigned.
Definition: Specifiers.h:50
llvm::hash_code hash_value(const CustomizableOptional< T > &O)
const FunctionProtoType * T
DisableValidationForModuleKind
Whether to disable the normal validation performed on precompiled headers and module files when they ...
@ None
Perform validation, don't disable it.
@ PCH
Disable validation for a precompiled header and the modules it depends on.
@ Module
Disable validation for module files.
bool shouldSkipCheckingODR(const Decl *D)
Definition: ASTReader.h:2467
std::string getClangFullRepositoryVersion()
Retrieves the full repository version that is an amalgamation of the information in getClangRepositor...
Definition: Version.cpp:68
OpenMPAtomicDefaultMemOrderClauseKind
OpenMP attributes for 'atomic_default_mem_order' clause.
Definition: OpenMPKinds.h:127
@ Success
Template argument deduction was successful.
U cast(CodeGen::Address addr)
Definition: Address.h:291
@ None
The alignment was not explicit in code.
OpenMPDeviceClauseModifier
OpenMP modifiers for 'device' clause.
Definition: OpenMPKinds.h:47
OpenMPMapModifierKind
OpenMP modifier kind for 'map' clause.
Definition: OpenMPKinds.h:78
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
OpenMPOrderClauseKind
OpenMP attributes for 'order' clause.
Definition: OpenMPKinds.h:164
OpenMPScheduleClauseKind
OpenMP attributes for 'schedule' clause.
Definition: OpenMPKinds.h:30
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:120
OpenMPMapClauseKind
OpenMP mapping kind for 'map' clause.
Definition: OpenMPKinds.h:70
unsigned long uint64_t
Definition: Format.h:5394
#define true
Definition: stdbool.h:21
#define bool
Definition: stdbool.h:20
The signature of a module, which is a hash of the AST content.
Definition: Module.h:57
static constexpr size_t size
Definition: Module.h:60
static ASTFileSignature create(std::array< uint8_t, 20 > Bytes)
Definition: Module.h:75
static ASTFileSignature createDummy()
Definition: Module.h:85
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
Definition: TemplateBase.h:676
static const ASTTemplateArgumentListInfo * Create(const ASTContext &C, const TemplateArgumentListInfo &List)
bool ParseAllComments
Treat ordinary comments as documentation comments.
BlockCommandNamesTy BlockCommandNames
Command names to treat as block commands in comments.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setLoc(SourceLocation L)
setLoc - Sets the main location of the declaration name.
void setInfo(const DeclarationNameLoc &Info)
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
A simple structure that captures a vtable use for the purposes of the ExternalSemaSource.
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:4738
The preprocessor keeps track of this information for each file that is #included.
Definition: HeaderSearch.h:58
void mergeModuleMembership(ModuleMap::ModuleHeaderRole Role)
Update the module membership bits based on the header role.
unsigned IndexHeaderMapHeader
Whether this is a header inside a framework that is currently being built.
Definition: HeaderSearch.h:116
unsigned DirInfo
Keep track of whether this is a system header, and if so, whether it is C++ clean or not.
Definition: HeaderSearch.h:80
unsigned isPragmaOnce
True if this is a #pragma once file.
Definition: HeaderSearch.h:73
unsigned IsValid
Whether this file has been looked up as a header.
Definition: HeaderSearch.h:120
unsigned isImport
True if this is a #import'd file.
Definition: HeaderSearch.h:69
StringRef Framework
If this header came from a framework include, this is the name of the framework.
Definition: HeaderSearch.h:141
unsigned ControllingMacroID
The ID number of the controlling macro.
Definition: HeaderSearch.h:127
unsigned External
Whether this header file info was supplied by an external source, and has not changed since.
Definition: HeaderSearch.h:85
static LineEntry get(unsigned Offs, unsigned Line, int Filename, SrcMgr::CharacteristicKind FileKind, unsigned IncludeOffset)
Metadata for a module file extension.
unsigned MajorVersion
The major version of the extension data.
std::string UserInfo
A string containing additional user information that will be stored with the metadata.
std::string BlockName
The name used to identify this particular extension block within the resulting module file.
unsigned MinorVersion
The minor version of the extension data.
A conflict between two modules.
Definition: Module.h:487
Module * Other
The module that this module conflicts with.
Definition: Module.h:489
std::string Message
The message provided to the user when there is a conflict.
Definition: Module.h:492
Information about a header directive as found in the module map file.
Definition: Module.h:250
A library or framework to link against when an entity from this module is used.
Definition: Module.h:446
This structure contains all sizes needed for by an OMPMappableExprListClause.
unsigned NumComponentLists
Number of component lists.
unsigned NumVars
Number of expressions listed.
unsigned NumUniqueDeclarations
Number of unique base declarations.
unsigned NumComponents
Total number of expression components.
Data for list of allocators.
SourceLocation LParenLoc
Locations of '(' and ')' symbols.
Expr * AllocatorTraits
Allocator traits.
a linked list of methods with the same selector name but different signatures.
A struct with extended info about a syntactic name qualifier, to be used for the case of out-of-line ...
Definition: Decl.h:743
TemplateParameterList ** TemplParamLists
A new-allocated array of size NumTemplParamLists, containing pointers to the "outer" template paramet...
Definition: Decl.h:757
NestedNameSpecifierLoc QualifierLoc
Definition: Decl.h:744
unsigned NumTemplParamLists
The number of "outer" template parameter lists.
Definition: Decl.h:750
void clear(SanitizerMask K=SanitizerKind::All)
Disable the sanitizers specified in K.
Definition: Sanitizers.h:176
SanitizerMask Mask
Bitmask of enabled sanitizers.
Definition: Sanitizers.h:182
Helper class that saves the current stream position and then restores it when destroyed.
PragmaMsStackAction Action
Definition: Sema.h:1203
Location information for a TemplateArgument.
Definition: TemplateBase.h:472
Source location and bit offset of a declaration.
Definition: ASTBitCodes.h:233
The input file info that has been loaded from an AST file.
Definition: ModuleFile.h:63
Describes the categories of an Objective-C class.
Definition: ASTBitCodes.h:1984
Source range/offset of a preprocessed entity.
Definition: ASTBitCodes.h:169
uint32_t BitOffset
Offset in the AST file relative to ModuleFile::MacroOffsetsBase.
Definition: ASTBitCodes.h:177
SourceLocation getBegin() const
Definition: ASTBitCodes.h:183
SourceLocation getEnd() const
Definition: ASTBitCodes.h:187
Source range of a skipped preprocessor region.
Definition: ASTBitCodes.h:193
SourceLocation getBegin() const
Definition: ASTBitCodes.h:203
SourceLocation getEnd() const
Definition: ASTBitCodes.h:206